xref: /openbsd-src/gnu/llvm/clang/lib/Lex/HeaderSearch.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick //  This file implements the DirectoryLookup and HeaderSearch interfaces.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/Lex/HeaderSearch.h"
14e5dd7070Spatrick #include "clang/Basic/Diagnostic.h"
15e5dd7070Spatrick #include "clang/Basic/FileManager.h"
16e5dd7070Spatrick #include "clang/Basic/IdentifierTable.h"
17e5dd7070Spatrick #include "clang/Basic/Module.h"
18e5dd7070Spatrick #include "clang/Basic/SourceManager.h"
19e5dd7070Spatrick #include "clang/Lex/DirectoryLookup.h"
20e5dd7070Spatrick #include "clang/Lex/ExternalPreprocessorSource.h"
21e5dd7070Spatrick #include "clang/Lex/HeaderMap.h"
22e5dd7070Spatrick #include "clang/Lex/HeaderSearchOptions.h"
23e5dd7070Spatrick #include "clang/Lex/LexDiagnostic.h"
24e5dd7070Spatrick #include "clang/Lex/ModuleMap.h"
25e5dd7070Spatrick #include "clang/Lex/Preprocessor.h"
26e5dd7070Spatrick #include "llvm/ADT/APInt.h"
27e5dd7070Spatrick #include "llvm/ADT/Hashing.h"
28e5dd7070Spatrick #include "llvm/ADT/SmallString.h"
29e5dd7070Spatrick #include "llvm/ADT/SmallVector.h"
30e5dd7070Spatrick #include "llvm/ADT/Statistic.h"
31e5dd7070Spatrick #include "llvm/ADT/StringRef.h"
32*12c85518Srobert #include "llvm/ADT/STLExtras.h"
33e5dd7070Spatrick #include "llvm/Support/Allocator.h"
34e5dd7070Spatrick #include "llvm/Support/Capacity.h"
35e5dd7070Spatrick #include "llvm/Support/Errc.h"
36e5dd7070Spatrick #include "llvm/Support/ErrorHandling.h"
37e5dd7070Spatrick #include "llvm/Support/FileSystem.h"
38e5dd7070Spatrick #include "llvm/Support/Path.h"
39e5dd7070Spatrick #include "llvm/Support/VirtualFileSystem.h"
40e5dd7070Spatrick #include <algorithm>
41e5dd7070Spatrick #include <cassert>
42e5dd7070Spatrick #include <cstddef>
43e5dd7070Spatrick #include <cstdio>
44e5dd7070Spatrick #include <cstring>
45e5dd7070Spatrick #include <string>
46e5dd7070Spatrick #include <system_error>
47e5dd7070Spatrick #include <utility>
48e5dd7070Spatrick 
49e5dd7070Spatrick using namespace clang;
50e5dd7070Spatrick 
51e5dd7070Spatrick #define DEBUG_TYPE "file-search"
52e5dd7070Spatrick 
53e5dd7070Spatrick ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");
54e5dd7070Spatrick ALWAYS_ENABLED_STATISTIC(
55e5dd7070Spatrick     NumMultiIncludeFileOptzn,
56e5dd7070Spatrick     "Number of #includes skipped due to the multi-include optimization.");
57e5dd7070Spatrick ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");
58e5dd7070Spatrick ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,
59e5dd7070Spatrick                          "Number of subframework lookups.");
60e5dd7070Spatrick 
61e5dd7070Spatrick const IdentifierInfo *
getControllingMacro(ExternalPreprocessorSource * External)62e5dd7070Spatrick HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
63e5dd7070Spatrick   if (ControllingMacro) {
64e5dd7070Spatrick     if (ControllingMacro->isOutOfDate()) {
65e5dd7070Spatrick       assert(External && "We must have an external source if we have a "
66e5dd7070Spatrick                          "controlling macro that is out of date.");
67e5dd7070Spatrick       External->updateOutOfDateIdentifier(
68e5dd7070Spatrick           *const_cast<IdentifierInfo *>(ControllingMacro));
69e5dd7070Spatrick     }
70e5dd7070Spatrick     return ControllingMacro;
71e5dd7070Spatrick   }
72e5dd7070Spatrick 
73e5dd7070Spatrick   if (!ControllingMacroID || !External)
74e5dd7070Spatrick     return nullptr;
75e5dd7070Spatrick 
76e5dd7070Spatrick   ControllingMacro = External->GetIdentifier(ControllingMacroID);
77e5dd7070Spatrick   return ControllingMacro;
78e5dd7070Spatrick }
79e5dd7070Spatrick 
80e5dd7070Spatrick ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
81e5dd7070Spatrick 
HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,SourceManager & SourceMgr,DiagnosticsEngine & Diags,const LangOptions & LangOpts,const TargetInfo * Target)82e5dd7070Spatrick HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
83e5dd7070Spatrick                            SourceManager &SourceMgr, DiagnosticsEngine &Diags,
84e5dd7070Spatrick                            const LangOptions &LangOpts,
85e5dd7070Spatrick                            const TargetInfo *Target)
86e5dd7070Spatrick     : HSOpts(std::move(HSOpts)), Diags(Diags),
87e5dd7070Spatrick       FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
88e5dd7070Spatrick       ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
89e5dd7070Spatrick 
PrintStats()90e5dd7070Spatrick void HeaderSearch::PrintStats() {
91e5dd7070Spatrick   llvm::errs() << "\n*** HeaderSearch Stats:\n"
92e5dd7070Spatrick                << FileInfo.size() << " files tracked.\n";
93*12c85518Srobert   unsigned NumOnceOnlyFiles = 0;
94*12c85518Srobert   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i)
95*12c85518Srobert     NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport);
96*12c85518Srobert   llvm::errs() << "  " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
97e5dd7070Spatrick 
98e5dd7070Spatrick   llvm::errs() << "  " << NumIncluded << " #include/#include_next/#import.\n"
99e5dd7070Spatrick                << "    " << NumMultiIncludeFileOptzn
100e5dd7070Spatrick                << " #includes skipped due to the multi-include optimization.\n";
101e5dd7070Spatrick 
102e5dd7070Spatrick   llvm::errs() << NumFrameworkLookups << " framework lookups.\n"
103e5dd7070Spatrick                << NumSubFrameworkLookups << " subframework lookups.\n";
104e5dd7070Spatrick }
105e5dd7070Spatrick 
SetSearchPaths(std::vector<DirectoryLookup> dirs,unsigned int angledDirIdx,unsigned int systemDirIdx,bool noCurDirSearch,llvm::DenseMap<unsigned int,unsigned int> searchDirToHSEntry)106*12c85518Srobert void HeaderSearch::SetSearchPaths(
107*12c85518Srobert     std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx,
108*12c85518Srobert     unsigned int systemDirIdx, bool noCurDirSearch,
109*12c85518Srobert     llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) {
110*12c85518Srobert   assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
111*12c85518Srobert          "Directory indices are unordered");
112*12c85518Srobert   SearchDirs = std::move(dirs);
113*12c85518Srobert   SearchDirsUsage.assign(SearchDirs.size(), false);
114*12c85518Srobert   AngledDirIdx = angledDirIdx;
115*12c85518Srobert   SystemDirIdx = systemDirIdx;
116*12c85518Srobert   NoCurDirSearch = noCurDirSearch;
117*12c85518Srobert   SearchDirToHSEntry = std::move(searchDirToHSEntry);
118*12c85518Srobert   //LookupFileCache.clear();
119*12c85518Srobert   indexInitialHeaderMaps();
120*12c85518Srobert }
121*12c85518Srobert 
AddSearchPath(const DirectoryLookup & dir,bool isAngled)122*12c85518Srobert void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
123*12c85518Srobert   unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
124*12c85518Srobert   SearchDirs.insert(SearchDirs.begin() + idx, dir);
125*12c85518Srobert   SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false);
126*12c85518Srobert   if (!isAngled)
127*12c85518Srobert     AngledDirIdx++;
128*12c85518Srobert   SystemDirIdx++;
129*12c85518Srobert }
130*12c85518Srobert 
computeUserEntryUsage() const131*12c85518Srobert std::vector<bool> HeaderSearch::computeUserEntryUsage() const {
132*12c85518Srobert   std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());
133*12c85518Srobert   for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {
134*12c85518Srobert     // Check whether this DirectoryLookup has been successfully used.
135*12c85518Srobert     if (SearchDirsUsage[I]) {
136*12c85518Srobert       auto UserEntryIdxIt = SearchDirToHSEntry.find(I);
137*12c85518Srobert       // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
138*12c85518Srobert       if (UserEntryIdxIt != SearchDirToHSEntry.end())
139*12c85518Srobert         UserEntryUsage[UserEntryIdxIt->second] = true;
140*12c85518Srobert     }
141*12c85518Srobert   }
142*12c85518Srobert   return UserEntryUsage;
143*12c85518Srobert }
144*12c85518Srobert 
145e5dd7070Spatrick /// CreateHeaderMap - This method returns a HeaderMap for the specified
146e5dd7070Spatrick /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
CreateHeaderMap(const FileEntry * FE)147e5dd7070Spatrick const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
148e5dd7070Spatrick   // We expect the number of headermaps to be small, and almost always empty.
149e5dd7070Spatrick   // If it ever grows, use of a linear search should be re-evaluated.
150e5dd7070Spatrick   if (!HeaderMaps.empty()) {
151e5dd7070Spatrick     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
152e5dd7070Spatrick       // Pointer equality comparison of FileEntries works because they are
153e5dd7070Spatrick       // already uniqued by inode.
154e5dd7070Spatrick       if (HeaderMaps[i].first == FE)
155e5dd7070Spatrick         return HeaderMaps[i].second.get();
156e5dd7070Spatrick   }
157e5dd7070Spatrick 
158e5dd7070Spatrick   if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
159e5dd7070Spatrick     HeaderMaps.emplace_back(FE, std::move(HM));
160e5dd7070Spatrick     return HeaderMaps.back().second.get();
161e5dd7070Spatrick   }
162e5dd7070Spatrick 
163e5dd7070Spatrick   return nullptr;
164e5dd7070Spatrick }
165e5dd7070Spatrick 
166e5dd7070Spatrick /// Get filenames for all registered header maps.
getHeaderMapFileNames(SmallVectorImpl<std::string> & Names) const167e5dd7070Spatrick void HeaderSearch::getHeaderMapFileNames(
168e5dd7070Spatrick     SmallVectorImpl<std::string> &Names) const {
169e5dd7070Spatrick   for (auto &HM : HeaderMaps)
170ec727ea7Spatrick     Names.push_back(std::string(HM.first->getName()));
171e5dd7070Spatrick }
172e5dd7070Spatrick 
getCachedModuleFileName(Module * Module)173e5dd7070Spatrick std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
174*12c85518Srobert   OptionalFileEntryRef ModuleMap =
175e5dd7070Spatrick       getModuleMap().getModuleMapFileForUniquing(Module);
176*12c85518Srobert   // The ModuleMap maybe a nullptr, when we load a cached C++ module without
177*12c85518Srobert   // *.modulemap file. In this case, just return an empty string.
178*12c85518Srobert   if (!ModuleMap)
179*12c85518Srobert     return {};
180e5dd7070Spatrick   return getCachedModuleFileName(Module->Name, ModuleMap->getName());
181e5dd7070Spatrick }
182e5dd7070Spatrick 
getPrebuiltModuleFileName(StringRef ModuleName,bool FileMapOnly)183e5dd7070Spatrick std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
184e5dd7070Spatrick                                                     bool FileMapOnly) {
185e5dd7070Spatrick   // First check the module name to pcm file map.
186e5dd7070Spatrick   auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
187e5dd7070Spatrick   if (i != HSOpts->PrebuiltModuleFiles.end())
188e5dd7070Spatrick     return i->second;
189e5dd7070Spatrick 
190e5dd7070Spatrick   if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
191e5dd7070Spatrick     return {};
192e5dd7070Spatrick 
193e5dd7070Spatrick   // Then go through each prebuilt module directory and try to find the pcm
194e5dd7070Spatrick   // file.
195e5dd7070Spatrick   for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
196e5dd7070Spatrick     SmallString<256> Result(Dir);
197e5dd7070Spatrick     llvm::sys::fs::make_absolute(Result);
198*12c85518Srobert     if (ModuleName.contains(':'))
199*12c85518Srobert       // The separator of C++20 modules partitions (':') is not good for file
200*12c85518Srobert       // systems, here clang and gcc choose '-' by default since it is not a
201*12c85518Srobert       // valid character of C++ indentifiers. So we could avoid conflicts.
202*12c85518Srobert       llvm::sys::path::append(Result, ModuleName.split(':').first + "-" +
203*12c85518Srobert                                           ModuleName.split(':').second +
204*12c85518Srobert                                           ".pcm");
205*12c85518Srobert     else
206e5dd7070Spatrick       llvm::sys::path::append(Result, ModuleName + ".pcm");
207e5dd7070Spatrick     if (getFileMgr().getFile(Result.str()))
208ec727ea7Spatrick       return std::string(Result);
209e5dd7070Spatrick   }
210*12c85518Srobert 
211e5dd7070Spatrick   return {};
212e5dd7070Spatrick }
213e5dd7070Spatrick 
getPrebuiltImplicitModuleFileName(Module * Module)214a9ac8606Spatrick std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) {
215*12c85518Srobert   OptionalFileEntryRef ModuleMap =
216a9ac8606Spatrick       getModuleMap().getModuleMapFileForUniquing(Module);
217a9ac8606Spatrick   StringRef ModuleName = Module->Name;
218a9ac8606Spatrick   StringRef ModuleMapPath = ModuleMap->getName();
219a9ac8606Spatrick   StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();
220a9ac8606Spatrick   for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
221a9ac8606Spatrick     SmallString<256> CachePath(Dir);
222a9ac8606Spatrick     llvm::sys::fs::make_absolute(CachePath);
223a9ac8606Spatrick     llvm::sys::path::append(CachePath, ModuleCacheHash);
224a9ac8606Spatrick     std::string FileName =
225a9ac8606Spatrick         getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);
226a9ac8606Spatrick     if (!FileName.empty() && getFileMgr().getFile(FileName))
227a9ac8606Spatrick       return FileName;
228a9ac8606Spatrick   }
229a9ac8606Spatrick   return {};
230a9ac8606Spatrick }
231a9ac8606Spatrick 
getCachedModuleFileName(StringRef ModuleName,StringRef ModuleMapPath)232e5dd7070Spatrick std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
233e5dd7070Spatrick                                                   StringRef ModuleMapPath) {
234a9ac8606Spatrick   return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,
235a9ac8606Spatrick                                      getModuleCachePath());
236a9ac8606Spatrick }
237a9ac8606Spatrick 
getCachedModuleFileNameImpl(StringRef ModuleName,StringRef ModuleMapPath,StringRef CachePath)238a9ac8606Spatrick std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,
239a9ac8606Spatrick                                                       StringRef ModuleMapPath,
240a9ac8606Spatrick                                                       StringRef CachePath) {
241e5dd7070Spatrick   // If we don't have a module cache path or aren't supposed to use one, we
242e5dd7070Spatrick   // can't do anything.
243a9ac8606Spatrick   if (CachePath.empty())
244e5dd7070Spatrick     return {};
245e5dd7070Spatrick 
246a9ac8606Spatrick   SmallString<256> Result(CachePath);
247e5dd7070Spatrick   llvm::sys::fs::make_absolute(Result);
248e5dd7070Spatrick 
249e5dd7070Spatrick   if (HSOpts->DisableModuleHash) {
250e5dd7070Spatrick     llvm::sys::path::append(Result, ModuleName + ".pcm");
251e5dd7070Spatrick   } else {
252e5dd7070Spatrick     // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
253e5dd7070Spatrick     // ideally be globally unique to this particular module. Name collisions
254e5dd7070Spatrick     // in the hash are safe (because any translation unit can only import one
255e5dd7070Spatrick     // module with each name), but result in a loss of caching.
256e5dd7070Spatrick     //
257e5dd7070Spatrick     // To avoid false-negatives, we form as canonical a path as we can, and map
258e5dd7070Spatrick     // to lower-case in case we're on a case-insensitive file system.
259*12c85518Srobert     SmallString<128> CanonicalPath(ModuleMapPath);
260*12c85518Srobert     if (getModuleMap().canonicalizeModuleMapPath(CanonicalPath))
261e5dd7070Spatrick       return {};
262e5dd7070Spatrick 
263*12c85518Srobert     llvm::hash_code Hash = llvm::hash_combine(CanonicalPath.str().lower());
264e5dd7070Spatrick 
265e5dd7070Spatrick     SmallString<128> HashStr;
266e5dd7070Spatrick     llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
267e5dd7070Spatrick     llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
268e5dd7070Spatrick   }
269e5dd7070Spatrick   return Result.str().str();
270e5dd7070Spatrick }
271e5dd7070Spatrick 
lookupModule(StringRef ModuleName,SourceLocation ImportLoc,bool AllowSearch,bool AllowExtraModuleMapSearch)272*12c85518Srobert Module *HeaderSearch::lookupModule(StringRef ModuleName,
273*12c85518Srobert                                    SourceLocation ImportLoc, bool AllowSearch,
274e5dd7070Spatrick                                    bool AllowExtraModuleMapSearch) {
275e5dd7070Spatrick   // Look in the module map to determine if there is a module by this name.
276e5dd7070Spatrick   Module *Module = ModMap.findModule(ModuleName);
277e5dd7070Spatrick   if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
278e5dd7070Spatrick     return Module;
279e5dd7070Spatrick 
280e5dd7070Spatrick   StringRef SearchName = ModuleName;
281*12c85518Srobert   Module = lookupModule(ModuleName, SearchName, ImportLoc,
282*12c85518Srobert                         AllowExtraModuleMapSearch);
283e5dd7070Spatrick 
284e5dd7070Spatrick   // The facility for "private modules" -- adjacent, optional module maps named
285e5dd7070Spatrick   // module.private.modulemap that are supposed to define private submodules --
286e5dd7070Spatrick   // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
287e5dd7070Spatrick   //
288e5dd7070Spatrick   // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
289e5dd7070Spatrick   // should also rename to Foo_Private. Representing private as submodules
290e5dd7070Spatrick   // could force building unwanted dependencies into the parent module and cause
291e5dd7070Spatrick   // dependency cycles.
292e5dd7070Spatrick   if (!Module && SearchName.consume_back("_Private"))
293*12c85518Srobert     Module = lookupModule(ModuleName, SearchName, ImportLoc,
294*12c85518Srobert                           AllowExtraModuleMapSearch);
295e5dd7070Spatrick   if (!Module && SearchName.consume_back("Private"))
296*12c85518Srobert     Module = lookupModule(ModuleName, SearchName, ImportLoc,
297*12c85518Srobert                           AllowExtraModuleMapSearch);
298e5dd7070Spatrick   return Module;
299e5dd7070Spatrick }
300e5dd7070Spatrick 
lookupModule(StringRef ModuleName,StringRef SearchName,SourceLocation ImportLoc,bool AllowExtraModuleMapSearch)301e5dd7070Spatrick Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
302*12c85518Srobert                                    SourceLocation ImportLoc,
303e5dd7070Spatrick                                    bool AllowExtraModuleMapSearch) {
304e5dd7070Spatrick   Module *Module = nullptr;
305e5dd7070Spatrick 
306e5dd7070Spatrick   // Look through the various header search paths to load any available module
307e5dd7070Spatrick   // maps, searching for a module map that describes this module.
308*12c85518Srobert   for (DirectoryLookup &Dir : search_dir_range()) {
309*12c85518Srobert     if (Dir.isFramework()) {
310e5dd7070Spatrick       // Search for or infer a module map for a framework. Here we use
311e5dd7070Spatrick       // SearchName rather than ModuleName, to permit finding private modules
312e5dd7070Spatrick       // named FooPrivate in buggy frameworks named Foo.
313e5dd7070Spatrick       SmallString<128> FrameworkDirName;
314*12c85518Srobert       FrameworkDirName += Dir.getFrameworkDir()->getName();
315e5dd7070Spatrick       llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
316*12c85518Srobert       if (auto FrameworkDir =
317*12c85518Srobert               FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {
318*12c85518Srobert         bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;
319e5dd7070Spatrick         Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
320e5dd7070Spatrick         if (Module)
321e5dd7070Spatrick           break;
322e5dd7070Spatrick       }
323e5dd7070Spatrick     }
324e5dd7070Spatrick 
325e5dd7070Spatrick     // FIXME: Figure out how header maps and module maps will work together.
326e5dd7070Spatrick 
327e5dd7070Spatrick     // Only deal with normal search directories.
328*12c85518Srobert     if (!Dir.isNormalDir())
329e5dd7070Spatrick       continue;
330e5dd7070Spatrick 
331*12c85518Srobert     bool IsSystem = Dir.isSystemHeaderDirectory();
332*12c85518Srobert     // Only returns std::nullopt if not a normal directory, which we just
333*12c85518Srobert     // checked
334*12c85518Srobert     DirectoryEntryRef NormalDir = *Dir.getDirRef();
335e5dd7070Spatrick     // Search for a module map file in this directory.
336*12c85518Srobert     if (loadModuleMapFile(NormalDir, IsSystem,
337e5dd7070Spatrick                           /*IsFramework*/false) == LMM_NewlyLoaded) {
338e5dd7070Spatrick       // We just loaded a module map file; check whether the module is
339e5dd7070Spatrick       // available now.
340e5dd7070Spatrick       Module = ModMap.findModule(ModuleName);
341e5dd7070Spatrick       if (Module)
342e5dd7070Spatrick         break;
343e5dd7070Spatrick     }
344e5dd7070Spatrick 
345e5dd7070Spatrick     // Search for a module map in a subdirectory with the same name as the
346e5dd7070Spatrick     // module.
347e5dd7070Spatrick     SmallString<128> NestedModuleMapDirName;
348*12c85518Srobert     NestedModuleMapDirName = Dir.getDir()->getName();
349e5dd7070Spatrick     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
350e5dd7070Spatrick     if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
351e5dd7070Spatrick                           /*IsFramework*/false) == LMM_NewlyLoaded){
352e5dd7070Spatrick       // If we just loaded a module map file, look for the module again.
353e5dd7070Spatrick       Module = ModMap.findModule(ModuleName);
354e5dd7070Spatrick       if (Module)
355e5dd7070Spatrick         break;
356e5dd7070Spatrick     }
357e5dd7070Spatrick 
358e5dd7070Spatrick     // If we've already performed the exhaustive search for module maps in this
359e5dd7070Spatrick     // search directory, don't do it again.
360*12c85518Srobert     if (Dir.haveSearchedAllModuleMaps())
361e5dd7070Spatrick       continue;
362e5dd7070Spatrick 
363e5dd7070Spatrick     // Load all module maps in the immediate subdirectories of this search
364e5dd7070Spatrick     // directory if ModuleName was from @import.
365e5dd7070Spatrick     if (AllowExtraModuleMapSearch)
366*12c85518Srobert       loadSubdirectoryModuleMaps(Dir);
367e5dd7070Spatrick 
368e5dd7070Spatrick     // Look again for the module.
369e5dd7070Spatrick     Module = ModMap.findModule(ModuleName);
370e5dd7070Spatrick     if (Module)
371e5dd7070Spatrick       break;
372e5dd7070Spatrick   }
373e5dd7070Spatrick 
374e5dd7070Spatrick   return Module;
375e5dd7070Spatrick }
376e5dd7070Spatrick 
indexInitialHeaderMaps()377*12c85518Srobert void HeaderSearch::indexInitialHeaderMaps() {
378*12c85518Srobert   llvm::StringMap<unsigned, llvm::BumpPtrAllocator> Index(SearchDirs.size());
379*12c85518Srobert 
380*12c85518Srobert   // Iterate over all filename keys and associate them with the index i.
381*12c85518Srobert   unsigned i = 0;
382*12c85518Srobert   for (; i != SearchDirs.size(); ++i) {
383*12c85518Srobert     auto &Dir = SearchDirs[i];
384*12c85518Srobert 
385*12c85518Srobert     // We're concerned with only the initial contiguous run of header
386*12c85518Srobert     // maps within SearchDirs, which can be 99% of SearchDirs when
387*12c85518Srobert     // SearchDirs.size() is ~10000.
388*12c85518Srobert     if (!Dir.isHeaderMap())
389*12c85518Srobert       break;
390*12c85518Srobert 
391*12c85518Srobert     // Give earlier keys precedence over identical later keys.
392*12c85518Srobert     auto Callback = [&](StringRef Filename) {
393*12c85518Srobert       Index.try_emplace(Filename.lower(), i);
394*12c85518Srobert     };
395*12c85518Srobert     Dir.getHeaderMap()->forEachKey(Callback);
396*12c85518Srobert   }
397*12c85518Srobert 
398*12c85518Srobert   SearchDirHeaderMapIndex = std::move(Index);
399*12c85518Srobert   FirstNonHeaderMapSearchDirIdx = i;
400*12c85518Srobert }
401*12c85518Srobert 
402e5dd7070Spatrick //===----------------------------------------------------------------------===//
403e5dd7070Spatrick // File lookup within a DirectoryLookup scope
404e5dd7070Spatrick //===----------------------------------------------------------------------===//
405e5dd7070Spatrick 
406e5dd7070Spatrick /// getName - Return the directory or filename corresponding to this lookup
407e5dd7070Spatrick /// object.
getName() const408e5dd7070Spatrick StringRef DirectoryLookup::getName() const {
409e5dd7070Spatrick   // FIXME: Use the name from \c DirectoryEntryRef.
410e5dd7070Spatrick   if (isNormalDir())
411e5dd7070Spatrick     return getDir()->getName();
412e5dd7070Spatrick   if (isFramework())
413e5dd7070Spatrick     return getFrameworkDir()->getName();
414e5dd7070Spatrick   assert(isHeaderMap() && "Unknown DirectoryLookup");
415e5dd7070Spatrick   return getHeaderMap()->getFileName();
416e5dd7070Spatrick }
417e5dd7070Spatrick 
getFileAndSuggestModule(StringRef FileName,SourceLocation IncludeLoc,const DirectoryEntry * Dir,bool IsSystemHeaderDir,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool OpenFile,bool CacheFailures)418*12c85518Srobert OptionalFileEntryRef HeaderSearch::getFileAndSuggestModule(
419e5dd7070Spatrick     StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
420e5dd7070Spatrick     bool IsSystemHeaderDir, Module *RequestingModule,
421*12c85518Srobert     ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/,
422*12c85518Srobert     bool CacheFailures /*=true*/) {
423e5dd7070Spatrick   // If we have a module map that might map this header, load it and
424e5dd7070Spatrick   // check whether we'll have a suggestion for a module.
425*12c85518Srobert   auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures);
426e5dd7070Spatrick   if (!File) {
427e5dd7070Spatrick     // For rare, surprising errors (e.g. "out of file handles"), diag the EC
428e5dd7070Spatrick     // message.
429e5dd7070Spatrick     std::error_code EC = llvm::errorToErrorCode(File.takeError());
430e5dd7070Spatrick     if (EC != llvm::errc::no_such_file_or_directory &&
431e5dd7070Spatrick         EC != llvm::errc::invalid_argument &&
432e5dd7070Spatrick         EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
433e5dd7070Spatrick       Diags.Report(IncludeLoc, diag::err_cannot_open_file)
434e5dd7070Spatrick           << FileName << EC.message();
435e5dd7070Spatrick     }
436*12c85518Srobert     return std::nullopt;
437e5dd7070Spatrick   }
438e5dd7070Spatrick 
439e5dd7070Spatrick   // If there is a module that corresponds to this header, suggest it.
440e5dd7070Spatrick   if (!findUsableModuleForHeader(
441e5dd7070Spatrick           &File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(),
442e5dd7070Spatrick           RequestingModule, SuggestedModule, IsSystemHeaderDir))
443*12c85518Srobert     return std::nullopt;
444e5dd7070Spatrick 
445e5dd7070Spatrick   return *File;
446e5dd7070Spatrick }
447e5dd7070Spatrick 
448e5dd7070Spatrick /// LookupFile - Lookup the specified file in this search path, returning it
449e5dd7070Spatrick /// if it exists or returning null if not.
LookupFile(StringRef & Filename,HeaderSearch & HS,SourceLocation IncludeLoc,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool & InUserSpecifiedSystemFramework,bool & IsFrameworkFound,bool & IsInHeaderMap,SmallVectorImpl<char> & MappedName,bool OpenFile) const450*12c85518Srobert OptionalFileEntryRef DirectoryLookup::LookupFile(
451e5dd7070Spatrick     StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
452e5dd7070Spatrick     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
453e5dd7070Spatrick     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
454e5dd7070Spatrick     bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
455*12c85518Srobert     bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName,
456*12c85518Srobert     bool OpenFile) const {
457e5dd7070Spatrick   InUserSpecifiedSystemFramework = false;
458e5dd7070Spatrick   IsInHeaderMap = false;
459e5dd7070Spatrick   MappedName.clear();
460e5dd7070Spatrick 
461e5dd7070Spatrick   SmallString<1024> TmpDir;
462e5dd7070Spatrick   if (isNormalDir()) {
463e5dd7070Spatrick     // Concatenate the requested file onto the directory.
464*12c85518Srobert     TmpDir = getDirRef()->getName();
465e5dd7070Spatrick     llvm::sys::path::append(TmpDir, Filename);
466e5dd7070Spatrick     if (SearchPath) {
467*12c85518Srobert       StringRef SearchPathRef(getDirRef()->getName());
468e5dd7070Spatrick       SearchPath->clear();
469e5dd7070Spatrick       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
470e5dd7070Spatrick     }
471e5dd7070Spatrick     if (RelativePath) {
472e5dd7070Spatrick       RelativePath->clear();
473e5dd7070Spatrick       RelativePath->append(Filename.begin(), Filename.end());
474e5dd7070Spatrick     }
475e5dd7070Spatrick 
476*12c85518Srobert     return HS.getFileAndSuggestModule(
477*12c85518Srobert         TmpDir, IncludeLoc, getDir(), isSystemHeaderDirectory(),
478*12c85518Srobert         RequestingModule, SuggestedModule, OpenFile);
479e5dd7070Spatrick   }
480e5dd7070Spatrick 
481e5dd7070Spatrick   if (isFramework())
482e5dd7070Spatrick     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
483e5dd7070Spatrick                              RequestingModule, SuggestedModule,
484e5dd7070Spatrick                              InUserSpecifiedSystemFramework, IsFrameworkFound);
485e5dd7070Spatrick 
486e5dd7070Spatrick   assert(isHeaderMap() && "Unknown directory lookup");
487e5dd7070Spatrick   const HeaderMap *HM = getHeaderMap();
488e5dd7070Spatrick   SmallString<1024> Path;
489e5dd7070Spatrick   StringRef Dest = HM->lookupFilename(Filename, Path);
490e5dd7070Spatrick   if (Dest.empty())
491*12c85518Srobert     return std::nullopt;
492e5dd7070Spatrick 
493e5dd7070Spatrick   IsInHeaderMap = true;
494e5dd7070Spatrick 
495e5dd7070Spatrick   auto FixupSearchPath = [&]() {
496e5dd7070Spatrick     if (SearchPath) {
497e5dd7070Spatrick       StringRef SearchPathRef(getName());
498e5dd7070Spatrick       SearchPath->clear();
499e5dd7070Spatrick       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
500e5dd7070Spatrick     }
501e5dd7070Spatrick     if (RelativePath) {
502e5dd7070Spatrick       RelativePath->clear();
503e5dd7070Spatrick       RelativePath->append(Filename.begin(), Filename.end());
504e5dd7070Spatrick     }
505e5dd7070Spatrick   };
506e5dd7070Spatrick 
507e5dd7070Spatrick   // Check if the headermap maps the filename to a framework include
508e5dd7070Spatrick   // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
509e5dd7070Spatrick   // framework include.
510e5dd7070Spatrick   if (llvm::sys::path::is_relative(Dest)) {
511e5dd7070Spatrick     MappedName.append(Dest.begin(), Dest.end());
512e5dd7070Spatrick     Filename = StringRef(MappedName.begin(), MappedName.size());
513*12c85518Srobert     Dest = HM->lookupFilename(Filename, Path);
514e5dd7070Spatrick   }
515*12c85518Srobert 
516*12c85518Srobert   if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest, OpenFile)) {
517e5dd7070Spatrick     FixupSearchPath();
518e5dd7070Spatrick     return *Res;
519e5dd7070Spatrick   }
520e5dd7070Spatrick 
521*12c85518Srobert   // Header maps need to be marked as used whenever the filename matches.
522*12c85518Srobert   // The case where the target file **exists** is handled by callee of this
523*12c85518Srobert   // function as part of the regular logic that applies to include search paths.
524*12c85518Srobert   // The case where the target file **does not exist** is handled here:
525*12c85518Srobert   HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc);
526*12c85518Srobert   return std::nullopt;
527e5dd7070Spatrick }
528e5dd7070Spatrick 
529e5dd7070Spatrick /// Given a framework directory, find the top-most framework directory.
530e5dd7070Spatrick ///
531e5dd7070Spatrick /// \param FileMgr The file manager to use for directory lookups.
532e5dd7070Spatrick /// \param DirName The name of the framework directory.
533e5dd7070Spatrick /// \param SubmodulePath Will be populated with the submodule path from the
534e5dd7070Spatrick /// returned top-level module to the originally named framework.
535*12c85518Srobert static OptionalDirectoryEntryRef
getTopFrameworkDir(FileManager & FileMgr,StringRef DirName,SmallVectorImpl<std::string> & SubmodulePath)536e5dd7070Spatrick getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
537e5dd7070Spatrick                    SmallVectorImpl<std::string> &SubmodulePath) {
538e5dd7070Spatrick   assert(llvm::sys::path::extension(DirName) == ".framework" &&
539e5dd7070Spatrick          "Not a framework directory");
540e5dd7070Spatrick 
541e5dd7070Spatrick   // Note: as an egregious but useful hack we use the real path here, because
542e5dd7070Spatrick   // frameworks moving between top-level frameworks to embedded frameworks tend
543e5dd7070Spatrick   // to be symlinked, and we base the logical structure of modules on the
544e5dd7070Spatrick   // physical layout. In particular, we need to deal with crazy includes like
545e5dd7070Spatrick   //
546e5dd7070Spatrick   //   #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
547e5dd7070Spatrick   //
548e5dd7070Spatrick   // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
549e5dd7070Spatrick   // which one should access with, e.g.,
550e5dd7070Spatrick   //
551e5dd7070Spatrick   //   #include <Bar/Wibble.h>
552e5dd7070Spatrick   //
553e5dd7070Spatrick   // Similar issues occur when a top-level framework has moved into an
554e5dd7070Spatrick   // embedded framework.
555*12c85518Srobert   auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);
556e5dd7070Spatrick 
557e5dd7070Spatrick   if (TopFrameworkDir)
558*12c85518Srobert     DirName = FileMgr.getCanonicalName(*TopFrameworkDir);
559e5dd7070Spatrick   do {
560e5dd7070Spatrick     // Get the parent directory name.
561e5dd7070Spatrick     DirName = llvm::sys::path::parent_path(DirName);
562e5dd7070Spatrick     if (DirName.empty())
563e5dd7070Spatrick       break;
564e5dd7070Spatrick 
565e5dd7070Spatrick     // Determine whether this directory exists.
566*12c85518Srobert     auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
567e5dd7070Spatrick     if (!Dir)
568e5dd7070Spatrick       break;
569e5dd7070Spatrick 
570e5dd7070Spatrick     // If this is a framework directory, then we're a subframework of this
571e5dd7070Spatrick     // framework.
572e5dd7070Spatrick     if (llvm::sys::path::extension(DirName) == ".framework") {
573ec727ea7Spatrick       SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
574e5dd7070Spatrick       TopFrameworkDir = *Dir;
575e5dd7070Spatrick     }
576e5dd7070Spatrick   } while (true);
577e5dd7070Spatrick 
578e5dd7070Spatrick   return TopFrameworkDir;
579e5dd7070Spatrick }
580e5dd7070Spatrick 
needModuleLookup(Module * RequestingModule,bool HasSuggestedModule)581e5dd7070Spatrick static bool needModuleLookup(Module *RequestingModule,
582e5dd7070Spatrick                              bool HasSuggestedModule) {
583e5dd7070Spatrick   return HasSuggestedModule ||
584e5dd7070Spatrick          (RequestingModule && RequestingModule->NoUndeclaredIncludes);
585e5dd7070Spatrick }
586e5dd7070Spatrick 
587e5dd7070Spatrick /// DoFrameworkLookup - Do a lookup of the specified file in the current
588e5dd7070Spatrick /// DirectoryLookup, which is a framework directory.
DoFrameworkLookup(StringRef Filename,HeaderSearch & HS,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool & InUserSpecifiedSystemFramework,bool & IsFrameworkFound) const589*12c85518Srobert OptionalFileEntryRef DirectoryLookup::DoFrameworkLookup(
590e5dd7070Spatrick     StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
591e5dd7070Spatrick     SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
592e5dd7070Spatrick     ModuleMap::KnownHeader *SuggestedModule,
593e5dd7070Spatrick     bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
594e5dd7070Spatrick   FileManager &FileMgr = HS.getFileMgr();
595e5dd7070Spatrick 
596e5dd7070Spatrick   // Framework names must have a '/' in the filename.
597e5dd7070Spatrick   size_t SlashPos = Filename.find('/');
598e5dd7070Spatrick   if (SlashPos == StringRef::npos)
599*12c85518Srobert     return std::nullopt;
600e5dd7070Spatrick 
601e5dd7070Spatrick   // Find out if this is the home for the specified framework, by checking
602e5dd7070Spatrick   // HeaderSearch.  Possible answers are yes/no and unknown.
603e5dd7070Spatrick   FrameworkCacheEntry &CacheEntry =
604e5dd7070Spatrick     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
605e5dd7070Spatrick 
606e5dd7070Spatrick   // If it is known and in some other directory, fail.
607*12c85518Srobert   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef())
608*12c85518Srobert     return std::nullopt;
609e5dd7070Spatrick 
610e5dd7070Spatrick   // Otherwise, construct the path to this framework dir.
611e5dd7070Spatrick 
612e5dd7070Spatrick   // FrameworkName = "/System/Library/Frameworks/"
613e5dd7070Spatrick   SmallString<1024> FrameworkName;
614e5dd7070Spatrick   FrameworkName += getFrameworkDirRef()->getName();
615e5dd7070Spatrick   if (FrameworkName.empty() || FrameworkName.back() != '/')
616e5dd7070Spatrick     FrameworkName.push_back('/');
617e5dd7070Spatrick 
618e5dd7070Spatrick   // FrameworkName = "/System/Library/Frameworks/Cocoa"
619e5dd7070Spatrick   StringRef ModuleName(Filename.begin(), SlashPos);
620e5dd7070Spatrick   FrameworkName += ModuleName;
621e5dd7070Spatrick 
622e5dd7070Spatrick   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
623e5dd7070Spatrick   FrameworkName += ".framework/";
624e5dd7070Spatrick 
625e5dd7070Spatrick   // If the cache entry was unresolved, populate it now.
626e5dd7070Spatrick   if (!CacheEntry.Directory) {
627e5dd7070Spatrick     ++NumFrameworkLookups;
628e5dd7070Spatrick 
629e5dd7070Spatrick     // If the framework dir doesn't exist, we fail.
630e5dd7070Spatrick     auto Dir = FileMgr.getDirectory(FrameworkName);
631e5dd7070Spatrick     if (!Dir)
632*12c85518Srobert       return std::nullopt;
633e5dd7070Spatrick 
634e5dd7070Spatrick     // Otherwise, if it does, remember that this is the right direntry for this
635e5dd7070Spatrick     // framework.
636*12c85518Srobert     CacheEntry.Directory = getFrameworkDirRef();
637e5dd7070Spatrick 
638e5dd7070Spatrick     // If this is a user search directory, check if the framework has been
639e5dd7070Spatrick     // user-specified as a system framework.
640e5dd7070Spatrick     if (getDirCharacteristic() == SrcMgr::C_User) {
641e5dd7070Spatrick       SmallString<1024> SystemFrameworkMarker(FrameworkName);
642e5dd7070Spatrick       SystemFrameworkMarker += ".system_framework";
643e5dd7070Spatrick       if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
644e5dd7070Spatrick         CacheEntry.IsUserSpecifiedSystemFramework = true;
645e5dd7070Spatrick       }
646e5dd7070Spatrick     }
647e5dd7070Spatrick   }
648e5dd7070Spatrick 
649e5dd7070Spatrick   // Set out flags.
650e5dd7070Spatrick   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
651*12c85518Srobert   IsFrameworkFound = CacheEntry.Directory.has_value();
652e5dd7070Spatrick 
653e5dd7070Spatrick   if (RelativePath) {
654e5dd7070Spatrick     RelativePath->clear();
655e5dd7070Spatrick     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
656e5dd7070Spatrick   }
657e5dd7070Spatrick 
658e5dd7070Spatrick   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
659e5dd7070Spatrick   unsigned OrigSize = FrameworkName.size();
660e5dd7070Spatrick 
661e5dd7070Spatrick   FrameworkName += "Headers/";
662e5dd7070Spatrick 
663e5dd7070Spatrick   if (SearchPath) {
664e5dd7070Spatrick     SearchPath->clear();
665e5dd7070Spatrick     // Without trailing '/'.
666e5dd7070Spatrick     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
667e5dd7070Spatrick   }
668e5dd7070Spatrick 
669e5dd7070Spatrick   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
670e5dd7070Spatrick 
671e5dd7070Spatrick   auto File =
672e5dd7070Spatrick       FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
673e5dd7070Spatrick   if (!File) {
674e5dd7070Spatrick     // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
675e5dd7070Spatrick     const char *Private = "Private";
676e5dd7070Spatrick     FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
677e5dd7070Spatrick                          Private+strlen(Private));
678e5dd7070Spatrick     if (SearchPath)
679e5dd7070Spatrick       SearchPath->insert(SearchPath->begin()+OrigSize, Private,
680e5dd7070Spatrick                          Private+strlen(Private));
681e5dd7070Spatrick 
682e5dd7070Spatrick     File = FileMgr.getOptionalFileRef(FrameworkName,
683e5dd7070Spatrick                                       /*OpenFile=*/!SuggestedModule);
684e5dd7070Spatrick   }
685e5dd7070Spatrick 
686e5dd7070Spatrick   // If we found the header and are allowed to suggest a module, do so now.
687e5dd7070Spatrick   if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
688e5dd7070Spatrick     // Find the framework in which this header occurs.
689e5dd7070Spatrick     StringRef FrameworkPath = File->getFileEntry().getDir()->getName();
690e5dd7070Spatrick     bool FoundFramework = false;
691e5dd7070Spatrick     do {
692e5dd7070Spatrick       // Determine whether this directory exists.
693e5dd7070Spatrick       auto Dir = FileMgr.getDirectory(FrameworkPath);
694e5dd7070Spatrick       if (!Dir)
695e5dd7070Spatrick         break;
696e5dd7070Spatrick 
697e5dd7070Spatrick       // If this is a framework directory, then we're a subframework of this
698e5dd7070Spatrick       // framework.
699e5dd7070Spatrick       if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
700e5dd7070Spatrick         FoundFramework = true;
701e5dd7070Spatrick         break;
702e5dd7070Spatrick       }
703e5dd7070Spatrick 
704e5dd7070Spatrick       // Get the parent directory name.
705e5dd7070Spatrick       FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
706e5dd7070Spatrick       if (FrameworkPath.empty())
707e5dd7070Spatrick         break;
708e5dd7070Spatrick     } while (true);
709e5dd7070Spatrick 
710e5dd7070Spatrick     bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
711e5dd7070Spatrick     if (FoundFramework) {
712e5dd7070Spatrick       if (!HS.findUsableModuleForFrameworkHeader(
713e5dd7070Spatrick               &File->getFileEntry(), FrameworkPath, RequestingModule,
714e5dd7070Spatrick               SuggestedModule, IsSystem))
715*12c85518Srobert         return std::nullopt;
716e5dd7070Spatrick     } else {
717e5dd7070Spatrick       if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(),
718e5dd7070Spatrick                                         RequestingModule, SuggestedModule,
719e5dd7070Spatrick                                         IsSystem))
720*12c85518Srobert         return std::nullopt;
721e5dd7070Spatrick     }
722e5dd7070Spatrick   }
723e5dd7070Spatrick   if (File)
724e5dd7070Spatrick     return *File;
725*12c85518Srobert   return std::nullopt;
726*12c85518Srobert }
727*12c85518Srobert 
cacheLookupSuccess(LookupFileCacheInfo & CacheLookup,ConstSearchDirIterator HitIt,SourceLocation Loc)728*12c85518Srobert void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
729*12c85518Srobert                                       ConstSearchDirIterator HitIt,
730*12c85518Srobert                                       SourceLocation Loc) {
731*12c85518Srobert   CacheLookup.HitIt = HitIt;
732*12c85518Srobert   noteLookupUsage(HitIt.Idx, Loc);
733*12c85518Srobert }
734*12c85518Srobert 
noteLookupUsage(unsigned HitIdx,SourceLocation Loc)735*12c85518Srobert void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {
736*12c85518Srobert   SearchDirsUsage[HitIdx] = true;
737*12c85518Srobert 
738*12c85518Srobert   auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);
739*12c85518Srobert   if (UserEntryIdxIt != SearchDirToHSEntry.end())
740*12c85518Srobert     Diags.Report(Loc, diag::remark_pp_search_path_usage)
741*12c85518Srobert         << HSOpts->UserEntries[UserEntryIdxIt->second].Path;
742e5dd7070Spatrick }
743e5dd7070Spatrick 
setTarget(const TargetInfo & Target)744e5dd7070Spatrick void HeaderSearch::setTarget(const TargetInfo &Target) {
745e5dd7070Spatrick   ModMap.setTarget(Target);
746e5dd7070Spatrick }
747e5dd7070Spatrick 
748e5dd7070Spatrick //===----------------------------------------------------------------------===//
749e5dd7070Spatrick // Header File Location.
750e5dd7070Spatrick //===----------------------------------------------------------------------===//
751e5dd7070Spatrick 
752e5dd7070Spatrick /// Return true with a diagnostic if the file that MSVC would have found
753e5dd7070Spatrick /// fails to match the one that Clang would have found with MSVC header search
754e5dd7070Spatrick /// disabled.
checkMSVCHeaderSearch(DiagnosticsEngine & Diags,const FileEntry * MSFE,const FileEntry * FE,SourceLocation IncludeLoc)755e5dd7070Spatrick static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
756e5dd7070Spatrick                                   const FileEntry *MSFE, const FileEntry *FE,
757e5dd7070Spatrick                                   SourceLocation IncludeLoc) {
758e5dd7070Spatrick   if (MSFE && FE != MSFE) {
759e5dd7070Spatrick     Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
760e5dd7070Spatrick     return true;
761e5dd7070Spatrick   }
762e5dd7070Spatrick   return false;
763e5dd7070Spatrick }
764e5dd7070Spatrick 
copyString(StringRef Str,llvm::BumpPtrAllocator & Alloc)765e5dd7070Spatrick static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
766e5dd7070Spatrick   assert(!Str.empty());
767e5dd7070Spatrick   char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
768e5dd7070Spatrick   std::copy(Str.begin(), Str.end(), CopyStr);
769e5dd7070Spatrick   CopyStr[Str.size()] = '\0';
770e5dd7070Spatrick   return CopyStr;
771e5dd7070Spatrick }
772e5dd7070Spatrick 
isFrameworkStylePath(StringRef Path,bool & IsPrivateHeader,SmallVectorImpl<char> & FrameworkName,SmallVectorImpl<char> & IncludeSpelling)773e5dd7070Spatrick static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
774*12c85518Srobert                                  SmallVectorImpl<char> &FrameworkName,
775*12c85518Srobert                                  SmallVectorImpl<char> &IncludeSpelling) {
776e5dd7070Spatrick   using namespace llvm::sys;
777e5dd7070Spatrick   path::const_iterator I = path::begin(Path);
778e5dd7070Spatrick   path::const_iterator E = path::end(Path);
779e5dd7070Spatrick   IsPrivateHeader = false;
780e5dd7070Spatrick 
781e5dd7070Spatrick   // Detect different types of framework style paths:
782e5dd7070Spatrick   //
783e5dd7070Spatrick   //   ...Foo.framework/{Headers,PrivateHeaders}
784e5dd7070Spatrick   //   ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
785e5dd7070Spatrick   //   ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
786e5dd7070Spatrick   //   ...<other variations with 'Versions' like in the above path>
787e5dd7070Spatrick   //
788e5dd7070Spatrick   // and some other variations among these lines.
789e5dd7070Spatrick   int FoundComp = 0;
790e5dd7070Spatrick   while (I != E) {
791*12c85518Srobert     if (*I == "Headers") {
792e5dd7070Spatrick       ++FoundComp;
793*12c85518Srobert     } else if (*I == "PrivateHeaders") {
794e5dd7070Spatrick       ++FoundComp;
795e5dd7070Spatrick       IsPrivateHeader = true;
796*12c85518Srobert     } else if (I->endswith(".framework")) {
797*12c85518Srobert       StringRef Name = I->drop_back(10); // Drop .framework
798*12c85518Srobert       // Need to reset the strings and counter to support nested frameworks.
799*12c85518Srobert       FrameworkName.clear();
800*12c85518Srobert       FrameworkName.append(Name.begin(), Name.end());
801*12c85518Srobert       IncludeSpelling.clear();
802*12c85518Srobert       IncludeSpelling.append(Name.begin(), Name.end());
803*12c85518Srobert       FoundComp = 1;
804*12c85518Srobert     } else if (FoundComp >= 2) {
805*12c85518Srobert       IncludeSpelling.push_back('/');
806*12c85518Srobert       IncludeSpelling.append(I->begin(), I->end());
807e5dd7070Spatrick     }
808e5dd7070Spatrick     ++I;
809e5dd7070Spatrick   }
810e5dd7070Spatrick 
811e5dd7070Spatrick   return !FrameworkName.empty() && FoundComp >= 2;
812e5dd7070Spatrick }
813e5dd7070Spatrick 
814e5dd7070Spatrick static void
diagnoseFrameworkInclude(DiagnosticsEngine & Diags,SourceLocation IncludeLoc,StringRef Includer,StringRef IncludeFilename,const FileEntry * IncludeFE,bool isAngled=false,bool FoundByHeaderMap=false)815e5dd7070Spatrick diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
816e5dd7070Spatrick                          StringRef Includer, StringRef IncludeFilename,
817e5dd7070Spatrick                          const FileEntry *IncludeFE, bool isAngled = false,
818e5dd7070Spatrick                          bool FoundByHeaderMap = false) {
819e5dd7070Spatrick   bool IsIncluderPrivateHeader = false;
820e5dd7070Spatrick   SmallString<128> FromFramework, ToFramework;
821*12c85518Srobert   SmallString<128> FromIncludeSpelling, ToIncludeSpelling;
822*12c85518Srobert   if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,
823*12c85518Srobert                             FromIncludeSpelling))
824e5dd7070Spatrick     return;
825e5dd7070Spatrick   bool IsIncludeePrivateHeader = false;
826*12c85518Srobert   bool IsIncludeeInFramework =
827*12c85518Srobert       isFrameworkStylePath(IncludeFE->getName(), IsIncludeePrivateHeader,
828*12c85518Srobert                            ToFramework, ToIncludeSpelling);
829e5dd7070Spatrick 
830e5dd7070Spatrick   if (!isAngled && !FoundByHeaderMap) {
831e5dd7070Spatrick     SmallString<128> NewInclude("<");
832e5dd7070Spatrick     if (IsIncludeeInFramework) {
833*12c85518Srobert       NewInclude += ToIncludeSpelling;
834*12c85518Srobert       NewInclude += ">";
835*12c85518Srobert     } else {
836e5dd7070Spatrick       NewInclude += IncludeFilename;
837e5dd7070Spatrick       NewInclude += ">";
838*12c85518Srobert     }
839e5dd7070Spatrick     Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
840e5dd7070Spatrick         << IncludeFilename
841e5dd7070Spatrick         << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
842e5dd7070Spatrick   }
843e5dd7070Spatrick 
844e5dd7070Spatrick   // Headers in Foo.framework/Headers should not include headers
845e5dd7070Spatrick   // from Foo.framework/PrivateHeaders, since this violates public/private
846e5dd7070Spatrick   // API boundaries and can cause modular dependency cycles.
847e5dd7070Spatrick   if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
848e5dd7070Spatrick       IsIncludeePrivateHeader && FromFramework == ToFramework)
849e5dd7070Spatrick     Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
850e5dd7070Spatrick         << IncludeFilename;
851e5dd7070Spatrick }
852e5dd7070Spatrick 
853e5dd7070Spatrick /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
854e5dd7070Spatrick /// return null on failure.  isAngled indicates whether the file reference is
855e5dd7070Spatrick /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
856e5dd7070Spatrick /// non-empty, indicates where the \#including file(s) are, in case a relative
857e5dd7070Spatrick /// search is needed. Microsoft mode will pass all \#including files.
LookupFile(StringRef Filename,SourceLocation IncludeLoc,bool isAngled,ConstSearchDirIterator FromDir,ConstSearchDirIterator * CurDirArg,ArrayRef<std::pair<const FileEntry *,const DirectoryEntry * >> Includers,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool * IsMapped,bool * IsFrameworkFound,bool SkipCache,bool BuildSystemModule,bool OpenFile,bool CacheFailures)858*12c85518Srobert OptionalFileEntryRef HeaderSearch::LookupFile(
859e5dd7070Spatrick     StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
860*12c85518Srobert     ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg,
861e5dd7070Spatrick     ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
862e5dd7070Spatrick     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
863e5dd7070Spatrick     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
864e5dd7070Spatrick     bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
865*12c85518Srobert     bool BuildSystemModule, bool OpenFile, bool CacheFailures) {
866*12c85518Srobert   ConstSearchDirIterator CurDirLocal = nullptr;
867*12c85518Srobert   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
868*12c85518Srobert 
869e5dd7070Spatrick   if (IsMapped)
870e5dd7070Spatrick     *IsMapped = false;
871e5dd7070Spatrick 
872e5dd7070Spatrick   if (IsFrameworkFound)
873e5dd7070Spatrick     *IsFrameworkFound = false;
874e5dd7070Spatrick 
875e5dd7070Spatrick   if (SuggestedModule)
876e5dd7070Spatrick     *SuggestedModule = ModuleMap::KnownHeader();
877e5dd7070Spatrick 
878e5dd7070Spatrick   // If 'Filename' is absolute, check to see if it exists and no searching.
879e5dd7070Spatrick   if (llvm::sys::path::is_absolute(Filename)) {
880e5dd7070Spatrick     CurDir = nullptr;
881e5dd7070Spatrick 
882e5dd7070Spatrick     // If this was an #include_next "/absolute/file", fail.
883e5dd7070Spatrick     if (FromDir)
884*12c85518Srobert       return std::nullopt;
885e5dd7070Spatrick 
886e5dd7070Spatrick     if (SearchPath)
887e5dd7070Spatrick       SearchPath->clear();
888e5dd7070Spatrick     if (RelativePath) {
889e5dd7070Spatrick       RelativePath->clear();
890e5dd7070Spatrick       RelativePath->append(Filename.begin(), Filename.end());
891e5dd7070Spatrick     }
892e5dd7070Spatrick     // Otherwise, just return the file.
893e5dd7070Spatrick     return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
894e5dd7070Spatrick                                    /*IsSystemHeaderDir*/ false,
895*12c85518Srobert                                    RequestingModule, SuggestedModule, OpenFile,
896*12c85518Srobert                                    CacheFailures);
897e5dd7070Spatrick   }
898e5dd7070Spatrick 
899e5dd7070Spatrick   // This is the header that MSVC's header search would have found.
900e5dd7070Spatrick   ModuleMap::KnownHeader MSSuggestedModule;
901*12c85518Srobert   OptionalFileEntryRef MSFE;
902e5dd7070Spatrick 
903e5dd7070Spatrick   // Unless disabled, check to see if the file is in the #includer's
904e5dd7070Spatrick   // directory.  This cannot be based on CurDir, because each includer could be
905e5dd7070Spatrick   // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
906e5dd7070Spatrick   // include of "baz.h" should resolve to "whatever/foo/baz.h".
907e5dd7070Spatrick   // This search is not done for <> headers.
908e5dd7070Spatrick   if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
909e5dd7070Spatrick     SmallString<1024> TmpDir;
910e5dd7070Spatrick     bool First = true;
911e5dd7070Spatrick     for (const auto &IncluderAndDir : Includers) {
912e5dd7070Spatrick       const FileEntry *Includer = IncluderAndDir.first;
913e5dd7070Spatrick 
914e5dd7070Spatrick       // Concatenate the requested file onto the directory.
915e5dd7070Spatrick       // FIXME: Portability.  Filename concatenation should be in sys::Path.
916e5dd7070Spatrick       TmpDir = IncluderAndDir.second->getName();
917e5dd7070Spatrick       TmpDir.push_back('/');
918e5dd7070Spatrick       TmpDir.append(Filename.begin(), Filename.end());
919e5dd7070Spatrick 
920e5dd7070Spatrick       // FIXME: We don't cache the result of getFileInfo across the call to
921e5dd7070Spatrick       // getFileAndSuggestModule, because it's a reference to an element of
922e5dd7070Spatrick       // a container that could be reallocated across this call.
923e5dd7070Spatrick       //
924e5dd7070Spatrick       // If we have no includer, that means we're processing a #include
925e5dd7070Spatrick       // from a module build. We should treat this as a system header if we're
926e5dd7070Spatrick       // building a [system] module.
927e5dd7070Spatrick       bool IncluderIsSystemHeader =
928e5dd7070Spatrick           Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
929e5dd7070Spatrick           BuildSystemModule;
930*12c85518Srobert       if (OptionalFileEntryRef FE = getFileAndSuggestModule(
931e5dd7070Spatrick               TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
932e5dd7070Spatrick               RequestingModule, SuggestedModule)) {
933e5dd7070Spatrick         if (!Includer) {
934e5dd7070Spatrick           assert(First && "only first includer can have no file");
935e5dd7070Spatrick           return FE;
936e5dd7070Spatrick         }
937e5dd7070Spatrick 
938e5dd7070Spatrick         // Leave CurDir unset.
939e5dd7070Spatrick         // This file is a system header or C++ unfriendly if the old file is.
940e5dd7070Spatrick         //
941e5dd7070Spatrick         // Note that we only use one of FromHFI/ToHFI at once, due to potential
942e5dd7070Spatrick         // reallocation of the underlying vector potentially making the first
943e5dd7070Spatrick         // reference binding dangling.
944e5dd7070Spatrick         HeaderFileInfo &FromHFI = getFileInfo(Includer);
945e5dd7070Spatrick         unsigned DirInfo = FromHFI.DirInfo;
946e5dd7070Spatrick         bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
947e5dd7070Spatrick         StringRef Framework = FromHFI.Framework;
948e5dd7070Spatrick 
949e5dd7070Spatrick         HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry());
950e5dd7070Spatrick         ToHFI.DirInfo = DirInfo;
951e5dd7070Spatrick         ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
952e5dd7070Spatrick         ToHFI.Framework = Framework;
953e5dd7070Spatrick 
954e5dd7070Spatrick         if (SearchPath) {
955e5dd7070Spatrick           StringRef SearchPathRef(IncluderAndDir.second->getName());
956e5dd7070Spatrick           SearchPath->clear();
957e5dd7070Spatrick           SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
958e5dd7070Spatrick         }
959e5dd7070Spatrick         if (RelativePath) {
960e5dd7070Spatrick           RelativePath->clear();
961e5dd7070Spatrick           RelativePath->append(Filename.begin(), Filename.end());
962e5dd7070Spatrick         }
963e5dd7070Spatrick         if (First) {
964e5dd7070Spatrick           diagnoseFrameworkInclude(Diags, IncludeLoc,
965e5dd7070Spatrick                                    IncluderAndDir.second->getName(), Filename,
966e5dd7070Spatrick                                    &FE->getFileEntry());
967e5dd7070Spatrick           return FE;
968e5dd7070Spatrick         }
969e5dd7070Spatrick 
970e5dd7070Spatrick         // Otherwise, we found the path via MSVC header search rules.  If
971e5dd7070Spatrick         // -Wmsvc-include is enabled, we have to keep searching to see if we
972e5dd7070Spatrick         // would've found this header in -I or -isystem directories.
973e5dd7070Spatrick         if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
974e5dd7070Spatrick           return FE;
975e5dd7070Spatrick         } else {
976a9ac8606Spatrick           MSFE = FE;
977e5dd7070Spatrick           if (SuggestedModule) {
978e5dd7070Spatrick             MSSuggestedModule = *SuggestedModule;
979e5dd7070Spatrick             *SuggestedModule = ModuleMap::KnownHeader();
980e5dd7070Spatrick           }
981e5dd7070Spatrick           break;
982e5dd7070Spatrick         }
983e5dd7070Spatrick       }
984e5dd7070Spatrick       First = false;
985e5dd7070Spatrick     }
986e5dd7070Spatrick   }
987e5dd7070Spatrick 
988e5dd7070Spatrick   CurDir = nullptr;
989e5dd7070Spatrick 
990e5dd7070Spatrick   // If this is a system #include, ignore the user #include locs.
991*12c85518Srobert   ConstSearchDirIterator It =
992*12c85518Srobert       isAngled ? angled_dir_begin() : search_dir_begin();
993e5dd7070Spatrick 
994e5dd7070Spatrick   // If this is a #include_next request, start searching after the directory the
995e5dd7070Spatrick   // file was found in.
996e5dd7070Spatrick   if (FromDir)
997*12c85518Srobert     It = FromDir;
998e5dd7070Spatrick 
999e5dd7070Spatrick   // Cache all of the lookups performed by this method.  Many headers are
1000e5dd7070Spatrick   // multiply included, and the "pragma once" optimization prevents them from
1001e5dd7070Spatrick   // being relex/pp'd, but they would still have to search through a
1002e5dd7070Spatrick   // (potentially huge) series of SearchDirs to find it.
1003e5dd7070Spatrick   LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
1004e5dd7070Spatrick 
1005*12c85518Srobert   ConstSearchDirIterator NextIt = std::next(It);
1006*12c85518Srobert 
1007*12c85518Srobert   if (!SkipCache) {
1008*12c85518Srobert     if (CacheLookup.StartIt == NextIt) {
1009*12c85518Srobert       // HIT: Skip querying potentially lots of directories for this lookup.
1010*12c85518Srobert       if (CacheLookup.HitIt)
1011*12c85518Srobert         It = CacheLookup.HitIt;
1012e5dd7070Spatrick       if (CacheLookup.MappedName) {
1013e5dd7070Spatrick         Filename = CacheLookup.MappedName;
1014e5dd7070Spatrick         if (IsMapped)
1015e5dd7070Spatrick           *IsMapped = true;
1016e5dd7070Spatrick       }
1017e5dd7070Spatrick     } else {
1018*12c85518Srobert       // MISS: This is the first query, or the previous query didn't match
1019*12c85518Srobert       // our search start.  We will fill in our found location below, so prime
1020*12c85518Srobert       // the start point value.
1021*12c85518Srobert       CacheLookup.reset(/*NewStartIt=*/NextIt);
1022*12c85518Srobert 
1023*12c85518Srobert       if (It == search_dir_begin() && FirstNonHeaderMapSearchDirIdx > 0) {
1024*12c85518Srobert         // Handle cold misses of user includes in the presence of many header
1025*12c85518Srobert         // maps.  We avoid searching perhaps thousands of header maps by
1026*12c85518Srobert         // jumping directly to the correct one or jumping beyond all of them.
1027*12c85518Srobert         auto Iter = SearchDirHeaderMapIndex.find(Filename.lower());
1028*12c85518Srobert         if (Iter == SearchDirHeaderMapIndex.end())
1029*12c85518Srobert           // Not in index => Skip to first SearchDir after initial header maps
1030*12c85518Srobert           It = search_dir_nth(FirstNonHeaderMapSearchDirIdx);
1031*12c85518Srobert         else
1032*12c85518Srobert           // In index => Start with a specific header map
1033*12c85518Srobert           It = search_dir_nth(Iter->second);
1034e5dd7070Spatrick       }
1035*12c85518Srobert     }
1036*12c85518Srobert   } else
1037*12c85518Srobert     CacheLookup.reset(/*NewStartIt=*/NextIt);
1038e5dd7070Spatrick 
1039e5dd7070Spatrick   SmallString<64> MappedName;
1040e5dd7070Spatrick 
1041e5dd7070Spatrick   // Check each directory in sequence to see if it contains this file.
1042*12c85518Srobert   for (; It != search_dir_end(); ++It) {
1043e5dd7070Spatrick     bool InUserSpecifiedSystemFramework = false;
1044e5dd7070Spatrick     bool IsInHeaderMap = false;
1045e5dd7070Spatrick     bool IsFrameworkFoundInDir = false;
1046*12c85518Srobert     OptionalFileEntryRef File = It->LookupFile(
1047e5dd7070Spatrick         Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
1048e5dd7070Spatrick         SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
1049*12c85518Srobert         IsInHeaderMap, MappedName, OpenFile);
1050e5dd7070Spatrick     if (!MappedName.empty()) {
1051e5dd7070Spatrick       assert(IsInHeaderMap && "MappedName should come from a header map");
1052e5dd7070Spatrick       CacheLookup.MappedName =
1053e5dd7070Spatrick           copyString(MappedName, LookupFileCache.getAllocator());
1054e5dd7070Spatrick     }
1055e5dd7070Spatrick     if (IsMapped)
1056e5dd7070Spatrick       // A filename is mapped when a header map remapped it to a relative path
1057e5dd7070Spatrick       // used in subsequent header search or to an absolute path pointing to an
1058e5dd7070Spatrick       // existing file.
1059e5dd7070Spatrick       *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
1060e5dd7070Spatrick     if (IsFrameworkFound)
1061e5dd7070Spatrick       // Because we keep a filename remapped for subsequent search directory
1062e5dd7070Spatrick       // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
1063e5dd7070Spatrick       // just for remapping in a current search directory.
1064e5dd7070Spatrick       *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
1065e5dd7070Spatrick     if (!File)
1066e5dd7070Spatrick       continue;
1067e5dd7070Spatrick 
1068*12c85518Srobert     CurDir = It;
1069*12c85518Srobert 
1070*12c85518Srobert     const auto FE = &File->getFileEntry();
1071*12c85518Srobert     IncludeNames[FE] = Filename;
1072e5dd7070Spatrick 
1073e5dd7070Spatrick     // This file is a system header or C++ unfriendly if the dir is.
1074*12c85518Srobert     HeaderFileInfo &HFI = getFileInfo(FE);
1075e5dd7070Spatrick     HFI.DirInfo = CurDir->getDirCharacteristic();
1076e5dd7070Spatrick 
1077e5dd7070Spatrick     // If the directory characteristic is User but this framework was
1078e5dd7070Spatrick     // user-specified to be treated as a system framework, promote the
1079e5dd7070Spatrick     // characteristic.
1080e5dd7070Spatrick     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
1081e5dd7070Spatrick       HFI.DirInfo = SrcMgr::C_System;
1082e5dd7070Spatrick 
1083e5dd7070Spatrick     // If the filename matches a known system header prefix, override
1084e5dd7070Spatrick     // whether the file is a system header.
1085e5dd7070Spatrick     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
1086e5dd7070Spatrick       if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
1087e5dd7070Spatrick         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
1088e5dd7070Spatrick                                                        : SrcMgr::C_User;
1089e5dd7070Spatrick         break;
1090e5dd7070Spatrick       }
1091e5dd7070Spatrick     }
1092e5dd7070Spatrick 
1093*12c85518Srobert     // Set the `Framework` info if this file is in a header map with framework
1094*12c85518Srobert     // style include spelling or found in a framework dir. The header map case
1095*12c85518Srobert     // is possible when building frameworks which use header maps.
1096*12c85518Srobert     if (CurDir->isHeaderMap() && isAngled) {
1097e5dd7070Spatrick       size_t SlashPos = Filename.find('/');
1098*12c85518Srobert       if (SlashPos != StringRef::npos)
1099*12c85518Srobert         HFI.Framework =
1100*12c85518Srobert             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1101*12c85518Srobert       if (CurDir->isIndexHeaderMap())
1102e5dd7070Spatrick         HFI.IndexHeaderMapHeader = 1;
1103*12c85518Srobert     } else if (CurDir->isFramework()) {
1104*12c85518Srobert       size_t SlashPos = Filename.find('/');
1105*12c85518Srobert       if (SlashPos != StringRef::npos)
1106*12c85518Srobert         HFI.Framework =
1107*12c85518Srobert             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1108e5dd7070Spatrick     }
1109e5dd7070Spatrick 
1110e5dd7070Spatrick     if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1111e5dd7070Spatrick                               &File->getFileEntry(), IncludeLoc)) {
1112e5dd7070Spatrick       if (SuggestedModule)
1113e5dd7070Spatrick         *SuggestedModule = MSSuggestedModule;
1114e5dd7070Spatrick       return MSFE;
1115e5dd7070Spatrick     }
1116e5dd7070Spatrick 
1117e5dd7070Spatrick     bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
1118e5dd7070Spatrick     if (!Includers.empty())
1119e5dd7070Spatrick       diagnoseFrameworkInclude(
1120e5dd7070Spatrick           Diags, IncludeLoc, Includers.front().second->getName(), Filename,
1121e5dd7070Spatrick           &File->getFileEntry(), isAngled, FoundByHeaderMap);
1122e5dd7070Spatrick 
1123e5dd7070Spatrick     // Remember this location for the next lookup we do.
1124*12c85518Srobert     cacheLookupSuccess(CacheLookup, It, IncludeLoc);
1125e5dd7070Spatrick     return File;
1126e5dd7070Spatrick   }
1127e5dd7070Spatrick 
1128e5dd7070Spatrick   // If we are including a file with a quoted include "foo.h" from inside
1129e5dd7070Spatrick   // a header in a framework that is currently being built, and we couldn't
1130e5dd7070Spatrick   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1131e5dd7070Spatrick   // "Foo" is the name of the framework in which the including header was found.
1132e5dd7070Spatrick   if (!Includers.empty() && Includers.front().first && !isAngled &&
1133*12c85518Srobert       !Filename.contains('/')) {
1134e5dd7070Spatrick     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
1135e5dd7070Spatrick     if (IncludingHFI.IndexHeaderMapHeader) {
1136e5dd7070Spatrick       SmallString<128> ScratchFilename;
1137e5dd7070Spatrick       ScratchFilename += IncludingHFI.Framework;
1138e5dd7070Spatrick       ScratchFilename += '/';
1139e5dd7070Spatrick       ScratchFilename += Filename;
1140e5dd7070Spatrick 
1141*12c85518Srobert       OptionalFileEntryRef File = LookupFile(
1142*12c85518Srobert           ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir,
1143e5dd7070Spatrick           Includers.front(), SearchPath, RelativePath, RequestingModule,
1144e5dd7070Spatrick           SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
1145e5dd7070Spatrick 
1146e5dd7070Spatrick       if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1147e5dd7070Spatrick                                 File ? &File->getFileEntry() : nullptr,
1148e5dd7070Spatrick                                 IncludeLoc)) {
1149e5dd7070Spatrick         if (SuggestedModule)
1150e5dd7070Spatrick           *SuggestedModule = MSSuggestedModule;
1151e5dd7070Spatrick         return MSFE;
1152e5dd7070Spatrick       }
1153e5dd7070Spatrick 
1154*12c85518Srobert       cacheLookupSuccess(LookupFileCache[Filename],
1155*12c85518Srobert                          LookupFileCache[ScratchFilename].HitIt, IncludeLoc);
1156e5dd7070Spatrick       // FIXME: SuggestedModule.
1157e5dd7070Spatrick       return File;
1158e5dd7070Spatrick     }
1159e5dd7070Spatrick   }
1160e5dd7070Spatrick 
1161e5dd7070Spatrick   if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1162e5dd7070Spatrick                             nullptr, IncludeLoc)) {
1163e5dd7070Spatrick     if (SuggestedModule)
1164e5dd7070Spatrick       *SuggestedModule = MSSuggestedModule;
1165e5dd7070Spatrick     return MSFE;
1166e5dd7070Spatrick   }
1167e5dd7070Spatrick 
1168e5dd7070Spatrick   // Otherwise, didn't find it. Remember we didn't find this.
1169*12c85518Srobert   CacheLookup.HitIt = search_dir_end();
1170*12c85518Srobert   return std::nullopt;
1171e5dd7070Spatrick }
1172e5dd7070Spatrick 
1173e5dd7070Spatrick /// LookupSubframeworkHeader - Look up a subframework for the specified
1174e5dd7070Spatrick /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1175e5dd7070Spatrick /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1176e5dd7070Spatrick /// is a subframework within Carbon.framework.  If so, return the FileEntry
1177e5dd7070Spatrick /// for the designated file, otherwise return null.
LookupSubframeworkHeader(StringRef Filename,const FileEntry * ContextFileEnt,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule)1178*12c85518Srobert OptionalFileEntryRef HeaderSearch::LookupSubframeworkHeader(
1179e5dd7070Spatrick     StringRef Filename, const FileEntry *ContextFileEnt,
1180e5dd7070Spatrick     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1181e5dd7070Spatrick     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
1182e5dd7070Spatrick   assert(ContextFileEnt && "No context file?");
1183e5dd7070Spatrick 
1184e5dd7070Spatrick   // Framework names must have a '/' in the filename.  Find it.
1185e5dd7070Spatrick   // FIXME: Should we permit '\' on Windows?
1186e5dd7070Spatrick   size_t SlashPos = Filename.find('/');
1187e5dd7070Spatrick   if (SlashPos == StringRef::npos)
1188*12c85518Srobert     return std::nullopt;
1189e5dd7070Spatrick 
1190e5dd7070Spatrick   // Look up the base framework name of the ContextFileEnt.
1191e5dd7070Spatrick   StringRef ContextName = ContextFileEnt->getName();
1192e5dd7070Spatrick 
1193e5dd7070Spatrick   // If the context info wasn't a framework, couldn't be a subframework.
1194e5dd7070Spatrick   const unsigned DotFrameworkLen = 10;
1195e5dd7070Spatrick   auto FrameworkPos = ContextName.find(".framework");
1196e5dd7070Spatrick   if (FrameworkPos == StringRef::npos ||
1197e5dd7070Spatrick       (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1198e5dd7070Spatrick        ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1199*12c85518Srobert     return std::nullopt;
1200e5dd7070Spatrick 
1201e5dd7070Spatrick   SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1202e5dd7070Spatrick                                                           FrameworkPos +
1203e5dd7070Spatrick                                                           DotFrameworkLen + 1);
1204e5dd7070Spatrick 
1205e5dd7070Spatrick   // Append Frameworks/HIToolbox.framework/
1206e5dd7070Spatrick   FrameworkName += "Frameworks/";
1207e5dd7070Spatrick   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1208e5dd7070Spatrick   FrameworkName += ".framework/";
1209e5dd7070Spatrick 
1210e5dd7070Spatrick   auto &CacheLookup =
1211e5dd7070Spatrick       *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1212e5dd7070Spatrick                                           FrameworkCacheEntry())).first;
1213e5dd7070Spatrick 
1214e5dd7070Spatrick   // Some other location?
1215e5dd7070Spatrick   if (CacheLookup.second.Directory &&
1216e5dd7070Spatrick       CacheLookup.first().size() == FrameworkName.size() &&
1217e5dd7070Spatrick       memcmp(CacheLookup.first().data(), &FrameworkName[0],
1218e5dd7070Spatrick              CacheLookup.first().size()) != 0)
1219*12c85518Srobert     return std::nullopt;
1220e5dd7070Spatrick 
1221e5dd7070Spatrick   // Cache subframework.
1222e5dd7070Spatrick   if (!CacheLookup.second.Directory) {
1223e5dd7070Spatrick     ++NumSubFrameworkLookups;
1224e5dd7070Spatrick 
1225e5dd7070Spatrick     // If the framework dir doesn't exist, we fail.
1226*12c85518Srobert     auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
1227e5dd7070Spatrick     if (!Dir)
1228*12c85518Srobert       return std::nullopt;
1229e5dd7070Spatrick 
1230e5dd7070Spatrick     // Otherwise, if it does, remember that this is the right direntry for this
1231e5dd7070Spatrick     // framework.
1232*12c85518Srobert     CacheLookup.second.Directory = Dir;
1233e5dd7070Spatrick   }
1234e5dd7070Spatrick 
1235e5dd7070Spatrick 
1236e5dd7070Spatrick   if (RelativePath) {
1237e5dd7070Spatrick     RelativePath->clear();
1238e5dd7070Spatrick     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1239e5dd7070Spatrick   }
1240e5dd7070Spatrick 
1241e5dd7070Spatrick   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1242e5dd7070Spatrick   SmallString<1024> HeadersFilename(FrameworkName);
1243e5dd7070Spatrick   HeadersFilename += "Headers/";
1244e5dd7070Spatrick   if (SearchPath) {
1245e5dd7070Spatrick     SearchPath->clear();
1246e5dd7070Spatrick     // Without trailing '/'.
1247e5dd7070Spatrick     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1248e5dd7070Spatrick   }
1249e5dd7070Spatrick 
1250e5dd7070Spatrick   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1251e5dd7070Spatrick   auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1252e5dd7070Spatrick   if (!File) {
1253e5dd7070Spatrick     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1254e5dd7070Spatrick     HeadersFilename = FrameworkName;
1255e5dd7070Spatrick     HeadersFilename += "PrivateHeaders/";
1256e5dd7070Spatrick     if (SearchPath) {
1257e5dd7070Spatrick       SearchPath->clear();
1258e5dd7070Spatrick       // Without trailing '/'.
1259e5dd7070Spatrick       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1260e5dd7070Spatrick     }
1261e5dd7070Spatrick 
1262e5dd7070Spatrick     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1263e5dd7070Spatrick     File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1264e5dd7070Spatrick 
1265e5dd7070Spatrick     if (!File)
1266*12c85518Srobert       return std::nullopt;
1267e5dd7070Spatrick   }
1268e5dd7070Spatrick 
1269e5dd7070Spatrick   // This file is a system header or C++ unfriendly if the old file is.
1270e5dd7070Spatrick   //
1271e5dd7070Spatrick   // Note that the temporary 'DirInfo' is required here, as either call to
1272e5dd7070Spatrick   // getFileInfo could resize the vector and we don't want to rely on order
1273e5dd7070Spatrick   // of evaluation.
1274e5dd7070Spatrick   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1275e5dd7070Spatrick   getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
1276e5dd7070Spatrick 
1277e5dd7070Spatrick   FrameworkName.pop_back(); // remove the trailing '/'
1278e5dd7070Spatrick   if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName,
1279e5dd7070Spatrick                                           RequestingModule, SuggestedModule,
1280e5dd7070Spatrick                                           /*IsSystem*/ false))
1281*12c85518Srobert     return std::nullopt;
1282e5dd7070Spatrick 
1283e5dd7070Spatrick   return *File;
1284e5dd7070Spatrick }
1285e5dd7070Spatrick 
1286e5dd7070Spatrick //===----------------------------------------------------------------------===//
1287e5dd7070Spatrick // File Info Management.
1288e5dd7070Spatrick //===----------------------------------------------------------------------===//
1289e5dd7070Spatrick 
1290e5dd7070Spatrick /// Merge the header file info provided by \p OtherHFI into the current
1291e5dd7070Spatrick /// header file info (\p HFI)
mergeHeaderFileInfo(HeaderFileInfo & HFI,const HeaderFileInfo & OtherHFI)1292e5dd7070Spatrick static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1293e5dd7070Spatrick                                 const HeaderFileInfo &OtherHFI) {
1294e5dd7070Spatrick   assert(OtherHFI.External && "expected to merge external HFI");
1295e5dd7070Spatrick 
1296e5dd7070Spatrick   HFI.isImport |= OtherHFI.isImport;
1297e5dd7070Spatrick   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1298e5dd7070Spatrick   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1299e5dd7070Spatrick 
1300e5dd7070Spatrick   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1301e5dd7070Spatrick     HFI.ControllingMacro = OtherHFI.ControllingMacro;
1302e5dd7070Spatrick     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1303e5dd7070Spatrick   }
1304e5dd7070Spatrick 
1305e5dd7070Spatrick   HFI.DirInfo = OtherHFI.DirInfo;
1306e5dd7070Spatrick   HFI.External = (!HFI.IsValid || HFI.External);
1307e5dd7070Spatrick   HFI.IsValid = true;
1308e5dd7070Spatrick   HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1309e5dd7070Spatrick 
1310e5dd7070Spatrick   if (HFI.Framework.empty())
1311e5dd7070Spatrick     HFI.Framework = OtherHFI.Framework;
1312e5dd7070Spatrick }
1313e5dd7070Spatrick 
1314e5dd7070Spatrick /// getFileInfo - Return the HeaderFileInfo structure for the specified
1315e5dd7070Spatrick /// FileEntry.
getFileInfo(const FileEntry * FE)1316e5dd7070Spatrick HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1317e5dd7070Spatrick   if (FE->getUID() >= FileInfo.size())
1318e5dd7070Spatrick     FileInfo.resize(FE->getUID() + 1);
1319e5dd7070Spatrick 
1320e5dd7070Spatrick   HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1321e5dd7070Spatrick   // FIXME: Use a generation count to check whether this is really up to date.
1322e5dd7070Spatrick   if (ExternalSource && !HFI->Resolved) {
1323e5dd7070Spatrick     auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1324a9ac8606Spatrick     if (ExternalHFI.IsValid) {
1325a9ac8606Spatrick       HFI->Resolved = true;
1326e5dd7070Spatrick       if (ExternalHFI.External)
1327e5dd7070Spatrick         mergeHeaderFileInfo(*HFI, ExternalHFI);
1328e5dd7070Spatrick     }
1329a9ac8606Spatrick   }
1330e5dd7070Spatrick 
1331e5dd7070Spatrick   HFI->IsValid = true;
1332e5dd7070Spatrick   // We have local information about this header file, so it's no longer
1333e5dd7070Spatrick   // strictly external.
1334e5dd7070Spatrick   HFI->External = false;
1335e5dd7070Spatrick   return *HFI;
1336e5dd7070Spatrick }
1337e5dd7070Spatrick 
1338e5dd7070Spatrick const HeaderFileInfo *
getExistingFileInfo(const FileEntry * FE,bool WantExternal) const1339e5dd7070Spatrick HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1340e5dd7070Spatrick                                   bool WantExternal) const {
1341e5dd7070Spatrick   // If we have an external source, ensure we have the latest information.
1342e5dd7070Spatrick   // FIXME: Use a generation count to check whether this is really up to date.
1343e5dd7070Spatrick   HeaderFileInfo *HFI;
1344e5dd7070Spatrick   if (ExternalSource) {
1345e5dd7070Spatrick     if (FE->getUID() >= FileInfo.size()) {
1346e5dd7070Spatrick       if (!WantExternal)
1347e5dd7070Spatrick         return nullptr;
1348e5dd7070Spatrick       FileInfo.resize(FE->getUID() + 1);
1349e5dd7070Spatrick     }
1350e5dd7070Spatrick 
1351e5dd7070Spatrick     HFI = &FileInfo[FE->getUID()];
1352e5dd7070Spatrick     if (!WantExternal && (!HFI->IsValid || HFI->External))
1353e5dd7070Spatrick       return nullptr;
1354e5dd7070Spatrick     if (!HFI->Resolved) {
1355e5dd7070Spatrick       auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1356a9ac8606Spatrick       if (ExternalHFI.IsValid) {
1357a9ac8606Spatrick         HFI->Resolved = true;
1358e5dd7070Spatrick         if (ExternalHFI.External)
1359e5dd7070Spatrick           mergeHeaderFileInfo(*HFI, ExternalHFI);
1360e5dd7070Spatrick       }
1361a9ac8606Spatrick     }
1362e5dd7070Spatrick   } else if (FE->getUID() >= FileInfo.size()) {
1363e5dd7070Spatrick     return nullptr;
1364e5dd7070Spatrick   } else {
1365e5dd7070Spatrick     HFI = &FileInfo[FE->getUID()];
1366e5dd7070Spatrick   }
1367e5dd7070Spatrick 
1368e5dd7070Spatrick   if (!HFI->IsValid || (HFI->External && !WantExternal))
1369e5dd7070Spatrick     return nullptr;
1370e5dd7070Spatrick 
1371e5dd7070Spatrick   return HFI;
1372e5dd7070Spatrick }
1373e5dd7070Spatrick 
isFileMultipleIncludeGuarded(const FileEntry * File)1374e5dd7070Spatrick bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1375ec727ea7Spatrick   // Check if we've entered this file and found an include guard or #pragma
1376ec727ea7Spatrick   // once. Note that we dor't check for #import, because that's not a property
1377ec727ea7Spatrick   // of the file itself.
1378e5dd7070Spatrick   if (auto *HFI = getExistingFileInfo(File))
1379ec727ea7Spatrick     return HFI->isPragmaOnce || HFI->ControllingMacro ||
1380e5dd7070Spatrick            HFI->ControllingMacroID;
1381e5dd7070Spatrick   return false;
1382e5dd7070Spatrick }
1383e5dd7070Spatrick 
MarkFileModuleHeader(const FileEntry * FE,ModuleMap::ModuleHeaderRole Role,bool isCompilingModuleHeader)1384e5dd7070Spatrick void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1385e5dd7070Spatrick                                         ModuleMap::ModuleHeaderRole Role,
1386e5dd7070Spatrick                                         bool isCompilingModuleHeader) {
1387*12c85518Srobert   bool isModularHeader = ModuleMap::isModular(Role);
1388e5dd7070Spatrick 
1389e5dd7070Spatrick   // Don't mark the file info as non-external if there's nothing to change.
1390e5dd7070Spatrick   if (!isCompilingModuleHeader) {
1391e5dd7070Spatrick     if (!isModularHeader)
1392e5dd7070Spatrick       return;
1393e5dd7070Spatrick     auto *HFI = getExistingFileInfo(FE);
1394e5dd7070Spatrick     if (HFI && HFI->isModuleHeader)
1395e5dd7070Spatrick       return;
1396e5dd7070Spatrick   }
1397e5dd7070Spatrick 
1398e5dd7070Spatrick   auto &HFI = getFileInfo(FE);
1399e5dd7070Spatrick   HFI.isModuleHeader |= isModularHeader;
1400e5dd7070Spatrick   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1401e5dd7070Spatrick }
1402e5dd7070Spatrick 
ShouldEnterIncludeFile(Preprocessor & PP,const FileEntry * File,bool isImport,bool ModulesEnabled,Module * M,bool & IsFirstIncludeOfFile)1403e5dd7070Spatrick bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1404e5dd7070Spatrick                                           const FileEntry *File, bool isImport,
1405*12c85518Srobert                                           bool ModulesEnabled, Module *M,
1406*12c85518Srobert                                           bool &IsFirstIncludeOfFile) {
1407e5dd7070Spatrick   ++NumIncluded; // Count # of attempted #includes.
1408e5dd7070Spatrick 
1409*12c85518Srobert   IsFirstIncludeOfFile = false;
1410*12c85518Srobert 
1411e5dd7070Spatrick   // Get information about this file.
1412e5dd7070Spatrick   HeaderFileInfo &FileInfo = getFileInfo(File);
1413e5dd7070Spatrick 
1414e5dd7070Spatrick   // FIXME: this is a workaround for the lack of proper modules-aware support
1415e5dd7070Spatrick   // for #import / #pragma once
1416e5dd7070Spatrick   auto TryEnterImported = [&]() -> bool {
1417e5dd7070Spatrick     if (!ModulesEnabled)
1418e5dd7070Spatrick       return false;
1419e5dd7070Spatrick     // Ensure FileInfo bits are up to date.
1420e5dd7070Spatrick     ModMap.resolveHeaderDirectives(File);
1421e5dd7070Spatrick     // Modules with builtins are special; multiple modules use builtins as
1422e5dd7070Spatrick     // modular headers, example:
1423e5dd7070Spatrick     //
1424e5dd7070Spatrick     //    module stddef { header "stddef.h" export * }
1425e5dd7070Spatrick     //
1426e5dd7070Spatrick     // After module map parsing, this expands to:
1427e5dd7070Spatrick     //
1428e5dd7070Spatrick     //    module stddef {
1429e5dd7070Spatrick     //      header "/path_to_builtin_dirs/stddef.h"
1430e5dd7070Spatrick     //      textual "stddef.h"
1431e5dd7070Spatrick     //    }
1432e5dd7070Spatrick     //
1433e5dd7070Spatrick     // It's common that libc++ and system modules will both define such
1434e5dd7070Spatrick     // submodules. Make sure cached results for a builtin header won't
1435ec727ea7Spatrick     // prevent other builtin modules from potentially entering the builtin
1436ec727ea7Spatrick     // header. Note that builtins are header guarded and the decision to
1437ec727ea7Spatrick     // actually enter them is postponed to the controlling macros logic below.
1438e5dd7070Spatrick     bool TryEnterHdr = false;
1439e5dd7070Spatrick     if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1440ec727ea7Spatrick       TryEnterHdr = ModMap.isBuiltinHeader(File);
1441e5dd7070Spatrick 
1442e5dd7070Spatrick     // Textual headers can be #imported from different modules. Since ObjC
1443e5dd7070Spatrick     // headers find in the wild might rely only on #import and do not contain
1444e5dd7070Spatrick     // controlling macros, be conservative and only try to enter textual headers
1445e5dd7070Spatrick     // if such macro is present.
1446e5dd7070Spatrick     if (!FileInfo.isModuleHeader &&
1447e5dd7070Spatrick         FileInfo.getControllingMacro(ExternalLookup))
1448e5dd7070Spatrick       TryEnterHdr = true;
1449e5dd7070Spatrick     return TryEnterHdr;
1450e5dd7070Spatrick   };
1451e5dd7070Spatrick 
1452e5dd7070Spatrick   // If this is a #import directive, check that we have not already imported
1453e5dd7070Spatrick   // this header.
1454e5dd7070Spatrick   if (isImport) {
1455e5dd7070Spatrick     // If this has already been imported, don't import it again.
1456e5dd7070Spatrick     FileInfo.isImport = true;
1457e5dd7070Spatrick 
1458e5dd7070Spatrick     // Has this already been #import'ed or #include'd?
1459*12c85518Srobert     if (PP.alreadyIncluded(File) && !TryEnterImported())
1460e5dd7070Spatrick       return false;
1461e5dd7070Spatrick   } else {
1462e5dd7070Spatrick     // Otherwise, if this is a #include of a file that was previously #import'd
1463e5dd7070Spatrick     // or if this is the second #include of a #pragma once file, ignore it.
1464*12c85518Srobert     if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported())
1465e5dd7070Spatrick       return false;
1466e5dd7070Spatrick   }
1467e5dd7070Spatrick 
1468e5dd7070Spatrick   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
1469e5dd7070Spatrick   // if the macro that guards it is defined, we know the #include has no effect.
1470e5dd7070Spatrick   if (const IdentifierInfo *ControllingMacro
1471e5dd7070Spatrick       = FileInfo.getControllingMacro(ExternalLookup)) {
1472e5dd7070Spatrick     // If the header corresponds to a module, check whether the macro is already
1473e5dd7070Spatrick     // defined in that module rather than checking in the current set of visible
1474e5dd7070Spatrick     // modules.
1475e5dd7070Spatrick     if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1476e5dd7070Spatrick           : PP.isMacroDefined(ControllingMacro)) {
1477e5dd7070Spatrick       ++NumMultiIncludeFileOptzn;
1478e5dd7070Spatrick       return false;
1479e5dd7070Spatrick     }
1480e5dd7070Spatrick   }
1481e5dd7070Spatrick 
1482*12c85518Srobert   IsFirstIncludeOfFile = PP.markIncluded(File);
1483e5dd7070Spatrick 
1484e5dd7070Spatrick   return true;
1485e5dd7070Spatrick }
1486e5dd7070Spatrick 
getTotalMemory() const1487e5dd7070Spatrick size_t HeaderSearch::getTotalMemory() const {
1488e5dd7070Spatrick   return SearchDirs.capacity()
1489e5dd7070Spatrick     + llvm::capacity_in_bytes(FileInfo)
1490e5dd7070Spatrick     + llvm::capacity_in_bytes(HeaderMaps)
1491e5dd7070Spatrick     + LookupFileCache.getAllocator().getTotalMemory()
1492e5dd7070Spatrick     + FrameworkMap.getAllocator().getTotalMemory();
1493e5dd7070Spatrick }
1494e5dd7070Spatrick 
searchDirIdx(const DirectoryLookup & DL) const1495*12c85518Srobert unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const {
1496*12c85518Srobert   return &DL - &*SearchDirs.begin();
1497*12c85518Srobert }
1498*12c85518Srobert 
getUniqueFrameworkName(StringRef Framework)1499e5dd7070Spatrick StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1500e5dd7070Spatrick   return FrameworkNames.insert(Framework).first->first();
1501e5dd7070Spatrick }
1502e5dd7070Spatrick 
getIncludeNameForHeader(const FileEntry * File) const1503*12c85518Srobert StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {
1504*12c85518Srobert   auto It = IncludeNames.find(File);
1505*12c85518Srobert   if (It == IncludeNames.end())
1506*12c85518Srobert     return {};
1507*12c85518Srobert   return It->second;
1508*12c85518Srobert }
1509*12c85518Srobert 
hasModuleMap(StringRef FileName,const DirectoryEntry * Root,bool IsSystem)1510e5dd7070Spatrick bool HeaderSearch::hasModuleMap(StringRef FileName,
1511e5dd7070Spatrick                                 const DirectoryEntry *Root,
1512e5dd7070Spatrick                                 bool IsSystem) {
1513e5dd7070Spatrick   if (!HSOpts->ImplicitModuleMaps)
1514e5dd7070Spatrick     return false;
1515e5dd7070Spatrick 
1516e5dd7070Spatrick   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1517e5dd7070Spatrick 
1518e5dd7070Spatrick   StringRef DirName = FileName;
1519e5dd7070Spatrick   do {
1520e5dd7070Spatrick     // Get the parent directory name.
1521e5dd7070Spatrick     DirName = llvm::sys::path::parent_path(DirName);
1522e5dd7070Spatrick     if (DirName.empty())
1523e5dd7070Spatrick       return false;
1524e5dd7070Spatrick 
1525e5dd7070Spatrick     // Determine whether this directory exists.
1526*12c85518Srobert     auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
1527e5dd7070Spatrick     if (!Dir)
1528e5dd7070Spatrick       return false;
1529e5dd7070Spatrick 
1530e5dd7070Spatrick     // Try to load the module map file in this directory.
1531e5dd7070Spatrick     switch (loadModuleMapFile(*Dir, IsSystem,
1532*12c85518Srobert                               llvm::sys::path::extension(Dir->getName()) ==
1533e5dd7070Spatrick                                   ".framework")) {
1534e5dd7070Spatrick     case LMM_NewlyLoaded:
1535e5dd7070Spatrick     case LMM_AlreadyLoaded:
1536e5dd7070Spatrick       // Success. All of the directories we stepped through inherit this module
1537e5dd7070Spatrick       // map file.
1538e5dd7070Spatrick       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1539e5dd7070Spatrick         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1540e5dd7070Spatrick       return true;
1541e5dd7070Spatrick 
1542e5dd7070Spatrick     case LMM_NoDirectory:
1543e5dd7070Spatrick     case LMM_InvalidModuleMap:
1544e5dd7070Spatrick       break;
1545e5dd7070Spatrick     }
1546e5dd7070Spatrick 
1547e5dd7070Spatrick     // If we hit the top of our search, we're done.
1548e5dd7070Spatrick     if (*Dir == Root)
1549e5dd7070Spatrick       return false;
1550e5dd7070Spatrick 
1551e5dd7070Spatrick     // Keep track of all of the directories we checked, so we can mark them as
1552e5dd7070Spatrick     // having module maps if we eventually do find a module map.
1553e5dd7070Spatrick     FixUpDirectories.push_back(*Dir);
1554e5dd7070Spatrick   } while (true);
1555e5dd7070Spatrick }
1556e5dd7070Spatrick 
1557e5dd7070Spatrick ModuleMap::KnownHeader
findModuleForHeader(const FileEntry * File,bool AllowTextual,bool AllowExcluded) const1558*12c85518Srobert HeaderSearch::findModuleForHeader(const FileEntry *File, bool AllowTextual,
1559*12c85518Srobert                                   bool AllowExcluded) const {
1560e5dd7070Spatrick   if (ExternalSource) {
1561e5dd7070Spatrick     // Make sure the external source has handled header info about this file,
1562e5dd7070Spatrick     // which includes whether the file is part of a module.
1563e5dd7070Spatrick     (void)getExistingFileInfo(File);
1564e5dd7070Spatrick   }
1565*12c85518Srobert   return ModMap.findModuleForHeader(File, AllowTextual, AllowExcluded);
1566e5dd7070Spatrick }
1567e5dd7070Spatrick 
1568ec727ea7Spatrick ArrayRef<ModuleMap::KnownHeader>
findAllModulesForHeader(const FileEntry * File) const1569ec727ea7Spatrick HeaderSearch::findAllModulesForHeader(const FileEntry *File) const {
1570ec727ea7Spatrick   if (ExternalSource) {
1571ec727ea7Spatrick     // Make sure the external source has handled header info about this file,
1572ec727ea7Spatrick     // which includes whether the file is part of a module.
1573ec727ea7Spatrick     (void)getExistingFileInfo(File);
1574ec727ea7Spatrick   }
1575ec727ea7Spatrick   return ModMap.findAllModulesForHeader(File);
1576ec727ea7Spatrick }
1577ec727ea7Spatrick 
suggestModule(HeaderSearch & HS,const FileEntry * File,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule)1578e5dd7070Spatrick static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1579e5dd7070Spatrick                           Module *RequestingModule,
1580e5dd7070Spatrick                           ModuleMap::KnownHeader *SuggestedModule) {
1581e5dd7070Spatrick   ModuleMap::KnownHeader Module =
1582e5dd7070Spatrick       HS.findModuleForHeader(File, /*AllowTextual*/true);
1583e5dd7070Spatrick 
1584e5dd7070Spatrick   // If this module specifies [no_undeclared_includes], we cannot find any
1585e5dd7070Spatrick   // file that's in a non-dependency module.
1586e5dd7070Spatrick   if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1587e5dd7070Spatrick     HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);
1588e5dd7070Spatrick     if (!RequestingModule->directlyUses(Module.getModule())) {
1589ec727ea7Spatrick       // Builtin headers are a special case. Multiple modules can use the same
1590ec727ea7Spatrick       // builtin as a modular header (see also comment in
1591ec727ea7Spatrick       // ShouldEnterIncludeFile()), so the builtin header may have been
1592ec727ea7Spatrick       // "claimed" by an unrelated module. This shouldn't prevent us from
1593ec727ea7Spatrick       // including the builtin header textually in this module.
1594ec727ea7Spatrick       if (HS.getModuleMap().isBuiltinHeader(File)) {
1595ec727ea7Spatrick         if (SuggestedModule)
1596ec727ea7Spatrick           *SuggestedModule = ModuleMap::KnownHeader();
1597ec727ea7Spatrick         return true;
1598ec727ea7Spatrick       }
1599*12c85518Srobert       // TODO: Add this module (or just its module map file) into something like
1600*12c85518Srobert       // `RequestingModule->AffectingClangModules`.
1601e5dd7070Spatrick       return false;
1602e5dd7070Spatrick     }
1603e5dd7070Spatrick   }
1604e5dd7070Spatrick 
1605ec727ea7Spatrick   if (SuggestedModule)
1606ec727ea7Spatrick     *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1607ec727ea7Spatrick                            ? ModuleMap::KnownHeader()
1608ec727ea7Spatrick                            : Module;
1609ec727ea7Spatrick 
1610e5dd7070Spatrick   return true;
1611e5dd7070Spatrick }
1612e5dd7070Spatrick 
findUsableModuleForHeader(const FileEntry * File,const DirectoryEntry * Root,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool IsSystemHeaderDir)1613e5dd7070Spatrick bool HeaderSearch::findUsableModuleForHeader(
1614e5dd7070Spatrick     const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1615e5dd7070Spatrick     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1616e5dd7070Spatrick   if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1617e5dd7070Spatrick     // If there is a module that corresponds to this header, suggest it.
1618e5dd7070Spatrick     hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1619e5dd7070Spatrick     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1620e5dd7070Spatrick   }
1621e5dd7070Spatrick   return true;
1622e5dd7070Spatrick }
1623e5dd7070Spatrick 
findUsableModuleForFrameworkHeader(const FileEntry * File,StringRef FrameworkName,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool IsSystemFramework)1624e5dd7070Spatrick bool HeaderSearch::findUsableModuleForFrameworkHeader(
1625e5dd7070Spatrick     const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1626e5dd7070Spatrick     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1627e5dd7070Spatrick   // If we're supposed to suggest a module, look for one now.
1628e5dd7070Spatrick   if (needModuleLookup(RequestingModule, SuggestedModule)) {
1629e5dd7070Spatrick     // Find the top-level framework based on this framework.
1630e5dd7070Spatrick     SmallVector<std::string, 4> SubmodulePath;
1631*12c85518Srobert     OptionalDirectoryEntryRef TopFrameworkDir =
1632*12c85518Srobert         ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1633*12c85518Srobert     assert(TopFrameworkDir && "Could not find the top-most framework dir");
1634e5dd7070Spatrick 
1635e5dd7070Spatrick     // Determine the name of the top-level framework.
1636e5dd7070Spatrick     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1637e5dd7070Spatrick 
1638e5dd7070Spatrick     // Load this framework module. If that succeeds, find the suggested module
1639e5dd7070Spatrick     // for this header, if any.
1640*12c85518Srobert     loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);
1641e5dd7070Spatrick 
1642e5dd7070Spatrick     // FIXME: This can find a module not part of ModuleName, which is
1643e5dd7070Spatrick     // important so that we're consistent about whether this header
1644e5dd7070Spatrick     // corresponds to a module. Possibly we should lock down framework modules
1645e5dd7070Spatrick     // so that this is not possible.
1646e5dd7070Spatrick     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1647e5dd7070Spatrick   }
1648e5dd7070Spatrick   return true;
1649e5dd7070Spatrick }
1650e5dd7070Spatrick 
getPrivateModuleMap(const FileEntry * File,FileManager & FileMgr)1651e5dd7070Spatrick static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1652e5dd7070Spatrick                                             FileManager &FileMgr) {
1653e5dd7070Spatrick   StringRef Filename = llvm::sys::path::filename(File->getName());
1654e5dd7070Spatrick   SmallString<128>  PrivateFilename(File->getDir()->getName());
1655e5dd7070Spatrick   if (Filename == "module.map")
1656e5dd7070Spatrick     llvm::sys::path::append(PrivateFilename, "module_private.map");
1657e5dd7070Spatrick   else if (Filename == "module.modulemap")
1658e5dd7070Spatrick     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1659e5dd7070Spatrick   else
1660e5dd7070Spatrick     return nullptr;
1661e5dd7070Spatrick   if (auto File = FileMgr.getFile(PrivateFilename))
1662e5dd7070Spatrick     return *File;
1663e5dd7070Spatrick   return nullptr;
1664e5dd7070Spatrick }
1665e5dd7070Spatrick 
loadModuleMapFile(const FileEntry * File,bool IsSystem,FileID ID,unsigned * Offset,StringRef OriginalModuleMapFile)1666e5dd7070Spatrick bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
1667e5dd7070Spatrick                                      FileID ID, unsigned *Offset,
1668e5dd7070Spatrick                                      StringRef OriginalModuleMapFile) {
1669e5dd7070Spatrick   // Find the directory for the module. For frameworks, that may require going
1670e5dd7070Spatrick   // up from the 'Modules' directory.
1671*12c85518Srobert   OptionalDirectoryEntryRef Dir;
1672e5dd7070Spatrick   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1673*12c85518Srobert     Dir = FileMgr.getOptionalDirectoryRef(".");
1674e5dd7070Spatrick   } else {
1675e5dd7070Spatrick     if (!OriginalModuleMapFile.empty()) {
1676e5dd7070Spatrick       // We're building a preprocessed module map. Find or invent the directory
1677e5dd7070Spatrick       // that it originally occupied.
1678*12c85518Srobert       Dir = FileMgr.getOptionalDirectoryRef(
1679e5dd7070Spatrick           llvm::sys::path::parent_path(OriginalModuleMapFile));
1680*12c85518Srobert       if (!Dir) {
1681*12c85518Srobert         auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0);
1682*12c85518Srobert         Dir = FakeFile.getDir();
1683e5dd7070Spatrick       }
1684e5dd7070Spatrick     } else {
1685*12c85518Srobert       // TODO: Replace with `Dir = File.getDir()` when `File` is switched to
1686*12c85518Srobert       // `FileEntryRef`.
1687*12c85518Srobert       Dir = FileMgr.getOptionalDirectoryRef(File->getDir()->getName());
1688e5dd7070Spatrick     }
1689e5dd7070Spatrick 
1690*12c85518Srobert     assert(Dir && "parent must exist");
1691e5dd7070Spatrick     StringRef DirName(Dir->getName());
1692e5dd7070Spatrick     if (llvm::sys::path::filename(DirName) == "Modules") {
1693e5dd7070Spatrick       DirName = llvm::sys::path::parent_path(DirName);
1694e5dd7070Spatrick       if (DirName.endswith(".framework"))
1695*12c85518Srobert         if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName))
1696*12c85518Srobert           Dir = *MaybeDir;
1697e5dd7070Spatrick       // FIXME: This assert can fail if there's a race between the above check
1698e5dd7070Spatrick       // and the removal of the directory.
1699e5dd7070Spatrick       assert(Dir && "parent must exist");
1700e5dd7070Spatrick     }
1701e5dd7070Spatrick   }
1702e5dd7070Spatrick 
1703*12c85518Srobert   assert(Dir && "module map home directory must exist");
1704*12c85518Srobert   switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) {
1705e5dd7070Spatrick   case LMM_AlreadyLoaded:
1706e5dd7070Spatrick   case LMM_NewlyLoaded:
1707e5dd7070Spatrick     return false;
1708e5dd7070Spatrick   case LMM_NoDirectory:
1709e5dd7070Spatrick   case LMM_InvalidModuleMap:
1710e5dd7070Spatrick     return true;
1711e5dd7070Spatrick   }
1712e5dd7070Spatrick   llvm_unreachable("Unknown load module map result");
1713e5dd7070Spatrick }
1714e5dd7070Spatrick 
1715e5dd7070Spatrick HeaderSearch::LoadModuleMapResult
loadModuleMapFileImpl(const FileEntry * File,bool IsSystem,DirectoryEntryRef Dir,FileID ID,unsigned * Offset)1716e5dd7070Spatrick HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1717*12c85518Srobert                                     DirectoryEntryRef Dir, FileID ID,
1718e5dd7070Spatrick                                     unsigned *Offset) {
1719e5dd7070Spatrick   assert(File && "expected FileEntry");
1720e5dd7070Spatrick 
1721e5dd7070Spatrick   // Check whether we've already loaded this module map, and mark it as being
1722e5dd7070Spatrick   // loaded in case we recursively try to load it from itself.
1723e5dd7070Spatrick   auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1724e5dd7070Spatrick   if (!AddResult.second)
1725e5dd7070Spatrick     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1726e5dd7070Spatrick 
1727e5dd7070Spatrick   if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1728e5dd7070Spatrick     LoadedModuleMaps[File] = false;
1729e5dd7070Spatrick     return LMM_InvalidModuleMap;
1730e5dd7070Spatrick   }
1731e5dd7070Spatrick 
1732e5dd7070Spatrick   // Try to load a corresponding private module map.
1733e5dd7070Spatrick   if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1734e5dd7070Spatrick     if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1735e5dd7070Spatrick       LoadedModuleMaps[File] = false;
1736e5dd7070Spatrick       return LMM_InvalidModuleMap;
1737e5dd7070Spatrick     }
1738e5dd7070Spatrick   }
1739e5dd7070Spatrick 
1740e5dd7070Spatrick   // This directory has a module map.
1741e5dd7070Spatrick   return LMM_NewlyLoaded;
1742e5dd7070Spatrick }
1743e5dd7070Spatrick 
1744e5dd7070Spatrick const FileEntry *
lookupModuleMapFile(const DirectoryEntry * Dir,bool IsFramework)1745e5dd7070Spatrick HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1746e5dd7070Spatrick   if (!HSOpts->ImplicitModuleMaps)
1747e5dd7070Spatrick     return nullptr;
1748e5dd7070Spatrick   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1749e5dd7070Spatrick   // module.map at the framework root is also accepted.
1750e5dd7070Spatrick   SmallString<128> ModuleMapFileName(Dir->getName());
1751e5dd7070Spatrick   if (IsFramework)
1752e5dd7070Spatrick     llvm::sys::path::append(ModuleMapFileName, "Modules");
1753e5dd7070Spatrick   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1754e5dd7070Spatrick   if (auto F = FileMgr.getFile(ModuleMapFileName))
1755e5dd7070Spatrick     return *F;
1756e5dd7070Spatrick 
1757e5dd7070Spatrick   // Continue to allow module.map
1758e5dd7070Spatrick   ModuleMapFileName = Dir->getName();
1759e5dd7070Spatrick   llvm::sys::path::append(ModuleMapFileName, "module.map");
1760e5dd7070Spatrick   if (auto F = FileMgr.getFile(ModuleMapFileName))
1761e5dd7070Spatrick     return *F;
1762ec727ea7Spatrick 
1763ec727ea7Spatrick   // For frameworks, allow to have a private module map with a preferred
1764ec727ea7Spatrick   // spelling when a public module map is absent.
1765ec727ea7Spatrick   if (IsFramework) {
1766ec727ea7Spatrick     ModuleMapFileName = Dir->getName();
1767ec727ea7Spatrick     llvm::sys::path::append(ModuleMapFileName, "Modules",
1768ec727ea7Spatrick                             "module.private.modulemap");
1769ec727ea7Spatrick     if (auto F = FileMgr.getFile(ModuleMapFileName))
1770ec727ea7Spatrick       return *F;
1771ec727ea7Spatrick   }
1772e5dd7070Spatrick   return nullptr;
1773e5dd7070Spatrick }
1774e5dd7070Spatrick 
loadFrameworkModule(StringRef Name,DirectoryEntryRef Dir,bool IsSystem)1775*12c85518Srobert Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
1776e5dd7070Spatrick                                           bool IsSystem) {
1777e5dd7070Spatrick   if (Module *Module = ModMap.findModule(Name))
1778e5dd7070Spatrick     return Module;
1779e5dd7070Spatrick 
1780e5dd7070Spatrick   // Try to load a module map file.
1781e5dd7070Spatrick   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1782e5dd7070Spatrick   case LMM_InvalidModuleMap:
1783e5dd7070Spatrick     // Try to infer a module map from the framework directory.
1784e5dd7070Spatrick     if (HSOpts->ImplicitModuleMaps)
1785e5dd7070Spatrick       ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1786e5dd7070Spatrick     break;
1787e5dd7070Spatrick 
1788e5dd7070Spatrick   case LMM_AlreadyLoaded:
1789e5dd7070Spatrick   case LMM_NoDirectory:
1790e5dd7070Spatrick     return nullptr;
1791e5dd7070Spatrick 
1792e5dd7070Spatrick   case LMM_NewlyLoaded:
1793e5dd7070Spatrick     break;
1794e5dd7070Spatrick   }
1795e5dd7070Spatrick 
1796e5dd7070Spatrick   return ModMap.findModule(Name);
1797e5dd7070Spatrick }
1798e5dd7070Spatrick 
1799e5dd7070Spatrick HeaderSearch::LoadModuleMapResult
loadModuleMapFile(StringRef DirName,bool IsSystem,bool IsFramework)1800e5dd7070Spatrick HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1801e5dd7070Spatrick                                 bool IsFramework) {
1802*12c85518Srobert   if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName))
1803e5dd7070Spatrick     return loadModuleMapFile(*Dir, IsSystem, IsFramework);
1804e5dd7070Spatrick 
1805e5dd7070Spatrick   return LMM_NoDirectory;
1806e5dd7070Spatrick }
1807e5dd7070Spatrick 
1808e5dd7070Spatrick HeaderSearch::LoadModuleMapResult
loadModuleMapFile(DirectoryEntryRef Dir,bool IsSystem,bool IsFramework)1809*12c85518Srobert HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
1810e5dd7070Spatrick                                 bool IsFramework) {
1811e5dd7070Spatrick   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1812e5dd7070Spatrick   if (KnownDir != DirectoryHasModuleMap.end())
1813e5dd7070Spatrick     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1814e5dd7070Spatrick 
1815e5dd7070Spatrick   if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1816e5dd7070Spatrick     LoadModuleMapResult Result =
1817e5dd7070Spatrick         loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1818e5dd7070Spatrick     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1819e5dd7070Spatrick     // E.g. Foo.framework/Modules/module.modulemap
1820e5dd7070Spatrick     //      ^Dir                  ^ModuleMapFile
1821e5dd7070Spatrick     if (Result == LMM_NewlyLoaded)
1822e5dd7070Spatrick       DirectoryHasModuleMap[Dir] = true;
1823e5dd7070Spatrick     else if (Result == LMM_InvalidModuleMap)
1824e5dd7070Spatrick       DirectoryHasModuleMap[Dir] = false;
1825e5dd7070Spatrick     return Result;
1826e5dd7070Spatrick   }
1827e5dd7070Spatrick   return LMM_InvalidModuleMap;
1828e5dd7070Spatrick }
1829e5dd7070Spatrick 
collectAllModules(SmallVectorImpl<Module * > & Modules)1830e5dd7070Spatrick void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1831e5dd7070Spatrick   Modules.clear();
1832e5dd7070Spatrick 
1833e5dd7070Spatrick   if (HSOpts->ImplicitModuleMaps) {
1834e5dd7070Spatrick     // Load module maps for each of the header search directories.
1835*12c85518Srobert     for (DirectoryLookup &DL : search_dir_range()) {
1836*12c85518Srobert       bool IsSystem = DL.isSystemHeaderDirectory();
1837*12c85518Srobert       if (DL.isFramework()) {
1838e5dd7070Spatrick         std::error_code EC;
1839e5dd7070Spatrick         SmallString<128> DirNative;
1840*12c85518Srobert         llvm::sys::path::native(DL.getFrameworkDir()->getName(), DirNative);
1841e5dd7070Spatrick 
1842e5dd7070Spatrick         // Search each of the ".framework" directories to load them as modules.
1843e5dd7070Spatrick         llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1844e5dd7070Spatrick         for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1845e5dd7070Spatrick                                            DirEnd;
1846e5dd7070Spatrick              Dir != DirEnd && !EC; Dir.increment(EC)) {
1847e5dd7070Spatrick           if (llvm::sys::path::extension(Dir->path()) != ".framework")
1848e5dd7070Spatrick             continue;
1849e5dd7070Spatrick 
1850*12c85518Srobert           auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path());
1851e5dd7070Spatrick           if (!FrameworkDir)
1852e5dd7070Spatrick             continue;
1853e5dd7070Spatrick 
1854e5dd7070Spatrick           // Load this framework module.
1855e5dd7070Spatrick           loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
1856e5dd7070Spatrick                               IsSystem);
1857e5dd7070Spatrick         }
1858e5dd7070Spatrick         continue;
1859e5dd7070Spatrick       }
1860e5dd7070Spatrick 
1861e5dd7070Spatrick       // FIXME: Deal with header maps.
1862*12c85518Srobert       if (DL.isHeaderMap())
1863e5dd7070Spatrick         continue;
1864e5dd7070Spatrick 
1865e5dd7070Spatrick       // Try to load a module map file for the search directory.
1866*12c85518Srobert       loadModuleMapFile(*DL.getDirRef(), IsSystem, /*IsFramework*/ false);
1867e5dd7070Spatrick 
1868e5dd7070Spatrick       // Try to load module map files for immediate subdirectories of this
1869e5dd7070Spatrick       // search directory.
1870*12c85518Srobert       loadSubdirectoryModuleMaps(DL);
1871e5dd7070Spatrick     }
1872e5dd7070Spatrick   }
1873e5dd7070Spatrick 
1874e5dd7070Spatrick   // Populate the list of modules.
1875*12c85518Srobert   llvm::transform(ModMap.modules(), std::back_inserter(Modules),
1876*12c85518Srobert                   [](const auto &NameAndMod) { return NameAndMod.second; });
1877e5dd7070Spatrick }
1878e5dd7070Spatrick 
loadTopLevelSystemModules()1879e5dd7070Spatrick void HeaderSearch::loadTopLevelSystemModules() {
1880e5dd7070Spatrick   if (!HSOpts->ImplicitModuleMaps)
1881e5dd7070Spatrick     return;
1882e5dd7070Spatrick 
1883e5dd7070Spatrick   // Load module maps for each of the header search directories.
1884*12c85518Srobert   for (const DirectoryLookup &DL : search_dir_range()) {
1885e5dd7070Spatrick     // We only care about normal header directories.
1886*12c85518Srobert     if (!DL.isNormalDir())
1887e5dd7070Spatrick       continue;
1888e5dd7070Spatrick 
1889e5dd7070Spatrick     // Try to load a module map file for the search directory.
1890*12c85518Srobert     loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(),
1891*12c85518Srobert                       DL.isFramework());
1892e5dd7070Spatrick   }
1893e5dd7070Spatrick }
1894e5dd7070Spatrick 
loadSubdirectoryModuleMaps(DirectoryLookup & SearchDir)1895e5dd7070Spatrick void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1896e5dd7070Spatrick   assert(HSOpts->ImplicitModuleMaps &&
1897e5dd7070Spatrick          "Should not be loading subdirectory module maps");
1898e5dd7070Spatrick 
1899e5dd7070Spatrick   if (SearchDir.haveSearchedAllModuleMaps())
1900e5dd7070Spatrick     return;
1901e5dd7070Spatrick 
1902e5dd7070Spatrick   std::error_code EC;
1903e5dd7070Spatrick   SmallString<128> Dir = SearchDir.getDir()->getName();
1904e5dd7070Spatrick   FileMgr.makeAbsolutePath(Dir);
1905e5dd7070Spatrick   SmallString<128> DirNative;
1906e5dd7070Spatrick   llvm::sys::path::native(Dir, DirNative);
1907e5dd7070Spatrick   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1908e5dd7070Spatrick   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1909e5dd7070Spatrick        Dir != DirEnd && !EC; Dir.increment(EC)) {
1910e5dd7070Spatrick     bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1911e5dd7070Spatrick     if (IsFramework == SearchDir.isFramework())
1912e5dd7070Spatrick       loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1913e5dd7070Spatrick                         SearchDir.isFramework());
1914e5dd7070Spatrick   }
1915e5dd7070Spatrick 
1916e5dd7070Spatrick   SearchDir.setSearchedAllModuleMaps(true);
1917e5dd7070Spatrick }
1918e5dd7070Spatrick 
suggestPathToFileForDiagnostics(const FileEntry * File,llvm::StringRef MainFile,bool * IsSystem)1919e5dd7070Spatrick std::string HeaderSearch::suggestPathToFileForDiagnostics(
1920e5dd7070Spatrick     const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
1921e5dd7070Spatrick   // FIXME: We assume that the path name currently cached in the FileEntry is
1922e5dd7070Spatrick   // the most appropriate one for this analysis (and that it's spelled the
1923e5dd7070Spatrick   // same way as the corresponding header search path).
1924e5dd7070Spatrick   return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1925e5dd7070Spatrick                                          MainFile, IsSystem);
1926e5dd7070Spatrick }
1927e5dd7070Spatrick 
suggestPathToFileForDiagnostics(llvm::StringRef File,llvm::StringRef WorkingDir,llvm::StringRef MainFile,bool * IsSystem)1928e5dd7070Spatrick std::string HeaderSearch::suggestPathToFileForDiagnostics(
1929e5dd7070Spatrick     llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1930e5dd7070Spatrick     bool *IsSystem) {
1931e5dd7070Spatrick   using namespace llvm::sys;
1932e5dd7070Spatrick 
1933*12c85518Srobert   llvm::SmallString<32> FilePath = File;
1934*12c85518Srobert   // remove_dots switches to backslashes on windows as a side-effect!
1935*12c85518Srobert   // We always want to suggest forward slashes for includes.
1936*12c85518Srobert   // (not remove_dots(..., posix) as that misparses windows paths).
1937*12c85518Srobert   path::remove_dots(FilePath, /*remove_dot_dot=*/true);
1938*12c85518Srobert   path::native(FilePath, path::Style::posix);
1939*12c85518Srobert   File = FilePath;
1940*12c85518Srobert 
1941e5dd7070Spatrick   unsigned BestPrefixLength = 0;
1942*12c85518Srobert   // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
1943*12c85518Srobert   // the longest prefix we've seen so for it, returns true and updates the
1944*12c85518Srobert   // `BestPrefixLength` accordingly.
1945*12c85518Srobert   auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool {
1946e5dd7070Spatrick     if (!WorkingDir.empty() && !path::is_absolute(Dir))
1947*12c85518Srobert       fs::make_absolute(WorkingDir, Dir);
1948*12c85518Srobert     path::remove_dots(Dir, /*remove_dot_dot=*/true);
1949e5dd7070Spatrick     for (auto NI = path::begin(File), NE = path::end(File),
1950e5dd7070Spatrick               DI = path::begin(Dir), DE = path::end(Dir);
1951*12c85518Srobert          NI != NE; ++NI, ++DI) {
1952e5dd7070Spatrick       if (DI == DE) {
1953*12c85518Srobert         // Dir is a prefix of File, up to choice of path separators.
1954e5dd7070Spatrick         unsigned PrefixLength = NI - path::begin(File);
1955e5dd7070Spatrick         if (PrefixLength > BestPrefixLength) {
1956e5dd7070Spatrick           BestPrefixLength = PrefixLength;
1957e5dd7070Spatrick           return true;
1958e5dd7070Spatrick         }
1959e5dd7070Spatrick         break;
1960e5dd7070Spatrick       }
1961e5dd7070Spatrick 
1962e5dd7070Spatrick       // Consider all path separators equal.
1963e5dd7070Spatrick       if (NI->size() == 1 && DI->size() == 1 &&
1964e5dd7070Spatrick           path::is_separator(NI->front()) && path::is_separator(DI->front()))
1965e5dd7070Spatrick         continue;
1966e5dd7070Spatrick 
1967*12c85518Srobert       // Special case Apple .sdk folders since the search path is typically a
1968*12c85518Srobert       // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
1969*12c85518Srobert       // located in `iPhoneSimulator.sdk` (the real folder).
1970*12c85518Srobert       if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
1971*12c85518Srobert         StringRef NBasename = path::stem(*NI);
1972*12c85518Srobert         StringRef DBasename = path::stem(*DI);
1973*12c85518Srobert         if (DBasename.startswith(NBasename))
1974*12c85518Srobert           continue;
1975*12c85518Srobert       }
1976*12c85518Srobert 
1977e5dd7070Spatrick       if (*NI != *DI)
1978e5dd7070Spatrick         break;
1979e5dd7070Spatrick     }
1980e5dd7070Spatrick     return false;
1981e5dd7070Spatrick   };
1982e5dd7070Spatrick 
1983*12c85518Srobert   bool BestPrefixIsFramework = false;
1984*12c85518Srobert   for (const DirectoryLookup &DL : search_dir_range()) {
1985*12c85518Srobert     if (DL.isNormalDir()) {
1986*12c85518Srobert       StringRef Dir = DL.getDir()->getName();
1987*12c85518Srobert       if (CheckDir(Dir)) {
1988*12c85518Srobert         if (IsSystem)
1989*12c85518Srobert           *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
1990*12c85518Srobert         BestPrefixIsFramework = false;
1991*12c85518Srobert       }
1992*12c85518Srobert     } else if (DL.isFramework()) {
1993*12c85518Srobert       StringRef Dir = DL.getFrameworkDir()->getName();
1994*12c85518Srobert       if (CheckDir(Dir)) {
1995*12c85518Srobert         if (IsSystem)
1996*12c85518Srobert           *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
1997*12c85518Srobert         BestPrefixIsFramework = true;
1998*12c85518Srobert       }
1999*12c85518Srobert     }
2000e5dd7070Spatrick   }
2001e5dd7070Spatrick 
2002e5dd7070Spatrick   // Try to shorten include path using TUs directory, if we couldn't find any
2003e5dd7070Spatrick   // suitable prefix in include search paths.
2004*12c85518Srobert   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {
2005*12c85518Srobert     if (IsSystem)
2006e5dd7070Spatrick       *IsSystem = false;
2007*12c85518Srobert     BestPrefixIsFramework = false;
2008*12c85518Srobert   }
2009e5dd7070Spatrick 
2010a9ac8606Spatrick   // Try resolving resulting filename via reverse search in header maps,
2011*12c85518Srobert   // key from header name is user preferred name for the include file.
2012a9ac8606Spatrick   StringRef Filename = File.drop_front(BestPrefixLength);
2013*12c85518Srobert   for (const DirectoryLookup &DL : search_dir_range()) {
2014*12c85518Srobert     if (!DL.isHeaderMap())
2015a9ac8606Spatrick       continue;
2016e5dd7070Spatrick 
2017a9ac8606Spatrick     StringRef SpelledFilename =
2018*12c85518Srobert         DL.getHeaderMap()->reverseLookupFilename(Filename);
2019a9ac8606Spatrick     if (!SpelledFilename.empty()) {
2020a9ac8606Spatrick       Filename = SpelledFilename;
2021*12c85518Srobert       BestPrefixIsFramework = false;
2022a9ac8606Spatrick       break;
2023a9ac8606Spatrick     }
2024a9ac8606Spatrick   }
2025*12c85518Srobert 
2026*12c85518Srobert   // If the best prefix is a framework path, we need to compute the proper
2027*12c85518Srobert   // include spelling for the framework header.
2028*12c85518Srobert   bool IsPrivateHeader;
2029*12c85518Srobert   SmallString<128> FrameworkName, IncludeSpelling;
2030*12c85518Srobert   if (BestPrefixIsFramework &&
2031*12c85518Srobert       isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,
2032*12c85518Srobert                            IncludeSpelling)) {
2033*12c85518Srobert     Filename = IncludeSpelling;
2034*12c85518Srobert   }
2035a9ac8606Spatrick   return path::convert_to_slash(Filename);
2036e5dd7070Spatrick }
2037