InitHeaderSearch.cpp revision 4c2bcad7b843c10fd4a2ffd43da40bfefb4dc8ba
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/System/Path.h"
27#include "llvm/Config/config.h"
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::Twine &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(llvm::StringRef Base,
60                                   llvm::StringRef ArchDir,
61                                   llvm::StringRef Dir32,
62                                   llvm::StringRef Dir64,
63                                   const llvm::Triple &triple);
64
65  /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to suport a MinGW
66  ///  libstdc++.
67  void AddMinGWCPlusPlusIncludePaths(llvm::StringRef Base,
68                                     llvm::StringRef Arch,
69                                     llvm::StringRef 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(llvm::StringRef 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                                    bool UseStandardCXXIncludes);
87
88  /// Realize - Merges all search path lists into one list and send it to
89  /// HeaderSearch.
90  void Realize();
91};
92
93}
94
95void InitHeaderSearch::AddPath(const llvm::Twine &Path,
96                               IncludeDirGroup Group, bool isCXXAware,
97                               bool isUserSupplied, bool isFramework,
98                               bool IgnoreSysRoot) {
99  assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
100  FileManager &FM = Headers.getFileMgr();
101
102  // Compute the actual path, taking into consideration -isysroot.
103  llvm::SmallString<256> MappedPathStr;
104  llvm::raw_svector_ostream MappedPath(MappedPathStr);
105
106  // Handle isysroot.
107  if (Group == System && !IgnoreSysRoot) {
108    // FIXME: Portability.  This should be a sys::Path interface, this doesn't
109    // handle things like C:\ right, nor win32 \\network\device\blah.
110    if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
111      MappedPath << isysroot;
112  }
113
114  Path.print(MappedPath);
115
116  // Compute the DirectoryLookup type.
117  SrcMgr::CharacteristicKind Type;
118  if (Group == Quoted || Group == Angled)
119    Type = SrcMgr::C_User;
120  else if (isCXXAware)
121    Type = SrcMgr::C_System;
122  else
123    Type = SrcMgr::C_ExternCSystem;
124
125
126  // If the directory exists, add it.
127  if (const DirectoryEntry *DE = FM.getDirectory(MappedPath.str())) {
128    IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
129                                                  isFramework));
130    return;
131  }
132
133  // Check to see if this is an apple-style headermap (which are not allowed to
134  // be frameworks).
135  if (!isFramework) {
136    if (const FileEntry *FE = FM.getFile(MappedPath.str())) {
137      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
138        // It is a headermap, add it to the search path.
139        IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
140        return;
141      }
142    }
143  }
144
145  if (Verbose)
146    llvm::errs() << "ignoring nonexistent directory \""
147                 << MappedPath.str() << "\"\n";
148}
149
150
151void InitHeaderSearch::AddDelimitedPaths(llvm::StringRef at) {
152  if (at.empty()) // Empty string should not add '.' path.
153    return;
154
155  llvm::StringRef::size_type delim;
156  while ((delim = at.find(llvm::sys::PathSeparator)) != llvm::StringRef::npos) {
157    if (delim == 0)
158      AddPath(".", Angled, false, true, false);
159    else
160      AddPath(at.substr(0, delim), Angled, false, true, false);
161    at = at.substr(delim + 1);
162  }
163
164  if (at.empty())
165    AddPath(".", Angled, false, true, false);
166  else
167    AddPath(at, Angled, false, true, false);
168}
169
170void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(llvm::StringRef Base,
171                                                   llvm::StringRef ArchDir,
172                                                   llvm::StringRef Dir32,
173                                                   llvm::StringRef Dir64,
174                                                   const llvm::Triple &triple) {
175  // Add the base dir
176  AddPath(Base, System, true, false, false);
177
178  // Add the multilib dirs
179  llvm::Triple::ArchType arch = triple.getArch();
180  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
181  if (is64bit)
182    AddPath(Base + "/" + ArchDir + "/" + Dir64, System, true, false, false);
183  else
184    AddPath(Base + "/" + ArchDir + "/" + Dir32, System, true, false, false);
185
186  // Add the backward dir
187  AddPath(Base + "/backward", System, true, false, false);
188}
189
190void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(llvm::StringRef Base,
191                                                     llvm::StringRef Arch,
192                                                     llvm::StringRef Version) {
193  AddPath(Base + "/" + Arch + "/" + Version + "/include",
194          System, true, false, false);
195  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
196          System, true, false, false);
197  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
198          System, true, false, false);
199}
200
201  // FIXME: This probably should goto to some platform utils place.
202#ifdef _MSC_VER
203
204  // Read registry string.
205  // This also supports a means to look for high-versioned keys by use
206  // of a $VERSION placeholder in the key path.
207  // $VERSION in the key path is a placeholder for the version number,
208  // causing the highest value path to be searched for and used.
209  // I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
210  // There can be additional characters in the component.  Only the numberic
211  // characters are compared.
212static bool getSystemRegistryString(const char *keyPath, const char *valueName,
213                                    char *value, size_t maxLength) {
214  HKEY hRootKey = NULL;
215  HKEY hKey = NULL;
216  const char* subKey = NULL;
217  DWORD valueType;
218  DWORD valueSize = maxLength - 1;
219  long lResult;
220  bool returnValue = false;
221  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) {
222    hRootKey = HKEY_CLASSES_ROOT;
223    subKey = keyPath + 18;
224  }
225  else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) {
226    hRootKey = HKEY_USERS;
227    subKey = keyPath + 11;
228  }
229  else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) {
230    hRootKey = HKEY_LOCAL_MACHINE;
231    subKey = keyPath + 19;
232  }
233  else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) {
234    hRootKey = HKEY_CURRENT_USER;
235    subKey = keyPath + 18;
236  }
237  else
238    return(false);
239  const char *placeHolder = strstr(subKey, "$VERSION");
240  char bestName[256];
241  bestName[0] = '\0';
242  // If we have a $VERSION placeholder, do the highest-version search.
243  if (placeHolder) {
244    const char *keyEnd = placeHolder - 1;
245    const char *nextKey = placeHolder;
246    // Find end of previous key.
247    while ((keyEnd > subKey) && (*keyEnd != '\\'))
248      keyEnd--;
249    // Find end of key containing $VERSION.
250    while (*nextKey && (*nextKey != '\\'))
251      nextKey++;
252    size_t partialKeyLength = keyEnd - subKey;
253    char partialKey[256];
254    if (partialKeyLength > sizeof(partialKey))
255      partialKeyLength = sizeof(partialKey);
256    strncpy(partialKey, subKey, partialKeyLength);
257    partialKey[partialKeyLength] = '\0';
258    HKEY hTopKey = NULL;
259    lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey);
260    if (lResult == ERROR_SUCCESS) {
261      char keyName[256];
262      int bestIndex = -1;
263      double bestValue = 0.0;
264      DWORD index, size = sizeof(keyName) - 1;
265      for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
266          NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
267        const char *sp = keyName;
268        while (*sp && !isdigit(*sp))
269          sp++;
270        if (!*sp)
271          continue;
272        const char *ep = sp + 1;
273        while (*ep && (isdigit(*ep) || (*ep == '.')))
274          ep++;
275        char numBuf[32];
276        strncpy(numBuf, sp, sizeof(numBuf) - 1);
277        numBuf[sizeof(numBuf) - 1] = '\0';
278        double value = strtod(numBuf, NULL);
279        if (value > bestValue) {
280          bestIndex = (int)index;
281          bestValue = value;
282          strcpy(bestName, keyName);
283        }
284        size = sizeof(keyName) - 1;
285      }
286      // If we found the highest versioned key, open the key and get the value.
287      if (bestIndex != -1) {
288        // Append rest of key.
289        strncat(bestName, nextKey, sizeof(bestName) - 1);
290        bestName[sizeof(bestName) - 1] = '\0';
291        // Open the chosen key path remainder.
292        lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey);
293        if (lResult == ERROR_SUCCESS) {
294          lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
295            (LPBYTE)value, &valueSize);
296          if (lResult == ERROR_SUCCESS)
297            returnValue = true;
298          RegCloseKey(hKey);
299        }
300      }
301      RegCloseKey(hTopKey);
302    }
303  }
304  else {
305    lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
306    if (lResult == ERROR_SUCCESS) {
307      lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
308        (LPBYTE)value, &valueSize);
309      if (lResult == ERROR_SUCCESS)
310        returnValue = true;
311      RegCloseKey(hKey);
312    }
313  }
314  return(returnValue);
315}
316#else // _MSC_VER
317  // Read registry string.
318static bool getSystemRegistryString(const char*, const char*, char*, size_t) {
319  return(false);
320}
321#endif // _MSC_VER
322
323  // Get Visual Studio installation directory.
324static bool getVisualStudioDir(std::string &path) {
325  char vsIDEInstallDir[256];
326  // Try the Windows registry first.
327  bool hasVCDir = getSystemRegistryString(
328    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
329    "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1);
330    // If we have both vc80 and vc90, pick version we were compiled with.
331  if (hasVCDir && vsIDEInstallDir[0]) {
332    char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
333    if (p)
334      *p = '\0';
335    path = vsIDEInstallDir;
336    return(true);
337  }
338  else {
339    // Try the environment.
340    const char* vs90comntools = getenv("VS90COMNTOOLS");
341    const char* vs80comntools = getenv("VS80COMNTOOLS");
342    const char* vscomntools = NULL;
343      // If we have both vc80 and vc90, pick version we were compiled with.
344    if (vs90comntools && vs80comntools) {
345      #if (_MSC_VER >= 1500)  // VC90
346          vscomntools = vs90comntools;
347      #elif (_MSC_VER == 1400) // VC80
348          vscomntools = vs80comntools;
349      #else
350          vscomntools = vs90comntools;
351      #endif
352    }
353    else if (vs90comntools)
354      vscomntools = vs90comntools;
355    else if (vs80comntools)
356      vscomntools = vs80comntools;
357    if (vscomntools && *vscomntools) {
358      char *p = (char*)strstr(vscomntools, "\\Common7\\Tools");
359      if (p)
360        *p = '\0';
361      path = vscomntools;
362      return(true);
363    }
364    else
365      return(false);
366  }
367  return(false);
368}
369
370  // Get Windows SDK installation directory.
371static bool getWindowsSDKDir(std::string &path) {
372  char windowsSDKInstallDir[256];
373  // Try the Windows registry.
374  bool hasSDKDir = getSystemRegistryString(
375   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
376    "InstallationFolder", windowsSDKInstallDir, sizeof(windowsSDKInstallDir) - 1);
377    // If we have both vc80 and vc90, pick version we were compiled with.
378  if (hasSDKDir && windowsSDKInstallDir[0]) {
379    path = windowsSDKInstallDir;
380    return(true);
381  }
382  return(false);
383}
384
385void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple) {
386  // FIXME: temporary hack: hard-coded paths.
387  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
388  if (CIncludeDirs != "") {
389    llvm::SmallVector<llvm::StringRef, 5> dirs;
390    CIncludeDirs.split(dirs, ":");
391    for (llvm::SmallVectorImpl<llvm::StringRef>::iterator i = dirs.begin();
392         i != dirs.end();
393         ++i)
394      AddPath(*i, System, false, false, false);
395    return;
396  }
397  llvm::Triple::OSType os = triple.getOS();
398  switch (os) {
399  case llvm::Triple::Win32:
400    {
401      std::string VSDir;
402      std::string WindowsSDKDir;
403      if (getVisualStudioDir(VSDir)) {
404        AddPath(VSDir + "\\VC\\include", System, false, false, false);
405        if (getWindowsSDKDir(WindowsSDKDir))
406          AddPath(WindowsSDKDir, System, false, false, false);
407        else
408          AddPath(VSDir + "\\VC\\PlatformSDK\\Include",
409            System, false, false, false);
410      }
411      else {
412          // Default install paths.
413        AddPath("C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
414          System, false, false, false);
415        AddPath(
416        "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
417          System, false, false, false);
418        AddPath("C:/Program Files/Microsoft Visual Studio 8/VC/include",
419          System, false, false, false);
420        AddPath(
421        "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include",
422          System, false, false, false);
423          // For some clang developers.
424        AddPath("G:/Program Files/Microsoft Visual Studio 9.0/VC/include",
425          System, false, false, false);
426        AddPath(
427        "G:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
428          System, false, false, false);
429      }
430    }
431    break;
432  case llvm::Triple::MinGW64:
433  case llvm::Triple::MinGW32:
434    AddPath("c:/mingw/include", System, true, false, false);
435    break;
436  default:
437    break;
438  }
439
440  AddPath("/usr/local/include", System, true, false, false);
441  AddPath("/usr/include", System, false, false, false);
442}
443
444void InitHeaderSearch::AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple) {
445  llvm::Triple::OSType os = triple.getOS();
446  llvm::StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
447  if (CxxIncludeRoot != "") {
448    llvm::StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
449    if (CxxIncludeArch == "")
450      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
451                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR, triple);
452    else
453      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
454                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR, triple);
455    return;
456  }
457  // FIXME: temporary hack: hard-coded paths.
458  switch (os) {
459  case llvm::Triple::Cygwin:
460    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include",
461        System, true, false, false);
462    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include/c++",
463        System, true, false, false);
464    break;
465  case llvm::Triple::MinGW64:
466    // Try gcc 4.4.0
467    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.4.0");
468    // Try gcc 4.3.0
469    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.3.0");
470    // Fall through.
471  case llvm::Triple::MinGW32:
472    // Try gcc 4.4.0
473    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
474    // Try gcc 4.3.0
475    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
476    break;
477  case llvm::Triple::Darwin:
478    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
479                                "i686-apple-darwin10", "", "x86_64", triple);
480    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
481                                "i686-apple-darwin8", "", "", triple);
482    break;
483  case llvm::Triple::DragonFly:
484    AddPath("/usr/include/c++/4.1", System, true, false, false);
485    break;
486  case llvm::Triple::Linux:
487    // Exherbo (2010-01-25)
488    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
489                                "x86_64-pc-linux-gnu", "32", "", triple);
490    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
491                                "i686-pc-linux-gnu", "", "", triple);
492    // Debian sid
493    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
494                                "x86_64-linux-gnu", "32", "", triple);
495    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
496                                "i486-linux-gnu", "64", "", triple);
497    // Ubuntu 7.10 - Gutsy Gibbon
498    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.3",
499                                "i486-linux-gnu", "", "", triple);
500    // Ubuntu 9.04
501    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.3",
502                                "x86_64-linux-gnu","32", "", triple);
503    // Ubuntu 9.10
504    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
505                                "x86_64-linux-gnu", "32", "", triple);
506    // Fedora 8
507    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
508                                "i386-redhat-linux", "", "", triple);
509    // Fedora 9
510    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
511                                "i386-redhat-linux", "", "", triple);
512    // Fedora 10
513    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
514                                "i386-redhat-linux","", "", triple);
515
516    // Fedora 10 x86_64
517    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
518                                "x86_64-redhat-linux", "32", "", triple);
519
520    // Fedora 11
521    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
522                                "i586-redhat-linux","", "", triple);
523
524    // Fedora 12
525    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
526                                "i686-redhat-linux","", "", triple);
527
528    // Fedora 12 (February-2010+)
529    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
530                                "i686-redhat-linux","", "", triple);
531
532    // openSUSE 11.1 32 bit
533    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
534                                "i586-suse-linux", "", "", triple);
535    // openSUSE 11.1 64 bit
536    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
537                                "x86_64-suse-linux", "32", "", triple);
538    // openSUSE 11.2
539    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
540                                "i586-suse-linux", "", "", triple);
541    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
542                                "x86_64-suse-linux", "", "", triple);
543    // Arch Linux 2008-06-24
544    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
545                                "i686-pc-linux-gnu", "", "", triple);
546    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
547                                "x86_64-unknown-linux-gnu", "", "", triple);
548    // Gentoo x86 2009.1 stable
549    AddGnuCPlusPlusIncludePaths(
550      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4",
551      "i686-pc-linux-gnu", "", "", triple);
552    // Gentoo x86 2009.0 stable
553    AddGnuCPlusPlusIncludePaths(
554      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
555      "i686-pc-linux-gnu", "", "", triple);
556    // Gentoo x86 2008.0 stable
557    AddGnuCPlusPlusIncludePaths(
558      "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
559      "i686-pc-linux-gnu", "", "", triple);
560    // Ubuntu 8.10
561    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
562                                "i486-pc-linux-gnu", "", "", triple);
563    // Ubuntu 9.04
564    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
565                                "i486-linux-gnu","", "", triple);
566    // Gentoo amd64 stable
567    AddGnuCPlusPlusIncludePaths(
568        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
569        "i686-pc-linux-gnu", "", "", triple);
570
571    // Gentoo amd64 gcc 4.3.2
572    AddGnuCPlusPlusIncludePaths(
573        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.2/include/g++-v4",
574        "x86_64-pc-linux-gnu", "", "", triple);
575
576    // Gentoo amd64 gcc 4.4.3
577    AddGnuCPlusPlusIncludePaths(
578        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.3/include/g++-v4",
579        "x86_64-pc-linux-gnu", "32", "", triple);
580
581    break;
582  case llvm::Triple::FreeBSD:
583    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2", "", "", "", triple);
584    break;
585  case llvm::Triple::Solaris:
586    // Solaris - Fall though..
587  case llvm::Triple::AuroraUX:
588    // AuroraUX
589    AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
590                                "i386-pc-solaris2.11", "", "", triple);
591    break;
592  default:
593    break;
594  }
595}
596
597void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
598                                                    const llvm::Triple &triple,
599                                                  bool UseStandardCXXIncludes) {
600  if (Lang.CPlusPlus && UseStandardCXXIncludes)
601    AddDefaultCPlusPlusIncludePaths(triple);
602
603  AddDefaultCIncludePaths(triple);
604
605  // Add the default framework include paths on Darwin.
606  if (triple.getOS() == llvm::Triple::Darwin) {
607    AddPath("/System/Library/Frameworks", System, true, false, true);
608    AddPath("/Library/Frameworks", System, true, false, true);
609  }
610}
611
612/// RemoveDuplicates - If there are duplicate directory entries in the specified
613/// search list, remove the later (dead) ones.
614static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
615                             bool Verbose) {
616  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
617  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
618  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
619  for (unsigned i = 0; i != SearchList.size(); ++i) {
620    unsigned DirToRemove = i;
621
622    const DirectoryLookup &CurEntry = SearchList[i];
623
624    if (CurEntry.isNormalDir()) {
625      // If this isn't the first time we've seen this dir, remove it.
626      if (SeenDirs.insert(CurEntry.getDir()))
627        continue;
628    } else if (CurEntry.isFramework()) {
629      // If this isn't the first time we've seen this framework dir, remove it.
630      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
631        continue;
632    } else {
633      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
634      // If this isn't the first time we've seen this headermap, remove it.
635      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
636        continue;
637    }
638
639    // If we have a normal #include dir/framework/headermap that is shadowed
640    // later in the chain by a system include location, we actually want to
641    // ignore the user's request and drop the user dir... keeping the system
642    // dir.  This is weird, but required to emulate GCC's search path correctly.
643    //
644    // Since dupes of system dirs are rare, just rescan to find the original
645    // that we're nuking instead of using a DenseMap.
646    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
647      // Find the dir that this is the same of.
648      unsigned FirstDir;
649      for (FirstDir = 0; ; ++FirstDir) {
650        assert(FirstDir != i && "Didn't find dupe?");
651
652        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
653
654        // If these are different lookup types, then they can't be the dupe.
655        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
656          continue;
657
658        bool isSame;
659        if (CurEntry.isNormalDir())
660          isSame = SearchEntry.getDir() == CurEntry.getDir();
661        else if (CurEntry.isFramework())
662          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
663        else {
664          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
665          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
666        }
667
668        if (isSame)
669          break;
670      }
671
672      // If the first dir in the search path is a non-system dir, zap it
673      // instead of the system one.
674      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
675        DirToRemove = FirstDir;
676    }
677
678    if (Verbose) {
679      llvm::errs() << "ignoring duplicate directory \""
680                   << CurEntry.getName() << "\"\n";
681      if (DirToRemove != i)
682        llvm::errs() << "  as it is a non-system directory that duplicates "
683                     << "a system directory\n";
684    }
685
686    // This is reached if the current entry is a duplicate.  Remove the
687    // DirToRemove (usually the current dir).
688    SearchList.erase(SearchList.begin()+DirToRemove);
689    --i;
690  }
691}
692
693
694void InitHeaderSearch::Realize() {
695  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
696  std::vector<DirectoryLookup> SearchList;
697  SearchList = IncludeGroup[Angled];
698  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
699                    IncludeGroup[System].end());
700  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
701                    IncludeGroup[After].end());
702  RemoveDuplicates(SearchList, Verbose);
703  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
704
705  // Prepend QUOTED list on the search list.
706  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
707                    IncludeGroup[Quoted].end());
708
709
710  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
711  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
712                         DontSearchCurDir);
713
714  // If verbose, print the list of directories that will be searched.
715  if (Verbose) {
716    llvm::errs() << "#include \"...\" search starts here:\n";
717    unsigned QuotedIdx = IncludeGroup[Quoted].size();
718    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
719      if (i == QuotedIdx)
720        llvm::errs() << "#include <...> search starts here:\n";
721      const char *Name = SearchList[i].getName();
722      const char *Suffix;
723      if (SearchList[i].isNormalDir())
724        Suffix = "";
725      else if (SearchList[i].isFramework())
726        Suffix = " (framework directory)";
727      else {
728        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
729        Suffix = " (headermap)";
730      }
731      llvm::errs() << " " << Name << Suffix << "\n";
732    }
733    llvm::errs() << "End of search list.\n";
734  }
735}
736
737void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
738                                     const HeaderSearchOptions &HSOpts,
739                                     const LangOptions &Lang,
740                                     const llvm::Triple &Triple) {
741  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
742
743  // Add the user defined entries.
744  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
745    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
746    Init.AddPath(E.Path, E.Group, false, E.IsUserSupplied, E.IsFramework,
747                 false);
748  }
749
750  // Add entries from CPATH and friends.
751  Init.AddDelimitedPaths(HSOpts.EnvIncPath);
752  if (Lang.CPlusPlus && Lang.ObjC1)
753    Init.AddDelimitedPaths(HSOpts.ObjCXXEnvIncPath);
754  else if (Lang.CPlusPlus)
755    Init.AddDelimitedPaths(HSOpts.CXXEnvIncPath);
756  else if (Lang.ObjC1)
757    Init.AddDelimitedPaths(HSOpts.ObjCEnvIncPath);
758  else
759    Init.AddDelimitedPaths(HSOpts.CEnvIncPath);
760
761  if (HSOpts.UseBuiltinIncludes) {
762    // Ignore the sys root, we *always* look for clang headers relative to
763    // supplied path.
764    llvm::sys::Path P(HSOpts.ResourceDir);
765    P.appendComponent("include");
766    Init.AddPath(P.str(), System, false, false, false, /*IgnoreSysRoot=*/ true);
767  }
768
769  if (HSOpts.UseStandardIncludes)
770    Init.AddDefaultSystemIncludePaths(Lang, Triple,
771                                      HSOpts.UseStandardCXXIncludes);
772
773  Init.Realize();
774}
775