xref: /aosp_15_r20/external/clang/lib/Lex/HeaderSearch.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file implements the DirectoryLookup and HeaderSearch interfaces.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "clang/Lex/HeaderSearch.h"
15*67e74705SXin Li #include "clang/Basic/FileManager.h"
16*67e74705SXin Li #include "clang/Basic/IdentifierTable.h"
17*67e74705SXin Li #include "clang/Lex/ExternalPreprocessorSource.h"
18*67e74705SXin Li #include "clang/Lex/HeaderMap.h"
19*67e74705SXin Li #include "clang/Lex/HeaderSearchOptions.h"
20*67e74705SXin Li #include "clang/Lex/LexDiagnostic.h"
21*67e74705SXin Li #include "clang/Lex/Lexer.h"
22*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
23*67e74705SXin Li #include "llvm/ADT/APInt.h"
24*67e74705SXin Li #include "llvm/ADT/Hashing.h"
25*67e74705SXin Li #include "llvm/ADT/SmallString.h"
26*67e74705SXin Li #include "llvm/Support/Capacity.h"
27*67e74705SXin Li #include "llvm/Support/FileSystem.h"
28*67e74705SXin Li #include "llvm/Support/Path.h"
29*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
30*67e74705SXin Li #include <cstdio>
31*67e74705SXin Li #include <utility>
32*67e74705SXin Li #if defined(LLVM_ON_UNIX)
33*67e74705SXin Li #include <limits.h>
34*67e74705SXin Li #endif
35*67e74705SXin Li using namespace clang;
36*67e74705SXin Li 
37*67e74705SXin Li const IdentifierInfo *
getControllingMacro(ExternalPreprocessorSource * External)38*67e74705SXin Li HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
39*67e74705SXin Li   if (ControllingMacro) {
40*67e74705SXin Li     if (ControllingMacro->isOutOfDate())
41*67e74705SXin Li       External->updateOutOfDateIdentifier(
42*67e74705SXin Li           *const_cast<IdentifierInfo *>(ControllingMacro));
43*67e74705SXin Li     return ControllingMacro;
44*67e74705SXin Li   }
45*67e74705SXin Li 
46*67e74705SXin Li   if (!ControllingMacroID || !External)
47*67e74705SXin Li     return nullptr;
48*67e74705SXin Li 
49*67e74705SXin Li   ControllingMacro = External->GetIdentifier(ControllingMacroID);
50*67e74705SXin Li   return ControllingMacro;
51*67e74705SXin Li }
52*67e74705SXin Li 
~ExternalHeaderFileInfoSource()53*67e74705SXin Li ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
54*67e74705SXin Li 
HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,SourceManager & SourceMgr,DiagnosticsEngine & Diags,const LangOptions & LangOpts,const TargetInfo * Target)55*67e74705SXin Li HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
56*67e74705SXin Li                            SourceManager &SourceMgr, DiagnosticsEngine &Diags,
57*67e74705SXin Li                            const LangOptions &LangOpts,
58*67e74705SXin Li                            const TargetInfo *Target)
59*67e74705SXin Li     : HSOpts(std::move(HSOpts)), Diags(Diags),
60*67e74705SXin Li       FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
61*67e74705SXin Li       ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
62*67e74705SXin Li   AngledDirIdx = 0;
63*67e74705SXin Li   SystemDirIdx = 0;
64*67e74705SXin Li   NoCurDirSearch = false;
65*67e74705SXin Li 
66*67e74705SXin Li   ExternalLookup = nullptr;
67*67e74705SXin Li   ExternalSource = nullptr;
68*67e74705SXin Li   NumIncluded = 0;
69*67e74705SXin Li   NumMultiIncludeFileOptzn = 0;
70*67e74705SXin Li   NumFrameworkLookups = NumSubFrameworkLookups = 0;
71*67e74705SXin Li }
72*67e74705SXin Li 
~HeaderSearch()73*67e74705SXin Li HeaderSearch::~HeaderSearch() {
74*67e74705SXin Li   // Delete headermaps.
75*67e74705SXin Li   for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
76*67e74705SXin Li     delete HeaderMaps[i].second;
77*67e74705SXin Li }
78*67e74705SXin Li 
PrintStats()79*67e74705SXin Li void HeaderSearch::PrintStats() {
80*67e74705SXin Li   fprintf(stderr, "\n*** HeaderSearch Stats:\n");
81*67e74705SXin Li   fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
82*67e74705SXin Li   unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
83*67e74705SXin Li   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
84*67e74705SXin Li     NumOnceOnlyFiles += FileInfo[i].isImport;
85*67e74705SXin Li     if (MaxNumIncludes < FileInfo[i].NumIncludes)
86*67e74705SXin Li       MaxNumIncludes = FileInfo[i].NumIncludes;
87*67e74705SXin Li     NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
88*67e74705SXin Li   }
89*67e74705SXin Li   fprintf(stderr, "  %d #import/#pragma once files.\n", NumOnceOnlyFiles);
90*67e74705SXin Li   fprintf(stderr, "  %d included exactly once.\n", NumSingleIncludedFiles);
91*67e74705SXin Li   fprintf(stderr, "  %d max times a file is included.\n", MaxNumIncludes);
92*67e74705SXin Li 
93*67e74705SXin Li   fprintf(stderr, "  %d #include/#include_next/#import.\n", NumIncluded);
94*67e74705SXin Li   fprintf(stderr, "    %d #includes skipped due to"
95*67e74705SXin Li           " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
96*67e74705SXin Li 
97*67e74705SXin Li   fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
98*67e74705SXin Li   fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
99*67e74705SXin Li }
100*67e74705SXin Li 
101*67e74705SXin Li /// CreateHeaderMap - This method returns a HeaderMap for the specified
102*67e74705SXin Li /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
CreateHeaderMap(const FileEntry * FE)103*67e74705SXin Li const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
104*67e74705SXin Li   // We expect the number of headermaps to be small, and almost always empty.
105*67e74705SXin Li   // If it ever grows, use of a linear search should be re-evaluated.
106*67e74705SXin Li   if (!HeaderMaps.empty()) {
107*67e74705SXin Li     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
108*67e74705SXin Li       // Pointer equality comparison of FileEntries works because they are
109*67e74705SXin Li       // already uniqued by inode.
110*67e74705SXin Li       if (HeaderMaps[i].first == FE)
111*67e74705SXin Li         return HeaderMaps[i].second;
112*67e74705SXin Li   }
113*67e74705SXin Li 
114*67e74705SXin Li   if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
115*67e74705SXin Li     HeaderMaps.push_back(std::make_pair(FE, HM));
116*67e74705SXin Li     return HM;
117*67e74705SXin Li   }
118*67e74705SXin Li 
119*67e74705SXin Li   return nullptr;
120*67e74705SXin Li }
121*67e74705SXin Li 
getModuleFileName(Module * Module)122*67e74705SXin Li std::string HeaderSearch::getModuleFileName(Module *Module) {
123*67e74705SXin Li   const FileEntry *ModuleMap =
124*67e74705SXin Li       getModuleMap().getModuleMapFileForUniquing(Module);
125*67e74705SXin Li   return getModuleFileName(Module->Name, ModuleMap->getName());
126*67e74705SXin Li }
127*67e74705SXin Li 
getModuleFileName(StringRef ModuleName,StringRef ModuleMapPath)128*67e74705SXin Li std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
129*67e74705SXin Li                                             StringRef ModuleMapPath) {
130*67e74705SXin Li   // If we don't have a module cache path or aren't supposed to use one, we
131*67e74705SXin Li   // can't do anything.
132*67e74705SXin Li   if (getModuleCachePath().empty())
133*67e74705SXin Li     return std::string();
134*67e74705SXin Li 
135*67e74705SXin Li   SmallString<256> Result(getModuleCachePath());
136*67e74705SXin Li   llvm::sys::fs::make_absolute(Result);
137*67e74705SXin Li 
138*67e74705SXin Li   if (HSOpts->DisableModuleHash) {
139*67e74705SXin Li     llvm::sys::path::append(Result, ModuleName + ".pcm");
140*67e74705SXin Li   } else {
141*67e74705SXin Li     // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
142*67e74705SXin Li     // ideally be globally unique to this particular module. Name collisions
143*67e74705SXin Li     // in the hash are safe (because any translation unit can only import one
144*67e74705SXin Li     // module with each name), but result in a loss of caching.
145*67e74705SXin Li     //
146*67e74705SXin Li     // To avoid false-negatives, we form as canonical a path as we can, and map
147*67e74705SXin Li     // to lower-case in case we're on a case-insensitive file system.
148*67e74705SXin Li    auto *Dir =
149*67e74705SXin Li         FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
150*67e74705SXin Li     if (!Dir)
151*67e74705SXin Li       return std::string();
152*67e74705SXin Li     auto DirName = FileMgr.getCanonicalName(Dir);
153*67e74705SXin Li     auto FileName = llvm::sys::path::filename(ModuleMapPath);
154*67e74705SXin Li 
155*67e74705SXin Li     llvm::hash_code Hash =
156*67e74705SXin Li       llvm::hash_combine(DirName.lower(), FileName.lower());
157*67e74705SXin Li 
158*67e74705SXin Li     SmallString<128> HashStr;
159*67e74705SXin Li     llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
160*67e74705SXin Li     llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
161*67e74705SXin Li   }
162*67e74705SXin Li   return Result.str().str();
163*67e74705SXin Li }
164*67e74705SXin Li 
lookupModule(StringRef ModuleName,bool AllowSearch)165*67e74705SXin Li Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
166*67e74705SXin Li   // Look in the module map to determine if there is a module by this name.
167*67e74705SXin Li   Module *Module = ModMap.findModule(ModuleName);
168*67e74705SXin Li   if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
169*67e74705SXin Li     return Module;
170*67e74705SXin Li 
171*67e74705SXin Li   // Look through the various header search paths to load any available module
172*67e74705SXin Li   // maps, searching for a module map that describes this module.
173*67e74705SXin Li   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
174*67e74705SXin Li     if (SearchDirs[Idx].isFramework()) {
175*67e74705SXin Li       // Search for or infer a module map for a framework.
176*67e74705SXin Li       SmallString<128> FrameworkDirName;
177*67e74705SXin Li       FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
178*67e74705SXin Li       llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
179*67e74705SXin Li       if (const DirectoryEntry *FrameworkDir
180*67e74705SXin Li             = FileMgr.getDirectory(FrameworkDirName)) {
181*67e74705SXin Li         bool IsSystem
182*67e74705SXin Li           = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
183*67e74705SXin Li         Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
184*67e74705SXin Li         if (Module)
185*67e74705SXin Li           break;
186*67e74705SXin Li       }
187*67e74705SXin Li     }
188*67e74705SXin Li 
189*67e74705SXin Li     // FIXME: Figure out how header maps and module maps will work together.
190*67e74705SXin Li 
191*67e74705SXin Li     // Only deal with normal search directories.
192*67e74705SXin Li     if (!SearchDirs[Idx].isNormalDir())
193*67e74705SXin Li       continue;
194*67e74705SXin Li 
195*67e74705SXin Li     bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
196*67e74705SXin Li     // Search for a module map file in this directory.
197*67e74705SXin Li     if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
198*67e74705SXin Li                           /*IsFramework*/false) == LMM_NewlyLoaded) {
199*67e74705SXin Li       // We just loaded a module map file; check whether the module is
200*67e74705SXin Li       // available now.
201*67e74705SXin Li       Module = ModMap.findModule(ModuleName);
202*67e74705SXin Li       if (Module)
203*67e74705SXin Li         break;
204*67e74705SXin Li     }
205*67e74705SXin Li 
206*67e74705SXin Li     // Search for a module map in a subdirectory with the same name as the
207*67e74705SXin Li     // module.
208*67e74705SXin Li     SmallString<128> NestedModuleMapDirName;
209*67e74705SXin Li     NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
210*67e74705SXin Li     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
211*67e74705SXin Li     if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
212*67e74705SXin Li                           /*IsFramework*/false) == LMM_NewlyLoaded){
213*67e74705SXin Li       // If we just loaded a module map file, look for the module again.
214*67e74705SXin Li       Module = ModMap.findModule(ModuleName);
215*67e74705SXin Li       if (Module)
216*67e74705SXin Li         break;
217*67e74705SXin Li     }
218*67e74705SXin Li 
219*67e74705SXin Li     // If we've already performed the exhaustive search for module maps in this
220*67e74705SXin Li     // search directory, don't do it again.
221*67e74705SXin Li     if (SearchDirs[Idx].haveSearchedAllModuleMaps())
222*67e74705SXin Li       continue;
223*67e74705SXin Li 
224*67e74705SXin Li     // Load all module maps in the immediate subdirectories of this search
225*67e74705SXin Li     // directory.
226*67e74705SXin Li     loadSubdirectoryModuleMaps(SearchDirs[Idx]);
227*67e74705SXin Li 
228*67e74705SXin Li     // Look again for the module.
229*67e74705SXin Li     Module = ModMap.findModule(ModuleName);
230*67e74705SXin Li     if (Module)
231*67e74705SXin Li       break;
232*67e74705SXin Li   }
233*67e74705SXin Li 
234*67e74705SXin Li   return Module;
235*67e74705SXin Li }
236*67e74705SXin Li 
237*67e74705SXin Li //===----------------------------------------------------------------------===//
238*67e74705SXin Li // File lookup within a DirectoryLookup scope
239*67e74705SXin Li //===----------------------------------------------------------------------===//
240*67e74705SXin Li 
241*67e74705SXin Li /// getName - Return the directory or filename corresponding to this lookup
242*67e74705SXin Li /// object.
getName() const243*67e74705SXin Li const char *DirectoryLookup::getName() const {
244*67e74705SXin Li   if (isNormalDir())
245*67e74705SXin Li     return getDir()->getName();
246*67e74705SXin Li   if (isFramework())
247*67e74705SXin Li     return getFrameworkDir()->getName();
248*67e74705SXin Li   assert(isHeaderMap() && "Unknown DirectoryLookup");
249*67e74705SXin Li   return getHeaderMap()->getFileName();
250*67e74705SXin Li }
251*67e74705SXin Li 
getFileAndSuggestModule(StringRef FileName,SourceLocation IncludeLoc,const DirectoryEntry * Dir,bool IsSystemHeaderDir,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule)252*67e74705SXin Li const FileEntry *HeaderSearch::getFileAndSuggestModule(
253*67e74705SXin Li     StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
254*67e74705SXin Li     bool IsSystemHeaderDir, Module *RequestingModule,
255*67e74705SXin Li     ModuleMap::KnownHeader *SuggestedModule) {
256*67e74705SXin Li   // If we have a module map that might map this header, load it and
257*67e74705SXin Li   // check whether we'll have a suggestion for a module.
258*67e74705SXin Li   const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
259*67e74705SXin Li   if (!File)
260*67e74705SXin Li     return nullptr;
261*67e74705SXin Li 
262*67e74705SXin Li   // If there is a module that corresponds to this header, suggest it.
263*67e74705SXin Li   if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
264*67e74705SXin Li                                  RequestingModule, SuggestedModule,
265*67e74705SXin Li                                  IsSystemHeaderDir))
266*67e74705SXin Li     return nullptr;
267*67e74705SXin Li 
268*67e74705SXin Li   return File;
269*67e74705SXin Li }
270*67e74705SXin Li 
271*67e74705SXin Li /// LookupFile - Lookup the specified file in this search path, returning it
272*67e74705SXin Li /// 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 & HasBeenMapped,SmallVectorImpl<char> & MappedName) const273*67e74705SXin Li const FileEntry *DirectoryLookup::LookupFile(
274*67e74705SXin Li     StringRef &Filename,
275*67e74705SXin Li     HeaderSearch &HS,
276*67e74705SXin Li     SourceLocation IncludeLoc,
277*67e74705SXin Li     SmallVectorImpl<char> *SearchPath,
278*67e74705SXin Li     SmallVectorImpl<char> *RelativePath,
279*67e74705SXin Li     Module *RequestingModule,
280*67e74705SXin Li     ModuleMap::KnownHeader *SuggestedModule,
281*67e74705SXin Li     bool &InUserSpecifiedSystemFramework,
282*67e74705SXin Li     bool &HasBeenMapped,
283*67e74705SXin Li     SmallVectorImpl<char> &MappedName) const {
284*67e74705SXin Li   InUserSpecifiedSystemFramework = false;
285*67e74705SXin Li   HasBeenMapped = false;
286*67e74705SXin Li 
287*67e74705SXin Li   SmallString<1024> TmpDir;
288*67e74705SXin Li   if (isNormalDir()) {
289*67e74705SXin Li     // Concatenate the requested file onto the directory.
290*67e74705SXin Li     TmpDir = getDir()->getName();
291*67e74705SXin Li     llvm::sys::path::append(TmpDir, Filename);
292*67e74705SXin Li     if (SearchPath) {
293*67e74705SXin Li       StringRef SearchPathRef(getDir()->getName());
294*67e74705SXin Li       SearchPath->clear();
295*67e74705SXin Li       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
296*67e74705SXin Li     }
297*67e74705SXin Li     if (RelativePath) {
298*67e74705SXin Li       RelativePath->clear();
299*67e74705SXin Li       RelativePath->append(Filename.begin(), Filename.end());
300*67e74705SXin Li     }
301*67e74705SXin Li 
302*67e74705SXin Li     return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
303*67e74705SXin Li                                       isSystemHeaderDirectory(),
304*67e74705SXin Li                                       RequestingModule, SuggestedModule);
305*67e74705SXin Li   }
306*67e74705SXin Li 
307*67e74705SXin Li   if (isFramework())
308*67e74705SXin Li     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
309*67e74705SXin Li                              RequestingModule, SuggestedModule,
310*67e74705SXin Li                              InUserSpecifiedSystemFramework);
311*67e74705SXin Li 
312*67e74705SXin Li   assert(isHeaderMap() && "Unknown directory lookup");
313*67e74705SXin Li   const HeaderMap *HM = getHeaderMap();
314*67e74705SXin Li   SmallString<1024> Path;
315*67e74705SXin Li   StringRef Dest = HM->lookupFilename(Filename, Path);
316*67e74705SXin Li   if (Dest.empty())
317*67e74705SXin Li     return nullptr;
318*67e74705SXin Li 
319*67e74705SXin Li   const FileEntry *Result;
320*67e74705SXin Li 
321*67e74705SXin Li   // Check if the headermap maps the filename to a framework include
322*67e74705SXin Li   // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
323*67e74705SXin Li   // framework include.
324*67e74705SXin Li   if (llvm::sys::path::is_relative(Dest)) {
325*67e74705SXin Li     MappedName.clear();
326*67e74705SXin Li     MappedName.append(Dest.begin(), Dest.end());
327*67e74705SXin Li     Filename = StringRef(MappedName.begin(), MappedName.size());
328*67e74705SXin Li     HasBeenMapped = true;
329*67e74705SXin Li     Result = HM->LookupFile(Filename, HS.getFileMgr());
330*67e74705SXin Li 
331*67e74705SXin Li   } else {
332*67e74705SXin Li     Result = HS.getFileMgr().getFile(Dest);
333*67e74705SXin Li   }
334*67e74705SXin Li 
335*67e74705SXin Li   if (Result) {
336*67e74705SXin Li     if (SearchPath) {
337*67e74705SXin Li       StringRef SearchPathRef(getName());
338*67e74705SXin Li       SearchPath->clear();
339*67e74705SXin Li       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
340*67e74705SXin Li     }
341*67e74705SXin Li     if (RelativePath) {
342*67e74705SXin Li       RelativePath->clear();
343*67e74705SXin Li       RelativePath->append(Filename.begin(), Filename.end());
344*67e74705SXin Li     }
345*67e74705SXin Li   }
346*67e74705SXin Li   return Result;
347*67e74705SXin Li }
348*67e74705SXin Li 
349*67e74705SXin Li /// \brief Given a framework directory, find the top-most framework directory.
350*67e74705SXin Li ///
351*67e74705SXin Li /// \param FileMgr The file manager to use for directory lookups.
352*67e74705SXin Li /// \param DirName The name of the framework directory.
353*67e74705SXin Li /// \param SubmodulePath Will be populated with the submodule path from the
354*67e74705SXin Li /// returned top-level module to the originally named framework.
355*67e74705SXin Li static const DirectoryEntry *
getTopFrameworkDir(FileManager & FileMgr,StringRef DirName,SmallVectorImpl<std::string> & SubmodulePath)356*67e74705SXin Li getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
357*67e74705SXin Li                    SmallVectorImpl<std::string> &SubmodulePath) {
358*67e74705SXin Li   assert(llvm::sys::path::extension(DirName) == ".framework" &&
359*67e74705SXin Li          "Not a framework directory");
360*67e74705SXin Li 
361*67e74705SXin Li   // Note: as an egregious but useful hack we use the real path here, because
362*67e74705SXin Li   // frameworks moving between top-level frameworks to embedded frameworks tend
363*67e74705SXin Li   // to be symlinked, and we base the logical structure of modules on the
364*67e74705SXin Li   // physical layout. In particular, we need to deal with crazy includes like
365*67e74705SXin Li   //
366*67e74705SXin Li   //   #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
367*67e74705SXin Li   //
368*67e74705SXin Li   // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
369*67e74705SXin Li   // which one should access with, e.g.,
370*67e74705SXin Li   //
371*67e74705SXin Li   //   #include <Bar/Wibble.h>
372*67e74705SXin Li   //
373*67e74705SXin Li   // Similar issues occur when a top-level framework has moved into an
374*67e74705SXin Li   // embedded framework.
375*67e74705SXin Li   const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
376*67e74705SXin Li   DirName = FileMgr.getCanonicalName(TopFrameworkDir);
377*67e74705SXin Li   do {
378*67e74705SXin Li     // Get the parent directory name.
379*67e74705SXin Li     DirName = llvm::sys::path::parent_path(DirName);
380*67e74705SXin Li     if (DirName.empty())
381*67e74705SXin Li       break;
382*67e74705SXin Li 
383*67e74705SXin Li     // Determine whether this directory exists.
384*67e74705SXin Li     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
385*67e74705SXin Li     if (!Dir)
386*67e74705SXin Li       break;
387*67e74705SXin Li 
388*67e74705SXin Li     // If this is a framework directory, then we're a subframework of this
389*67e74705SXin Li     // framework.
390*67e74705SXin Li     if (llvm::sys::path::extension(DirName) == ".framework") {
391*67e74705SXin Li       SubmodulePath.push_back(llvm::sys::path::stem(DirName));
392*67e74705SXin Li       TopFrameworkDir = Dir;
393*67e74705SXin Li     }
394*67e74705SXin Li   } while (true);
395*67e74705SXin Li 
396*67e74705SXin Li   return TopFrameworkDir;
397*67e74705SXin Li }
398*67e74705SXin Li 
399*67e74705SXin Li /// DoFrameworkLookup - Do a lookup of the specified file in the current
400*67e74705SXin Li /// DirectoryLookup, which is a framework directory.
DoFrameworkLookup(StringRef Filename,HeaderSearch & HS,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool & InUserSpecifiedSystemFramework) const401*67e74705SXin Li const FileEntry *DirectoryLookup::DoFrameworkLookup(
402*67e74705SXin Li     StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
403*67e74705SXin Li     SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
404*67e74705SXin Li     ModuleMap::KnownHeader *SuggestedModule,
405*67e74705SXin Li     bool &InUserSpecifiedSystemFramework) const {
406*67e74705SXin Li   FileManager &FileMgr = HS.getFileMgr();
407*67e74705SXin Li 
408*67e74705SXin Li   // Framework names must have a '/' in the filename.
409*67e74705SXin Li   size_t SlashPos = Filename.find('/');
410*67e74705SXin Li   if (SlashPos == StringRef::npos) return nullptr;
411*67e74705SXin Li 
412*67e74705SXin Li   // Find out if this is the home for the specified framework, by checking
413*67e74705SXin Li   // HeaderSearch.  Possible answers are yes/no and unknown.
414*67e74705SXin Li   HeaderSearch::FrameworkCacheEntry &CacheEntry =
415*67e74705SXin Li     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
416*67e74705SXin Li 
417*67e74705SXin Li   // If it is known and in some other directory, fail.
418*67e74705SXin Li   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
419*67e74705SXin Li     return nullptr;
420*67e74705SXin Li 
421*67e74705SXin Li   // Otherwise, construct the path to this framework dir.
422*67e74705SXin Li 
423*67e74705SXin Li   // FrameworkName = "/System/Library/Frameworks/"
424*67e74705SXin Li   SmallString<1024> FrameworkName;
425*67e74705SXin Li   FrameworkName += getFrameworkDir()->getName();
426*67e74705SXin Li   if (FrameworkName.empty() || FrameworkName.back() != '/')
427*67e74705SXin Li     FrameworkName.push_back('/');
428*67e74705SXin Li 
429*67e74705SXin Li   // FrameworkName = "/System/Library/Frameworks/Cocoa"
430*67e74705SXin Li   StringRef ModuleName(Filename.begin(), SlashPos);
431*67e74705SXin Li   FrameworkName += ModuleName;
432*67e74705SXin Li 
433*67e74705SXin Li   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
434*67e74705SXin Li   FrameworkName += ".framework/";
435*67e74705SXin Li 
436*67e74705SXin Li   // If the cache entry was unresolved, populate it now.
437*67e74705SXin Li   if (!CacheEntry.Directory) {
438*67e74705SXin Li     HS.IncrementFrameworkLookupCount();
439*67e74705SXin Li 
440*67e74705SXin Li     // If the framework dir doesn't exist, we fail.
441*67e74705SXin Li     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
442*67e74705SXin Li     if (!Dir) return nullptr;
443*67e74705SXin Li 
444*67e74705SXin Li     // Otherwise, if it does, remember that this is the right direntry for this
445*67e74705SXin Li     // framework.
446*67e74705SXin Li     CacheEntry.Directory = getFrameworkDir();
447*67e74705SXin Li 
448*67e74705SXin Li     // If this is a user search directory, check if the framework has been
449*67e74705SXin Li     // user-specified as a system framework.
450*67e74705SXin Li     if (getDirCharacteristic() == SrcMgr::C_User) {
451*67e74705SXin Li       SmallString<1024> SystemFrameworkMarker(FrameworkName);
452*67e74705SXin Li       SystemFrameworkMarker += ".system_framework";
453*67e74705SXin Li       if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
454*67e74705SXin Li         CacheEntry.IsUserSpecifiedSystemFramework = true;
455*67e74705SXin Li       }
456*67e74705SXin Li     }
457*67e74705SXin Li   }
458*67e74705SXin Li 
459*67e74705SXin Li   // Set the 'user-specified system framework' flag.
460*67e74705SXin Li   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
461*67e74705SXin Li 
462*67e74705SXin Li   if (RelativePath) {
463*67e74705SXin Li     RelativePath->clear();
464*67e74705SXin Li     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
465*67e74705SXin Li   }
466*67e74705SXin Li 
467*67e74705SXin Li   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
468*67e74705SXin Li   unsigned OrigSize = FrameworkName.size();
469*67e74705SXin Li 
470*67e74705SXin Li   FrameworkName += "Headers/";
471*67e74705SXin Li 
472*67e74705SXin Li   if (SearchPath) {
473*67e74705SXin Li     SearchPath->clear();
474*67e74705SXin Li     // Without trailing '/'.
475*67e74705SXin Li     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
476*67e74705SXin Li   }
477*67e74705SXin Li 
478*67e74705SXin Li   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
479*67e74705SXin Li   const FileEntry *FE = FileMgr.getFile(FrameworkName,
480*67e74705SXin Li                                         /*openFile=*/!SuggestedModule);
481*67e74705SXin Li   if (!FE) {
482*67e74705SXin Li     // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
483*67e74705SXin Li     const char *Private = "Private";
484*67e74705SXin Li     FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
485*67e74705SXin Li                          Private+strlen(Private));
486*67e74705SXin Li     if (SearchPath)
487*67e74705SXin Li       SearchPath->insert(SearchPath->begin()+OrigSize, Private,
488*67e74705SXin Li                          Private+strlen(Private));
489*67e74705SXin Li 
490*67e74705SXin Li     FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
491*67e74705SXin Li   }
492*67e74705SXin Li 
493*67e74705SXin Li   // If we found the header and are allowed to suggest a module, do so now.
494*67e74705SXin Li   if (FE && SuggestedModule) {
495*67e74705SXin Li     // Find the framework in which this header occurs.
496*67e74705SXin Li     StringRef FrameworkPath = FE->getDir()->getName();
497*67e74705SXin Li     bool FoundFramework = false;
498*67e74705SXin Li     do {
499*67e74705SXin Li       // Determine whether this directory exists.
500*67e74705SXin Li       const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
501*67e74705SXin Li       if (!Dir)
502*67e74705SXin Li         break;
503*67e74705SXin Li 
504*67e74705SXin Li       // If this is a framework directory, then we're a subframework of this
505*67e74705SXin Li       // framework.
506*67e74705SXin Li       if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
507*67e74705SXin Li         FoundFramework = true;
508*67e74705SXin Li         break;
509*67e74705SXin Li       }
510*67e74705SXin Li 
511*67e74705SXin Li       // Get the parent directory name.
512*67e74705SXin Li       FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
513*67e74705SXin Li       if (FrameworkPath.empty())
514*67e74705SXin Li         break;
515*67e74705SXin Li     } while (true);
516*67e74705SXin Li 
517*67e74705SXin Li     bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
518*67e74705SXin Li     if (FoundFramework) {
519*67e74705SXin Li       if (!HS.findUsableModuleForFrameworkHeader(
520*67e74705SXin Li               FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
521*67e74705SXin Li         return nullptr;
522*67e74705SXin Li     } else {
523*67e74705SXin Li       if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
524*67e74705SXin Li                                         SuggestedModule, IsSystem))
525*67e74705SXin Li         return nullptr;
526*67e74705SXin Li     }
527*67e74705SXin Li   }
528*67e74705SXin Li   return FE;
529*67e74705SXin Li }
530*67e74705SXin Li 
setTarget(const TargetInfo & Target)531*67e74705SXin Li void HeaderSearch::setTarget(const TargetInfo &Target) {
532*67e74705SXin Li   ModMap.setTarget(Target);
533*67e74705SXin Li }
534*67e74705SXin Li 
535*67e74705SXin Li 
536*67e74705SXin Li //===----------------------------------------------------------------------===//
537*67e74705SXin Li // Header File Location.
538*67e74705SXin Li //===----------------------------------------------------------------------===//
539*67e74705SXin Li 
540*67e74705SXin Li /// \brief Return true with a diagnostic if the file that MSVC would have found
541*67e74705SXin Li /// fails to match the one that Clang would have found with MSVC header search
542*67e74705SXin Li /// disabled.
checkMSVCHeaderSearch(DiagnosticsEngine & Diags,const FileEntry * MSFE,const FileEntry * FE,SourceLocation IncludeLoc)543*67e74705SXin Li static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
544*67e74705SXin Li                                   const FileEntry *MSFE, const FileEntry *FE,
545*67e74705SXin Li                                   SourceLocation IncludeLoc) {
546*67e74705SXin Li   if (MSFE && FE != MSFE) {
547*67e74705SXin Li     Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
548*67e74705SXin Li     return true;
549*67e74705SXin Li   }
550*67e74705SXin Li   return false;
551*67e74705SXin Li }
552*67e74705SXin Li 
copyString(StringRef Str,llvm::BumpPtrAllocator & Alloc)553*67e74705SXin Li static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
554*67e74705SXin Li   assert(!Str.empty());
555*67e74705SXin Li   char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
556*67e74705SXin Li   std::copy(Str.begin(), Str.end(), CopyStr);
557*67e74705SXin Li   CopyStr[Str.size()] = '\0';
558*67e74705SXin Li   return CopyStr;
559*67e74705SXin Li }
560*67e74705SXin Li 
561*67e74705SXin Li /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
562*67e74705SXin Li /// return null on failure.  isAngled indicates whether the file reference is
563*67e74705SXin Li /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
564*67e74705SXin Li /// non-empty, indicates where the \#including file(s) are, in case a relative
565*67e74705SXin Li /// search is needed. Microsoft mode will pass all \#including files.
LookupFile(StringRef Filename,SourceLocation IncludeLoc,bool isAngled,const DirectoryLookup * FromDir,const DirectoryLookup * & CurDir,ArrayRef<std::pair<const FileEntry *,const DirectoryEntry * >> Includers,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool SkipCache,bool BuildSystemModule)566*67e74705SXin Li const FileEntry *HeaderSearch::LookupFile(
567*67e74705SXin Li     StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
568*67e74705SXin Li     const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
569*67e74705SXin Li     ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
570*67e74705SXin Li     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
571*67e74705SXin Li     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
572*67e74705SXin Li     bool SkipCache, bool BuildSystemModule) {
573*67e74705SXin Li   if (SuggestedModule)
574*67e74705SXin Li     *SuggestedModule = ModuleMap::KnownHeader();
575*67e74705SXin Li 
576*67e74705SXin Li   // If 'Filename' is absolute, check to see if it exists and no searching.
577*67e74705SXin Li   if (llvm::sys::path::is_absolute(Filename)) {
578*67e74705SXin Li     CurDir = nullptr;
579*67e74705SXin Li 
580*67e74705SXin Li     // If this was an #include_next "/absolute/file", fail.
581*67e74705SXin Li     if (FromDir) return nullptr;
582*67e74705SXin Li 
583*67e74705SXin Li     if (SearchPath)
584*67e74705SXin Li       SearchPath->clear();
585*67e74705SXin Li     if (RelativePath) {
586*67e74705SXin Li       RelativePath->clear();
587*67e74705SXin Li       RelativePath->append(Filename.begin(), Filename.end());
588*67e74705SXin Li     }
589*67e74705SXin Li     // Otherwise, just return the file.
590*67e74705SXin Li     return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
591*67e74705SXin Li                                    /*IsSystemHeaderDir*/false,
592*67e74705SXin Li                                    RequestingModule, SuggestedModule);
593*67e74705SXin Li   }
594*67e74705SXin Li 
595*67e74705SXin Li   // This is the header that MSVC's header search would have found.
596*67e74705SXin Li   const FileEntry *MSFE = nullptr;
597*67e74705SXin Li   ModuleMap::KnownHeader MSSuggestedModule;
598*67e74705SXin Li 
599*67e74705SXin Li   // Unless disabled, check to see if the file is in the #includer's
600*67e74705SXin Li   // directory.  This cannot be based on CurDir, because each includer could be
601*67e74705SXin Li   // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
602*67e74705SXin Li   // include of "baz.h" should resolve to "whatever/foo/baz.h".
603*67e74705SXin Li   // This search is not done for <> headers.
604*67e74705SXin Li   if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
605*67e74705SXin Li     SmallString<1024> TmpDir;
606*67e74705SXin Li     bool First = true;
607*67e74705SXin Li     for (const auto &IncluderAndDir : Includers) {
608*67e74705SXin Li       const FileEntry *Includer = IncluderAndDir.first;
609*67e74705SXin Li 
610*67e74705SXin Li       // Concatenate the requested file onto the directory.
611*67e74705SXin Li       // FIXME: Portability.  Filename concatenation should be in sys::Path.
612*67e74705SXin Li       TmpDir = IncluderAndDir.second->getName();
613*67e74705SXin Li       TmpDir.push_back('/');
614*67e74705SXin Li       TmpDir.append(Filename.begin(), Filename.end());
615*67e74705SXin Li 
616*67e74705SXin Li       // FIXME: We don't cache the result of getFileInfo across the call to
617*67e74705SXin Li       // getFileAndSuggestModule, because it's a reference to an element of
618*67e74705SXin Li       // a container that could be reallocated across this call.
619*67e74705SXin Li       //
620*67e74705SXin Li       // If we have no includer, that means we're processing a #include
621*67e74705SXin Li       // from a module build. We should treat this as a system header if we're
622*67e74705SXin Li       // building a [system] module.
623*67e74705SXin Li       bool IncluderIsSystemHeader =
624*67e74705SXin Li           Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
625*67e74705SXin Li           BuildSystemModule;
626*67e74705SXin Li       if (const FileEntry *FE = getFileAndSuggestModule(
627*67e74705SXin Li               TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
628*67e74705SXin Li               RequestingModule, SuggestedModule)) {
629*67e74705SXin Li         if (!Includer) {
630*67e74705SXin Li           assert(First && "only first includer can have no file");
631*67e74705SXin Li           return FE;
632*67e74705SXin Li         }
633*67e74705SXin Li 
634*67e74705SXin Li         // Leave CurDir unset.
635*67e74705SXin Li         // This file is a system header or C++ unfriendly if the old file is.
636*67e74705SXin Li         //
637*67e74705SXin Li         // Note that we only use one of FromHFI/ToHFI at once, due to potential
638*67e74705SXin Li         // reallocation of the underlying vector potentially making the first
639*67e74705SXin Li         // reference binding dangling.
640*67e74705SXin Li         HeaderFileInfo &FromHFI = getFileInfo(Includer);
641*67e74705SXin Li         unsigned DirInfo = FromHFI.DirInfo;
642*67e74705SXin Li         bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
643*67e74705SXin Li         StringRef Framework = FromHFI.Framework;
644*67e74705SXin Li 
645*67e74705SXin Li         HeaderFileInfo &ToHFI = getFileInfo(FE);
646*67e74705SXin Li         ToHFI.DirInfo = DirInfo;
647*67e74705SXin Li         ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
648*67e74705SXin Li         ToHFI.Framework = Framework;
649*67e74705SXin Li 
650*67e74705SXin Li         if (SearchPath) {
651*67e74705SXin Li           StringRef SearchPathRef(IncluderAndDir.second->getName());
652*67e74705SXin Li           SearchPath->clear();
653*67e74705SXin Li           SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
654*67e74705SXin Li         }
655*67e74705SXin Li         if (RelativePath) {
656*67e74705SXin Li           RelativePath->clear();
657*67e74705SXin Li           RelativePath->append(Filename.begin(), Filename.end());
658*67e74705SXin Li         }
659*67e74705SXin Li         if (First)
660*67e74705SXin Li           return FE;
661*67e74705SXin Li 
662*67e74705SXin Li         // Otherwise, we found the path via MSVC header search rules.  If
663*67e74705SXin Li         // -Wmsvc-include is enabled, we have to keep searching to see if we
664*67e74705SXin Li         // would've found this header in -I or -isystem directories.
665*67e74705SXin Li         if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
666*67e74705SXin Li           return FE;
667*67e74705SXin Li         } else {
668*67e74705SXin Li           MSFE = FE;
669*67e74705SXin Li           if (SuggestedModule) {
670*67e74705SXin Li             MSSuggestedModule = *SuggestedModule;
671*67e74705SXin Li             *SuggestedModule = ModuleMap::KnownHeader();
672*67e74705SXin Li           }
673*67e74705SXin Li           break;
674*67e74705SXin Li         }
675*67e74705SXin Li       }
676*67e74705SXin Li       First = false;
677*67e74705SXin Li     }
678*67e74705SXin Li   }
679*67e74705SXin Li 
680*67e74705SXin Li   CurDir = nullptr;
681*67e74705SXin Li 
682*67e74705SXin Li   // If this is a system #include, ignore the user #include locs.
683*67e74705SXin Li   unsigned i = isAngled ? AngledDirIdx : 0;
684*67e74705SXin Li 
685*67e74705SXin Li   // If this is a #include_next request, start searching after the directory the
686*67e74705SXin Li   // file was found in.
687*67e74705SXin Li   if (FromDir)
688*67e74705SXin Li     i = FromDir-&SearchDirs[0];
689*67e74705SXin Li 
690*67e74705SXin Li   // Cache all of the lookups performed by this method.  Many headers are
691*67e74705SXin Li   // multiply included, and the "pragma once" optimization prevents them from
692*67e74705SXin Li   // being relex/pp'd, but they would still have to search through a
693*67e74705SXin Li   // (potentially huge) series of SearchDirs to find it.
694*67e74705SXin Li   LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
695*67e74705SXin Li 
696*67e74705SXin Li   // If the entry has been previously looked up, the first value will be
697*67e74705SXin Li   // non-zero.  If the value is equal to i (the start point of our search), then
698*67e74705SXin Li   // this is a matching hit.
699*67e74705SXin Li   if (!SkipCache && CacheLookup.StartIdx == i+1) {
700*67e74705SXin Li     // Skip querying potentially lots of directories for this lookup.
701*67e74705SXin Li     i = CacheLookup.HitIdx;
702*67e74705SXin Li     if (CacheLookup.MappedName)
703*67e74705SXin Li       Filename = CacheLookup.MappedName;
704*67e74705SXin Li   } else {
705*67e74705SXin Li     // Otherwise, this is the first query, or the previous query didn't match
706*67e74705SXin Li     // our search start.  We will fill in our found location below, so prime the
707*67e74705SXin Li     // start point value.
708*67e74705SXin Li     CacheLookup.reset(/*StartIdx=*/i+1);
709*67e74705SXin Li   }
710*67e74705SXin Li 
711*67e74705SXin Li   SmallString<64> MappedName;
712*67e74705SXin Li 
713*67e74705SXin Li   // Check each directory in sequence to see if it contains this file.
714*67e74705SXin Li   for (; i != SearchDirs.size(); ++i) {
715*67e74705SXin Li     bool InUserSpecifiedSystemFramework = false;
716*67e74705SXin Li     bool HasBeenMapped = false;
717*67e74705SXin Li     const FileEntry *FE = SearchDirs[i].LookupFile(
718*67e74705SXin Li         Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
719*67e74705SXin Li         SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
720*67e74705SXin Li         MappedName);
721*67e74705SXin Li     if (HasBeenMapped) {
722*67e74705SXin Li       CacheLookup.MappedName =
723*67e74705SXin Li           copyString(Filename, LookupFileCache.getAllocator());
724*67e74705SXin Li     }
725*67e74705SXin Li     if (!FE) continue;
726*67e74705SXin Li 
727*67e74705SXin Li     CurDir = &SearchDirs[i];
728*67e74705SXin Li 
729*67e74705SXin Li     // This file is a system header or C++ unfriendly if the dir is.
730*67e74705SXin Li     HeaderFileInfo &HFI = getFileInfo(FE);
731*67e74705SXin Li     HFI.DirInfo = CurDir->getDirCharacteristic();
732*67e74705SXin Li 
733*67e74705SXin Li     // If the directory characteristic is User but this framework was
734*67e74705SXin Li     // user-specified to be treated as a system framework, promote the
735*67e74705SXin Li     // characteristic.
736*67e74705SXin Li     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
737*67e74705SXin Li       HFI.DirInfo = SrcMgr::C_System;
738*67e74705SXin Li 
739*67e74705SXin Li     // If the filename matches a known system header prefix, override
740*67e74705SXin Li     // whether the file is a system header.
741*67e74705SXin Li     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
742*67e74705SXin Li       if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
743*67e74705SXin Li         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
744*67e74705SXin Li                                                        : SrcMgr::C_User;
745*67e74705SXin Li         break;
746*67e74705SXin Li       }
747*67e74705SXin Li     }
748*67e74705SXin Li 
749*67e74705SXin Li     // If this file is found in a header map and uses the framework style of
750*67e74705SXin Li     // includes, then this header is part of a framework we're building.
751*67e74705SXin Li     if (CurDir->isIndexHeaderMap()) {
752*67e74705SXin Li       size_t SlashPos = Filename.find('/');
753*67e74705SXin Li       if (SlashPos != StringRef::npos) {
754*67e74705SXin Li         HFI.IndexHeaderMapHeader = 1;
755*67e74705SXin Li         HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
756*67e74705SXin Li                                                          SlashPos));
757*67e74705SXin Li       }
758*67e74705SXin Li     }
759*67e74705SXin Li 
760*67e74705SXin Li     if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
761*67e74705SXin Li       if (SuggestedModule)
762*67e74705SXin Li         *SuggestedModule = MSSuggestedModule;
763*67e74705SXin Li       return MSFE;
764*67e74705SXin Li     }
765*67e74705SXin Li 
766*67e74705SXin Li     // Remember this location for the next lookup we do.
767*67e74705SXin Li     CacheLookup.HitIdx = i;
768*67e74705SXin Li     return FE;
769*67e74705SXin Li   }
770*67e74705SXin Li 
771*67e74705SXin Li   // If we are including a file with a quoted include "foo.h" from inside
772*67e74705SXin Li   // a header in a framework that is currently being built, and we couldn't
773*67e74705SXin Li   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
774*67e74705SXin Li   // "Foo" is the name of the framework in which the including header was found.
775*67e74705SXin Li   if (!Includers.empty() && Includers.front().first && !isAngled &&
776*67e74705SXin Li       Filename.find('/') == StringRef::npos) {
777*67e74705SXin Li     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
778*67e74705SXin Li     if (IncludingHFI.IndexHeaderMapHeader) {
779*67e74705SXin Li       SmallString<128> ScratchFilename;
780*67e74705SXin Li       ScratchFilename += IncludingHFI.Framework;
781*67e74705SXin Li       ScratchFilename += '/';
782*67e74705SXin Li       ScratchFilename += Filename;
783*67e74705SXin Li 
784*67e74705SXin Li       const FileEntry *FE =
785*67e74705SXin Li           LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
786*67e74705SXin Li                      CurDir, Includers.front(), SearchPath, RelativePath,
787*67e74705SXin Li                      RequestingModule, SuggestedModule);
788*67e74705SXin Li 
789*67e74705SXin Li       if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
790*67e74705SXin Li         if (SuggestedModule)
791*67e74705SXin Li           *SuggestedModule = MSSuggestedModule;
792*67e74705SXin Li         return MSFE;
793*67e74705SXin Li       }
794*67e74705SXin Li 
795*67e74705SXin Li       LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
796*67e74705SXin Li       CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
797*67e74705SXin Li       // FIXME: SuggestedModule.
798*67e74705SXin Li       return FE;
799*67e74705SXin Li     }
800*67e74705SXin Li   }
801*67e74705SXin Li 
802*67e74705SXin Li   if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
803*67e74705SXin Li     if (SuggestedModule)
804*67e74705SXin Li       *SuggestedModule = MSSuggestedModule;
805*67e74705SXin Li     return MSFE;
806*67e74705SXin Li   }
807*67e74705SXin Li 
808*67e74705SXin Li   // Otherwise, didn't find it. Remember we didn't find this.
809*67e74705SXin Li   CacheLookup.HitIdx = SearchDirs.size();
810*67e74705SXin Li   return nullptr;
811*67e74705SXin Li }
812*67e74705SXin Li 
813*67e74705SXin Li /// LookupSubframeworkHeader - Look up a subframework for the specified
814*67e74705SXin Li /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
815*67e74705SXin Li /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
816*67e74705SXin Li /// is a subframework within Carbon.framework.  If so, return the FileEntry
817*67e74705SXin Li /// for the designated file, otherwise return null.
818*67e74705SXin Li const FileEntry *HeaderSearch::
LookupSubframeworkHeader(StringRef Filename,const FileEntry * ContextFileEnt,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule)819*67e74705SXin Li LookupSubframeworkHeader(StringRef Filename,
820*67e74705SXin Li                          const FileEntry *ContextFileEnt,
821*67e74705SXin Li                          SmallVectorImpl<char> *SearchPath,
822*67e74705SXin Li                          SmallVectorImpl<char> *RelativePath,
823*67e74705SXin Li                          Module *RequestingModule,
824*67e74705SXin Li                          ModuleMap::KnownHeader *SuggestedModule) {
825*67e74705SXin Li   assert(ContextFileEnt && "No context file?");
826*67e74705SXin Li 
827*67e74705SXin Li   // Framework names must have a '/' in the filename.  Find it.
828*67e74705SXin Li   // FIXME: Should we permit '\' on Windows?
829*67e74705SXin Li   size_t SlashPos = Filename.find('/');
830*67e74705SXin Li   if (SlashPos == StringRef::npos) return nullptr;
831*67e74705SXin Li 
832*67e74705SXin Li   // Look up the base framework name of the ContextFileEnt.
833*67e74705SXin Li   const char *ContextName = ContextFileEnt->getName();
834*67e74705SXin Li 
835*67e74705SXin Li   // If the context info wasn't a framework, couldn't be a subframework.
836*67e74705SXin Li   const unsigned DotFrameworkLen = 10;
837*67e74705SXin Li   const char *FrameworkPos = strstr(ContextName, ".framework");
838*67e74705SXin Li   if (FrameworkPos == nullptr ||
839*67e74705SXin Li       (FrameworkPos[DotFrameworkLen] != '/' &&
840*67e74705SXin Li        FrameworkPos[DotFrameworkLen] != '\\'))
841*67e74705SXin Li     return nullptr;
842*67e74705SXin Li 
843*67e74705SXin Li   SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
844*67e74705SXin Li 
845*67e74705SXin Li   // Append Frameworks/HIToolbox.framework/
846*67e74705SXin Li   FrameworkName += "Frameworks/";
847*67e74705SXin Li   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
848*67e74705SXin Li   FrameworkName += ".framework/";
849*67e74705SXin Li 
850*67e74705SXin Li   auto &CacheLookup =
851*67e74705SXin Li       *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
852*67e74705SXin Li                                           FrameworkCacheEntry())).first;
853*67e74705SXin Li 
854*67e74705SXin Li   // Some other location?
855*67e74705SXin Li   if (CacheLookup.second.Directory &&
856*67e74705SXin Li       CacheLookup.first().size() == FrameworkName.size() &&
857*67e74705SXin Li       memcmp(CacheLookup.first().data(), &FrameworkName[0],
858*67e74705SXin Li              CacheLookup.first().size()) != 0)
859*67e74705SXin Li     return nullptr;
860*67e74705SXin Li 
861*67e74705SXin Li   // Cache subframework.
862*67e74705SXin Li   if (!CacheLookup.second.Directory) {
863*67e74705SXin Li     ++NumSubFrameworkLookups;
864*67e74705SXin Li 
865*67e74705SXin Li     // If the framework dir doesn't exist, we fail.
866*67e74705SXin Li     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
867*67e74705SXin Li     if (!Dir) return nullptr;
868*67e74705SXin Li 
869*67e74705SXin Li     // Otherwise, if it does, remember that this is the right direntry for this
870*67e74705SXin Li     // framework.
871*67e74705SXin Li     CacheLookup.second.Directory = Dir;
872*67e74705SXin Li   }
873*67e74705SXin Li 
874*67e74705SXin Li   const FileEntry *FE = nullptr;
875*67e74705SXin Li 
876*67e74705SXin Li   if (RelativePath) {
877*67e74705SXin Li     RelativePath->clear();
878*67e74705SXin Li     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
879*67e74705SXin Li   }
880*67e74705SXin Li 
881*67e74705SXin Li   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
882*67e74705SXin Li   SmallString<1024> HeadersFilename(FrameworkName);
883*67e74705SXin Li   HeadersFilename += "Headers/";
884*67e74705SXin Li   if (SearchPath) {
885*67e74705SXin Li     SearchPath->clear();
886*67e74705SXin Li     // Without trailing '/'.
887*67e74705SXin Li     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
888*67e74705SXin Li   }
889*67e74705SXin Li 
890*67e74705SXin Li   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
891*67e74705SXin Li   if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
892*67e74705SXin Li 
893*67e74705SXin Li     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
894*67e74705SXin Li     HeadersFilename = FrameworkName;
895*67e74705SXin Li     HeadersFilename += "PrivateHeaders/";
896*67e74705SXin Li     if (SearchPath) {
897*67e74705SXin Li       SearchPath->clear();
898*67e74705SXin Li       // Without trailing '/'.
899*67e74705SXin Li       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
900*67e74705SXin Li     }
901*67e74705SXin Li 
902*67e74705SXin Li     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
903*67e74705SXin Li     if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
904*67e74705SXin Li       return nullptr;
905*67e74705SXin Li   }
906*67e74705SXin Li 
907*67e74705SXin Li   // This file is a system header or C++ unfriendly if the old file is.
908*67e74705SXin Li   //
909*67e74705SXin Li   // Note that the temporary 'DirInfo' is required here, as either call to
910*67e74705SXin Li   // getFileInfo could resize the vector and we don't want to rely on order
911*67e74705SXin Li   // of evaluation.
912*67e74705SXin Li   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
913*67e74705SXin Li   getFileInfo(FE).DirInfo = DirInfo;
914*67e74705SXin Li 
915*67e74705SXin Li   FrameworkName.pop_back(); // remove the trailing '/'
916*67e74705SXin Li   if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
917*67e74705SXin Li                                           SuggestedModule, /*IsSystem*/ false))
918*67e74705SXin Li     return nullptr;
919*67e74705SXin Li 
920*67e74705SXin Li   return FE;
921*67e74705SXin Li }
922*67e74705SXin Li 
923*67e74705SXin Li //===----------------------------------------------------------------------===//
924*67e74705SXin Li // File Info Management.
925*67e74705SXin Li //===----------------------------------------------------------------------===//
926*67e74705SXin Li 
927*67e74705SXin Li /// \brief Merge the header file info provided by \p OtherHFI into the current
928*67e74705SXin Li /// header file info (\p HFI)
mergeHeaderFileInfo(HeaderFileInfo & HFI,const HeaderFileInfo & OtherHFI)929*67e74705SXin Li static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
930*67e74705SXin Li                                 const HeaderFileInfo &OtherHFI) {
931*67e74705SXin Li   assert(OtherHFI.External && "expected to merge external HFI");
932*67e74705SXin Li 
933*67e74705SXin Li   HFI.isImport |= OtherHFI.isImport;
934*67e74705SXin Li   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
935*67e74705SXin Li   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
936*67e74705SXin Li   HFI.NumIncludes += OtherHFI.NumIncludes;
937*67e74705SXin Li 
938*67e74705SXin Li   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
939*67e74705SXin Li     HFI.ControllingMacro = OtherHFI.ControllingMacro;
940*67e74705SXin Li     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
941*67e74705SXin Li   }
942*67e74705SXin Li 
943*67e74705SXin Li   HFI.DirInfo = OtherHFI.DirInfo;
944*67e74705SXin Li   HFI.External = (!HFI.IsValid || HFI.External);
945*67e74705SXin Li   HFI.IsValid = true;
946*67e74705SXin Li   HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
947*67e74705SXin Li 
948*67e74705SXin Li   if (HFI.Framework.empty())
949*67e74705SXin Li     HFI.Framework = OtherHFI.Framework;
950*67e74705SXin Li }
951*67e74705SXin Li 
952*67e74705SXin Li /// getFileInfo - Return the HeaderFileInfo structure for the specified
953*67e74705SXin Li /// FileEntry.
getFileInfo(const FileEntry * FE)954*67e74705SXin Li HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
955*67e74705SXin Li   if (FE->getUID() >= FileInfo.size())
956*67e74705SXin Li     FileInfo.resize(FE->getUID() + 1);
957*67e74705SXin Li 
958*67e74705SXin Li   HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
959*67e74705SXin Li   // FIXME: Use a generation count to check whether this is really up to date.
960*67e74705SXin Li   if (ExternalSource && !HFI->Resolved) {
961*67e74705SXin Li     HFI->Resolved = true;
962*67e74705SXin Li     auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
963*67e74705SXin Li 
964*67e74705SXin Li     HFI = &FileInfo[FE->getUID()];
965*67e74705SXin Li     if (ExternalHFI.External)
966*67e74705SXin Li       mergeHeaderFileInfo(*HFI, ExternalHFI);
967*67e74705SXin Li   }
968*67e74705SXin Li 
969*67e74705SXin Li   HFI->IsValid = true;
970*67e74705SXin Li   // We have local information about this header file, so it's no longer
971*67e74705SXin Li   // strictly external.
972*67e74705SXin Li   HFI->External = false;
973*67e74705SXin Li   return *HFI;
974*67e74705SXin Li }
975*67e74705SXin Li 
976*67e74705SXin Li const HeaderFileInfo *
getExistingFileInfo(const FileEntry * FE,bool WantExternal) const977*67e74705SXin Li HeaderSearch::getExistingFileInfo(const FileEntry *FE,
978*67e74705SXin Li                                   bool WantExternal) const {
979*67e74705SXin Li   // If we have an external source, ensure we have the latest information.
980*67e74705SXin Li   // FIXME: Use a generation count to check whether this is really up to date.
981*67e74705SXin Li   HeaderFileInfo *HFI;
982*67e74705SXin Li   if (ExternalSource) {
983*67e74705SXin Li     if (FE->getUID() >= FileInfo.size()) {
984*67e74705SXin Li       if (!WantExternal)
985*67e74705SXin Li         return nullptr;
986*67e74705SXin Li       FileInfo.resize(FE->getUID() + 1);
987*67e74705SXin Li     }
988*67e74705SXin Li 
989*67e74705SXin Li     HFI = &FileInfo[FE->getUID()];
990*67e74705SXin Li     if (!WantExternal && (!HFI->IsValid || HFI->External))
991*67e74705SXin Li       return nullptr;
992*67e74705SXin Li     if (!HFI->Resolved) {
993*67e74705SXin Li       HFI->Resolved = true;
994*67e74705SXin Li       auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
995*67e74705SXin Li 
996*67e74705SXin Li       HFI = &FileInfo[FE->getUID()];
997*67e74705SXin Li       if (ExternalHFI.External)
998*67e74705SXin Li         mergeHeaderFileInfo(*HFI, ExternalHFI);
999*67e74705SXin Li     }
1000*67e74705SXin Li   } else if (FE->getUID() >= FileInfo.size()) {
1001*67e74705SXin Li     return nullptr;
1002*67e74705SXin Li   } else {
1003*67e74705SXin Li     HFI = &FileInfo[FE->getUID()];
1004*67e74705SXin Li   }
1005*67e74705SXin Li 
1006*67e74705SXin Li   if (!HFI->IsValid || (HFI->External && !WantExternal))
1007*67e74705SXin Li     return nullptr;
1008*67e74705SXin Li 
1009*67e74705SXin Li   return HFI;
1010*67e74705SXin Li }
1011*67e74705SXin Li 
isFileMultipleIncludeGuarded(const FileEntry * File)1012*67e74705SXin Li bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1013*67e74705SXin Li   // Check if we've ever seen this file as a header.
1014*67e74705SXin Li   if (auto *HFI = getExistingFileInfo(File))
1015*67e74705SXin Li     return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1016*67e74705SXin Li            HFI->ControllingMacroID;
1017*67e74705SXin Li   return false;
1018*67e74705SXin Li }
1019*67e74705SXin Li 
MarkFileModuleHeader(const FileEntry * FE,ModuleMap::ModuleHeaderRole Role,bool isCompilingModuleHeader)1020*67e74705SXin Li void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1021*67e74705SXin Li                                         ModuleMap::ModuleHeaderRole Role,
1022*67e74705SXin Li                                         bool isCompilingModuleHeader) {
1023*67e74705SXin Li   bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1024*67e74705SXin Li 
1025*67e74705SXin Li   // Don't mark the file info as non-external if there's nothing to change.
1026*67e74705SXin Li   if (!isCompilingModuleHeader) {
1027*67e74705SXin Li     if (!isModularHeader)
1028*67e74705SXin Li       return;
1029*67e74705SXin Li     auto *HFI = getExistingFileInfo(FE);
1030*67e74705SXin Li     if (HFI && HFI->isModuleHeader)
1031*67e74705SXin Li       return;
1032*67e74705SXin Li   }
1033*67e74705SXin Li 
1034*67e74705SXin Li   auto &HFI = getFileInfo(FE);
1035*67e74705SXin Li   HFI.isModuleHeader |= isModularHeader;
1036*67e74705SXin Li   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1037*67e74705SXin Li }
1038*67e74705SXin Li 
ShouldEnterIncludeFile(Preprocessor & PP,const FileEntry * File,bool isImport,Module * M)1039*67e74705SXin Li bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1040*67e74705SXin Li                                           const FileEntry *File,
1041*67e74705SXin Li                                           bool isImport, Module *M) {
1042*67e74705SXin Li   ++NumIncluded; // Count # of attempted #includes.
1043*67e74705SXin Li 
1044*67e74705SXin Li   // Get information about this file.
1045*67e74705SXin Li   HeaderFileInfo &FileInfo = getFileInfo(File);
1046*67e74705SXin Li 
1047*67e74705SXin Li   // If this is a #import directive, check that we have not already imported
1048*67e74705SXin Li   // this header.
1049*67e74705SXin Li   if (isImport) {
1050*67e74705SXin Li     // If this has already been imported, don't import it again.
1051*67e74705SXin Li     FileInfo.isImport = true;
1052*67e74705SXin Li 
1053*67e74705SXin Li     // Has this already been #import'ed or #include'd?
1054*67e74705SXin Li     if (FileInfo.NumIncludes) return false;
1055*67e74705SXin Li   } else {
1056*67e74705SXin Li     // Otherwise, if this is a #include of a file that was previously #import'd
1057*67e74705SXin Li     // or if this is the second #include of a #pragma once file, ignore it.
1058*67e74705SXin Li     if (FileInfo.isImport)
1059*67e74705SXin Li       return false;
1060*67e74705SXin Li   }
1061*67e74705SXin Li 
1062*67e74705SXin Li   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
1063*67e74705SXin Li   // if the macro that guards it is defined, we know the #include has no effect.
1064*67e74705SXin Li   if (const IdentifierInfo *ControllingMacro
1065*67e74705SXin Li       = FileInfo.getControllingMacro(ExternalLookup)) {
1066*67e74705SXin Li     // If the header corresponds to a module, check whether the macro is already
1067*67e74705SXin Li     // defined in that module rather than checking in the current set of visible
1068*67e74705SXin Li     // modules.
1069*67e74705SXin Li     if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1070*67e74705SXin Li           : PP.isMacroDefined(ControllingMacro)) {
1071*67e74705SXin Li       ++NumMultiIncludeFileOptzn;
1072*67e74705SXin Li       return false;
1073*67e74705SXin Li     }
1074*67e74705SXin Li   }
1075*67e74705SXin Li 
1076*67e74705SXin Li   // Increment the number of times this file has been included.
1077*67e74705SXin Li   ++FileInfo.NumIncludes;
1078*67e74705SXin Li 
1079*67e74705SXin Li   return true;
1080*67e74705SXin Li }
1081*67e74705SXin Li 
getTotalMemory() const1082*67e74705SXin Li size_t HeaderSearch::getTotalMemory() const {
1083*67e74705SXin Li   return SearchDirs.capacity()
1084*67e74705SXin Li     + llvm::capacity_in_bytes(FileInfo)
1085*67e74705SXin Li     + llvm::capacity_in_bytes(HeaderMaps)
1086*67e74705SXin Li     + LookupFileCache.getAllocator().getTotalMemory()
1087*67e74705SXin Li     + FrameworkMap.getAllocator().getTotalMemory();
1088*67e74705SXin Li }
1089*67e74705SXin Li 
getUniqueFrameworkName(StringRef Framework)1090*67e74705SXin Li StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1091*67e74705SXin Li   return FrameworkNames.insert(Framework).first->first();
1092*67e74705SXin Li }
1093*67e74705SXin Li 
hasModuleMap(StringRef FileName,const DirectoryEntry * Root,bool IsSystem)1094*67e74705SXin Li bool HeaderSearch::hasModuleMap(StringRef FileName,
1095*67e74705SXin Li                                 const DirectoryEntry *Root,
1096*67e74705SXin Li                                 bool IsSystem) {
1097*67e74705SXin Li   if (!HSOpts->ImplicitModuleMaps)
1098*67e74705SXin Li     return false;
1099*67e74705SXin Li 
1100*67e74705SXin Li   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1101*67e74705SXin Li 
1102*67e74705SXin Li   StringRef DirName = FileName;
1103*67e74705SXin Li   do {
1104*67e74705SXin Li     // Get the parent directory name.
1105*67e74705SXin Li     DirName = llvm::sys::path::parent_path(DirName);
1106*67e74705SXin Li     if (DirName.empty())
1107*67e74705SXin Li       return false;
1108*67e74705SXin Li 
1109*67e74705SXin Li     // Determine whether this directory exists.
1110*67e74705SXin Li     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1111*67e74705SXin Li     if (!Dir)
1112*67e74705SXin Li       return false;
1113*67e74705SXin Li 
1114*67e74705SXin Li     // Try to load the module map file in this directory.
1115*67e74705SXin Li     switch (loadModuleMapFile(Dir, IsSystem,
1116*67e74705SXin Li                               llvm::sys::path::extension(Dir->getName()) ==
1117*67e74705SXin Li                                   ".framework")) {
1118*67e74705SXin Li     case LMM_NewlyLoaded:
1119*67e74705SXin Li     case LMM_AlreadyLoaded:
1120*67e74705SXin Li       // Success. All of the directories we stepped through inherit this module
1121*67e74705SXin Li       // map file.
1122*67e74705SXin Li       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1123*67e74705SXin Li         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1124*67e74705SXin Li       return true;
1125*67e74705SXin Li 
1126*67e74705SXin Li     case LMM_NoDirectory:
1127*67e74705SXin Li     case LMM_InvalidModuleMap:
1128*67e74705SXin Li       break;
1129*67e74705SXin Li     }
1130*67e74705SXin Li 
1131*67e74705SXin Li     // If we hit the top of our search, we're done.
1132*67e74705SXin Li     if (Dir == Root)
1133*67e74705SXin Li       return false;
1134*67e74705SXin Li 
1135*67e74705SXin Li     // Keep track of all of the directories we checked, so we can mark them as
1136*67e74705SXin Li     // having module maps if we eventually do find a module map.
1137*67e74705SXin Li     FixUpDirectories.push_back(Dir);
1138*67e74705SXin Li   } while (true);
1139*67e74705SXin Li }
1140*67e74705SXin Li 
1141*67e74705SXin Li ModuleMap::KnownHeader
findModuleForHeader(const FileEntry * File) const1142*67e74705SXin Li HeaderSearch::findModuleForHeader(const FileEntry *File) const {
1143*67e74705SXin Li   if (ExternalSource) {
1144*67e74705SXin Li     // Make sure the external source has handled header info about this file,
1145*67e74705SXin Li     // which includes whether the file is part of a module.
1146*67e74705SXin Li     (void)getExistingFileInfo(File);
1147*67e74705SXin Li   }
1148*67e74705SXin Li   return ModMap.findModuleForHeader(File);
1149*67e74705SXin Li }
1150*67e74705SXin Li 
findUsableModuleForHeader(const FileEntry * File,const DirectoryEntry * Root,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool IsSystemHeaderDir)1151*67e74705SXin Li bool HeaderSearch::findUsableModuleForHeader(
1152*67e74705SXin Li     const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1153*67e74705SXin Li     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1154*67e74705SXin Li   if (File && SuggestedModule) {
1155*67e74705SXin Li     // If there is a module that corresponds to this header, suggest it.
1156*67e74705SXin Li     hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1157*67e74705SXin Li     *SuggestedModule = findModuleForHeader(File);
1158*67e74705SXin Li   }
1159*67e74705SXin Li   return true;
1160*67e74705SXin Li }
1161*67e74705SXin Li 
findUsableModuleForFrameworkHeader(const FileEntry * File,StringRef FrameworkName,Module * RequestingModule,ModuleMap::KnownHeader * SuggestedModule,bool IsSystemFramework)1162*67e74705SXin Li bool HeaderSearch::findUsableModuleForFrameworkHeader(
1163*67e74705SXin Li     const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1164*67e74705SXin Li     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1165*67e74705SXin Li   // If we're supposed to suggest a module, look for one now.
1166*67e74705SXin Li   if (SuggestedModule) {
1167*67e74705SXin Li     // Find the top-level framework based on this framework.
1168*67e74705SXin Li     SmallVector<std::string, 4> SubmodulePath;
1169*67e74705SXin Li     const DirectoryEntry *TopFrameworkDir
1170*67e74705SXin Li       = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1171*67e74705SXin Li 
1172*67e74705SXin Li     // Determine the name of the top-level framework.
1173*67e74705SXin Li     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1174*67e74705SXin Li 
1175*67e74705SXin Li     // Load this framework module. If that succeeds, find the suggested module
1176*67e74705SXin Li     // for this header, if any.
1177*67e74705SXin Li     loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1178*67e74705SXin Li 
1179*67e74705SXin Li     // FIXME: This can find a module not part of ModuleName, which is
1180*67e74705SXin Li     // important so that we're consistent about whether this header
1181*67e74705SXin Li     // corresponds to a module. Possibly we should lock down framework modules
1182*67e74705SXin Li     // so that this is not possible.
1183*67e74705SXin Li     *SuggestedModule = findModuleForHeader(File);
1184*67e74705SXin Li   }
1185*67e74705SXin Li   return true;
1186*67e74705SXin Li }
1187*67e74705SXin Li 
getPrivateModuleMap(const FileEntry * File,FileManager & FileMgr)1188*67e74705SXin Li static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1189*67e74705SXin Li                                             FileManager &FileMgr) {
1190*67e74705SXin Li   StringRef Filename = llvm::sys::path::filename(File->getName());
1191*67e74705SXin Li   SmallString<128>  PrivateFilename(File->getDir()->getName());
1192*67e74705SXin Li   if (Filename == "module.map")
1193*67e74705SXin Li     llvm::sys::path::append(PrivateFilename, "module_private.map");
1194*67e74705SXin Li   else if (Filename == "module.modulemap")
1195*67e74705SXin Li     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1196*67e74705SXin Li   else
1197*67e74705SXin Li     return nullptr;
1198*67e74705SXin Li   return FileMgr.getFile(PrivateFilename);
1199*67e74705SXin Li }
1200*67e74705SXin Li 
loadModuleMapFile(const FileEntry * File,bool IsSystem)1201*67e74705SXin Li bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1202*67e74705SXin Li   // Find the directory for the module. For frameworks, that may require going
1203*67e74705SXin Li   // up from the 'Modules' directory.
1204*67e74705SXin Li   const DirectoryEntry *Dir = nullptr;
1205*67e74705SXin Li   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1206*67e74705SXin Li     Dir = FileMgr.getDirectory(".");
1207*67e74705SXin Li   else {
1208*67e74705SXin Li     Dir = File->getDir();
1209*67e74705SXin Li     StringRef DirName(Dir->getName());
1210*67e74705SXin Li     if (llvm::sys::path::filename(DirName) == "Modules") {
1211*67e74705SXin Li       DirName = llvm::sys::path::parent_path(DirName);
1212*67e74705SXin Li       if (DirName.endswith(".framework"))
1213*67e74705SXin Li         Dir = FileMgr.getDirectory(DirName);
1214*67e74705SXin Li       // FIXME: This assert can fail if there's a race between the above check
1215*67e74705SXin Li       // and the removal of the directory.
1216*67e74705SXin Li       assert(Dir && "parent must exist");
1217*67e74705SXin Li     }
1218*67e74705SXin Li   }
1219*67e74705SXin Li 
1220*67e74705SXin Li   switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
1221*67e74705SXin Li   case LMM_AlreadyLoaded:
1222*67e74705SXin Li   case LMM_NewlyLoaded:
1223*67e74705SXin Li     return false;
1224*67e74705SXin Li   case LMM_NoDirectory:
1225*67e74705SXin Li   case LMM_InvalidModuleMap:
1226*67e74705SXin Li     return true;
1227*67e74705SXin Li   }
1228*67e74705SXin Li   llvm_unreachable("Unknown load module map result");
1229*67e74705SXin Li }
1230*67e74705SXin Li 
1231*67e74705SXin Li HeaderSearch::LoadModuleMapResult
loadModuleMapFileImpl(const FileEntry * File,bool IsSystem,const DirectoryEntry * Dir)1232*67e74705SXin Li HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1233*67e74705SXin Li                                     const DirectoryEntry *Dir) {
1234*67e74705SXin Li   assert(File && "expected FileEntry");
1235*67e74705SXin Li 
1236*67e74705SXin Li   // Check whether we've already loaded this module map, and mark it as being
1237*67e74705SXin Li   // loaded in case we recursively try to load it from itself.
1238*67e74705SXin Li   auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1239*67e74705SXin Li   if (!AddResult.second)
1240*67e74705SXin Li     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1241*67e74705SXin Li 
1242*67e74705SXin Li   if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
1243*67e74705SXin Li     LoadedModuleMaps[File] = false;
1244*67e74705SXin Li     return LMM_InvalidModuleMap;
1245*67e74705SXin Li   }
1246*67e74705SXin Li 
1247*67e74705SXin Li   // Try to load a corresponding private module map.
1248*67e74705SXin Li   if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1249*67e74705SXin Li     if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1250*67e74705SXin Li       LoadedModuleMaps[File] = false;
1251*67e74705SXin Li       return LMM_InvalidModuleMap;
1252*67e74705SXin Li     }
1253*67e74705SXin Li   }
1254*67e74705SXin Li 
1255*67e74705SXin Li   // This directory has a module map.
1256*67e74705SXin Li   return LMM_NewlyLoaded;
1257*67e74705SXin Li }
1258*67e74705SXin Li 
1259*67e74705SXin Li const FileEntry *
lookupModuleMapFile(const DirectoryEntry * Dir,bool IsFramework)1260*67e74705SXin Li HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1261*67e74705SXin Li   if (!HSOpts->ImplicitModuleMaps)
1262*67e74705SXin Li     return nullptr;
1263*67e74705SXin Li   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1264*67e74705SXin Li   // module.map at the framework root is also accepted.
1265*67e74705SXin Li   SmallString<128> ModuleMapFileName(Dir->getName());
1266*67e74705SXin Li   if (IsFramework)
1267*67e74705SXin Li     llvm::sys::path::append(ModuleMapFileName, "Modules");
1268*67e74705SXin Li   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1269*67e74705SXin Li   if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1270*67e74705SXin Li     return F;
1271*67e74705SXin Li 
1272*67e74705SXin Li   // Continue to allow module.map
1273*67e74705SXin Li   ModuleMapFileName = Dir->getName();
1274*67e74705SXin Li   llvm::sys::path::append(ModuleMapFileName, "module.map");
1275*67e74705SXin Li   return FileMgr.getFile(ModuleMapFileName);
1276*67e74705SXin Li }
1277*67e74705SXin Li 
loadFrameworkModule(StringRef Name,const DirectoryEntry * Dir,bool IsSystem)1278*67e74705SXin Li Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1279*67e74705SXin Li                                           const DirectoryEntry *Dir,
1280*67e74705SXin Li                                           bool IsSystem) {
1281*67e74705SXin Li   if (Module *Module = ModMap.findModule(Name))
1282*67e74705SXin Li     return Module;
1283*67e74705SXin Li 
1284*67e74705SXin Li   // Try to load a module map file.
1285*67e74705SXin Li   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1286*67e74705SXin Li   case LMM_InvalidModuleMap:
1287*67e74705SXin Li     // Try to infer a module map from the framework directory.
1288*67e74705SXin Li     if (HSOpts->ImplicitModuleMaps)
1289*67e74705SXin Li       ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1290*67e74705SXin Li     break;
1291*67e74705SXin Li 
1292*67e74705SXin Li   case LMM_AlreadyLoaded:
1293*67e74705SXin Li   case LMM_NoDirectory:
1294*67e74705SXin Li     return nullptr;
1295*67e74705SXin Li 
1296*67e74705SXin Li   case LMM_NewlyLoaded:
1297*67e74705SXin Li     break;
1298*67e74705SXin Li   }
1299*67e74705SXin Li 
1300*67e74705SXin Li   return ModMap.findModule(Name);
1301*67e74705SXin Li }
1302*67e74705SXin Li 
1303*67e74705SXin Li 
1304*67e74705SXin Li HeaderSearch::LoadModuleMapResult
loadModuleMapFile(StringRef DirName,bool IsSystem,bool IsFramework)1305*67e74705SXin Li HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1306*67e74705SXin Li                                 bool IsFramework) {
1307*67e74705SXin Li   if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1308*67e74705SXin Li     return loadModuleMapFile(Dir, IsSystem, IsFramework);
1309*67e74705SXin Li 
1310*67e74705SXin Li   return LMM_NoDirectory;
1311*67e74705SXin Li }
1312*67e74705SXin Li 
1313*67e74705SXin Li HeaderSearch::LoadModuleMapResult
loadModuleMapFile(const DirectoryEntry * Dir,bool IsSystem,bool IsFramework)1314*67e74705SXin Li HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1315*67e74705SXin Li                                 bool IsFramework) {
1316*67e74705SXin Li   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1317*67e74705SXin Li   if (KnownDir != DirectoryHasModuleMap.end())
1318*67e74705SXin Li     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1319*67e74705SXin Li 
1320*67e74705SXin Li   if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1321*67e74705SXin Li     LoadModuleMapResult Result =
1322*67e74705SXin Li         loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1323*67e74705SXin Li     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1324*67e74705SXin Li     // E.g. Foo.framework/Modules/module.modulemap
1325*67e74705SXin Li     //      ^Dir                  ^ModuleMapFile
1326*67e74705SXin Li     if (Result == LMM_NewlyLoaded)
1327*67e74705SXin Li       DirectoryHasModuleMap[Dir] = true;
1328*67e74705SXin Li     else if (Result == LMM_InvalidModuleMap)
1329*67e74705SXin Li       DirectoryHasModuleMap[Dir] = false;
1330*67e74705SXin Li     return Result;
1331*67e74705SXin Li   }
1332*67e74705SXin Li   return LMM_InvalidModuleMap;
1333*67e74705SXin Li }
1334*67e74705SXin Li 
collectAllModules(SmallVectorImpl<Module * > & Modules)1335*67e74705SXin Li void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1336*67e74705SXin Li   Modules.clear();
1337*67e74705SXin Li 
1338*67e74705SXin Li   if (HSOpts->ImplicitModuleMaps) {
1339*67e74705SXin Li     // Load module maps for each of the header search directories.
1340*67e74705SXin Li     for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1341*67e74705SXin Li       bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1342*67e74705SXin Li       if (SearchDirs[Idx].isFramework()) {
1343*67e74705SXin Li         std::error_code EC;
1344*67e74705SXin Li         SmallString<128> DirNative;
1345*67e74705SXin Li         llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1346*67e74705SXin Li                                 DirNative);
1347*67e74705SXin Li 
1348*67e74705SXin Li         // Search each of the ".framework" directories to load them as modules.
1349*67e74705SXin Li         vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1350*67e74705SXin Li         for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1351*67e74705SXin Li              Dir != DirEnd && !EC; Dir.increment(EC)) {
1352*67e74705SXin Li           if (llvm::sys::path::extension(Dir->getName()) != ".framework")
1353*67e74705SXin Li             continue;
1354*67e74705SXin Li 
1355*67e74705SXin Li           const DirectoryEntry *FrameworkDir =
1356*67e74705SXin Li               FileMgr.getDirectory(Dir->getName());
1357*67e74705SXin Li           if (!FrameworkDir)
1358*67e74705SXin Li             continue;
1359*67e74705SXin Li 
1360*67e74705SXin Li           // Load this framework module.
1361*67e74705SXin Li           loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1362*67e74705SXin Li                               FrameworkDir, IsSystem);
1363*67e74705SXin Li         }
1364*67e74705SXin Li         continue;
1365*67e74705SXin Li       }
1366*67e74705SXin Li 
1367*67e74705SXin Li       // FIXME: Deal with header maps.
1368*67e74705SXin Li       if (SearchDirs[Idx].isHeaderMap())
1369*67e74705SXin Li         continue;
1370*67e74705SXin Li 
1371*67e74705SXin Li       // Try to load a module map file for the search directory.
1372*67e74705SXin Li       loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1373*67e74705SXin Li                         /*IsFramework*/ false);
1374*67e74705SXin Li 
1375*67e74705SXin Li       // Try to load module map files for immediate subdirectories of this
1376*67e74705SXin Li       // search directory.
1377*67e74705SXin Li       loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1378*67e74705SXin Li     }
1379*67e74705SXin Li   }
1380*67e74705SXin Li 
1381*67e74705SXin Li   // Populate the list of modules.
1382*67e74705SXin Li   for (ModuleMap::module_iterator M = ModMap.module_begin(),
1383*67e74705SXin Li                                MEnd = ModMap.module_end();
1384*67e74705SXin Li        M != MEnd; ++M) {
1385*67e74705SXin Li     Modules.push_back(M->getValue());
1386*67e74705SXin Li   }
1387*67e74705SXin Li }
1388*67e74705SXin Li 
loadTopLevelSystemModules()1389*67e74705SXin Li void HeaderSearch::loadTopLevelSystemModules() {
1390*67e74705SXin Li   if (!HSOpts->ImplicitModuleMaps)
1391*67e74705SXin Li     return;
1392*67e74705SXin Li 
1393*67e74705SXin Li   // Load module maps for each of the header search directories.
1394*67e74705SXin Li   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1395*67e74705SXin Li     // We only care about normal header directories.
1396*67e74705SXin Li     if (!SearchDirs[Idx].isNormalDir()) {
1397*67e74705SXin Li       continue;
1398*67e74705SXin Li     }
1399*67e74705SXin Li 
1400*67e74705SXin Li     // Try to load a module map file for the search directory.
1401*67e74705SXin Li     loadModuleMapFile(SearchDirs[Idx].getDir(),
1402*67e74705SXin Li                       SearchDirs[Idx].isSystemHeaderDirectory(),
1403*67e74705SXin Li                       SearchDirs[Idx].isFramework());
1404*67e74705SXin Li   }
1405*67e74705SXin Li }
1406*67e74705SXin Li 
loadSubdirectoryModuleMaps(DirectoryLookup & SearchDir)1407*67e74705SXin Li void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1408*67e74705SXin Li   assert(HSOpts->ImplicitModuleMaps &&
1409*67e74705SXin Li          "Should not be loading subdirectory module maps");
1410*67e74705SXin Li 
1411*67e74705SXin Li   if (SearchDir.haveSearchedAllModuleMaps())
1412*67e74705SXin Li     return;
1413*67e74705SXin Li 
1414*67e74705SXin Li   std::error_code EC;
1415*67e74705SXin Li   SmallString<128> DirNative;
1416*67e74705SXin Li   llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1417*67e74705SXin Li   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1418*67e74705SXin Li   for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1419*67e74705SXin Li        Dir != DirEnd && !EC; Dir.increment(EC)) {
1420*67e74705SXin Li     bool IsFramework =
1421*67e74705SXin Li         llvm::sys::path::extension(Dir->getName()) == ".framework";
1422*67e74705SXin Li     if (IsFramework == SearchDir.isFramework())
1423*67e74705SXin Li       loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
1424*67e74705SXin Li                         SearchDir.isFramework());
1425*67e74705SXin Li   }
1426*67e74705SXin Li 
1427*67e74705SXin Li   SearchDir.setSearchedAllModuleMaps(true);
1428*67e74705SXin Li }
1429*67e74705SXin Li 
suggestPathToFileForDiagnostics(const FileEntry * File,bool * IsSystem)1430*67e74705SXin Li std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1431*67e74705SXin Li                                                           bool *IsSystem) {
1432*67e74705SXin Li   // FIXME: We assume that the path name currently cached in the FileEntry is
1433*67e74705SXin Li   // the most appropriate one for this analysis (and that it's spelled the same
1434*67e74705SXin Li   // way as the corresponding header search path).
1435*67e74705SXin Li   const char *Name = File->getName();
1436*67e74705SXin Li 
1437*67e74705SXin Li   unsigned BestPrefixLength = 0;
1438*67e74705SXin Li   unsigned BestSearchDir;
1439*67e74705SXin Li 
1440*67e74705SXin Li   for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1441*67e74705SXin Li     // FIXME: Support this search within frameworks and header maps.
1442*67e74705SXin Li     if (!SearchDirs[I].isNormalDir())
1443*67e74705SXin Li       continue;
1444*67e74705SXin Li 
1445*67e74705SXin Li     const char *Dir = SearchDirs[I].getDir()->getName();
1446*67e74705SXin Li     for (auto NI = llvm::sys::path::begin(Name),
1447*67e74705SXin Li               NE = llvm::sys::path::end(Name),
1448*67e74705SXin Li               DI = llvm::sys::path::begin(Dir),
1449*67e74705SXin Li               DE = llvm::sys::path::end(Dir);
1450*67e74705SXin Li          /*termination condition in loop*/; ++NI, ++DI) {
1451*67e74705SXin Li       // '.' components in Name are ignored.
1452*67e74705SXin Li       while (NI != NE && *NI == ".")
1453*67e74705SXin Li         ++NI;
1454*67e74705SXin Li       if (NI == NE)
1455*67e74705SXin Li         break;
1456*67e74705SXin Li 
1457*67e74705SXin Li       // '.' components in Dir are ignored.
1458*67e74705SXin Li       while (DI != DE && *DI == ".")
1459*67e74705SXin Li         ++DI;
1460*67e74705SXin Li       if (DI == DE) {
1461*67e74705SXin Li         // Dir is a prefix of Name, up to '.' components and choice of path
1462*67e74705SXin Li         // separators.
1463*67e74705SXin Li         unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1464*67e74705SXin Li         if (PrefixLength > BestPrefixLength) {
1465*67e74705SXin Li           BestPrefixLength = PrefixLength;
1466*67e74705SXin Li           BestSearchDir = I;
1467*67e74705SXin Li         }
1468*67e74705SXin Li         break;
1469*67e74705SXin Li       }
1470*67e74705SXin Li 
1471*67e74705SXin Li       if (*NI != *DI)
1472*67e74705SXin Li         break;
1473*67e74705SXin Li     }
1474*67e74705SXin Li   }
1475*67e74705SXin Li 
1476*67e74705SXin Li   if (IsSystem)
1477*67e74705SXin Li     *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1478*67e74705SXin Li   return Name + BestPrefixLength;
1479*67e74705SXin Li }
1480