https://github.com/quic-asaravan updated 
https://github.com/llvm/llvm-project/pull/240916

>From a99deda39b8aa6a22c605f8a9fbefd14f9cb6ab9 Mon Sep 17 00:00:00 2001
From: quic-asaravan <[email protected]>
Date: Sun, 1 Nov 2026 22:16:45 -0800
Subject: [PATCH 1/3] Fix #include_next of a differently named header from a
 module header

When #include_next is used in a header belonging to a module, clang finds
the directory of the current file by repeatedly looking up the requested
name until a hit equals the current file. If the requested name differs
from the current file's name (e.g. libc++'s __mbstate_t.h doing
search restarts from the first include directory, finding the wrong header.

Look up the current file's own name to locate its directory instead when
the names differ. Use the file's path relative to its search directory
(e.g. "sys/inner.h") rather than just its basename, so that headers found
in a subdirectory of an include directory are located correctly too.
---
 clang/include/clang/Lex/HeaderSearch.h        |  2 +-
 clang/lib/Lex/HeaderSearch.cpp                | 12 ++-
 clang/lib/Lex/PPDirectives.cpp                | 99 ++++++++++++++++---
 .../Modules/include_next_different_name.c     | 57 +++++++++++
 .../include_next_different_name_relative.c    | 33 +++++++
 5 files changed, 181 insertions(+), 22 deletions(-)
 create mode 100644 clang/test/Modules/include_next_different_name.c
 create mode 100644 clang/test/Modules/include_next_different_name_relative.c

diff --git a/clang/include/clang/Lex/HeaderSearch.h 
b/clang/include/clang/Lex/HeaderSearch.h
index adaa126024c3ca..eadaed1659286c 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -574,7 +574,7 @@ class HeaderSearch {
       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
       bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
       bool BuildSystemModule = false, bool OpenFile = true,
-      bool CacheFailures = true);
+      bool CacheFailures = true, bool DiagnoseShadowing = true);
 
   /// Look up a subframework for the specified \#include file.
   ///
