1 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the DirectoryLookup and HeaderSearch interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/HeaderSearch.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Lex/HeaderMap.h"
18 #include "clang/Lex/HeaderSearchOptions.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/Lexer.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/Capacity.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <cstdio>
27 #if defined(LLVM_ON_UNIX)
28 #include <limits.h>
29 #endif
30 using namespace clang;
31 
32 const IdentifierInfo *
33 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
34   if (ControllingMacro)
35     return ControllingMacro;
36 
37   if (!ControllingMacroID || !External)
38     return 0;
39 
40   ControllingMacro = External->GetIdentifier(ControllingMacroID);
41   return ControllingMacro;
42 }
43 
44 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
45 
46 HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
47                            SourceManager &SourceMgr, DiagnosticsEngine &Diags,
48                            const LangOptions &LangOpts,
49                            const TargetInfo *Target)
50     : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
51       FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
52   AngledDirIdx = 0;
53   SystemDirIdx = 0;
54   NoCurDirSearch = false;
55 
56   ExternalLookup = 0;
57   ExternalSource = 0;
58   NumIncluded = 0;
59   NumMultiIncludeFileOptzn = 0;
60   NumFrameworkLookups = NumSubFrameworkLookups = 0;
61 
62   EnabledModules = LangOpts.Modules;
63 }
64 
65 HeaderSearch::~HeaderSearch() {
66   // Delete headermaps.
67   for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
68     delete HeaderMaps[i].second;
69 }
70 
71 void HeaderSearch::PrintStats() {
72   fprintf(stderr, "\n*** HeaderSearch Stats:\n");
73   fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
74   unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
75   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
76     NumOnceOnlyFiles += FileInfo[i].isImport;
77     if (MaxNumIncludes < FileInfo[i].NumIncludes)
78       MaxNumIncludes = FileInfo[i].NumIncludes;
79     NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
80   }
81   fprintf(stderr, "  %d #import/#pragma once files.\n", NumOnceOnlyFiles);
82   fprintf(stderr, "  %d included exactly once.\n", NumSingleIncludedFiles);
83   fprintf(stderr, "  %d max times a file is included.\n", MaxNumIncludes);
84 
85   fprintf(stderr, "  %d #include/#include_next/#import.\n", NumIncluded);
86   fprintf(stderr, "    %d #includes skipped due to"
87           " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
88 
89   fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
90   fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
91 }
92 
93 /// CreateHeaderMap - This method returns a HeaderMap for the specified
94 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
95 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
96   // We expect the number of headermaps to be small, and almost always empty.
97   // If it ever grows, use of a linear search should be re-evaluated.
98   if (!HeaderMaps.empty()) {
99     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
100       // Pointer equality comparison of FileEntries works because they are
101       // already uniqued by inode.
102       if (HeaderMaps[i].first == FE)
103         return HeaderMaps[i].second;
104   }
105 
106   if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
107     HeaderMaps.push_back(std::make_pair(FE, HM));
108     return HM;
109   }
110 
111   return 0;
112 }
113 
114 std::string HeaderSearch::getModuleFileName(Module *Module) {
115   // If we don't have a module cache path, we can't do anything.
116   if (ModuleCachePath.empty())
117     return std::string();
118 
119 
120   SmallString<256> Result(ModuleCachePath);
121   llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
122   return Result.str().str();
123 }
124 
125 std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
126   // If we don't have a module cache path, we can't do anything.
127   if (ModuleCachePath.empty())
128     return std::string();
129 
130 
131   SmallString<256> Result(ModuleCachePath);
132   llvm::sys::path::append(Result, ModuleName + ".pcm");
133   return Result.str().str();
134 }
135 
136 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
137   // Look in the module map to determine if there is a module by this name.
138   Module *Module = ModMap.findModule(ModuleName);
139   if (Module || !AllowSearch)
140     return Module;
141 
142   // Look through the various header search paths to load any available module
143   // maps, searching for a module map that describes this module.
144   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
145     if (SearchDirs[Idx].isFramework()) {
146       // Search for or infer a module map for a framework.
147       SmallString<128> FrameworkDirName;
148       FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
149       llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
150       if (const DirectoryEntry *FrameworkDir
151             = FileMgr.getDirectory(FrameworkDirName)) {
152         bool IsSystem
153           = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
154         Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
155         if (Module)
156           break;
157       }
158     }
159 
160     // FIXME: Figure out how header maps and module maps will work together.
161 
162     // Only deal with normal search directories.
163     if (!SearchDirs[Idx].isNormalDir())
164       continue;
165 
166     bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
167     // Search for a module map file in this directory.
168     if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem)
169           == LMM_NewlyLoaded) {
170       // We just loaded a module map file; check whether the module is
171       // available now.
172       Module = ModMap.findModule(ModuleName);
173       if (Module)
174         break;
175     }
176 
177     // Search for a module map in a subdirectory with the same name as the
178     // module.
179     SmallString<128> NestedModuleMapDirName;
180     NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
181     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
182     if (loadModuleMapFile(NestedModuleMapDirName, IsSystem) == LMM_NewlyLoaded){
183       // If we just loaded a module map file, look for the module again.
184       Module = ModMap.findModule(ModuleName);
185       if (Module)
186         break;
187     }
188 
189     // If we've already performed the exhaustive search for module maps in this
190     // search directory, don't do it again.
191     if (SearchDirs[Idx].haveSearchedAllModuleMaps())
192       continue;
193 
194     // Load all module maps in the immediate subdirectories of this search
195     // directory.
196     loadSubdirectoryModuleMaps(SearchDirs[Idx]);
197 
198     // Look again for the module.
199     Module = ModMap.findModule(ModuleName);
200     if (Module)
201       break;
202   }
203 
204   return Module;
205 }
206 
207 //===----------------------------------------------------------------------===//
208 // File lookup within a DirectoryLookup scope
209 //===----------------------------------------------------------------------===//
210 
211 /// getName - Return the directory or filename corresponding to this lookup
212 /// object.
213 const char *DirectoryLookup::getName() const {
214   if (isNormalDir())
215     return getDir()->getName();
216   if (isFramework())
217     return getFrameworkDir()->getName();
218   assert(isHeaderMap() && "Unknown DirectoryLookup");
219   return getHeaderMap()->getFileName();
220 }
221 
222 
223 /// LookupFile - Lookup the specified file in this search path, returning it
224 /// if it exists or returning null if not.
225 const FileEntry *DirectoryLookup::LookupFile(
226     StringRef &Filename,
227     HeaderSearch &HS,
228     SmallVectorImpl<char> *SearchPath,
229     SmallVectorImpl<char> *RelativePath,
230     ModuleMap::KnownHeader *SuggestedModule,
231     bool &InUserSpecifiedSystemFramework,
232     SmallVectorImpl<char> &MappedName) const {
233   InUserSpecifiedSystemFramework = false;
234 
235   SmallString<1024> TmpDir;
236   if (isNormalDir()) {
237     // Concatenate the requested file onto the directory.
238     TmpDir = getDir()->getName();
239     llvm::sys::path::append(TmpDir, Filename);
240     if (SearchPath != NULL) {
241       StringRef SearchPathRef(getDir()->getName());
242       SearchPath->clear();
243       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
244     }
245     if (RelativePath != NULL) {
246       RelativePath->clear();
247       RelativePath->append(Filename.begin(), Filename.end());
248     }
249 
250     // If we have a module map that might map this header, load it and
251     // check whether we'll have a suggestion for a module.
252     HS.hasModuleMap(TmpDir, getDir(), isSystemHeaderDirectory());
253     if (SuggestedModule) {
254       const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
255                                                       /*openFile=*/false);
256       if (!File)
257         return File;
258 
259       // If there is a module that corresponds to this header, suggest it.
260       *SuggestedModule = HS.findModuleForHeader(File);
261       if (!SuggestedModule->getModule() &&
262           HS.hasModuleMap(TmpDir, getDir(), isSystemHeaderDirectory()))
263         *SuggestedModule = HS.findModuleForHeader(File);
264       return File;
265     }
266 
267     return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
268   }
269 
270   if (isFramework())
271     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
272                              SuggestedModule, InUserSpecifiedSystemFramework);
273 
274   assert(isHeaderMap() && "Unknown directory lookup");
275   const HeaderMap *HM = getHeaderMap();
276   SmallString<1024> Path;
277   StringRef Dest = HM->lookupFilename(Filename, Path);
278   if (Dest.empty())
279     return 0;
280 
281   const FileEntry *Result;
282 
283   // Check if the headermap maps the filename to a framework include
284   // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
285   // framework include.
286   if (llvm::sys::path::is_relative(Dest)) {
287     MappedName.clear();
288     MappedName.append(Dest.begin(), Dest.end());
289     Filename = StringRef(MappedName.begin(), MappedName.size());
290     Result = HM->LookupFile(Filename, HS.getFileMgr());
291 
292   } else {
293     Result = HS.getFileMgr().getFile(Dest);
294   }
295 
296   if (Result) {
297     if (SearchPath != NULL) {
298       StringRef SearchPathRef(getName());
299       SearchPath->clear();
300       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
301     }
302     if (RelativePath != NULL) {
303       RelativePath->clear();
304       RelativePath->append(Filename.begin(), Filename.end());
305     }
306   }
307   return Result;
308 }
309 
310 /// \brief Given a framework directory, find the top-most framework directory.
311 ///
312 /// \param FileMgr The file manager to use for directory lookups.
313 /// \param DirName The name of the framework directory.
314 /// \param SubmodulePath Will be populated with the submodule path from the
315 /// returned top-level module to the originally named framework.
316 static const DirectoryEntry *
317 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
318                    SmallVectorImpl<std::string> &SubmodulePath) {
319   assert(llvm::sys::path::extension(DirName) == ".framework" &&
320          "Not a framework directory");
321 
322   // Note: as an egregious but useful hack we use the real path here, because
323   // frameworks moving between top-level frameworks to embedded frameworks tend
324   // to be symlinked, and we base the logical structure of modules on the
325   // physical layout. In particular, we need to deal with crazy includes like
326   //
327   //   #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
328   //
329   // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
330   // which one should access with, e.g.,
331   //
332   //   #include <Bar/Wibble.h>
333   //
334   // Similar issues occur when a top-level framework has moved into an
335   // embedded framework.
336   const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
337   DirName = FileMgr.getCanonicalName(TopFrameworkDir);
338   do {
339     // Get the parent directory name.
340     DirName = llvm::sys::path::parent_path(DirName);
341     if (DirName.empty())
342       break;
343 
344     // Determine whether this directory exists.
345     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
346     if (!Dir)
347       break;
348 
349     // If this is a framework directory, then we're a subframework of this
350     // framework.
351     if (llvm::sys::path::extension(DirName) == ".framework") {
352       SubmodulePath.push_back(llvm::sys::path::stem(DirName));
353       TopFrameworkDir = Dir;
354     }
355   } while (true);
356 
357   return TopFrameworkDir;
358 }
359 
360 /// DoFrameworkLookup - Do a lookup of the specified file in the current
361 /// DirectoryLookup, which is a framework directory.
362 const FileEntry *DirectoryLookup::DoFrameworkLookup(
363     StringRef Filename,
364     HeaderSearch &HS,
365     SmallVectorImpl<char> *SearchPath,
366     SmallVectorImpl<char> *RelativePath,
367     ModuleMap::KnownHeader *SuggestedModule,
368     bool &InUserSpecifiedSystemFramework) const
369 {
370   FileManager &FileMgr = HS.getFileMgr();
371 
372   // Framework names must have a '/' in the filename.
373   size_t SlashPos = Filename.find('/');
374   if (SlashPos == StringRef::npos) return 0;
375 
376   // Find out if this is the home for the specified framework, by checking
377   // HeaderSearch.  Possible answers are yes/no and unknown.
378   HeaderSearch::FrameworkCacheEntry &CacheEntry =
379     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
380 
381   // If it is known and in some other directory, fail.
382   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
383     return 0;
384 
385   // Otherwise, construct the path to this framework dir.
386 
387   // FrameworkName = "/System/Library/Frameworks/"
388   SmallString<1024> FrameworkName;
389   FrameworkName += getFrameworkDir()->getName();
390   if (FrameworkName.empty() || FrameworkName.back() != '/')
391     FrameworkName.push_back('/');
392 
393   // FrameworkName = "/System/Library/Frameworks/Cocoa"
394   StringRef ModuleName(Filename.begin(), SlashPos);
395   FrameworkName += ModuleName;
396 
397   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
398   FrameworkName += ".framework/";
399 
400   // If the cache entry was unresolved, populate it now.
401   if (CacheEntry.Directory == 0) {
402     HS.IncrementFrameworkLookupCount();
403 
404     // If the framework dir doesn't exist, we fail.
405     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
406     if (Dir == 0) return 0;
407 
408     // Otherwise, if it does, remember that this is the right direntry for this
409     // framework.
410     CacheEntry.Directory = getFrameworkDir();
411 
412     // If this is a user search directory, check if the framework has been
413     // user-specified as a system framework.
414     if (getDirCharacteristic() == SrcMgr::C_User) {
415       SmallString<1024> SystemFrameworkMarker(FrameworkName);
416       SystemFrameworkMarker += ".system_framework";
417       if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
418         CacheEntry.IsUserSpecifiedSystemFramework = true;
419       }
420     }
421   }
422 
423   // Set the 'user-specified system framework' flag.
424   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
425 
426   if (RelativePath != NULL) {
427     RelativePath->clear();
428     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
429   }
430 
431   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
432   unsigned OrigSize = FrameworkName.size();
433 
434   FrameworkName += "Headers/";
435 
436   if (SearchPath != NULL) {
437     SearchPath->clear();
438     // Without trailing '/'.
439     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
440   }
441 
442   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
443   const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
444                                         /*openFile=*/!SuggestedModule);
445   if (!FE) {
446     // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
447     const char *Private = "Private";
448     FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
449                          Private+strlen(Private));
450     if (SearchPath != NULL)
451       SearchPath->insert(SearchPath->begin()+OrigSize, Private,
452                          Private+strlen(Private));
453 
454     FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
455   }
456 
457   // If we found the header and are allowed to suggest a module, do so now.
458   if (FE && SuggestedModule) {
459     // Find the framework in which this header occurs.
460     StringRef FrameworkPath = FE->getName();
461     bool FoundFramework = false;
462     do {
463       // Get the parent directory name.
464       FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
465       if (FrameworkPath.empty())
466         break;
467 
468       // Determine whether this directory exists.
469       const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
470       if (!Dir)
471         break;
472 
473       // If this is a framework directory, then we're a subframework of this
474       // framework.
475       if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
476         FoundFramework = true;
477         break;
478       }
479     } while (true);
480 
481     if (FoundFramework) {
482       // Find the top-level framework based on this framework.
483       SmallVector<std::string, 4> SubmodulePath;
484       const DirectoryEntry *TopFrameworkDir
485         = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
486 
487       // Determine the name of the top-level framework.
488       StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
489 
490       // Load this framework module. If that succeeds, find the suggested module
491       // for this header, if any.
492       bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
493       if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
494         *SuggestedModule = HS.findModuleForHeader(FE);
495       }
496     } else {
497       *SuggestedModule = HS.findModuleForHeader(FE);
498     }
499   }
500   return FE;
501 }
502 
503 void HeaderSearch::setTarget(const TargetInfo &Target) {
504   ModMap.setTarget(Target);
505 }
506 
507 
508 //===----------------------------------------------------------------------===//
509 // Header File Location.
510 //===----------------------------------------------------------------------===//
511 
512 
513 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
514 /// return null on failure.  isAngled indicates whether the file reference is
515 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
516 /// non-empty, indicates where the \#including file(s) are, in case a relative
517 /// search is needed. Microsoft mode will pass all \#including files.
518 const FileEntry *HeaderSearch::LookupFile(
519     StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
520     const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
521     ArrayRef<const FileEntry *> Includers, SmallVectorImpl<char> *SearchPath,
522     SmallVectorImpl<char> *RelativePath,
523     ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
524   if (!HSOpts->ModuleMapFiles.empty()) {
525     // Preload all explicitly specified module map files. This enables modules
526     // map files lying in a directory structure separate from the header files
527     // that they describe. These cannot be loaded lazily upon encountering a
528     // header file, as there is no other known mapping from a header file to its
529     // module map file.
530     for (llvm::SetVector<std::string>::iterator
531              I = HSOpts->ModuleMapFiles.begin(),
532              E = HSOpts->ModuleMapFiles.end();
533          I != E; ++I) {
534       const FileEntry *File = FileMgr.getFile(*I);
535       if (!File)
536         continue;
537       loadModuleMapFile(File, /*IsSystem=*/false);
538     }
539     HSOpts->ModuleMapFiles.clear();
540   }
541 
542   if (SuggestedModule)
543     *SuggestedModule = ModuleMap::KnownHeader();
544 
545   // If 'Filename' is absolute, check to see if it exists and no searching.
546   if (llvm::sys::path::is_absolute(Filename)) {
547     CurDir = 0;
548 
549     // If this was an #include_next "/absolute/file", fail.
550     if (FromDir) return 0;
551 
552     if (SearchPath != NULL)
553       SearchPath->clear();
554     if (RelativePath != NULL) {
555       RelativePath->clear();
556       RelativePath->append(Filename.begin(), Filename.end());
557     }
558     // Otherwise, just return the file.
559     return FileMgr.getFile(Filename, /*openFile=*/true);
560   }
561 
562   // Unless disabled, check to see if the file is in the #includer's
563   // directory.  This cannot be based on CurDir, because each includer could be
564   // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
565   // include of "baz.h" should resolve to "whatever/foo/baz.h".
566   // This search is not done for <> headers.
567   if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
568     SmallString<1024> TmpDir;
569     for (ArrayRef<const FileEntry *>::iterator I(Includers.begin()),
570          E(Includers.end());
571          I != E; ++I) {
572       const FileEntry *Includer = *I;
573       // Concatenate the requested file onto the directory.
574       // FIXME: Portability.  Filename concatenation should be in sys::Path.
575       TmpDir = Includer->getDir()->getName();
576       TmpDir.push_back('/');
577       TmpDir.append(Filename.begin(), Filename.end());
578       if (const FileEntry *FE =
579               FileMgr.getFile(TmpDir.str(), /*openFile=*/true)) {
580         // Leave CurDir unset.
581         // This file is a system header or C++ unfriendly if the old file is.
582         //
583         // Note that we only use one of FromHFI/ToHFI at once, due to potential
584         // reallocation of the underlying vector potentially making the first
585         // reference binding dangling.
586         HeaderFileInfo &FromHFI = getFileInfo(Includer);
587         unsigned DirInfo = FromHFI.DirInfo;
588         bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
589         StringRef Framework = FromHFI.Framework;
590 
591         HeaderFileInfo &ToHFI = getFileInfo(FE);
592         ToHFI.DirInfo = DirInfo;
593         ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
594         ToHFI.Framework = Framework;
595 
596         if (SearchPath != NULL) {
597           StringRef SearchPathRef(Includer->getDir()->getName());
598           SearchPath->clear();
599           SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
600         }
601         if (RelativePath != NULL) {
602           RelativePath->clear();
603           RelativePath->append(Filename.begin(), Filename.end());
604         }
605         if (I != Includers.begin())
606           Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms)
607               << FE->getName();
608         return FE;
609       }
610     }
611   }
612 
613   CurDir = 0;
614 
615   // If this is a system #include, ignore the user #include locs.
616   unsigned i = isAngled ? AngledDirIdx : 0;
617 
618   // If this is a #include_next request, start searching after the directory the
619   // file was found in.
620   if (FromDir)
621     i = FromDir-&SearchDirs[0];
622 
623   // Cache all of the lookups performed by this method.  Many headers are
624   // multiply included, and the "pragma once" optimization prevents them from
625   // being relex/pp'd, but they would still have to search through a
626   // (potentially huge) series of SearchDirs to find it.
627   std::pair<unsigned, unsigned> &CacheLookup =
628     LookupFileCache.GetOrCreateValue(Filename).getValue();
629 
630   // If the entry has been previously looked up, the first value will be
631   // non-zero.  If the value is equal to i (the start point of our search), then
632   // this is a matching hit.
633   if (!SkipCache && CacheLookup.first == i+1) {
634     // Skip querying potentially lots of directories for this lookup.
635     i = CacheLookup.second;
636   } else {
637     // Otherwise, this is the first query, or the previous query didn't match
638     // our search start.  We will fill in our found location below, so prime the
639     // start point value.
640     CacheLookup.first = i+1;
641   }
642 
643   SmallString<64> MappedName;
644 
645   // Check each directory in sequence to see if it contains this file.
646   for (; i != SearchDirs.size(); ++i) {
647     bool InUserSpecifiedSystemFramework = false;
648     const FileEntry *FE =
649       SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
650                                SuggestedModule, InUserSpecifiedSystemFramework,
651                                MappedName);
652     if (!FE) continue;
653 
654     CurDir = &SearchDirs[i];
655 
656     // This file is a system header or C++ unfriendly if the dir is.
657     HeaderFileInfo &HFI = getFileInfo(FE);
658     HFI.DirInfo = CurDir->getDirCharacteristic();
659 
660     // If the directory characteristic is User but this framework was
661     // user-specified to be treated as a system framework, promote the
662     // characteristic.
663     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
664       HFI.DirInfo = SrcMgr::C_System;
665 
666     // If the filename matches a known system header prefix, override
667     // whether the file is a system header.
668     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
669       if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
670         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
671                                                        : SrcMgr::C_User;
672         break;
673       }
674     }
675 
676     // If this file is found in a header map and uses the framework style of
677     // includes, then this header is part of a framework we're building.
678     if (CurDir->isIndexHeaderMap()) {
679       size_t SlashPos = Filename.find('/');
680       if (SlashPos != StringRef::npos) {
681         HFI.IndexHeaderMapHeader = 1;
682         HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
683                                                          SlashPos));
684       }
685     }
686 
687     // Remember this location for the next lookup we do.
688     CacheLookup.second = i;
689     return FE;
690   }
691 
692   // If we are including a file with a quoted include "foo.h" from inside
693   // a header in a framework that is currently being built, and we couldn't
694   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
695   // "Foo" is the name of the framework in which the including header was found.
696   if (!Includers.empty() && !isAngled &&
697       Filename.find('/') == StringRef::npos) {
698     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front());
699     if (IncludingHFI.IndexHeaderMapHeader) {
700       SmallString<128> ScratchFilename;
701       ScratchFilename += IncludingHFI.Framework;
702       ScratchFilename += '/';
703       ScratchFilename += Filename;
704 
705       const FileEntry *Result = LookupFile(
706           ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
707           Includers.front(), SearchPath, RelativePath, SuggestedModule);
708       std::pair<unsigned, unsigned> &CacheLookup
709         = LookupFileCache.GetOrCreateValue(Filename).getValue();
710       CacheLookup.second
711         = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
712       return Result;
713     }
714   }
715 
716   // Otherwise, didn't find it. Remember we didn't find this.
717   CacheLookup.second = SearchDirs.size();
718   return 0;
719 }
720 
721 /// LookupSubframeworkHeader - Look up a subframework for the specified
722 /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
723 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
724 /// is a subframework within Carbon.framework.  If so, return the FileEntry
725 /// for the designated file, otherwise return null.
726 const FileEntry *HeaderSearch::
727 LookupSubframeworkHeader(StringRef Filename,
728                          const FileEntry *ContextFileEnt,
729                          SmallVectorImpl<char> *SearchPath,
730                          SmallVectorImpl<char> *RelativePath,
731                          ModuleMap::KnownHeader *SuggestedModule) {
732   assert(ContextFileEnt && "No context file?");
733 
734   // Framework names must have a '/' in the filename.  Find it.
735   // FIXME: Should we permit '\' on Windows?
736   size_t SlashPos = Filename.find('/');
737   if (SlashPos == StringRef::npos) return 0;
738 
739   // Look up the base framework name of the ContextFileEnt.
740   const char *ContextName = ContextFileEnt->getName();
741 
742   // If the context info wasn't a framework, couldn't be a subframework.
743   const unsigned DotFrameworkLen = 10;
744   const char *FrameworkPos = strstr(ContextName, ".framework");
745   if (FrameworkPos == 0 ||
746       (FrameworkPos[DotFrameworkLen] != '/' &&
747        FrameworkPos[DotFrameworkLen] != '\\'))
748     return 0;
749 
750   SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
751 
752   // Append Frameworks/HIToolbox.framework/
753   FrameworkName += "Frameworks/";
754   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
755   FrameworkName += ".framework/";
756 
757   llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
758     FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
759 
760   // Some other location?
761   if (CacheLookup.getValue().Directory &&
762       CacheLookup.getKeyLength() == FrameworkName.size() &&
763       memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
764              CacheLookup.getKeyLength()) != 0)
765     return 0;
766 
767   // Cache subframework.
768   if (CacheLookup.getValue().Directory == 0) {
769     ++NumSubFrameworkLookups;
770 
771     // If the framework dir doesn't exist, we fail.
772     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
773     if (Dir == 0) return 0;
774 
775     // Otherwise, if it does, remember that this is the right direntry for this
776     // framework.
777     CacheLookup.getValue().Directory = Dir;
778   }
779 
780   const FileEntry *FE = 0;
781 
782   if (RelativePath != NULL) {
783     RelativePath->clear();
784     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
785   }
786 
787   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
788   SmallString<1024> HeadersFilename(FrameworkName);
789   HeadersFilename += "Headers/";
790   if (SearchPath != NULL) {
791     SearchPath->clear();
792     // Without trailing '/'.
793     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
794   }
795 
796   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
797   if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
798 
799     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
800     HeadersFilename = FrameworkName;
801     HeadersFilename += "PrivateHeaders/";
802     if (SearchPath != NULL) {
803       SearchPath->clear();
804       // Without trailing '/'.
805       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
806     }
807 
808     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
809     if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
810       return 0;
811   }
812 
813   // This file is a system header or C++ unfriendly if the old file is.
814   //
815   // Note that the temporary 'DirInfo' is required here, as either call to
816   // getFileInfo could resize the vector and we don't want to rely on order
817   // of evaluation.
818   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
819   getFileInfo(FE).DirInfo = DirInfo;
820 
821   // If we're supposed to suggest a module, look for one now.
822   if (SuggestedModule) {
823     // Find the top-level framework based on this framework.
824     FrameworkName.pop_back(); // remove the trailing '/'
825     SmallVector<std::string, 4> SubmodulePath;
826     const DirectoryEntry *TopFrameworkDir
827       = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
828 
829     // Determine the name of the top-level framework.
830     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
831 
832     // Load this framework module. If that succeeds, find the suggested module
833     // for this header, if any.
834     bool IsSystem = false;
835     if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
836       *SuggestedModule = findModuleForHeader(FE);
837     }
838   }
839 
840   return FE;
841 }
842 
843 /// \brief Helper static function to normalize a path for injection into
844 /// a synthetic header.
845 /*static*/ std::string
846 HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
847   // Implicit include paths should be resolved relative to the current
848   // working directory first, and then use the regular header search
849   // mechanism. The proper way to handle this is to have the
850   // predefines buffer located at the current working directory, but
851   // it has no file entry. For now, workaround this by using an
852   // absolute path if we find the file here, and otherwise letting
853   // header search handle it.
854   SmallString<128> Path(File);
855   llvm::sys::fs::make_absolute(Path);
856   bool exists;
857   if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
858     Path = File;
859   else if (exists)
860     FileMgr.getFile(File);
861 
862   return Lexer::Stringify(Path.str());
863 }
864 
865 //===----------------------------------------------------------------------===//
866 // File Info Management.
867 //===----------------------------------------------------------------------===//
868 
869 /// \brief Merge the header file info provided by \p OtherHFI into the current
870 /// header file info (\p HFI)
871 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
872                                 const HeaderFileInfo &OtherHFI) {
873   HFI.isImport |= OtherHFI.isImport;
874   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
875   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
876   HFI.NumIncludes += OtherHFI.NumIncludes;
877 
878   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
879     HFI.ControllingMacro = OtherHFI.ControllingMacro;
880     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
881   }
882 
883   if (OtherHFI.External) {
884     HFI.DirInfo = OtherHFI.DirInfo;
885     HFI.External = OtherHFI.External;
886     HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
887   }
888 
889   if (HFI.Framework.empty())
890     HFI.Framework = OtherHFI.Framework;
891 
892   HFI.Resolved = true;
893 }
894 
895 /// getFileInfo - Return the HeaderFileInfo structure for the specified
896 /// FileEntry.
897 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
898   if (FE->getUID() >= FileInfo.size())
899     FileInfo.resize(FE->getUID()+1);
900 
901   HeaderFileInfo &HFI = FileInfo[FE->getUID()];
902   if (ExternalSource && !HFI.Resolved)
903     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
904   return HFI;
905 }
906 
907 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
908   // Check if we've ever seen this file as a header.
909   if (File->getUID() >= FileInfo.size())
910     return false;
911 
912   // Resolve header file info from the external source, if needed.
913   HeaderFileInfo &HFI = FileInfo[File->getUID()];
914   if (ExternalSource && !HFI.Resolved)
915     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
916 
917   return HFI.isPragmaOnce || HFI.isImport ||
918       HFI.ControllingMacro || HFI.ControllingMacroID;
919 }
920 
921 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
922                                         ModuleMap::ModuleHeaderRole Role,
923                                         bool isCompilingModuleHeader) {
924   if (FE->getUID() >= FileInfo.size())
925     FileInfo.resize(FE->getUID()+1);
926 
927   HeaderFileInfo &HFI = FileInfo[FE->getUID()];
928   HFI.isModuleHeader = true;
929   HFI.isCompilingModuleHeader = isCompilingModuleHeader;
930   HFI.setHeaderRole(Role);
931 }
932 
933 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
934   ++NumIncluded; // Count # of attempted #includes.
935 
936   // Get information about this file.
937   HeaderFileInfo &FileInfo = getFileInfo(File);
938 
939   // If this is a #import directive, check that we have not already imported
940   // this header.
941   if (isImport) {
942     // If this has already been imported, don't import it again.
943     FileInfo.isImport = true;
944 
945     // Has this already been #import'ed or #include'd?
946     if (FileInfo.NumIncludes) return false;
947   } else {
948     // Otherwise, if this is a #include of a file that was previously #import'd
949     // or if this is the second #include of a #pragma once file, ignore it.
950     if (FileInfo.isImport)
951       return false;
952   }
953 
954   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
955   // if the macro that guards it is defined, we know the #include has no effect.
956   if (const IdentifierInfo *ControllingMacro
957       = FileInfo.getControllingMacro(ExternalLookup))
958     if (ControllingMacro->hasMacroDefinition()) {
959       ++NumMultiIncludeFileOptzn;
960       return false;
961     }
962 
963   // Increment the number of times this file has been included.
964   ++FileInfo.NumIncludes;
965 
966   return true;
967 }
968 
969 size_t HeaderSearch::getTotalMemory() const {
970   return SearchDirs.capacity()
971     + llvm::capacity_in_bytes(FileInfo)
972     + llvm::capacity_in_bytes(HeaderMaps)
973     + LookupFileCache.getAllocator().getTotalMemory()
974     + FrameworkMap.getAllocator().getTotalMemory();
975 }
976 
977 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
978   return FrameworkNames.GetOrCreateValue(Framework).getKey();
979 }
980 
981 bool HeaderSearch::hasModuleMap(StringRef FileName,
982                                 const DirectoryEntry *Root,
983                                 bool IsSystem) {
984   if (!enabledModules())
985     return false;
986 
987   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
988 
989   StringRef DirName = FileName;
990   do {
991     // Get the parent directory name.
992     DirName = llvm::sys::path::parent_path(DirName);
993     if (DirName.empty())
994       return false;
995 
996     // Determine whether this directory exists.
997     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
998     if (!Dir)
999       return false;
1000 
1001     // Try to load the "module.map" file in this directory.
1002     switch (loadModuleMapFile(Dir, IsSystem)) {
1003     case LMM_NewlyLoaded:
1004     case LMM_AlreadyLoaded:
1005       // Success. All of the directories we stepped through inherit this module
1006       // map file.
1007       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1008         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1009       return true;
1010 
1011     case LMM_NoDirectory:
1012     case LMM_InvalidModuleMap:
1013       break;
1014     }
1015 
1016     // If we hit the top of our search, we're done.
1017     if (Dir == Root)
1018       return false;
1019 
1020     // Keep track of all of the directories we checked, so we can mark them as
1021     // having module maps if we eventually do find a module map.
1022     FixUpDirectories.push_back(Dir);
1023   } while (true);
1024 }
1025 
1026 ModuleMap::KnownHeader
1027 HeaderSearch::findModuleForHeader(const FileEntry *File) const {
1028   if (ExternalSource) {
1029     // Make sure the external source has handled header info about this file,
1030     // which includes whether the file is part of a module.
1031     (void)getFileInfo(File);
1032   }
1033   return ModMap.findModuleForHeader(File);
1034 }
1035 
1036 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1037   const DirectoryEntry *Dir = File->getDir();
1038 
1039   llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1040     = DirectoryHasModuleMap.find(Dir);
1041   if (KnownDir != DirectoryHasModuleMap.end())
1042     return !KnownDir->second;
1043 
1044   bool Result = ModMap.parseModuleMapFile(File, IsSystem);
1045   if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
1046     // If the file we loaded was a module.map, look for the corresponding
1047     // module_private.map.
1048     SmallString<128> PrivateFilename(Dir->getName());
1049     llvm::sys::path::append(PrivateFilename, "module_private.map");
1050     if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
1051       Result = ModMap.parseModuleMapFile(PrivateFile, IsSystem);
1052   }
1053 
1054   DirectoryHasModuleMap[Dir] = !Result;
1055   return Result;
1056 }
1057 
1058 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1059                                           const DirectoryEntry *Dir,
1060                                           bool IsSystem) {
1061   if (Module *Module = ModMap.findModule(Name))
1062     return Module;
1063 
1064   // Try to load a module map file.
1065   switch (loadModuleMapFile(Dir, IsSystem)) {
1066   case LMM_InvalidModuleMap:
1067     break;
1068 
1069   case LMM_AlreadyLoaded:
1070   case LMM_NoDirectory:
1071     return 0;
1072 
1073   case LMM_NewlyLoaded:
1074     return ModMap.findModule(Name);
1075   }
1076 
1077   // Figure out the top-level framework directory and the submodule path from
1078   // that top-level framework to the requested framework.
1079   SmallVector<std::string, 2> SubmodulePath;
1080   SubmodulePath.push_back(Name);
1081   const DirectoryEntry *TopFrameworkDir
1082     = ::getTopFrameworkDir(FileMgr, Dir->getName(), SubmodulePath);
1083 
1084 
1085   // Try to infer a module map from the top-level framework directory.
1086   Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
1087                                                TopFrameworkDir,
1088                                                IsSystem,
1089                                                /*Parent=*/0);
1090   if (!Result)
1091     return 0;
1092 
1093   // Follow the submodule path to find the requested (sub)framework module
1094   // within the top-level framework module.
1095   SubmodulePath.pop_back();
1096   while (!SubmodulePath.empty() && Result) {
1097     Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
1098     SubmodulePath.pop_back();
1099   }
1100   return Result;
1101 }
1102 
1103 
1104 HeaderSearch::LoadModuleMapResult
1105 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem) {
1106   if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1107     return loadModuleMapFile(Dir, IsSystem);
1108 
1109   return LMM_NoDirectory;
1110 }
1111 
1112 HeaderSearch::LoadModuleMapResult
1113 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem) {
1114   llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1115     = DirectoryHasModuleMap.find(Dir);
1116   if (KnownDir != DirectoryHasModuleMap.end())
1117     return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1118 
1119   SmallString<128> ModuleMapFileName;
1120   ModuleMapFileName += Dir->getName();
1121   unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
1122   llvm::sys::path::append(ModuleMapFileName, "module.map");
1123   if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
1124     // We have found a module map file. Try to parse it.
1125     if (ModMap.parseModuleMapFile(ModuleMapFile, IsSystem)) {
1126       // No suitable module map.
1127       DirectoryHasModuleMap[Dir] = false;
1128       return LMM_InvalidModuleMap;
1129     }
1130 
1131     // This directory has a module map.
1132     DirectoryHasModuleMap[Dir] = true;
1133 
1134     // Check whether there is a private module map that we need to load as well.
1135     ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
1136                             ModuleMapFileName.end());
1137     llvm::sys::path::append(ModuleMapFileName, "module_private.map");
1138     if (const FileEntry *PrivateModuleMapFile
1139                                         = FileMgr.getFile(ModuleMapFileName)) {
1140       if (ModMap.parseModuleMapFile(PrivateModuleMapFile, IsSystem)) {
1141         // No suitable module map.
1142         DirectoryHasModuleMap[Dir] = false;
1143         return LMM_InvalidModuleMap;
1144       }
1145     }
1146 
1147     return LMM_NewlyLoaded;
1148   }
1149 
1150   // No suitable module map.
1151   DirectoryHasModuleMap[Dir] = false;
1152   return LMM_InvalidModuleMap;
1153 }
1154 
1155 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1156   Modules.clear();
1157 
1158   // Load module maps for each of the header search directories.
1159   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1160     bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1161     if (SearchDirs[Idx].isFramework()) {
1162       llvm::error_code EC;
1163       SmallString<128> DirNative;
1164       llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1165                               DirNative);
1166 
1167       // Search each of the ".framework" directories to load them as modules.
1168       for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1169            Dir != DirEnd && !EC; Dir.increment(EC)) {
1170         if (llvm::sys::path::extension(Dir->path()) != ".framework")
1171           continue;
1172 
1173         const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1174         if (!FrameworkDir)
1175           continue;
1176 
1177         // Load this framework module.
1178         loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1179                             IsSystem);
1180       }
1181       continue;
1182     }
1183 
1184     // FIXME: Deal with header maps.
1185     if (SearchDirs[Idx].isHeaderMap())
1186       continue;
1187 
1188     // Try to load a module map file for the search directory.
1189     loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem);
1190 
1191     // Try to load module map files for immediate subdirectories of this search
1192     // directory.
1193     loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1194   }
1195 
1196   // Populate the list of modules.
1197   for (ModuleMap::module_iterator M = ModMap.module_begin(),
1198                                MEnd = ModMap.module_end();
1199        M != MEnd; ++M) {
1200     Modules.push_back(M->getValue());
1201   }
1202 }
1203 
1204 void HeaderSearch::loadTopLevelSystemModules() {
1205   // Load module maps for each of the header search directories.
1206   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1207     // We only care about normal header directories.
1208     if (!SearchDirs[Idx].isNormalDir()) {
1209       continue;
1210     }
1211 
1212     // Try to load a module map file for the search directory.
1213     loadModuleMapFile(SearchDirs[Idx].getDir(),
1214                       SearchDirs[Idx].isSystemHeaderDirectory());
1215   }
1216 }
1217 
1218 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1219   if (SearchDir.haveSearchedAllModuleMaps())
1220     return;
1221 
1222   llvm::error_code EC;
1223   SmallString<128> DirNative;
1224   llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1225   for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1226        Dir != DirEnd && !EC; Dir.increment(EC)) {
1227     loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory());
1228   }
1229 
1230   SearchDir.setSearchedAllModuleMaps(true);
1231 }
1232