blob: 383d9b478236eb3df4efd086fe480b8a983846ff [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencer5f016e22007-07-11 17:01:13 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattner822da612007-12-17 06:36:45 +000015#include "clang/Lex/HeaderMap.h"
Chandler Carruthcb381ea2011-12-09 01:33:57 +000016#include "clang/Lex/Lexer.h"
Douglas Gregora30cfe52011-11-11 19:10:28 +000017#include "clang/Basic/Diagnostic.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000018#include "clang/Basic/FileManager.h"
19#include "clang/Basic/IdentifierTable.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000020#include "llvm/Support/FileSystem.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000021#include "llvm/Support/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/ADT/SmallString.h"
Ted Kremenekeabea452011-07-27 18:41:18 +000023#include "llvm/Support/Capacity.h"
Chris Lattner3daed522009-03-02 22:20:04 +000024#include <cstdio>
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Douglas Gregor8c5a7602009-04-25 23:30:02 +000027const IdentifierInfo *
28HeaderFileInfo::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
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000039ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
40
Douglas Gregor51f564f2011-12-31 04:05:44 +000041HeaderSearch::HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags,
Douglas Gregordc58aa72012-01-30 06:01:29 +000042 const LangOptions &LangOpts,
43 const TargetInfo *Target)
Douglas Gregora30cfe52011-11-11 19:10:28 +000044 : FileMgr(FM), Diags(Diags), FrameworkMap(64),
Douglas Gregordc58aa72012-01-30 06:01:29 +000045 ModMap(FileMgr, *Diags.getClient(), LangOpts, Target)
Douglas Gregor8e238062011-11-11 00:35:06 +000046{
Nico Weber74a5fd82011-05-24 04:31:14 +000047 AngledDirIdx = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000048 SystemDirIdx = 0;
49 NoCurDirSearch = false;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor8c5a7602009-04-25 23:30:02 +000051 ExternalLookup = 0;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000052 ExternalSource = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000053 NumIncluded = 0;
54 NumMultiIncludeFileOptzn = 0;
55 NumFrameworkLookups = NumSubFrameworkLookups = 0;
56}
57
Chris Lattner822da612007-12-17 06:36:45 +000058HeaderSearch::~HeaderSearch() {
59 // Delete headermaps.
60 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
61 delete HeaderMaps[i].second;
62}
Mike Stump1eb44332009-09-09 15:08:12 +000063
Reid Spencer5f016e22007-07-11 17:01:13 +000064void 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);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Reid Spencer5f016e22007-07-11 17:01:13 +000078 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
79 fprintf(stderr, " %d #includes skipped due to"
80 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump1eb44332009-09-09 15:08:12 +000081
Reid Spencer5f016e22007-07-11 17:01:13 +000082 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
83 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
84}
85
Chris Lattner822da612007-12-17 06:36:45 +000086/// CreateHeaderMap - This method returns a HeaderMap for the specified
87/// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000088const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000089 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000090 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000091 if (!HeaderMaps.empty()) {
92 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000093 // Pointer equality comparison of FileEntries works because they are
94 // already uniqued by inode.
Mike Stump1eb44332009-09-09 15:08:12 +000095 if (HeaderMaps[i].first == FE)
Chris Lattner822da612007-12-17 06:36:45 +000096 return HeaderMaps[i].second;
97 }
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner39b49bc2010-11-23 08:35:12 +000099 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattner822da612007-12-17 06:36:45 +0000100 HeaderMaps.push_back(std::make_pair(FE, HM));
101 return HM;
102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Chris Lattner822da612007-12-17 06:36:45 +0000104 return 0;
105}
106
Douglas Gregore434ec72012-01-29 17:08:11 +0000107std::string HeaderSearch::getModuleFileName(Module *Module) {
Douglas Gregor9a6da692011-09-12 20:41:59 +0000108 // If we don't have a module cache path, we can't do anything.
Douglas Gregore434ec72012-01-29 17:08:11 +0000109 if (ModuleCachePath.empty())
110 return std::string();
111
112
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000113 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000114 llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
115 return Result.str().str();
116}
117
118std::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();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000122
Douglas Gregore434ec72012-01-29 17:08:11 +0000123
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000124 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000125 llvm::sys::path::append(Result, ModuleName + ".pcm");
126 return Result.str().str();
127}
128
129Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000130 // Look in the module map to determine if there is a module by this name.
Douglas Gregore434ec72012-01-29 17:08:11 +0000131 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.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000140 SmallString<128> FrameworkDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000141 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);
Douglas Gregorcf70d782011-11-12 00:05:07 +0000148 if (Module)
149 break;
150 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000151 }
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.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000170 SmallString<128> NestedModuleMapDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000171 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;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000178 }
179 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000180
181 return Module;
Douglas Gregor9a6da692011-09-12 20:41:59 +0000182}
183
Chris Lattnerdf772332007-12-17 07:52:39 +0000184//===----------------------------------------------------------------------===//
185// File lookup within a DirectoryLookup scope
186//===----------------------------------------------------------------------===//
187
Chris Lattner3af66a92007-12-17 17:57:27 +0000188/// getName - Return the directory or filename corresponding to this lookup
189/// object.
190const 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
Chris Lattnerdf772332007-12-17 07:52:39 +0000200/// LookupFile - Lookup the specified file in this search path, returning it
201/// if it exists or returning null if not.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000202const FileEntry *DirectoryLookup::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000203 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000204 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000205 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000206 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000207 Module **SuggestedModule) const {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000208 SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000209 if (isNormalDir()) {
210 // Concatenate the requested file onto the directory.
Eli Friedmana6e023c2011-07-08 20:17:28 +0000211 TmpDir = getDir()->getName();
212 llvm::sys::path::append(TmpDir, Filename);
Manuel Klimek74124942011-04-26 21:50:03 +0000213 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000214 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000215 SearchPath->clear();
216 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
217 }
218 if (RelativePath != NULL) {
219 RelativePath->clear();
220 RelativePath->append(Filename.begin(), Filename.end());
221 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000222
223 // If we have a module map that might map this header, load it and
224 // check whether we'll have a suggestion for a module.
225 if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
226 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
227 /*openFile=*/false);
228 if (!File)
229 return File;
230
231 // If there is a module that corresponds to this header,
232 // suggest it.
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000233 *SuggestedModule = HS.findModuleForHeader(File);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000234 return File;
235 }
236
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000237 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000238 }
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattnerafded5b2007-12-17 08:13:48 +0000240 if (isFramework())
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000241 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000242 SuggestedModule);
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000244 assert(isHeaderMap() && "Unknown directory lookup");
Manuel Klimek74124942011-04-26 21:50:03 +0000245 const FileEntry * const Result = getHeaderMap()->LookupFile(
246 Filename, HS.getFileMgr());
247 if (Result) {
248 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 StringRef SearchPathRef(getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000250 SearchPath->clear();
251 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
252 }
253 if (RelativePath != NULL) {
254 RelativePath->clear();
255 RelativePath->append(Filename.begin(), Filename.end());
256 }
257 }
258 return Result;
Chris Lattnerdf772332007-12-17 07:52:39 +0000259}
260
261
Chris Lattnerafded5b2007-12-17 08:13:48 +0000262/// DoFrameworkLookup - Do a lookup of the specified file in the current
263/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000264const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000265 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000266 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000267 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000268 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000269 Module **SuggestedModule) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000270{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000271 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000274 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000275 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattnerafded5b2007-12-17 08:13:48 +0000277 // Find out if this is the home for the specified framework, by checking
278 // HeaderSearch. Possible answer are yes/no and unknown.
Mike Stump1eb44332009-09-09 15:08:12 +0000279 const DirectoryEntry *&FrameworkDirCache =
Chris Lattnera1394812010-01-10 01:35:12 +0000280 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Chris Lattnerafded5b2007-12-17 08:13:48 +0000282 // If it is known and in some other directory, fail.
283 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattnerafded5b2007-12-17 08:13:48 +0000286 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000289 SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000290 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 if (FrameworkName.empty() || FrameworkName.back() != '/')
292 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000295 StringRef ModuleName(Filename.begin(), SlashPos);
296 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
299 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Chris Lattnerafded5b2007-12-17 08:13:48 +0000301 // If the cache entry is still unresolved, query to see if the cache entry is
302 // still unresolved. If so, check its existence now.
303 if (FrameworkDirCache == 0) {
304 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 // If the framework dir doesn't exist, we fail.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000307 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Daniel Dunbarf535a982012-04-05 17:09:11 +0000308 if (!llvm::sys::fs::exists(FrameworkName.str()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 // Otherwise, if it does, remember that this is the right direntry for this
312 // framework.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000313 FrameworkDirCache = getFrameworkDir();
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Manuel Klimek74124942011-04-26 21:50:03 +0000316 if (RelativePath != NULL) {
317 RelativePath->clear();
318 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
319 }
320
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000321 // If we're allowed to look for modules, try to load or create the module
322 // corresponding to this framework.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000323 Module *Module = 0;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000324 if (SuggestedModule) {
325 if (const DirectoryEntry *FrameworkDir
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000326 = FileMgr.getDirectory(FrameworkName)) {
327 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregore434ec72012-01-29 17:08:11 +0000328 Module = HS.loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000329 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000330 }
331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
333 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000336
337 if (SearchPath != NULL) {
338 SearchPath->clear();
339 // Without trailing '/'.
340 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
341 }
342
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000343 // Determine whether this is the module we're building or not.
Douglas Gregor09833922011-12-06 17:31:28 +0000344 bool AutomaticImport = Module;
Chris Lattnera1394812010-01-10 01:35:12 +0000345 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000346 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000347 /*openFile=*/!AutomaticImport)) {
348 if (AutomaticImport)
Douglas Gregor09833922011-12-06 17:31:28 +0000349 *SuggestedModule = HS.findModuleForHeader(FE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 return FE;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000351 }
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
354 const char *Private = "Private";
Mike Stump1eb44332009-09-09 15:08:12 +0000355 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 Private+strlen(Private));
Manuel Klimek74124942011-04-26 21:50:03 +0000357 if (SearchPath != NULL)
358 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
359 Private+strlen(Private));
360
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000361 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
362 /*openFile=*/!AutomaticImport);
363 if (FE && AutomaticImport)
Douglas Gregor09833922011-12-06 17:31:28 +0000364 *SuggestedModule = HS.findModuleForHeader(FE);
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000365 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000366}
367
Douglas Gregordc58aa72012-01-30 06:01:29 +0000368void HeaderSearch::setTarget(const TargetInfo &Target) {
369 ModMap.setTarget(Target);
370}
371
Chris Lattnerdf772332007-12-17 07:52:39 +0000372
Chris Lattnerafded5b2007-12-17 08:13:48 +0000373//===----------------------------------------------------------------------===//
374// Header File Location.
375//===----------------------------------------------------------------------===//
376
377
Reid Spencer5f016e22007-07-11 17:01:13 +0000378/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
379/// return null on failure. isAngled indicates whether the file reference is
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000380/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
381/// non-null, indicates where the #including file is, in case a relative search
382/// is needed.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000383const FileEntry *HeaderSearch::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000384 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000385 bool isAngled,
386 const DirectoryLookup *FromDir,
387 const DirectoryLookup *&CurDir,
388 const FileEntry *CurFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000389 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000390 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000391 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000392 bool SkipCache)
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000393{
394 if (SuggestedModule)
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000395 *SuggestedModule = 0;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000396
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000398 if (llvm::sys::path::is_absolute(Filename)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 CurDir = 0;
400
401 // If this was an #include_next "/absolute/file", fail.
402 if (FromDir) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Manuel Klimek74124942011-04-26 21:50:03 +0000404 if (SearchPath != NULL)
405 SearchPath->clear();
406 if (RelativePath != NULL) {
407 RelativePath->clear();
408 RelativePath->append(Filename.begin(), Filename.end());
409 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000411 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000414 // Unless disabled, check to see if the file is in the #includer's
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000415 // directory. This has to be based on CurFileEnt, not CurDir, because
416 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
Chris Lattnerdf772332007-12-17 07:52:39 +0000417 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
418 // This search is not done for <> headers.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000419 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000420 SmallString<1024> TmpDir;
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000421 // Concatenate the requested file onto the directory.
422 // FIXME: Portability. Filename concatenation should be in sys::Path.
423 TmpDir += CurFileEnt->getDir()->getName();
424 TmpDir.push_back('/');
425 TmpDir.append(Filename.begin(), Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000426 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000427 // Leave CurDir unset.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000428 // This file is a system header or C++ unfriendly if the old file is.
429 //
430 // Note that the temporary 'DirInfo' is required here, as either call to
431 // getFileInfo could resize the vector and we don't want to rely on order
432 // of evaluation.
433 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000434 getFileInfo(FE).DirInfo = DirInfo;
Manuel Klimek74124942011-04-26 21:50:03 +0000435 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000436 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000437 SearchPath->clear();
438 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
439 }
440 if (RelativePath != NULL) {
441 RelativePath->clear();
442 RelativePath->append(Filename.begin(), Filename.end());
443 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 return FE;
445 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 }
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 CurDir = 0;
449
450 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000451 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 // If this is a #include_next request, start searching after the directory the
454 // file was found in.
455 if (FromDir)
456 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Chris Lattner9960ae82007-07-22 07:28:00 +0000458 // Cache all of the lookups performed by this method. Many headers are
459 // multiply included, and the "pragma once" optimization prevents them from
460 // being relex/pp'd, but they would still have to search through a
461 // (potentially huge) series of SearchDirs to find it.
462 std::pair<unsigned, unsigned> &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000463 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000464
465 // If the entry has been previously looked up, the first value will be
466 // non-zero. If the value is equal to i (the start point of our search), then
467 // this is a matching hit.
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000468 if (!SkipCache && CacheLookup.first == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000469 // Skip querying potentially lots of directories for this lookup.
470 i = CacheLookup.second;
471 } else {
472 // Otherwise, this is the first query, or the previous query didn't match
473 // our search start. We will fill in our found location below, so prime the
474 // start point value.
475 CacheLookup.first = i+1;
476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 // Check each directory in sequence to see if it contains this file.
479 for (; i != SearchDirs.size(); ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000480 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000481 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000482 SuggestedModule);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000483 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattnerafded5b2007-12-17 08:13:48 +0000485 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattnerafded5b2007-12-17 08:13:48 +0000487 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000488 HeaderFileInfo &HFI = getFileInfo(FE);
489 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000491 // If this file is found in a header map and uses the framework style of
492 // includes, then this header is part of a framework we're building.
493 if (CurDir->isIndexHeaderMap()) {
494 size_t SlashPos = Filename.find('/');
495 if (SlashPos != StringRef::npos) {
496 HFI.IndexHeaderMapHeader = 1;
497 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
498 SlashPos));
499 }
500 }
501
Chris Lattnerafded5b2007-12-17 08:13:48 +0000502 // Remember this location for the next lookup we do.
503 CacheLookup.second = i;
504 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000507 // If we are including a file with a quoted include "foo.h" from inside
508 // a header in a framework that is currently being built, and we couldn't
509 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
510 // "Foo" is the name of the framework in which the including header was found.
511 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
512 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
513 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000514 SmallString<128> ScratchFilename;
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000515 ScratchFilename += IncludingHFI.Framework;
516 ScratchFilename += '/';
517 ScratchFilename += Filename;
518
519 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
520 FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000521 SearchPath, RelativePath,
522 SuggestedModule);
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000523 std::pair<unsigned, unsigned> &CacheLookup
524 = LookupFileCache.GetOrCreateValue(Filename).getValue();
525 CacheLookup.second
526 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
527 return Result;
528 }
529 }
530
Chris Lattner9960ae82007-07-22 07:28:00 +0000531 // Otherwise, didn't find it. Remember we didn't find this.
532 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 return 0;
534}
535
536/// LookupSubframeworkHeader - Look up a subframework for the specified
537/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
538/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
539/// is a subframework within Carbon.framework. If so, return the FileEntry
540/// for the designated file, otherwise return null.
541const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000542LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000543 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000544 SmallVectorImpl<char> *SearchPath,
545 SmallVectorImpl<char> *RelativePath) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000546 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000549 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000550 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000551 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 // Look up the base framework name of the ContextFileEnt.
554 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000557 const unsigned DotFrameworkLen = 10;
558 const char *FrameworkPos = strstr(ContextName, ".framework");
559 if (FrameworkPos == 0 ||
560 (FrameworkPos[DotFrameworkLen] != '/' &&
561 FrameworkPos[DotFrameworkLen] != '\\'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000564 SmallString<1024> FrameworkName(ContextName,
Douglas Gregorefda0e82011-12-09 16:48:01 +0000565 FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000566
567 // Append Frameworks/HIToolbox.framework/
568 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000569 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 FrameworkName += ".framework/";
571
572 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000573 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 // Some other location?
576 if (CacheLookup.getValue() &&
577 CacheLookup.getKeyLength() == FrameworkName.size() &&
578 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
579 CacheLookup.getKeyLength()) != 0)
580 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 // Cache subframework.
583 if (CacheLookup.getValue() == 0) {
584 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000587 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 // Otherwise, if it does, remember that this is the right direntry for this
591 // framework.
592 CacheLookup.setValue(Dir);
593 }
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 const FileEntry *FE = 0;
596
Manuel Klimek74124942011-04-26 21:50:03 +0000597 if (RelativePath != NULL) {
598 RelativePath->clear();
599 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
600 }
601
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000603 SmallString<1024> HeadersFilename(FrameworkName);
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 HeadersFilename += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000605 if (SearchPath != NULL) {
606 SearchPath->clear();
607 // Without trailing '/'.
608 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
609 }
610
Chris Lattnera1394812010-01-10 01:35:12 +0000611 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000612 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
615 HeadersFilename = FrameworkName;
616 HeadersFilename += "PrivateHeaders/";
Manuel Klimek74124942011-04-26 21:50:03 +0000617 if (SearchPath != NULL) {
618 SearchPath->clear();
619 // Without trailing '/'.
620 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
621 }
622
Chris Lattnera1394812010-01-10 01:35:12 +0000623 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000624 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 return 0;
626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000629 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000630 // Note that the temporary 'DirInfo' is required here, as either call to
631 // getFileInfo could resize the vector and we don't want to rely on order
632 // of evaluation.
633 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
634 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 return FE;
636}
637
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000638/// \brief Helper static function to normalize a path for injection into
639/// a synthetic header.
640/*static*/ std::string
641HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
642 // Implicit include paths should be resolved relative to the current
643 // working directory first, and then use the regular header search
644 // mechanism. The proper way to handle this is to have the
645 // predefines buffer located at the current working directory, but
646 // it has no file entry. For now, workaround this by using an
647 // absolute path if we find the file here, and otherwise letting
648 // header search handle it.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000649 SmallString<128> Path(File);
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000650 llvm::sys::fs::make_absolute(Path);
651 bool exists;
652 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
653 Path = File;
654 else if (exists)
655 FileMgr.getFile(File);
656
657 return Lexer::Stringify(Path.str());
658}
659
Reid Spencer5f016e22007-07-11 17:01:13 +0000660//===----------------------------------------------------------------------===//
661// File Info Management.
662//===----------------------------------------------------------------------===//
663
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000664/// \brief Merge the header file info provided by \p OtherHFI into the current
665/// header file info (\p HFI)
666static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
667 const HeaderFileInfo &OtherHFI) {
668 HFI.isImport |= OtherHFI.isImport;
669 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
670 HFI.NumIncludes += OtherHFI.NumIncludes;
671
672 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
673 HFI.ControllingMacro = OtherHFI.ControllingMacro;
674 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
675 }
676
677 if (OtherHFI.External) {
678 HFI.DirInfo = OtherHFI.DirInfo;
679 HFI.External = OtherHFI.External;
680 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
681 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000682
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000683 if (HFI.Framework.empty())
684 HFI.Framework = OtherHFI.Framework;
685
686 HFI.Resolved = true;
687}
688
Steve Naroff83d63c72009-04-24 20:03:17 +0000689/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000690/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000691HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 if (FE->getUID() >= FileInfo.size())
693 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000694
695 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000696 if (ExternalSource && !HFI.Resolved)
697 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000698 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +0000699}
Reid Spencer5f016e22007-07-11 17:01:13 +0000700
Douglas Gregordd3e5542011-05-04 00:14:37 +0000701bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
702 // Check if we've ever seen this file as a header.
703 if (File->getUID() >= FileInfo.size())
704 return false;
705
706 // Resolve header file info from the external source, if needed.
707 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000708 if (ExternalSource && !HFI.Resolved)
709 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +0000710
711 return HFI.isPragmaOnce || HFI.ControllingMacro || HFI.ControllingMacroID;
712}
713
Steve Naroff83d63c72009-04-24 20:03:17 +0000714void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
715 if (UID >= FileInfo.size())
716 FileInfo.resize(UID+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000717 HFI.Resolved = true;
Steve Naroff83d63c72009-04-24 20:03:17 +0000718 FileInfo[UID] = HFI;
719}
720
Reid Spencer5f016e22007-07-11 17:01:13 +0000721/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
722/// #include, #include_next, or #import directive. Return false if #including
723/// the file will have no effect or true if we should include it.
724bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
725 ++NumIncluded; // Count # of attempted #includes.
726
727 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +0000728 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 // If this is a #import directive, check that we have not already imported
731 // this header.
732 if (isImport) {
733 // If this has already been imported, don't import it again.
734 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 // Has this already been #import'ed or #include'd?
737 if (FileInfo.NumIncludes) return false;
738 } else {
739 // Otherwise, if this is a #include of a file that was previously #import'd
740 // or if this is the second #include of a #pragma once file, ignore it.
741 if (FileInfo.isImport)
742 return false;
743 }
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
746 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +0000747 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000748 = FileInfo.getControllingMacro(ExternalLookup))
749 if (ControllingMacro->hasMacroDefinition()) {
750 ++NumMultiIncludeFileOptzn;
751 return false;
752 }
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 // Increment the number of times this file has been included.
755 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 return true;
758}
759
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000760size_t HeaderSearch::getTotalMemory() const {
761 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +0000762 + llvm::capacity_in_bytes(FileInfo)
763 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000764 + LookupFileCache.getAllocator().getTotalMemory()
765 + FrameworkMap.getAllocator().getTotalMemory();
766}
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000767
768StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
769 return FrameworkNames.GetOrCreateValue(Framework).getKey();
770}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000771
772bool HeaderSearch::hasModuleMap(StringRef FileName,
773 const DirectoryEntry *Root) {
774 llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
775
776 StringRef DirName = FileName;
777 do {
778 // Get the parent directory name.
779 DirName = llvm::sys::path::parent_path(DirName);
780 if (DirName.empty())
781 return false;
782
783 // Determine whether this directory exists.
784 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
785 if (!Dir)
786 return false;
787
Douglas Gregorcf70d782011-11-12 00:05:07 +0000788 // Try to load the module map file in this directory.
Douglas Gregor26697972011-11-12 00:22:19 +0000789 switch (loadModuleMapFile(Dir)) {
790 case LMM_NewlyLoaded:
791 case LMM_AlreadyLoaded:
Douglas Gregorcf70d782011-11-12 00:05:07 +0000792 // Success. All of the directories we stepped through inherit this module
793 // map file.
Douglas Gregora30cfe52011-11-11 19:10:28 +0000794 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
795 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
796
797 return true;
Douglas Gregor26697972011-11-12 00:22:19 +0000798
799 case LMM_NoDirectory:
800 case LMM_InvalidModuleMap:
801 break;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000802 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000803
Douglas Gregorcf70d782011-11-12 00:05:07 +0000804 // If we hit the top of our search, we're done.
805 if (Dir == Root)
806 return false;
807
Douglas Gregora30cfe52011-11-11 19:10:28 +0000808 // Keep track of all of the directories we checked, so we can mark them as
809 // having module maps if we eventually do find a module map.
810 FixUpDirectories.push_back(Dir);
811 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000812}
813
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000814Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000815 if (Module *Mod = ModMap.findModuleForHeader(File))
816 return Mod;
Douglas Gregor65f3b5e2011-11-11 22:18:48 +0000817
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000818 return 0;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000819}
820
Douglas Gregordb1cde72011-11-16 00:09:06 +0000821bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
822 const DirectoryEntry *Dir = File->getDir();
823
824 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
825 = DirectoryHasModuleMap.find(Dir);
826 if (KnownDir != DirectoryHasModuleMap.end())
827 return !KnownDir->second;
828
829 bool Result = ModMap.parseModuleMapFile(File);
Douglas Gregor4813442c2011-12-07 21:25:07 +0000830 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
831 // If the file we loaded was a module.map, look for the corresponding
832 // module_private.map.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000833 SmallString<128> PrivateFilename(Dir->getName());
Douglas Gregor4813442c2011-12-07 21:25:07 +0000834 llvm::sys::path::append(PrivateFilename, "module_private.map");
835 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
836 Result = ModMap.parseModuleMapFile(PrivateFile);
837 }
838
839 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000840 return Result;
841}
842
Douglas Gregore434ec72012-01-29 17:08:11 +0000843Module *HeaderSearch::loadFrameworkModule(StringRef Name,
844 const DirectoryEntry *Dir,
845 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000846 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000847 return Module;
848
849 // Try to load a module map file.
850 switch (loadModuleMapFile(Dir)) {
851 case LMM_InvalidModuleMap:
852 break;
853
854 case LMM_AlreadyLoaded:
855 case LMM_NoDirectory:
856 return 0;
857
858 case LMM_NewlyLoaded:
859 return ModMap.findModule(Name);
860 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000861
862 // The top-level framework directory, from which we'll infer a framework
863 // module.
864 const DirectoryEntry *TopFrameworkDir = Dir;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000865
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000866 // The path from the module we're actually looking for back to the top-level
867 // framework name.
868 llvm::SmallVector<StringRef, 2> SubmodulePath;
869 SubmodulePath.push_back(Name);
870
871 // Walk the directory structure to find any enclosing frameworks.
872 StringRef DirName = Dir->getName();
873 do {
874 // Get the parent directory name.
875 DirName = llvm::sys::path::parent_path(DirName);
876 if (DirName.empty())
877 break;
878
879 // Determine whether this directory exists.
880 Dir = FileMgr.getDirectory(DirName);
881 if (!Dir)
882 break;
883
884 // If this is a framework directory, then we're a subframework of this
885 // framework.
886 if (llvm::sys::path::extension(DirName) == ".framework") {
887 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
888 TopFrameworkDir = Dir;
889 }
890 } while (true);
891
892 // Try to infer a module map from the top-level framework directory.
893 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000894 TopFrameworkDir,
895 IsSystem,
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000896 /*Parent=*/0);
897
898 // Follow the submodule path to find the requested (sub)framework module
899 // within the top-level framework module.
900 SubmodulePath.pop_back();
901 while (!SubmodulePath.empty() && Result) {
902 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
903 SubmodulePath.pop_back();
904 }
905 return Result;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000906}
907
Douglas Gregordb1cde72011-11-16 00:09:06 +0000908
Douglas Gregor26697972011-11-12 00:22:19 +0000909HeaderSearch::LoadModuleMapResult
910HeaderSearch::loadModuleMapFile(StringRef DirName) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000911 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
912 return loadModuleMapFile(Dir);
913
Douglas Gregor26697972011-11-12 00:22:19 +0000914 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000915}
916
Douglas Gregor26697972011-11-12 00:22:19 +0000917HeaderSearch::LoadModuleMapResult
918HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000919 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
920 = DirectoryHasModuleMap.find(Dir);
921 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +0000922 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000923
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000924 SmallString<128> ModuleMapFileName;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000925 ModuleMapFileName += Dir->getName();
Douglas Gregor587986e2011-12-07 02:23:45 +0000926 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregorcf70d782011-11-12 00:05:07 +0000927 llvm::sys::path::append(ModuleMapFileName, "module.map");
928 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
929 // We have found a module map file. Try to parse it.
Douglas Gregor587986e2011-12-07 02:23:45 +0000930 if (ModMap.parseModuleMapFile(ModuleMapFile)) {
931 // No suitable module map.
932 DirectoryHasModuleMap[Dir] = false;
933 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000934 }
Douglas Gregor587986e2011-12-07 02:23:45 +0000935
936 // This directory has a module map.
937 DirectoryHasModuleMap[Dir] = true;
938
939 // Check whether there is a private module map that we need to load as well.
940 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
941 ModuleMapFileName.end());
942 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
943 if (const FileEntry *PrivateModuleMapFile
944 = FileMgr.getFile(ModuleMapFileName)) {
945 if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
946 // No suitable module map.
947 DirectoryHasModuleMap[Dir] = false;
948 return LMM_InvalidModuleMap;
949 }
950 }
951
952 return LMM_NewlyLoaded;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000953 }
954
955 // No suitable module map.
956 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor26697972011-11-12 00:22:19 +0000957 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000958}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000959
Douglas Gregorc5b2e582012-01-29 18:15:03 +0000960void HeaderSearch::collectAllModules(llvm::SmallVectorImpl<Module *> &Modules) {
961 Modules.clear();
962
963 // Load module maps for each of the header search directories.
964 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
965 if (SearchDirs[Idx].isFramework()) {
966 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000967 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +0000968 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
969 DirNative);
970
971 // Search each of the ".framework" directories to load them as modules.
972 bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
973 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
974 Dir != DirEnd && !EC; Dir.increment(EC)) {
975 if (llvm::sys::path::extension(Dir->path()) != ".framework")
976 continue;
977
978 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
979 if (!FrameworkDir)
980 continue;
981
982 // Load this framework module.
983 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
984 IsSystem);
985 }
986 continue;
987 }
988
989 // FIXME: Deal with header maps.
990 if (SearchDirs[Idx].isHeaderMap())
991 continue;
992
993 // Try to load a module map file for the search directory.
994 loadModuleMapFile(SearchDirs[Idx].getDir());
995
996 // Try to load module map files for immediate subdirectories of this search
997 // directory.
998 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000999 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001000 llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
1001 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1002 Dir != DirEnd && !EC; Dir.increment(EC)) {
1003 loadModuleMapFile(Dir->path());
1004 }
1005 }
1006
1007 // Populate the list of modules.
1008 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1009 MEnd = ModMap.module_end();
1010 M != MEnd; ++M) {
1011 Modules.push_back(M->getValue());
1012 }
1013}
1014