diff --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 824ed8936621a8..50ad38d711fcfa 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -957,7 +957,8 @@ OptionalFileEntryRef HeaderSearch::LookupFile(
     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
     bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
-    bool BuildSystemModule, bool OpenFile, bool CacheFailures) {
+    bool BuildSystemModule, bool OpenFile, bool CacheFailures,
+    bool DiagnoseShadowing) {
   ConstSearchDirIterator CurDirLocal = nullptr;
   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
 
@@ -1027,9 +1028,10 @@ OptionalFileEntryRef HeaderSearch::LookupFile(
       if (OptionalFileEntryRef FE = getFileAndSuggestModule(
               TmpDir, IncludeLoc, IncluderAndDir.second, 
IncluderIsSystemHeader,
               RequestingModule, SuggestedModule)) {
-        diagnoseHeaderShadowing(Filename, *FE, IncludeLoc, FromDir, Includers,
-                                isAngled, &IncluderAndDir - Includers.begin(),
-                                nullptr);
+        if (DiagnoseShadowing)
+          diagnoseHeaderShadowing(Filename, *FE, IncludeLoc, FromDir, 
Includers,
+                                  isAngled, &IncluderAndDir - 
Includers.begin(),
+                                  nullptr);
         if (!Includer) {
           assert(First && "only first includer can have no file");
           return FE;
@@ -1168,7 +1170,7 @@ OptionalFileEntryRef HeaderSearch::LookupFile(
     // the includers' directories. That file is the one that ends up being used
     // (see checkMSVCHeaderSearch() below), so reporting this one as the chosen
     // candidate would be wrong.
-    if (!MSFE)
+    if (!MSFE && DiagnoseShadowing)
       diagnoseHeaderShadowing(Filename, *File, IncludeLoc, FromDir, Includers,
                               isAngled, -1, It);
 
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index f1e9aaa72ff048..6fd1b2cfe1d9ee 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -1126,23 +1126,90 @@ OptionalFileEntryRef Preprocessor::LookupFile(
   if (FromFile) {
     // We're supposed to start looking from after a particular file. Search
     // the include path until we find that file or run out of files.
-    ConstSearchDirIterator TmpCurDir = CurDir;
-    ConstSearchDirIterator TmpFromDir = nullptr;
-    while (OptionalFileEntryRef FE = HeaderInfo.LookupFile(
-               Filename, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
-               Includers, SearchPath, RelativePath, RequestingModule,
-               SuggestedModule, /*IsMapped=*/nullptr,
-               /*IsFrameworkFound=*/nullptr, SkipCache)) {
-      // Keep looking as if this file did a #include_next.
-      TmpFromDir = TmpCurDir;
-      ++TmpFromDir;
-      if (&FE->getFileEntry() == FromFile) {
-        // Found it.
-        FromDir = TmpFromDir;
-        CurDir = TmpCurDir;
-        break;
+    // The #include_next may name a different header than the current file
+    // (e.g. __mbstate_t.h doing #include_next <wchar.h>), in which case
+    // looking up Filename would never find FromFile. Look up the current
+    // file's own name to locate the directory it was found in. That name is
+    // its path relative to the search directory (e.g. "sys/inner.h"), not just
+    // the basename, so that headers in subdirectories are found too.
+    auto FindFromFile = [&](StringRef LocateName) {
+      bool SameName = LocateName == Filename;
+      ConstSearchDirIterator TmpCurDir = CurDir;
+      ConstSearchDirIterator TmpFromDir = nullptr;
+      while (OptionalFileEntryRef FE = HeaderInfo.LookupFile(
+                 LocateName, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
+                 Includers, SameName ? SearchPath : nullptr,
+                 SameName ? RelativePath : nullptr, RequestingModule,
+                 SameName ? SuggestedModule : nullptr, /*IsMapped=*/nullptr,
+                 /*IsFrameworkFound=*/nullptr, SkipCache,
+                 /*BuildSystemModule=*/false, /*OpenFile=*/true,
+                 /*CacheFailures=*/true, /*DiagnoseShadowing=*/false)) {
+        // Keep looking as if this file did a #include_next.
+        TmpFromDir = TmpCurDir;
+        ++TmpFromDir;
+        if (&FE->getFileEntry() == FromFile) {
+          // Found it.
+          FromDir = TmpFromDir;
+          CurDir = TmpCurDir;
+          return true;
+        }
       }
-    }
+      return false;
+    };
+
+    // Candidate names for the current file: its path relative to the search
+    // directory it was found in, if known, else to every search directory
+    // that contains it. Search directories are matched by identity rather than
+    // by spelling, as the file may have been reached through a different path
+    // (e.g. "./x/sys/inner.h" for -Ix).
+    // FIXME: If a search directory is nested in another (-Ix -Ix/sub), the 
file
+    // is reachable under several names ("sys/inner.h" and "inner.h") and we
+    // cannot tell which one it was originally found as. Fixing this requires
+    // recording the search directory when a module header is entered.
+    SmallVector<std::string, 4> Names;
+    StringRef BaseName;
+    if (CurPPLexer)
+      if (OptionalFileEntryRef CurFE = CurPPLexer->getFileEntry()) {
+        StringRef Path = CurFE->getName();
+        BaseName = llvm::sys::path::filename(Path);
+        // Each ancestor directory of the file, with the file's path relative
+        // to it.
+        SmallVector<std::pair<DirectoryEntryRef, std::string>, 8> Ancestors;
+        SmallString<128> Rel(BaseName);
+        for (StringRef Parent = llvm::sys::path::parent_path(Path);
+             !Parent.empty(); Parent = llvm::sys::path::parent_path(Parent)) {
+          if (OptionalDirectoryEntryRef Dir =
+                  FileMgr.getOptionalDirectoryRef(Parent))
+            Ancestors.emplace_back(*Dir, Rel.str().str());
+          StringRef Name = llvm::sys::path::filename(Parent);
+          if (Name.empty())
+            break;
+          SmallString<128> NewRel(Name);
+          llvm::sys::path::append(NewRel, Rel);
+          Rel = NewRel;
+        }
+        auto AddRelPath = [&](const DirectoryLookup &DL) {
+          OptionalDirectoryEntryRef Dir = DL.getDirRef();
+          if (!Dir)
+            return;
+          for (const auto &[AncestorDir, AncestorRel] : Ancestors)
+            if (AncestorDir == *Dir) {
+              Names.push_back(AncestorRel);
+              return;
+            }
+        };
+        if (CurDir)
+          AddRelPath(*CurDir);
+        else
+          for (const DirectoryLookup &DL : HeaderInfo.search_dir_range())
+            AddRelPath(DL);
+      }
+    if (!BaseName.empty() && BaseName != Filename)
+      Names.push_back(BaseName.str());
+    Names.push_back(Filename.str());
+    for (const std::string &Name : Names)
+      if (FindFromFile(Name))
+        break;
   }
 
   // Do a standard file entry lookup.
diff --git a/clang/test/Modules/include_next_different_name.c 
b/clang/test/Modules/include_next_different_name.c
new file mode 100644
index 00000000000000..2be45f67fa2acb
--- /dev/null
+++ b/clang/test/Modules/include_next_different_name.c
@@ -0,0 +1,57 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -I%t/x -I%t/y -fsyntax-only -verify %t/main.c
+// RUN: %clang_cc1 -I%t/x -I%t/y -fmodules -fimplicit-module-maps \
+// RUN:   -fmodules-cache-path=%t/cache -fsyntax-only -verify %t/main.c
+// RUN: %clang_cc1 -I%t/x -I%t/y -fsyntax-only -verify %t/main_sub.c
+// RUN: %clang_cc1 -I%t/x -I%t/y -fmodules -fimplicit-module-maps \
+// RUN:   -fmodules-cache-path=%t/cache -fsyntax-only -verify %t/main_sub.c
+
+// A header in a module doing '#include_next' of a header with a different name
+// must continue the search after the directory the current header was found 
in,
+// not restart from the first include directory.
+
+//--- x/wrapper.h
+#ifndef X_WRAPPER_H
+#define X_WRAPPER_H
+int wrapper_x_marker(void) { return 1; }
+#endif
+
+//--- y/wrapper.h
+#ifndef Y_WRAPPER_H
+#define Y_WRAPPER_H
+int wrapper_y_marker(void) { return 2; }
+#endif
+
+//--- x/inner.h
+#ifndef X_INNER_H
+#define X_INNER_H
+// Found in 'x', so the search must continue in 'y' and find y/wrapper.h.
+#include_next <wrapper.h>
+#endif
+
+//--- x/module.modulemap
+module Inner { header "inner.h" export * }
+
+//--- main.c
+// expected-no-diagnostics
+#include <inner.h>
+int use(void) { return wrapper_y_marker(); }
+
+// The current header lives in a subdirectory of the include directory
+// ("#include <sys/inner.h>"); that subdirectory must be considered when
+// locating the directory the header was found in.
+
+//--- x/sys/inner.h
+#ifndef X_SYS_INNER_H
+#define X_SYS_INNER_H
+#include_next <wrapper.h>
+#endif
+
+//--- x/sys/module.modulemap
+module SysInner { header "inner.h" export * }
+
+//--- main_sub.c
+// expected-no-diagnostics
+#include <sys/inner.h>
+int use_sub(void) { return wrapper_y_marker(); }
diff --git a/clang/test/Modules/include_next_different_name_relative.c 
b/clang/test/Modules/include_next_different_name_relative.c
new file mode 100644
index 00000000000000..5ca8d3060cd23d
--- /dev/null
+++ b/clang/test/Modules/include_next_different_name_relative.c
@@ -0,0 +1,33 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t && %clang_cc1 -I%t/z -I%t/x -I%t/y -fmodules \
+// RUN:   -fimplicit-module-maps -fmodules-cache-path=%t/cache \
+// RUN:   -Werror=shadow-header -fsyntax-only main.c
+
+// The current header is reached through a path that is not textually prefixed
+// by its search directory ("./x/sys/inner.h" for -I%t/x), and an unrelated
+// header with the same relative name comes first in the search path. Locating
+// the current header's directory must still work, and must not report
+// -Wshadow-header for the headers it probes.
+
+//--- z/sys/inner.h
+int unrelated_z_marker(void) { return 3; }
+
+//--- x/sys/inner.h
+#ifndef X_SYS_INNER_H
+#define X_SYS_INNER_H
+#include_next <wrapper.h>
+#endif
+
+//--- x/sys/module.modulemap
+module SysInner { header "inner.h" export * }
+
+//--- x/wrapper.h
+int wrapper_x_marker(void) { return 1; }
+
+//--- y/wrapper.h
+int wrapper_y_marker(void) { return 2; }
+
+//--- main.c
+#include "x/sys/inner.h"
+int use(void) { return wrapper_y_marker(); }

>From 9c27aa311dee780fe7501d17b842681e1043217c Mon Sep 17 00:00:00 2001
From: quic-asaravan <[email protected]>
Date: Sun, 1 Nov 2026 22:16:45 -0800
Subject: [PATCH 2/3] [clang][Lex] Fix #include_next of a differently named
 header from a module header

For a module header, #include_next finds the current file's directory by
looking up the requested name until a hit equals the current file. This never
succeeds when the names differ (e.g. libc++'s __mbstate_t.h doing
#include_next <wchar.h>), so the search restarts from the first include
directory and finds the wrong header.

Look up the current file's own name, relative to the search directory that
contains it, instead. Don't diagnose -Wshadow-header for these lookups.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 clang/lib/Lex/PPDirectives.cpp                | 55 +++++++------------
 .../Modules/include_next_nested_search_dirs.c | 51 +++++++++++++++++
 2 files changed, 72 insertions(+), 34 deletions(-)
 create mode 100644 clang/test/Modules/include_next_nested_search_dirs.c

diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 6fd1b2cfe1d9ee..a506bff37b1b3f 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -1126,12 +1126,8 @@ OptionalFileEntryRef Preprocessor::LookupFile(
   if (FromFile) {
     // We're supposed to start looking from after a particular file. Search
     // the include path until we find that file or run out of files.
-    // The #include_next may name a different header than the current file
-    // (e.g. __mbstate_t.h doing #include_next <wchar.h>), in which case
-    // looking up Filename would never find FromFile. Look up the current
-    // file's own name to locate the directory it was found in. That name is
-    // its path relative to the search directory (e.g. "sys/inner.h"), not just
-    // the basename, so that headers in subdirectories are found too.
+    // Filename may differ from FromFile's name (e.g. #include_next <wchar.h>
+    // from __mbstate_t.h), so locate FromFile by its own name instead.
     auto FindFromFile = [&](StringRef LocateName) {
       bool SameName = LocateName == Filename;
       ConstSearchDirIterator TmpCurDir = CurDir;
@@ -1157,30 +1153,33 @@ OptionalFileEntryRef Preprocessor::LookupFile(
       return false;
     };
 
-    // Candidate names for the current file: its path relative to the search
-    // directory it was found in, if known, else to every search directory
-    // that contains it. Search directories are matched by identity rather than
-    // by spelling, as the file may have been reached through a different path
-    // (e.g. "./x/sys/inner.h" for -Ix).
-    // FIXME: If a search directory is nested in another (-Ix -Ix/sub), the 
file
-    // is reachable under several names ("sys/inner.h" and "inner.h") and we
-    // cannot tell which one it was originally found as. Fixing this requires
-    // recording the search directory when a module header is entered.
+    // Candidate names for FromFile: its path relative to each search directory
+    // containing it, innermost first. Directories are matched by identity, as
+    // the file may have been reached via another spelling (e.g. "./x/...").
+    // FIXME: With nested search directories (-Ix -Ix/sub) the original name is
+    // ambiguous; we assume the innermost. Fixing this requires recording the
+    // search directory when a module header is entered.
     SmallVector<std::string, 4> Names;
     StringRef BaseName;
     if (CurPPLexer)
       if (OptionalFileEntryRef CurFE = CurPPLexer->getFileEntry()) {
         StringRef Path = CurFE->getName();
         BaseName = llvm::sys::path::filename(Path);
-        // Each ancestor directory of the file, with the file's path relative
-        // to it.
-        SmallVector<std::pair<DirectoryEntryRef, std::string>, 8> Ancestors;
+        auto IsSearchDir = [&](DirectoryEntryRef Dir) {
+          auto Matches = [&](const DirectoryLookup &DL) {
+            OptionalDirectoryEntryRef DLDir = DL.getDirRef();
+            return DLDir && *DLDir == Dir;
+          };
+          return CurDir ? Matches(*CurDir)
+                        : llvm::any_of(HeaderInfo.search_dir_range(), Matches);
+        };
         SmallString<128> Rel(BaseName);
         for (StringRef Parent = llvm::sys::path::parent_path(Path);
              !Parent.empty(); Parent = llvm::sys::path::parent_path(Parent)) {
           if (OptionalDirectoryEntryRef Dir =
                   FileMgr.getOptionalDirectoryRef(Parent))
-            Ancestors.emplace_back(*Dir, Rel.str().str());
+            if (IsSearchDir(*Dir))
+              Names.push_back(Rel.str().str());
           StringRef Name = llvm::sys::path::filename(Parent);
           if (Name.empty())
             break;
@@ -1188,22 +1187,10 @@ OptionalFileEntryRef Preprocessor::LookupFile(
           llvm::sys::path::append(NewRel, Rel);
           Rel = NewRel;
         }
-        auto AddRelPath = [&](const DirectoryLookup &DL) {
-          OptionalDirectoryEntryRef Dir = DL.getDirRef();
-          if (!Dir)
-            return;
-          for (const auto &[AncestorDir, AncestorRel] : Ancestors)
-            if (AncestorDir == *Dir) {
-              Names.push_back(AncestorRel);
-              return;
-            }
-        };
-        if (CurDir)
-          AddRelPath(*CurDir);
-        else
-          for (const DirectoryLookup &DL : HeaderInfo.search_dir_range())
-            AddRelPath(DL);
       }
+    // A same-name #include_next is most likely how the file was found.
+    if (llvm::is_contained(Names, Filename))
+      Names.insert(Names.begin(), Filename.str());
     if (!BaseName.empty() && BaseName != Filename)
       Names.push_back(BaseName.str());
     Names.push_back(Filename.str());
diff --git a/clang/test/Modules/include_next_nested_search_dirs.c 
b/clang/test/Modules/include_next_nested_search_dirs.c
new file mode 100644
index 00000000000000..801cd96574b5dd
--- /dev/null
+++ b/clang/test/Modules/include_next_nested_search_dirs.c
@@ -0,0 +1,51 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -I%t/inc -I%t/inc/v1 -I%t/sys -fsyntax-only -verify 
%t/main.c
+// RUN: %clang_cc1 -I%t/inc -I%t/inc/v1 -I%t/sys -fmodules \
+// RUN:   -fimplicit-module-maps -fmodules-cache-path=%t/cache -fsyntax-only \
+// RUN:   -verify %t/main.c
+
+// One search directory is nested in another (like libc++'s <include> and
+// <include/c++/v1>). Wrapper headers in the inner directory doing
+// '#include_next' must continue after the inner directory, i.e. the header is
+// located under the name relative to the innermost search directory.
+
+//--- inc/v1/header.h
+#ifndef V1_HEADER_H
+#define V1_HEADER_H
+#include_next <header.h>
+#endif
+
+//--- inc/v1/other.h
+#ifndef V1_OTHER_H
+#define V1_OTHER_H
+#include_next <sysother.h>
+#endif
+
+// Same name as the system header but must not be picked.
+//--- inc/v1/sysother.h
+#ifndef V1_SYSOTHER_H
+#define V1_SYSOTHER_H
+#endif
+
+//--- inc/v1/module.modulemap
+module Header { header "header.h" export * }
+module Other { header "other.h" export * }
+
+//--- sys/header.h
+#ifndef SYS_HEADER_H
+#define SYS_HEADER_H
+int sys_header_marker(void);
+#endif
+
+//--- sys/sysother.h
+#ifndef SYS_SYSOTHER_H
+#define SYS_SYSOTHER_H
+int sys_other_marker(void);
+#endif
+
+//--- main.c
+// expected-no-diagnostics
+#include <header.h>
+#include <other.h>
+int use(void) { return sys_header_marker() + sys_other_marker(); }

>From b4c1709a6c28b1a345dc6e09351d217fc5c22c1b Mon Sep 17 00:00:00 2001
From: quic-asaravan <[email protected]>
Date: Tue, 17 Nov 2026 21:33:22 -0800
Subject: [PATCH 3/3] [clang][Lex] Locate #include_next start via the module
 map path

With nested search directories (-Ix -Ix/sub), a module header found
through the outer directory as "sub/h.h" was assumed to have been found
through the inner one as "h.h", so #include_next skipped the inner
directory and picked a header from a later one.

For a module header, first try the path its module map gives it, which is
how it was entered. Also, when the search directory the file was found in
is known, start after it directly instead of locating the file again.
---
 clang/lib/Lex/PPDirectives.cpp                | 37 +++++++++++++------
 .../include_next_nested_search_dirs_outer.c   | 37 +++++++++++++++++++
 2 files changed, 63 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/Modules/include_next_nested_search_dirs_outer.c

diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index a506bff37b1b3f..fd4919b30f558f 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -1153,13 +1153,22 @@ OptionalFileEntryRef Preprocessor::LookupFile(
       return false;
     };
 
-    // Candidate names for FromFile: its path relative to each search directory
-    // containing it, innermost first. Directories are matched by identity, as
-    // the file may have been reached via another spelling (e.g. "./x/...").
-    // FIXME: With nested search directories (-Ix -Ix/sub) the original name is
-    // ambiguous; we assume the innermost. Fixing this requires recording the
-    // search directory when a module header is entered.
+    // Candidate names for FromFile. A module header is entered under the path
+    // given in its module map (relative to the module's root directory), so
+    // that is the name it was found as, even if nested search directories
+    // (-Ix -Ix/sub) make it reachable under several names. Otherwise, fall 
back
+    // to its path relative to each search directory containing it, innermost
+    // first. Directories are matched by identity, as the file may have been
+    // reached via another spelling (e.g. "./x/...").
     SmallVector<std::string, 4> Names;
+    if (CurLexerSubmodule)
+      for (Module::HeaderKind HK :
+           {Module::HK_Normal, Module::HK_Textual, Module::HK_Private,
+            Module::HK_PrivateTextual})
+        for (const Module::Header &H : CurLexerSubmodule->getHeaders(HK))
+          if (&H.Entry.getFileEntry() == FromFile &&
+              !H.PathRelativeToRootModuleDirectory.empty())
+            Names.push_back(H.PathRelativeToRootModuleDirectory);
     StringRef BaseName;
     if (CurPPLexer)
       if (OptionalFileEntryRef CurFE = CurPPLexer->getFileEntry()) {
@@ -2184,12 +2193,18 @@ Preprocessor::getIncludeNextStart(const Token 
&IncludeNextTok) const {
     Lookup = nullptr;
     Diag(IncludeNextTok, diag::pp_include_next_in_primary);
   } else if (CurLexerSubmodule) {
-    // Start looking up in the directory *after* the one in which the current
-    // file would be found, if any.
     assert(CurPPLexer && "#include_next directive in macro?");
-    if (auto FE = CurPPLexer->getFileEntry())
-      LookupFromFile = *FE;
-    Lookup = nullptr;
+    if (Lookup) {
+      // The file was found by walking the search path, so we know the exact
+      // directory it came from. Start looking after it.
+      ++Lookup;
+    } else {
+      // The file was not found via a search directory (e.g. it was reached
+      // through a module map). Start looking in the directory *after* the one
+      // in which the current file would be found, if any.
+      if (auto FE = CurPPLexer->getFileEntry())
+        LookupFromFile = *FE;
+    }
   } else if (!Lookup) {
     // The current file was not found by walking the include path. Either it
     // is the primary file (handled above), or it was found by absolute path,
diff --git a/clang/test/Modules/include_next_nested_search_dirs_outer.c 
b/clang/test/Modules/include_next_nested_search_dirs_outer.c
new file mode 100644
index 00000000000000..8351eae6812ada
--- /dev/null
+++ b/clang/test/Modules/include_next_nested_search_dirs_outer.c
@@ -0,0 +1,37 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -I%t/inc -I%t/inc/v1 -I%t/sys -fsyntax-only -verify 
%t/main.c
+// RUN: %clang_cc1 -I%t/inc -I%t/inc/v1 -I%t/sys -fmodules \
+// RUN:   -fimplicit-module-maps -fmodules-cache-path=%t/cache -fsyntax-only \
+// RUN:   -verify %t/main.c
+
+// One search directory is nested in another, and the header is found through
+// the outer one (as "v1/other.h"). The '#include_next' must continue after the
+// outer directory, so it finds the header in the inner directory, rather than
+// assuming the header was found through the inner one and skipping to 'sys'.
+
+//--- inc/v1/other.h
+#ifndef V1_OTHER_H
+#define V1_OTHER_H
+#include_next <target.h>
+#endif
+
+//--- inc/v1/target.h
+#ifndef V1_TARGET_H
+#define V1_TARGET_H
+int v1_target_marker(void);
+#endif
+
+//--- inc/module.modulemap
+module Other { header "v1/other.h" export * }
+
+//--- sys/target.h
+#ifndef SYS_TARGET_H
+#define SYS_TARGET_H
+int sys_target_marker(void);
+#endif
+
+//--- main.c
+// expected-no-diagnostics
+#include <v1/other.h>
+int use(void) { return v1_target_marker(); }

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to