]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Driver/ToolChains.cpp
Vendor import of clang tags/RELEASE_32/final r170710 (effectively, 3.2
[FreeBSD/FreeBSD.git] / lib / Driver / ToolChains.cpp
1 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
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 #include "ToolChains.h"
11
12 #include "clang/Driver/Arg.h"
13 #include "clang/Driver/ArgList.h"
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/OptTable.h"
18 #include "clang/Driver/Option.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Basic/ObjCRuntime.h"
21 #include "clang/Basic/Version.h"
22
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/system_error.h"
33
34 #include "SanitizerArgs.h"
35
36 #include <cstdlib> // ::getenv
37
38 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
39
40 using namespace clang::driver;
41 using namespace clang::driver::toolchains;
42 using namespace clang;
43
44 /// Darwin - Darwin tool chain for i386 and x86_64.
45
46 Darwin::Darwin(const Driver &D, const llvm::Triple& Triple)
47   : ToolChain(D, Triple), TargetInitialized(false)
48 {
49   // Compute the initial Darwin version from the triple
50   unsigned Major, Minor, Micro;
51   if (!Triple.getMacOSXVersion(Major, Minor, Micro))
52     getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
53       Triple.getOSName();
54   llvm::raw_string_ostream(MacosxVersionMin)
55     << Major << '.' << Minor << '.' << Micro;
56
57   // FIXME: DarwinVersion is only used to find GCC's libexec directory.
58   // It should be removed when we stop supporting that.
59   DarwinVersion[0] = Minor + 4;
60   DarwinVersion[1] = Micro;
61   DarwinVersion[2] = 0;
62
63   // Compute the initial iOS version from the triple
64   Triple.getiOSVersion(Major, Minor, Micro);
65   llvm::raw_string_ostream(iOSVersionMin)
66     << Major << '.' << Minor << '.' << Micro;
67 }
68
69 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
70   types::ID Ty = types::lookupTypeForExtension(Ext);
71
72   // Darwin always preprocesses assembly files (unless -x is used explicitly).
73   if (Ty == types::TY_PP_Asm)
74     return types::TY_Asm;
75
76   return Ty;
77 }
78
79 bool Darwin::HasNativeLLVMSupport() const {
80   return true;
81 }
82
83 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
84 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
85   if (isTargetIPhoneOS())
86     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
87   if (isNonFragile)
88     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
89   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
90 }
91
92 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
93 bool Darwin::hasBlocksRuntime() const {
94   if (isTargetIPhoneOS())
95     return !isIPhoneOSVersionLT(3, 2);
96   else
97     return !isMacosxVersionLT(10, 6);
98 }
99
100 static const char *GetArmArchForMArch(StringRef Value) {
101   return llvm::StringSwitch<const char*>(Value)
102     .Case("armv6k", "armv6")
103     .Case("armv5tej", "armv5")
104     .Case("xscale", "xscale")
105     .Case("armv4t", "armv4t")
106     .Case("armv7", "armv7")
107     .Cases("armv7a", "armv7-a", "armv7")
108     .Cases("armv7r", "armv7-r", "armv7")
109     .Cases("armv7m", "armv7-m", "armv7")
110     .Cases("armv7f", "armv7-f", "armv7f")
111     .Cases("armv7k", "armv7-k", "armv7k")
112     .Cases("armv7s", "armv7-s", "armv7s")
113     .Default(0);
114 }
115
116 static const char *GetArmArchForMCpu(StringRef Value) {
117   return llvm::StringSwitch<const char *>(Value)
118     .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
119     .Cases("arm10e", "arm10tdmi", "armv5")
120     .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
121     .Case("xscale", "xscale")
122     .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s",
123            "arm1176jzf-s", "cortex-m0", "armv6")
124     .Cases("cortex-a8", "cortex-r4", "cortex-m3", "cortex-a9", "cortex-a15",
125            "armv7")
126     .Case("cortex-a9-mp", "armv7f")
127     .Case("swift", "armv7s")
128     .Default(0);
129 }
130
131 StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
132   switch (getTriple().getArch()) {
133   default:
134     return getArchName();
135
136   case llvm::Triple::thumb:
137   case llvm::Triple::arm: {
138     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
139       if (const char *Arch = GetArmArchForMArch(A->getValue()))
140         return Arch;
141
142     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
143       if (const char *Arch = GetArmArchForMCpu(A->getValue()))
144         return Arch;
145
146     return "arm";
147   }
148   }
149 }
150
151 Darwin::~Darwin() {
152   // Free tool implementations.
153   for (llvm::DenseMap<unsigned, Tool*>::iterator
154          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
155     delete it->second;
156 }
157
158 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
159                                                 types::ID InputType) const {
160   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
161
162   // If the target isn't initialized (e.g., an unknown Darwin platform, return
163   // the default triple).
164   if (!isTargetInitialized())
165     return Triple.getTriple();
166
167   SmallString<16> Str;
168   Str += isTargetIPhoneOS() ? "ios" : "macosx";
169   Str += getTargetVersion().getAsString();
170   Triple.setOSName(Str);
171
172   return Triple.getTriple();
173 }
174
175 void Generic_ELF::anchor() {}
176
177 Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
178                          const ActionList &Inputs) const {
179   Action::ActionClass Key = JA.getKind();
180
181   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
182     // FIXME: This seems like a hacky way to choose clang frontend.
183     Key = Action::AnalyzeJobClass;
184   }
185
186   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
187                                              options::OPT_no_integrated_as,
188                                              IsIntegratedAssemblerDefault());
189
190   Tool *&T = Tools[Key];
191   if (!T) {
192     switch (Key) {
193     case Action::InputClass:
194     case Action::BindArchClass:
195       llvm_unreachable("Invalid tool kind.");
196     case Action::PreprocessJobClass:
197       T = new tools::darwin::Preprocess(*this); break;
198     case Action::AnalyzeJobClass:
199     case Action::MigrateJobClass:
200       T = new tools::Clang(*this); break;
201     case Action::PrecompileJobClass:
202     case Action::CompileJobClass:
203       T = new tools::darwin::Compile(*this); break;
204     case Action::AssembleJobClass: {
205       if (UseIntegratedAs)
206         T = new tools::ClangAs(*this);
207       else
208         T = new tools::darwin::Assemble(*this);
209       break;
210     }
211     case Action::LinkJobClass:
212       T = new tools::darwin::Link(*this); break;
213     case Action::LipoJobClass:
214       T = new tools::darwin::Lipo(*this); break;
215     case Action::DsymutilJobClass:
216       T = new tools::darwin::Dsymutil(*this); break;
217     case Action::VerifyJobClass:
218       T = new tools::darwin::VerifyDebug(*this); break;
219     }
220   }
221
222   return *T;
223 }
224
225
226 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple)
227   : Darwin(D, Triple)
228 {
229   getProgramPaths().push_back(getDriver().getInstalledDir());
230   if (getDriver().getInstalledDir() != getDriver().Dir)
231     getProgramPaths().push_back(getDriver().Dir);
232
233   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
234   getProgramPaths().push_back(getDriver().getInstalledDir());
235   if (getDriver().getInstalledDir() != getDriver().Dir)
236     getProgramPaths().push_back(getDriver().Dir);
237 }
238
239 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
240                                  ArgStringList &CmdArgs) const {
241
242   CmdArgs.push_back("-force_load");
243   llvm::sys::Path P(getDriver().ClangExecutable);
244   P.eraseComponent(); // 'clang'
245   P.eraseComponent(); // 'bin'
246   P.appendComponent("lib");
247   P.appendComponent("arc");
248   P.appendComponent("libarclite_");
249   std::string s = P.str();
250   // Mash in the platform.
251   if (isTargetIOSSimulator())
252     s += "iphonesimulator";
253   else if (isTargetIPhoneOS())
254     s += "iphoneos";
255   else
256     s += "macosx";
257   s += ".a";
258
259   CmdArgs.push_back(Args.MakeArgString(s));
260 }
261
262 void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
263                                     ArgStringList &CmdArgs,
264                                     const char *DarwinStaticLib) const {
265   llvm::sys::Path P(getDriver().ResourceDir);
266   P.appendComponent("lib");
267   P.appendComponent("darwin");
268   P.appendComponent(DarwinStaticLib);
269
270   // For now, allow missing resource libraries to support developers who may
271   // not have compiler-rt checked out or integrated into their build.
272   bool Exists;
273   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
274     CmdArgs.push_back(Args.MakeArgString(P.str()));
275 }
276
277 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
278                                         ArgStringList &CmdArgs) const {
279   // Darwin only supports the compiler-rt based runtime libraries.
280   switch (GetRuntimeLibType(Args)) {
281   case ToolChain::RLT_CompilerRT:
282     break;
283   default:
284     getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
285       << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
286     return;
287   }
288
289   // Darwin doesn't support real static executables, don't link any runtime
290   // libraries with -static.
291   if (Args.hasArg(options::OPT_static) ||
292       Args.hasArg(options::OPT_fapple_kext) ||
293       Args.hasArg(options::OPT_mkernel))
294     return;
295
296   // Reject -static-libgcc for now, we can deal with this when and if someone
297   // cares. This is useful in situations where someone wants to statically link
298   // something like libstdc++, and needs its runtime support routines.
299   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
300     getDriver().Diag(diag::err_drv_unsupported_opt)
301       << A->getAsString(Args);
302     return;
303   }
304
305   // If we are building profile support, link that library in.
306   if (Args.hasArg(options::OPT_fprofile_arcs) ||
307       Args.hasArg(options::OPT_fprofile_generate) ||
308       Args.hasArg(options::OPT_fcreate_profile) ||
309       Args.hasArg(options::OPT_coverage)) {
310     // Select the appropriate runtime library for the target.
311     if (isTargetIPhoneOS()) {
312       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
313     } else {
314       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
315     }
316   }
317
318   SanitizerArgs Sanitize(getDriver(), Args);
319
320   // Add ASAN runtime library, if required. Dynamic libraries and bundles
321   // should not be linked with the runtime library.
322   if (Sanitize.needsAsanRt()) {
323     if (Args.hasArg(options::OPT_dynamiclib) ||
324         Args.hasArg(options::OPT_bundle)) return;
325     if (isTargetIPhoneOS()) {
326       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
327         << "-fsanitize=address";
328     } else {
329       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx.a");
330
331       // The ASAN runtime library requires C++ and CoreFoundation.
332       AddCXXStdlibLibArgs(Args, CmdArgs);
333       CmdArgs.push_back("-framework");
334       CmdArgs.push_back("CoreFoundation");
335     }
336   }
337
338   // Otherwise link libSystem, then the dynamic runtime library, and finally any
339   // target specific static runtime library.
340   CmdArgs.push_back("-lSystem");
341
342   // Select the dynamic runtime library and the target specific static library.
343   if (isTargetIPhoneOS()) {
344     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
345     // it never went into the SDK.
346     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
347     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
348       CmdArgs.push_back("-lgcc_s.1");
349
350     // We currently always need a static runtime library for iOS.
351     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
352   } else {
353     // The dynamic runtime library was merged with libSystem for 10.6 and
354     // beyond; only 10.4 and 10.5 need an additional runtime library.
355     if (isMacosxVersionLT(10, 5))
356       CmdArgs.push_back("-lgcc_s.10.4");
357     else if (isMacosxVersionLT(10, 6))
358       CmdArgs.push_back("-lgcc_s.10.5");
359
360     // For OS X, we thought we would only need a static runtime library when
361     // targeting 10.4, to provide versions of the static functions which were
362     // omitted from 10.4.dylib.
363     //
364     // Unfortunately, that turned out to not be true, because Darwin system
365     // headers can still use eprintf on i386, and it is not exported from
366     // libSystem. Therefore, we still must provide a runtime library just for
367     // the tiny tiny handful of projects that *might* use that symbol.
368     if (isMacosxVersionLT(10, 5)) {
369       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
370     } else {
371       if (getTriple().getArch() == llvm::Triple::x86)
372         AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
373       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
374     }
375   }
376 }
377
378 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
379   const OptTable &Opts = getDriver().getOpts();
380
381   // Support allowing the SDKROOT environment variable used by xcrun and other
382   // Xcode tools to define the default sysroot, by making it the default for
383   // isysroot.
384   if (!Args.hasArg(options::OPT_isysroot)) {
385     if (char *env = ::getenv("SDKROOT")) {
386       // We only use this value as the default if it is an absolute path and
387       // exists.
388       if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env)) {
389         Args.append(Args.MakeSeparateArg(
390                       0, Opts.getOption(options::OPT_isysroot), env));
391       }
392     }
393   }
394
395   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
396   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
397   Arg *iOSSimVersion = Args.getLastArg(
398     options::OPT_mios_simulator_version_min_EQ);
399
400   if (OSXVersion && (iOSVersion || iOSSimVersion)) {
401     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
402           << OSXVersion->getAsString(Args)
403           << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
404     iOSVersion = iOSSimVersion = 0;
405   } else if (iOSVersion && iOSSimVersion) {
406     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
407           << iOSVersion->getAsString(Args)
408           << iOSSimVersion->getAsString(Args);
409     iOSSimVersion = 0;
410   } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
411     // If no deployment target was specified on the command line, check for
412     // environment defines.
413     StringRef OSXTarget;
414     StringRef iOSTarget;
415     StringRef iOSSimTarget;
416     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
417       OSXTarget = env;
418     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
419       iOSTarget = env;
420     if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
421       iOSSimTarget = env;
422
423     // If no '-miphoneos-version-min' specified on the command line and
424     // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
425     // based on -isysroot.
426     if (iOSTarget.empty()) {
427       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
428         StringRef first, second;
429         StringRef isysroot = A->getValue();
430         llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
431         if (second != "")
432           iOSTarget = second.substr(0,3);
433       }
434     }
435
436     // If no OSX or iOS target has been specified and we're compiling for armv7,
437     // go ahead as assume we're targeting iOS.
438     if (OSXTarget.empty() && iOSTarget.empty() &&
439         (getDarwinArchName(Args) == "armv7" ||
440          getDarwinArchName(Args) == "armv7s"))
441         iOSTarget = iOSVersionMin;
442
443     // Handle conflicting deployment targets
444     //
445     // FIXME: Don't hardcode default here.
446
447     // Do not allow conflicts with the iOS simulator target.
448     if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
449       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
450         << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
451         << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
452             "IPHONEOS_DEPLOYMENT_TARGET");
453     }
454
455     // Allow conflicts among OSX and iOS for historical reasons, but choose the
456     // default platform.
457     if (!OSXTarget.empty() && !iOSTarget.empty()) {
458       if (getTriple().getArch() == llvm::Triple::arm ||
459           getTriple().getArch() == llvm::Triple::thumb)
460         OSXTarget = "";
461       else
462         iOSTarget = "";
463     }
464
465     if (!OSXTarget.empty()) {
466       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
467       OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
468       Args.append(OSXVersion);
469     } else if (!iOSTarget.empty()) {
470       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
471       iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
472       Args.append(iOSVersion);
473     } else if (!iOSSimTarget.empty()) {
474       const Option O = Opts.getOption(
475         options::OPT_mios_simulator_version_min_EQ);
476       iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
477       Args.append(iOSSimVersion);
478     } else {
479       // Otherwise, assume we are targeting OS X.
480       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
481       OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
482       Args.append(OSXVersion);
483     }
484   }
485
486   // Reject invalid architecture combinations.
487   if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
488                         getTriple().getArch() != llvm::Triple::x86_64)) {
489     getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
490       << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
491   }
492
493   // Set the tool chain target information.
494   unsigned Major, Minor, Micro;
495   bool HadExtra;
496   if (OSXVersion) {
497     assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
498     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
499                                    Micro, HadExtra) || HadExtra ||
500         Major != 10 || Minor >= 100 || Micro >= 100)
501       getDriver().Diag(diag::err_drv_invalid_version_number)
502         << OSXVersion->getAsString(Args);
503   } else {
504     const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
505     assert(Version && "Unknown target platform!");
506     if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
507                                    Micro, HadExtra) || HadExtra ||
508         Major >= 10 || Minor >= 100 || Micro >= 100)
509       getDriver().Diag(diag::err_drv_invalid_version_number)
510         << Version->getAsString(Args);
511   }
512
513   bool IsIOSSim = bool(iOSSimVersion);
514
515   // In GCC, the simulator historically was treated as being OS X in some
516   // contexts, like determining the link logic, despite generally being called
517   // with an iOS deployment target. For compatibility, we detect the
518   // simulator as iOS + x86, and treat it differently in a few contexts.
519   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
520                      getTriple().getArch() == llvm::Triple::x86_64))
521     IsIOSSim = true;
522
523   setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
524 }
525
526 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
527                                       ArgStringList &CmdArgs) const {
528   CXXStdlibType Type = GetCXXStdlibType(Args);
529
530   switch (Type) {
531   case ToolChain::CST_Libcxx:
532     CmdArgs.push_back("-lc++");
533     break;
534
535   case ToolChain::CST_Libstdcxx: {
536     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
537     // it was previously found in the gcc lib dir. However, for all the Darwin
538     // platforms we care about it was -lstdc++.6, so we search for that
539     // explicitly if we can't see an obvious -lstdc++ candidate.
540
541     // Check in the sysroot first.
542     bool Exists;
543     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
544       llvm::sys::Path P(A->getValue());
545       P.appendComponent("usr");
546       P.appendComponent("lib");
547       P.appendComponent("libstdc++.dylib");
548
549       if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
550         P.eraseComponent();
551         P.appendComponent("libstdc++.6.dylib");
552         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
553           CmdArgs.push_back(Args.MakeArgString(P.str()));
554           return;
555         }
556       }
557     }
558
559     // Otherwise, look in the root.
560     // FIXME: This should be removed someday when we don't have to care about
561     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
562     if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
563       (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
564       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
565       return;
566     }
567
568     // Otherwise, let the linker search.
569     CmdArgs.push_back("-lstdc++");
570     break;
571   }
572   }
573 }
574
575 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
576                                    ArgStringList &CmdArgs) const {
577
578   // For Darwin platforms, use the compiler-rt-based support library
579   // instead of the gcc-provided one (which is also incidentally
580   // only present in the gcc lib dir, which makes it hard to find).
581
582   llvm::sys::Path P(getDriver().ResourceDir);
583   P.appendComponent("lib");
584   P.appendComponent("darwin");
585
586   // Use the newer cc_kext for iOS ARM after 6.0.
587   if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
588       !isIPhoneOSVersionLT(6, 0)) {
589     P.appendComponent("libclang_rt.cc_kext.a");
590   } else {
591     P.appendComponent("libclang_rt.cc_kext_ios5.a");
592   }
593
594   // For now, allow missing resource libraries to support developers who may
595   // not have compiler-rt checked out or integrated into their build.
596   bool Exists;
597   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
598     CmdArgs.push_back(Args.MakeArgString(P.str()));
599 }
600
601 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
602                                       const char *BoundArch) const {
603   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
604   const OptTable &Opts = getDriver().getOpts();
605
606   // FIXME: We really want to get out of the tool chain level argument
607   // translation business, as it makes the driver functionality much
608   // more opaque. For now, we follow gcc closely solely for the
609   // purpose of easily achieving feature parity & testability. Once we
610   // have something that works, we should reevaluate each translation
611   // and try to push it down into tool specific logic.
612
613   for (ArgList::const_iterator it = Args.begin(),
614          ie = Args.end(); it != ie; ++it) {
615     Arg *A = *it;
616
617     if (A->getOption().matches(options::OPT_Xarch__)) {
618       // Skip this argument unless the architecture matches either the toolchain
619       // triple arch, or the arch being bound.
620       llvm::Triple::ArchType XarchArch =
621         tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
622       if (!(XarchArch == getArch()  ||
623             (BoundArch && XarchArch ==
624              tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
625         continue;
626
627       Arg *OriginalArg = A;
628       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
629       unsigned Prev = Index;
630       Arg *XarchArg = Opts.ParseOneArg(Args, Index);
631
632       // If the argument parsing failed or more than one argument was
633       // consumed, the -Xarch_ argument's parameter tried to consume
634       // extra arguments. Emit an error and ignore.
635       //
636       // We also want to disallow any options which would alter the
637       // driver behavior; that isn't going to work in our model. We
638       // use isDriverOption() as an approximation, although things
639       // like -O4 are going to slip through.
640       if (!XarchArg || Index > Prev + 1) {
641         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
642           << A->getAsString(Args);
643         continue;
644       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
645         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
646           << A->getAsString(Args);
647         continue;
648       }
649
650       XarchArg->setBaseArg(A);
651       A = XarchArg;
652
653       DAL->AddSynthesizedArg(A);
654
655       // Linker input arguments require custom handling. The problem is that we
656       // have already constructed the phase actions, so we can not treat them as
657       // "input arguments".
658       if (A->getOption().hasFlag(options::LinkerInput)) {
659         // Convert the argument into individual Zlinker_input_args.
660         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
661           DAL->AddSeparateArg(OriginalArg,
662                               Opts.getOption(options::OPT_Zlinker_input),
663                               A->getValue(i));
664
665         }
666         continue;
667       }
668     }
669
670     // Sob. These is strictly gcc compatible for the time being. Apple
671     // gcc translates options twice, which means that self-expanding
672     // options add duplicates.
673     switch ((options::ID) A->getOption().getID()) {
674     default:
675       DAL->append(A);
676       break;
677
678     case options::OPT_mkernel:
679     case options::OPT_fapple_kext:
680       DAL->append(A);
681       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
682       break;
683
684     case options::OPT_dependency_file:
685       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
686                           A->getValue());
687       break;
688
689     case options::OPT_gfull:
690       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
691       DAL->AddFlagArg(A,
692                Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
693       break;
694
695     case options::OPT_gused:
696       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
697       DAL->AddFlagArg(A,
698              Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
699       break;
700
701     case options::OPT_shared:
702       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
703       break;
704
705     case options::OPT_fconstant_cfstrings:
706       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
707       break;
708
709     case options::OPT_fno_constant_cfstrings:
710       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
711       break;
712
713     case options::OPT_Wnonportable_cfstrings:
714       DAL->AddFlagArg(A,
715                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
716       break;
717
718     case options::OPT_Wno_nonportable_cfstrings:
719       DAL->AddFlagArg(A,
720                    Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
721       break;
722
723     case options::OPT_fpascal_strings:
724       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
725       break;
726
727     case options::OPT_fno_pascal_strings:
728       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
729       break;
730     }
731   }
732
733   if (getTriple().getArch() == llvm::Triple::x86 ||
734       getTriple().getArch() == llvm::Triple::x86_64)
735     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
736       DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
737
738   // Add the arch options based on the particular spelling of -arch, to match
739   // how the driver driver works.
740   if (BoundArch) {
741     StringRef Name = BoundArch;
742     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
743     const Option MArch = Opts.getOption(options::OPT_march_EQ);
744
745     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
746     // which defines the list of which architectures we accept.
747     if (Name == "ppc")
748       ;
749     else if (Name == "ppc601")
750       DAL->AddJoinedArg(0, MCpu, "601");
751     else if (Name == "ppc603")
752       DAL->AddJoinedArg(0, MCpu, "603");
753     else if (Name == "ppc604")
754       DAL->AddJoinedArg(0, MCpu, "604");
755     else if (Name == "ppc604e")
756       DAL->AddJoinedArg(0, MCpu, "604e");
757     else if (Name == "ppc750")
758       DAL->AddJoinedArg(0, MCpu, "750");
759     else if (Name == "ppc7400")
760       DAL->AddJoinedArg(0, MCpu, "7400");
761     else if (Name == "ppc7450")
762       DAL->AddJoinedArg(0, MCpu, "7450");
763     else if (Name == "ppc970")
764       DAL->AddJoinedArg(0, MCpu, "970");
765
766     else if (Name == "ppc64")
767       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
768
769     else if (Name == "i386")
770       ;
771     else if (Name == "i486")
772       DAL->AddJoinedArg(0, MArch, "i486");
773     else if (Name == "i586")
774       DAL->AddJoinedArg(0, MArch, "i586");
775     else if (Name == "i686")
776       DAL->AddJoinedArg(0, MArch, "i686");
777     else if (Name == "pentium")
778       DAL->AddJoinedArg(0, MArch, "pentium");
779     else if (Name == "pentium2")
780       DAL->AddJoinedArg(0, MArch, "pentium2");
781     else if (Name == "pentpro")
782       DAL->AddJoinedArg(0, MArch, "pentiumpro");
783     else if (Name == "pentIIm3")
784       DAL->AddJoinedArg(0, MArch, "pentium2");
785
786     else if (Name == "x86_64")
787       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
788
789     else if (Name == "arm")
790       DAL->AddJoinedArg(0, MArch, "armv4t");
791     else if (Name == "armv4t")
792       DAL->AddJoinedArg(0, MArch, "armv4t");
793     else if (Name == "armv5")
794       DAL->AddJoinedArg(0, MArch, "armv5tej");
795     else if (Name == "xscale")
796       DAL->AddJoinedArg(0, MArch, "xscale");
797     else if (Name == "armv6")
798       DAL->AddJoinedArg(0, MArch, "armv6k");
799     else if (Name == "armv7")
800       DAL->AddJoinedArg(0, MArch, "armv7a");
801     else if (Name == "armv7f")
802       DAL->AddJoinedArg(0, MArch, "armv7f");
803     else if (Name == "armv7k")
804       DAL->AddJoinedArg(0, MArch, "armv7k");
805     else if (Name == "armv7s")
806       DAL->AddJoinedArg(0, MArch, "armv7s");
807
808     else
809       llvm_unreachable("invalid Darwin arch");
810   }
811
812   // Add an explicit version min argument for the deployment target. We do this
813   // after argument translation because -Xarch_ arguments may add a version min
814   // argument.
815   if (BoundArch)
816     AddDeploymentTarget(*DAL);
817
818   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
819   // FIXME: It would be far better to avoid inserting those -static arguments,
820   // but we can't check the deployment target in the translation code until
821   // it is set here.
822   if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
823     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
824       Arg *A = *it;
825       ++it;
826       if (A->getOption().getID() != options::OPT_mkernel &&
827           A->getOption().getID() != options::OPT_fapple_kext)
828         continue;
829       assert(it != ie && "unexpected argument translation");
830       A = *it;
831       assert(A->getOption().getID() == options::OPT_static &&
832              "missing expected -static argument");
833       it = DAL->getArgs().erase(it);
834     }
835   }
836
837   // Validate the C++ standard library choice.
838   CXXStdlibType Type = GetCXXStdlibType(*DAL);
839   if (Type == ToolChain::CST_Libcxx) {
840     // Check whether the target provides libc++.
841     StringRef where;
842
843     // Complain about targetting iOS < 5.0 in any way.
844     if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))
845       where = "iOS 5.0";
846
847     if (where != StringRef()) {
848       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
849         << where;
850     }
851   }
852
853   return DAL;
854 }
855
856 bool Darwin::IsUnwindTablesDefault() const {
857   return getArch() == llvm::Triple::x86_64;
858 }
859
860 bool Darwin::UseDwarfDebugFlags() const {
861   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
862     return S[0] != '\0';
863   return false;
864 }
865
866 bool Darwin::UseSjLjExceptions() const {
867   // Darwin uses SjLj exceptions on ARM.
868   return (getTriple().getArch() == llvm::Triple::arm ||
869           getTriple().getArch() == llvm::Triple::thumb);
870 }
871
872 bool Darwin::isPICDefault() const {
873   return true;
874 }
875
876 bool Darwin::isPICDefaultForced() const {
877   return getArch() == llvm::Triple::x86_64;
878 }
879
880 bool Darwin::SupportsProfiling() const {
881   // Profiling instrumentation is only supported on x86.
882   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
883 }
884
885 bool Darwin::SupportsObjCGC() const {
886   // Garbage collection is supported everywhere except on iPhone OS.
887   return !isTargetIPhoneOS();
888 }
889
890 void Darwin::CheckObjCARC() const {
891   if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
892     return;
893   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
894 }
895
896 std::string
897 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
898                                                 types::ID InputType) const {
899   return ComputeLLVMTriple(Args, InputType);
900 }
901
902 /// Generic_GCC - A tool chain using the 'gcc' command to perform
903 /// all subcommands; this relies on gcc translating the majority of
904 /// command line options.
905
906 /// \brief Parse a GCCVersion object out of a string of text.
907 ///
908 /// This is the primary means of forming GCCVersion objects.
909 /*static*/
910 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
911   const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
912   std::pair<StringRef, StringRef> First = VersionText.split('.');
913   std::pair<StringRef, StringRef> Second = First.second.split('.');
914
915   GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
916   if (First.first.getAsInteger(10, GoodVersion.Major) ||
917       GoodVersion.Major < 0)
918     return BadVersion;
919   if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
920       GoodVersion.Minor < 0)
921     return BadVersion;
922
923   // First look for a number prefix and parse that if present. Otherwise just
924   // stash the entire patch string in the suffix, and leave the number
925   // unspecified. This covers versions strings such as:
926   //   4.4
927   //   4.4.0
928   //   4.4.x
929   //   4.4.2-rc4
930   //   4.4.x-patched
931   // And retains any patch number it finds.
932   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
933   if (!PatchText.empty()) {
934     if (unsigned EndNumber = PatchText.find_first_not_of("0123456789")) {
935       // Try to parse the number and any suffix.
936       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
937           GoodVersion.Patch < 0)
938         return BadVersion;
939       GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
940     }
941   }
942
943   return GoodVersion;
944 }
945
946 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
947 bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
948   if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
949   if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
950
951   // Note that we rank versions with *no* patch specified is better than ones
952   // hard-coding a patch version. Thus if the RHS has no patch, it always
953   // wins, and the LHS only wins if it has no patch and the RHS does have
954   // a patch.
955   if (RHS.Patch == -1) return true;   if (Patch == -1) return false;
956   if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
957   if (PatchSuffix == RHS.PatchSuffix) return false;
958
959   // Finally, between completely tied version numbers, the version with the
960   // suffix loses as we prefer full releases.
961   if (RHS.PatchSuffix.empty()) return true;
962   return false;
963 }
964
965 static StringRef getGCCToolchainDir(const ArgList &Args) {
966   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
967   if (A)
968     return A->getValue();
969   return GCC_INSTALL_PREFIX;
970 }
971
972 /// \brief Construct a GCCInstallationDetector from the driver.
973 ///
974 /// This performs all of the autodetection and sets up the various paths.
975 /// Once constructed, a GCCInstallationDetector is essentially immutable.
976 ///
977 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
978 /// should instead pull the target out of the driver. This is currently
979 /// necessary because the driver doesn't store the final version of the target
980 /// triple.
981 Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
982     const Driver &D,
983     const llvm::Triple &TargetTriple,
984     const ArgList &Args)
985     : IsValid(false) {
986   llvm::Triple MultiarchTriple
987     = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
988                                  : TargetTriple.get32BitArchVariant();
989   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
990   // The library directories which may contain GCC installations.
991   SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
992   // The compatible GCC triples for this particular architecture.
993   SmallVector<StringRef, 10> CandidateTripleAliases;
994   SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
995   CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
996                            CandidateTripleAliases,
997                            CandidateMultiarchLibDirs,
998                            CandidateMultiarchTripleAliases);
999
1000   // Compute the set of prefixes for our search.
1001   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1002                                        D.PrefixDirs.end());
1003
1004   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1005   if (GCCToolchainDir != "") {
1006     if (GCCToolchainDir.back() == '/')
1007       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1008
1009     Prefixes.push_back(GCCToolchainDir);
1010   } else {
1011     Prefixes.push_back(D.SysRoot);
1012     Prefixes.push_back(D.SysRoot + "/usr");
1013     Prefixes.push_back(D.InstalledDir + "/..");
1014   }
1015
1016   // Loop over the various components which exist and select the best GCC
1017   // installation available. GCC installs are ranked by version number.
1018   Version = GCCVersion::Parse("0.0.0");
1019   for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1020     if (!llvm::sys::fs::exists(Prefixes[i]))
1021       continue;
1022     for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1023       const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1024       if (!llvm::sys::fs::exists(LibDir))
1025         continue;
1026       for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1027         ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1028                                CandidateTripleAliases[k]);
1029     }
1030     for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) {
1031       const std::string LibDir
1032         = Prefixes[i] + CandidateMultiarchLibDirs[j].str();
1033       if (!llvm::sys::fs::exists(LibDir))
1034         continue;
1035       for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke;
1036            ++k)
1037         ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1038                                CandidateMultiarchTripleAliases[k],
1039                                /*NeedsMultiarchSuffix=*/true);
1040     }
1041   }
1042 }
1043
1044 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1045     const llvm::Triple &TargetTriple,
1046     const llvm::Triple &MultiarchTriple,
1047     SmallVectorImpl<StringRef> &LibDirs,
1048     SmallVectorImpl<StringRef> &TripleAliases,
1049     SmallVectorImpl<StringRef> &MultiarchLibDirs,
1050     SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
1051   // Declare a bunch of static data sets that we'll select between below. These
1052   // are specifically designed to always refer to string literals to avoid any
1053   // lifetime or initialization issues.
1054   static const char *const ARMLibDirs[] = { "/lib" };
1055   static const char *const ARMTriples[] = {
1056     "arm-linux-gnueabi",
1057     "arm-linux-androideabi"
1058   };
1059   static const char *const ARMHFTriples[] = {
1060     "arm-linux-gnueabihf",
1061   };
1062
1063   static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1064   static const char *const X86_64Triples[] = {
1065     "x86_64-linux-gnu",
1066     "x86_64-unknown-linux-gnu",
1067     "x86_64-pc-linux-gnu",
1068     "x86_64-redhat-linux6E",
1069     "x86_64-redhat-linux",
1070     "x86_64-suse-linux",
1071     "x86_64-manbo-linux-gnu",
1072     "x86_64-linux-gnu",
1073     "x86_64-slackware-linux"
1074   };
1075   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1076   static const char *const X86Triples[] = {
1077     "i686-linux-gnu",
1078     "i686-pc-linux-gnu",
1079     "i486-linux-gnu",
1080     "i386-linux-gnu",
1081     "i686-redhat-linux",
1082     "i586-redhat-linux",
1083     "i386-redhat-linux",
1084     "i586-suse-linux",
1085     "i486-slackware-linux",
1086     "i686-montavista-linux"
1087   };
1088
1089   static const char *const MIPSLibDirs[] = { "/lib" };
1090   static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1091   static const char *const MIPSELLibDirs[] = { "/lib" };
1092   static const char *const MIPSELTriples[] = {
1093     "mipsel-linux-gnu",
1094     "mipsel-linux-android"
1095   };
1096
1097   static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1098   static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
1099   static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1100   static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
1101
1102   static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1103   static const char *const PPCTriples[] = {
1104     "powerpc-linux-gnu",
1105     "powerpc-unknown-linux-gnu",
1106     "powerpc-suse-linux",
1107     "powerpc-montavista-linuxspe"
1108   };
1109   static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1110   static const char *const PPC64Triples[] = {
1111     "powerpc64-linux-gnu",
1112     "powerpc64-unknown-linux-gnu",
1113     "powerpc64-suse-linux",
1114     "ppc64-redhat-linux"
1115   };
1116
1117   switch (TargetTriple.getArch()) {
1118   case llvm::Triple::arm:
1119   case llvm::Triple::thumb:
1120     LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1121     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1122       TripleAliases.append(
1123         ARMHFTriples, ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1124     } else {
1125       TripleAliases.append(
1126         ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1127     }
1128     break;
1129   case llvm::Triple::x86_64:
1130     LibDirs.append(
1131       X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1132     TripleAliases.append(
1133       X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1134     MultiarchLibDirs.append(
1135       X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1136     MultiarchTripleAliases.append(
1137       X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1138     break;
1139   case llvm::Triple::x86:
1140     LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1141     TripleAliases.append(
1142       X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1143     MultiarchLibDirs.append(
1144       X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1145     MultiarchTripleAliases.append(
1146       X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1147     break;
1148   case llvm::Triple::mips:
1149     LibDirs.append(
1150       MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1151     TripleAliases.append(
1152       MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1153     MultiarchLibDirs.append(
1154       MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1155     MultiarchTripleAliases.append(
1156       MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1157     break;
1158   case llvm::Triple::mipsel:
1159     LibDirs.append(
1160       MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1161     TripleAliases.append(
1162       MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1163     MultiarchLibDirs.append(
1164       MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1165     MultiarchTripleAliases.append(
1166       MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1167     break;
1168   case llvm::Triple::mips64:
1169     LibDirs.append(
1170       MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1171     TripleAliases.append(
1172       MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1173     MultiarchLibDirs.append(
1174       MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1175     MultiarchTripleAliases.append(
1176       MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1177     break;
1178   case llvm::Triple::mips64el:
1179     LibDirs.append(
1180       MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1181     TripleAliases.append(
1182       MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1183     MultiarchLibDirs.append(
1184       MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1185     MultiarchTripleAliases.append(
1186       MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1187     break;
1188   case llvm::Triple::ppc:
1189     LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1190     TripleAliases.append(
1191       PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1192     MultiarchLibDirs.append(
1193       PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1194     MultiarchTripleAliases.append(
1195       PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1196     break;
1197   case llvm::Triple::ppc64:
1198     LibDirs.append(
1199       PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1200     TripleAliases.append(
1201       PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1202     MultiarchLibDirs.append(
1203       PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1204     MultiarchTripleAliases.append(
1205       PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1206     break;
1207
1208   default:
1209     // By default, just rely on the standard lib directories and the original
1210     // triple.
1211     break;
1212   }
1213
1214   // Always append the drivers target triple to the end, in case it doesn't
1215   // match any of our aliases.
1216   TripleAliases.push_back(TargetTriple.str());
1217
1218   // Also include the multiarch variant if it's different.
1219   if (TargetTriple.str() != MultiarchTriple.str())
1220     MultiarchTripleAliases.push_back(MultiarchTriple.str());
1221 }
1222
1223 // FIXME: There is the same routine in the Tools.cpp.
1224 static bool hasMipsN32ABIArg(const ArgList &Args) {
1225   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1226   return A && (A->getValue() == StringRef("n32"));
1227 }
1228
1229 static StringRef getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch,
1230                                           const ArgList &Args) {
1231   if (TargetArch == llvm::Triple::x86_64 ||
1232       TargetArch == llvm::Triple::ppc64)
1233     return "/64";
1234
1235   if (TargetArch == llvm::Triple::mips64 ||
1236       TargetArch == llvm::Triple::mips64el) {
1237     if (hasMipsN32ABIArg(Args))
1238       return "/n32";
1239     else
1240       return "/64";
1241   }
1242
1243   return "/32";
1244 }
1245
1246 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1247     llvm::Triple::ArchType TargetArch, const ArgList &Args,
1248     const std::string &LibDir,
1249     StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
1250   // There are various different suffixes involving the triple we
1251   // check for. We also record what is necessary to walk from each back
1252   // up to the lib directory.
1253   const std::string LibSuffixes[] = {
1254     "/gcc/" + CandidateTriple.str(),
1255     "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1256
1257     // The Freescale PPC SDK has the gcc libraries in
1258     // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1259     "/" + CandidateTriple.str(),
1260
1261     // Ubuntu has a strange mis-matched pair of triples that this happens to
1262     // match.
1263     // FIXME: It may be worthwhile to generalize this and look for a second
1264     // triple.
1265     "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1266   };
1267   const std::string InstallSuffixes[] = {
1268     "/../../..",
1269     "/../../../..",
1270     "/../..",
1271     "/../../../.."
1272   };
1273   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1274   const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) -
1275                                    (TargetArch != llvm::Triple::x86));
1276   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1277     StringRef LibSuffix = LibSuffixes[i];
1278     llvm::error_code EC;
1279     for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1280          !EC && LI != LE; LI = LI.increment(EC)) {
1281       StringRef VersionText = llvm::sys::path::filename(LI->path());
1282       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1283       static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1284       if (CandidateVersion < MinVersion)
1285         continue;
1286       if (CandidateVersion <= Version)
1287         continue;
1288
1289       // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1290       // in what would normally be GCCInstallPath and put the 64-bit
1291       // libs in a subdirectory named 64. The simple logic we follow is that
1292       // *if* there is a subdirectory of the right name with crtbegin.o in it,
1293       // we use that. If not, and if not a multiarch triple, we look for
1294       // crtbegin.o without the subdirectory.
1295       StringRef MultiarchSuffix = getTargetMultiarchSuffix(TargetArch, Args);
1296       if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
1297         GCCMultiarchSuffix = MultiarchSuffix.str();
1298       } else {
1299         if (NeedsMultiarchSuffix ||
1300             !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1301           continue;
1302         GCCMultiarchSuffix.clear();
1303       }
1304
1305       Version = CandidateVersion;
1306       GCCTriple.setTriple(CandidateTriple);
1307       // FIXME: We hack together the directory name here instead of
1308       // using LI to ensure stable path separators across Windows and
1309       // Linux.
1310       GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1311       GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1312       IsValid = true;
1313     }
1314   }
1315 }
1316
1317 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1318                          const ArgList &Args)
1319   : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) {
1320   getProgramPaths().push_back(getDriver().getInstalledDir());
1321   if (getDriver().getInstalledDir() != getDriver().Dir)
1322     getProgramPaths().push_back(getDriver().Dir);
1323 }
1324
1325 Generic_GCC::~Generic_GCC() {
1326   // Free tool implementations.
1327   for (llvm::DenseMap<unsigned, Tool*>::iterator
1328          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1329     delete it->second;
1330 }
1331
1332 Tool &Generic_GCC::SelectTool(const Compilation &C,
1333                               const JobAction &JA,
1334                               const ActionList &Inputs) const {
1335   Action::ActionClass Key;
1336   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1337     Key = Action::AnalyzeJobClass;
1338   else
1339     Key = JA.getKind();
1340
1341   Tool *&T = Tools[Key];
1342   if (!T) {
1343     switch (Key) {
1344     case Action::InputClass:
1345     case Action::BindArchClass:
1346       llvm_unreachable("Invalid tool kind.");
1347     case Action::PreprocessJobClass:
1348       T = new tools::gcc::Preprocess(*this); break;
1349     case Action::PrecompileJobClass:
1350       T = new tools::gcc::Precompile(*this); break;
1351     case Action::AnalyzeJobClass:
1352     case Action::MigrateJobClass:
1353       T = new tools::Clang(*this); break;
1354     case Action::CompileJobClass:
1355       T = new tools::gcc::Compile(*this); break;
1356     case Action::AssembleJobClass:
1357       T = new tools::gcc::Assemble(*this); break;
1358     case Action::LinkJobClass:
1359       T = new tools::gcc::Link(*this); break;
1360
1361       // This is a bit ungeneric, but the only platform using a driver
1362       // driver is Darwin.
1363     case Action::LipoJobClass:
1364       T = new tools::darwin::Lipo(*this); break;
1365     case Action::DsymutilJobClass:
1366       T = new tools::darwin::Dsymutil(*this); break;
1367     case Action::VerifyJobClass:
1368       T = new tools::darwin::VerifyDebug(*this); break;
1369     }
1370   }
1371
1372   return *T;
1373 }
1374
1375 bool Generic_GCC::IsUnwindTablesDefault() const {
1376   return getArch() == llvm::Triple::x86_64;
1377 }
1378
1379 bool Generic_GCC::isPICDefault() const {
1380   return false;
1381 }
1382
1383 bool Generic_GCC::isPICDefaultForced() const {
1384   return false;
1385 }
1386
1387 /// Hexagon Toolchain
1388
1389 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple& Triple)
1390   : ToolChain(D, Triple) {
1391   getProgramPaths().push_back(getDriver().getInstalledDir());
1392   if (getDriver().getInstalledDir() != getDriver().Dir.c_str())
1393     getProgramPaths().push_back(getDriver().Dir);
1394 }
1395
1396 Hexagon_TC::~Hexagon_TC() {
1397   // Free tool implementations.
1398   for (llvm::DenseMap<unsigned, Tool*>::iterator
1399          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1400     delete it->second;
1401 }
1402
1403 Tool &Hexagon_TC::SelectTool(const Compilation &C,
1404                              const JobAction &JA,
1405                              const ActionList &Inputs) const {
1406   Action::ActionClass Key;
1407   //   if (JA.getKind () == Action::CompileJobClass)
1408   //     Key = JA.getKind ();
1409   //     else
1410
1411   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1412     Key = Action::AnalyzeJobClass;
1413   else
1414     Key = JA.getKind();
1415   //   if ((JA.getKind () == Action::CompileJobClass)
1416   //     && (JA.getType () != types::TY_LTO_BC)) {
1417   //     Key = JA.getKind ();
1418   //   }
1419
1420   Tool *&T = Tools[Key];
1421   if (!T) {
1422     switch (Key) {
1423     case Action::InputClass:
1424     case Action::BindArchClass:
1425       assert(0 && "Invalid tool kind.");
1426     case Action::AnalyzeJobClass:
1427       T = new tools::Clang(*this); break;
1428     case Action::AssembleJobClass:
1429       T = new tools::hexagon::Assemble(*this); break;
1430     case Action::LinkJobClass:
1431       T = new tools::hexagon::Link(*this); break;
1432     default:
1433       assert(false && "Unsupported action for Hexagon target.");
1434     }
1435   }
1436
1437   return *T;
1438 }
1439
1440 bool Hexagon_TC::isPICDefault() const {
1441   return false;
1442 }
1443
1444 bool Hexagon_TC::isPICDefaultForced() const {
1445   return false;
1446 }
1447
1448 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1449 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1450 /// Currently does not support anything else but compilation.
1451
1452 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple)
1453   : ToolChain(D, Triple) {
1454   // Path mangling to find libexec
1455   std::string Path(getDriver().Dir);
1456
1457   Path += "/../libexec";
1458   getProgramPaths().push_back(Path);
1459 }
1460
1461 TCEToolChain::~TCEToolChain() {
1462   for (llvm::DenseMap<unsigned, Tool*>::iterator
1463            it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1464       delete it->second;
1465 }
1466
1467 bool TCEToolChain::IsMathErrnoDefault() const {
1468   return true;
1469 }
1470
1471 bool TCEToolChain::isPICDefault() const {
1472   return false;
1473 }
1474
1475 bool TCEToolChain::isPICDefaultForced() const {
1476   return false;
1477 }
1478
1479 Tool &TCEToolChain::SelectTool(const Compilation &C,
1480                             const JobAction &JA,
1481                                const ActionList &Inputs) const {
1482   Action::ActionClass Key;
1483   Key = Action::AnalyzeJobClass;
1484
1485   Tool *&T = Tools[Key];
1486   if (!T) {
1487     switch (Key) {
1488     case Action::PreprocessJobClass:
1489       T = new tools::gcc::Preprocess(*this); break;
1490     case Action::AnalyzeJobClass:
1491       T = new tools::Clang(*this); break;
1492     default:
1493      llvm_unreachable("Unsupported action for TCE target.");
1494     }
1495   }
1496   return *T;
1497 }
1498
1499 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1500
1501 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1502   : Generic_ELF(D, Triple, Args) {
1503   getFilePaths().push_back(getDriver().Dir + "/../lib");
1504   getFilePaths().push_back("/usr/lib");
1505 }
1506
1507 Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
1508                           const ActionList &Inputs) const {
1509   Action::ActionClass Key;
1510   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1511     Key = Action::AnalyzeJobClass;
1512   else
1513     Key = JA.getKind();
1514
1515   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1516                                              options::OPT_no_integrated_as,
1517                                              IsIntegratedAssemblerDefault());
1518
1519   Tool *&T = Tools[Key];
1520   if (!T) {
1521     switch (Key) {
1522     case Action::AssembleJobClass: {
1523       if (UseIntegratedAs)
1524         T = new tools::ClangAs(*this);
1525       else
1526         T = new tools::openbsd::Assemble(*this);
1527       break;
1528     }
1529     case Action::LinkJobClass:
1530       T = new tools::openbsd::Link(*this); break;
1531     default:
1532       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1533     }
1534   }
1535
1536   return *T;
1537 }
1538
1539 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1540
1541 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1542   : Generic_ELF(D, Triple, Args) {
1543   getFilePaths().push_back(getDriver().Dir + "/../lib");
1544   getFilePaths().push_back("/usr/lib");
1545 }
1546
1547 Tool &Bitrig::SelectTool(const Compilation &C, const JobAction &JA,
1548                          const ActionList &Inputs) const {
1549   Action::ActionClass Key;
1550   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1551     Key = Action::AnalyzeJobClass;
1552   else
1553     Key = JA.getKind();
1554
1555   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1556                                              options::OPT_no_integrated_as,
1557                                              IsIntegratedAssemblerDefault());
1558
1559   Tool *&T = Tools[Key];
1560   if (!T) {
1561     switch (Key) {
1562     case Action::AssembleJobClass: {
1563       if (UseIntegratedAs)
1564         T = new tools::ClangAs(*this);
1565       else
1566         T = new tools::bitrig::Assemble(*this);
1567       break;
1568     }
1569     case Action::LinkJobClass:
1570       T = new tools::bitrig::Link(*this); break;
1571     default:
1572       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1573     }
1574   }
1575
1576   return *T;
1577 }
1578
1579 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1580                                           ArgStringList &CC1Args) const {
1581   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1582       DriverArgs.hasArg(options::OPT_nostdincxx))
1583     return;
1584
1585   switch (GetCXXStdlibType(DriverArgs)) {
1586   case ToolChain::CST_Libcxx:
1587     addSystemInclude(DriverArgs, CC1Args,
1588                      getDriver().SysRoot + "/usr/include/c++/");
1589     break;
1590   case ToolChain::CST_Libstdcxx:
1591     addSystemInclude(DriverArgs, CC1Args,
1592                      getDriver().SysRoot + "/usr/include/c++/stdc++");
1593     addSystemInclude(DriverArgs, CC1Args,
1594                      getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1595
1596     StringRef Triple = getTriple().str();
1597     if (Triple.startswith("amd64"))
1598       addSystemInclude(DriverArgs, CC1Args,
1599                        getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1600                        Triple.substr(5));
1601     else
1602       addSystemInclude(DriverArgs, CC1Args,
1603                        getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1604                        Triple);
1605     break;
1606   }
1607 }
1608
1609 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1610                                  ArgStringList &CmdArgs) const {
1611   switch (GetCXXStdlibType(Args)) {
1612   case ToolChain::CST_Libcxx:
1613     CmdArgs.push_back("-lc++");
1614     CmdArgs.push_back("-lcxxrt");
1615     // Include supc++ to provide Unwind until provided by libcxx.
1616     CmdArgs.push_back("-lgcc");
1617     break;
1618   case ToolChain::CST_Libstdcxx:
1619     CmdArgs.push_back("-lstdc++");
1620     break;
1621   }
1622 }
1623
1624 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1625
1626 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1627   : Generic_ELF(D, Triple, Args) {
1628
1629   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1630   // back to '/usr/lib' if it doesn't exist.
1631   if ((Triple.getArch() == llvm::Triple::x86 ||
1632        Triple.getArch() == llvm::Triple::ppc) &&
1633       llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1634     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1635   else
1636     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1637 }
1638
1639 Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1640                           const ActionList &Inputs) const {
1641   Action::ActionClass Key;
1642   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1643     Key = Action::AnalyzeJobClass;
1644   else
1645     Key = JA.getKind();
1646
1647   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1648                                              options::OPT_no_integrated_as,
1649                                              IsIntegratedAssemblerDefault());
1650
1651   Tool *&T = Tools[Key];
1652   if (!T) {
1653     switch (Key) {
1654     case Action::AssembleJobClass:
1655       if (UseIntegratedAs)
1656         T = new tools::ClangAs(*this);
1657       else
1658         T = new tools::freebsd::Assemble(*this);
1659       break;
1660     case Action::LinkJobClass:
1661       T = new tools::freebsd::Link(*this); break;
1662     default:
1663       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1664     }
1665   }
1666
1667   return *T;
1668 }
1669
1670 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1671
1672 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1673   : Generic_ELF(D, Triple, Args) {
1674
1675   if (getDriver().UseStdLib) {
1676     // When targeting a 32-bit platform, try the special directory used on
1677     // 64-bit hosts, and only fall back to the main library directory if that
1678     // doesn't work.
1679     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
1680     // what all logic is needed to emulate the '=' prefix here.
1681     if (Triple.getArch() == llvm::Triple::x86)
1682       getFilePaths().push_back("=/usr/lib/i386");
1683
1684     getFilePaths().push_back("=/usr/lib");
1685   }
1686 }
1687
1688 Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1689                          const ActionList &Inputs) const {
1690   Action::ActionClass Key;
1691   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1692     Key = Action::AnalyzeJobClass;
1693   else
1694     Key = JA.getKind();
1695
1696   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1697                                              options::OPT_no_integrated_as,
1698                                              IsIntegratedAssemblerDefault());
1699
1700   Tool *&T = Tools[Key];
1701   if (!T) {
1702     switch (Key) {
1703     case Action::AssembleJobClass:
1704       if (UseIntegratedAs)
1705         T = new tools::ClangAs(*this);
1706       else
1707         T = new tools::netbsd::Assemble(*this);
1708       break;
1709     case Action::LinkJobClass:
1710       T = new tools::netbsd::Link(*this);
1711       break;
1712     default:
1713       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1714     }
1715   }
1716
1717   return *T;
1718 }
1719
1720 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1721
1722 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1723   : Generic_ELF(D, Triple, Args) {
1724   getFilePaths().push_back(getDriver().Dir + "/../lib");
1725   getFilePaths().push_back("/usr/lib");
1726 }
1727
1728 Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1729                         const ActionList &Inputs) const {
1730   Action::ActionClass Key;
1731   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1732     Key = Action::AnalyzeJobClass;
1733   else
1734     Key = JA.getKind();
1735
1736   Tool *&T = Tools[Key];
1737   if (!T) {
1738     switch (Key) {
1739     case Action::AssembleJobClass:
1740       T = new tools::minix::Assemble(*this); break;
1741     case Action::LinkJobClass:
1742       T = new tools::minix::Link(*this); break;
1743     default:
1744       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1745     }
1746   }
1747
1748   return *T;
1749 }
1750
1751 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1752
1753 AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
1754                    const ArgList &Args)
1755   : Generic_GCC(D, Triple, Args) {
1756
1757   getProgramPaths().push_back(getDriver().getInstalledDir());
1758   if (getDriver().getInstalledDir() != getDriver().Dir)
1759     getProgramPaths().push_back(getDriver().Dir);
1760
1761   getFilePaths().push_back(getDriver().Dir + "/../lib");
1762   getFilePaths().push_back("/usr/lib");
1763   getFilePaths().push_back("/usr/sfw/lib");
1764   getFilePaths().push_back("/opt/gcc4/lib");
1765   getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1766
1767 }
1768
1769 Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1770                            const ActionList &Inputs) const {
1771   Action::ActionClass Key;
1772   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1773     Key = Action::AnalyzeJobClass;
1774   else
1775     Key = JA.getKind();
1776
1777   Tool *&T = Tools[Key];
1778   if (!T) {
1779     switch (Key) {
1780     case Action::AssembleJobClass:
1781       T = new tools::auroraux::Assemble(*this); break;
1782     case Action::LinkJobClass:
1783       T = new tools::auroraux::Link(*this); break;
1784     default:
1785       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1786     }
1787   }
1788
1789   return *T;
1790 }
1791
1792 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
1793
1794 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
1795                  const ArgList &Args)
1796   : Generic_GCC(D, Triple, Args) {
1797
1798   getProgramPaths().push_back(getDriver().getInstalledDir());
1799   if (getDriver().getInstalledDir() != getDriver().Dir)
1800     getProgramPaths().push_back(getDriver().Dir);
1801
1802   getFilePaths().push_back(getDriver().Dir + "/../lib");
1803   getFilePaths().push_back("/usr/lib");
1804 }
1805
1806 Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA,
1807                            const ActionList &Inputs) const {
1808   Action::ActionClass Key;
1809   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1810     Key = Action::AnalyzeJobClass;
1811   else
1812     Key = JA.getKind();
1813
1814   Tool *&T = Tools[Key];
1815   if (!T) {
1816     switch (Key) {
1817     case Action::AssembleJobClass:
1818       T = new tools::solaris::Assemble(*this); break;
1819     case Action::LinkJobClass:
1820       T = new tools::solaris::Link(*this); break;
1821     default:
1822       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1823     }
1824   }
1825
1826   return *T;
1827 }
1828
1829 /// Linux toolchain (very bare-bones at the moment).
1830
1831 enum LinuxDistro {
1832   ArchLinux,
1833   DebianLenny,
1834   DebianSqueeze,
1835   DebianWheezy,
1836   Exherbo,
1837   RHEL4,
1838   RHEL5,
1839   RHEL6,
1840   Fedora13,
1841   Fedora14,
1842   Fedora15,
1843   Fedora16,
1844   FedoraRawhide,
1845   OpenSuse11_3,
1846   OpenSuse11_4,
1847   OpenSuse12_1,
1848   OpenSuse12_2,
1849   UbuntuHardy,
1850   UbuntuIntrepid,
1851   UbuntuJaunty,
1852   UbuntuKarmic,
1853   UbuntuLucid,
1854   UbuntuMaverick,
1855   UbuntuNatty,
1856   UbuntuOneiric,
1857   UbuntuPrecise,
1858   UbuntuQuantal,
1859   UbuntuRaring,
1860   UnknownDistro
1861 };
1862
1863 static bool IsRedhat(enum LinuxDistro Distro) {
1864   return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
1865          (Distro >= RHEL4    && Distro <= RHEL6);
1866 }
1867
1868 static bool IsOpenSuse(enum LinuxDistro Distro) {
1869   return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2;
1870 }
1871
1872 static bool IsDebian(enum LinuxDistro Distro) {
1873   return Distro >= DebianLenny && Distro <= DebianWheezy;
1874 }
1875
1876 static bool IsUbuntu(enum LinuxDistro Distro) {
1877   return Distro >= UbuntuHardy && Distro <= UbuntuRaring;
1878 }
1879
1880 static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1881   OwningPtr<llvm::MemoryBuffer> File;
1882   if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1883     StringRef Data = File.get()->getBuffer();
1884     SmallVector<StringRef, 8> Lines;
1885     Data.split(Lines, "\n");
1886     LinuxDistro Version = UnknownDistro;
1887     for (unsigned i = 0, s = Lines.size(); i != s; ++i)
1888       if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
1889         Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
1890           .Case("hardy", UbuntuHardy)
1891           .Case("intrepid", UbuntuIntrepid)
1892           .Case("jaunty", UbuntuJaunty)
1893           .Case("karmic", UbuntuKarmic)
1894           .Case("lucid", UbuntuLucid)
1895           .Case("maverick", UbuntuMaverick)
1896           .Case("natty", UbuntuNatty)
1897           .Case("oneiric", UbuntuOneiric)
1898           .Case("precise", UbuntuPrecise)
1899           .Case("quantal", UbuntuQuantal)
1900           .Case("raring", UbuntuRaring)
1901           .Default(UnknownDistro);
1902     return Version;
1903   }
1904
1905   if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1906     StringRef Data = File.get()->getBuffer();
1907     if (Data.startswith("Fedora release 16"))
1908       return Fedora16;
1909     else if (Data.startswith("Fedora release 15"))
1910       return Fedora15;
1911     else if (Data.startswith("Fedora release 14"))
1912       return Fedora14;
1913     else if (Data.startswith("Fedora release 13"))
1914       return Fedora13;
1915     else if (Data.startswith("Fedora release") &&
1916              Data.find("Rawhide") != StringRef::npos)
1917       return FedoraRawhide;
1918     else if (Data.startswith("Red Hat Enterprise Linux") &&
1919              Data.find("release 6") != StringRef::npos)
1920       return RHEL6;
1921     else if ((Data.startswith("Red Hat Enterprise Linux") ||
1922               Data.startswith("CentOS")) &&
1923              Data.find("release 5") != StringRef::npos)
1924       return RHEL5;
1925     else if ((Data.startswith("Red Hat Enterprise Linux") ||
1926               Data.startswith("CentOS")) &&
1927              Data.find("release 4") != StringRef::npos)
1928       return RHEL4;
1929     return UnknownDistro;
1930   }
1931
1932   if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1933     StringRef Data = File.get()->getBuffer();
1934     if (Data[0] == '5')
1935       return DebianLenny;
1936     else if (Data.startswith("squeeze/sid") || Data[0] == '6')
1937       return DebianSqueeze;
1938     else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
1939       return DebianWheezy;
1940     return UnknownDistro;
1941   }
1942
1943   if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
1944     return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
1945       .StartsWith("openSUSE 11.3", OpenSuse11_3)
1946       .StartsWith("openSUSE 11.4", OpenSuse11_4)
1947       .StartsWith("openSUSE 12.1", OpenSuse12_1)
1948       .StartsWith("openSUSE 12.2", OpenSuse12_2)
1949       .Default(UnknownDistro);
1950
1951   bool Exists;
1952   if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1953     return Exherbo;
1954
1955   if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1956     return ArchLinux;
1957
1958   return UnknownDistro;
1959 }
1960
1961 /// \brief Get our best guess at the multiarch triple for a target.
1962 ///
1963 /// Debian-based systems are starting to use a multiarch setup where they use
1964 /// a target-triple directory in the library and header search paths.
1965 /// Unfortunately, this triple does not align with the vanilla target triple,
1966 /// so we provide a rough mapping here.
1967 static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
1968                                       StringRef SysRoot) {
1969   // For most architectures, just use whatever we have rather than trying to be
1970   // clever.
1971   switch (TargetTriple.getArch()) {
1972   default:
1973     return TargetTriple.str();
1974
1975     // We use the existence of '/lib/<triple>' as a directory to detect some
1976     // common linux triples that don't quite match the Clang triple for both
1977     // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
1978     // regardless of what the actual target triple is.
1979   case llvm::Triple::arm:
1980   case llvm::Triple::thumb:
1981     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1982       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
1983         return "arm-linux-gnueabihf";
1984     } else {
1985       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
1986         return "arm-linux-gnueabi";
1987     }
1988     return TargetTriple.str();
1989   case llvm::Triple::x86:
1990     if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
1991       return "i386-linux-gnu";
1992     return TargetTriple.str();
1993   case llvm::Triple::x86_64:
1994     if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
1995       return "x86_64-linux-gnu";
1996     return TargetTriple.str();
1997   case llvm::Triple::mips:
1998     if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
1999       return "mips-linux-gnu";
2000     return TargetTriple.str();
2001   case llvm::Triple::mipsel:
2002     if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2003       return "mipsel-linux-gnu";
2004     return TargetTriple.str();
2005   case llvm::Triple::ppc:
2006     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2007       return "powerpc-linux-gnu";
2008     return TargetTriple.str();
2009   case llvm::Triple::ppc64:
2010     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2011       return "powerpc64-linux-gnu";
2012     return TargetTriple.str();
2013   }
2014 }
2015
2016 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2017   if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2018 }
2019
2020 static bool isMipsArch(llvm::Triple::ArchType Arch) {
2021   return Arch == llvm::Triple::mips ||
2022          Arch == llvm::Triple::mipsel ||
2023          Arch == llvm::Triple::mips64 ||
2024          Arch == llvm::Triple::mips64el;
2025 }
2026
2027 static bool isMipsR2Arch(llvm::Triple::ArchType Arch,
2028                          const ArgList &Args) {
2029   if (Arch != llvm::Triple::mips &&
2030       Arch != llvm::Triple::mipsel)
2031     return false;
2032
2033   Arg *A = Args.getLastArg(options::OPT_march_EQ,
2034                            options::OPT_mcpu_EQ,
2035                            options::OPT_mips_CPUs_Group);
2036
2037   if (!A)
2038     return false;
2039
2040   if (A->getOption().matches(options::OPT_mips_CPUs_Group))
2041     return A->getOption().matches(options::OPT_mips32r2);
2042
2043   return A->getValue() == StringRef("mips32r2");
2044 }
2045
2046 static StringRef getMultilibDir(const llvm::Triple &Triple,
2047                                 const ArgList &Args) {
2048   if (!isMipsArch(Triple.getArch()))
2049     return Triple.isArch32Bit() ? "lib32" : "lib64";
2050
2051   // lib32 directory has a special meaning on MIPS targets.
2052   // It contains N32 ABI binaries. Use this folder if produce
2053   // code for N32 ABI only.
2054   if (hasMipsN32ABIArg(Args))
2055     return "lib32";
2056
2057   return Triple.isArch32Bit() ? "lib" : "lib64";
2058 }
2059
2060 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2061   : Generic_ELF(D, Triple, Args) {
2062   llvm::Triple::ArchType Arch = Triple.getArch();
2063   const std::string &SysRoot = getDriver().SysRoot;
2064
2065   // OpenSuse stores the linker with the compiler, add that to the search
2066   // path.
2067   ToolChain::path_list &PPaths = getProgramPaths();
2068   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2069                          GCCInstallation.getTriple().str() + "/bin").str());
2070
2071   Linker = GetProgramPath("ld");
2072
2073   LinuxDistro Distro = DetectLinuxDistro(Arch);
2074
2075   if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
2076     ExtraOpts.push_back("-z");
2077     ExtraOpts.push_back("relro");
2078   }
2079
2080   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2081     ExtraOpts.push_back("-X");
2082
2083   const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2084
2085   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2086   // and the MIPS ABI require .dynsym to be sorted in different ways.
2087   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2088   // ABI requires a mapping between the GOT and the symbol table.
2089   // Android loader does not support .gnu.hash.
2090   if (!isMipsArch(Arch) && !IsAndroid) {
2091     if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
2092         (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2093       ExtraOpts.push_back("--hash-style=gnu");
2094
2095     if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
2096         Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2097       ExtraOpts.push_back("--hash-style=both");
2098   }
2099
2100   if (IsRedhat(Distro))
2101     ExtraOpts.push_back("--no-add-needed");
2102
2103   if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2104       IsOpenSuse(Distro) ||
2105       (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2106       (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2107     ExtraOpts.push_back("--build-id");
2108
2109   if (IsOpenSuse(Distro))
2110     ExtraOpts.push_back("--enable-new-dtags");
2111
2112   // The selection of paths to try here is designed to match the patterns which
2113   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2114   // This was determined by running GCC in a fake filesystem, creating all
2115   // possible permutations of these directories, and seeing which ones it added
2116   // to the link paths.
2117   path_list &Paths = getFilePaths();
2118
2119   const std::string Multilib = getMultilibDir(Triple, Args);
2120   const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2121
2122   // Add the multilib suffixed paths where they are available.
2123   if (GCCInstallation.isValid()) {
2124     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2125     const std::string &LibPath = GCCInstallation.getParentLibPath();
2126
2127     if (IsAndroid && isMipsR2Arch(Triple.getArch(), Args))
2128       addPathIfExists(GCCInstallation.getInstallPath() +
2129                       GCCInstallation.getMultiarchSuffix() +
2130                       "/mips-r2",
2131                       Paths);
2132     else
2133       addPathIfExists((GCCInstallation.getInstallPath() +
2134                        GCCInstallation.getMultiarchSuffix()),
2135                       Paths);
2136
2137     // If the GCC installation we found is inside of the sysroot, we want to
2138     // prefer libraries installed in the parent prefix of the GCC installation.
2139     // It is important to *not* use these paths when the GCC installation is
2140     // outside of the system root as that can pick up unintended libraries.
2141     // This usually happens when there is an external cross compiler on the
2142     // host system, and a more minimal sysroot available that is the target of
2143     // the cross.
2144     if (StringRef(LibPath).startswith(SysRoot)) {
2145       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
2146                       Paths);
2147       addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2148       addPathIfExists(LibPath + "/../" + Multilib, Paths);
2149     }
2150     // On Android, libraries in the parent prefix of the GCC installation are
2151     // preferred to the ones under sysroot.
2152     if (IsAndroid) {
2153       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2154     }
2155   }
2156   addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2157   addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2158   addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2159   addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2160
2161   // Try walking via the GCC triple path in case of multiarch GCC
2162   // installations with strange symlinks.
2163   if (GCCInstallation.isValid())
2164     addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2165                     "/../../" + Multilib, Paths);
2166
2167   // Add the non-multilib suffixed paths (if potentially different).
2168   if (GCCInstallation.isValid()) {
2169     const std::string &LibPath = GCCInstallation.getParentLibPath();
2170     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2171     if (!GCCInstallation.getMultiarchSuffix().empty())
2172       addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2173
2174     if (StringRef(LibPath).startswith(SysRoot)) {
2175       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2176       addPathIfExists(LibPath, Paths);
2177     }
2178   }
2179   addPathIfExists(SysRoot + "/lib", Paths);
2180   addPathIfExists(SysRoot + "/usr/lib", Paths);
2181 }
2182
2183 bool Linux::HasNativeLLVMSupport() const {
2184   return true;
2185 }
2186
2187 Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
2188                         const ActionList &Inputs) const {
2189   Action::ActionClass Key;
2190   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2191     Key = Action::AnalyzeJobClass;
2192   else
2193     Key = JA.getKind();
2194
2195   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
2196                                              options::OPT_no_integrated_as,
2197                                              IsIntegratedAssemblerDefault());
2198
2199   Tool *&T = Tools[Key];
2200   if (!T) {
2201     switch (Key) {
2202     case Action::AssembleJobClass:
2203       if (UseIntegratedAs)
2204         T = new tools::ClangAs(*this);
2205       else
2206         T = new tools::linuxtools::Assemble(*this);
2207       break;
2208     case Action::LinkJobClass:
2209       T = new tools::linuxtools::Link(*this); break;
2210     default:
2211       T = &Generic_GCC::SelectTool(C, JA, Inputs);
2212     }
2213   }
2214
2215   return *T;
2216 }
2217
2218 void Linux::addClangTargetOptions(ArgStringList &CC1Args) const {
2219   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2220   if (V >= Generic_GCC::GCCVersion::Parse("4.7.0"))
2221     CC1Args.push_back("-fuse-init-array");
2222 }
2223
2224 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2225                                       ArgStringList &CC1Args) const {
2226   const Driver &D = getDriver();
2227
2228   if (DriverArgs.hasArg(options::OPT_nostdinc))
2229     return;
2230
2231   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2232     addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
2233
2234   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2235     llvm::sys::Path P(D.ResourceDir);
2236     P.appendComponent("include");
2237     addSystemInclude(DriverArgs, CC1Args, P.str());
2238   }
2239
2240   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2241     return;
2242
2243   // Check for configure-time C include directories.
2244   StringRef CIncludeDirs(C_INCLUDE_DIRS);
2245   if (CIncludeDirs != "") {
2246     SmallVector<StringRef, 5> dirs;
2247     CIncludeDirs.split(dirs, ":");
2248     for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2249          I != E; ++I) {
2250       StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
2251       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2252     }
2253     return;
2254   }
2255
2256   // Lacking those, try to detect the correct set of system includes for the
2257   // target triple.
2258
2259   // Implement generic Debian multiarch support.
2260   const StringRef X86_64MultiarchIncludeDirs[] = {
2261     "/usr/include/x86_64-linux-gnu",
2262
2263     // FIXME: These are older forms of multiarch. It's not clear that they're
2264     // in use in any released version of Debian, so we should consider
2265     // removing them.
2266     "/usr/include/i686-linux-gnu/64",
2267     "/usr/include/i486-linux-gnu/64"
2268   };
2269   const StringRef X86MultiarchIncludeDirs[] = {
2270     "/usr/include/i386-linux-gnu",
2271
2272     // FIXME: These are older forms of multiarch. It's not clear that they're
2273     // in use in any released version of Debian, so we should consider
2274     // removing them.
2275     "/usr/include/x86_64-linux-gnu/32",
2276     "/usr/include/i686-linux-gnu",
2277     "/usr/include/i486-linux-gnu"
2278   };
2279   const StringRef ARMMultiarchIncludeDirs[] = {
2280     "/usr/include/arm-linux-gnueabi"
2281   };
2282   const StringRef ARMHFMultiarchIncludeDirs[] = {
2283     "/usr/include/arm-linux-gnueabihf"
2284   };
2285   const StringRef MIPSMultiarchIncludeDirs[] = {
2286     "/usr/include/mips-linux-gnu"
2287   };
2288   const StringRef MIPSELMultiarchIncludeDirs[] = {
2289     "/usr/include/mipsel-linux-gnu"
2290   };
2291   const StringRef PPCMultiarchIncludeDirs[] = {
2292     "/usr/include/powerpc-linux-gnu"
2293   };
2294   const StringRef PPC64MultiarchIncludeDirs[] = {
2295     "/usr/include/powerpc64-linux-gnu"
2296   };
2297   ArrayRef<StringRef> MultiarchIncludeDirs;
2298   if (getTriple().getArch() == llvm::Triple::x86_64) {
2299     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2300   } else if (getTriple().getArch() == llvm::Triple::x86) {
2301     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2302   } else if (getTriple().getArch() == llvm::Triple::arm) {
2303     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2304       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2305     else
2306       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2307   } else if (getTriple().getArch() == llvm::Triple::mips) {
2308     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2309   } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2310     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2311   } else if (getTriple().getArch() == llvm::Triple::ppc) {
2312     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2313   } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2314     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2315   }
2316   for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2317                                      E = MultiarchIncludeDirs.end();
2318        I != E; ++I) {
2319     if (llvm::sys::fs::exists(D.SysRoot + *I)) {
2320       addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
2321       break;
2322     }
2323   }
2324
2325   if (getTriple().getOS() == llvm::Triple::RTEMS)
2326     return;
2327
2328   // Add an include of '/include' directly. This isn't provided by default by
2329   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2330   // add even when Clang is acting as-if it were a system compiler.
2331   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
2332
2333   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
2334 }
2335
2336 /// \brief Helper to add the thre variant paths for a libstdc++ installation.
2337 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2338                                                 const ArgList &DriverArgs,
2339                                                 ArgStringList &CC1Args) {
2340   if (!llvm::sys::fs::exists(Base))
2341     return false;
2342   addSystemInclude(DriverArgs, CC1Args, Base);
2343   addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2344   addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2345   return true;
2346 }
2347
2348 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2349                                          ArgStringList &CC1Args) const {
2350   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2351       DriverArgs.hasArg(options::OPT_nostdincxx))
2352     return;
2353
2354   // Check if libc++ has been enabled and provide its include paths if so.
2355   if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2356     // libc++ is always installed at a fixed path on Linux currently.
2357     addSystemInclude(DriverArgs, CC1Args,
2358                      getDriver().SysRoot + "/usr/include/c++/v1");
2359     return;
2360   }
2361
2362   // We need a detected GCC installation on Linux to provide libstdc++'s
2363   // headers. We handled the libc++ case above.
2364   if (!GCCInstallation.isValid())
2365     return;
2366
2367   // By default, look for the C++ headers in an include directory adjacent to
2368   // the lib directory of the GCC installation. Note that this is expect to be
2369   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2370   StringRef LibDir = GCCInstallation.getParentLibPath();
2371   StringRef InstallDir = GCCInstallation.getInstallPath();
2372   StringRef Version = GCCInstallation.getVersion().Text;
2373   StringRef TripleStr = GCCInstallation.getTriple().str();
2374
2375   const std::string IncludePathCandidates[] = {
2376     LibDir.str() + "/../include/c++/" + Version.str(),
2377     // Gentoo is weird and places its headers inside the GCC install, so if the
2378     // first attempt to find the headers fails, try this pattern.
2379     InstallDir.str() + "/include/g++-v4",
2380     // Android standalone toolchain has C++ headers in yet another place.
2381     LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(),
2382     // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2383     // without a subdirectory corresponding to the gcc version.
2384     LibDir.str() + "/../include/c++",
2385   };
2386
2387   for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2388     if (addLibStdCXXIncludePaths(IncludePathCandidates[i], (TripleStr +
2389                 GCCInstallation.getMultiarchSuffix()),
2390             DriverArgs, CC1Args))
2391       break;
2392   }
2393 }
2394
2395 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2396
2397 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2398   : Generic_ELF(D, Triple, Args) {
2399
2400   // Path mangling to find libexec
2401   getProgramPaths().push_back(getDriver().getInstalledDir());
2402   if (getDriver().getInstalledDir() != getDriver().Dir)
2403     getProgramPaths().push_back(getDriver().Dir);
2404
2405   getFilePaths().push_back(getDriver().Dir + "/../lib");
2406   getFilePaths().push_back("/usr/lib");
2407   getFilePaths().push_back("/usr/lib/gcc41");
2408 }
2409
2410 Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
2411                             const ActionList &Inputs) const {
2412   Action::ActionClass Key;
2413   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2414     Key = Action::AnalyzeJobClass;
2415   else
2416     Key = JA.getKind();
2417
2418   Tool *&T = Tools[Key];
2419   if (!T) {
2420     switch (Key) {
2421     case Action::AssembleJobClass:
2422       T = new tools::dragonfly::Assemble(*this); break;
2423     case Action::LinkJobClass:
2424       T = new tools::dragonfly::Link(*this); break;
2425     default:
2426       T = &Generic_GCC::SelectTool(C, JA, Inputs);
2427     }
2428   }
2429
2430   return *T;
2431 }