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