InitHeaderSearch.cpp revision 199482
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/Support/raw_ostream.h"
25#include "llvm/System/Path.h"
26#include "llvm/Config/config.h"
27#include <cstdio>
28#ifdef _MSC_VER
29  #define WIN32_LEAN_AND_MEAN 1
30  #include <windows.h>
31#endif
32using namespace clang;
33using namespace clang::frontend;
34
35namespace {
36
37/// InitHeaderSearch - This class makes it easier to set the search paths of
38///  a HeaderSearch object. InitHeaderSearch stores several search path lists
39///  internally, which can be sent to a HeaderSearch object in one swoop.
40class InitHeaderSearch {
41  std::vector<DirectoryLookup> IncludeGroup[4];
42  HeaderSearch& Headers;
43  bool Verbose;
44  std::string isysroot;
45
46public:
47
48  InitHeaderSearch(HeaderSearch &HS,
49      bool verbose = false, const std::string &iSysroot = "")
50    : Headers(HS), Verbose(verbose), isysroot(iSysroot) {}
51
52  /// AddPath - Add the specified path to the specified group list.
53  void AddPath(const llvm::StringRef &Path, IncludeDirGroup Group,
54               bool isCXXAware, bool isUserSupplied,
55               bool isFramework, bool IgnoreSysRoot = false);
56
57  /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to suport a gnu
58  ///  libstdc++.
59  void AddGnuCPlusPlusIncludePaths(const std::string &Base,
60                                   const char *ArchDir,
61                                   const char *Dir32,
62                                   const char *Dir64,
63                                   const llvm::Triple &triple);
64
65  /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to suport a MinGW
66  ///  libstdc++.
67  void AddMinGWCPlusPlusIncludePaths(const std::string &Base,
68                                     const char *Arch,
69                                     const char *Version);
70
71  /// AddDelimitedPaths - Add a list of paths delimited by the system PATH
72  /// separator. The processing follows that of the CPATH variable for gcc.
73  void AddDelimitedPaths(const char *String);
74
75  // AddDefaultCIncludePaths - Add paths that should always be searched.
76  void AddDefaultCIncludePaths(const llvm::Triple &triple);
77
78  // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
79  //  compiling c++.
80  void AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple);
81
82  /// AddDefaultSystemIncludePaths - Adds the default system include paths so
83  ///  that e.g. stdio.h is found.
84  void AddDefaultSystemIncludePaths(const LangOptions &Lang,
85                                    const llvm::Triple &triple);
86
87  /// Realize - Merges all search path lists into one list and send it to
88  /// HeaderSearch.
89  void Realize();
90};
91
92}
93
94void InitHeaderSearch::AddPath(const llvm::StringRef &Path,
95                               IncludeDirGroup Group, bool isCXXAware,
96                               bool isUserSupplied, bool isFramework,
97                               bool IgnoreSysRoot) {
98  assert(!Path.empty() && "can't handle empty path here");
99  FileManager &FM = Headers.getFileMgr();
100
101  // Compute the actual path, taking into consideration -isysroot.
102  llvm::SmallString<256> MappedPath;
103
104  // Handle isysroot.
105  if (Group == System && !IgnoreSysRoot) {
106    // FIXME: Portability.  This should be a sys::Path interface, this doesn't
107    // handle things like C:\ right, nor win32 \\network\device\blah.
108    if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
109      MappedPath.append(isysroot.begin(), isysroot.end());
110  }
111
112  MappedPath.append(Path.begin(), Path.end());
113
114  // Compute the DirectoryLookup type.
115  SrcMgr::CharacteristicKind Type;
116  if (Group == Quoted || Group == Angled)
117    Type = SrcMgr::C_User;
118  else if (isCXXAware)
119    Type = SrcMgr::C_System;
120  else
121    Type = SrcMgr::C_ExternCSystem;
122
123
124  // If the directory exists, add it.
125  if (const DirectoryEntry *DE = FM.getDirectory(MappedPath.str())) {
126    IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
127                                                  isFramework));
128    return;
129  }
130
131  // Check to see if this is an apple-style headermap (which are not allowed to
132  // be frameworks).
133  if (!isFramework) {
134    if (const FileEntry *FE = FM.getFile(MappedPath.str())) {
135      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
136        // It is a headermap, add it to the search path.
137        IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
138        return;
139      }
140    }
141  }
142
143  if (Verbose)
144    llvm::errs() << "ignoring nonexistent directory \""
145                 << MappedPath.str() << "\"\n";
146}
147
148
149void InitHeaderSearch::AddDelimitedPaths(const char *at) {
150  if (*at == 0) // Empty string should not add '.' path.
151    return;
152
153  const char* delim = strchr(at, llvm::sys::PathSeparator);
154  while (delim != 0) {
155    if (delim-at == 0)
156      AddPath(".", Angled, false, true, false);
157    else
158      AddPath(llvm::StringRef(at, delim-at), Angled, false, true, false);
159    at = delim + 1;
160    delim = strchr(at, llvm::sys::PathSeparator);
161  }
162  if (*at == 0)
163    AddPath(".", Angled, false, true, false);
164  else
165    AddPath(at, Angled, false, true, false);
166}
167
168void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(const std::string &Base,
169                                                   const char *ArchDir,
170                                                   const char *Dir32,
171                                                   const char *Dir64,
172                                                   const llvm::Triple &triple) {
173  // Add the common dirs
174  AddPath(Base, System, true, false, false);
175  AddPath(Base + "/backward", System, true, false, false);
176
177  // Add the multilib dirs
178  llvm::Triple::ArchType arch = triple.getArch();
179  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
180  if (is64bit)
181    AddPath(Base + "/" + ArchDir + "/" + Dir64, System, true, false, false);
182  else
183    AddPath(Base + "/" + ArchDir + "/" + Dir32, System, true, false, false);
184}
185
186void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(const std::string &Base,
187                                                     const char *Arch,
188                                                     const char *Version) {
189  std::string localBase = Base + "/" + Arch + "/" + Version + "/include";
190  AddPath(localBase, System, true, false, false);
191  AddPath(localBase + "/c++", System, true, false, false);
192  AddPath(localBase + "/c++/backward", System, true, false, false);
193}
194
195  // FIXME: This probably should goto to some platform utils place.
196#ifdef _MSC_VER
197  // Read registry string.
198bool getSystemRegistryString(const char *keyPath, const char *valueName,
199                       char *value, size_t maxLength) {
200  HKEY hRootKey = NULL;
201  HKEY hKey = NULL;
202  const char* subKey = NULL;
203  DWORD valueType;
204  DWORD valueSize = maxLength - 1;
205  bool returnValue = false;
206  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) {
207    hRootKey = HKEY_CLASSES_ROOT;
208    subKey = keyPath + 18;
209  }
210  else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) {
211    hRootKey = HKEY_USERS;
212    subKey = keyPath + 11;
213  }
214  else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) {
215    hRootKey = HKEY_LOCAL_MACHINE;
216    subKey = keyPath + 19;
217  }
218  else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) {
219    hRootKey = HKEY_CURRENT_USER;
220    subKey = keyPath + 18;
221  }
222  else
223    return(false);
224  long lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
225  if (lResult == ERROR_SUCCESS) {
226    lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
227      (LPBYTE)value, &valueSize);
228    if (lResult == ERROR_SUCCESS)
229      returnValue = true;
230    RegCloseKey(hKey);
231  }
232  return(returnValue);
233}
234#else // _MSC_VER
235  // Read registry string.
236bool getSystemRegistryString(const char *, const char *, char *, size_t) {
237  return(false);
238}
239#endif // _MSC_VER
240
241  // Get Visual Studio installation directory.
242bool getVisualStudioDir(std::string &path) {
243  // Try the Windows registry first.
244  char vs80IDEInstallDir[256];
245  char vs90IDEInstallDir[256];
246  const char* vsIDEInstallDir = NULL;
247  bool has80 = getSystemRegistryString(
248    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0",
249    "InstallDir", vs80IDEInstallDir, sizeof(vs80IDEInstallDir) - 1);
250  bool has90 = getSystemRegistryString(
251    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0",
252    "InstallDir", vs90IDEInstallDir, sizeof(vs90IDEInstallDir) - 1);
253    // If we have both vc80 and vc90, pick version we were compiled with.
254  if (has80 && has90) {
255    #ifdef _MSC_VER
256      #if (_MSC_VER >= 1500)  // VC90
257          vsIDEInstallDir = vs90IDEInstallDir;
258      #elif (_MSC_VER == 1400) // VC80
259          vsIDEInstallDir = vs80IDEInstallDir;
260      #else
261          vsIDEInstallDir = vs90IDEInstallDir;
262      #endif
263    #else
264      vsIDEInstallDir = vs90IDEInstallDir;
265    #endif
266  }
267  else if (has90)
268    vsIDEInstallDir = vs90IDEInstallDir;
269  else if (has80)
270    vsIDEInstallDir = vs80IDEInstallDir;
271  if (vsIDEInstallDir && *vsIDEInstallDir) {
272    char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
273    if (p)
274      *p = '\0';
275    path = vsIDEInstallDir;
276    return(true);
277  }
278  else {
279    // Try the environment.
280    const char* vs90comntools = getenv("VS90COMNTOOLS");
281    const char* vs80comntools = getenv("VS80COMNTOOLS");
282    const char* vscomntools = NULL;
283      // If we have both vc80 and vc90, pick version we were compiled with.
284    if (vs90comntools && vs80comntools) {
285      #if (_MSC_VER >= 1500)  // VC90
286          vscomntools = vs90comntools;
287      #elif (_MSC_VER == 1400) // VC80
288          vscomntools = vs80comntools;
289      #else
290          vscomntools = vs90comntools;
291      #endif
292    }
293    else if (vs90comntools)
294      vscomntools = vs90comntools;
295    else if (vs80comntools)
296      vscomntools = vs80comntools;
297    if (vscomntools && *vscomntools) {
298      char *p = (char*)strstr(vscomntools, "\\Common7\\Tools");
299      if (p)
300        *p = '\0';
301      path = vscomntools;
302      return(true);
303    }
304    else
305      return(false);
306  }
307  return(false);
308}
309
310void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple) {
311  // FIXME: temporary hack: hard-coded paths.
312  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
313  if (CIncludeDirs != "") {
314    llvm::SmallVector<llvm::StringRef, 5> dirs;
315    CIncludeDirs.split(dirs, ":");
316    for (llvm::SmallVectorImpl<llvm::StringRef>::iterator i = dirs.begin();
317         i != dirs.end();
318         ++i)
319      AddPath(*i, System, false, false, false);
320    return;
321  }
322  llvm::Triple::OSType os = triple.getOS();
323  switch (os) {
324  case llvm::Triple::Win32:
325    {
326      std::string VSDir;
327      if (getVisualStudioDir(VSDir)) {
328        AddPath(VSDir + "\\VC\\include", System, false, false, false);
329        AddPath(VSDir + "\\VC\\PlatformSDK\\Include",
330          System, false, false, false);
331      }
332      else {
333          // Default install paths.
334        AddPath("C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
335          System, false, false, false);
336        AddPath(
337        "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
338          System, false, false, false);
339        AddPath("C:/Program Files/Microsoft Visual Studio 8/VC/include",
340          System, false, false, false);
341        AddPath(
342        "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include",
343          System, false, false, false);
344          // For some clang developers.
345        AddPath("G:/Program Files/Microsoft Visual Studio 9.0/VC/include",
346          System, false, false, false);
347        AddPath(
348        "G:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
349          System, false, false, false);
350      }
351    }
352    break;
353  case llvm::Triple::MinGW64:
354  case llvm::Triple::MinGW32:
355    AddPath("c:/mingw/include", System, true, false, false);
356    break;
357  default:
358    break;
359  }
360
361  AddPath("/usr/local/include", System, false, false, false);
362  AddPath("/usr/include", System, false, false, false);
363}
364
365void InitHeaderSearch::AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple) {
366  llvm::Triple::OSType os = triple.getOS();
367  llvm::StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
368  if (CxxIncludeRoot != "") {
369    llvm::StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
370    if (CxxIncludeArch == "")
371      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
372                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR, triple);
373    else
374      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
375                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR, triple);
376    return;
377  }
378  // FIXME: temporary hack: hard-coded paths.
379  switch (os) {
380  case llvm::Triple::Cygwin:
381    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include",
382        System, true, false, false);
383    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include/c++",
384        System, true, false, false);
385    break;
386  case llvm::Triple::MinGW64:
387    // Try gcc 4.4.0
388    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.4.0");
389    // Try gcc 4.3.0
390    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.3.0");
391    // Fall through.
392  case llvm::Triple::MinGW32:
393    // Try gcc 4.4.0
394    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
395    // Try gcc 4.3.0
396    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
397    break;
398  case llvm::Triple::Darwin:
399    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
400                                "i686-apple-darwin10", "", "x86_64", triple);
401    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
402                                "i686-apple-darwin8", "", "", triple);
403    break;
404  case llvm::Triple::Linux:
405    // Ubuntu 7.10 - Gutsy Gibbon
406    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.3",
407                                "i486-linux-gnu", "", "", triple);
408    // Ubuntu 9.04
409    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.3",
410                                "x86_64-linux-gnu","32", "", triple);
411    // Ubuntu 9.10
412    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
413                                "x86_64-linux-gnu", "32", "", triple);
414    // Fedora 8
415    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
416                                "i386-redhat-linux", "", "", triple);
417    // Fedora 9
418    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
419                                "i386-redhat-linux", "", "", triple);
420    // Fedora 10
421    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
422                                "i386-redhat-linux","", "", triple);
423
424    // Fedora 11
425    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
426                                "i586-redhat-linux","", "", triple);
427
428    // openSUSE 11.1 32 bit
429    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
430                                "i586-suse-linux", "", "", triple);
431    // openSUSE 11.1 64 bit
432    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
433                                "x86_64-suse-linux", "32", "", triple);
434    // openSUSE 11.2
435    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
436                                "i586-suse-linux", "", "", triple);
437    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
438                                "x86_64-suse-linux", "", "", triple);
439    // Arch Linux 2008-06-24
440    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
441                                "i686-pc-linux-gnu", "", "", triple);
442    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
443                                "x86_64-unknown-linux-gnu", "", "", triple);
444    // Gentoo x86 2009.1 stable
445    AddGnuCPlusPlusIncludePaths(
446      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4",
447      "i686-pc-linux-gnu", "", "", triple);
448    // Gentoo x86 2009.0 stable
449    AddGnuCPlusPlusIncludePaths(
450      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
451      "i686-pc-linux-gnu", "", "", triple);
452    // Gentoo x86 2008.0 stable
453    AddGnuCPlusPlusIncludePaths(
454      "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
455      "i686-pc-linux-gnu", "", "", triple);
456    // Ubuntu 8.10
457    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
458                                "i486-pc-linux-gnu", "", "", triple);
459    // Ubuntu 9.04
460    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
461                                "i486-linux-gnu","", "", triple);
462    // Gentoo amd64 stable
463    AddGnuCPlusPlusIncludePaths(
464        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
465        "i686-pc-linux-gnu", "", "", triple);
466    // Exherbo (2009-10-26)
467    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
468                                "x86_64-pc-linux-gnu", "32", "", triple);
469    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
470                                "i686-pc-linux-gnu", "", "", triple);
471    break;
472  case llvm::Triple::FreeBSD:
473    // DragonFly
474    AddPath("/usr/include/c++/4.1", System, true, false, false);
475    // FreeBSD
476    AddPath("/usr/include/c++/4.2", System, true, false, false);
477    break;
478  case llvm::Triple::Solaris:
479    // Solaris - Fall though..
480  case llvm::Triple::AuroraUX:
481    // AuroraUX
482    AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
483                                "i386-pc-solaris2.11", "", "", triple);
484    break;
485  default:
486    break;
487  }
488}
489
490void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
491                                                    const llvm::Triple &triple) {
492  AddDefaultCIncludePaths(triple);
493
494  // Add the default framework include paths on Darwin.
495  if (triple.getOS() == llvm::Triple::Darwin) {
496    AddPath("/System/Library/Frameworks", System, true, false, true);
497    AddPath("/Library/Frameworks", System, true, false, true);
498  }
499
500  if (Lang.CPlusPlus)
501    AddDefaultCPlusPlusIncludePaths(triple);
502}
503
504/// RemoveDuplicates - If there are duplicate directory entries in the specified
505/// search list, remove the later (dead) ones.
506static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
507                             bool Verbose) {
508  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
509  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
510  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
511  for (unsigned i = 0; i != SearchList.size(); ++i) {
512    unsigned DirToRemove = i;
513
514    const DirectoryLookup &CurEntry = SearchList[i];
515
516    if (CurEntry.isNormalDir()) {
517      // If this isn't the first time we've seen this dir, remove it.
518      if (SeenDirs.insert(CurEntry.getDir()))
519        continue;
520    } else if (CurEntry.isFramework()) {
521      // If this isn't the first time we've seen this framework dir, remove it.
522      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
523        continue;
524    } else {
525      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
526      // If this isn't the first time we've seen this headermap, remove it.
527      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
528        continue;
529    }
530
531    // If we have a normal #include dir/framework/headermap that is shadowed
532    // later in the chain by a system include location, we actually want to
533    // ignore the user's request and drop the user dir... keeping the system
534    // dir.  This is weird, but required to emulate GCC's search path correctly.
535    //
536    // Since dupes of system dirs are rare, just rescan to find the original
537    // that we're nuking instead of using a DenseMap.
538    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
539      // Find the dir that this is the same of.
540      unsigned FirstDir;
541      for (FirstDir = 0; ; ++FirstDir) {
542        assert(FirstDir != i && "Didn't find dupe?");
543
544        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
545
546        // If these are different lookup types, then they can't be the dupe.
547        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
548          continue;
549
550        bool isSame;
551        if (CurEntry.isNormalDir())
552          isSame = SearchEntry.getDir() == CurEntry.getDir();
553        else if (CurEntry.isFramework())
554          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
555        else {
556          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
557          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
558        }
559
560        if (isSame)
561          break;
562      }
563
564      // If the first dir in the search path is a non-system dir, zap it
565      // instead of the system one.
566      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
567        DirToRemove = FirstDir;
568    }
569
570    if (Verbose) {
571      fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
572              CurEntry.getName());
573      if (DirToRemove != i)
574        fprintf(stderr, "  as it is a non-system directory that duplicates"
575                " a system directory\n");
576    }
577
578    // This is reached if the current entry is a duplicate.  Remove the
579    // DirToRemove (usually the current dir).
580    SearchList.erase(SearchList.begin()+DirToRemove);
581    --i;
582  }
583}
584
585
586void InitHeaderSearch::Realize() {
587  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
588  std::vector<DirectoryLookup> SearchList;
589  SearchList = IncludeGroup[Angled];
590  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
591                    IncludeGroup[System].end());
592  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
593                    IncludeGroup[After].end());
594  RemoveDuplicates(SearchList, Verbose);
595  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
596
597  // Prepend QUOTED list on the search list.
598  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
599                    IncludeGroup[Quoted].end());
600
601
602  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
603  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
604                         DontSearchCurDir);
605
606  // If verbose, print the list of directories that will be searched.
607  if (Verbose) {
608    fprintf(stderr, "#include \"...\" search starts here:\n");
609    unsigned QuotedIdx = IncludeGroup[Quoted].size();
610    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
611      if (i == QuotedIdx)
612        fprintf(stderr, "#include <...> search starts here:\n");
613      const char *Name = SearchList[i].getName();
614      const char *Suffix;
615      if (SearchList[i].isNormalDir())
616        Suffix = "";
617      else if (SearchList[i].isFramework())
618        Suffix = " (framework directory)";
619      else {
620        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
621        Suffix = " (headermap)";
622      }
623      fprintf(stderr, " %s%s\n", Name, Suffix);
624    }
625    fprintf(stderr, "End of search list.\n");
626  }
627}
628
629void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
630                                     const HeaderSearchOptions &HSOpts,
631                                     const LangOptions &Lang,
632                                     const llvm::Triple &Triple) {
633  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
634
635  // Add the user defined entries.
636  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
637    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
638    Init.AddPath(E.Path, E.Group, false, E.IsUserSupplied, E.IsFramework,
639                 false);
640  }
641
642  // Add entries from CPATH and friends.
643  Init.AddDelimitedPaths(HSOpts.EnvIncPath.c_str());
644  if (Lang.CPlusPlus && Lang.ObjC1)
645    Init.AddDelimitedPaths(HSOpts.ObjCXXEnvIncPath.c_str());
646  else if (Lang.CPlusPlus)
647    Init.AddDelimitedPaths(HSOpts.CXXEnvIncPath.c_str());
648  else if (Lang.ObjC1)
649    Init.AddDelimitedPaths(HSOpts.ObjCEnvIncPath.c_str());
650  else
651    Init.AddDelimitedPaths(HSOpts.CEnvIncPath.c_str());
652
653  if (!HSOpts.BuiltinIncludePath.empty()) {
654    // Ignore the sys root, we *always* look for clang headers relative to
655    // supplied path.
656    Init.AddPath(HSOpts.BuiltinIncludePath, System,
657                 false, false, false, /*IgnoreSysRoot=*/ true);
658  }
659
660  if (HSOpts.UseStandardIncludes)
661    Init.AddDefaultSystemIncludePaths(Lang, Triple);
662
663  Init.Realize();
664}
665