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