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