• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef HAVE_CLANG_CONFIG_H
13 # include "clang/Config/config.h"
14 #endif
15 
16 #include "clang/Driver/Arg.h"
17 #include "clang/Driver/ArgList.h"
18 #include "clang/Driver/Compilation.h"
19 #include "clang/Driver/Driver.h"
20 #include "clang/Driver/DriverDiagnostic.h"
21 #include "clang/Driver/HostInfo.h"
22 #include "clang/Driver/ObjCRuntime.h"
23 #include "clang/Driver/OptTable.h"
24 #include "clang/Driver/Option.h"
25 #include "clang/Driver/Options.h"
26 #include "clang/Basic/Version.h"
27 
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/system_error.h"
37 
38 #include <cstdlib> // ::getenv
39 
40 #include "llvm/Config/config.h" // for CXX_INCLUDE_ROOT
41 
42 using namespace clang::driver;
43 using namespace clang::driver::toolchains;
44 
45 /// Darwin - Darwin tool chain for i386 and x86_64.
46 
Darwin(const HostInfo & Host,const llvm::Triple & Triple)47 Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple)
48   : ToolChain(Host, Triple), TargetInitialized(false),
49     ARCRuntimeForSimulator(ARCSimulator_None)
50 {
51   // Compute the initial Darwin version based on the host.
52   bool HadExtra;
53   std::string OSName = Triple.getOSName();
54   if (!Driver::GetReleaseVersion(&OSName.c_str()[6],
55                                  DarwinVersion[0], DarwinVersion[1],
56                                  DarwinVersion[2], HadExtra))
57     getDriver().Diag(clang::diag::err_drv_invalid_darwin_version) << OSName;
58 
59   llvm::raw_string_ostream(MacosxVersionMin)
60     << "10." << std::max(0, (int)DarwinVersion[0] - 4) << '.'
61     << DarwinVersion[1];
62 }
63 
LookupTypeForExtension(const char * Ext) const64 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
65   types::ID Ty = types::lookupTypeForExtension(Ext);
66 
67   // Darwin always preprocesses assembly files (unless -x is used explicitly).
68   if (Ty == types::TY_PP_Asm)
69     return types::TY_Asm;
70 
71   return Ty;
72 }
73 
HasNativeLLVMSupport() const74 bool Darwin::HasNativeLLVMSupport() const {
75   return true;
76 }
77 
hasARCRuntime() const78 bool Darwin::hasARCRuntime() const {
79   // FIXME: Remove this once there is a proper way to detect an ARC runtime
80   // for the simulator.
81   switch (ARCRuntimeForSimulator) {
82   case ARCSimulator_None:
83     break;
84   case ARCSimulator_HasARCRuntime:
85     return true;
86   case ARCSimulator_NoARCRuntime:
87     return false;
88   }
89 
90   if (isTargetIPhoneOS())
91     return !isIPhoneOSVersionLT(5);
92   else
93     return !isMacosxVersionLT(10, 7);
94 }
95 
96 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
configureObjCRuntime(ObjCRuntime & runtime) const97 void Darwin::configureObjCRuntime(ObjCRuntime &runtime) const {
98   if (runtime.getKind() != ObjCRuntime::NeXT)
99     return ToolChain::configureObjCRuntime(runtime);
100 
101   runtime.HasARC = runtime.HasWeak = hasARCRuntime();
102 
103   // So far, objc_terminate is only available in iOS 5.
104   // FIXME: do the simulator logic properly.
105   if (!ARCRuntimeForSimulator && isTargetIPhoneOS())
106     runtime.HasTerminate = !isIPhoneOSVersionLT(5);
107   else
108     runtime.HasTerminate = false;
109 }
110 
111 // FIXME: Can we tablegen this?
GetArmArchForMArch(llvm::StringRef Value)112 static const char *GetArmArchForMArch(llvm::StringRef Value) {
113   if (Value == "armv6k")
114     return "armv6";
115 
116   if (Value == "armv5tej")
117     return "armv5";
118 
119   if (Value == "xscale")
120     return "xscale";
121 
122   if (Value == "armv4t")
123     return "armv4t";
124 
125   if (Value == "armv7" || Value == "armv7-a" || Value == "armv7-r" ||
126       Value == "armv7-m" || Value == "armv7a" || Value == "armv7r" ||
127       Value == "armv7m")
128     return "armv7";
129 
130   return 0;
131 }
132 
133 // FIXME: Can we tablegen this?
GetArmArchForMCpu(llvm::StringRef Value)134 static const char *GetArmArchForMCpu(llvm::StringRef Value) {
135   if (Value == "arm10tdmi" || Value == "arm1020t" || Value == "arm9e" ||
136       Value == "arm946e-s" || Value == "arm966e-s" ||
137       Value == "arm968e-s" || Value == "arm10e" ||
138       Value == "arm1020e" || Value == "arm1022e" || Value == "arm926ej-s" ||
139       Value == "arm1026ej-s")
140     return "armv5";
141 
142   if (Value == "xscale")
143     return "xscale";
144 
145   if (Value == "arm1136j-s" || Value == "arm1136jf-s" ||
146       Value == "arm1176jz-s" || Value == "arm1176jzf-s" ||
147       Value == "cortex-m0" )
148     return "armv6";
149 
150   if (Value == "cortex-a8" || Value == "cortex-r4" || Value == "cortex-m3")
151     return "armv7";
152 
153   return 0;
154 }
155 
getDarwinArchName(const ArgList & Args) const156 llvm::StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
157   switch (getTriple().getArch()) {
158   default:
159     return getArchName();
160 
161   case llvm::Triple::thumb:
162   case llvm::Triple::arm: {
163     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
164       if (const char *Arch = GetArmArchForMArch(A->getValue(Args)))
165         return Arch;
166 
167     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
168       if (const char *Arch = GetArmArchForMCpu(A->getValue(Args)))
169         return Arch;
170 
171     return "arm";
172   }
173   }
174 }
175 
~Darwin()176 Darwin::~Darwin() {
177   // Free tool implementations.
178   for (llvm::DenseMap<unsigned, Tool*>::iterator
179          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
180     delete it->second;
181 }
182 
ComputeEffectiveClangTriple(const ArgList & Args) const183 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args) const {
184   llvm::Triple Triple(ComputeLLVMTriple(Args));
185 
186   // If the target isn't initialized (e.g., an unknown Darwin platform, return
187   // the default triple).
188   if (!isTargetInitialized())
189     return Triple.getTriple();
190 
191   unsigned Version[3];
192   getTargetVersion(Version);
193 
194   llvm::SmallString<16> Str;
195   llvm::raw_svector_ostream(Str)
196     << (isTargetIPhoneOS() ? "ios" : "macosx")
197     << Version[0] << "." << Version[1] << "." << Version[2];
198   Triple.setOSName(Str.str());
199 
200   return Triple.getTriple();
201 }
202 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const203 Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
204                          const ActionList &Inputs) const {
205   Action::ActionClass Key;
206 
207   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
208     // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI.
209     if (Inputs.size() == 1 &&
210         types::isCXX(Inputs[0]->getType()) &&
211         getTriple().getOS() == llvm::Triple::Darwin &&
212         getTriple().getArch() == llvm::Triple::x86 &&
213         C.getArgs().getLastArg(options::OPT_fapple_kext))
214       Key = JA.getKind();
215     else
216       Key = Action::AnalyzeJobClass;
217   } else
218     Key = JA.getKind();
219 
220   // FIXME: This doesn't belong here, but ideally we will support static soon
221   // anyway.
222   bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
223                     C.getArgs().hasArg(options::OPT_static) ||
224                     C.getArgs().hasArg(options::OPT_fapple_kext));
225   bool IsIADefault = IsIntegratedAssemblerDefault() && !HasStatic;
226   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
227                                              options::OPT_no_integrated_as,
228                                              IsIADefault);
229 
230   Tool *&T = Tools[Key];
231   if (!T) {
232     switch (Key) {
233     case Action::InputClass:
234     case Action::BindArchClass:
235       assert(0 && "Invalid tool kind.");
236     case Action::PreprocessJobClass:
237       T = new tools::darwin::Preprocess(*this); break;
238     case Action::AnalyzeJobClass:
239       T = new tools::Clang(*this); break;
240     case Action::PrecompileJobClass:
241     case Action::CompileJobClass:
242       T = new tools::darwin::Compile(*this); break;
243     case Action::AssembleJobClass: {
244       if (UseIntegratedAs)
245         T = new tools::ClangAs(*this);
246       else
247         T = new tools::darwin::Assemble(*this);
248       break;
249     }
250     case Action::LinkJobClass:
251       T = new tools::darwin::Link(*this); break;
252     case Action::LipoJobClass:
253       T = new tools::darwin::Lipo(*this); break;
254     case Action::DsymutilJobClass:
255       T = new tools::darwin::Dsymutil(*this); break;
256     }
257   }
258 
259   return *T;
260 }
261 
262 
DarwinClang(const HostInfo & Host,const llvm::Triple & Triple)263 DarwinClang::DarwinClang(const HostInfo &Host, const llvm::Triple& Triple)
264   : Darwin(Host, Triple)
265 {
266   std::string UsrPrefix = "llvm-gcc-4.2/";
267 
268   getProgramPaths().push_back(getDriver().getInstalledDir());
269   if (getDriver().getInstalledDir() != getDriver().Dir)
270     getProgramPaths().push_back(getDriver().Dir);
271 
272   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
273   getProgramPaths().push_back(getDriver().getInstalledDir());
274   if (getDriver().getInstalledDir() != getDriver().Dir)
275     getProgramPaths().push_back(getDriver().Dir);
276 
277   // For fallback, we need to know how to find the GCC cc1 executables, so we
278   // also add the GCC libexec paths. This is legacy code that can be removed
279   // once fallback is no longer useful.
280   std::string ToolChainDir = "i686-apple-darwin";
281   ToolChainDir += llvm::utostr(DarwinVersion[0]);
282   ToolChainDir += "/4.2.1";
283 
284   std::string Path = getDriver().Dir;
285   Path += "/../" + UsrPrefix + "libexec/gcc/";
286   Path += ToolChainDir;
287   getProgramPaths().push_back(Path);
288 
289   Path = "/usr/" + UsrPrefix + "libexec/gcc/";
290   Path += ToolChainDir;
291   getProgramPaths().push_back(Path);
292 }
293 
AddLinkSearchPathArgs(const ArgList & Args,ArgStringList & CmdArgs) const294 void DarwinClang::AddLinkSearchPathArgs(const ArgList &Args,
295                                        ArgStringList &CmdArgs) const {
296   // The Clang toolchain uses explicit paths for internal libraries.
297 
298   // Unfortunately, we still might depend on a few of the libraries that are
299   // only available in the gcc library directory (in particular
300   // libstdc++.dylib). For now, hardcode the path to the known install location.
301   llvm::sys::Path P(getDriver().Dir);
302   P.eraseComponent(); // .../usr/bin -> ../usr
303   P.appendComponent("lib");
304   P.appendComponent("gcc");
305   switch (getTriple().getArch()) {
306   default:
307     assert(0 && "Invalid Darwin arch!");
308   case llvm::Triple::x86:
309   case llvm::Triple::x86_64:
310     P.appendComponent("i686-apple-darwin10");
311     break;
312   case llvm::Triple::arm:
313   case llvm::Triple::thumb:
314     P.appendComponent("arm-apple-darwin10");
315     break;
316   case llvm::Triple::ppc:
317   case llvm::Triple::ppc64:
318     P.appendComponent("powerpc-apple-darwin10");
319     break;
320   }
321   P.appendComponent("4.2.1");
322 
323   // Determine the arch specific GCC subdirectory.
324   const char *ArchSpecificDir = 0;
325   switch (getTriple().getArch()) {
326   default:
327     break;
328   case llvm::Triple::arm:
329   case llvm::Triple::thumb: {
330     std::string Triple = ComputeLLVMTriple(Args);
331     llvm::StringRef TripleStr = Triple;
332     if (TripleStr.startswith("armv5") || TripleStr.startswith("thumbv5"))
333       ArchSpecificDir = "v5";
334     else if (TripleStr.startswith("armv6") || TripleStr.startswith("thumbv6"))
335       ArchSpecificDir = "v6";
336     else if (TripleStr.startswith("armv7") || TripleStr.startswith("thumbv7"))
337       ArchSpecificDir = "v7";
338     break;
339   }
340   case llvm::Triple::ppc64:
341     ArchSpecificDir = "ppc64";
342     break;
343   case llvm::Triple::x86_64:
344     ArchSpecificDir = "x86_64";
345     break;
346   }
347 
348   if (ArchSpecificDir) {
349     P.appendComponent(ArchSpecificDir);
350     bool Exists;
351     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
352       CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
353     P.eraseComponent();
354   }
355 
356   bool Exists;
357   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
358     CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
359 }
360 
AddLinkARCArgs(const ArgList & Args,ArgStringList & CmdArgs) const361 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
362                                  ArgStringList &CmdArgs) const {
363 
364   CmdArgs.push_back("-force_load");
365   llvm::sys::Path P(getDriver().ClangExecutable);
366   P.eraseComponent(); // 'clang'
367   P.eraseComponent(); // 'bin'
368   P.appendComponent("lib");
369   P.appendComponent("arc");
370   P.appendComponent("libarclite_");
371   std::string s = P.str();
372   // Mash in the platform.
373   if (isTargetIPhoneOS())
374     s += "iphoneos";
375   // FIXME: isTargetIphoneOSSimulator() is not returning true.
376   else if (ARCRuntimeForSimulator != ARCSimulator_None)
377     s += "iphonesimulator";
378   else
379     s += "macosx";
380   s += ".a";
381 
382   CmdArgs.push_back(Args.MakeArgString(s));
383 }
384 
AddLinkRuntimeLib(const ArgList & Args,ArgStringList & CmdArgs,const char * DarwinStaticLib) const385 void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
386                                     ArgStringList &CmdArgs,
387                                     const char *DarwinStaticLib) const {
388   llvm::sys::Path P(getDriver().ResourceDir);
389   P.appendComponent("lib");
390   P.appendComponent("darwin");
391   P.appendComponent(DarwinStaticLib);
392 
393   // For now, allow missing resource libraries to support developers who may
394   // not have compiler-rt checked out or integrated into their build.
395   bool Exists;
396   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
397     CmdArgs.push_back(Args.MakeArgString(P.str()));
398 }
399 
AddLinkRuntimeLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const400 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
401                                         ArgStringList &CmdArgs) const {
402   // Darwin doesn't support real static executables, don't link any runtime
403   // libraries with -static.
404   if (Args.hasArg(options::OPT_static))
405     return;
406 
407   // Reject -static-libgcc for now, we can deal with this when and if someone
408   // cares. This is useful in situations where someone wants to statically link
409   // something like libstdc++, and needs its runtime support routines.
410   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
411     getDriver().Diag(clang::diag::err_drv_unsupported_opt)
412       << A->getAsString(Args);
413     return;
414   }
415 
416   // Otherwise link libSystem, then the dynamic runtime library, and finally any
417   // target specific static runtime library.
418   CmdArgs.push_back("-lSystem");
419 
420   // Select the dynamic runtime library and the target specific static library.
421   if (isTargetIPhoneOS()) {
422     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
423     // it never went into the SDK.
424     if (!isTargetIOSSimulator())
425         CmdArgs.push_back("-lgcc_s.1");
426 
427     // We currently always need a static runtime library for iOS.
428     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
429   } else {
430     // The dynamic runtime library was merged with libSystem for 10.6 and
431     // beyond; only 10.4 and 10.5 need an additional runtime library.
432     if (isMacosxVersionLT(10, 5))
433       CmdArgs.push_back("-lgcc_s.10.4");
434     else if (isMacosxVersionLT(10, 6))
435       CmdArgs.push_back("-lgcc_s.10.5");
436 
437     // For OS X, we thought we would only need a static runtime library when
438     // targeting 10.4, to provide versions of the static functions which were
439     // omitted from 10.4.dylib.
440     //
441     // Unfortunately, that turned out to not be true, because Darwin system
442     // headers can still use eprintf on i386, and it is not exported from
443     // libSystem. Therefore, we still must provide a runtime library just for
444     // the tiny tiny handful of projects that *might* use that symbol.
445     if (isMacosxVersionLT(10, 5)) {
446       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
447     } else {
448       if (getTriple().getArch() == llvm::Triple::x86)
449         AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
450       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
451     }
452   }
453 }
454 
SimulatorVersionDefineName()455 static inline llvm::StringRef SimulatorVersionDefineName() {
456   return "__IPHONE_OS_VERSION_MIN_REQUIRED";
457 }
458 
459 /// \brief Parse the simulator version define:
460 /// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9])
461 // and return the grouped values as integers, e.g:
462 //   __IPHONE_OS_VERSION_MIN_REQUIRED=40201
463 // will return Major=4, Minor=2, Micro=1.
GetVersionFromSimulatorDefine(llvm::StringRef define,unsigned & Major,unsigned & Minor,unsigned & Micro)464 static bool GetVersionFromSimulatorDefine(llvm::StringRef define,
465                                           unsigned &Major, unsigned &Minor,
466                                           unsigned &Micro) {
467   assert(define.startswith(SimulatorVersionDefineName()));
468   llvm::StringRef name, version;
469   llvm::tie(name, version) = define.split('=');
470   if (version.empty())
471     return false;
472   std::string verstr = version.str();
473   char *end;
474   unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10);
475   if (*end != '\0')
476     return false;
477   Major = num / 10000;
478   num = num % 10000;
479   Minor = num / 100;
480   Micro = num % 100;
481   return true;
482 }
483 
AddDeploymentTarget(DerivedArgList & Args) const484 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
485   const OptTable &Opts = getDriver().getOpts();
486 
487   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
488   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
489   Arg *iOSSimVersion = Args.getLastArg(
490     options::OPT_mios_simulator_version_min_EQ);
491 
492   // FIXME: HACK! When compiling for the simulator we don't get a
493   // '-miphoneos-version-min' to help us know whether there is an ARC runtime
494   // or not; try to parse a __IPHONE_OS_VERSION_MIN_REQUIRED
495   // define passed in command-line.
496   if (!iOSVersion) {
497     for (arg_iterator it = Args.filtered_begin(options::OPT_D),
498            ie = Args.filtered_end(); it != ie; ++it) {
499       llvm::StringRef define = (*it)->getValue(Args);
500       if (define.startswith(SimulatorVersionDefineName())) {
501         unsigned Major, Minor, Micro;
502         if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) &&
503             Major < 10 && Minor < 100 && Micro < 100) {
504           ARCRuntimeForSimulator = Major < 5 ? ARCSimulator_NoARCRuntime
505                                              : ARCSimulator_HasARCRuntime;
506         }
507         break;
508       }
509     }
510   }
511 
512   if (OSXVersion && (iOSVersion || iOSSimVersion)) {
513     getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with)
514           << OSXVersion->getAsString(Args)
515           << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
516     iOSVersion = iOSSimVersion = 0;
517   } else if (iOSVersion && iOSSimVersion) {
518     getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with)
519           << iOSVersion->getAsString(Args)
520           << iOSSimVersion->getAsString(Args);
521     iOSSimVersion = 0;
522   } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
523     // If not deployment target was specified on the command line, check for
524     // environment defines.
525     const char *OSXTarget = ::getenv("MACOSX_DEPLOYMENT_TARGET");
526     const char *iOSTarget = ::getenv("IPHONEOS_DEPLOYMENT_TARGET");
527     const char *iOSSimTarget = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET");
528 
529     // Ignore empty strings.
530     if (OSXTarget && OSXTarget[0] == '\0')
531       OSXTarget = 0;
532     if (iOSTarget && iOSTarget[0] == '\0')
533       iOSTarget = 0;
534     if (iOSSimTarget && iOSSimTarget[0] == '\0')
535       iOSSimTarget = 0;
536 
537     // Handle conflicting deployment targets
538     //
539     // FIXME: Don't hardcode default here.
540 
541     // Do not allow conflicts with the iOS simulator target.
542     if (iOSSimTarget && (OSXTarget || iOSTarget)) {
543       getDriver().Diag(clang::diag::err_drv_conflicting_deployment_targets)
544         << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
545         << (OSXTarget ? "MACOSX_DEPLOYMENT_TARGET" :
546             "IPHONEOS_DEPLOYMENT_TARGET");
547     }
548 
549     // Allow conflicts among OSX and iOS for historical reasons, but choose the
550     // default platform.
551     if (OSXTarget && iOSTarget) {
552       if (getTriple().getArch() == llvm::Triple::arm ||
553           getTriple().getArch() == llvm::Triple::thumb)
554         OSXTarget = 0;
555       else
556         iOSTarget = 0;
557     }
558 
559     if (OSXTarget) {
560       const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
561       OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
562       Args.append(OSXVersion);
563     } else if (iOSTarget) {
564       const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
565       iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
566       Args.append(iOSVersion);
567     } else if (iOSSimTarget) {
568       const Option *O = Opts.getOption(
569         options::OPT_mios_simulator_version_min_EQ);
570       iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
571       Args.append(iOSSimVersion);
572     } else {
573       // Otherwise, assume we are targeting OS X.
574       const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
575       OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
576       Args.append(OSXVersion);
577     }
578   }
579 
580   // Reject invalid architecture combinations.
581   if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
582                         getTriple().getArch() != llvm::Triple::x86_64)) {
583     getDriver().Diag(clang::diag::err_drv_invalid_arch_for_deployment_target)
584       << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
585   }
586 
587   // Set the tool chain target information.
588   unsigned Major, Minor, Micro;
589   bool HadExtra;
590   if (OSXVersion) {
591     assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
592     if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor,
593                                    Micro, HadExtra) || HadExtra ||
594         Major != 10 || Minor >= 100 || Micro >= 100)
595       getDriver().Diag(clang::diag::err_drv_invalid_version_number)
596         << OSXVersion->getAsString(Args);
597   } else {
598     const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
599     assert(Version && "Unknown target platform!");
600     if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor,
601                                    Micro, HadExtra) || HadExtra ||
602         Major >= 10 || Minor >= 100 || Micro >= 100)
603       getDriver().Diag(clang::diag::err_drv_invalid_version_number)
604         << Version->getAsString(Args);
605   }
606 
607   bool IsIOSSim = bool(iOSSimVersion);
608 
609   // In GCC, the simulator historically was treated as being OS X in some
610   // contexts, like determining the link logic, despite generally being called
611   // with an iOS deployment target. For compatibility, we detect the
612   // simulator as iOS + x86, and treat it differently in a few contexts.
613   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
614                      getTriple().getArch() == llvm::Triple::x86_64))
615     IsIOSSim = true;
616 
617   setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
618 }
619 
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const620 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
621                                       ArgStringList &CmdArgs) const {
622   CXXStdlibType Type = GetCXXStdlibType(Args);
623 
624   switch (Type) {
625   case ToolChain::CST_Libcxx:
626     CmdArgs.push_back("-lc++");
627     break;
628 
629   case ToolChain::CST_Libstdcxx: {
630     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
631     // it was previously found in the gcc lib dir. However, for all the Darwin
632     // platforms we care about it was -lstdc++.6, so we search for that
633     // explicitly if we can't see an obvious -lstdc++ candidate.
634 
635     // Check in the sysroot first.
636     bool Exists;
637     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
638       llvm::sys::Path P(A->getValue(Args));
639       P.appendComponent("usr");
640       P.appendComponent("lib");
641       P.appendComponent("libstdc++.dylib");
642 
643       if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
644         P.eraseComponent();
645         P.appendComponent("libstdc++.6.dylib");
646         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
647           CmdArgs.push_back(Args.MakeArgString(P.str()));
648           return;
649         }
650       }
651     }
652 
653     // Otherwise, look in the root.
654     if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
655       (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
656       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
657       return;
658     }
659 
660     // Otherwise, let the linker search.
661     CmdArgs.push_back("-lstdc++");
662     break;
663   }
664   }
665 }
666 
AddCCKextLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const667 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
668                                    ArgStringList &CmdArgs) const {
669 
670   // For Darwin platforms, use the compiler-rt-based support library
671   // instead of the gcc-provided one (which is also incidentally
672   // only present in the gcc lib dir, which makes it hard to find).
673 
674   llvm::sys::Path P(getDriver().ResourceDir);
675   P.appendComponent("lib");
676   P.appendComponent("darwin");
677   P.appendComponent("libclang_rt.cc_kext.a");
678 
679   // For now, allow missing resource libraries to support developers who may
680   // not have compiler-rt checked out or integrated into their build.
681   bool Exists;
682   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
683     CmdArgs.push_back(Args.MakeArgString(P.str()));
684 }
685 
TranslateArgs(const DerivedArgList & Args,const char * BoundArch) const686 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
687                                       const char *BoundArch) const {
688   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
689   const OptTable &Opts = getDriver().getOpts();
690 
691   // FIXME: We really want to get out of the tool chain level argument
692   // translation business, as it makes the driver functionality much
693   // more opaque. For now, we follow gcc closely solely for the
694   // purpose of easily achieving feature parity & testability. Once we
695   // have something that works, we should reevaluate each translation
696   // and try to push it down into tool specific logic.
697 
698   for (ArgList::const_iterator it = Args.begin(),
699          ie = Args.end(); it != ie; ++it) {
700     Arg *A = *it;
701 
702     if (A->getOption().matches(options::OPT_Xarch__)) {
703       // Skip this argument unless the architecture matches either the toolchain
704       // triple arch, or the arch being bound.
705       //
706       // FIXME: Canonicalize name.
707       llvm::StringRef XarchArch = A->getValue(Args, 0);
708       if (!(XarchArch == getArchName()  ||
709             (BoundArch && XarchArch == BoundArch)))
710         continue;
711 
712       Arg *OriginalArg = A;
713       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1));
714       unsigned Prev = Index;
715       Arg *XarchArg = Opts.ParseOneArg(Args, Index);
716 
717       // If the argument parsing failed or more than one argument was
718       // consumed, the -Xarch_ argument's parameter tried to consume
719       // extra arguments. Emit an error and ignore.
720       //
721       // We also want to disallow any options which would alter the
722       // driver behavior; that isn't going to work in our model. We
723       // use isDriverOption() as an approximation, although things
724       // like -O4 are going to slip through.
725       if (!XarchArg || Index > Prev + 1) {
726         getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument_with_args)
727           << A->getAsString(Args);
728         continue;
729       } else if (XarchArg->getOption().isDriverOption()) {
730         getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument_isdriver)
731           << A->getAsString(Args);
732         continue;
733       }
734 
735       XarchArg->setBaseArg(A);
736       A = XarchArg;
737 
738       DAL->AddSynthesizedArg(A);
739 
740       // Linker input arguments require custom handling. The problem is that we
741       // have already constructed the phase actions, so we can not treat them as
742       // "input arguments".
743       if (A->getOption().isLinkerInput()) {
744         // Convert the argument into individual Zlinker_input_args.
745         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
746           DAL->AddSeparateArg(OriginalArg,
747                               Opts.getOption(options::OPT_Zlinker_input),
748                               A->getValue(Args, i));
749 
750         }
751         continue;
752       }
753     }
754 
755     // Sob. These is strictly gcc compatible for the time being. Apple
756     // gcc translates options twice, which means that self-expanding
757     // options add duplicates.
758     switch ((options::ID) A->getOption().getID()) {
759     default:
760       DAL->append(A);
761       break;
762 
763     case options::OPT_mkernel:
764     case options::OPT_fapple_kext:
765       DAL->append(A);
766       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
767       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
768       break;
769 
770     case options::OPT_dependency_file:
771       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
772                           A->getValue(Args));
773       break;
774 
775     case options::OPT_gfull:
776       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
777       DAL->AddFlagArg(A,
778                Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
779       break;
780 
781     case options::OPT_gused:
782       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
783       DAL->AddFlagArg(A,
784              Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
785       break;
786 
787     case options::OPT_fterminated_vtables:
788     case options::OPT_findirect_virtual_calls:
789       DAL->AddFlagArg(A, Opts.getOption(options::OPT_fapple_kext));
790       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
791       break;
792 
793     case options::OPT_shared:
794       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
795       break;
796 
797     case options::OPT_fconstant_cfstrings:
798       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
799       break;
800 
801     case options::OPT_fno_constant_cfstrings:
802       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
803       break;
804 
805     case options::OPT_Wnonportable_cfstrings:
806       DAL->AddFlagArg(A,
807                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
808       break;
809 
810     case options::OPT_Wno_nonportable_cfstrings:
811       DAL->AddFlagArg(A,
812                    Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
813       break;
814 
815     case options::OPT_fpascal_strings:
816       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
817       break;
818 
819     case options::OPT_fno_pascal_strings:
820       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
821       break;
822     }
823   }
824 
825   if (getTriple().getArch() == llvm::Triple::x86 ||
826       getTriple().getArch() == llvm::Triple::x86_64)
827     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
828       DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
829 
830   // Add the arch options based on the particular spelling of -arch, to match
831   // how the driver driver works.
832   if (BoundArch) {
833     llvm::StringRef Name = BoundArch;
834     const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ);
835     const Option *MArch = Opts.getOption(options::OPT_march_EQ);
836 
837     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
838     // which defines the list of which architectures we accept.
839     if (Name == "ppc")
840       ;
841     else if (Name == "ppc601")
842       DAL->AddJoinedArg(0, MCpu, "601");
843     else if (Name == "ppc603")
844       DAL->AddJoinedArg(0, MCpu, "603");
845     else if (Name == "ppc604")
846       DAL->AddJoinedArg(0, MCpu, "604");
847     else if (Name == "ppc604e")
848       DAL->AddJoinedArg(0, MCpu, "604e");
849     else if (Name == "ppc750")
850       DAL->AddJoinedArg(0, MCpu, "750");
851     else if (Name == "ppc7400")
852       DAL->AddJoinedArg(0, MCpu, "7400");
853     else if (Name == "ppc7450")
854       DAL->AddJoinedArg(0, MCpu, "7450");
855     else if (Name == "ppc970")
856       DAL->AddJoinedArg(0, MCpu, "970");
857 
858     else if (Name == "ppc64")
859       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
860 
861     else if (Name == "i386")
862       ;
863     else if (Name == "i486")
864       DAL->AddJoinedArg(0, MArch, "i486");
865     else if (Name == "i586")
866       DAL->AddJoinedArg(0, MArch, "i586");
867     else if (Name == "i686")
868       DAL->AddJoinedArg(0, MArch, "i686");
869     else if (Name == "pentium")
870       DAL->AddJoinedArg(0, MArch, "pentium");
871     else if (Name == "pentium2")
872       DAL->AddJoinedArg(0, MArch, "pentium2");
873     else if (Name == "pentpro")
874       DAL->AddJoinedArg(0, MArch, "pentiumpro");
875     else if (Name == "pentIIm3")
876       DAL->AddJoinedArg(0, MArch, "pentium2");
877 
878     else if (Name == "x86_64")
879       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
880 
881     else if (Name == "arm")
882       DAL->AddJoinedArg(0, MArch, "armv4t");
883     else if (Name == "armv4t")
884       DAL->AddJoinedArg(0, MArch, "armv4t");
885     else if (Name == "armv5")
886       DAL->AddJoinedArg(0, MArch, "armv5tej");
887     else if (Name == "xscale")
888       DAL->AddJoinedArg(0, MArch, "xscale");
889     else if (Name == "armv6")
890       DAL->AddJoinedArg(0, MArch, "armv6k");
891     else if (Name == "armv7")
892       DAL->AddJoinedArg(0, MArch, "armv7a");
893 
894     else
895       llvm_unreachable("invalid Darwin arch");
896   }
897 
898   // Add an explicit version min argument for the deployment target. We do this
899   // after argument translation because -Xarch_ arguments may add a version min
900   // argument.
901   AddDeploymentTarget(*DAL);
902 
903   return DAL;
904 }
905 
IsUnwindTablesDefault() const906 bool Darwin::IsUnwindTablesDefault() const {
907   // FIXME: Gross; we should probably have some separate target
908   // definition, possibly even reusing the one in clang.
909   return getArchName() == "x86_64";
910 }
911 
UseDwarfDebugFlags() const912 bool Darwin::UseDwarfDebugFlags() const {
913   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
914     return S[0] != '\0';
915   return false;
916 }
917 
UseSjLjExceptions() const918 bool Darwin::UseSjLjExceptions() const {
919   // Darwin uses SjLj exceptions on ARM.
920   return (getTriple().getArch() == llvm::Triple::arm ||
921           getTriple().getArch() == llvm::Triple::thumb);
922 }
923 
GetDefaultRelocationModel() const924 const char *Darwin::GetDefaultRelocationModel() const {
925   return "pic";
926 }
927 
GetForcedPicModel() const928 const char *Darwin::GetForcedPicModel() const {
929   if (getArchName() == "x86_64")
930     return "pic";
931   return 0;
932 }
933 
SupportsProfiling() const934 bool Darwin::SupportsProfiling() const {
935   // Profiling instrumentation is only supported on x86.
936   return getArchName() == "i386" || getArchName() == "x86_64";
937 }
938 
SupportsObjCGC() const939 bool Darwin::SupportsObjCGC() const {
940   // Garbage collection is supported everywhere except on iPhone OS.
941   return !isTargetIPhoneOS();
942 }
943 
944 std::string
ComputeEffectiveClangTriple(const ArgList & Args) const945 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args) const {
946   return ComputeLLVMTriple(Args);
947 }
948 
949 /// Generic_GCC - A tool chain using the 'gcc' command to perform
950 /// all subcommands; this relies on gcc translating the majority of
951 /// command line options.
952 
Generic_GCC(const HostInfo & Host,const llvm::Triple & Triple)953 Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple)
954   : ToolChain(Host, Triple) {
955   getProgramPaths().push_back(getDriver().getInstalledDir());
956   if (getDriver().getInstalledDir() != getDriver().Dir)
957     getProgramPaths().push_back(getDriver().Dir);
958 }
959 
~Generic_GCC()960 Generic_GCC::~Generic_GCC() {
961   // Free tool implementations.
962   for (llvm::DenseMap<unsigned, Tool*>::iterator
963          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
964     delete it->second;
965 }
966 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const967 Tool &Generic_GCC::SelectTool(const Compilation &C,
968                               const JobAction &JA,
969                               const ActionList &Inputs) const {
970   Action::ActionClass Key;
971   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
972     Key = Action::AnalyzeJobClass;
973   else
974     Key = JA.getKind();
975 
976   Tool *&T = Tools[Key];
977   if (!T) {
978     switch (Key) {
979     case Action::InputClass:
980     case Action::BindArchClass:
981       assert(0 && "Invalid tool kind.");
982     case Action::PreprocessJobClass:
983       T = new tools::gcc::Preprocess(*this); break;
984     case Action::PrecompileJobClass:
985       T = new tools::gcc::Precompile(*this); break;
986     case Action::AnalyzeJobClass:
987       T = new tools::Clang(*this); break;
988     case Action::CompileJobClass:
989       T = new tools::gcc::Compile(*this); break;
990     case Action::AssembleJobClass:
991       T = new tools::gcc::Assemble(*this); break;
992     case Action::LinkJobClass:
993       T = new tools::gcc::Link(*this); break;
994 
995       // This is a bit ungeneric, but the only platform using a driver
996       // driver is Darwin.
997     case Action::LipoJobClass:
998       T = new tools::darwin::Lipo(*this); break;
999     case Action::DsymutilJobClass:
1000       T = new tools::darwin::Dsymutil(*this); break;
1001     }
1002   }
1003 
1004   return *T;
1005 }
1006 
IsUnwindTablesDefault() const1007 bool Generic_GCC::IsUnwindTablesDefault() const {
1008   // FIXME: Gross; we should probably have some separate target
1009   // definition, possibly even reusing the one in clang.
1010   return getArchName() == "x86_64";
1011 }
1012 
GetDefaultRelocationModel() const1013 const char *Generic_GCC::GetDefaultRelocationModel() const {
1014   return "static";
1015 }
1016 
GetForcedPicModel() const1017 const char *Generic_GCC::GetForcedPicModel() const {
1018   return 0;
1019 }
1020 
1021 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1022 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1023 /// Currently does not support anything else but compilation.
1024 
TCEToolChain(const HostInfo & Host,const llvm::Triple & Triple)1025 TCEToolChain::TCEToolChain(const HostInfo &Host, const llvm::Triple& Triple)
1026   : ToolChain(Host, Triple) {
1027   // Path mangling to find libexec
1028   std::string Path(getDriver().Dir);
1029 
1030   Path += "/../libexec";
1031   getProgramPaths().push_back(Path);
1032 }
1033 
~TCEToolChain()1034 TCEToolChain::~TCEToolChain() {
1035   for (llvm::DenseMap<unsigned, Tool*>::iterator
1036            it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1037       delete it->second;
1038 }
1039 
IsMathErrnoDefault() const1040 bool TCEToolChain::IsMathErrnoDefault() const {
1041   return true;
1042 }
1043 
IsUnwindTablesDefault() const1044 bool TCEToolChain::IsUnwindTablesDefault() const {
1045   return false;
1046 }
1047 
GetDefaultRelocationModel() const1048 const char *TCEToolChain::GetDefaultRelocationModel() const {
1049   return "static";
1050 }
1051 
GetForcedPicModel() const1052 const char *TCEToolChain::GetForcedPicModel() const {
1053   return 0;
1054 }
1055 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1056 Tool &TCEToolChain::SelectTool(const Compilation &C,
1057                             const JobAction &JA,
1058                                const ActionList &Inputs) const {
1059   Action::ActionClass Key;
1060   Key = Action::AnalyzeJobClass;
1061 
1062   Tool *&T = Tools[Key];
1063   if (!T) {
1064     switch (Key) {
1065     case Action::PreprocessJobClass:
1066       T = new tools::gcc::Preprocess(*this); break;
1067     case Action::AnalyzeJobClass:
1068       T = new tools::Clang(*this); break;
1069     default:
1070      assert(false && "Unsupported action for TCE target.");
1071     }
1072   }
1073   return *T;
1074 }
1075 
1076 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1077 
OpenBSD(const HostInfo & Host,const llvm::Triple & Triple)1078 OpenBSD::OpenBSD(const HostInfo &Host, const llvm::Triple& Triple)
1079   : Generic_ELF(Host, Triple) {
1080   getFilePaths().push_back(getDriver().Dir + "/../lib");
1081   getFilePaths().push_back("/usr/lib");
1082 }
1083 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1084 Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
1085                           const ActionList &Inputs) const {
1086   Action::ActionClass Key;
1087   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1088     Key = Action::AnalyzeJobClass;
1089   else
1090     Key = JA.getKind();
1091 
1092   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1093                                              options::OPT_no_integrated_as,
1094                                              IsIntegratedAssemblerDefault());
1095 
1096   Tool *&T = Tools[Key];
1097   if (!T) {
1098     switch (Key) {
1099     case Action::AssembleJobClass: {
1100       if (UseIntegratedAs)
1101         T = new tools::ClangAs(*this);
1102       else
1103         T = new tools::openbsd::Assemble(*this);
1104       break;
1105     }
1106     case Action::LinkJobClass:
1107       T = new tools::openbsd::Link(*this); break;
1108     default:
1109       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1110     }
1111   }
1112 
1113   return *T;
1114 }
1115 
1116 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1117 
FreeBSD(const HostInfo & Host,const llvm::Triple & Triple)1118 FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple)
1119   : Generic_ELF(Host, Triple) {
1120 
1121   // Determine if we are compiling 32-bit code on an x86_64 platform.
1122   bool Lib32 = false;
1123   if (Triple.getArch() == llvm::Triple::x86 &&
1124       llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
1125         llvm::Triple::x86_64)
1126     Lib32 = true;
1127 
1128   if (Triple.getArch() == llvm::Triple::ppc &&
1129       llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
1130         llvm::Triple::ppc64)
1131     Lib32 = true;
1132 
1133   if (Lib32) {
1134     getFilePaths().push_back("/usr/lib32");
1135   } else {
1136     getFilePaths().push_back("/usr/lib");
1137   }
1138 }
1139 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1140 Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1141                           const ActionList &Inputs) const {
1142   Action::ActionClass Key;
1143   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1144     Key = Action::AnalyzeJobClass;
1145   else
1146     Key = JA.getKind();
1147 
1148   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1149                                              options::OPT_no_integrated_as,
1150                                              IsIntegratedAssemblerDefault());
1151 
1152   Tool *&T = Tools[Key];
1153   if (!T) {
1154     switch (Key) {
1155     case Action::AssembleJobClass:
1156       if (UseIntegratedAs)
1157         T = new tools::ClangAs(*this);
1158       else
1159         T = new tools::freebsd::Assemble(*this);
1160       break;
1161     case Action::LinkJobClass:
1162       T = new tools::freebsd::Link(*this); break;
1163     default:
1164       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1165     }
1166   }
1167 
1168   return *T;
1169 }
1170 
1171 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1172 
NetBSD(const HostInfo & Host,const llvm::Triple & Triple,const llvm::Triple & ToolTriple)1173 NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple,
1174                const llvm::Triple& ToolTriple)
1175   : Generic_ELF(Host, Triple), ToolTriple(ToolTriple) {
1176 
1177   // Determine if we are compiling 32-bit code on an x86_64 platform.
1178   bool Lib32 = false;
1179   if (ToolTriple.getArch() == llvm::Triple::x86_64 &&
1180       Triple.getArch() == llvm::Triple::x86)
1181     Lib32 = true;
1182 
1183   if (getDriver().UseStdLib) {
1184     if (Lib32)
1185       getFilePaths().push_back("=/usr/lib/i386");
1186     else
1187       getFilePaths().push_back("=/usr/lib");
1188   }
1189 }
1190 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1191 Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1192                          const ActionList &Inputs) const {
1193   Action::ActionClass Key;
1194   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1195     Key = Action::AnalyzeJobClass;
1196   else
1197     Key = JA.getKind();
1198 
1199   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1200                                              options::OPT_no_integrated_as,
1201                                              IsIntegratedAssemblerDefault());
1202 
1203   Tool *&T = Tools[Key];
1204   if (!T) {
1205     switch (Key) {
1206     case Action::AssembleJobClass:
1207       if (UseIntegratedAs)
1208         T = new tools::ClangAs(*this);
1209       else
1210         T = new tools::netbsd::Assemble(*this, ToolTriple);
1211       break;
1212     case Action::LinkJobClass:
1213       T = new tools::netbsd::Link(*this, ToolTriple);
1214       break;
1215     default:
1216       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1217     }
1218   }
1219 
1220   return *T;
1221 }
1222 
1223 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1224 
Minix(const HostInfo & Host,const llvm::Triple & Triple)1225 Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple)
1226   : Generic_GCC(Host, Triple) {
1227   getFilePaths().push_back(getDriver().Dir + "/../lib");
1228   getFilePaths().push_back("/usr/lib");
1229   getFilePaths().push_back("/usr/gnu/lib");
1230   getFilePaths().push_back("/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
1231 }
1232 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1233 Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1234                         const ActionList &Inputs) const {
1235   Action::ActionClass Key;
1236   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1237     Key = Action::AnalyzeJobClass;
1238   else
1239     Key = JA.getKind();
1240 
1241   Tool *&T = Tools[Key];
1242   if (!T) {
1243     switch (Key) {
1244     case Action::AssembleJobClass:
1245       T = new tools::minix::Assemble(*this); break;
1246     case Action::LinkJobClass:
1247       T = new tools::minix::Link(*this); break;
1248     default:
1249       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1250     }
1251   }
1252 
1253   return *T;
1254 }
1255 
1256 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1257 
AuroraUX(const HostInfo & Host,const llvm::Triple & Triple)1258 AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple)
1259   : Generic_GCC(Host, Triple) {
1260 
1261   getProgramPaths().push_back(getDriver().getInstalledDir());
1262   if (getDriver().getInstalledDir() != getDriver().Dir)
1263     getProgramPaths().push_back(getDriver().Dir);
1264 
1265   getFilePaths().push_back(getDriver().Dir + "/../lib");
1266   getFilePaths().push_back("/usr/lib");
1267   getFilePaths().push_back("/usr/sfw/lib");
1268   getFilePaths().push_back("/opt/gcc4/lib");
1269   getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1270 
1271 }
1272 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1273 Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1274                            const ActionList &Inputs) const {
1275   Action::ActionClass Key;
1276   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1277     Key = Action::AnalyzeJobClass;
1278   else
1279     Key = JA.getKind();
1280 
1281   Tool *&T = Tools[Key];
1282   if (!T) {
1283     switch (Key) {
1284     case Action::AssembleJobClass:
1285       T = new tools::auroraux::Assemble(*this); break;
1286     case Action::LinkJobClass:
1287       T = new tools::auroraux::Link(*this); break;
1288     default:
1289       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1290     }
1291   }
1292 
1293   return *T;
1294 }
1295 
1296 
1297 /// Linux toolchain (very bare-bones at the moment).
1298 
1299 enum LinuxDistro {
1300   ArchLinux,
1301   DebianLenny,
1302   DebianSqueeze,
1303   DebianWheezy,
1304   Exherbo,
1305   RHEL4,
1306   RHEL5,
1307   RHEL6,
1308   Fedora13,
1309   Fedora14,
1310   Fedora15,
1311   FedoraRawhide,
1312   OpenSuse11_3,
1313   OpenSuse11_4,
1314   OpenSuse12_1,
1315   UbuntuHardy,
1316   UbuntuIntrepid,
1317   UbuntuJaunty,
1318   UbuntuKarmic,
1319   UbuntuLucid,
1320   UbuntuMaverick,
1321   UbuntuNatty,
1322   UbuntuOneiric,
1323   UnknownDistro
1324 };
1325 
IsRedhat(enum LinuxDistro Distro)1326 static bool IsRedhat(enum LinuxDistro Distro) {
1327   return Distro == Fedora13 || Distro == Fedora14 ||
1328          Distro == Fedora15 || Distro == FedoraRawhide ||
1329          Distro == RHEL4 || Distro == RHEL5 || Distro == RHEL6;
1330 }
1331 
IsOpenSuse(enum LinuxDistro Distro)1332 static bool IsOpenSuse(enum LinuxDistro Distro) {
1333   return Distro == OpenSuse11_3 || Distro == OpenSuse11_4 ||
1334          Distro == OpenSuse12_1;
1335 }
1336 
IsDebian(enum LinuxDistro Distro)1337 static bool IsDebian(enum LinuxDistro Distro) {
1338   return Distro == DebianLenny || Distro == DebianSqueeze ||
1339          Distro == DebianWheezy;
1340 }
1341 
IsUbuntu(enum LinuxDistro Distro)1342 static bool IsUbuntu(enum LinuxDistro Distro) {
1343   return Distro == UbuntuHardy  || Distro == UbuntuIntrepid ||
1344          Distro == UbuntuLucid  || Distro == UbuntuMaverick ||
1345          Distro == UbuntuJaunty || Distro == UbuntuKarmic ||
1346          Distro == UbuntuNatty  || Distro == UbuntuOneiric;
1347 }
1348 
IsDebianBased(enum LinuxDistro Distro)1349 static bool IsDebianBased(enum LinuxDistro Distro) {
1350   return IsDebian(Distro) || IsUbuntu(Distro);
1351 }
1352 
HasMultilib(llvm::Triple::ArchType Arch,enum LinuxDistro Distro)1353 static bool HasMultilib(llvm::Triple::ArchType Arch, enum LinuxDistro Distro) {
1354   if (Arch == llvm::Triple::x86_64) {
1355     bool Exists;
1356     if (Distro == Exherbo &&
1357         (llvm::sys::fs::exists("/usr/lib32/libc.so", Exists) || !Exists))
1358       return false;
1359 
1360     return true;
1361   }
1362   if (Arch == llvm::Triple::ppc64)
1363     return true;
1364   if ((Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc) &&
1365       IsDebianBased(Distro))
1366     return true;
1367   return false;
1368 }
1369 
DetectLinuxDistro(llvm::Triple::ArchType Arch)1370 static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1371   llvm::OwningPtr<llvm::MemoryBuffer> File;
1372   if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1373     llvm::StringRef Data = File.get()->getBuffer();
1374     llvm::SmallVector<llvm::StringRef, 8> Lines;
1375     Data.split(Lines, "\n");
1376     for (unsigned int i = 0, s = Lines.size(); i < s; ++ i) {
1377       if (Lines[i] == "DISTRIB_CODENAME=hardy")
1378         return UbuntuHardy;
1379       else if (Lines[i] == "DISTRIB_CODENAME=intrepid")
1380         return UbuntuIntrepid;
1381       else if (Lines[i] == "DISTRIB_CODENAME=jaunty")
1382         return UbuntuJaunty;
1383       else if (Lines[i] == "DISTRIB_CODENAME=karmic")
1384         return UbuntuKarmic;
1385       else if (Lines[i] == "DISTRIB_CODENAME=lucid")
1386         return UbuntuLucid;
1387       else if (Lines[i] == "DISTRIB_CODENAME=maverick")
1388         return UbuntuMaverick;
1389       else if (Lines[i] == "DISTRIB_CODENAME=natty")
1390         return UbuntuNatty;
1391       else if (Lines[i] == "DISTRIB_CODENAME=oneiric")
1392         return UbuntuOneiric;
1393     }
1394     return UnknownDistro;
1395   }
1396 
1397   if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1398     llvm::StringRef Data = File.get()->getBuffer();
1399     if (Data.startswith("Fedora release 15"))
1400       return Fedora15;
1401     else if (Data.startswith("Fedora release 14"))
1402       return Fedora14;
1403     else if (Data.startswith("Fedora release 13"))
1404       return Fedora13;
1405     else if (Data.startswith("Fedora release") &&
1406              Data.find("Rawhide") != llvm::StringRef::npos)
1407       return FedoraRawhide;
1408     else if (Data.startswith("Red Hat Enterprise Linux") &&
1409              Data.find("release 6") != llvm::StringRef::npos)
1410       return RHEL6;
1411     else if ((Data.startswith("Red Hat Enterprise Linux") ||
1412 	      Data.startswith("CentOS")) &&
1413              Data.find("release 5") != llvm::StringRef::npos)
1414       return RHEL5;
1415     else if ((Data.startswith("Red Hat Enterprise Linux") ||
1416 	      Data.startswith("CentOS")) &&
1417              Data.find("release 4") != llvm::StringRef::npos)
1418       return RHEL4;
1419     return UnknownDistro;
1420   }
1421 
1422   if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1423     llvm::StringRef Data = File.get()->getBuffer();
1424     if (Data[0] == '5')
1425       return DebianLenny;
1426     else if (Data.startswith("squeeze/sid"))
1427       return DebianSqueeze;
1428     else if (Data.startswith("wheezy/sid"))
1429       return DebianWheezy;
1430     return UnknownDistro;
1431   }
1432 
1433   if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) {
1434     llvm::StringRef Data = File.get()->getBuffer();
1435     if (Data.startswith("openSUSE 11.3"))
1436       return OpenSuse11_3;
1437     else if (Data.startswith("openSUSE 11.4"))
1438       return OpenSuse11_4;
1439     else if (Data.startswith("openSUSE 12.1"))
1440       return OpenSuse12_1;
1441     return UnknownDistro;
1442   }
1443 
1444   bool Exists;
1445   if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1446     return Exherbo;
1447 
1448   if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1449     return ArchLinux;
1450 
1451   return UnknownDistro;
1452 }
1453 
findGCCBaseLibDir(const std::string & GccTriple)1454 static std::string findGCCBaseLibDir(const std::string &GccTriple) {
1455   // FIXME: Using CXX_INCLUDE_ROOT is here is a bit of a hack, but
1456   // avoids adding yet another option to configure/cmake.
1457   // It would probably be cleaner to break it in two variables
1458   // CXX_GCC_ROOT with just /foo/bar
1459   // CXX_GCC_VER with 4.5.2
1460   // Then we would have
1461   // CXX_INCLUDE_ROOT = CXX_GCC_ROOT/include/c++/CXX_GCC_VER
1462   // and this function would return
1463   // CXX_GCC_ROOT/lib/gcc/CXX_INCLUDE_ARCH/CXX_GCC_VER
1464   llvm::SmallString<128> CxxIncludeRoot(CXX_INCLUDE_ROOT);
1465   if (CxxIncludeRoot != "") {
1466     // This is of the form /foo/bar/include/c++/4.5.2/
1467     if (CxxIncludeRoot.back() == '/')
1468       llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the /
1469     llvm::StringRef Version = llvm::sys::path::filename(CxxIncludeRoot);
1470     llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the version
1471     llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the c++
1472     llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the include
1473     std::string ret(CxxIncludeRoot.c_str());
1474     ret.append("/lib/gcc/");
1475     ret.append(CXX_INCLUDE_ARCH);
1476     ret.append("/");
1477     ret.append(Version);
1478     return ret;
1479   }
1480   static const char* GccVersions[] = {"4.6.1", "4.6.0", "4.6",
1481                                       "4.5.2", "4.5.1", "4.5",
1482                                       "4.4.5", "4.4.4", "4.4.3", "4.4",
1483                                       "4.3.4", "4.3.3", "4.3.2", "4.3",
1484                                       "4.2.4", "4.2.3", "4.2.2", "4.2.1",
1485                                       "4.2", "4.1.1"};
1486   bool Exists;
1487   for (unsigned i = 0; i < sizeof(GccVersions)/sizeof(char*); ++i) {
1488     std::string Suffix = GccTriple + "/" + GccVersions[i];
1489     std::string t1 = "/usr/lib/gcc/" + Suffix;
1490     if (!llvm::sys::fs::exists(t1 + "/crtbegin.o", Exists) && Exists)
1491       return t1;
1492     std::string t2 = "/usr/lib64/gcc/" + Suffix;
1493     if (!llvm::sys::fs::exists(t2 + "/crtbegin.o", Exists) && Exists)
1494       return t2;
1495     std::string t3 = "/usr/lib/" + GccTriple + "/gcc/" + Suffix;
1496     if (!llvm::sys::fs::exists(t3 + "/crtbegin.o", Exists) && Exists)
1497       return t3;
1498   }
1499   return "";
1500 }
1501 
Linux(const HostInfo & Host,const llvm::Triple & Triple)1502 Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple)
1503   : Generic_ELF(Host, Triple) {
1504   llvm::Triple::ArchType Arch =
1505     llvm::Triple(getDriver().DefaultHostTriple).getArch();
1506 
1507   std::string Suffix32  = "";
1508   if (Arch == llvm::Triple::x86_64)
1509     Suffix32 = "/32";
1510 
1511   std::string Suffix64  = "";
1512   if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
1513     Suffix64 = "/64";
1514 
1515   std::string Lib32 = "lib";
1516 
1517   bool Exists;
1518   if (!llvm::sys::fs::exists("/lib32", Exists) && Exists)
1519     Lib32 = "lib32";
1520 
1521   std::string Lib64 = "lib";
1522   bool Symlink;
1523   if (!llvm::sys::fs::exists("/lib64", Exists) && Exists &&
1524       (llvm::sys::fs::is_symlink("/lib64", Symlink) || !Symlink))
1525     Lib64 = "lib64";
1526 
1527   std::string GccTriple = "";
1528   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
1529     if (!llvm::sys::fs::exists("/usr/lib/gcc/arm-linux-gnueabi", Exists) &&
1530         Exists)
1531       GccTriple = "arm-linux-gnueabi";
1532   } else if (Arch == llvm::Triple::x86_64) {
1533     if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-linux-gnu", Exists) &&
1534         Exists)
1535       GccTriple = "x86_64-linux-gnu";
1536     else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-unknown-linux-gnu",
1537              Exists) && Exists)
1538       GccTriple = "x86_64-unknown-linux-gnu";
1539     else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-pc-linux-gnu",
1540              Exists) && Exists)
1541       GccTriple = "x86_64-pc-linux-gnu";
1542     else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-redhat-linux6E",
1543              Exists) && Exists)
1544       GccTriple = "x86_64-redhat-linux6E";
1545     else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-redhat-linux",
1546              Exists) && Exists)
1547       GccTriple = "x86_64-redhat-linux";
1548     else if (!llvm::sys::fs::exists("/usr/lib64/gcc/x86_64-suse-linux",
1549              Exists) && Exists)
1550       GccTriple = "x86_64-suse-linux";
1551     else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-manbo-linux-gnu",
1552              Exists) && Exists)
1553       GccTriple = "x86_64-manbo-linux-gnu";
1554     else if (!llvm::sys::fs::exists("/usr/lib/x86_64-linux-gnu/gcc",
1555              Exists) && Exists)
1556       GccTriple = "x86_64-linux-gnu";
1557   } else if (Arch == llvm::Triple::x86) {
1558     if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-linux-gnu", Exists) && Exists)
1559       GccTriple = "i686-linux-gnu";
1560     else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-pc-linux-gnu", Exists) &&
1561              Exists)
1562       GccTriple = "i686-pc-linux-gnu";
1563     else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-linux-gnu", Exists) &&
1564              Exists)
1565       GccTriple = "i486-linux-gnu";
1566     else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-redhat-linux", Exists) &&
1567              Exists)
1568       GccTriple = "i686-redhat-linux";
1569     else if (!llvm::sys::fs::exists("/usr/lib/gcc/i586-suse-linux", Exists) &&
1570              Exists)
1571       GccTriple = "i586-suse-linux";
1572     else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-slackware-linux", Exists)
1573             && Exists)
1574       GccTriple = "i486-slackware-linux";
1575   } else if (Arch == llvm::Triple::ppc) {
1576     if (!llvm::sys::fs::exists("/usr/lib/powerpc-linux-gnu", Exists) && Exists)
1577       GccTriple = "powerpc-linux-gnu";
1578     else if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc-unknown-linux-gnu",
1579                                     Exists) && Exists)
1580       GccTriple = "powerpc-unknown-linux-gnu";
1581   } else if (Arch == llvm::Triple::ppc64) {
1582     if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc64-unknown-linux-gnu",
1583                                Exists) && Exists)
1584       GccTriple = "powerpc64-unknown-linux-gnu";
1585     else if (!llvm::sys::fs::exists("/usr/lib64/gcc/"
1586                                     "powerpc64-unknown-linux-gnu", Exists) &&
1587              Exists)
1588       GccTriple = "powerpc64-unknown-linux-gnu";
1589   }
1590 
1591   std::string Base = findGCCBaseLibDir(GccTriple);
1592   path_list &Paths = getFilePaths();
1593   bool Is32Bits = (getArch() == llvm::Triple::x86 ||
1594                    getArch() == llvm::Triple::ppc);
1595 
1596   std::string Suffix;
1597   std::string Lib;
1598 
1599   if (Is32Bits) {
1600     Suffix = Suffix32;
1601     Lib = Lib32;
1602   } else {
1603     Suffix = Suffix64;
1604     Lib = Lib64;
1605   }
1606 
1607   llvm::sys::Path LinkerPath(Base + "/../../../../" + GccTriple + "/bin/ld");
1608   if (!llvm::sys::fs::exists(LinkerPath.str(), Exists) && Exists)
1609     Linker = LinkerPath.str();
1610   else
1611     Linker = GetProgramPath("ld");
1612 
1613   LinuxDistro Distro = DetectLinuxDistro(Arch);
1614 
1615   if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
1616     ExtraOpts.push_back("-z");
1617     ExtraOpts.push_back("relro");
1618   }
1619 
1620   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
1621     ExtraOpts.push_back("-X");
1622 
1623   if (IsRedhat(Distro) || IsOpenSuse(Distro) || Distro == UbuntuMaverick ||
1624       Distro == UbuntuNatty || Distro == UbuntuOneiric)
1625     ExtraOpts.push_back("--hash-style=gnu");
1626 
1627   if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
1628       Distro == UbuntuJaunty || Distro == UbuntuKarmic)
1629     ExtraOpts.push_back("--hash-style=both");
1630 
1631   if (IsRedhat(Distro))
1632     ExtraOpts.push_back("--no-add-needed");
1633 
1634   if (Distro == DebianSqueeze || Distro == DebianWheezy ||
1635       IsOpenSuse(Distro) ||
1636       (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
1637       Distro == UbuntuLucid ||
1638       Distro == UbuntuMaverick || Distro == UbuntuKarmic ||
1639       Distro == UbuntuNatty || Distro == UbuntuOneiric)
1640     ExtraOpts.push_back("--build-id");
1641 
1642   if (IsOpenSuse(Distro))
1643     ExtraOpts.push_back("--enable-new-dtags");
1644 
1645   if (Distro == ArchLinux)
1646     Lib = "lib";
1647 
1648   Paths.push_back(Base + Suffix);
1649   if (HasMultilib(Arch, Distro)) {
1650     if (IsOpenSuse(Distro) && Is32Bits)
1651       Paths.push_back(Base + "/../../../../" + GccTriple + "/lib/../lib");
1652     Paths.push_back(Base + "/../../../../" + Lib);
1653   }
1654 
1655   // FIXME: This is in here to find crt1.o. It is provided by libc, and
1656   // libc (like gcc), can be installed in any directory. Once we are
1657   // fetching this from a config file, we should have a libc prefix.
1658   Paths.push_back("/lib/../" + Lib);
1659   Paths.push_back("/usr/lib/../" + Lib);
1660 
1661   if (!Suffix.empty())
1662     Paths.push_back(Base);
1663   if (IsOpenSuse(Distro))
1664     Paths.push_back(Base + "/../../../../" + GccTriple + "/lib");
1665   Paths.push_back(Base + "/../../..");
1666   if (Arch == getArch() && IsUbuntu(Distro))
1667     Paths.push_back("/usr/lib/" + GccTriple);
1668 }
1669 
HasNativeLLVMSupport() const1670 bool Linux::HasNativeLLVMSupport() const {
1671   return true;
1672 }
1673 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1674 Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
1675                         const ActionList &Inputs) const {
1676   Action::ActionClass Key;
1677   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1678     Key = Action::AnalyzeJobClass;
1679   else
1680     Key = JA.getKind();
1681 
1682   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1683                                              options::OPT_no_integrated_as,
1684                                              IsIntegratedAssemblerDefault());
1685 
1686   Tool *&T = Tools[Key];
1687   if (!T) {
1688     switch (Key) {
1689     case Action::AssembleJobClass:
1690       if (UseIntegratedAs)
1691         T = new tools::ClangAs(*this);
1692       else
1693         T = new tools::linuxtools::Assemble(*this);
1694       break;
1695     case Action::LinkJobClass:
1696       T = new tools::linuxtools::Link(*this); break;
1697     default:
1698       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1699     }
1700   }
1701 
1702   return *T;
1703 }
1704 
1705 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
1706 
DragonFly(const HostInfo & Host,const llvm::Triple & Triple)1707 DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple)
1708   : Generic_ELF(Host, Triple) {
1709 
1710   // Path mangling to find libexec
1711   getProgramPaths().push_back(getDriver().getInstalledDir());
1712   if (getDriver().getInstalledDir() != getDriver().Dir)
1713     getProgramPaths().push_back(getDriver().Dir);
1714 
1715   getFilePaths().push_back(getDriver().Dir + "/../lib");
1716   getFilePaths().push_back("/usr/lib");
1717   getFilePaths().push_back("/usr/lib/gcc41");
1718 }
1719 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1720 Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
1721                             const ActionList &Inputs) const {
1722   Action::ActionClass Key;
1723   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1724     Key = Action::AnalyzeJobClass;
1725   else
1726     Key = JA.getKind();
1727 
1728   Tool *&T = Tools[Key];
1729   if (!T) {
1730     switch (Key) {
1731     case Action::AssembleJobClass:
1732       T = new tools::dragonfly::Assemble(*this); break;
1733     case Action::LinkJobClass:
1734       T = new tools::dragonfly::Link(*this); break;
1735     default:
1736       T = &Generic_GCC::SelectTool(C, JA, Inputs);
1737     }
1738   }
1739 
1740   return *T;
1741 }
1742 
Windows(const HostInfo & Host,const llvm::Triple & Triple)1743 Windows::Windows(const HostInfo &Host, const llvm::Triple& Triple)
1744   : ToolChain(Host, Triple) {
1745 }
1746 
SelectTool(const Compilation & C,const JobAction & JA,const ActionList & Inputs) const1747 Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA,
1748                           const ActionList &Inputs) const {
1749   Action::ActionClass Key;
1750   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1751     Key = Action::AnalyzeJobClass;
1752   else
1753     Key = JA.getKind();
1754 
1755   Tool *&T = Tools[Key];
1756   if (!T) {
1757     switch (Key) {
1758     case Action::InputClass:
1759     case Action::BindArchClass:
1760     case Action::LipoJobClass:
1761     case Action::DsymutilJobClass:
1762       assert(0 && "Invalid tool kind.");
1763     case Action::PreprocessJobClass:
1764     case Action::PrecompileJobClass:
1765     case Action::AnalyzeJobClass:
1766     case Action::CompileJobClass:
1767       T = new tools::Clang(*this); break;
1768     case Action::AssembleJobClass:
1769       T = new tools::ClangAs(*this); break;
1770     case Action::LinkJobClass:
1771       T = new tools::visualstudio::Link(*this); break;
1772     }
1773   }
1774 
1775   return *T;
1776 }
1777 
IsIntegratedAssemblerDefault() const1778 bool Windows::IsIntegratedAssemblerDefault() const {
1779   return true;
1780 }
1781 
IsUnwindTablesDefault() const1782 bool Windows::IsUnwindTablesDefault() const {
1783   // FIXME: Gross; we should probably have some separate target
1784   // definition, possibly even reusing the one in clang.
1785   return getArchName() == "x86_64";
1786 }
1787 
GetDefaultRelocationModel() const1788 const char *Windows::GetDefaultRelocationModel() const {
1789   return "static";
1790 }
1791 
GetForcedPicModel() const1792 const char *Windows::GetForcedPicModel() const {
1793   if (getArchName() == "x86_64")
1794     return "pic";
1795   return 0;
1796 }
1797