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