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