]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp
MFC r228379:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Frontend / InitHeaderSearch.cpp
1 //===--- InitHeaderSearch.cpp - Initialize header search paths ------------===//
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 InitHeaderSearch class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifdef HAVE_CLANG_CONFIG_H
15 # include "clang/Config/config.h"
16 #endif
17
18 #include "clang/Frontend/Utils.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/Version.h"
22 #include "clang/Frontend/HeaderSearchOptions.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Config/config.h"
34 #ifndef CLANG_PREFIX
35 #define CLANG_PREFIX
36 #endif
37 using namespace clang;
38 using namespace clang::frontend;
39
40 namespace {
41
42 /// InitHeaderSearch - This class makes it easier to set the search paths of
43 ///  a HeaderSearch object. InitHeaderSearch stores several search path lists
44 ///  internally, which can be sent to a HeaderSearch object in one swoop.
45 class InitHeaderSearch {
46   std::vector<std::pair<IncludeDirGroup, DirectoryLookup> > IncludePath;
47   typedef std::vector<std::pair<IncludeDirGroup,
48                       DirectoryLookup> >::const_iterator path_iterator;
49   HeaderSearch &Headers;
50   bool Verbose;
51   std::string IncludeSysroot;
52   bool IsNotEmptyOrRoot;
53
54 public:
55
56   InitHeaderSearch(HeaderSearch &HS, bool verbose, StringRef sysroot)
57     : Headers(HS), Verbose(verbose), IncludeSysroot(sysroot),
58       IsNotEmptyOrRoot(!(sysroot.empty() || sysroot == "/")) {
59   }
60
61   /// AddPath - Add the specified path to the specified group list.
62   void AddPath(const Twine &Path, IncludeDirGroup Group,
63                bool isCXXAware, bool isUserSupplied,
64                bool isFramework, bool IgnoreSysRoot = false);
65
66   /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to support a gnu
67   ///  libstdc++.
68   void AddGnuCPlusPlusIncludePaths(StringRef Base,
69                                    StringRef ArchDir,
70                                    StringRef Dir32,
71                                    StringRef Dir64,
72                                    const llvm::Triple &triple);
73
74   /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to support a MinGW
75   ///  libstdc++.
76   void AddMinGWCPlusPlusIncludePaths(StringRef Base,
77                                      StringRef Arch,
78                                      StringRef Version);
79
80   /// AddMinGW64CXXPaths - Add the necessary paths to support
81   /// libstdc++ of x86_64-w64-mingw32 aka mingw-w64.
82   void AddMinGW64CXXPaths(StringRef Base,
83                           StringRef Version);
84
85   // AddDefaultCIncludePaths - Add paths that should always be searched.
86   void AddDefaultCIncludePaths(const llvm::Triple &triple,
87                                const HeaderSearchOptions &HSOpts);
88
89   // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
90   //  compiling c++.
91   void AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple,
92                                        const HeaderSearchOptions &HSOpts);
93
94   /// AddDefaultSystemIncludePaths - Adds the default system include paths so
95   ///  that e.g. stdio.h is found.
96   void AddDefaultIncludePaths(const LangOptions &Lang,
97                               const llvm::Triple &triple,
98                               const HeaderSearchOptions &HSOpts);
99
100   /// Realize - Merges all search path lists into one list and send it to
101   /// HeaderSearch.
102   void Realize(const LangOptions &Lang);
103 };
104
105 }  // end anonymous namespace.
106
107 void InitHeaderSearch::AddPath(const Twine &Path,
108                                IncludeDirGroup Group, bool isCXXAware,
109                                bool isUserSupplied, bool isFramework,
110                                bool IgnoreSysRoot) {
111   assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
112   FileManager &FM = Headers.getFileMgr();
113
114   // Compute the actual path, taking into consideration -isysroot.
115   llvm::SmallString<256> MappedPathStorage;
116   StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
117
118   // Handle isysroot.
119   if ((Group == System || Group == CXXSystem) && !IgnoreSysRoot &&
120 #if defined(_WIN32)
121       !MappedPathStr.empty() &&
122       llvm::sys::path::is_separator(MappedPathStr[0]) &&
123 #else
124       llvm::sys::path::is_absolute(MappedPathStr) &&
125 #endif
126       IsNotEmptyOrRoot) {
127     MappedPathStorage.clear();
128     MappedPathStr =
129       (IncludeSysroot + Path).toStringRef(MappedPathStorage);
130   }
131
132   // Compute the DirectoryLookup type.
133   SrcMgr::CharacteristicKind Type;
134   if (Group == Quoted || Group == Angled || Group == IndexHeaderMap)
135     Type = SrcMgr::C_User;
136   else if (isCXXAware)
137     Type = SrcMgr::C_System;
138   else
139     Type = SrcMgr::C_ExternCSystem;
140
141
142   // If the directory exists, add it.
143   if (const DirectoryEntry *DE = FM.getDirectory(MappedPathStr)) {
144     IncludePath.push_back(std::make_pair(Group, DirectoryLookup(DE, Type,
145                           isUserSupplied, isFramework)));
146     return;
147   }
148
149   // Check to see if this is an apple-style headermap (which are not allowed to
150   // be frameworks).
151   if (!isFramework) {
152     if (const FileEntry *FE = FM.getFile(MappedPathStr)) {
153       if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
154         // It is a headermap, add it to the search path.
155         IncludePath.push_back(std::make_pair(Group, DirectoryLookup(HM, Type,
156                               isUserSupplied, Group == IndexHeaderMap)));
157         return;
158       }
159     }
160   }
161
162   if (Verbose)
163     llvm::errs() << "ignoring nonexistent directory \""
164                  << MappedPathStr << "\"\n";
165 }
166
167 void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(StringRef Base,
168                                                    StringRef ArchDir,
169                                                    StringRef Dir32,
170                                                    StringRef Dir64,
171                                                    const llvm::Triple &triple) {
172   // Add the base dir
173   AddPath(Base, CXXSystem, true, false, false);
174
175   // Add the multilib dirs
176   llvm::Triple::ArchType arch = triple.getArch();
177   bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
178   if (is64bit)
179     AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, true, false, false);
180   else
181     AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, true, false, false);
182
183   // Add the backward dir
184   AddPath(Base + "/backward", CXXSystem, true, false, false);
185 }
186
187 void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(StringRef Base,
188                                                      StringRef Arch,
189                                                      StringRef Version) {
190   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
191           CXXSystem, true, false, false);
192   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/" + Arch,
193           CXXSystem, true, false, false);
194   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
195           CXXSystem, true, false, false);
196 }
197
198 void InitHeaderSearch::AddMinGW64CXXPaths(StringRef Base,
199                                           StringRef Version) {
200   // Assumes Base is HeaderSearchOpts' ResourceDir
201   AddPath(Base + "/../../../include/c++/" + Version,
202           CXXSystem, true, false, false);
203   AddPath(Base + "/../../../include/c++/" + Version + "/x86_64-w64-mingw32",
204           CXXSystem, true, false, false);
205   AddPath(Base + "/../../../include/c++/" + Version + "/i686-w64-mingw32",
206           CXXSystem, true, false, false);
207   AddPath(Base + "/../../../include/c++/" + Version + "/backward",
208           CXXSystem, true, false, false);
209 }
210
211 void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
212                                             const HeaderSearchOptions &HSOpts) {
213   llvm::Triple::OSType os = triple.getOS();
214
215   if (HSOpts.UseStandardSystemIncludes) {
216     switch (os) {
217     case llvm::Triple::FreeBSD:
218     case llvm::Triple::NetBSD:
219       break;
220     default:
221       // FIXME: temporary hack: hard-coded paths.
222       AddPath("/usr/local/include", System, true, false, false);
223       break;
224     }
225   }
226
227   // Builtin includes use #include_next directives and should be positioned
228   // just prior C include dirs.
229   if (HSOpts.UseBuiltinIncludes) {
230     // Ignore the sys root, we *always* look for clang headers relative to
231     // supplied path.
232     llvm::sys::Path P(HSOpts.ResourceDir);
233     P.appendComponent("include");
234     AddPath(P.str(), System, false, false, false, /*IgnoreSysRoot=*/ true);
235   }
236
237   // All remaining additions are for system include directories, early exit if
238   // we aren't using them.
239   if (!HSOpts.UseStandardSystemIncludes)
240     return;
241
242   // Add dirs specified via 'configure --with-c-include-dirs'.
243   StringRef CIncludeDirs(C_INCLUDE_DIRS);
244   if (CIncludeDirs != "") {
245     SmallVector<StringRef, 5> dirs;
246     CIncludeDirs.split(dirs, ":");
247     for (SmallVectorImpl<StringRef>::iterator i = dirs.begin();
248          i != dirs.end();
249          ++i)
250       AddPath(*i, System, false, false, false);
251     return;
252   }
253
254   switch (os) {
255   case llvm::Triple::Linux:
256   case llvm::Triple::Win32:
257     llvm_unreachable("Include management is handled in the driver.");
258
259   case llvm::Triple::Haiku:
260     AddPath("/boot/common/include", System, true, false, false);
261     AddPath("/boot/develop/headers/os", System, true, false, false);
262     AddPath("/boot/develop/headers/os/app", System, true, false, false);
263     AddPath("/boot/develop/headers/os/arch", System, true, false, false);
264     AddPath("/boot/develop/headers/os/device", System, true, false, false);
265     AddPath("/boot/develop/headers/os/drivers", System, true, false, false);
266     AddPath("/boot/develop/headers/os/game", System, true, false, false);
267     AddPath("/boot/develop/headers/os/interface", System, true, false, false);
268     AddPath("/boot/develop/headers/os/kernel", System, true, false, false);
269     AddPath("/boot/develop/headers/os/locale", System, true, false, false);
270     AddPath("/boot/develop/headers/os/mail", System, true, false, false);
271     AddPath("/boot/develop/headers/os/media", System, true, false, false);
272     AddPath("/boot/develop/headers/os/midi", System, true, false, false);
273     AddPath("/boot/develop/headers/os/midi2", System, true, false, false);
274     AddPath("/boot/develop/headers/os/net", System, true, false, false);
275     AddPath("/boot/develop/headers/os/storage", System, true, false, false);
276     AddPath("/boot/develop/headers/os/support", System, true, false, false);
277     AddPath("/boot/develop/headers/os/translation",
278       System, true, false, false);
279     AddPath("/boot/develop/headers/os/add-ons/graphics",
280       System, true, false, false);
281     AddPath("/boot/develop/headers/os/add-ons/input_server",
282       System, true, false, false);
283     AddPath("/boot/develop/headers/os/add-ons/screen_saver",
284       System, true, false, false);
285     AddPath("/boot/develop/headers/os/add-ons/tracker",
286       System, true, false, false);
287     AddPath("/boot/develop/headers/os/be_apps/Deskbar",
288       System, true, false, false);
289     AddPath("/boot/develop/headers/os/be_apps/NetPositive",
290       System, true, false, false);
291     AddPath("/boot/develop/headers/os/be_apps/Tracker",
292       System, true, false, false);
293     AddPath("/boot/develop/headers/cpp", System, true, false, false);
294     AddPath("/boot/develop/headers/cpp/i586-pc-haiku",
295       System, true, false, false);
296     AddPath("/boot/develop/headers/3rdparty", System, true, false, false);
297     AddPath("/boot/develop/headers/bsd", System, true, false, false);
298     AddPath("/boot/develop/headers/glibc", System, true, false, false);
299     AddPath("/boot/develop/headers/posix", System, true, false, false);
300     AddPath("/boot/develop/headers",  System, true, false, false);
301     break;
302   case llvm::Triple::RTEMS:
303     break;
304   case llvm::Triple::Cygwin:
305     AddPath("/usr/include/w32api", System, true, false, false);
306     break;
307   case llvm::Triple::MinGW32: { 
308       // mingw-w64 crt include paths
309       llvm::sys::Path P(HSOpts.ResourceDir);
310       P.appendComponent("../../../i686-w64-mingw32/include"); // <sysroot>/i686-w64-mingw32/include
311       AddPath(P.str(), System, true, false, false);
312       P = llvm::sys::Path(HSOpts.ResourceDir);
313       P.appendComponent("../../../x86_64-w64-mingw32/include"); // <sysroot>/x86_64-w64-mingw32/include
314       AddPath(P.str(), System, true, false, false);
315       // mingw.org crt include paths
316       P = llvm::sys::Path(HSOpts.ResourceDir);
317       P.appendComponent("../../../include"); // <sysroot>/include
318       AddPath(P.str(), System, true, false, false);
319       AddPath("/mingw/include", System, true, false, false);
320       AddPath("c:/mingw/include", System, true, false, false); 
321     }
322     break;
323   case llvm::Triple::FreeBSD:
324     AddPath(CLANG_PREFIX "/usr/include/clang/" CLANG_VERSION_STRING,
325       System, false, false, false);
326     break;
327       
328   default:
329     break;
330   }
331
332   if ( os != llvm::Triple::RTEMS )
333     AddPath(CLANG_PREFIX "/usr/include", System, false, false, false);
334 }
335
336 void InitHeaderSearch::
337 AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple, const HeaderSearchOptions &HSOpts) {
338   llvm::Triple::OSType os = triple.getOS();
339   StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
340   if (CxxIncludeRoot != "") {
341     StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
342     if (CxxIncludeArch == "")
343       AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
344                                   CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
345                                   triple);
346     else
347       AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
348                                   CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
349                                   triple);
350     return;
351   }
352   // FIXME: temporary hack: hard-coded paths.
353
354   if (triple.isOSDarwin()) {
355     switch (triple.getArch()) {
356     default: break;
357
358     case llvm::Triple::ppc:
359     case llvm::Triple::ppc64:
360       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
361                                   "powerpc-apple-darwin10", "", "ppc64",
362                                   triple);
363       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
364                                   "powerpc-apple-darwin10", "", "ppc64",
365                                   triple);
366       break;
367
368     case llvm::Triple::x86:
369     case llvm::Triple::x86_64:
370       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
371                                   "i686-apple-darwin10", "", "x86_64", triple);
372       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
373                                   "i686-apple-darwin8", "", "", triple);
374       break;
375
376     case llvm::Triple::arm:
377     case llvm::Triple::thumb:
378       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
379                                   "arm-apple-darwin10", "v7", "", triple);
380       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
381                                   "arm-apple-darwin10", "v6", "", triple);
382       break;
383     }
384     return;
385   }
386
387   switch (os) {
388   case llvm::Triple::Linux:
389   case llvm::Triple::Win32:
390     llvm_unreachable("Include management is handled in the driver.");
391
392   case llvm::Triple::Cygwin:
393     // Cygwin-1.7
394     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.4");
395     // g++-4 / Cygwin-1.5
396     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.2");
397     // FIXME: Do we support g++-3.4.4?
398     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "3.4.4");
399     break;
400   case llvm::Triple::MinGW32:
401     // mingw-w64 C++ include paths (i686-w64-mingw32 and x86_64-w64-mingw32)
402     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.0");
403     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.1");
404     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.2");
405     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.3");
406     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.0");
407     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.1");
408     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.2");
409     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.7.0");
410     // mingw.org C++ include paths
411     AddMinGWCPlusPlusIncludePaths("/mingw/lib/gcc", "mingw32", "4.5.2"); //MSYS
412     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.5.0");
413     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
414     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
415     break;
416   case llvm::Triple::DragonFly:
417     AddPath("/usr/include/c++/4.1", CXXSystem, true, false, false);
418     break;
419   case llvm::Triple::FreeBSD:
420     // FreeBSD 8.0
421     // FreeBSD 7.3
422     AddGnuCPlusPlusIncludePaths(CLANG_PREFIX "/usr/include/c++/4.2",
423                                 "", "", "", triple);
424     AddGnuCPlusPlusIncludePaths(CLANG_PREFIX "/usr/include/c++/4.2/backward",
425                                 "", "", "", triple);
426     break;
427   case llvm::Triple::NetBSD:
428     AddGnuCPlusPlusIncludePaths("/usr/include/g++", "", "", "", triple);
429     break;
430   case llvm::Triple::OpenBSD: {
431     std::string t = triple.getTriple();
432     if (t.substr(0, 6) == "x86_64")
433       t.replace(0, 6, "amd64");
434     AddGnuCPlusPlusIncludePaths("/usr/include/g++",
435                                 t, "", "", triple);
436     break;
437   }
438   case llvm::Triple::Minix:
439     AddGnuCPlusPlusIncludePaths("/usr/gnu/include/c++/4.4.3",
440                                 "", "", "", triple);
441     break;
442   case llvm::Triple::Solaris:
443     // Solaris - Fall though..
444   case llvm::Triple::AuroraUX:
445     // AuroraUX
446     AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
447                                 "i386-pc-solaris2.11", "", "", triple);
448     break;
449   default:
450     break;
451   }
452 }
453
454 void InitHeaderSearch::AddDefaultIncludePaths(const LangOptions &Lang,
455                                               const llvm::Triple &triple,
456                                             const HeaderSearchOptions &HSOpts) {
457   // NB: This code path is going away. All of the logic is moving into the
458   // driver which has the information necessary to do target-specific
459   // selections of default include paths. Each target which moves there will be
460   // exempted from this logic here until we can delete the entire pile of code.
461   switch (triple.getOS()) {
462   default:
463     break; // Everything else continues to use this routine's logic.
464
465   case llvm::Triple::Linux:
466   case llvm::Triple::Win32:
467     return;
468   }
469
470   if (Lang.CPlusPlus && HSOpts.UseStandardCXXIncludes &&
471       HSOpts.UseStandardSystemIncludes) {
472     if (HSOpts.UseLibcxx) {
473       if (triple.isOSDarwin()) {
474         // On Darwin, libc++ may be installed alongside the compiler in
475         // lib/c++/v1.
476         llvm::sys::Path P(HSOpts.ResourceDir);
477         if (!P.isEmpty()) {
478           P.eraseComponent();  // Remove version from foo/lib/clang/version
479           P.eraseComponent();  // Remove clang from foo/lib/clang
480           
481           // Get foo/lib/c++/v1
482           P.appendComponent("c++");
483           P.appendComponent("v1");
484           AddPath(P.str(), CXXSystem, true, false, false, true);
485         }
486       }
487       
488       AddPath("/usr/include/c++/v1", CXXSystem, true, false, false);
489     } else {
490       AddDefaultCPlusPlusIncludePaths(triple, HSOpts);
491     }
492   }
493
494   AddDefaultCIncludePaths(triple, HSOpts);
495
496   // Add the default framework include paths on Darwin.
497   if (HSOpts.UseStandardSystemIncludes) {
498     if (triple.isOSDarwin()) {
499       AddPath("/System/Library/Frameworks", System, true, false, true);
500       AddPath("/Library/Frameworks", System, true, false, true);
501     }
502   }
503 }
504
505 /// RemoveDuplicates - If there are duplicate directory entries in the specified
506 /// search list, remove the later (dead) ones.  Returns the number of non-system
507 /// headers removed, which is used to update NumAngled.
508 static unsigned RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
509                                  unsigned First, bool Verbose) {
510   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
511   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
512   llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
513   unsigned NonSystemRemoved = 0;
514   for (unsigned i = First; i != SearchList.size(); ++i) {
515     unsigned DirToRemove = i;
516
517     const DirectoryLookup &CurEntry = SearchList[i];
518
519     if (CurEntry.isNormalDir()) {
520       // If this isn't the first time we've seen this dir, remove it.
521       if (SeenDirs.insert(CurEntry.getDir()))
522         continue;
523     } else if (CurEntry.isFramework()) {
524       // If this isn't the first time we've seen this framework dir, remove it.
525       if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
526         continue;
527     } else {
528       assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
529       // If this isn't the first time we've seen this headermap, remove it.
530       if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
531         continue;
532     }
533
534     // If we have a normal #include dir/framework/headermap that is shadowed
535     // later in the chain by a system include location, we actually want to
536     // ignore the user's request and drop the user dir... keeping the system
537     // dir.  This is weird, but required to emulate GCC's search path correctly.
538     //
539     // Since dupes of system dirs are rare, just rescan to find the original
540     // that we're nuking instead of using a DenseMap.
541     if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
542       // Find the dir that this is the same of.
543       unsigned FirstDir;
544       for (FirstDir = 0; ; ++FirstDir) {
545         assert(FirstDir != i && "Didn't find dupe?");
546
547         const DirectoryLookup &SearchEntry = SearchList[FirstDir];
548
549         // If these are different lookup types, then they can't be the dupe.
550         if (SearchEntry.getLookupType() != CurEntry.getLookupType())
551           continue;
552
553         bool isSame;
554         if (CurEntry.isNormalDir())
555           isSame = SearchEntry.getDir() == CurEntry.getDir();
556         else if (CurEntry.isFramework())
557           isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
558         else {
559           assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
560           isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
561         }
562
563         if (isSame)
564           break;
565       }
566
567       // If the first dir in the search path is a non-system dir, zap it
568       // instead of the system one.
569       if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
570         DirToRemove = FirstDir;
571     }
572
573     if (Verbose) {
574       llvm::errs() << "ignoring duplicate directory \""
575                    << CurEntry.getName() << "\"\n";
576       if (DirToRemove != i)
577         llvm::errs() << "  as it is a non-system directory that duplicates "
578                      << "a system directory\n";
579     }
580     if (DirToRemove != i)
581       ++NonSystemRemoved;
582
583     // This is reached if the current entry is a duplicate.  Remove the
584     // DirToRemove (usually the current dir).
585     SearchList.erase(SearchList.begin()+DirToRemove);
586     --i;
587   }
588   return NonSystemRemoved;
589 }
590
591
592 void InitHeaderSearch::Realize(const LangOptions &Lang) {
593   // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
594   std::vector<DirectoryLookup> SearchList;
595   SearchList.reserve(IncludePath.size());
596
597   // Quoted arguments go first.
598   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
599        it != ie; ++it) {
600     if (it->first == Quoted)
601       SearchList.push_back(it->second);
602   }
603   // Deduplicate and remember index.
604   RemoveDuplicates(SearchList, 0, Verbose);
605   unsigned NumQuoted = SearchList.size();
606
607   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
608        it != ie; ++it) {
609     if (it->first == Angled || it->first == IndexHeaderMap)
610       SearchList.push_back(it->second);
611   }
612
613   RemoveDuplicates(SearchList, NumQuoted, Verbose);
614   unsigned NumAngled = SearchList.size();
615
616   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
617        it != ie; ++it) {
618     if (it->first == System ||
619         (!Lang.ObjC1 && !Lang.CPlusPlus && it->first == CSystem)    ||
620         (/*FIXME !Lang.ObjC1 && */Lang.CPlusPlus  && it->first == CXXSystem)  ||
621         (Lang.ObjC1  && !Lang.CPlusPlus && it->first == ObjCSystem) ||
622         (Lang.ObjC1  && Lang.CPlusPlus  && it->first == ObjCXXSystem))
623       SearchList.push_back(it->second);
624   }
625
626   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
627        it != ie; ++it) {
628     if (it->first == After)
629       SearchList.push_back(it->second);
630   }
631
632   // Remove duplicates across both the Angled and System directories.  GCC does
633   // this and failing to remove duplicates across these two groups breaks
634   // #include_next.
635   unsigned NonSystemRemoved = RemoveDuplicates(SearchList, NumQuoted, Verbose);
636   NumAngled -= NonSystemRemoved;
637
638   bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
639   Headers.SetSearchPaths(SearchList, NumQuoted, NumAngled, DontSearchCurDir);
640
641   // If verbose, print the list of directories that will be searched.
642   if (Verbose) {
643     llvm::errs() << "#include \"...\" search starts here:\n";
644     for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
645       if (i == NumQuoted)
646         llvm::errs() << "#include <...> search starts here:\n";
647       const char *Name = SearchList[i].getName();
648       const char *Suffix;
649       if (SearchList[i].isNormalDir())
650         Suffix = "";
651       else if (SearchList[i].isFramework())
652         Suffix = " (framework directory)";
653       else {
654         assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
655         Suffix = " (headermap)";
656       }
657       llvm::errs() << " " << Name << Suffix << "\n";
658     }
659     llvm::errs() << "End of search list.\n";
660   }
661 }
662
663 void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
664                                      const HeaderSearchOptions &HSOpts,
665                                      const LangOptions &Lang,
666                                      const llvm::Triple &Triple) {
667   InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
668
669   // Add the user defined entries.
670   for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
671     const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
672     Init.AddPath(E.Path, E.Group, !E.ImplicitExternC, E.IsUserSupplied,
673                  E.IsFramework, E.IgnoreSysRoot);
674   }
675
676   Init.AddDefaultIncludePaths(Lang, Triple, HSOpts);
677
678   Init.Realize(Lang);
679 }