• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Tools.cpp - Tools 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 "Tools.h"
11 
12 #include "clang/Driver/Action.h"
13 #include "clang/Driver/Arg.h"
14 #include "clang/Driver/ArgList.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/Job.h"
19 #include "clang/Driver/HostInfo.h"
20 #include "clang/Driver/ObjCRuntime.h"
21 #include "clang/Driver/Option.h"
22 #include "clang/Driver/Options.h"
23 #include "clang/Driver/ToolChain.h"
24 #include "clang/Driver/Util.h"
25 
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/Process.h"
34 #include "llvm/Support/ErrorHandling.h"
35 
36 #include "InputInfo.h"
37 #include "ToolChains.h"
38 
39 #ifdef __CYGWIN__
40 #include <cygwin/version.h>
41 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
42 #define IS_CYGWIN15 1
43 #endif
44 #endif
45 
46 using namespace clang::driver;
47 using namespace clang::driver::tools;
48 
49 /// FindTargetProgramPath - Return path of the target specific version of
50 /// ProgName.  If it doesn't exist, return path of ProgName itself.
FindTargetProgramPath(const ToolChain & TheToolChain,const std::string TripleString,const char * ProgName)51 static std::string FindTargetProgramPath(const ToolChain &TheToolChain,
52                                          const std::string TripleString,
53                                          const char *ProgName) {
54   std::string Executable(TripleString + "-" + ProgName);
55   std::string Path(TheToolChain.GetProgramPath(Executable.c_str()));
56   if (Path != Executable)
57     return Path;
58   return TheToolChain.GetProgramPath(ProgName);
59 }
60 
61 /// CheckPreprocessingOptions - Perform some validation of preprocessing
62 /// arguments that is shared with gcc.
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)63 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
64   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
65     if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP)
66       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
67         << A->getAsString(Args) << "-E";
68 }
69 
70 /// CheckCodeGenerationOptions - Perform some validation of code generation
71 /// arguments that is shared with gcc.
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)72 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
73   // In gcc, only ARM checks this, but it seems reasonable to check universally.
74   if (Args.hasArg(options::OPT_static))
75     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
76                                        options::OPT_mdynamic_no_pic))
77       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
78         << A->getAsString(Args) << "-static";
79 }
80 
81 // Quote target names for inclusion in GNU Make dependency files.
82 // Only the characters '$', '#', ' ', '\t' are quoted.
QuoteTarget(llvm::StringRef Target,llvm::SmallVectorImpl<char> & Res)83 static void QuoteTarget(llvm::StringRef Target,
84                         llvm::SmallVectorImpl<char> &Res) {
85   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
86     switch (Target[i]) {
87     case ' ':
88     case '\t':
89       // Escape the preceding backslashes
90       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
91         Res.push_back('\\');
92 
93       // Escape the space/tab
94       Res.push_back('\\');
95       break;
96     case '$':
97       Res.push_back('$');
98       break;
99     case '#':
100       Res.push_back('\\');
101       break;
102     default:
103       break;
104     }
105 
106     Res.push_back(Target[i]);
107   }
108 }
109 
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs)110 static void AddLinkerInputs(const ToolChain &TC,
111                             const InputInfoList &Inputs, const ArgList &Args,
112                             ArgStringList &CmdArgs) {
113   const Driver &D = TC.getDriver();
114 
115   // Add extra linker input arguments which are not treated as inputs
116   // (constructed via -Xarch_).
117   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
118 
119   for (InputInfoList::const_iterator
120          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
121     const InputInfo &II = *it;
122 
123     if (!TC.HasNativeLLVMSupport()) {
124       // Don't try to pass LLVM inputs unless we have native support.
125       if (II.getType() == types::TY_LLVM_IR ||
126           II.getType() == types::TY_LTO_IR ||
127           II.getType() == types::TY_LLVM_BC ||
128           II.getType() == types::TY_LTO_BC)
129         D.Diag(clang::diag::err_drv_no_linker_llvm_support)
130           << TC.getTripleString();
131     }
132 
133     // Add filenames immediately.
134     if (II.isFilename()) {
135       CmdArgs.push_back(II.getFilename());
136       continue;
137     }
138 
139     // Otherwise, this is a linker input argument.
140     const Arg &A = II.getInputArg();
141 
142     // Handle reserved library options.
143     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
144       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
145     } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
146       TC.AddCCKextLibArgs(Args, CmdArgs);
147     } else
148       A.renderAsInput(Args, CmdArgs);
149   }
150 }
151 
152 /// \brief Determine whether Objective-C automated reference counting is
153 /// enabled.
isObjCAutoRefCount(const ArgList & Args)154 static bool isObjCAutoRefCount(const ArgList &Args) {
155   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
156 }
157 
addProfileRT(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,llvm::Triple Triple)158 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
159                          ArgStringList &CmdArgs,
160                          llvm::Triple Triple) {
161   if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
162         Args.hasArg(options::OPT_fprofile_generate) ||
163         Args.hasArg(options::OPT_fcreate_profile) ||
164         Args.hasArg(options::OPT_coverage)))
165     return;
166 
167   // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lgcov to
168   // the link line. We cannot do the same thing because unlike gcov there is a
169   // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but that is
170   // not supported by old linkers.
171   llvm::Twine ProfileRT =
172     llvm::Twine(TC.getDriver().Dir) + "/../lib/" + "libprofile_rt.a";
173 
174   if (Triple.getOS() == llvm::Triple::Darwin) {
175     // On Darwin, if the static library doesn't exist try the dylib.
176     bool Exists;
177     if (llvm::sys::fs::exists(ProfileRT.str(), Exists) || !Exists)
178       ProfileRT =
179         llvm::Twine(TC.getDriver().Dir) + "/../lib/" + "libprofile_rt.dylib";
180   }
181 
182   CmdArgs.push_back(Args.MakeArgString(ProfileRT));
183 }
184 
AddPreprocessingOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs) const185 void Clang::AddPreprocessingOptions(const Driver &D,
186                                     const ArgList &Args,
187                                     ArgStringList &CmdArgs,
188                                     const InputInfo &Output,
189                                     const InputInfoList &Inputs) const {
190   Arg *A;
191 
192   CheckPreprocessingOptions(D, Args);
193 
194   Args.AddLastArg(CmdArgs, options::OPT_C);
195   Args.AddLastArg(CmdArgs, options::OPT_CC);
196 
197   // Handle dependency file generation.
198   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
199       (A = Args.getLastArg(options::OPT_MD)) ||
200       (A = Args.getLastArg(options::OPT_MMD))) {
201     // Determine the output location.
202     const char *DepFile;
203     if (Output.getType() == types::TY_Dependencies) {
204       DepFile = Output.getFilename();
205     } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
206       DepFile = MF->getValue(Args);
207     } else if (A->getOption().matches(options::OPT_M) ||
208                A->getOption().matches(options::OPT_MM)) {
209       DepFile = "-";
210     } else {
211       DepFile = darwin::CC1::getDependencyFileName(Args, Inputs);
212     }
213     CmdArgs.push_back("-dependency-file");
214     CmdArgs.push_back(DepFile);
215 
216     // Add a default target if one wasn't specified.
217     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
218       const char *DepTarget;
219 
220       // If user provided -o, that is the dependency target, except
221       // when we are only generating a dependency file.
222       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
223       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
224         DepTarget = OutputOpt->getValue(Args);
225       } else {
226         // Otherwise derive from the base input.
227         //
228         // FIXME: This should use the computed output file location.
229         llvm::SmallString<128> P(Inputs[0].getBaseInput());
230         llvm::sys::path::replace_extension(P, "o");
231         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
232       }
233 
234       CmdArgs.push_back("-MT");
235       llvm::SmallString<128> Quoted;
236       QuoteTarget(DepTarget, Quoted);
237       CmdArgs.push_back(Args.MakeArgString(Quoted));
238     }
239 
240     if (A->getOption().matches(options::OPT_M) ||
241         A->getOption().matches(options::OPT_MD))
242       CmdArgs.push_back("-sys-header-deps");
243   }
244 
245   if (Args.hasArg(options::OPT_MG)) {
246     if (!A || A->getOption().matches(options::OPT_MD) ||
247               A->getOption().matches(options::OPT_MMD))
248       D.Diag(clang::diag::err_drv_mg_requires_m_or_mm);
249     CmdArgs.push_back("-MG");
250   }
251 
252   Args.AddLastArg(CmdArgs, options::OPT_MP);
253 
254   // Convert all -MQ <target> args to -MT <quoted target>
255   for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
256                                              options::OPT_MQ),
257          ie = Args.filtered_end(); it != ie; ++it) {
258     const Arg *A = *it;
259     A->claim();
260 
261     if (A->getOption().matches(options::OPT_MQ)) {
262       CmdArgs.push_back("-MT");
263       llvm::SmallString<128> Quoted;
264       QuoteTarget(A->getValue(Args), Quoted);
265       CmdArgs.push_back(Args.MakeArgString(Quoted));
266 
267     // -MT flag - no change
268     } else {
269       A->render(Args, CmdArgs);
270     }
271   }
272 
273   // Add -i* options, and automatically translate to
274   // -include-pch/-include-pth for transparent PCH support. It's
275   // wonky, but we include looking for .gch so we can support seamless
276   // replacement into a build system already set up to be generating
277   // .gch files.
278   bool RenderedImplicitInclude = false;
279   for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
280          ie = Args.filtered_end(); it != ie; ++it) {
281     const Arg *A = it;
282 
283     if (A->getOption().matches(options::OPT_include)) {
284       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
285       RenderedImplicitInclude = true;
286 
287       // Use PCH if the user requested it.
288       bool UsePCH = D.CCCUsePCH;
289 
290       bool FoundPTH = false;
291       bool FoundPCH = false;
292       llvm::sys::Path P(A->getValue(Args));
293       bool Exists;
294       if (UsePCH) {
295         P.appendSuffix("pch");
296         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
297           FoundPCH = true;
298         else
299           P.eraseSuffix();
300       }
301 
302       if (!FoundPCH) {
303         P.appendSuffix("pth");
304         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
305           FoundPTH = true;
306         else
307           P.eraseSuffix();
308       }
309 
310       if (!FoundPCH && !FoundPTH) {
311         P.appendSuffix("gch");
312         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
313           FoundPCH = UsePCH;
314           FoundPTH = !UsePCH;
315         }
316         else
317           P.eraseSuffix();
318       }
319 
320       if (FoundPCH || FoundPTH) {
321         if (IsFirstImplicitInclude) {
322           A->claim();
323           if (UsePCH)
324             CmdArgs.push_back("-include-pch");
325           else
326             CmdArgs.push_back("-include-pth");
327           CmdArgs.push_back(Args.MakeArgString(P.str()));
328           continue;
329         } else {
330           // Ignore the PCH if not first on command line and emit warning.
331           D.Diag(clang::diag::warn_drv_pch_not_first_include)
332               << P.str() << A->getAsString(Args);
333         }
334       }
335     }
336 
337     // Not translated, render as usual.
338     A->claim();
339     A->render(Args, CmdArgs);
340   }
341 
342   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
343   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
344 
345   // Add C++ include arguments, if needed.
346   types::ID InputType = Inputs[0].getType();
347   if (types::isCXX(InputType)) {
348     bool ObjCXXAutoRefCount
349       = types::isObjC(InputType) && isObjCAutoRefCount(Args);
350     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs,
351                                                 ObjCXXAutoRefCount);
352     Args.AddAllArgs(CmdArgs, options::OPT_stdlib_EQ);
353   }
354 
355   // Add -Wp, and -Xassembler if using the preprocessor.
356 
357   // FIXME: There is a very unfortunate problem here, some troubled
358   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
359   // really support that we would have to parse and then translate
360   // those options. :(
361   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
362                        options::OPT_Xpreprocessor);
363 
364   // -I- is a deprecated GCC feature, reject it.
365   if (Arg *A = Args.getLastArg(options::OPT_I_))
366     D.Diag(clang::diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
367 
368   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
369   // -isysroot to the CC1 invocation.
370   if (Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) {
371     if (!Args.hasArg(options::OPT_isysroot)) {
372       CmdArgs.push_back("-isysroot");
373       CmdArgs.push_back(A->getValue(Args));
374     }
375   }
376 }
377 
378 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
379 //
380 // FIXME: tblgen this.
getARMTargetCPU(const ArgList & Args,const llvm::Triple & Triple)381 static const char *getARMTargetCPU(const ArgList &Args,
382                                    const llvm::Triple &Triple) {
383   // FIXME: Warn on inconsistent use of -mcpu and -march.
384 
385   // If we have -mcpu=, use that.
386   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
387     return A->getValue(Args);
388 
389   llvm::StringRef MArch;
390   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
391     // Otherwise, if we have -march= choose the base CPU for that arch.
392     MArch = A->getValue(Args);
393   } else {
394     // Otherwise, use the Arch from the triple.
395     MArch = Triple.getArchName();
396   }
397 
398   if (MArch == "armv2" || MArch == "armv2a")
399     return "arm2";
400   if (MArch == "armv3")
401     return "arm6";
402   if (MArch == "armv3m")
403     return "arm7m";
404   if (MArch == "armv4" || MArch == "armv4t")
405     return "arm7tdmi";
406   if (MArch == "armv5" || MArch == "armv5t")
407     return "arm10tdmi";
408   if (MArch == "armv5e" || MArch == "armv5te")
409     return "arm1026ejs";
410   if (MArch == "armv5tej")
411     return "arm926ej-s";
412   if (MArch == "armv6" || MArch == "armv6k")
413     return "arm1136jf-s";
414   if (MArch == "armv6j")
415     return "arm1136j-s";
416   if (MArch == "armv6z" || MArch == "armv6zk")
417     return "arm1176jzf-s";
418   if (MArch == "armv6t2")
419     return "arm1156t2-s";
420   if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
421     return "cortex-a8";
422   if (MArch == "armv7r" || MArch == "armv7-r")
423     return "cortex-r4";
424   if (MArch == "armv7m" || MArch == "armv7-m")
425     return "cortex-m3";
426   if (MArch == "ep9312")
427     return "ep9312";
428   if (MArch == "iwmmxt")
429     return "iwmmxt";
430   if (MArch == "xscale")
431     return "xscale";
432   if (MArch == "armv6m" || MArch == "armv6-m")
433     return "cortex-m0";
434 
435   // If all else failed, return the most base CPU LLVM supports.
436   return "arm7tdmi";
437 }
438 
439 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
440 /// CPU.
441 //
442 // FIXME: This is redundant with -mcpu, why does LLVM use this.
443 // FIXME: tblgen this, or kill it!
getLLVMArchSuffixForARM(llvm::StringRef CPU)444 static const char *getLLVMArchSuffixForARM(llvm::StringRef CPU) {
445   if (CPU == "arm7tdmi" || CPU == "arm7tdmi-s" || CPU == "arm710t" ||
446       CPU == "arm720t" || CPU == "arm9" || CPU == "arm9tdmi" ||
447       CPU == "arm920" || CPU == "arm920t" || CPU == "arm922t" ||
448       CPU == "arm940t" || CPU == "ep9312")
449     return "v4t";
450 
451   if (CPU == "arm10tdmi" || CPU == "arm1020t")
452     return "v5";
453 
454   if (CPU == "arm9e" || CPU == "arm926ej-s" || CPU == "arm946e-s" ||
455       CPU == "arm966e-s" || CPU == "arm968e-s" || CPU == "arm10e" ||
456       CPU == "arm1020e" || CPU == "arm1022e" || CPU == "xscale" ||
457       CPU == "iwmmxt")
458     return "v5e";
459 
460   if (CPU == "arm1136j-s" || CPU == "arm1136jf-s" || CPU == "arm1176jz-s" ||
461       CPU == "arm1176jzf-s" || CPU == "mpcorenovfp" || CPU == "mpcore")
462     return "v6";
463 
464   if (CPU == "arm1156t2-s" || CPU == "arm1156t2f-s")
465     return "v6t2";
466 
467   if (CPU == "cortex-a8" || CPU == "cortex-a9")
468     return "v7";
469 
470   return "";
471 }
472 
473 // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)474 static bool isSignedCharDefault(const llvm::Triple &Triple) {
475   switch (Triple.getArch()) {
476   default:
477     return true;
478 
479   case llvm::Triple::arm:
480   case llvm::Triple::ppc:
481   case llvm::Triple::ppc64:
482     if (Triple.getOS() == llvm::Triple::Darwin)
483       return true;
484     return false;
485 
486   case llvm::Triple::systemz:
487     return false;
488   }
489 }
490 
AddARMTargetArgs(const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const491 void Clang::AddARMTargetArgs(const ArgList &Args,
492                              ArgStringList &CmdArgs,
493                              bool KernelOrKext) const {
494   const Driver &D = getToolChain().getDriver();
495   llvm::Triple Triple = getToolChain().getTriple();
496 
497   // Disable movt generation, if requested.
498 #ifdef DISABLE_ARM_DARWIN_USE_MOVT
499   CmdArgs.push_back("-backend-option");
500   CmdArgs.push_back("-arm-darwin-use-movt=0");
501 #endif
502 
503   // Select the ABI to use.
504   //
505   // FIXME: Support -meabi.
506   const char *ABIName = 0;
507   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
508     ABIName = A->getValue(Args);
509   } else {
510     // Select the default based on the platform.
511     switch(Triple.getEnvironment()) {
512     case llvm::Triple::GNUEABI:
513       ABIName = "aapcs-linux";
514       break;
515     case llvm::Triple::EABI:
516       ABIName = "aapcs";
517       break;
518     default:
519       ABIName = "apcs-gnu";
520     }
521   }
522   CmdArgs.push_back("-target-abi");
523   CmdArgs.push_back(ABIName);
524 
525   // Set the CPU based on -march= and -mcpu=.
526   CmdArgs.push_back("-target-cpu");
527   CmdArgs.push_back(getARMTargetCPU(Args, Triple));
528 
529   // Select the float ABI as determined by -msoft-float, -mhard-float, and
530   // -mfloat-abi=.
531   llvm::StringRef FloatABI;
532   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
533                                options::OPT_mhard_float,
534                                options::OPT_mfloat_abi_EQ)) {
535     if (A->getOption().matches(options::OPT_msoft_float))
536       FloatABI = "soft";
537     else if (A->getOption().matches(options::OPT_mhard_float))
538       FloatABI = "hard";
539     else {
540       FloatABI = A->getValue(Args);
541       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
542         D.Diag(clang::diag::err_drv_invalid_mfloat_abi)
543           << A->getAsString(Args);
544         FloatABI = "soft";
545       }
546     }
547   }
548 
549   // If unspecified, choose the default based on the platform.
550   if (FloatABI.empty()) {
551     const llvm::Triple &Triple = getToolChain().getTriple();
552     switch (Triple.getOS()) {
553     case llvm::Triple::Darwin: {
554       // Darwin defaults to "softfp" for v6 and v7.
555       //
556       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
557       llvm::StringRef ArchName =
558         getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
559       if (ArchName.startswith("v6") || ArchName.startswith("v7"))
560         FloatABI = "softfp";
561       else
562         FloatABI = "soft";
563       break;
564     }
565 
566     case llvm::Triple::Linux: {
567       if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUEABI) {
568         FloatABI = "softfp";
569         break;
570       }
571     }
572     // fall through
573 
574     default:
575       switch(Triple.getEnvironment()) {
576       case llvm::Triple::GNUEABI:
577         FloatABI = "softfp";
578         break;
579       case llvm::Triple::EABI:
580         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
581         FloatABI = "softfp";
582         break;
583       default:
584         // Assume "soft", but warn the user we are guessing.
585         FloatABI = "soft";
586         D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
587         break;
588       }
589     }
590   }
591 
592   if (FloatABI == "soft") {
593     // Floating point operations and argument passing are soft.
594     //
595     // FIXME: This changes CPP defines, we need -target-soft-float.
596     CmdArgs.push_back("-msoft-float");
597     CmdArgs.push_back("-mfloat-abi");
598     CmdArgs.push_back("soft");
599   } else if (FloatABI == "softfp") {
600     // Floating point operations are hard, but argument passing is soft.
601     CmdArgs.push_back("-mfloat-abi");
602     CmdArgs.push_back("soft");
603   } else {
604     // Floating point operations and argument passing are hard.
605     assert(FloatABI == "hard" && "Invalid float abi!");
606     CmdArgs.push_back("-mfloat-abi");
607     CmdArgs.push_back("hard");
608   }
609 
610   // Set appropriate target features for floating point mode.
611   //
612   // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
613   // yet (it uses the -mfloat-abi and -msoft-float options above), and it is
614   // stripped out by the ARM target.
615 
616   // Use software floating point operations?
617   if (FloatABI == "soft") {
618     CmdArgs.push_back("-target-feature");
619     CmdArgs.push_back("+soft-float");
620   }
621 
622   // Use software floating point argument passing?
623   if (FloatABI != "hard") {
624     CmdArgs.push_back("-target-feature");
625     CmdArgs.push_back("+soft-float-abi");
626   }
627 
628   // Honor -mfpu=.
629   //
630   // FIXME: Centralize feature selection, defaulting shouldn't be also in the
631   // frontend target.
632   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ)) {
633     llvm::StringRef FPU = A->getValue(Args);
634 
635     // Set the target features based on the FPU.
636     if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
637       // Disable any default FPU support.
638       CmdArgs.push_back("-target-feature");
639       CmdArgs.push_back("-vfp2");
640       CmdArgs.push_back("-target-feature");
641       CmdArgs.push_back("-vfp3");
642       CmdArgs.push_back("-target-feature");
643       CmdArgs.push_back("-neon");
644     } else if (FPU == "vfp") {
645       CmdArgs.push_back("-target-feature");
646       CmdArgs.push_back("+vfp2");
647     } else if (FPU == "vfp3") {
648       CmdArgs.push_back("-target-feature");
649       CmdArgs.push_back("+vfp3");
650     } else if (FPU == "neon") {
651       CmdArgs.push_back("-target-feature");
652       CmdArgs.push_back("+neon");
653     } else
654       D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
655   }
656 
657   // Setting -msoft-float effectively disables NEON because of the GCC
658   // implementation, although the same isn't true of VFP or VFP3.
659   if (FloatABI == "soft") {
660     CmdArgs.push_back("-target-feature");
661     CmdArgs.push_back("-neon");
662   }
663 
664   // Kernel code has more strict alignment requirements.
665   if (KernelOrKext) {
666     CmdArgs.push_back("-backend-option");
667     CmdArgs.push_back("-arm-long-calls");
668 
669     CmdArgs.push_back("-backend-option");
670     CmdArgs.push_back("-arm-strict-align");
671 
672     // The kext linker doesn't know how to deal with movw/movt.
673 #ifndef DISABLE_ARM_DARWIN_USE_MOVT
674     CmdArgs.push_back("-backend-option");
675     CmdArgs.push_back("-arm-darwin-use-movt=0");
676 #endif
677   }
678 }
679 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const680 void Clang::AddMIPSTargetArgs(const ArgList &Args,
681                              ArgStringList &CmdArgs) const {
682   const Driver &D = getToolChain().getDriver();
683 
684   // Select the ABI to use.
685   const char *ABIName = 0;
686   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
687     ABIName = A->getValue(Args);
688   } else {
689     ABIName = "o32";
690   }
691 
692   CmdArgs.push_back("-target-abi");
693   CmdArgs.push_back(ABIName);
694 
695   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
696     llvm::StringRef MArch = A->getValue(Args);
697     CmdArgs.push_back("-target-cpu");
698 
699     if ((MArch == "r2000") || (MArch == "r3000"))
700       CmdArgs.push_back("mips1");
701     else if (MArch == "r6000")
702       CmdArgs.push_back("mips2");
703     else
704       CmdArgs.push_back(Args.MakeArgString(MArch));
705   }
706 
707   // Select the float ABI as determined by -msoft-float, -mhard-float, and
708   llvm::StringRef FloatABI;
709   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
710                                options::OPT_mhard_float)) {
711     if (A->getOption().matches(options::OPT_msoft_float))
712       FloatABI = "soft";
713     else if (A->getOption().matches(options::OPT_mhard_float))
714       FloatABI = "hard";
715   }
716 
717   // If unspecified, choose the default based on the platform.
718   if (FloatABI.empty()) {
719     // Assume "soft", but warn the user we are guessing.
720     FloatABI = "soft";
721     D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
722   }
723 
724   if (FloatABI == "soft") {
725     // Floating point operations and argument passing are soft.
726     //
727     // FIXME: This changes CPP defines, we need -target-soft-float.
728     CmdArgs.push_back("-msoft-float");
729   } else {
730     assert(FloatABI == "hard" && "Invalid float abi!");
731     CmdArgs.push_back("-mhard-float");
732   }
733 }
734 
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const735 void Clang::AddSparcTargetArgs(const ArgList &Args,
736                              ArgStringList &CmdArgs) const {
737   const Driver &D = getToolChain().getDriver();
738 
739   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
740     llvm::StringRef MArch = A->getValue(Args);
741     CmdArgs.push_back("-target-cpu");
742     CmdArgs.push_back(MArch.str().c_str());
743   }
744 
745   // Select the float ABI as determined by -msoft-float, -mhard-float, and
746   llvm::StringRef FloatABI;
747   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
748                                options::OPT_mhard_float)) {
749     if (A->getOption().matches(options::OPT_msoft_float))
750       FloatABI = "soft";
751     else if (A->getOption().matches(options::OPT_mhard_float))
752       FloatABI = "hard";
753   }
754 
755   // If unspecified, choose the default based on the platform.
756   if (FloatABI.empty()) {
757     switch (getToolChain().getTriple().getOS()) {
758     default:
759       // Assume "soft", but warn the user we are guessing.
760       FloatABI = "soft";
761       D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
762       break;
763     }
764   }
765 
766   if (FloatABI == "soft") {
767     // Floating point operations and argument passing are soft.
768     //
769     // FIXME: This changes CPP defines, we need -target-soft-float.
770     CmdArgs.push_back("-msoft-float");
771     CmdArgs.push_back("-target-feature");
772     CmdArgs.push_back("+soft-float");
773   } else {
774     assert(FloatABI == "hard" && "Invalid float abi!");
775     CmdArgs.push_back("-mhard-float");
776   }
777 }
778 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const779 void Clang::AddX86TargetArgs(const ArgList &Args,
780                              ArgStringList &CmdArgs) const {
781   if (!Args.hasFlag(options::OPT_mred_zone,
782                     options::OPT_mno_red_zone,
783                     true) ||
784       Args.hasArg(options::OPT_mkernel) ||
785       Args.hasArg(options::OPT_fapple_kext))
786     CmdArgs.push_back("-disable-red-zone");
787 
788   if (Args.hasFlag(options::OPT_msoft_float,
789                    options::OPT_mno_soft_float,
790                    false))
791     CmdArgs.push_back("-no-implicit-float");
792 
793   const char *CPUName = 0;
794   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
795     if (llvm::StringRef(A->getValue(Args)) == "native") {
796       // FIXME: Reject attempts to use -march=native unless the target matches
797       // the host.
798       //
799       // FIXME: We should also incorporate the detected target features for use
800       // with -native.
801       std::string CPU = llvm::sys::getHostCPUName();
802       if (!CPU.empty())
803         CPUName = Args.MakeArgString(CPU);
804     } else
805       CPUName = A->getValue(Args);
806   }
807 
808   // Select the default CPU if none was given (or detection failed).
809   if (!CPUName) {
810     // FIXME: Need target hooks.
811     if (getToolChain().getOS().startswith("darwin")) {
812       if (getToolChain().getArch() == llvm::Triple::x86_64)
813         CPUName = "core2";
814       else if (getToolChain().getArch() == llvm::Triple::x86)
815         CPUName = "yonah";
816     } else if (getToolChain().getOS().startswith("haiku"))  {
817       if (getToolChain().getArch() == llvm::Triple::x86_64)
818         CPUName = "x86-64";
819       else if (getToolChain().getArch() == llvm::Triple::x86)
820         CPUName = "i586";
821     } else if (getToolChain().getOS().startswith("openbsd"))  {
822       if (getToolChain().getArch() == llvm::Triple::x86_64)
823         CPUName = "x86-64";
824       else if (getToolChain().getArch() == llvm::Triple::x86)
825         CPUName = "i486";
826     } else if (getToolChain().getOS().startswith("freebsd"))  {
827       if (getToolChain().getArch() == llvm::Triple::x86_64)
828         CPUName = "x86-64";
829       else if (getToolChain().getArch() == llvm::Triple::x86)
830         CPUName = "i486";
831     } else if (getToolChain().getOS().startswith("netbsd"))  {
832       if (getToolChain().getArch() == llvm::Triple::x86_64)
833         CPUName = "x86-64";
834       else if (getToolChain().getArch() == llvm::Triple::x86)
835         CPUName = "i486";
836     } else {
837       if (getToolChain().getArch() == llvm::Triple::x86_64)
838         CPUName = "x86-64";
839       else if (getToolChain().getArch() == llvm::Triple::x86)
840         CPUName = "pentium4";
841     }
842   }
843 
844   if (CPUName) {
845     CmdArgs.push_back("-target-cpu");
846     CmdArgs.push_back(CPUName);
847   }
848 
849   // The required algorithm here is slightly strange: the options are applied
850   // in order (so -mno-sse -msse2 disables SSE3), but any option that gets
851   // directly overridden later is ignored (so "-mno-sse -msse2 -mno-sse2 -msse"
852   // is equivalent to "-mno-sse2 -msse"). The -cc1 handling deals with the
853   // former correctly, but not the latter; handle directly-overridden
854   // attributes here.
855   llvm::StringMap<unsigned> PrevFeature;
856   std::vector<const char*> Features;
857   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
858          ie = Args.filtered_end(); it != ie; ++it) {
859     llvm::StringRef Name = (*it)->getOption().getName();
860     (*it)->claim();
861 
862     // Skip over "-m".
863     assert(Name.startswith("-m") && "Invalid feature name.");
864     Name = Name.substr(2);
865 
866     bool IsNegative = Name.startswith("no-");
867     if (IsNegative)
868       Name = Name.substr(3);
869 
870     unsigned& Prev = PrevFeature[Name];
871     if (Prev)
872       Features[Prev - 1] = 0;
873     Prev = Features.size() + 1;
874     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
875   }
876   for (unsigned i = 0; i < Features.size(); i++) {
877     if (Features[i]) {
878       CmdArgs.push_back("-target-feature");
879       CmdArgs.push_back(Features[i]);
880     }
881   }
882 }
883 
884 static bool
shouldUseExceptionTablesForObjCExceptions(unsigned objcABIVersion,const llvm::Triple & Triple)885 shouldUseExceptionTablesForObjCExceptions(unsigned objcABIVersion,
886                                           const llvm::Triple &Triple) {
887   // We use the zero-cost exception tables for Objective-C if the non-fragile
888   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
889   // later.
890 
891   if (objcABIVersion >= 2)
892     return true;
893 
894   if (Triple.getOS() != llvm::Triple::Darwin)
895     return false;
896 
897   return (!Triple.isMacOSXVersionLT(10,5) &&
898           (Triple.getArch() == llvm::Triple::x86_64 ||
899            Triple.getArch() == llvm::Triple::arm));
900 }
901 
902 /// addExceptionArgs - Adds exception related arguments to the driver command
903 /// arguments. There's a master flag, -fexceptions and also language specific
904 /// flags to enable/disable C++ and Objective-C exceptions.
905 /// This makes it possible to for example disable C++ exceptions but enable
906 /// Objective-C exceptions.
addExceptionArgs(const ArgList & Args,types::ID InputType,const llvm::Triple & Triple,bool KernelOrKext,bool IsRewriter,unsigned objcABIVersion,ArgStringList & CmdArgs)907 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
908                              const llvm::Triple &Triple,
909                              bool KernelOrKext, bool IsRewriter,
910                              unsigned objcABIVersion,
911                              ArgStringList &CmdArgs) {
912   if (KernelOrKext)
913     return;
914 
915   // Exceptions are enabled by default.
916   bool ExceptionsEnabled = true;
917 
918   // This keeps track of whether exceptions were explicitly turned on or off.
919   bool DidHaveExplicitExceptionFlag = false;
920 
921   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
922                                options::OPT_fno_exceptions)) {
923     if (A->getOption().matches(options::OPT_fexceptions))
924       ExceptionsEnabled = true;
925     else
926       ExceptionsEnabled = false;
927 
928     DidHaveExplicitExceptionFlag = true;
929   }
930 
931   bool ShouldUseExceptionTables = false;
932 
933   // Exception tables and cleanups can be enabled with -fexceptions even if the
934   // language itself doesn't support exceptions.
935   if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
936     ShouldUseExceptionTables = true;
937 
938   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
939   // is not necessarily sensible, but follows GCC.
940   if (types::isObjC(InputType) &&
941       Args.hasFlag(options::OPT_fobjc_exceptions,
942                    options::OPT_fno_objc_exceptions,
943                    true)) {
944     CmdArgs.push_back("-fobjc-exceptions");
945 
946     ShouldUseExceptionTables |=
947       shouldUseExceptionTablesForObjCExceptions(objcABIVersion, Triple);
948   }
949 
950   if (types::isCXX(InputType)) {
951     bool CXXExceptionsEnabled = ExceptionsEnabled;
952 
953     if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
954                                  options::OPT_fno_cxx_exceptions,
955                                  options::OPT_fexceptions,
956                                  options::OPT_fno_exceptions)) {
957       if (A->getOption().matches(options::OPT_fcxx_exceptions))
958         CXXExceptionsEnabled = true;
959       else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
960         CXXExceptionsEnabled = false;
961     }
962 
963     if (CXXExceptionsEnabled) {
964       CmdArgs.push_back("-fcxx-exceptions");
965 
966       ShouldUseExceptionTables = true;
967     }
968   }
969 
970   if (ShouldUseExceptionTables)
971     CmdArgs.push_back("-fexceptions");
972 }
973 
ShouldDisableCFI(const ArgList & Args,const ToolChain & TC)974 static bool ShouldDisableCFI(const ArgList &Args,
975                              const ToolChain &TC) {
976   if (TC.getTriple().getOS() == llvm::Triple::Darwin) {
977     // The native darwin assembler doesn't support cfi directives, so
978     // we disable them if we think the .s file will be passed to it.
979 
980     // FIXME: Duplicated code with ToolChains.cpp
981     // FIXME: This doesn't belong here, but ideally we will support static soon
982     // anyway.
983     bool HasStatic = (Args.hasArg(options::OPT_mkernel) ||
984                       Args.hasArg(options::OPT_static) ||
985                       Args.hasArg(options::OPT_fapple_kext));
986     bool IsIADefault = TC.IsIntegratedAssemblerDefault() && !HasStatic;
987     bool UseIntegratedAs = Args.hasFlag(options::OPT_integrated_as,
988                                         options::OPT_no_integrated_as,
989                                         IsIADefault);
990     bool UseCFI = Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
991                                options::OPT_fno_dwarf2_cfi_asm,
992                                UseIntegratedAs);
993     return !UseCFI;
994   }
995 
996   // For now we assume that every other assembler support CFI.
997   return false;
998 }
999 
1000 /// \brief Check whether the given input tree contains any compilation actions.
ContainsCompileAction(const Action * A)1001 static bool ContainsCompileAction(const Action *A) {
1002   if (llvm::isa<CompileJobAction>(A))
1003     return true;
1004 
1005   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
1006     if (ContainsCompileAction(*it))
1007       return true;
1008 
1009   return false;
1010 }
1011 
1012 /// \brief Check if -relax-all should be passed to the internal assembler.
1013 /// This is done by default when compiling non-assembler source with -O0.
UseRelaxAll(Compilation & C,const ArgList & Args)1014 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
1015   bool RelaxDefault = true;
1016 
1017   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1018     RelaxDefault = A->getOption().matches(options::OPT_O0);
1019 
1020   if (RelaxDefault) {
1021     RelaxDefault = false;
1022     for (ActionList::const_iterator it = C.getActions().begin(),
1023            ie = C.getActions().end(); it != ie; ++it) {
1024       if (ContainsCompileAction(*it)) {
1025         RelaxDefault = true;
1026         break;
1027       }
1028     }
1029   }
1030 
1031   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1032     RelaxDefault);
1033 }
1034 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const1035 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
1036                          const InputInfo &Output,
1037                          const InputInfoList &Inputs,
1038                          const ArgList &Args,
1039                          const char *LinkingOutput) const {
1040   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
1041                                   options::OPT_fapple_kext);
1042   const Driver &D = getToolChain().getDriver();
1043   ArgStringList CmdArgs;
1044 
1045   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
1046 
1047   // Invoke ourselves in -cc1 mode.
1048   //
1049   // FIXME: Implement custom jobs for internal actions.
1050   CmdArgs.push_back("-cc1");
1051 
1052   // Add the "effective" target triple.
1053   CmdArgs.push_back("-triple");
1054   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1055   CmdArgs.push_back(Args.MakeArgString(TripleStr));
1056 
1057   // Select the appropriate action.
1058   bool IsRewriter = false;
1059   if (isa<AnalyzeJobAction>(JA)) {
1060     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
1061     CmdArgs.push_back("-analyze");
1062   } else if (isa<PreprocessJobAction>(JA)) {
1063     if (Output.getType() == types::TY_Dependencies)
1064       CmdArgs.push_back("-Eonly");
1065     else
1066       CmdArgs.push_back("-E");
1067   } else if (isa<AssembleJobAction>(JA)) {
1068     CmdArgs.push_back("-emit-obj");
1069 
1070     if (UseRelaxAll(C, Args))
1071       CmdArgs.push_back("-mrelax-all");
1072 
1073     // When using an integrated assembler, translate -Wa, and -Xassembler
1074     // options.
1075     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
1076                                                options::OPT_Xassembler),
1077            ie = Args.filtered_end(); it != ie; ++it) {
1078       const Arg *A = *it;
1079       A->claim();
1080 
1081       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
1082         llvm::StringRef Value = A->getValue(Args, i);
1083 
1084         if (Value == "-force_cpusubtype_ALL") {
1085           // Do nothing, this is the default and we don't support anything else.
1086         } else if (Value == "-L") {
1087           CmdArgs.push_back("-msave-temp-labels");
1088         } else if (Value == "--fatal-warnings") {
1089           CmdArgs.push_back("-mllvm");
1090           CmdArgs.push_back("-fatal-assembler-warnings");
1091         } else if (Value == "--noexecstack") {
1092           CmdArgs.push_back("-mnoexecstack");
1093         } else {
1094           D.Diag(clang::diag::err_drv_unsupported_option_argument)
1095             << A->getOption().getName() << Value;
1096         }
1097       }
1098     }
1099 
1100     // Also ignore explicit -force_cpusubtype_ALL option.
1101     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
1102   } else if (isa<PrecompileJobAction>(JA)) {
1103     // Use PCH if the user requested it.
1104     bool UsePCH = D.CCCUsePCH;
1105 
1106     if (UsePCH)
1107       CmdArgs.push_back("-emit-pch");
1108     else
1109       CmdArgs.push_back("-emit-pth");
1110   } else {
1111     assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
1112 
1113     if (JA.getType() == types::TY_Nothing) {
1114       CmdArgs.push_back("-fsyntax-only");
1115     } else if (JA.getType() == types::TY_LLVM_IR ||
1116                JA.getType() == types::TY_LTO_IR) {
1117       CmdArgs.push_back("-emit-llvm");
1118     } else if (JA.getType() == types::TY_LLVM_BC ||
1119                JA.getType() == types::TY_LTO_BC) {
1120       CmdArgs.push_back("-emit-llvm-bc");
1121     } else if (JA.getType() == types::TY_PP_Asm) {
1122       CmdArgs.push_back("-S");
1123     } else if (JA.getType() == types::TY_AST) {
1124       CmdArgs.push_back("-emit-pch");
1125     } else if (JA.getType() == types::TY_RewrittenObjC) {
1126       CmdArgs.push_back("-rewrite-objc");
1127       IsRewriter = true;
1128     } else {
1129       assert(JA.getType() == types::TY_PP_Asm &&
1130              "Unexpected output type!");
1131     }
1132   }
1133 
1134   // The make clang go fast button.
1135   CmdArgs.push_back("-disable-free");
1136 
1137   // Disable the verification pass in -asserts builds.
1138 #ifdef NDEBUG
1139   CmdArgs.push_back("-disable-llvm-verifier");
1140 #endif
1141 
1142   // Set the main file name, so that debug info works even with
1143   // -save-temps.
1144   CmdArgs.push_back("-main-file-name");
1145   CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
1146 
1147   // Some flags which affect the language (via preprocessor
1148   // defines). See darwin::CC1::AddCPPArgs.
1149   if (Args.hasArg(options::OPT_static))
1150     CmdArgs.push_back("-static-define");
1151 
1152   if (isa<AnalyzeJobAction>(JA)) {
1153     // Enable region store model by default.
1154     CmdArgs.push_back("-analyzer-store=region");
1155 
1156     // Treat blocks as analysis entry points.
1157     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
1158 
1159     CmdArgs.push_back("-analyzer-eagerly-assume");
1160 
1161     // Add default argument set.
1162     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
1163       CmdArgs.push_back("-analyzer-checker=core");
1164       CmdArgs.push_back("-analyzer-checker=deadcode");
1165       CmdArgs.push_back("-analyzer-checker=security");
1166 
1167       if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
1168         CmdArgs.push_back("-analyzer-checker=unix");
1169 
1170       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
1171         CmdArgs.push_back("-analyzer-checker=osx");
1172     }
1173 
1174     // Set the output format. The default is plist, for (lame) historical
1175     // reasons.
1176     CmdArgs.push_back("-analyzer-output");
1177     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
1178       CmdArgs.push_back(A->getValue(Args));
1179     else
1180       CmdArgs.push_back("plist");
1181 
1182     // Disable the presentation of standard compiler warnings when
1183     // using --analyze.  We only want to show static analyzer diagnostics
1184     // or frontend errors.
1185     CmdArgs.push_back("-w");
1186 
1187     // Add -Xanalyzer arguments when running as analyzer.
1188     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
1189   }
1190 
1191   CheckCodeGenerationOptions(D, Args);
1192 
1193   // Perform argument translation for LLVM backend. This
1194   // takes some care in reconciling with llvm-gcc. The
1195   // issue is that llvm-gcc translates these options based on
1196   // the values in cc1, whereas we are processing based on
1197   // the driver arguments.
1198 
1199   // This comes from the default translation the driver + cc1
1200   // would do to enable flag_pic.
1201   //
1202   // FIXME: Centralize this code.
1203   bool PICEnabled = (Args.hasArg(options::OPT_fPIC) ||
1204                      Args.hasArg(options::OPT_fpic) ||
1205                      Args.hasArg(options::OPT_fPIE) ||
1206                      Args.hasArg(options::OPT_fpie));
1207   bool PICDisabled = (Args.hasArg(options::OPT_mkernel) ||
1208                       Args.hasArg(options::OPT_static));
1209   const char *Model = getToolChain().GetForcedPicModel();
1210   if (!Model) {
1211     if (Args.hasArg(options::OPT_mdynamic_no_pic))
1212       Model = "dynamic-no-pic";
1213     else if (PICDisabled)
1214       Model = "static";
1215     else if (PICEnabled)
1216       Model = "pic";
1217     else
1218       Model = getToolChain().GetDefaultRelocationModel();
1219   }
1220   if (llvm::StringRef(Model) != "pic") {
1221     CmdArgs.push_back("-mrelocation-model");
1222     CmdArgs.push_back(Model);
1223   }
1224 
1225   // Infer the __PIC__ value.
1226   //
1227   // FIXME:  This isn't quite right on Darwin, which always sets
1228   // __PIC__=2.
1229   if (strcmp(Model, "pic") == 0 || strcmp(Model, "dynamic-no-pic") == 0) {
1230     CmdArgs.push_back("-pic-level");
1231     CmdArgs.push_back(Args.hasArg(options::OPT_fPIC) ? "2" : "1");
1232   }
1233   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
1234                     options::OPT_fno_merge_all_constants))
1235     CmdArgs.push_back("-fno-merge-all-constants");
1236 
1237   // LLVM Code Generator Options.
1238 
1239   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1240     CmdArgs.push_back("-mregparm");
1241     CmdArgs.push_back(A->getValue(Args));
1242   }
1243 
1244   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
1245     CmdArgs.push_back("-mrtd");
1246 
1247   // FIXME: Set --enable-unsafe-fp-math.
1248   if (Args.hasFlag(options::OPT_fno_omit_frame_pointer,
1249                    options::OPT_fomit_frame_pointer))
1250     CmdArgs.push_back("-mdisable-fp-elim");
1251   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
1252                     options::OPT_fno_zero_initialized_in_bss))
1253     CmdArgs.push_back("-mno-zero-initialized-in-bss");
1254   if (!Args.hasFlag(options::OPT_fstrict_aliasing,
1255                     options::OPT_fno_strict_aliasing,
1256                     getToolChain().IsStrictAliasingDefault()))
1257     CmdArgs.push_back("-relaxed-aliasing");
1258 
1259   // Decide whether to use verbose asm. Verbose assembly is the default on
1260   // toolchains which have the integrated assembler on by default.
1261   bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
1262   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
1263                    IsVerboseAsmDefault) ||
1264       Args.hasArg(options::OPT_dA))
1265     CmdArgs.push_back("-masm-verbose");
1266 
1267   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
1268     CmdArgs.push_back("-mdebug-pass");
1269     CmdArgs.push_back("Structure");
1270   }
1271   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
1272     CmdArgs.push_back("-mdebug-pass");
1273     CmdArgs.push_back("Arguments");
1274   }
1275 
1276   // Enable -mconstructor-aliases except on darwin, where we have to
1277   // work around a linker bug;  see <rdar://problem/7651567>.
1278   if (getToolChain().getTriple().getOS() != llvm::Triple::Darwin)
1279     CmdArgs.push_back("-mconstructor-aliases");
1280 
1281   // Darwin's kernel doesn't support guard variables; just die if we
1282   // try to use them.
1283   if (KernelOrKext &&
1284       getToolChain().getTriple().getOS() == llvm::Triple::Darwin)
1285     CmdArgs.push_back("-fforbid-guard-variables");
1286 
1287   if (Args.hasArg(options::OPT_mms_bitfields)) {
1288     CmdArgs.push_back("-mms-bitfields");
1289   }
1290 
1291   // This is a coarse approximation of what llvm-gcc actually does, both
1292   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
1293   // complicated ways.
1294   bool AsynchronousUnwindTables =
1295     Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
1296                  options::OPT_fno_asynchronous_unwind_tables,
1297                  getToolChain().IsUnwindTablesDefault() &&
1298                  !KernelOrKext);
1299   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
1300                    AsynchronousUnwindTables))
1301     CmdArgs.push_back("-munwind-tables");
1302 
1303   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
1304     CmdArgs.push_back("-mlimit-float-precision");
1305     CmdArgs.push_back(A->getValue(Args));
1306   }
1307 
1308   // FIXME: Handle -mtune=.
1309   (void) Args.hasArg(options::OPT_mtune_EQ);
1310 
1311   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
1312     CmdArgs.push_back("-mcode-model");
1313     CmdArgs.push_back(A->getValue(Args));
1314   }
1315 
1316   // Add target specific cpu and features flags.
1317   switch(getToolChain().getTriple().getArch()) {
1318   default:
1319     break;
1320 
1321   case llvm::Triple::arm:
1322   case llvm::Triple::thumb:
1323     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
1324     break;
1325 
1326   case llvm::Triple::mips:
1327   case llvm::Triple::mipsel:
1328     AddMIPSTargetArgs(Args, CmdArgs);
1329     break;
1330 
1331   case llvm::Triple::sparc:
1332     AddSparcTargetArgs(Args, CmdArgs);
1333     break;
1334 
1335   case llvm::Triple::x86:
1336   case llvm::Triple::x86_64:
1337     AddX86TargetArgs(Args, CmdArgs);
1338     break;
1339   }
1340 
1341   // Pass the linker version in use.
1342   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
1343     CmdArgs.push_back("-target-linker-version");
1344     CmdArgs.push_back(A->getValue(Args));
1345   }
1346 
1347   // -mno-omit-leaf-frame-pointer is the default on Darwin.
1348   if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
1349                    options::OPT_mno_omit_leaf_frame_pointer,
1350                    getToolChain().getTriple().getOS() != llvm::Triple::Darwin))
1351     CmdArgs.push_back("-momit-leaf-frame-pointer");
1352 
1353   // -fno-math-errno is default.
1354   if (Args.hasFlag(options::OPT_fmath_errno,
1355                    options::OPT_fno_math_errno,
1356                    false))
1357     CmdArgs.push_back("-fmath-errno");
1358 
1359   // Explicitly error on some things we know we don't support and can't just
1360   // ignore.
1361   types::ID InputType = Inputs[0].getType();
1362   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
1363     Arg *Unsupported;
1364     if ((Unsupported = Args.getLastArg(options::OPT_iframework)))
1365       D.Diag(clang::diag::err_drv_clang_unsupported)
1366         << Unsupported->getOption().getName();
1367 
1368     if (types::isCXX(InputType) &&
1369         getToolChain().getTriple().getOS() == llvm::Triple::Darwin &&
1370         getToolChain().getTriple().getArch() == llvm::Triple::x86) {
1371       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)))
1372         D.Diag(clang::diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
1373           << Unsupported->getOption().getName();
1374     }
1375   }
1376 
1377   Args.AddAllArgs(CmdArgs, options::OPT_v);
1378   Args.AddLastArg(CmdArgs, options::OPT_H);
1379   if (D.CCPrintHeaders) {
1380     CmdArgs.push_back("-header-include-file");
1381     CmdArgs.push_back(D.CCPrintHeadersFilename ?
1382                       D.CCPrintHeadersFilename : "-");
1383   }
1384   Args.AddLastArg(CmdArgs, options::OPT_P);
1385   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
1386 
1387   if (D.CCLogDiagnostics) {
1388     CmdArgs.push_back("-diagnostic-log-file");
1389     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
1390                       D.CCLogDiagnosticsFilename : "-");
1391   }
1392 
1393   // Special case debug options to only pass -g to clang. This is
1394   // wrong.
1395   Args.ClaimAllArgs(options::OPT_g_Group);
1396   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
1397     if (!A->getOption().matches(options::OPT_g0))
1398       CmdArgs.push_back("-g");
1399 
1400   Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
1401   Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
1402 
1403   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
1404 
1405   if (Args.hasArg(options::OPT_ftest_coverage) ||
1406       Args.hasArg(options::OPT_coverage))
1407     CmdArgs.push_back("-femit-coverage-notes");
1408   if (Args.hasArg(options::OPT_fprofile_arcs) ||
1409       Args.hasArg(options::OPT_coverage))
1410     CmdArgs.push_back("-femit-coverage-data");
1411 
1412   if (C.getArgs().hasArg(options::OPT_c) ||
1413       C.getArgs().hasArg(options::OPT_S)) {
1414     if (Output.isFilename()) {
1415       CmdArgs.push_back("-coverage-file");
1416       CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
1417     }
1418   }
1419 
1420   Args.AddLastArg(CmdArgs, options::OPT_nostdinc);
1421   Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
1422   Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
1423 
1424   // Pass the path to compiler resource files.
1425   CmdArgs.push_back("-resource-dir");
1426   CmdArgs.push_back(D.ResourceDir.c_str());
1427 
1428   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
1429 
1430   if (!Args.hasArg(options::OPT_fno_objc_arc)) {
1431     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
1432                                        options::OPT_ccc_arcmt_modify,
1433                                        options::OPT_ccc_arcmt_migrate)) {
1434       switch (A->getOption().getID()) {
1435       default:
1436         llvm_unreachable("missed a case");
1437       case options::OPT_ccc_arcmt_check:
1438         CmdArgs.push_back("-arcmt-check");
1439         break;
1440       case options::OPT_ccc_arcmt_modify:
1441         CmdArgs.push_back("-arcmt-modify");
1442         break;
1443       case options::OPT_ccc_arcmt_migrate:
1444         CmdArgs.push_back("-arcmt-migrate");
1445         CmdArgs.push_back("-arcmt-migrate-directory");
1446         CmdArgs.push_back(A->getValue(Args));
1447 
1448         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
1449         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
1450         break;
1451       }
1452     }
1453   }
1454 
1455   // Add preprocessing options like -I, -D, etc. if we are using the
1456   // preprocessor.
1457   //
1458   // FIXME: Support -fpreprocessed
1459   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
1460     AddPreprocessingOptions(D, Args, CmdArgs, Output, Inputs);
1461 
1462   // Manually translate -O to -O2 and -O4 to -O3; let clang reject
1463   // others.
1464   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1465     if (A->getOption().matches(options::OPT_O4))
1466       CmdArgs.push_back("-O3");
1467     else if (A->getOption().matches(options::OPT_O) &&
1468              A->getValue(Args)[0] == '\0')
1469       CmdArgs.push_back("-O2");
1470     else
1471       A->render(Args, CmdArgs);
1472   }
1473 
1474   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
1475   Args.AddLastArg(CmdArgs, options::OPT_pedantic);
1476   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
1477   Args.AddLastArg(CmdArgs, options::OPT_w);
1478 
1479   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
1480   // (-ansi is equivalent to -std=c89).
1481   //
1482   // If a std is supplied, only add -trigraphs if it follows the
1483   // option.
1484   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
1485     if (Std->getOption().matches(options::OPT_ansi))
1486       if (types::isCXX(InputType))
1487         CmdArgs.push_back("-std=c++98");
1488       else
1489         CmdArgs.push_back("-std=c89");
1490     else
1491       Std->render(Args, CmdArgs);
1492 
1493     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
1494                                  options::OPT_trigraphs))
1495       if (A != Std)
1496         A->render(Args, CmdArgs);
1497   } else {
1498     // Honor -std-default.
1499     //
1500     // FIXME: Clang doesn't correctly handle -std= when the input language
1501     // doesn't match. For the time being just ignore this for C++ inputs;
1502     // eventually we want to do all the standard defaulting here instead of
1503     // splitting it between the driver and clang -cc1.
1504     if (!types::isCXX(InputType))
1505         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
1506                                   "-std=", /*Joined=*/true);
1507     Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
1508   }
1509 
1510   // Map the bizarre '-Wwrite-strings' flag to a more sensible
1511   // '-fconst-strings'; this better indicates its actual behavior.
1512   if (Args.hasFlag(options::OPT_Wwrite_strings, options::OPT_Wno_write_strings,
1513                    false)) {
1514     // For perfect compatibility with GCC, we do this even in the presence of
1515     // '-w'. This flag names something other than a warning for GCC.
1516     CmdArgs.push_back("-fconst-strings");
1517   }
1518 
1519   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
1520   // during C++ compilation, which it is by default. GCC keeps this define even
1521   // in the presence of '-w', match this behavior bug-for-bug.
1522   if (types::isCXX(InputType) &&
1523       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
1524                    true)) {
1525     CmdArgs.push_back("-fdeprecated-macro");
1526   }
1527 
1528   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
1529   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
1530     if (Asm->getOption().matches(options::OPT_fasm))
1531       CmdArgs.push_back("-fgnu-keywords");
1532     else
1533       CmdArgs.push_back("-fno-gnu-keywords");
1534   }
1535 
1536   if (ShouldDisableCFI(Args, getToolChain()))
1537     CmdArgs.push_back("-fno-dwarf2-cfi-asm");
1538 
1539   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_)) {
1540     CmdArgs.push_back("-ftemplate-depth");
1541     CmdArgs.push_back(A->getValue(Args));
1542   }
1543 
1544   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
1545                                options::OPT_Wlarge_by_value_copy_def)) {
1546     CmdArgs.push_back("-Wlarge-by-value-copy");
1547     if (A->getNumValues())
1548       CmdArgs.push_back(A->getValue(Args));
1549     else
1550       CmdArgs.push_back("64"); // default value for -Wlarge-by-value-copy.
1551   }
1552 
1553   if (Args.hasArg(options::OPT__relocatable_pch))
1554     CmdArgs.push_back("-relocatable-pch");
1555 
1556   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
1557     CmdArgs.push_back("-fconstant-string-class");
1558     CmdArgs.push_back(A->getValue(Args));
1559   }
1560 
1561   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
1562     CmdArgs.push_back("-ftabstop");
1563     CmdArgs.push_back(A->getValue(Args));
1564   }
1565 
1566   CmdArgs.push_back("-ferror-limit");
1567   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
1568     CmdArgs.push_back(A->getValue(Args));
1569   else
1570     CmdArgs.push_back("19");
1571 
1572   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
1573     CmdArgs.push_back("-fmacro-backtrace-limit");
1574     CmdArgs.push_back(A->getValue(Args));
1575   }
1576 
1577   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
1578     CmdArgs.push_back("-ftemplate-backtrace-limit");
1579     CmdArgs.push_back(A->getValue(Args));
1580   }
1581 
1582   // Pass -fmessage-length=.
1583   CmdArgs.push_back("-fmessage-length");
1584   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
1585     CmdArgs.push_back(A->getValue(Args));
1586   } else {
1587     // If -fmessage-length=N was not specified, determine whether this is a
1588     // terminal and, if so, implicitly define -fmessage-length appropriately.
1589     unsigned N = llvm::sys::Process::StandardErrColumns();
1590     CmdArgs.push_back(Args.MakeArgString(llvm::Twine(N)));
1591   }
1592 
1593   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) {
1594     CmdArgs.push_back("-fvisibility");
1595     CmdArgs.push_back(A->getValue(Args));
1596   }
1597 
1598   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
1599 
1600   // -fhosted is default.
1601   if (KernelOrKext || Args.hasFlag(options::OPT_ffreestanding,
1602                                    options::OPT_fhosted,
1603                                    false))
1604     CmdArgs.push_back("-ffreestanding");
1605 
1606   // Forward -f (flag) options which we can pass directly.
1607   Args.AddLastArg(CmdArgs, options::OPT_fcatch_undefined_behavior);
1608   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
1609   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
1610   Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
1611   if (getToolChain().SupportsProfiling())
1612     Args.AddLastArg(CmdArgs, options::OPT_pg);
1613 
1614   // -flax-vector-conversions is default.
1615   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
1616                     options::OPT_fno_lax_vector_conversions))
1617     CmdArgs.push_back("-fno-lax-vector-conversions");
1618 
1619   if (Args.getLastArg(options::OPT_fapple_kext))
1620     CmdArgs.push_back("-fapple-kext");
1621 
1622   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
1623   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
1624   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
1625   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
1626   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
1627 
1628   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
1629     CmdArgs.push_back("-ftrapv-handler");
1630     CmdArgs.push_back(A->getValue(Args));
1631   }
1632 
1633   // Forward -ftrap_function= options to the backend.
1634   if (Arg *A = Args.getLastArg(options::OPT_ftrap_function_EQ)) {
1635     llvm::StringRef FuncName = A->getValue(Args);
1636     CmdArgs.push_back("-backend-option");
1637     CmdArgs.push_back(Args.MakeArgString("-trap-func=" + FuncName));
1638   }
1639 
1640   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
1641   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
1642   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
1643                                options::OPT_fno_wrapv)) {
1644     if (A->getOption().matches(options::OPT_fwrapv))
1645       CmdArgs.push_back("-fwrapv");
1646   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
1647                                       options::OPT_fno_strict_overflow)) {
1648     if (A->getOption().matches(options::OPT_fno_strict_overflow))
1649       CmdArgs.push_back("-fwrapv");
1650   }
1651   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
1652   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
1653 
1654   Args.AddLastArg(CmdArgs, options::OPT_pthread);
1655 
1656   // -stack-protector=0 is default.
1657   unsigned StackProtectorLevel = 0;
1658   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
1659                                options::OPT_fstack_protector_all,
1660                                options::OPT_fstack_protector)) {
1661     if (A->getOption().matches(options::OPT_fstack_protector))
1662       StackProtectorLevel = 1;
1663     else if (A->getOption().matches(options::OPT_fstack_protector_all))
1664       StackProtectorLevel = 2;
1665   } else
1666     StackProtectorLevel = getToolChain().GetDefaultStackProtectorLevel();
1667   if (StackProtectorLevel) {
1668     CmdArgs.push_back("-stack-protector");
1669     CmdArgs.push_back(Args.MakeArgString(llvm::Twine(StackProtectorLevel)));
1670   }
1671 
1672   // Translate -mstackrealign
1673   if (Args.hasArg(options::OPT_mstackrealign)) {
1674     CmdArgs.push_back("-backend-option");
1675     CmdArgs.push_back("-force-align-stack");
1676   }
1677 
1678   // Forward -f options with positive and negative forms; we translate
1679   // these by hand.
1680 
1681   if (Args.hasArg(options::OPT_mkernel)) {
1682     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
1683       CmdArgs.push_back("-fapple-kext");
1684     if (!Args.hasArg(options::OPT_fbuiltin))
1685       CmdArgs.push_back("-fno-builtin");
1686   }
1687   // -fbuiltin is default.
1688   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
1689     CmdArgs.push_back("-fno-builtin");
1690 
1691   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1692                     options::OPT_fno_assume_sane_operator_new))
1693     CmdArgs.push_back("-fno-assume-sane-operator-new");
1694 
1695   // -fblocks=0 is default.
1696   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
1697                    getToolChain().IsBlocksDefault()) ||
1698         (Args.hasArg(options::OPT_fgnu_runtime) &&
1699          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
1700          !Args.hasArg(options::OPT_fno_blocks))) {
1701     CmdArgs.push_back("-fblocks");
1702   }
1703 
1704   // -faccess-control is default.
1705   if (Args.hasFlag(options::OPT_fno_access_control,
1706                    options::OPT_faccess_control,
1707                    false))
1708     CmdArgs.push_back("-fno-access-control");
1709 
1710   // -felide-constructors is the default.
1711   if (Args.hasFlag(options::OPT_fno_elide_constructors,
1712                    options::OPT_felide_constructors,
1713                    false))
1714     CmdArgs.push_back("-fno-elide-constructors");
1715 
1716   // -frtti is default.
1717   if (KernelOrKext ||
1718       !Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti))
1719     CmdArgs.push_back("-fno-rtti");
1720 
1721   // -fshort-enums=0 is default.
1722   // FIXME: Are there targers where -fshort-enums is on by default ?
1723   if (Args.hasFlag(options::OPT_fshort_enums,
1724                    options::OPT_fno_short_enums, false))
1725     CmdArgs.push_back("-fshort-enums");
1726 
1727   // -fsigned-char is default.
1728   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
1729                     isSignedCharDefault(getToolChain().getTriple())))
1730     CmdArgs.push_back("-fno-signed-char");
1731 
1732   // -fthreadsafe-static is default.
1733   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
1734                     options::OPT_fno_threadsafe_statics))
1735     CmdArgs.push_back("-fno-threadsafe-statics");
1736 
1737   // -fuse-cxa-atexit is default.
1738   if (KernelOrKext ||
1739     !Args.hasFlag(options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
1740                   getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
1741                   getToolChain().getTriple().getOS() != llvm::Triple::MinGW32))
1742     CmdArgs.push_back("-fno-use-cxa-atexit");
1743 
1744   // -fms-extensions=0 is default.
1745   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1746                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
1747     CmdArgs.push_back("-fms-extensions");
1748 
1749   // -fmsc-version=1300 is default.
1750   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1751                    getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
1752       Args.hasArg(options::OPT_fmsc_version)) {
1753     llvm::StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
1754     if (msc_ver.empty())
1755       CmdArgs.push_back("-fmsc-version=1300");
1756     else
1757       CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
1758   }
1759 
1760 
1761   // -fborland-extensions=0 is default.
1762   if (Args.hasFlag(options::OPT_fborland_extensions,
1763                    options::OPT_fno_borland_extensions, false))
1764     CmdArgs.push_back("-fborland-extensions");
1765 
1766   // -fno-delayed-template-parsing is default.
1767   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
1768                    options::OPT_fno_delayed_template_parsing,
1769                    false))
1770     CmdArgs.push_back("-fdelayed-template-parsing");
1771 
1772   // -fgnu-keywords default varies depending on language; only pass if
1773   // specified.
1774   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
1775                                options::OPT_fno_gnu_keywords))
1776     A->render(Args, CmdArgs);
1777 
1778   if (Args.hasFlag(options::OPT_fgnu89_inline,
1779                    options::OPT_fno_gnu89_inline,
1780                    false))
1781     CmdArgs.push_back("-fgnu89-inline");
1782 
1783   // -fobjc-nonfragile-abi=0 is default.
1784   ObjCRuntime objCRuntime;
1785   unsigned objcABIVersion = 0;
1786   if (types::isObjC(InputType)) {
1787     bool NeXTRuntimeIsDefault
1788       = (IsRewriter || getToolChain().getTriple().isOSDarwin());
1789     if (Args.hasFlag(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
1790                      NeXTRuntimeIsDefault)) {
1791       objCRuntime.setKind(ObjCRuntime::NeXT);
1792     } else {
1793       CmdArgs.push_back("-fgnu-runtime");
1794       objCRuntime.setKind(ObjCRuntime::GNU);
1795     }
1796     getToolChain().configureObjCRuntime(objCRuntime);
1797     if (objCRuntime.HasARC)
1798       CmdArgs.push_back("-fobjc-runtime-has-arc");
1799     if (objCRuntime.HasWeak)
1800       CmdArgs.push_back("-fobjc-runtime-has-weak");
1801     if (objCRuntime.HasTerminate)
1802       CmdArgs.push_back("-fobjc-runtime-has-terminate");
1803 
1804     // Compute the Objective-C ABI "version" to use. Version numbers are
1805     // slightly confusing for historical reasons:
1806     //   1 - Traditional "fragile" ABI
1807     //   2 - Non-fragile ABI, version 1
1808     //   3 - Non-fragile ABI, version 2
1809     objcABIVersion = 1;
1810     // If -fobjc-abi-version= is present, use that to set the version.
1811     if (Arg *A = Args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
1812       if (llvm::StringRef(A->getValue(Args)) == "1")
1813         objcABIVersion = 1;
1814       else if (llvm::StringRef(A->getValue(Args)) == "2")
1815         objcABIVersion = 2;
1816       else if (llvm::StringRef(A->getValue(Args)) == "3")
1817         objcABIVersion = 3;
1818       else
1819         D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
1820     } else {
1821       // Otherwise, determine if we are using the non-fragile ABI.
1822       if (Args.hasFlag(options::OPT_fobjc_nonfragile_abi,
1823                        options::OPT_fno_objc_nonfragile_abi,
1824                        getToolChain().IsObjCNonFragileABIDefault())) {
1825         // Determine the non-fragile ABI version to use.
1826 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
1827         unsigned NonFragileABIVersion = 1;
1828 #else
1829         unsigned NonFragileABIVersion = 2;
1830 #endif
1831 
1832         if (Arg *A = Args.getLastArg(
1833               options::OPT_fobjc_nonfragile_abi_version_EQ)) {
1834           if (llvm::StringRef(A->getValue(Args)) == "1")
1835             NonFragileABIVersion = 1;
1836           else if (llvm::StringRef(A->getValue(Args)) == "2")
1837             NonFragileABIVersion = 2;
1838           else
1839             D.Diag(clang::diag::err_drv_clang_unsupported)
1840               << A->getAsString(Args);
1841         }
1842 
1843         objcABIVersion = 1 + NonFragileABIVersion;
1844       } else {
1845         objcABIVersion = 1;
1846       }
1847     }
1848 
1849     if (objcABIVersion == 2 || objcABIVersion == 3) {
1850       CmdArgs.push_back("-fobjc-nonfragile-abi");
1851 
1852       // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
1853       // legacy is the default.
1854       if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
1855                         options::OPT_fno_objc_legacy_dispatch,
1856                         getToolChain().IsObjCLegacyDispatchDefault())) {
1857         if (getToolChain().UseObjCMixedDispatch())
1858           CmdArgs.push_back("-fobjc-dispatch-method=mixed");
1859         else
1860           CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
1861       }
1862     }
1863 
1864     // FIXME: Don't expose -fobjc-default-synthesize-properties as a top-level
1865     // driver flag yet.  This feature is still under active development
1866     // and shouldn't be exposed as a user visible feature (which may change).
1867     // Clang still supports this as a -cc1 option for development and testing.
1868 #if 0
1869     // -fobjc-default-synthesize-properties=0 is default.
1870     if (Args.hasFlag(options::OPT_fobjc_default_synthesize_properties,
1871                      options::OPT_fno_objc_default_synthesize_properties,
1872                      getToolChain().IsObjCDefaultSynthPropertiesDefault())) {
1873       CmdArgs.push_back("-fobjc-default-synthesize-properties");
1874     }
1875 #endif
1876   }
1877 
1878   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
1879   // NOTE: This logic is duplicated in ToolChains.cpp.
1880   bool ARC = isObjCAutoRefCount(Args);
1881   if (ARC) {
1882     CmdArgs.push_back("-fobjc-arc");
1883 
1884     // Allow the user to enable full exceptions code emission.
1885     // We define off for Objective-CC, on for Objective-C++.
1886     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
1887                      options::OPT_fno_objc_arc_exceptions,
1888                      /*default*/ types::isCXX(InputType)))
1889       CmdArgs.push_back("-fobjc-arc-exceptions");
1890   }
1891 
1892   // -fobjc-infer-related-result-type is the default, except in the Objective-C
1893   // rewriter.
1894   if (IsRewriter)
1895     CmdArgs.push_back("-fno-objc-infer-related-result-type");
1896 
1897   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
1898   // takes precedence.
1899   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
1900   if (!GCArg)
1901     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
1902   if (GCArg) {
1903     if (ARC) {
1904       D.Diag(clang::diag::err_drv_objc_gc_arr)
1905         << GCArg->getAsString(Args);
1906     } else if (getToolChain().SupportsObjCGC()) {
1907       GCArg->render(Args, CmdArgs);
1908     } else {
1909       // FIXME: We should move this to a hard error.
1910       D.Diag(clang::diag::warn_drv_objc_gc_unsupported)
1911         << GCArg->getAsString(Args);
1912     }
1913   }
1914 
1915   // Add exception args.
1916   addExceptionArgs(Args, InputType, getToolChain().getTriple(),
1917                    KernelOrKext, IsRewriter, objcABIVersion, CmdArgs);
1918 
1919   if (getToolChain().UseSjLjExceptions())
1920     CmdArgs.push_back("-fsjlj-exceptions");
1921 
1922   // C++ "sane" operator new.
1923   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1924                     options::OPT_fno_assume_sane_operator_new))
1925     CmdArgs.push_back("-fno-assume-sane-operator-new");
1926 
1927   // -fconstant-cfstrings is default, and may be subject to argument translation
1928   // on Darwin.
1929   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
1930                     options::OPT_fno_constant_cfstrings) ||
1931       !Args.hasFlag(options::OPT_mconstant_cfstrings,
1932                     options::OPT_mno_constant_cfstrings))
1933     CmdArgs.push_back("-fno-constant-cfstrings");
1934 
1935   // -fshort-wchar default varies depending on platform; only
1936   // pass if specified.
1937   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
1938     A->render(Args, CmdArgs);
1939 
1940   // -fno-pascal-strings is default, only pass non-default. If the tool chain
1941   // happened to translate to -mpascal-strings, we want to back translate here.
1942   //
1943   // FIXME: This is gross; that translation should be pulled from the
1944   // tool chain.
1945   if (Args.hasFlag(options::OPT_fpascal_strings,
1946                    options::OPT_fno_pascal_strings,
1947                    false) ||
1948       Args.hasFlag(options::OPT_mpascal_strings,
1949                    options::OPT_mno_pascal_strings,
1950                    false))
1951     CmdArgs.push_back("-fpascal-strings");
1952 
1953   if (Args.hasArg(options::OPT_mkernel) ||
1954       Args.hasArg(options::OPT_fapple_kext)) {
1955     if (!Args.hasArg(options::OPT_fcommon))
1956       CmdArgs.push_back("-fno-common");
1957   }
1958   // -fcommon is default, only pass non-default.
1959   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
1960     CmdArgs.push_back("-fno-common");
1961 
1962   // -fsigned-bitfields is default, and clang doesn't yet support
1963   // -funsigned-bitfields.
1964   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
1965                     options::OPT_funsigned_bitfields))
1966     D.Diag(clang::diag::warn_drv_clang_unsupported)
1967       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
1968 
1969   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
1970   if (!Args.hasFlag(options::OPT_ffor_scope,
1971                     options::OPT_fno_for_scope))
1972     D.Diag(clang::diag::err_drv_clang_unsupported)
1973       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
1974 
1975   // -fcaret-diagnostics is default.
1976   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
1977                     options::OPT_fno_caret_diagnostics, true))
1978     CmdArgs.push_back("-fno-caret-diagnostics");
1979 
1980   // -fdiagnostics-fixit-info is default, only pass non-default.
1981   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
1982                     options::OPT_fno_diagnostics_fixit_info))
1983     CmdArgs.push_back("-fno-diagnostics-fixit-info");
1984 
1985   // Enable -fdiagnostics-show-name by default.
1986   if (Args.hasFlag(options::OPT_fdiagnostics_show_name,
1987                    options::OPT_fno_diagnostics_show_name, false))
1988     CmdArgs.push_back("-fdiagnostics-show-name");
1989 
1990   // Enable -fdiagnostics-show-option by default.
1991   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
1992                    options::OPT_fno_diagnostics_show_option))
1993     CmdArgs.push_back("-fdiagnostics-show-option");
1994 
1995   if (const Arg *A =
1996         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
1997     CmdArgs.push_back("-fdiagnostics-show-category");
1998     CmdArgs.push_back(A->getValue(Args));
1999   }
2000 
2001   if (const Arg *A =
2002         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2003     CmdArgs.push_back("-fdiagnostics-format");
2004     CmdArgs.push_back(A->getValue(Args));
2005   }
2006 
2007   if (Arg *A = Args.getLastArg(
2008       options::OPT_fdiagnostics_show_note_include_stack,
2009       options::OPT_fno_diagnostics_show_note_include_stack)) {
2010     if (A->getOption().matches(
2011         options::OPT_fdiagnostics_show_note_include_stack))
2012       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2013     else
2014       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2015   }
2016 
2017   // Color diagnostics are the default, unless the terminal doesn't support
2018   // them.
2019   if (Args.hasFlag(options::OPT_fcolor_diagnostics,
2020                    options::OPT_fno_color_diagnostics,
2021                    llvm::sys::Process::StandardErrHasColors()))
2022     CmdArgs.push_back("-fcolor-diagnostics");
2023 
2024   if (!Args.hasFlag(options::OPT_fshow_source_location,
2025                     options::OPT_fno_show_source_location))
2026     CmdArgs.push_back("-fno-show-source-location");
2027 
2028   if (!Args.hasFlag(options::OPT_fshow_column,
2029                     options::OPT_fno_show_column,
2030                     true))
2031     CmdArgs.push_back("-fno-show-column");
2032 
2033   if (!Args.hasFlag(options::OPT_fspell_checking,
2034                     options::OPT_fno_spell_checking))
2035     CmdArgs.push_back("-fno-spell-checking");
2036 
2037 
2038   // Silently ignore -fasm-blocks for now.
2039   (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
2040                       false);
2041 
2042   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
2043     A->render(Args, CmdArgs);
2044 
2045   // -fdollars-in-identifiers default varies depending on platform and
2046   // language; only pass if specified.
2047   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
2048                                options::OPT_fno_dollars_in_identifiers)) {
2049     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
2050       CmdArgs.push_back("-fdollars-in-identifiers");
2051     else
2052       CmdArgs.push_back("-fno-dollars-in-identifiers");
2053   }
2054 
2055   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
2056   // practical purposes.
2057   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
2058                                options::OPT_fno_unit_at_a_time)) {
2059     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
2060       D.Diag(clang::diag::warn_drv_clang_unsupported) << A->getAsString(Args);
2061   }
2062 
2063   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
2064   //
2065   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
2066 #if 0
2067   if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin &&
2068       (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2069        getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
2070     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
2071       CmdArgs.push_back("-fno-builtin-strcat");
2072     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
2073       CmdArgs.push_back("-fno-builtin-strcpy");
2074   }
2075 #endif
2076 
2077   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
2078   if (Arg *A = Args.getLastArg(options::OPT_traditional,
2079                                options::OPT_traditional_cpp)) {
2080     if (isa<PreprocessJobAction>(JA))
2081       CmdArgs.push_back("-traditional-cpp");
2082     else
2083       D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
2084   }
2085 
2086   Args.AddLastArg(CmdArgs, options::OPT_dM);
2087   Args.AddLastArg(CmdArgs, options::OPT_dD);
2088 
2089   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
2090   // parser.
2091   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
2092   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
2093          ie = Args.filtered_end(); it != ie; ++it) {
2094     (*it)->claim();
2095 
2096     // We translate this by hand to the -cc1 argument, since nightly test uses
2097     // it and developers have been trained to spell it with -mllvm.
2098     if (llvm::StringRef((*it)->getValue(Args, 0)) == "-disable-llvm-optzns")
2099       CmdArgs.push_back("-disable-llvm-optzns");
2100     else
2101       (*it)->render(Args, CmdArgs);
2102   }
2103 
2104   if (Output.getType() == types::TY_Dependencies) {
2105     // Handled with other dependency code.
2106   } else if (Output.isFilename()) {
2107     CmdArgs.push_back("-o");
2108     CmdArgs.push_back(Output.getFilename());
2109   } else {
2110     assert(Output.isNothing() && "Invalid output.");
2111   }
2112 
2113   for (InputInfoList::const_iterator
2114          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2115     const InputInfo &II = *it;
2116     CmdArgs.push_back("-x");
2117     CmdArgs.push_back(types::getTypeName(II.getType()));
2118     if (II.isFilename())
2119       CmdArgs.push_back(II.getFilename());
2120     else
2121       II.getInputArg().renderAsInput(Args, CmdArgs);
2122   }
2123 
2124   Args.AddAllArgs(CmdArgs, options::OPT_undef);
2125 
2126   const char *Exec = getToolChain().getDriver().getClangProgramPath();
2127 
2128   // Optionally embed the -cc1 level arguments into the debug info, for build
2129   // analysis.
2130   if (getToolChain().UseDwarfDebugFlags()) {
2131     ArgStringList OriginalArgs;
2132     for (ArgList::const_iterator it = Args.begin(),
2133            ie = Args.end(); it != ie; ++it)
2134       (*it)->render(Args, OriginalArgs);
2135 
2136     llvm::SmallString<256> Flags;
2137     Flags += Exec;
2138     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
2139       Flags += " ";
2140       Flags += OriginalArgs[i];
2141     }
2142     CmdArgs.push_back("-dwarf-debug-flags");
2143     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
2144   }
2145 
2146   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2147 
2148   if (Arg *A = Args.getLastArg(options::OPT_pg))
2149     if (Args.hasArg(options::OPT_fomit_frame_pointer))
2150       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
2151         << "-fomit-frame-pointer" << A->getAsString(Args);
2152 
2153   // Claim some arguments which clang supports automatically.
2154 
2155   // -fpch-preprocess is used with gcc to add a special marker in the output to
2156   // include the PCH file. Clang's PTH solution is completely transparent, so we
2157   // do not need to deal with it at all.
2158   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
2159 
2160   // Claim some arguments which clang doesn't support, but we don't
2161   // care to warn the user about.
2162   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
2163   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
2164 
2165   // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
2166   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
2167   Args.ClaimAllArgs(options::OPT_emit_llvm);
2168 }
2169 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const2170 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
2171                            const InputInfo &Output,
2172                            const InputInfoList &Inputs,
2173                            const ArgList &Args,
2174                            const char *LinkingOutput) const {
2175   ArgStringList CmdArgs;
2176 
2177   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
2178   const InputInfo &Input = Inputs[0];
2179 
2180   // Don't warn about "clang -w -c foo.s"
2181   Args.ClaimAllArgs(options::OPT_w);
2182   // and "clang -emit-llvm -c foo.s"
2183   Args.ClaimAllArgs(options::OPT_emit_llvm);
2184   // and "clang -use-gold-plugin -c foo.s"
2185   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
2186 
2187   // Invoke ourselves in -cc1as mode.
2188   //
2189   // FIXME: Implement custom jobs for internal actions.
2190   CmdArgs.push_back("-cc1as");
2191 
2192   // Add the "effective" target triple.
2193   CmdArgs.push_back("-triple");
2194   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2195   CmdArgs.push_back(Args.MakeArgString(TripleStr));
2196 
2197   // Set the output mode, we currently only expect to be used as a real
2198   // assembler.
2199   CmdArgs.push_back("-filetype");
2200   CmdArgs.push_back("obj");
2201 
2202   if (UseRelaxAll(C, Args))
2203     CmdArgs.push_back("-relax-all");
2204 
2205   // Ignore explicit -force_cpusubtype_ALL option.
2206   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
2207 
2208   // FIXME: Add -g support, once we have it.
2209 
2210   // FIXME: Add -static support, once we have it.
2211 
2212   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2213                        options::OPT_Xassembler);
2214   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
2215 
2216   assert(Output.isFilename() && "Unexpected lipo output.");
2217   CmdArgs.push_back("-o");
2218   CmdArgs.push_back(Output.getFilename());
2219 
2220   assert(Input.isFilename() && "Invalid input.");
2221   CmdArgs.push_back(Input.getFilename());
2222 
2223   const char *Exec = getToolChain().getDriver().getClangProgramPath();
2224   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2225 }
2226 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const2227 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
2228                                const InputInfo &Output,
2229                                const InputInfoList &Inputs,
2230                                const ArgList &Args,
2231                                const char *LinkingOutput) const {
2232   const Driver &D = getToolChain().getDriver();
2233   ArgStringList CmdArgs;
2234 
2235   for (ArgList::const_iterator
2236          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
2237     Arg *A = *it;
2238     if (A->getOption().hasForwardToGCC()) {
2239       // Don't forward any -g arguments to assembly steps.
2240       if (isa<AssembleJobAction>(JA) &&
2241           A->getOption().matches(options::OPT_g_Group))
2242         continue;
2243 
2244       // It is unfortunate that we have to claim here, as this means
2245       // we will basically never report anything interesting for
2246       // platforms using a generic gcc, even if we are just using gcc
2247       // to get to the assembler.
2248       A->claim();
2249       A->render(Args, CmdArgs);
2250     }
2251   }
2252 
2253   RenderExtraToolArgs(JA, CmdArgs);
2254 
2255   // If using a driver driver, force the arch.
2256   const std::string &Arch = getToolChain().getArchName();
2257   if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin) {
2258     CmdArgs.push_back("-arch");
2259 
2260     // FIXME: Remove these special cases.
2261     if (Arch == "powerpc")
2262       CmdArgs.push_back("ppc");
2263     else if (Arch == "powerpc64")
2264       CmdArgs.push_back("ppc64");
2265     else
2266       CmdArgs.push_back(Args.MakeArgString(Arch));
2267   }
2268 
2269   // Try to force gcc to match the tool chain we want, if we recognize
2270   // the arch.
2271   //
2272   // FIXME: The triple class should directly provide the information we want
2273   // here.
2274   if (Arch == "i386" || Arch == "powerpc")
2275     CmdArgs.push_back("-m32");
2276   else if (Arch == "x86_64" || Arch == "powerpc64")
2277     CmdArgs.push_back("-m64");
2278 
2279   if (Output.isFilename()) {
2280     CmdArgs.push_back("-o");
2281     CmdArgs.push_back(Output.getFilename());
2282   } else {
2283     assert(Output.isNothing() && "Unexpected output");
2284     CmdArgs.push_back("-fsyntax-only");
2285   }
2286 
2287 
2288   // Only pass -x if gcc will understand it; otherwise hope gcc
2289   // understands the suffix correctly. The main use case this would go
2290   // wrong in is for linker inputs if they happened to have an odd
2291   // suffix; really the only way to get this to happen is a command
2292   // like '-x foobar a.c' which will treat a.c like a linker input.
2293   //
2294   // FIXME: For the linker case specifically, can we safely convert
2295   // inputs into '-Wl,' options?
2296   for (InputInfoList::const_iterator
2297          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2298     const InputInfo &II = *it;
2299 
2300     // Don't try to pass LLVM or AST inputs to a generic gcc.
2301     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
2302         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
2303       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
2304         << getToolChain().getTripleString();
2305     else if (II.getType() == types::TY_AST)
2306       D.Diag(clang::diag::err_drv_no_ast_support)
2307         << getToolChain().getTripleString();
2308 
2309     if (types::canTypeBeUserSpecified(II.getType())) {
2310       CmdArgs.push_back("-x");
2311       CmdArgs.push_back(types::getTypeName(II.getType()));
2312     }
2313 
2314     if (II.isFilename())
2315       CmdArgs.push_back(II.getFilename());
2316     else {
2317       const Arg &A = II.getInputArg();
2318 
2319       // Reverse translate some rewritten options.
2320       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
2321         CmdArgs.push_back("-lstdc++");
2322         continue;
2323       }
2324 
2325       // Don't render as input, we need gcc to do the translations.
2326       A.render(Args, CmdArgs);
2327     }
2328   }
2329 
2330   const std::string customGCCName = D.getCCCGenericGCCName();
2331   const char *GCCName;
2332   if (!customGCCName.empty())
2333     GCCName = customGCCName.c_str();
2334   else if (D.CCCIsCXX) {
2335 #ifdef IS_CYGWIN15
2336     // FIXME: Detect the version of Cygwin at runtime?
2337     GCCName = "g++-4";
2338 #else
2339     GCCName = "g++";
2340 #endif
2341   } else
2342     GCCName = "gcc";
2343 
2344   const char *Exec =
2345     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
2346   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2347 }
2348 
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const2349 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
2350                                           ArgStringList &CmdArgs) const {
2351   CmdArgs.push_back("-E");
2352 }
2353 
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const2354 void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
2355                                           ArgStringList &CmdArgs) const {
2356   // The type is good enough.
2357 }
2358 
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const2359 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
2360                                        ArgStringList &CmdArgs) const {
2361   const Driver &D = getToolChain().getDriver();
2362 
2363   // If -flto, etc. are present then make sure not to force assembly output.
2364   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
2365       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
2366     CmdArgs.push_back("-c");
2367   else {
2368     if (JA.getType() != types::TY_PP_Asm)
2369       D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
2370         << getTypeName(JA.getType());
2371 
2372     CmdArgs.push_back("-S");
2373   }
2374 }
2375 
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const2376 void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
2377                                         ArgStringList &CmdArgs) const {
2378   CmdArgs.push_back("-c");
2379 }
2380 
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const2381 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
2382                                     ArgStringList &CmdArgs) const {
2383   // The types are (hopefully) good enough.
2384 }
2385 
getCC1Name(types::ID Type) const2386 const char *darwin::CC1::getCC1Name(types::ID Type) const {
2387   switch (Type) {
2388   default:
2389     assert(0 && "Unexpected type for Darwin CC1 tool.");
2390   case types::TY_Asm:
2391   case types::TY_C: case types::TY_CHeader:
2392   case types::TY_PP_C: case types::TY_PP_CHeader:
2393     return "cc1";
2394   case types::TY_ObjC: case types::TY_ObjCHeader:
2395   case types::TY_PP_ObjC: case types::TY_PP_ObjCHeader:
2396     return "cc1obj";
2397   case types::TY_CXX: case types::TY_CXXHeader:
2398   case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
2399     return "cc1plus";
2400   case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
2401   case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXXHeader:
2402     return "cc1objplus";
2403   }
2404 }
2405 
getBaseInputName(const ArgList & Args,const InputInfoList & Inputs)2406 const char *darwin::CC1::getBaseInputName(const ArgList &Args,
2407                                           const InputInfoList &Inputs) {
2408   return Args.MakeArgString(
2409     llvm::sys::path::filename(Inputs[0].getBaseInput()));
2410 }
2411 
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)2412 const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
2413                                           const InputInfoList &Inputs) {
2414   const char *Str = getBaseInputName(Args, Inputs);
2415 
2416   if (const char *End = strrchr(Str, '.'))
2417     return Args.MakeArgString(std::string(Str, End));
2418 
2419   return Str;
2420 }
2421 
2422 const char *
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)2423 darwin::CC1::getDependencyFileName(const ArgList &Args,
2424                                    const InputInfoList &Inputs) {
2425   // FIXME: Think about this more.
2426   std::string Res;
2427 
2428   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
2429     std::string Str(OutputOpt->getValue(Args));
2430 
2431     Res = Str.substr(0, Str.rfind('.'));
2432   } else
2433     Res = darwin::CC1::getBaseInputStem(Args, Inputs);
2434 
2435   return Args.MakeArgString(Res + ".d");
2436 }
2437 
AddCC1Args(const ArgList & Args,ArgStringList & CmdArgs) const2438 void darwin::CC1::AddCC1Args(const ArgList &Args,
2439                              ArgStringList &CmdArgs) const {
2440   const Driver &D = getToolChain().getDriver();
2441 
2442   CheckCodeGenerationOptions(D, Args);
2443 
2444   // Derived from cc1 spec.
2445   if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) &&
2446       !Args.hasArg(options::OPT_mdynamic_no_pic))
2447     CmdArgs.push_back("-fPIC");
2448 
2449   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2450       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
2451     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
2452       CmdArgs.push_back("-fno-builtin-strcat");
2453     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
2454       CmdArgs.push_back("-fno-builtin-strcpy");
2455   }
2456 
2457   if (Args.hasArg(options::OPT_g_Flag) &&
2458       !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
2459     CmdArgs.push_back("-feliminate-unused-debug-symbols");
2460 }
2461 
AddCC1OptionsArgs(const ArgList & Args,ArgStringList & CmdArgs,const InputInfoList & Inputs,const ArgStringList & OutputArgs) const2462 void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
2463                                     const InputInfoList &Inputs,
2464                                     const ArgStringList &OutputArgs) const {
2465   const Driver &D = getToolChain().getDriver();
2466 
2467   // Derived from cc1_options spec.
2468   if (Args.hasArg(options::OPT_fast) ||
2469       Args.hasArg(options::OPT_fastf) ||
2470       Args.hasArg(options::OPT_fastcp))
2471     CmdArgs.push_back("-O3");
2472 
2473   if (Arg *A = Args.getLastArg(options::OPT_pg))
2474     if (Args.hasArg(options::OPT_fomit_frame_pointer))
2475       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
2476         << A->getAsString(Args) << "-fomit-frame-pointer";
2477 
2478   AddCC1Args(Args, CmdArgs);
2479 
2480   if (!Args.hasArg(options::OPT_Q))
2481     CmdArgs.push_back("-quiet");
2482 
2483   CmdArgs.push_back("-dumpbase");
2484   CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
2485 
2486   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
2487 
2488   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
2489   Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
2490 
2491   // FIXME: The goal is to use the user provided -o if that is our
2492   // final output, otherwise to drive from the original input
2493   // name. Find a clean way to go about this.
2494   if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
2495       Args.hasArg(options::OPT_o)) {
2496     Arg *OutputOpt = Args.getLastArg(options::OPT_o);
2497     CmdArgs.push_back("-auxbase-strip");
2498     CmdArgs.push_back(OutputOpt->getValue(Args));
2499   } else {
2500     CmdArgs.push_back("-auxbase");
2501     CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
2502   }
2503 
2504   Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
2505 
2506   Args.AddAllArgs(CmdArgs, options::OPT_O);
2507   // FIXME: -Wall is getting some special treatment. Investigate.
2508   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
2509   Args.AddLastArg(CmdArgs, options::OPT_w);
2510   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
2511                   options::OPT_trigraphs);
2512   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2513     // Honor -std-default.
2514     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2515                               "-std=", /*Joined=*/true);
2516   }
2517 
2518   if (Args.hasArg(options::OPT_v))
2519     CmdArgs.push_back("-version");
2520   if (Args.hasArg(options::OPT_pg) &&
2521       getToolChain().SupportsProfiling())
2522     CmdArgs.push_back("-p");
2523   Args.AddLastArg(CmdArgs, options::OPT_p);
2524 
2525   // The driver treats -fsyntax-only specially.
2526   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2527       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
2528     // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
2529     // used to inhibit the default -fno-builtin-str{cat,cpy}.
2530     //
2531     // FIXME: Should we grow a better way to deal with "removing" args?
2532     for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
2533                                                options::OPT_fsyntax_only),
2534            ie = Args.filtered_end(); it != ie; ++it) {
2535       if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) &&
2536           !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) {
2537         (*it)->claim();
2538         (*it)->render(Args, CmdArgs);
2539       }
2540     }
2541   } else
2542     Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
2543 
2544   // Claim Clang only -f options, they aren't worth warning about.
2545   Args.ClaimAllArgs(options::OPT_f_clang_Group);
2546 
2547   Args.AddAllArgs(CmdArgs, options::OPT_undef);
2548   if (Args.hasArg(options::OPT_Qn))
2549     CmdArgs.push_back("-fno-ident");
2550 
2551   // FIXME: This isn't correct.
2552   //Args.AddLastArg(CmdArgs, options::OPT__help)
2553   //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
2554 
2555   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2556 
2557   // FIXME: Still don't get what is happening here. Investigate.
2558   Args.AddAllArgs(CmdArgs, options::OPT__param);
2559 
2560   if (Args.hasArg(options::OPT_fmudflap) ||
2561       Args.hasArg(options::OPT_fmudflapth)) {
2562     CmdArgs.push_back("-fno-builtin");
2563     CmdArgs.push_back("-fno-merge-constants");
2564   }
2565 
2566   if (Args.hasArg(options::OPT_coverage)) {
2567     CmdArgs.push_back("-fprofile-arcs");
2568     CmdArgs.push_back("-ftest-coverage");
2569   }
2570 
2571   if (types::isCXX(Inputs[0].getType()))
2572     CmdArgs.push_back("-D__private_extern__=extern");
2573 }
2574 
AddCPPOptionsArgs(const ArgList & Args,ArgStringList & CmdArgs,const InputInfoList & Inputs,const ArgStringList & OutputArgs) const2575 void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
2576                                     const InputInfoList &Inputs,
2577                                     const ArgStringList &OutputArgs) const {
2578   // Derived from cpp_options
2579   AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
2580 
2581   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2582 
2583   AddCC1Args(Args, CmdArgs);
2584 
2585   // NOTE: The code below has some commonality with cpp_options, but
2586   // in classic gcc style ends up sending things in different
2587   // orders. This may be a good merge candidate once we drop pedantic
2588   // compatibility.
2589 
2590   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
2591   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
2592                   options::OPT_trigraphs);
2593   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2594     // Honor -std-default.
2595     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2596                               "-std=", /*Joined=*/true);
2597   }
2598   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
2599   Args.AddLastArg(CmdArgs, options::OPT_w);
2600 
2601   // The driver treats -fsyntax-only specially.
2602   Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
2603 
2604   // Claim Clang only -f options, they aren't worth warning about.
2605   Args.ClaimAllArgs(options::OPT_f_clang_Group);
2606 
2607   if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
2608       !Args.hasArg(options::OPT_fno_working_directory))
2609     CmdArgs.push_back("-fworking-directory");
2610 
2611   Args.AddAllArgs(CmdArgs, options::OPT_O);
2612   Args.AddAllArgs(CmdArgs, options::OPT_undef);
2613   if (Args.hasArg(options::OPT_save_temps))
2614     CmdArgs.push_back("-fpch-preprocess");
2615 }
2616 
AddCPPUniqueOptionsArgs(const ArgList & Args,ArgStringList & CmdArgs,const InputInfoList & Inputs) const2617 void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
2618                                           ArgStringList &CmdArgs,
2619                                           const InputInfoList &Inputs) const {
2620   const Driver &D = getToolChain().getDriver();
2621 
2622   CheckPreprocessingOptions(D, Args);
2623 
2624   // Derived from cpp_unique_options.
2625   // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
2626   Args.AddLastArg(CmdArgs, options::OPT_C);
2627   Args.AddLastArg(CmdArgs, options::OPT_CC);
2628   if (!Args.hasArg(options::OPT_Q))
2629     CmdArgs.push_back("-quiet");
2630   Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
2631   Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
2632   Args.AddLastArg(CmdArgs, options::OPT_v);
2633   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
2634   Args.AddLastArg(CmdArgs, options::OPT_P);
2635 
2636   // FIXME: Handle %I properly.
2637   if (getToolChain().getArchName() == "x86_64") {
2638     CmdArgs.push_back("-imultilib");
2639     CmdArgs.push_back("x86_64");
2640   }
2641 
2642   if (Args.hasArg(options::OPT_MD)) {
2643     CmdArgs.push_back("-MD");
2644     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
2645   }
2646 
2647   if (Args.hasArg(options::OPT_MMD)) {
2648     CmdArgs.push_back("-MMD");
2649     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
2650   }
2651 
2652   Args.AddLastArg(CmdArgs, options::OPT_M);
2653   Args.AddLastArg(CmdArgs, options::OPT_MM);
2654   Args.AddAllArgs(CmdArgs, options::OPT_MF);
2655   Args.AddLastArg(CmdArgs, options::OPT_MG);
2656   Args.AddLastArg(CmdArgs, options::OPT_MP);
2657   Args.AddAllArgs(CmdArgs, options::OPT_MQ);
2658   Args.AddAllArgs(CmdArgs, options::OPT_MT);
2659   if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
2660       (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
2661     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
2662       CmdArgs.push_back("-MQ");
2663       CmdArgs.push_back(OutputOpt->getValue(Args));
2664     }
2665   }
2666 
2667   Args.AddLastArg(CmdArgs, options::OPT_remap);
2668   if (Args.hasArg(options::OPT_g3))
2669     CmdArgs.push_back("-dD");
2670   Args.AddLastArg(CmdArgs, options::OPT_H);
2671 
2672   AddCPPArgs(Args, CmdArgs);
2673 
2674   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
2675   Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
2676 
2677   for (InputInfoList::const_iterator
2678          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2679     const InputInfo &II = *it;
2680 
2681     CmdArgs.push_back(II.getFilename());
2682   }
2683 
2684   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
2685                        options::OPT_Xpreprocessor);
2686 
2687   if (Args.hasArg(options::OPT_fmudflap)) {
2688     CmdArgs.push_back("-D_MUDFLAP");
2689     CmdArgs.push_back("-include");
2690     CmdArgs.push_back("mf-runtime.h");
2691   }
2692 
2693   if (Args.hasArg(options::OPT_fmudflapth)) {
2694     CmdArgs.push_back("-D_MUDFLAP");
2695     CmdArgs.push_back("-D_MUDFLAPTH");
2696     CmdArgs.push_back("-include");
2697     CmdArgs.push_back("mf-runtime.h");
2698   }
2699 }
2700 
AddCPPArgs(const ArgList & Args,ArgStringList & CmdArgs) const2701 void darwin::CC1::AddCPPArgs(const ArgList &Args,
2702                              ArgStringList &CmdArgs) const {
2703   // Derived from cpp spec.
2704 
2705   if (Args.hasArg(options::OPT_static)) {
2706     // The gcc spec is broken here, it refers to dynamic but
2707     // that has been translated. Start by being bug compatible.
2708 
2709     // if (!Args.hasArg(arglist.parser.dynamicOption))
2710     CmdArgs.push_back("-D__STATIC__");
2711   } else
2712     CmdArgs.push_back("-D__DYNAMIC__");
2713 
2714   if (Args.hasArg(options::OPT_pthread))
2715     CmdArgs.push_back("-D_REENTRANT");
2716 }
2717 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const2718 void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
2719                                       const InputInfo &Output,
2720                                       const InputInfoList &Inputs,
2721                                       const ArgList &Args,
2722                                       const char *LinkingOutput) const {
2723   ArgStringList CmdArgs;
2724 
2725   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
2726 
2727   CmdArgs.push_back("-E");
2728 
2729   if (Args.hasArg(options::OPT_traditional) ||
2730       Args.hasArg(options::OPT_traditional_cpp))
2731     CmdArgs.push_back("-traditional-cpp");
2732 
2733   ArgStringList OutputArgs;
2734   assert(Output.isFilename() && "Unexpected CC1 output.");
2735   OutputArgs.push_back("-o");
2736   OutputArgs.push_back(Output.getFilename());
2737 
2738   if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) {
2739     AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2740   } else {
2741     AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2742     CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2743   }
2744 
2745   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
2746 
2747   const char *CC1Name = getCC1Name(Inputs[0].getType());
2748   const char *Exec =
2749     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
2750   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2751 }
2752 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const2753 void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
2754                                    const InputInfo &Output,
2755                                    const InputInfoList &Inputs,
2756                                    const ArgList &Args,
2757                                    const char *LinkingOutput) const {
2758   const Driver &D = getToolChain().getDriver();
2759   ArgStringList CmdArgs;
2760 
2761   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
2762 
2763   types::ID InputType = Inputs[0].getType();
2764   const Arg *A;
2765   if ((A = Args.getLastArg(options::OPT_traditional)))
2766     D.Diag(clang::diag::err_drv_argument_only_allowed_with)
2767       << A->getAsString(Args) << "-E";
2768 
2769   if (JA.getType() == types::TY_LLVM_IR ||
2770       JA.getType() == types::TY_LTO_IR)
2771     CmdArgs.push_back("-emit-llvm");
2772   else if (JA.getType() == types::TY_LLVM_BC ||
2773            JA.getType() == types::TY_LTO_BC)
2774     CmdArgs.push_back("-emit-llvm-bc");
2775   else if (Output.getType() == types::TY_AST)
2776     D.Diag(clang::diag::err_drv_no_ast_support)
2777       << getToolChain().getTripleString();
2778   else if (JA.getType() != types::TY_PP_Asm &&
2779            JA.getType() != types::TY_PCH)
2780     D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
2781       << getTypeName(JA.getType());
2782 
2783   ArgStringList OutputArgs;
2784   if (Output.getType() != types::TY_PCH) {
2785     OutputArgs.push_back("-o");
2786     if (Output.isNothing())
2787       OutputArgs.push_back("/dev/null");
2788     else
2789       OutputArgs.push_back(Output.getFilename());
2790   }
2791 
2792   // There is no need for this level of compatibility, but it makes
2793   // diffing easier.
2794   bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
2795                           Args.hasArg(options::OPT_S));
2796 
2797   if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
2798     AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
2799     if (OutputArgsEarly) {
2800       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2801     } else {
2802       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2803       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2804     }
2805   } else {
2806     CmdArgs.push_back("-fpreprocessed");
2807 
2808     for (InputInfoList::const_iterator
2809            it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2810       const InputInfo &II = *it;
2811 
2812       // Reject AST inputs.
2813       if (II.getType() == types::TY_AST) {
2814         D.Diag(clang::diag::err_drv_no_ast_support)
2815           << getToolChain().getTripleString();
2816         return;
2817       }
2818 
2819       CmdArgs.push_back(II.getFilename());
2820     }
2821 
2822     if (OutputArgsEarly) {
2823       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2824     } else {
2825       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2826       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2827     }
2828   }
2829 
2830   if (Output.getType() == types::TY_PCH) {
2831     assert(Output.isFilename() && "Invalid PCH output.");
2832 
2833     CmdArgs.push_back("-o");
2834     // NOTE: gcc uses a temp .s file for this, but there doesn't seem
2835     // to be a good reason.
2836     CmdArgs.push_back("/dev/null");
2837 
2838     CmdArgs.push_back("--output-pch=");
2839     CmdArgs.push_back(Output.getFilename());
2840   }
2841 
2842   const char *CC1Name = getCC1Name(Inputs[0].getType());
2843   const char *Exec =
2844     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
2845   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2846 }
2847 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const2848 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2849                                     const InputInfo &Output,
2850                                     const InputInfoList &Inputs,
2851                                     const ArgList &Args,
2852                                     const char *LinkingOutput) const {
2853   ArgStringList CmdArgs;
2854 
2855   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
2856   const InputInfo &Input = Inputs[0];
2857 
2858   // Determine the original source input.
2859   const Action *SourceAction = &JA;
2860   while (SourceAction->getKind() != Action::InputClass) {
2861     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
2862     SourceAction = SourceAction->getInputs()[0];
2863   }
2864 
2865   // Forward -g, assuming we are dealing with an actual assembly file.
2866   if (SourceAction->getType() == types::TY_Asm ||
2867       SourceAction->getType() == types::TY_PP_Asm) {
2868     if (Args.hasArg(options::OPT_gstabs))
2869       CmdArgs.push_back("--gstabs");
2870     else if (Args.hasArg(options::OPT_g_Group))
2871       CmdArgs.push_back("--gdwarf2");
2872   }
2873 
2874   // Derived from asm spec.
2875   AddDarwinArch(Args, CmdArgs);
2876 
2877   // Use -force_cpusubtype_ALL on x86 by default.
2878   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
2879       getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
2880       Args.hasArg(options::OPT_force__cpusubtype__ALL))
2881     CmdArgs.push_back("-force_cpusubtype_ALL");
2882 
2883   if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
2884       (Args.hasArg(options::OPT_mkernel) ||
2885        Args.hasArg(options::OPT_static) ||
2886        Args.hasArg(options::OPT_fapple_kext)))
2887     CmdArgs.push_back("-static");
2888 
2889   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2890                        options::OPT_Xassembler);
2891 
2892   assert(Output.isFilename() && "Unexpected lipo output.");
2893   CmdArgs.push_back("-o");
2894   CmdArgs.push_back(Output.getFilename());
2895 
2896   assert(Input.isFilename() && "Invalid input.");
2897   CmdArgs.push_back(Input.getFilename());
2898 
2899   // asm_final spec is empty.
2900 
2901   const char *Exec =
2902     Args.MakeArgString(getToolChain().GetProgramPath("as"));
2903   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2904 }
2905 
AddDarwinArch(const ArgList & Args,ArgStringList & CmdArgs) const2906 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
2907                                        ArgStringList &CmdArgs) const {
2908   llvm::StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
2909 
2910   // Derived from darwin_arch spec.
2911   CmdArgs.push_back("-arch");
2912   CmdArgs.push_back(Args.MakeArgString(ArchName));
2913 
2914   // FIXME: Is this needed anymore?
2915   if (ArchName == "arm")
2916     CmdArgs.push_back("-force_cpusubtype_ALL");
2917 }
2918 
AddLinkArgs(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs) const2919 void darwin::Link::AddLinkArgs(Compilation &C,
2920                                const ArgList &Args,
2921                                ArgStringList &CmdArgs) const {
2922   const Driver &D = getToolChain().getDriver();
2923   const toolchains::Darwin &DarwinTC = getDarwinToolChain();
2924 
2925   unsigned Version[3] = { 0, 0, 0 };
2926   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2927     bool HadExtra;
2928     if (!Driver::GetReleaseVersion(A->getValue(Args), Version[0],
2929                                    Version[1], Version[2], HadExtra) ||
2930         HadExtra)
2931       D.Diag(clang::diag::err_drv_invalid_version_number)
2932         << A->getAsString(Args);
2933   }
2934 
2935   // Newer linkers support -demangle, pass it if supported and not disabled by
2936   // the user.
2937   //
2938   // FIXME: We temporarily avoid passing -demangle to any iOS linker, because
2939   // unfortunately we can't be guaranteed that the linker version used there
2940   // will match the linker version detected at configure time. We need the
2941   // universal driver.
2942   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle) &&
2943       !DarwinTC.isTargetIPhoneOS()) {
2944     // Don't pass -demangle to ld_classic.
2945     //
2946     // FIXME: This is a temporary workaround, ld should be handling this.
2947     bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
2948                           Args.hasArg(options::OPT_static));
2949     if (getToolChain().getArch() == llvm::Triple::x86) {
2950       for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
2951                                                  options::OPT_Wl_COMMA),
2952              ie = Args.filtered_end(); it != ie; ++it) {
2953         const Arg *A = *it;
2954         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
2955           if (llvm::StringRef(A->getValue(Args, i)) == "-kext")
2956             UsesLdClassic = true;
2957       }
2958     }
2959     if (!UsesLdClassic)
2960       CmdArgs.push_back("-demangle");
2961   }
2962 
2963   // If we are using LTO, then automatically create a temporary file path for
2964   // the linker to use, so that it's lifetime will extend past a possible
2965   // dsymutil step.
2966   if (Version[0] >= 116 && D.IsUsingLTO(Args)) {
2967     const char *TmpPath = C.getArgs().MakeArgString(
2968       D.GetTemporaryPath(types::getTypeTempSuffix(types::TY_Object)));
2969     C.addTempFile(TmpPath);
2970     CmdArgs.push_back("-object_path_lto");
2971     CmdArgs.push_back(TmpPath);
2972   }
2973 
2974   // Derived from the "link" spec.
2975   Args.AddAllArgs(CmdArgs, options::OPT_static);
2976   if (!Args.hasArg(options::OPT_static))
2977     CmdArgs.push_back("-dynamic");
2978   if (Args.hasArg(options::OPT_fgnu_runtime)) {
2979     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
2980     // here. How do we wish to handle such things?
2981   }
2982 
2983   if (!Args.hasArg(options::OPT_dynamiclib)) {
2984     AddDarwinArch(Args, CmdArgs);
2985     // FIXME: Why do this only on this path?
2986     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
2987 
2988     Args.AddLastArg(CmdArgs, options::OPT_bundle);
2989     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
2990     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
2991 
2992     Arg *A;
2993     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
2994         (A = Args.getLastArg(options::OPT_current__version)) ||
2995         (A = Args.getLastArg(options::OPT_install__name)))
2996       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
2997         << A->getAsString(Args) << "-dynamiclib";
2998 
2999     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
3000     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
3001     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
3002   } else {
3003     CmdArgs.push_back("-dylib");
3004 
3005     Arg *A;
3006     if ((A = Args.getLastArg(options::OPT_bundle)) ||
3007         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
3008         (A = Args.getLastArg(options::OPT_client__name)) ||
3009         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
3010         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
3011         (A = Args.getLastArg(options::OPT_private__bundle)))
3012       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
3013         << A->getAsString(Args) << "-dynamiclib";
3014 
3015     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
3016                               "-dylib_compatibility_version");
3017     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
3018                               "-dylib_current_version");
3019 
3020     AddDarwinArch(Args, CmdArgs);
3021 
3022     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
3023                               "-dylib_install_name");
3024   }
3025 
3026   Args.AddLastArg(CmdArgs, options::OPT_all__load);
3027   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
3028   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
3029   if (DarwinTC.isTargetIPhoneOS())
3030     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
3031   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
3032   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
3033   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
3034   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
3035   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
3036   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
3037   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
3038   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
3039   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
3040   Args.AddAllArgs(CmdArgs, options::OPT_init);
3041 
3042   // Add the deployment target.
3043   unsigned TargetVersion[3];
3044   DarwinTC.getTargetVersion(TargetVersion);
3045 
3046   // If we had an explicit -mios-simulator-version-min argument, honor that,
3047   // otherwise use the traditional deployment targets. We can't just check the
3048   // is-sim attribute because existing code follows this path, and the linker
3049   // may not handle the argument.
3050   //
3051   // FIXME: We may be able to remove this, once we can verify no one depends on
3052   // it.
3053   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
3054     CmdArgs.push_back("-ios_simulator_version_min");
3055   else if (DarwinTC.isTargetIPhoneOS())
3056     CmdArgs.push_back("-iphoneos_version_min");
3057   else
3058     CmdArgs.push_back("-macosx_version_min");
3059   CmdArgs.push_back(Args.MakeArgString(llvm::Twine(TargetVersion[0]) + "." +
3060                                        llvm::Twine(TargetVersion[1]) + "." +
3061                                        llvm::Twine(TargetVersion[2])));
3062 
3063   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
3064   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
3065   Args.AddLastArg(CmdArgs, options::OPT_single__module);
3066   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
3067   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
3068 
3069   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
3070                                      options::OPT_fno_pie,
3071                                      options::OPT_fno_PIE)) {
3072     if (A->getOption().matches(options::OPT_fpie) ||
3073         A->getOption().matches(options::OPT_fPIE))
3074       CmdArgs.push_back("-pie");
3075     else
3076       CmdArgs.push_back("-no_pie");
3077   }
3078 
3079   Args.AddLastArg(CmdArgs, options::OPT_prebind);
3080   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
3081   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
3082   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
3083   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
3084   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
3085   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
3086   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
3087   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
3088   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
3089   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
3090   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
3091   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
3092   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
3093   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
3094   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
3095 
3096   // Give --sysroot= preference, over the Apple specific behavior to also use
3097   // --isysroot as the syslibroot.
3098   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) {
3099     CmdArgs.push_back("-syslibroot");
3100     CmdArgs.push_back(A->getValue(Args));
3101   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
3102     CmdArgs.push_back("-syslibroot");
3103     CmdArgs.push_back(A->getValue(Args));
3104   } else if (getDarwinToolChain().isTargetIPhoneOS()) {
3105     CmdArgs.push_back("-syslibroot");
3106     CmdArgs.push_back("/Developer/SDKs/Extra");
3107   }
3108 
3109   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
3110   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
3111   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
3112   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
3113   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
3114   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
3115   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
3116   Args.AddAllArgs(CmdArgs, options::OPT_y);
3117   Args.AddLastArg(CmdArgs, options::OPT_w);
3118   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
3119   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
3120   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
3121   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
3122   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
3123   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
3124   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
3125   Args.AddLastArg(CmdArgs, options::OPT_whyload);
3126   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
3127   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
3128   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
3129   Args.AddLastArg(CmdArgs, options::OPT_Mach);
3130 }
3131 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3132 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
3133                                 const InputInfo &Output,
3134                                 const InputInfoList &Inputs,
3135                                 const ArgList &Args,
3136                                 const char *LinkingOutput) const {
3137   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
3138 
3139   // The logic here is derived from gcc's behavior; most of which
3140   // comes from specs (starting with link_command). Consult gcc for
3141   // more information.
3142   ArgStringList CmdArgs;
3143 
3144   // I'm not sure why this particular decomposition exists in gcc, but
3145   // we follow suite for ease of comparison.
3146   AddLinkArgs(C, Args, CmdArgs);
3147 
3148   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
3149   Args.AddAllArgs(CmdArgs, options::OPT_s);
3150   Args.AddAllArgs(CmdArgs, options::OPT_t);
3151   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
3152   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
3153   Args.AddAllArgs(CmdArgs, options::OPT_A);
3154   Args.AddLastArg(CmdArgs, options::OPT_e);
3155   Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
3156   Args.AddAllArgs(CmdArgs, options::OPT_r);
3157 
3158   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
3159   // members of static archive libraries which implement Objective-C classes or
3160   // categories.
3161   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
3162     CmdArgs.push_back("-ObjC");
3163 
3164   CmdArgs.push_back("-o");
3165   CmdArgs.push_back(Output.getFilename());
3166 
3167   if (!Args.hasArg(options::OPT_A) &&
3168       !Args.hasArg(options::OPT_nostdlib) &&
3169       !Args.hasArg(options::OPT_nostartfiles)) {
3170     // Derived from startfile spec.
3171     if (Args.hasArg(options::OPT_dynamiclib)) {
3172       // Derived from darwin_dylib1 spec.
3173       if (getDarwinToolChain().isTargetIOSSimulator()) {
3174         // The simulator doesn't have a versioned crt1 file.
3175         CmdArgs.push_back("-ldylib1.o");
3176       } else if (getDarwinToolChain().isTargetIPhoneOS()) {
3177         if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
3178           CmdArgs.push_back("-ldylib1.o");
3179       } else {
3180         if (getDarwinToolChain().isMacosxVersionLT(10, 5))
3181           CmdArgs.push_back("-ldylib1.o");
3182         else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
3183           CmdArgs.push_back("-ldylib1.10.5.o");
3184       }
3185     } else {
3186       if (Args.hasArg(options::OPT_bundle)) {
3187         if (!Args.hasArg(options::OPT_static)) {
3188           // Derived from darwin_bundle1 spec.
3189           if (getDarwinToolChain().isTargetIOSSimulator()) {
3190             // The simulator doesn't have a versioned crt1 file.
3191             CmdArgs.push_back("-lbundle1.o");
3192           } else if (getDarwinToolChain().isTargetIPhoneOS()) {
3193             if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
3194               CmdArgs.push_back("-lbundle1.o");
3195           } else {
3196             if (getDarwinToolChain().isMacosxVersionLT(10, 6))
3197               CmdArgs.push_back("-lbundle1.o");
3198           }
3199         }
3200       } else {
3201         if (Args.hasArg(options::OPT_pg) &&
3202             getToolChain().SupportsProfiling()) {
3203           if (Args.hasArg(options::OPT_static) ||
3204               Args.hasArg(options::OPT_object) ||
3205               Args.hasArg(options::OPT_preload)) {
3206             CmdArgs.push_back("-lgcrt0.o");
3207           } else {
3208             CmdArgs.push_back("-lgcrt1.o");
3209 
3210             // darwin_crt2 spec is empty.
3211           }
3212         } else {
3213           if (Args.hasArg(options::OPT_static) ||
3214               Args.hasArg(options::OPT_object) ||
3215               Args.hasArg(options::OPT_preload)) {
3216             CmdArgs.push_back("-lcrt0.o");
3217           } else {
3218             // Derived from darwin_crt1 spec.
3219             if (getDarwinToolChain().isTargetIOSSimulator()) {
3220               // The simulator doesn't have a versioned crt1 file.
3221               CmdArgs.push_back("-lcrt1.o");
3222             } else if (getDarwinToolChain().isTargetIPhoneOS()) {
3223               if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
3224                 CmdArgs.push_back("-lcrt1.o");
3225               else
3226                 CmdArgs.push_back("-lcrt1.3.1.o");
3227             } else {
3228               if (getDarwinToolChain().isMacosxVersionLT(10, 5))
3229                 CmdArgs.push_back("-lcrt1.o");
3230               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
3231                 CmdArgs.push_back("-lcrt1.10.5.o");
3232               else
3233                 CmdArgs.push_back("-lcrt1.10.6.o");
3234 
3235               // darwin_crt2 spec is empty.
3236             }
3237           }
3238         }
3239       }
3240     }
3241 
3242     if (!getDarwinToolChain().isTargetIPhoneOS() &&
3243         Args.hasArg(options::OPT_shared_libgcc) &&
3244         getDarwinToolChain().isMacosxVersionLT(10, 5)) {
3245       const char *Str =
3246         Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
3247       CmdArgs.push_back(Str);
3248     }
3249   }
3250 
3251   Args.AddAllArgs(CmdArgs, options::OPT_L);
3252 
3253   if (Args.hasArg(options::OPT_fopenmp))
3254     // This is more complicated in gcc...
3255     CmdArgs.push_back("-lgomp");
3256 
3257   getDarwinToolChain().AddLinkSearchPathArgs(Args, CmdArgs);
3258 
3259   // In ARC, if we don't have runtime support, link in the runtime
3260   // stubs.  We have to do this *before* adding any of the normal
3261   // linker inputs so that its initializer gets run first.
3262   if (isObjCAutoRefCount(Args)) {
3263     ObjCRuntime runtime;
3264     getDarwinToolChain().configureObjCRuntime(runtime);
3265     if (!runtime.HasARC)
3266       getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
3267   }
3268 
3269   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3270 
3271   if (LinkingOutput) {
3272     CmdArgs.push_back("-arch_multiple");
3273     CmdArgs.push_back("-final_output");
3274     CmdArgs.push_back(LinkingOutput);
3275   }
3276 
3277   if (Args.hasArg(options::OPT_fnested_functions))
3278     CmdArgs.push_back("-allow_stack_execute");
3279 
3280   if (!Args.hasArg(options::OPT_nostdlib) &&
3281       !Args.hasArg(options::OPT_nodefaultlibs)) {
3282     if (getToolChain().getDriver().CCCIsCXX)
3283       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3284 
3285     // link_ssp spec is empty.
3286 
3287     // Let the tool chain choose which runtime library to link.
3288     getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
3289   }
3290 
3291   if (!Args.hasArg(options::OPT_A) &&
3292       !Args.hasArg(options::OPT_nostdlib) &&
3293       !Args.hasArg(options::OPT_nostartfiles)) {
3294     // endfile_spec is empty.
3295   }
3296 
3297   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
3298 
3299   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3300   Args.AddAllArgs(CmdArgs, options::OPT_F);
3301 
3302   const char *Exec =
3303     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3304   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3305 }
3306 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3307 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
3308                                 const InputInfo &Output,
3309                                 const InputInfoList &Inputs,
3310                                 const ArgList &Args,
3311                                 const char *LinkingOutput) const {
3312   ArgStringList CmdArgs;
3313 
3314   CmdArgs.push_back("-create");
3315   assert(Output.isFilename() && "Unexpected lipo output.");
3316 
3317   CmdArgs.push_back("-output");
3318   CmdArgs.push_back(Output.getFilename());
3319 
3320   for (InputInfoList::const_iterator
3321          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3322     const InputInfo &II = *it;
3323     assert(II.isFilename() && "Unexpected lipo input.");
3324     CmdArgs.push_back(II.getFilename());
3325   }
3326   const char *Exec =
3327     Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
3328   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3329 }
3330 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3331 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
3332                                     const InputInfo &Output,
3333                                     const InputInfoList &Inputs,
3334                                     const ArgList &Args,
3335                                     const char *LinkingOutput) const {
3336   ArgStringList CmdArgs;
3337 
3338   CmdArgs.push_back("-o");
3339   CmdArgs.push_back(Output.getFilename());
3340 
3341   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
3342   const InputInfo &Input = Inputs[0];
3343   assert(Input.isFilename() && "Unexpected dsymutil input.");
3344   CmdArgs.push_back(Input.getFilename());
3345 
3346   const char *Exec =
3347     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
3348   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3349 }
3350 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3351 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3352                                       const InputInfo &Output,
3353                                       const InputInfoList &Inputs,
3354                                       const ArgList &Args,
3355                                       const char *LinkingOutput) const {
3356   ArgStringList CmdArgs;
3357 
3358   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3359                        options::OPT_Xassembler);
3360 
3361   CmdArgs.push_back("-o");
3362   CmdArgs.push_back(Output.getFilename());
3363 
3364   for (InputInfoList::const_iterator
3365          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3366     const InputInfo &II = *it;
3367     CmdArgs.push_back(II.getFilename());
3368   }
3369 
3370   const char *Exec =
3371     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
3372   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3373 }
3374 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3375 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
3376                                   const InputInfo &Output,
3377                                   const InputInfoList &Inputs,
3378                                   const ArgList &Args,
3379                                   const char *LinkingOutput) const {
3380   ArgStringList CmdArgs;
3381 
3382   if ((!Args.hasArg(options::OPT_nostdlib)) &&
3383       (!Args.hasArg(options::OPT_shared))) {
3384     CmdArgs.push_back("-e");
3385     CmdArgs.push_back("_start");
3386   }
3387 
3388   if (Args.hasArg(options::OPT_static)) {
3389     CmdArgs.push_back("-Bstatic");
3390     CmdArgs.push_back("-dn");
3391   } else {
3392 //    CmdArgs.push_back("--eh-frame-hdr");
3393     CmdArgs.push_back("-Bdynamic");
3394     if (Args.hasArg(options::OPT_shared)) {
3395       CmdArgs.push_back("-shared");
3396     } else {
3397       CmdArgs.push_back("--dynamic-linker");
3398       CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
3399     }
3400   }
3401 
3402   if (Output.isFilename()) {
3403     CmdArgs.push_back("-o");
3404     CmdArgs.push_back(Output.getFilename());
3405   } else {
3406     assert(Output.isNothing() && "Invalid output.");
3407   }
3408 
3409   if (!Args.hasArg(options::OPT_nostdlib) &&
3410       !Args.hasArg(options::OPT_nostartfiles)) {
3411     if (!Args.hasArg(options::OPT_shared)) {
3412       CmdArgs.push_back(Args.MakeArgString(
3413                                 getToolChain().GetFilePath("crt1.o")));
3414       CmdArgs.push_back(Args.MakeArgString(
3415                                 getToolChain().GetFilePath("crti.o")));
3416       CmdArgs.push_back(Args.MakeArgString(
3417                                 getToolChain().GetFilePath("crtbegin.o")));
3418     } else {
3419       CmdArgs.push_back(Args.MakeArgString(
3420                                 getToolChain().GetFilePath("crti.o")));
3421     }
3422     CmdArgs.push_back(Args.MakeArgString(
3423                                 getToolChain().GetFilePath("crtn.o")));
3424   }
3425 
3426   CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
3427                                        + getToolChain().getTripleString()
3428                                        + "/4.2.4"));
3429 
3430   Args.AddAllArgs(CmdArgs, options::OPT_L);
3431   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3432   Args.AddAllArgs(CmdArgs, options::OPT_e);
3433 
3434   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3435 
3436   if (!Args.hasArg(options::OPT_nostdlib) &&
3437       !Args.hasArg(options::OPT_nodefaultlibs)) {
3438     // FIXME: For some reason GCC passes -lgcc before adding
3439     // the default system libraries. Just mimic this for now.
3440     CmdArgs.push_back("-lgcc");
3441 
3442     if (Args.hasArg(options::OPT_pthread))
3443       CmdArgs.push_back("-pthread");
3444     if (!Args.hasArg(options::OPT_shared))
3445       CmdArgs.push_back("-lc");
3446     CmdArgs.push_back("-lgcc");
3447   }
3448 
3449   if (!Args.hasArg(options::OPT_nostdlib) &&
3450       !Args.hasArg(options::OPT_nostartfiles)) {
3451     if (!Args.hasArg(options::OPT_shared))
3452       CmdArgs.push_back(Args.MakeArgString(
3453                                 getToolChain().GetFilePath("crtend.o")));
3454   }
3455 
3456   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
3457 
3458   const char *Exec =
3459     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3460   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3461 }
3462 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3463 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3464                                      const InputInfo &Output,
3465                                      const InputInfoList &Inputs,
3466                                      const ArgList &Args,
3467                                      const char *LinkingOutput) const {
3468   ArgStringList CmdArgs;
3469 
3470   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3471                        options::OPT_Xassembler);
3472 
3473   CmdArgs.push_back("-o");
3474   CmdArgs.push_back(Output.getFilename());
3475 
3476   for (InputInfoList::const_iterator
3477          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3478     const InputInfo &II = *it;
3479     CmdArgs.push_back(II.getFilename());
3480   }
3481 
3482   const char *Exec =
3483     Args.MakeArgString(getToolChain().GetProgramPath("as"));
3484   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3485 }
3486 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3487 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3488                                  const InputInfo &Output,
3489                                  const InputInfoList &Inputs,
3490                                  const ArgList &Args,
3491                                  const char *LinkingOutput) const {
3492   const Driver &D = getToolChain().getDriver();
3493   ArgStringList CmdArgs;
3494 
3495   if ((!Args.hasArg(options::OPT_nostdlib)) &&
3496       (!Args.hasArg(options::OPT_shared))) {
3497     CmdArgs.push_back("-e");
3498     CmdArgs.push_back("__start");
3499   }
3500 
3501   if (Args.hasArg(options::OPT_static)) {
3502     CmdArgs.push_back("-Bstatic");
3503   } else {
3504     if (Args.hasArg(options::OPT_rdynamic))
3505       CmdArgs.push_back("-export-dynamic");
3506     CmdArgs.push_back("--eh-frame-hdr");
3507     CmdArgs.push_back("-Bdynamic");
3508     if (Args.hasArg(options::OPT_shared)) {
3509       CmdArgs.push_back("-shared");
3510     } else {
3511       CmdArgs.push_back("-dynamic-linker");
3512       CmdArgs.push_back("/usr/libexec/ld.so");
3513     }
3514   }
3515 
3516   if (Output.isFilename()) {
3517     CmdArgs.push_back("-o");
3518     CmdArgs.push_back(Output.getFilename());
3519   } else {
3520     assert(Output.isNothing() && "Invalid output.");
3521   }
3522 
3523   if (!Args.hasArg(options::OPT_nostdlib) &&
3524       !Args.hasArg(options::OPT_nostartfiles)) {
3525     if (!Args.hasArg(options::OPT_shared)) {
3526       CmdArgs.push_back(Args.MakeArgString(
3527                               getToolChain().GetFilePath("crt0.o")));
3528       CmdArgs.push_back(Args.MakeArgString(
3529                               getToolChain().GetFilePath("crtbegin.o")));
3530     } else {
3531       CmdArgs.push_back(Args.MakeArgString(
3532                               getToolChain().GetFilePath("crtbeginS.o")));
3533     }
3534   }
3535 
3536   std::string Triple = getToolChain().getTripleString();
3537   if (Triple.substr(0, 6) == "x86_64")
3538     Triple.replace(0, 6, "amd64");
3539   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
3540                                        "/4.2.1"));
3541 
3542   Args.AddAllArgs(CmdArgs, options::OPT_L);
3543   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3544   Args.AddAllArgs(CmdArgs, options::OPT_e);
3545 
3546   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3547 
3548   if (!Args.hasArg(options::OPT_nostdlib) &&
3549       !Args.hasArg(options::OPT_nodefaultlibs)) {
3550     if (D.CCCIsCXX) {
3551       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3552       CmdArgs.push_back("-lm");
3553     }
3554 
3555     // FIXME: For some reason GCC passes -lgcc before adding
3556     // the default system libraries. Just mimic this for now.
3557     CmdArgs.push_back("-lgcc");
3558 
3559     if (Args.hasArg(options::OPT_pthread))
3560       CmdArgs.push_back("-lpthread");
3561     if (!Args.hasArg(options::OPT_shared))
3562       CmdArgs.push_back("-lc");
3563     CmdArgs.push_back("-lgcc");
3564   }
3565 
3566   if (!Args.hasArg(options::OPT_nostdlib) &&
3567       !Args.hasArg(options::OPT_nostartfiles)) {
3568     if (!Args.hasArg(options::OPT_shared))
3569       CmdArgs.push_back(Args.MakeArgString(
3570                               getToolChain().GetFilePath("crtend.o")));
3571     else
3572       CmdArgs.push_back(Args.MakeArgString(
3573                               getToolChain().GetFilePath("crtendS.o")));
3574   }
3575 
3576   const char *Exec =
3577     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3578   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3579 }
3580 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3581 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3582                                      const InputInfo &Output,
3583                                      const InputInfoList &Inputs,
3584                                      const ArgList &Args,
3585                                      const char *LinkingOutput) const {
3586   ArgStringList CmdArgs;
3587 
3588   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
3589   // instruct as in the base system to assemble 32-bit code.
3590   if (getToolChain().getArchName() == "i386")
3591     CmdArgs.push_back("--32");
3592 
3593   if (getToolChain().getArchName() == "powerpc")
3594     CmdArgs.push_back("-a32");
3595 
3596   // Set byte order explicitly
3597   if (getToolChain().getArchName() == "mips")
3598     CmdArgs.push_back("-EB");
3599   else if (getToolChain().getArchName() == "mipsel")
3600     CmdArgs.push_back("-EL");
3601 
3602   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3603                        options::OPT_Xassembler);
3604 
3605   CmdArgs.push_back("-o");
3606   CmdArgs.push_back(Output.getFilename());
3607 
3608   for (InputInfoList::const_iterator
3609          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3610     const InputInfo &II = *it;
3611     CmdArgs.push_back(II.getFilename());
3612   }
3613 
3614   const char *Exec =
3615     Args.MakeArgString(getToolChain().GetProgramPath("as"));
3616   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3617 }
3618 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3619 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3620                                  const InputInfo &Output,
3621                                  const InputInfoList &Inputs,
3622                                  const ArgList &Args,
3623                                  const char *LinkingOutput) const {
3624   const Driver &D = getToolChain().getDriver();
3625   ArgStringList CmdArgs;
3626 
3627   if (!D.SysRoot.empty())
3628     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3629 
3630   if (Args.hasArg(options::OPT_static)) {
3631     CmdArgs.push_back("-Bstatic");
3632   } else {
3633     if (Args.hasArg(options::OPT_rdynamic))
3634       CmdArgs.push_back("-export-dynamic");
3635     CmdArgs.push_back("--eh-frame-hdr");
3636     if (Args.hasArg(options::OPT_shared)) {
3637       CmdArgs.push_back("-Bshareable");
3638     } else {
3639       CmdArgs.push_back("-dynamic-linker");
3640       CmdArgs.push_back("/libexec/ld-elf.so.1");
3641     }
3642   }
3643 
3644   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
3645   // instruct ld in the base system to link 32-bit code.
3646   if (getToolChain().getArchName() == "i386") {
3647     CmdArgs.push_back("-m");
3648     CmdArgs.push_back("elf_i386_fbsd");
3649   }
3650 
3651   if (getToolChain().getArchName() == "powerpc") {
3652     CmdArgs.push_back("-m");
3653     CmdArgs.push_back("elf32ppc");
3654   }
3655 
3656   if (Output.isFilename()) {
3657     CmdArgs.push_back("-o");
3658     CmdArgs.push_back(Output.getFilename());
3659   } else {
3660     assert(Output.isNothing() && "Invalid output.");
3661   }
3662 
3663   if (!Args.hasArg(options::OPT_nostdlib) &&
3664       !Args.hasArg(options::OPT_nostartfiles)) {
3665     if (!Args.hasArg(options::OPT_shared)) {
3666       if (Args.hasArg(options::OPT_pg))
3667         CmdArgs.push_back(Args.MakeArgString(
3668                                 getToolChain().GetFilePath("gcrt1.o")));
3669       else
3670         CmdArgs.push_back(Args.MakeArgString(
3671                                 getToolChain().GetFilePath("crt1.o")));
3672       CmdArgs.push_back(Args.MakeArgString(
3673                               getToolChain().GetFilePath("crti.o")));
3674       CmdArgs.push_back(Args.MakeArgString(
3675                               getToolChain().GetFilePath("crtbegin.o")));
3676     } else {
3677       CmdArgs.push_back(Args.MakeArgString(
3678                               getToolChain().GetFilePath("crti.o")));
3679       CmdArgs.push_back(Args.MakeArgString(
3680                               getToolChain().GetFilePath("crtbeginS.o")));
3681     }
3682   }
3683 
3684   Args.AddAllArgs(CmdArgs, options::OPT_L);
3685   const ToolChain::path_list Paths = getToolChain().getFilePaths();
3686   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
3687        i != e; ++i)
3688     CmdArgs.push_back(Args.MakeArgString(llvm::StringRef("-L") + *i));
3689   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3690   Args.AddAllArgs(CmdArgs, options::OPT_e);
3691   Args.AddAllArgs(CmdArgs, options::OPT_s);
3692   Args.AddAllArgs(CmdArgs, options::OPT_t);
3693   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
3694   Args.AddAllArgs(CmdArgs, options::OPT_r);
3695 
3696   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3697 
3698   if (!Args.hasArg(options::OPT_nostdlib) &&
3699       !Args.hasArg(options::OPT_nodefaultlibs)) {
3700     if (D.CCCIsCXX) {
3701       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3702       if (Args.hasArg(options::OPT_pg))
3703         CmdArgs.push_back("-lm_p");
3704       else
3705         CmdArgs.push_back("-lm");
3706     }
3707     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
3708     // the default system libraries. Just mimic this for now.
3709     if (Args.hasArg(options::OPT_pg))
3710       CmdArgs.push_back("-lgcc_p");
3711     else
3712       CmdArgs.push_back("-lgcc");
3713     if (Args.hasArg(options::OPT_static)) {
3714       CmdArgs.push_back("-lgcc_eh");
3715     } else if (Args.hasArg(options::OPT_pg)) {
3716       CmdArgs.push_back("-lgcc_eh_p");
3717     } else {
3718       CmdArgs.push_back("--as-needed");
3719       CmdArgs.push_back("-lgcc_s");
3720       CmdArgs.push_back("--no-as-needed");
3721     }
3722 
3723     if (Args.hasArg(options::OPT_pthread)) {
3724       if (Args.hasArg(options::OPT_pg))
3725         CmdArgs.push_back("-lpthread_p");
3726       else
3727         CmdArgs.push_back("-lpthread");
3728     }
3729 
3730     if (Args.hasArg(options::OPT_pg)) {
3731       if (Args.hasArg(options::OPT_shared))
3732         CmdArgs.push_back("-lc");
3733       else
3734         CmdArgs.push_back("-lc_p");
3735       CmdArgs.push_back("-lgcc_p");
3736     } else {
3737       CmdArgs.push_back("-lc");
3738       CmdArgs.push_back("-lgcc");
3739     }
3740 
3741     if (Args.hasArg(options::OPT_static)) {
3742       CmdArgs.push_back("-lgcc_eh");
3743     } else if (Args.hasArg(options::OPT_pg)) {
3744       CmdArgs.push_back("-lgcc_eh_p");
3745     } else {
3746       CmdArgs.push_back("--as-needed");
3747       CmdArgs.push_back("-lgcc_s");
3748       CmdArgs.push_back("--no-as-needed");
3749     }
3750   }
3751 
3752   if (!Args.hasArg(options::OPT_nostdlib) &&
3753       !Args.hasArg(options::OPT_nostartfiles)) {
3754     if (!Args.hasArg(options::OPT_shared))
3755       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3756                                                                   "crtend.o")));
3757     else
3758       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3759                                                                  "crtendS.o")));
3760     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3761                                                                     "crtn.o")));
3762   }
3763 
3764   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
3765 
3766   const char *Exec =
3767     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3768   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3769 }
3770 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3771 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3772                                      const InputInfo &Output,
3773                                      const InputInfoList &Inputs,
3774                                      const ArgList &Args,
3775                                      const char *LinkingOutput) const {
3776   ArgStringList CmdArgs;
3777 
3778   // When building 32-bit code on NetBSD/amd64, we have to explicitly
3779   // instruct as in the base system to assemble 32-bit code.
3780   if (ToolTriple.getArch() == llvm::Triple::x86_64 &&
3781       getToolChain().getArch() == llvm::Triple::x86)
3782     CmdArgs.push_back("--32");
3783 
3784 
3785   // Set byte order explicitly
3786   if (getToolChain().getArchName() == "mips")
3787     CmdArgs.push_back("-EB");
3788   else if (getToolChain().getArchName() == "mipsel")
3789     CmdArgs.push_back("-EL");
3790 
3791   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3792                        options::OPT_Xassembler);
3793 
3794   CmdArgs.push_back("-o");
3795   CmdArgs.push_back(Output.getFilename());
3796 
3797   for (InputInfoList::const_iterator
3798          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3799     const InputInfo &II = *it;
3800     CmdArgs.push_back(II.getFilename());
3801   }
3802 
3803   const char *Exec = Args.MakeArgString(FindTargetProgramPath(getToolChain(),
3804                                                       ToolTriple.getTriple(),
3805                                                       "as"));
3806   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3807 }
3808 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3809 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3810                                  const InputInfo &Output,
3811                                  const InputInfoList &Inputs,
3812                                  const ArgList &Args,
3813                                  const char *LinkingOutput) const {
3814   const Driver &D = getToolChain().getDriver();
3815   ArgStringList CmdArgs;
3816 
3817   if (!D.SysRoot.empty())
3818     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3819 
3820   if (Args.hasArg(options::OPT_static)) {
3821     CmdArgs.push_back("-Bstatic");
3822   } else {
3823     if (Args.hasArg(options::OPT_rdynamic))
3824       CmdArgs.push_back("-export-dynamic");
3825     CmdArgs.push_back("--eh-frame-hdr");
3826     if (Args.hasArg(options::OPT_shared)) {
3827       CmdArgs.push_back("-Bshareable");
3828     } else {
3829       CmdArgs.push_back("-dynamic-linker");
3830       CmdArgs.push_back("/libexec/ld.elf_so");
3831     }
3832   }
3833 
3834   // When building 32-bit code on NetBSD/amd64, we have to explicitly
3835   // instruct ld in the base system to link 32-bit code.
3836   if (ToolTriple.getArch() == llvm::Triple::x86_64 &&
3837       getToolChain().getArch() == llvm::Triple::x86) {
3838     CmdArgs.push_back("-m");
3839     CmdArgs.push_back("elf_i386");
3840   }
3841 
3842   if (Output.isFilename()) {
3843     CmdArgs.push_back("-o");
3844     CmdArgs.push_back(Output.getFilename());
3845   } else {
3846     assert(Output.isNothing() && "Invalid output.");
3847   }
3848 
3849   if (!Args.hasArg(options::OPT_nostdlib) &&
3850       !Args.hasArg(options::OPT_nostartfiles)) {
3851     if (!Args.hasArg(options::OPT_shared)) {
3852       CmdArgs.push_back(Args.MakeArgString(
3853                               getToolChain().GetFilePath("crt0.o")));
3854       CmdArgs.push_back(Args.MakeArgString(
3855                               getToolChain().GetFilePath("crti.o")));
3856       CmdArgs.push_back(Args.MakeArgString(
3857                               getToolChain().GetFilePath("crtbegin.o")));
3858     } else {
3859       CmdArgs.push_back(Args.MakeArgString(
3860                               getToolChain().GetFilePath("crti.o")));
3861       CmdArgs.push_back(Args.MakeArgString(
3862                               getToolChain().GetFilePath("crtbeginS.o")));
3863     }
3864   }
3865 
3866   Args.AddAllArgs(CmdArgs, options::OPT_L);
3867   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3868   Args.AddAllArgs(CmdArgs, options::OPT_e);
3869   Args.AddAllArgs(CmdArgs, options::OPT_s);
3870   Args.AddAllArgs(CmdArgs, options::OPT_t);
3871   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
3872   Args.AddAllArgs(CmdArgs, options::OPT_r);
3873 
3874   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3875 
3876   if (!Args.hasArg(options::OPT_nostdlib) &&
3877       !Args.hasArg(options::OPT_nodefaultlibs)) {
3878     if (D.CCCIsCXX) {
3879       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3880       CmdArgs.push_back("-lm");
3881     }
3882     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
3883     // the default system libraries. Just mimic this for now.
3884     if (Args.hasArg(options::OPT_static)) {
3885       CmdArgs.push_back("-lgcc_eh");
3886     } else {
3887       CmdArgs.push_back("--as-needed");
3888       CmdArgs.push_back("-lgcc_s");
3889       CmdArgs.push_back("--no-as-needed");
3890     }
3891     CmdArgs.push_back("-lgcc");
3892 
3893     if (Args.hasArg(options::OPT_pthread))
3894       CmdArgs.push_back("-lpthread");
3895     CmdArgs.push_back("-lc");
3896 
3897     CmdArgs.push_back("-lgcc");
3898     if (Args.hasArg(options::OPT_static)) {
3899       CmdArgs.push_back("-lgcc_eh");
3900     } else {
3901       CmdArgs.push_back("--as-needed");
3902       CmdArgs.push_back("-lgcc_s");
3903       CmdArgs.push_back("--no-as-needed");
3904     }
3905   }
3906 
3907   if (!Args.hasArg(options::OPT_nostdlib) &&
3908       !Args.hasArg(options::OPT_nostartfiles)) {
3909     if (!Args.hasArg(options::OPT_shared))
3910       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3911                                                                   "crtend.o")));
3912     else
3913       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3914                                                                  "crtendS.o")));
3915     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3916                                                                     "crtn.o")));
3917   }
3918 
3919   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
3920 
3921   const char *Exec = Args.MakeArgString(FindTargetProgramPath(getToolChain(),
3922                                                       ToolTriple.getTriple(),
3923                                                       "ld"));
3924   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3925 }
3926 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3927 void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3928                                         const InputInfo &Output,
3929                                         const InputInfoList &Inputs,
3930                                         const ArgList &Args,
3931                                         const char *LinkingOutput) const {
3932   ArgStringList CmdArgs;
3933 
3934   // Add --32/--64 to make sure we get the format we want.
3935   // This is incomplete
3936   if (getToolChain().getArch() == llvm::Triple::x86) {
3937     CmdArgs.push_back("--32");
3938   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
3939     CmdArgs.push_back("--64");
3940   } else if (getToolChain().getArch() == llvm::Triple::arm) {
3941     llvm::StringRef MArch = getToolChain().getArchName();
3942     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
3943       CmdArgs.push_back("-mfpu=neon");
3944   }
3945 
3946   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3947                        options::OPT_Xassembler);
3948 
3949   CmdArgs.push_back("-o");
3950   CmdArgs.push_back(Output.getFilename());
3951 
3952   for (InputInfoList::const_iterator
3953          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3954     const InputInfo &II = *it;
3955     CmdArgs.push_back(II.getFilename());
3956   }
3957 
3958   const char *Exec =
3959     Args.MakeArgString(getToolChain().GetProgramPath("as"));
3960   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3961 }
3962 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3963 void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
3964                                     const InputInfo &Output,
3965                                     const InputInfoList &Inputs,
3966                                     const ArgList &Args,
3967                                     const char *LinkingOutput) const {
3968   const toolchains::Linux& ToolChain =
3969     static_cast<const toolchains::Linux&>(getToolChain());
3970   const Driver &D = ToolChain.getDriver();
3971   ArgStringList CmdArgs;
3972 
3973   // Silence warning for "clang -g foo.o -o foo"
3974   Args.ClaimAllArgs(options::OPT_g_Group);
3975   // and "clang -emit-llvm foo.o -o foo"
3976   Args.ClaimAllArgs(options::OPT_emit_llvm);
3977   // and for "clang -g foo.o -o foo". Other warning options are already
3978   // handled somewhere else.
3979   Args.ClaimAllArgs(options::OPT_w);
3980 
3981   if (!D.SysRoot.empty())
3982     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3983 
3984   if (Args.hasArg(options::OPT_pie))
3985     CmdArgs.push_back("-pie");
3986 
3987   if (Args.hasArg(options::OPT_rdynamic))
3988     CmdArgs.push_back("-export-dynamic");
3989 
3990   if (Args.hasArg(options::OPT_s))
3991     CmdArgs.push_back("-s");
3992 
3993   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
3994          e = ToolChain.ExtraOpts.end();
3995        i != e; ++i)
3996     CmdArgs.push_back(i->c_str());
3997 
3998   if (!Args.hasArg(options::OPT_static)) {
3999     CmdArgs.push_back("--eh-frame-hdr");
4000   }
4001 
4002   CmdArgs.push_back("-m");
4003   if (ToolChain.getArch() == llvm::Triple::x86)
4004     CmdArgs.push_back("elf_i386");
4005   else if (ToolChain.getArch() == llvm::Triple::arm
4006            ||  ToolChain.getArch() == llvm::Triple::thumb)
4007     CmdArgs.push_back("armelf_linux_eabi");
4008   else if (ToolChain.getArch() == llvm::Triple::ppc)
4009     CmdArgs.push_back("elf32ppclinux");
4010   else if (ToolChain.getArch() == llvm::Triple::ppc64)
4011     CmdArgs.push_back("elf64ppc");
4012   else
4013     CmdArgs.push_back("elf_x86_64");
4014 
4015   if (Args.hasArg(options::OPT_static)) {
4016     if (ToolChain.getArch() == llvm::Triple::arm
4017         || ToolChain.getArch() == llvm::Triple::thumb)
4018       CmdArgs.push_back("-Bstatic");
4019     else
4020       CmdArgs.push_back("-static");
4021   } else if (Args.hasArg(options::OPT_shared)) {
4022     CmdArgs.push_back("-shared");
4023   }
4024 
4025   if (ToolChain.getArch() == llvm::Triple::arm ||
4026       ToolChain.getArch() == llvm::Triple::thumb ||
4027       (!Args.hasArg(options::OPT_static) &&
4028        !Args.hasArg(options::OPT_shared))) {
4029     CmdArgs.push_back("-dynamic-linker");
4030     if (ToolChain.getArch() == llvm::Triple::x86)
4031       CmdArgs.push_back("/lib/ld-linux.so.2");
4032     else if (ToolChain.getArch() == llvm::Triple::arm ||
4033              ToolChain.getArch() == llvm::Triple::thumb)
4034       CmdArgs.push_back("/lib/ld-linux.so.3");
4035     else if (ToolChain.getArch() == llvm::Triple::ppc)
4036       CmdArgs.push_back("/lib/ld.so.1");
4037     else if (ToolChain.getArch() == llvm::Triple::ppc64)
4038       CmdArgs.push_back("/lib64/ld64.so.1");
4039     else
4040       CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
4041   }
4042 
4043   CmdArgs.push_back("-o");
4044   CmdArgs.push_back(Output.getFilename());
4045 
4046   if (!Args.hasArg(options::OPT_nostdlib) &&
4047       !Args.hasArg(options::OPT_nostartfiles)) {
4048     const char *crt1 = NULL;
4049     if (!Args.hasArg(options::OPT_shared)){
4050       if (Args.hasArg(options::OPT_pie))
4051         crt1 = "Scrt1.o";
4052       else
4053         crt1 = "crt1.o";
4054     }
4055     if (crt1)
4056       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
4057 
4058     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
4059 
4060     const char *crtbegin;
4061     if (Args.hasArg(options::OPT_static))
4062       crtbegin = "crtbeginT.o";
4063     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
4064       crtbegin = "crtbeginS.o";
4065     else
4066       crtbegin = "crtbegin.o";
4067     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
4068   }
4069 
4070   Args.AddAllArgs(CmdArgs, options::OPT_L);
4071 
4072   const ToolChain::path_list Paths = ToolChain.getFilePaths();
4073 
4074   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
4075        i != e; ++i)
4076     CmdArgs.push_back(Args.MakeArgString(llvm::StringRef("-L") + *i));
4077 
4078   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
4079 
4080   if (D.CCCIsCXX && !Args.hasArg(options::OPT_nostdlib)) {
4081     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
4082     CmdArgs.push_back("-lm");
4083   }
4084 
4085   if (!Args.hasArg(options::OPT_nostdlib)) {
4086     if (Args.hasArg(options::OPT_static))
4087       CmdArgs.push_back("--start-group");
4088 
4089     if (!D.CCCIsCXX)
4090       CmdArgs.push_back("-lgcc");
4091 
4092     if (Args.hasArg(options::OPT_static)) {
4093       if (D.CCCIsCXX)
4094         CmdArgs.push_back("-lgcc");
4095     } else {
4096       if (!D.CCCIsCXX)
4097         CmdArgs.push_back("--as-needed");
4098       CmdArgs.push_back("-lgcc_s");
4099       if (!D.CCCIsCXX)
4100         CmdArgs.push_back("--no-as-needed");
4101     }
4102 
4103     if (Args.hasArg(options::OPT_static))
4104       CmdArgs.push_back("-lgcc_eh");
4105     else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
4106       CmdArgs.push_back("-lgcc");
4107 
4108     if (Args.hasArg(options::OPT_pthread) ||
4109         Args.hasArg(options::OPT_pthreads))
4110       CmdArgs.push_back("-lpthread");
4111 
4112     CmdArgs.push_back("-lc");
4113 
4114     if (Args.hasArg(options::OPT_static))
4115       CmdArgs.push_back("--end-group");
4116     else {
4117       if (!D.CCCIsCXX)
4118         CmdArgs.push_back("-lgcc");
4119 
4120       if (!D.CCCIsCXX)
4121         CmdArgs.push_back("--as-needed");
4122       CmdArgs.push_back("-lgcc_s");
4123       if (!D.CCCIsCXX)
4124         CmdArgs.push_back("--no-as-needed");
4125 
4126       if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
4127         CmdArgs.push_back("-lgcc");
4128     }
4129 
4130 
4131     if (!Args.hasArg(options::OPT_nostartfiles)) {
4132       const char *crtend;
4133       if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
4134         crtend = "crtendS.o";
4135       else
4136         crtend = "crtend.o";
4137 
4138       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
4139       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
4140     }
4141   }
4142 
4143   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4144 
4145   if (Args.hasArg(options::OPT_use_gold_plugin)) {
4146     CmdArgs.push_back("-plugin");
4147     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
4148     CmdArgs.push_back(Args.MakeArgString(Plugin));
4149   }
4150 
4151   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
4152 }
4153 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4154 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4155                                    const InputInfo &Output,
4156                                    const InputInfoList &Inputs,
4157                                    const ArgList &Args,
4158                                    const char *LinkingOutput) const {
4159   ArgStringList CmdArgs;
4160 
4161   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4162                        options::OPT_Xassembler);
4163 
4164   CmdArgs.push_back("-o");
4165   CmdArgs.push_back(Output.getFilename());
4166 
4167   for (InputInfoList::const_iterator
4168          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4169     const InputInfo &II = *it;
4170     CmdArgs.push_back(II.getFilename());
4171   }
4172 
4173   const char *Exec =
4174     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
4175   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4176 }
4177 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4178 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
4179                                const InputInfo &Output,
4180                                const InputInfoList &Inputs,
4181                                const ArgList &Args,
4182                                const char *LinkingOutput) const {
4183   const Driver &D = getToolChain().getDriver();
4184   ArgStringList CmdArgs;
4185 
4186   if (Output.isFilename()) {
4187     CmdArgs.push_back("-o");
4188     CmdArgs.push_back(Output.getFilename());
4189   } else {
4190     assert(Output.isNothing() && "Invalid output.");
4191   }
4192 
4193   if (!Args.hasArg(options::OPT_nostdlib) &&
4194       !Args.hasArg(options::OPT_nostartfiles))
4195     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
4196                                                       "/usr/gnu/lib/crtso.o")));
4197 
4198   Args.AddAllArgs(CmdArgs, options::OPT_L);
4199   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4200   Args.AddAllArgs(CmdArgs, options::OPT_e);
4201 
4202   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4203 
4204   if (!Args.hasArg(options::OPT_nostdlib) &&
4205       !Args.hasArg(options::OPT_nodefaultlibs)) {
4206     if (D.CCCIsCXX) {
4207       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4208       CmdArgs.push_back("-lm");
4209     }
4210 
4211     if (Args.hasArg(options::OPT_pthread))
4212       CmdArgs.push_back("-lpthread");
4213     CmdArgs.push_back("-lc");
4214     CmdArgs.push_back("-lgcc");
4215     CmdArgs.push_back("-L/usr/gnu/lib");
4216     // FIXME: fill in the correct search path for the final
4217     // support libraries.
4218     CmdArgs.push_back("-L/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
4219   }
4220 
4221   if (!Args.hasArg(options::OPT_nostdlib) &&
4222       !Args.hasArg(options::OPT_nostartfiles)) {
4223     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
4224                                               "/usr/gnu/lib/libend.a")));
4225   }
4226 
4227   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4228 
4229   const char *Exec =
4230     Args.MakeArgString(getToolChain().GetProgramPath("/usr/gnu/bin/gld"));
4231   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4232 }
4233 
4234 /// DragonFly Tools
4235 
4236 // For now, DragonFly Assemble does just about the same as for
4237 // FreeBSD, but this may change soon.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4238 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4239                                        const InputInfo &Output,
4240                                        const InputInfoList &Inputs,
4241                                        const ArgList &Args,
4242                                        const char *LinkingOutput) const {
4243   ArgStringList CmdArgs;
4244 
4245   // When building 32-bit code on DragonFly/pc64, we have to explicitly
4246   // instruct as in the base system to assemble 32-bit code.
4247   if (getToolChain().getArchName() == "i386")
4248     CmdArgs.push_back("--32");
4249 
4250   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4251                        options::OPT_Xassembler);
4252 
4253   CmdArgs.push_back("-o");
4254   CmdArgs.push_back(Output.getFilename());
4255 
4256   for (InputInfoList::const_iterator
4257          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4258     const InputInfo &II = *it;
4259     CmdArgs.push_back(II.getFilename());
4260   }
4261 
4262   const char *Exec =
4263     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4264   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4265 }
4266 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4267 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
4268                                    const InputInfo &Output,
4269                                    const InputInfoList &Inputs,
4270                                    const ArgList &Args,
4271                                    const char *LinkingOutput) const {
4272   const Driver &D = getToolChain().getDriver();
4273   ArgStringList CmdArgs;
4274 
4275   if (!D.SysRoot.empty())
4276     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
4277 
4278   if (Args.hasArg(options::OPT_static)) {
4279     CmdArgs.push_back("-Bstatic");
4280   } else {
4281     if (Args.hasArg(options::OPT_shared))
4282       CmdArgs.push_back("-Bshareable");
4283     else {
4284       CmdArgs.push_back("-dynamic-linker");
4285       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
4286     }
4287   }
4288 
4289   // When building 32-bit code on DragonFly/pc64, we have to explicitly
4290   // instruct ld in the base system to link 32-bit code.
4291   if (getToolChain().getArchName() == "i386") {
4292     CmdArgs.push_back("-m");
4293     CmdArgs.push_back("elf_i386");
4294   }
4295 
4296   if (Output.isFilename()) {
4297     CmdArgs.push_back("-o");
4298     CmdArgs.push_back(Output.getFilename());
4299   } else {
4300     assert(Output.isNothing() && "Invalid output.");
4301   }
4302 
4303   if (!Args.hasArg(options::OPT_nostdlib) &&
4304       !Args.hasArg(options::OPT_nostartfiles)) {
4305     if (!Args.hasArg(options::OPT_shared)) {
4306       CmdArgs.push_back(
4307             Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
4308       CmdArgs.push_back(
4309             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
4310       CmdArgs.push_back(
4311             Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
4312     } else {
4313       CmdArgs.push_back(
4314             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
4315       CmdArgs.push_back(
4316             Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
4317     }
4318   }
4319 
4320   Args.AddAllArgs(CmdArgs, options::OPT_L);
4321   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4322   Args.AddAllArgs(CmdArgs, options::OPT_e);
4323 
4324   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4325 
4326   if (!Args.hasArg(options::OPT_nostdlib) &&
4327       !Args.hasArg(options::OPT_nodefaultlibs)) {
4328     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
4329     //         rpaths
4330     CmdArgs.push_back("-L/usr/lib/gcc41");
4331 
4332     if (!Args.hasArg(options::OPT_static)) {
4333       CmdArgs.push_back("-rpath");
4334       CmdArgs.push_back("/usr/lib/gcc41");
4335 
4336       CmdArgs.push_back("-rpath-link");
4337       CmdArgs.push_back("/usr/lib/gcc41");
4338 
4339       CmdArgs.push_back("-rpath");
4340       CmdArgs.push_back("/usr/lib");
4341 
4342       CmdArgs.push_back("-rpath-link");
4343       CmdArgs.push_back("/usr/lib");
4344     }
4345 
4346     if (D.CCCIsCXX) {
4347       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4348       CmdArgs.push_back("-lm");
4349     }
4350 
4351     if (Args.hasArg(options::OPT_shared)) {
4352       CmdArgs.push_back("-lgcc_pic");
4353     } else {
4354       CmdArgs.push_back("-lgcc");
4355     }
4356 
4357 
4358     if (Args.hasArg(options::OPT_pthread))
4359       CmdArgs.push_back("-lpthread");
4360 
4361     if (!Args.hasArg(options::OPT_nolibc)) {
4362       CmdArgs.push_back("-lc");
4363     }
4364 
4365     if (Args.hasArg(options::OPT_shared)) {
4366       CmdArgs.push_back("-lgcc_pic");
4367     } else {
4368       CmdArgs.push_back("-lgcc");
4369     }
4370   }
4371 
4372   if (!Args.hasArg(options::OPT_nostdlib) &&
4373       !Args.hasArg(options::OPT_nostartfiles)) {
4374     if (!Args.hasArg(options::OPT_shared))
4375       CmdArgs.push_back(Args.MakeArgString(
4376                               getToolChain().GetFilePath("crtend.o")));
4377     else
4378       CmdArgs.push_back(Args.MakeArgString(
4379                               getToolChain().GetFilePath("crtendS.o")));
4380     CmdArgs.push_back(Args.MakeArgString(
4381                               getToolChain().GetFilePath("crtn.o")));
4382   }
4383 
4384   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4385 
4386   const char *Exec =
4387     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4388   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4389 }
4390 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4391 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
4392                                       const InputInfo &Output,
4393                                       const InputInfoList &Inputs,
4394                                       const ArgList &Args,
4395                                       const char *LinkingOutput) const {
4396   ArgStringList CmdArgs;
4397 
4398   if (Output.isFilename()) {
4399     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
4400                                          Output.getFilename()));
4401   } else {
4402     assert(Output.isNothing() && "Invalid output.");
4403   }
4404 
4405   if (!Args.hasArg(options::OPT_nostdlib) &&
4406     !Args.hasArg(options::OPT_nostartfiles)) {
4407     CmdArgs.push_back("-defaultlib:libcmt");
4408   }
4409 
4410   CmdArgs.push_back("-nologo");
4411 
4412   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4413 
4414   const char *Exec =
4415     Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
4416   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4417 }
4418