]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Merge ATF 0.16 from vendor/atf/dist.
[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/Option.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/ToolChain.h"
22 #include "clang/Driver/Util.h"
23 #include "clang/Basic/ObjCRuntime.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 #include "llvm/Support/ErrorHandling.h"
34
35 #include "InputInfo.h"
36 #include "ToolChains.h"
37
38 using namespace clang::driver;
39 using namespace clang::driver::tools;
40 using namespace clang;
41
42 /// CheckPreprocessingOptions - Perform some validation of preprocessing
43 /// arguments that is shared with gcc.
44 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
45   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
46     if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP)
47       D.Diag(diag::err_drv_argument_only_allowed_with)
48         << A->getAsString(Args) << "-E";
49 }
50
51 /// CheckCodeGenerationOptions - Perform some validation of code generation
52 /// arguments that is shared with gcc.
53 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
54   // In gcc, only ARM checks this, but it seems reasonable to check universally.
55   if (Args.hasArg(options::OPT_static))
56     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
57                                        options::OPT_mdynamic_no_pic))
58       D.Diag(diag::err_drv_argument_not_allowed_with)
59         << A->getAsString(Args) << "-static";
60 }
61
62 // Quote target names for inclusion in GNU Make dependency files.
63 // Only the characters '$', '#', ' ', '\t' are quoted.
64 static void QuoteTarget(StringRef Target,
65                         SmallVectorImpl<char> &Res) {
66   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
67     switch (Target[i]) {
68     case ' ':
69     case '\t':
70       // Escape the preceding backslashes
71       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
72         Res.push_back('\\');
73
74       // Escape the space/tab
75       Res.push_back('\\');
76       break;
77     case '$':
78       Res.push_back('$');
79       break;
80     case '#':
81       Res.push_back('\\');
82       break;
83     default:
84       break;
85     }
86
87     Res.push_back(Target[i]);
88   }
89 }
90
91 static void addDirectoryList(const ArgList &Args,
92                              ArgStringList &CmdArgs,
93                              const char *ArgName,
94                              const char *EnvVar) {
95   const char *DirList = ::getenv(EnvVar);
96   if (!DirList)
97     return; // Nothing to do.
98
99   StringRef Dirs(DirList);
100   if (Dirs.empty()) // Empty string should not add '.'.
101     return;
102
103   StringRef::size_type Delim;
104   while ((Delim = Dirs.find(llvm::sys::PathSeparator)) != StringRef::npos) {
105     if (Delim == 0) { // Leading colon.
106       CmdArgs.push_back(ArgName);
107       CmdArgs.push_back(".");
108     } else {
109       CmdArgs.push_back(ArgName);
110       CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
111     }
112     Dirs = Dirs.substr(Delim + 1);
113   }
114
115   if (Dirs.empty()) { // Trailing colon.
116     CmdArgs.push_back(ArgName);
117     CmdArgs.push_back(".");
118   } else { // Add the last path.
119     CmdArgs.push_back(ArgName);
120     CmdArgs.push_back(Args.MakeArgString(Dirs));
121   }
122 }
123
124 static void AddLinkerInputs(const ToolChain &TC,
125                             const InputInfoList &Inputs, const ArgList &Args,
126                             ArgStringList &CmdArgs) {
127   const Driver &D = TC.getDriver();
128
129   // Add extra linker input arguments which are not treated as inputs
130   // (constructed via -Xarch_).
131   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
132
133   for (InputInfoList::const_iterator
134          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
135     const InputInfo &II = *it;
136
137     if (!TC.HasNativeLLVMSupport()) {
138       // Don't try to pass LLVM inputs unless we have native support.
139       if (II.getType() == types::TY_LLVM_IR ||
140           II.getType() == types::TY_LTO_IR ||
141           II.getType() == types::TY_LLVM_BC ||
142           II.getType() == types::TY_LTO_BC)
143         D.Diag(diag::err_drv_no_linker_llvm_support)
144           << TC.getTripleString();
145     }
146
147     // Add filenames immediately.
148     if (II.isFilename()) {
149       CmdArgs.push_back(II.getFilename());
150       continue;
151     }
152
153     // Otherwise, this is a linker input argument.
154     const Arg &A = II.getInputArg();
155
156     // Handle reserved library options.
157     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
158       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
159     } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
160       TC.AddCCKextLibArgs(Args, CmdArgs);
161     } else
162       A.renderAsInput(Args, CmdArgs);
163   }
164
165   // LIBRARY_PATH - included following the user specified library paths.
166   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
167 }
168
169 /// \brief Determine whether Objective-C automated reference counting is
170 /// enabled.
171 static bool isObjCAutoRefCount(const ArgList &Args) {
172   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
173 }
174
175 /// \brief Determine whether we are linking the ObjC runtime.
176 static bool isObjCRuntimeLinked(const ArgList &Args) {
177   if (isObjCAutoRefCount(Args)) {
178     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
179     return true;
180   }
181   return Args.hasArg(options::OPT_fobjc_link_runtime);
182 }
183
184 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
185                          ArgStringList &CmdArgs,
186                          llvm::Triple Triple) {
187   if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
188         Args.hasArg(options::OPT_fprofile_generate) ||
189         Args.hasArg(options::OPT_fcreate_profile) ||
190         Args.hasArg(options::OPT_coverage)))
191     return;
192
193   // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lgcov to
194   // the link line. We cannot do the same thing because unlike gcov there is a
195   // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but that is
196   // not supported by old linkers.
197   std::string ProfileRT =
198     std::string(TC.getDriver().Dir) + "/../lib/libprofile_rt.a";
199
200   CmdArgs.push_back(Args.MakeArgString(ProfileRT));
201 }
202
203 void Clang::AddPreprocessingOptions(Compilation &C,
204                                     const Driver &D,
205                                     const ArgList &Args,
206                                     ArgStringList &CmdArgs,
207                                     const InputInfo &Output,
208                                     const InputInfoList &Inputs) const {
209   Arg *A;
210
211   CheckPreprocessingOptions(D, Args);
212
213   Args.AddLastArg(CmdArgs, options::OPT_C);
214   Args.AddLastArg(CmdArgs, options::OPT_CC);
215
216   // Handle dependency file generation.
217   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
218       (A = Args.getLastArg(options::OPT_MD)) ||
219       (A = Args.getLastArg(options::OPT_MMD))) {
220     // Determine the output location.
221     const char *DepFile;
222     if (Output.getType() == types::TY_Dependencies) {
223       DepFile = Output.getFilename();
224     } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
225       DepFile = MF->getValue(Args);
226       C.addFailureResultFile(DepFile);
227     } else if (A->getOption().matches(options::OPT_M) ||
228                A->getOption().matches(options::OPT_MM)) {
229       DepFile = "-";
230     } else {
231       DepFile = darwin::CC1::getDependencyFileName(Args, Inputs);
232       C.addFailureResultFile(DepFile);
233     }
234     CmdArgs.push_back("-dependency-file");
235     CmdArgs.push_back(DepFile);
236
237     // Add a default target if one wasn't specified.
238     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
239       const char *DepTarget;
240
241       // If user provided -o, that is the dependency target, except
242       // when we are only generating a dependency file.
243       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
244       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
245         DepTarget = OutputOpt->getValue(Args);
246       } else {
247         // Otherwise derive from the base input.
248         //
249         // FIXME: This should use the computed output file location.
250         SmallString<128> P(Inputs[0].getBaseInput());
251         llvm::sys::path::replace_extension(P, "o");
252         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
253       }
254
255       CmdArgs.push_back("-MT");
256       SmallString<128> Quoted;
257       QuoteTarget(DepTarget, Quoted);
258       CmdArgs.push_back(Args.MakeArgString(Quoted));
259     }
260
261     if (A->getOption().matches(options::OPT_M) ||
262         A->getOption().matches(options::OPT_MD))
263       CmdArgs.push_back("-sys-header-deps");
264   }
265
266   if (Args.hasArg(options::OPT_MG)) {
267     if (!A || A->getOption().matches(options::OPT_MD) ||
268               A->getOption().matches(options::OPT_MMD))
269       D.Diag(diag::err_drv_mg_requires_m_or_mm);
270     CmdArgs.push_back("-MG");
271   }
272
273   Args.AddLastArg(CmdArgs, options::OPT_MP);
274
275   // Convert all -MQ <target> args to -MT <quoted target>
276   for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
277                                              options::OPT_MQ),
278          ie = Args.filtered_end(); it != ie; ++it) {
279     const Arg *A = *it;
280     A->claim();
281
282     if (A->getOption().matches(options::OPT_MQ)) {
283       CmdArgs.push_back("-MT");
284       SmallString<128> Quoted;
285       QuoteTarget(A->getValue(Args), Quoted);
286       CmdArgs.push_back(Args.MakeArgString(Quoted));
287
288     // -MT flag - no change
289     } else {
290       A->render(Args, CmdArgs);
291     }
292   }
293
294   // Add -i* options, and automatically translate to
295   // -include-pch/-include-pth for transparent PCH support. It's
296   // wonky, but we include looking for .gch so we can support seamless
297   // replacement into a build system already set up to be generating
298   // .gch files.
299   bool RenderedImplicitInclude = false;
300   for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
301          ie = Args.filtered_end(); it != ie; ++it) {
302     const Arg *A = it;
303
304     if (A->getOption().matches(options::OPT_include)) {
305       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
306       RenderedImplicitInclude = true;
307
308       // Use PCH if the user requested it.
309       bool UsePCH = D.CCCUsePCH;
310
311       bool FoundPTH = false;
312       bool FoundPCH = false;
313       llvm::sys::Path P(A->getValue(Args));
314       bool Exists;
315       if (UsePCH) {
316         P.appendSuffix("pch");
317         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
318           FoundPCH = true;
319         else
320           P.eraseSuffix();
321       }
322
323       if (!FoundPCH) {
324         P.appendSuffix("pth");
325         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
326           FoundPTH = true;
327         else
328           P.eraseSuffix();
329       }
330
331       if (!FoundPCH && !FoundPTH) {
332         P.appendSuffix("gch");
333         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
334           FoundPCH = UsePCH;
335           FoundPTH = !UsePCH;
336         }
337         else
338           P.eraseSuffix();
339       }
340
341       if (FoundPCH || FoundPTH) {
342         if (IsFirstImplicitInclude) {
343           A->claim();
344           if (UsePCH)
345             CmdArgs.push_back("-include-pch");
346           else
347             CmdArgs.push_back("-include-pth");
348           CmdArgs.push_back(Args.MakeArgString(P.str()));
349           continue;
350         } else {
351           // Ignore the PCH if not first on command line and emit warning.
352           D.Diag(diag::warn_drv_pch_not_first_include)
353               << P.str() << A->getAsString(Args);
354         }
355       }
356     }
357
358     // Not translated, render as usual.
359     A->claim();
360     A->render(Args, CmdArgs);
361   }
362
363   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
364   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
365                   options::OPT_index_header_map);
366
367   // Add -Wp, and -Xassembler if using the preprocessor.
368
369   // FIXME: There is a very unfortunate problem here, some troubled
370   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
371   // really support that we would have to parse and then translate
372   // those options. :(
373   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
374                        options::OPT_Xpreprocessor);
375
376   // -I- is a deprecated GCC feature, reject it.
377   if (Arg *A = Args.getLastArg(options::OPT_I_))
378     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
379
380   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
381   // -isysroot to the CC1 invocation.
382   StringRef sysroot = C.getSysRoot();
383   if (sysroot != "") {
384     if (!Args.hasArg(options::OPT_isysroot)) {
385       CmdArgs.push_back("-isysroot");
386       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
387     }
388   }
389   
390   // If a module path was provided, pass it along. Otherwise, use a temporary
391   // directory.
392   if (Arg *A = Args.getLastArg(options::OPT_fmodule_cache_path)) {
393     A->claim();
394     A->render(Args, CmdArgs);
395   } else {
396     SmallString<128> DefaultModuleCache;
397     llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, 
398                                            DefaultModuleCache);
399     llvm::sys::path::append(DefaultModuleCache, "clang-module-cache");
400     CmdArgs.push_back("-fmodule-cache-path");
401     CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache));
402   }
403   
404   // Parse additional include paths from environment variables.
405   // FIXME: We should probably sink the logic for handling these from the
406   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
407   // CPATH - included following the user specified includes (but prior to
408   // builtin and standard includes).
409   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
410   // C_INCLUDE_PATH - system includes enabled when compiling C.
411   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
412   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
413   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
414   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
415   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
416   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
417   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
418
419   // Add C++ include arguments, if needed.
420   if (types::isCXX(Inputs[0].getType()))
421     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
422
423   // Add system include arguments.
424   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
425 }
426
427 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
428 /// CPU.
429 //
430 // FIXME: This is redundant with -mcpu, why does LLVM use this.
431 // FIXME: tblgen this, or kill it!
432 static const char *getLLVMArchSuffixForARM(StringRef CPU) {
433   return llvm::StringSwitch<const char *>(CPU)
434     .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
435     .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
436     .Cases("arm920", "arm920t", "arm922t", "v4t")
437     .Cases("arm940t", "ep9312","v4t")
438     .Cases("arm10tdmi",  "arm1020t", "v5")
439     .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
440     .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
441     .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
442     .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
443     .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
444     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
445     .Cases("cortex-a8", "cortex-a9", "v7")
446     .Case("cortex-m3", "v7m")
447     .Case("cortex-m4", "v7m")
448     .Case("cortex-m0", "v6m")
449     .Default("");
450 }
451
452 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
453 //
454 // FIXME: tblgen this.
455 static std::string getARMTargetCPU(const ArgList &Args,
456                                    const llvm::Triple &Triple) {
457   // FIXME: Warn on inconsistent use of -mcpu and -march.
458
459   // If we have -mcpu=, use that.
460   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
461     StringRef MCPU = A->getValue(Args);
462     // Handle -mcpu=native.
463     if (MCPU == "native")
464       return llvm::sys::getHostCPUName();
465     else
466       return MCPU;
467   }
468
469   StringRef MArch;
470   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
471     // Otherwise, if we have -march= choose the base CPU for that arch.
472     MArch = A->getValue(Args);
473   } else {
474     // Otherwise, use the Arch from the triple.
475     MArch = Triple.getArchName();
476   }
477
478   // Handle -march=native.
479   std::string NativeMArch;
480   if (MArch == "native") {
481     std::string CPU = llvm::sys::getHostCPUName();
482     if (CPU != "generic") {
483       // Translate the native cpu into the architecture. The switch below will
484       // then chose the minimum cpu for that arch.
485       NativeMArch = std::string("arm") + getLLVMArchSuffixForARM(CPU);
486       MArch = NativeMArch;
487     }
488   }
489
490   return llvm::StringSwitch<const char *>(MArch)
491     .Cases("armv2", "armv2a","arm2")
492     .Case("armv3", "arm6")
493     .Case("armv3m", "arm7m")
494     .Cases("armv4", "armv4t", "arm7tdmi")
495     .Cases("armv5", "armv5t", "arm10tdmi")
496     .Cases("armv5e", "armv5te", "arm1022e")
497     .Case("armv5tej", "arm926ej-s")
498     .Cases("armv6", "armv6k", "arm1136jf-s")
499     .Case("armv6j", "arm1136j-s")
500     .Cases("armv6z", "armv6zk", "arm1176jzf-s")
501     .Case("armv6t2", "arm1156t2-s")
502     .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
503     .Cases("armv7r", "armv7-r", "cortex-r4")
504     .Cases("armv7m", "armv7-m", "cortex-m3")
505     .Case("ep9312", "ep9312")
506     .Case("iwmmxt", "iwmmxt")
507     .Case("xscale", "xscale")
508     .Cases("armv6m", "armv6-m", "cortex-m0")
509     // If all else failed, return the most base CPU LLVM supports.
510     .Default("arm7tdmi");
511 }
512
513 // FIXME: Move to target hook.
514 static bool isSignedCharDefault(const llvm::Triple &Triple) {
515   switch (Triple.getArch()) {
516   default:
517     return true;
518
519   case llvm::Triple::arm:
520   case llvm::Triple::ppc:
521   case llvm::Triple::ppc64:
522     if (Triple.isOSDarwin())
523       return true;
524     return false;
525   }
526 }
527
528 // Handle -mfpu=.
529 //
530 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
531 // frontend target.
532 static void addFPUArgs(const Driver &D, const Arg *A, const ArgList &Args,
533                        ArgStringList &CmdArgs) {
534   StringRef FPU = A->getValue(Args);
535
536   // Set the target features based on the FPU.
537   if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
538     // Disable any default FPU support.
539     CmdArgs.push_back("-target-feature");
540     CmdArgs.push_back("-vfp2");
541     CmdArgs.push_back("-target-feature");
542     CmdArgs.push_back("-vfp3");
543     CmdArgs.push_back("-target-feature");
544     CmdArgs.push_back("-neon");
545   } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
546     CmdArgs.push_back("-target-feature");
547     CmdArgs.push_back("+vfp3");
548     CmdArgs.push_back("-target-feature");
549     CmdArgs.push_back("+d16");
550     CmdArgs.push_back("-target-feature");
551     CmdArgs.push_back("-neon");
552   } else if (FPU == "vfp") {
553     CmdArgs.push_back("-target-feature");
554     CmdArgs.push_back("+vfp2");
555     CmdArgs.push_back("-target-feature");
556     CmdArgs.push_back("-neon");
557   } else if (FPU == "vfp3" || FPU == "vfpv3") {
558     CmdArgs.push_back("-target-feature");
559     CmdArgs.push_back("+vfp3");
560     CmdArgs.push_back("-target-feature");
561     CmdArgs.push_back("-neon");
562   } else if (FPU == "neon") {
563     CmdArgs.push_back("-target-feature");
564     CmdArgs.push_back("+neon");
565   } else
566     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
567 }
568
569 // Handle -mfpmath=.
570 static void addFPMathArgs(const Driver &D, const Arg *A, const ArgList &Args,
571                           ArgStringList &CmdArgs, StringRef CPU) {
572   StringRef FPMath = A->getValue(Args);
573   
574   // Set the target features based on the FPMath.
575   if (FPMath == "neon") {
576     CmdArgs.push_back("-target-feature");
577     CmdArgs.push_back("+neonfp");
578     
579     if (CPU != "cortex-a8" && CPU != "cortex-a9" && CPU != "cortex-a9-mp")    
580       D.Diag(diag::err_drv_invalid_feature) << "-mfpmath=neon" << CPU;
581     
582   } else if (FPMath == "vfp" || FPMath == "vfp2" || FPMath == "vfp3" ||
583              FPMath == "vfp4") {
584     CmdArgs.push_back("-target-feature");
585     CmdArgs.push_back("-neonfp");
586
587     // FIXME: Add warnings when disabling a feature not present for a given CPU.    
588   } else
589     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
590 }
591
592 // Select the float ABI as determined by -msoft-float, -mhard-float, and
593 // -mfloat-abi=.
594 static StringRef getARMFloatABI(const Driver &D,
595                                 const ArgList &Args,
596                                 const llvm::Triple &Triple) {
597   StringRef FloatABI;
598   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
599                                options::OPT_mhard_float,
600                                options::OPT_mfloat_abi_EQ)) {
601     if (A->getOption().matches(options::OPT_msoft_float))
602       FloatABI = "soft";
603     else if (A->getOption().matches(options::OPT_mhard_float))
604       FloatABI = "hard";
605     else {
606       FloatABI = A->getValue(Args);
607       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
608         D.Diag(diag::err_drv_invalid_mfloat_abi)
609           << A->getAsString(Args);
610         FloatABI = "soft";
611       }
612     }
613   }
614
615   // If unspecified, choose the default based on the platform.
616   if (FloatABI.empty()) {
617     switch (Triple.getOS()) {
618     case llvm::Triple::Darwin:
619     case llvm::Triple::MacOSX:
620     case llvm::Triple::IOS: {
621       // Darwin defaults to "softfp" for v6 and v7.
622       //
623       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
624       std::string ArchName =
625         getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
626       if (StringRef(ArchName).startswith("v6") ||
627           StringRef(ArchName).startswith("v7"))
628         FloatABI = "softfp";
629       else
630         FloatABI = "soft";
631       break;
632     }
633
634     default:
635       switch(Triple.getEnvironment()) {
636       case llvm::Triple::GNUEABIHF:
637         FloatABI = "hard";
638         break;
639       case llvm::Triple::GNUEABI:
640         FloatABI = "softfp";
641         break;
642       case llvm::Triple::EABI:
643         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
644         FloatABI = "softfp";
645         break;
646       case llvm::Triple::ANDROIDEABI: {
647         std::string ArchName =
648           getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
649         if (StringRef(ArchName).startswith("v7"))
650           FloatABI = "softfp";
651         else
652           FloatABI = "soft";
653         break;
654       }
655       default:
656         // Assume "soft", but warn the user we are guessing.
657         FloatABI = "soft";
658         D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
659         break;
660       }
661     }
662   }
663
664   return FloatABI;
665 }
666
667
668 void Clang::AddARMTargetArgs(const ArgList &Args,
669                              ArgStringList &CmdArgs,
670                              bool KernelOrKext) const {
671   const Driver &D = getToolChain().getDriver();
672   llvm::Triple Triple = getToolChain().getTriple();
673
674   // Select the ABI to use.
675   //
676   // FIXME: Support -meabi.
677   const char *ABIName = 0;
678   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
679     ABIName = A->getValue(Args);
680   } else {
681     // Select the default based on the platform.
682     switch(Triple.getEnvironment()) {
683     case llvm::Triple::ANDROIDEABI:
684     case llvm::Triple::GNUEABI:
685     case llvm::Triple::GNUEABIHF:
686       ABIName = "aapcs-linux";
687       break;
688     case llvm::Triple::EABI:
689       ABIName = "aapcs";
690       break;
691     default:
692       ABIName = "apcs-gnu";
693     }
694   }
695   CmdArgs.push_back("-target-abi");
696   CmdArgs.push_back(ABIName);
697
698   // Set the CPU based on -march= and -mcpu=.
699   CmdArgs.push_back("-target-cpu");
700   CmdArgs.push_back(Args.MakeArgString(getARMTargetCPU(Args, Triple)));
701
702   // Determine floating point ABI from the options & target defaults.
703   StringRef FloatABI = getARMFloatABI(D, Args, Triple);
704   if (FloatABI == "soft") {
705     // Floating point operations and argument passing are soft.
706     //
707     // FIXME: This changes CPP defines, we need -target-soft-float.
708     CmdArgs.push_back("-msoft-float");
709     CmdArgs.push_back("-mfloat-abi");
710     CmdArgs.push_back("soft");
711   } else if (FloatABI == "softfp") {
712     // Floating point operations are hard, but argument passing is soft.
713     CmdArgs.push_back("-mfloat-abi");
714     CmdArgs.push_back("soft");
715   } else {
716     // Floating point operations and argument passing are hard.
717     assert(FloatABI == "hard" && "Invalid float abi!");
718     CmdArgs.push_back("-mfloat-abi");
719     CmdArgs.push_back("hard");
720   }
721
722   // Set appropriate target features for floating point mode.
723   //
724   // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
725   // yet (it uses the -mfloat-abi and -msoft-float options above), and it is
726   // stripped out by the ARM target.
727
728   // Use software floating point operations?
729   if (FloatABI == "soft") {
730     CmdArgs.push_back("-target-feature");
731     CmdArgs.push_back("+soft-float");
732   }
733
734   // Use software floating point argument passing?
735   if (FloatABI != "hard") {
736     CmdArgs.push_back("-target-feature");
737     CmdArgs.push_back("+soft-float-abi");
738   }
739
740   // Honor -mfpu=.
741   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
742     addFPUArgs(D, A, Args, CmdArgs);
743
744   // Honor -mfpmath=.
745   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ))
746     addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
747
748   // Setting -msoft-float effectively disables NEON because of the GCC
749   // implementation, although the same isn't true of VFP or VFP3.
750   if (FloatABI == "soft") {
751     CmdArgs.push_back("-target-feature");
752     CmdArgs.push_back("-neon");
753   }
754
755   // Kernel code has more strict alignment requirements.
756   if (KernelOrKext) {
757     CmdArgs.push_back("-backend-option");
758     CmdArgs.push_back("-arm-long-calls");
759
760     CmdArgs.push_back("-backend-option");
761     CmdArgs.push_back("-arm-strict-align");
762
763     // The kext linker doesn't know how to deal with movw/movt.
764     CmdArgs.push_back("-backend-option");
765     CmdArgs.push_back("-arm-darwin-use-movt=0");
766   }
767
768   // Setting -mno-global-merge disables the codegen global merge pass. Setting 
769   // -mglobal-merge has no effect as the pass is enabled by default.
770   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
771                                options::OPT_mno_global_merge)) {
772     if (A->getOption().matches(options::OPT_mno_global_merge))
773       CmdArgs.push_back("-mno-global-merge");
774   }
775
776   if (Args.hasArg(options::OPT_mno_implicit_float))
777     CmdArgs.push_back("-no-implicit-float");
778 }
779
780 // Get default architecture.
781 static const char* getMipsArchFromCPU(StringRef CPUName) {
782   if (CPUName == "mips32" || CPUName == "mips32r2")
783     return "mips";
784
785   assert((CPUName == "mips64" || CPUName == "mips64r2") &&
786          "Unexpected cpu name.");
787
788   return "mips64";
789 }
790
791 // Check that ArchName is a known Mips architecture name.
792 static bool checkMipsArchName(StringRef ArchName) {
793   return ArchName == "mips" ||
794          ArchName == "mipsel" ||
795          ArchName == "mips64" ||
796          ArchName == "mips64el";
797 }
798
799 // Get default target cpu.
800 static const char* getMipsCPUFromArch(StringRef ArchName) {
801   if (ArchName == "mips" || ArchName == "mipsel")
802     return "mips32";
803
804   assert((ArchName == "mips64" || ArchName == "mips64el") &&
805          "Unexpected arch name.");
806
807   return "mips64";
808 }
809
810 // Get default ABI.
811 static const char* getMipsABIFromArch(StringRef ArchName) {
812     if (ArchName == "mips" || ArchName == "mipsel")
813       return "o32";
814     
815     assert((ArchName == "mips64" || ArchName == "mips64el") &&
816            "Unexpected arch name.");
817     return "n64";
818 }
819
820 // Get CPU and ABI names. They are not independent
821 // so we have to calculate them together.
822 static void getMipsCPUAndABI(const ArgList &Args,
823                              const ToolChain &TC,
824                              StringRef &CPUName,
825                              StringRef &ABIName) {
826   StringRef ArchName;
827
828   // Select target cpu and architecture.
829   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
830     CPUName = A->getValue(Args);
831     ArchName = getMipsArchFromCPU(CPUName);
832   }
833   else {
834     ArchName = Args.MakeArgString(TC.getArchName());
835     if (!checkMipsArchName(ArchName))
836       TC.getDriver().Diag(diag::err_drv_invalid_arch_name) << ArchName;
837     else
838       CPUName = getMipsCPUFromArch(ArchName);
839   }
840  
841   // Select the ABI to use.
842   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
843     ABIName = A->getValue(Args);
844   else 
845     ABIName = getMipsABIFromArch(ArchName);
846 }
847
848 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
849 // and -mfloat-abi=.
850 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
851   // Select the float ABI as determined by -msoft-float, -mhard-float,
852   // and -mfloat-abi=.
853   StringRef FloatABI;
854   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
855                                options::OPT_mhard_float,
856                                options::OPT_mfloat_abi_EQ)) {
857     if (A->getOption().matches(options::OPT_msoft_float))
858       FloatABI = "soft";
859     else if (A->getOption().matches(options::OPT_mhard_float))
860       FloatABI = "hard";
861     else {
862       FloatABI = A->getValue(Args);
863       if (FloatABI != "soft" && FloatABI != "single" && FloatABI != "hard") {
864         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
865         FloatABI = "hard";
866       }
867     }
868   }
869
870   // If unspecified, choose the default based on the platform.
871   if (FloatABI.empty()) {
872     // Assume "hard", because it's a default value used by gcc.
873     // When we start to recognize specific target MIPS processors,
874     // we will be able to select the default more correctly.
875     FloatABI = "hard";
876   }
877
878   return FloatABI;
879 }
880
881 static void AddTargetFeature(const ArgList &Args,
882                              ArgStringList &CmdArgs,
883                              OptSpecifier OnOpt,
884                              OptSpecifier OffOpt,
885                              StringRef FeatureName) {
886   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
887     CmdArgs.push_back("-target-feature");
888     if (A->getOption().matches(OnOpt))
889       CmdArgs.push_back(Args.MakeArgString("+" + FeatureName));
890     else
891       CmdArgs.push_back(Args.MakeArgString("-" + FeatureName));
892   }
893 }
894
895 void Clang::AddMIPSTargetArgs(const ArgList &Args,
896                              ArgStringList &CmdArgs) const {
897   const Driver &D = getToolChain().getDriver();
898   StringRef CPUName;
899   StringRef ABIName;
900   getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
901
902   CmdArgs.push_back("-target-cpu");
903   CmdArgs.push_back(CPUName.data());
904
905   CmdArgs.push_back("-target-abi");
906   CmdArgs.push_back(ABIName.data());
907
908   StringRef FloatABI = getMipsFloatABI(D, Args);
909
910   if (FloatABI == "soft") {
911     // Floating point operations and argument passing are soft.
912     CmdArgs.push_back("-msoft-float");
913     CmdArgs.push_back("-mfloat-abi");
914     CmdArgs.push_back("soft");
915
916     // FIXME: Note, this is a hack. We need to pass the selected float
917     // mode to the MipsTargetInfoBase to define appropriate macros there.
918     // Now it is the only method.
919     CmdArgs.push_back("-target-feature");
920     CmdArgs.push_back("+soft-float");
921   }
922   else if (FloatABI == "single") {
923     // Restrict the use of hardware floating-point
924     // instructions to 32-bit operations.
925     CmdArgs.push_back("-target-feature");
926     CmdArgs.push_back("+single-float");
927   }
928   else {
929     // Floating point operations and argument passing are hard.
930     assert(FloatABI == "hard" && "Invalid float abi!");
931     CmdArgs.push_back("-mfloat-abi");
932     CmdArgs.push_back("hard");
933   }
934
935   AddTargetFeature(Args, CmdArgs,
936                    options::OPT_mips16, options::OPT_mno_mips16,
937                    "mips16");
938   AddTargetFeature(Args, CmdArgs,
939                    options::OPT_mdsp, options::OPT_mno_dsp,
940                    "dsp");
941   AddTargetFeature(Args, CmdArgs,
942                    options::OPT_mdspr2, options::OPT_mno_dspr2,
943                    "dspr2");
944 }
945
946 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
947 static std::string getPPCTargetCPU(const ArgList &Args) {
948   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
949     StringRef CPUName = A->getValue(Args);
950
951     if (CPUName == "native") {
952       std::string CPU = llvm::sys::getHostCPUName();
953       if (!CPU.empty() && CPU != "generic")
954         return CPU;
955       else
956         return "";
957     }
958
959     return llvm::StringSwitch<const char *>(CPUName)
960       .Case("common", "generic")
961       .Case("440", "440")
962       .Case("440fp", "440")
963       .Case("450", "450")
964       .Case("601", "601")
965       .Case("602", "602")
966       .Case("603", "603")
967       .Case("603e", "603e")
968       .Case("603ev", "603ev")
969       .Case("604", "604")
970       .Case("604e", "604e")
971       .Case("620", "620")
972       .Case("G3", "g3")
973       .Case("7400", "7400")
974       .Case("G4", "g4")
975       .Case("7450", "7450")
976       .Case("G4+", "g4+")
977       .Case("750", "750")
978       .Case("970", "970")
979       .Case("G5", "g5")
980       .Case("a2", "a2")
981       .Case("power6", "pwr6")
982       .Case("power7", "pwr7")
983       .Case("powerpc", "ppc")
984       .Case("powerpc64", "ppc64")
985       .Default("");
986   }
987
988   return "";
989 }
990
991 void Clang::AddPPCTargetArgs(const ArgList &Args,
992                              ArgStringList &CmdArgs) const {
993   std::string TargetCPUName = getPPCTargetCPU(Args);
994
995   // LLVM may default to generating code for the native CPU,
996   // but, like gcc, we default to a more generic option for
997   // each architecture. (except on Darwin)
998   llvm::Triple Triple = getToolChain().getTriple();
999   if (TargetCPUName.empty() && !Triple.isOSDarwin()) {
1000     if (Triple.getArch() == llvm::Triple::ppc64)
1001       TargetCPUName = "ppc64";
1002     else
1003       TargetCPUName = "ppc";
1004   }
1005
1006   if (!TargetCPUName.empty()) {
1007     CmdArgs.push_back("-target-cpu");
1008     CmdArgs.push_back(Args.MakeArgString(TargetCPUName.c_str()));
1009   }
1010 }
1011
1012 void Clang::AddSparcTargetArgs(const ArgList &Args,
1013                              ArgStringList &CmdArgs) const {
1014   const Driver &D = getToolChain().getDriver();
1015
1016   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1017     CmdArgs.push_back("-target-cpu");
1018     CmdArgs.push_back(A->getValue(Args));
1019   }
1020
1021   // Select the float ABI as determined by -msoft-float, -mhard-float, and
1022   StringRef FloatABI;
1023   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1024                                options::OPT_mhard_float)) {
1025     if (A->getOption().matches(options::OPT_msoft_float))
1026       FloatABI = "soft";
1027     else if (A->getOption().matches(options::OPT_mhard_float))
1028       FloatABI = "hard";
1029   }
1030
1031   // If unspecified, choose the default based on the platform.
1032   if (FloatABI.empty()) {
1033     switch (getToolChain().getTriple().getOS()) {
1034     default:
1035       // Assume "soft", but warn the user we are guessing.
1036       FloatABI = "soft";
1037       D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
1038       break;
1039     }
1040   }
1041
1042   if (FloatABI == "soft") {
1043     // Floating point operations and argument passing are soft.
1044     //
1045     // FIXME: This changes CPP defines, we need -target-soft-float.
1046     CmdArgs.push_back("-msoft-float");
1047     CmdArgs.push_back("-target-feature");
1048     CmdArgs.push_back("+soft-float");
1049   } else {
1050     assert(FloatABI == "hard" && "Invalid float abi!");
1051     CmdArgs.push_back("-mhard-float");
1052   }
1053 }
1054
1055 void Clang::AddX86TargetArgs(const ArgList &Args,
1056                              ArgStringList &CmdArgs) const {
1057   if (!Args.hasFlag(options::OPT_mred_zone,
1058                     options::OPT_mno_red_zone,
1059                     true) ||
1060       Args.hasArg(options::OPT_mkernel) ||
1061       Args.hasArg(options::OPT_fapple_kext))
1062     CmdArgs.push_back("-disable-red-zone");
1063
1064   if (Args.hasFlag(options::OPT_msoft_float,
1065                    options::OPT_mno_soft_float,
1066                    false))
1067     CmdArgs.push_back("-no-implicit-float");
1068
1069   const char *CPUName = 0;
1070   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1071     if (StringRef(A->getValue(Args)) == "native") {
1072       // FIXME: Reject attempts to use -march=native unless the target matches
1073       // the host.
1074       //
1075       // FIXME: We should also incorporate the detected target features for use
1076       // with -native.
1077       std::string CPU = llvm::sys::getHostCPUName();
1078       if (!CPU.empty() && CPU != "generic")
1079         CPUName = Args.MakeArgString(CPU);
1080     } else
1081       CPUName = A->getValue(Args);
1082   }
1083
1084   // Select the default CPU if none was given (or detection failed).
1085   if (!CPUName) {
1086     // FIXME: Need target hooks.
1087     if (getToolChain().getTriple().isOSDarwin()) {
1088       if (getToolChain().getArch() == llvm::Triple::x86_64)
1089         CPUName = "core2";
1090       else if (getToolChain().getArch() == llvm::Triple::x86)
1091         CPUName = "yonah";
1092     } else if (getToolChain().getOS().startswith("haiku"))  {
1093       if (getToolChain().getArch() == llvm::Triple::x86_64)
1094         CPUName = "x86-64";
1095       else if (getToolChain().getArch() == llvm::Triple::x86)
1096         CPUName = "i586";
1097     } else if (getToolChain().getOS().startswith("openbsd"))  {
1098       if (getToolChain().getArch() == llvm::Triple::x86_64)
1099         CPUName = "x86-64";
1100       else if (getToolChain().getArch() == llvm::Triple::x86)
1101         CPUName = "i486";
1102     } else if (getToolChain().getOS().startswith("bitrig"))  {
1103       if (getToolChain().getArch() == llvm::Triple::x86_64)
1104         CPUName = "x86-64";
1105       else if (getToolChain().getArch() == llvm::Triple::x86)
1106         CPUName = "i686";
1107     } else if (getToolChain().getOS().startswith("freebsd"))  {
1108       if (getToolChain().getArch() == llvm::Triple::x86_64)
1109         CPUName = "x86-64";
1110       else if (getToolChain().getArch() == llvm::Triple::x86)
1111         CPUName = "i486";
1112     } else if (getToolChain().getOS().startswith("netbsd"))  {
1113       if (getToolChain().getArch() == llvm::Triple::x86_64)
1114         CPUName = "x86-64";
1115       else if (getToolChain().getArch() == llvm::Triple::x86)
1116         CPUName = "i486";
1117     } else {
1118       if (getToolChain().getArch() == llvm::Triple::x86_64)
1119         CPUName = "x86-64";
1120       else if (getToolChain().getArch() == llvm::Triple::x86)
1121         CPUName = "pentium4";
1122     }
1123   }
1124
1125   if (CPUName) {
1126     CmdArgs.push_back("-target-cpu");
1127     CmdArgs.push_back(CPUName);
1128   }
1129
1130   // The required algorithm here is slightly strange: the options are applied
1131   // in order (so -mno-sse -msse2 disables SSE3), but any option that gets
1132   // directly overridden later is ignored (so "-mno-sse -msse2 -mno-sse2 -msse"
1133   // is equivalent to "-mno-sse2 -msse"). The -cc1 handling deals with the
1134   // former correctly, but not the latter; handle directly-overridden
1135   // attributes here.
1136   llvm::StringMap<unsigned> PrevFeature;
1137   std::vector<const char*> Features;
1138   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
1139          ie = Args.filtered_end(); it != ie; ++it) {
1140     StringRef Name = (*it)->getOption().getName();
1141     (*it)->claim();
1142
1143     // Skip over "-m".
1144     assert(Name.startswith("-m") && "Invalid feature name.");
1145     Name = Name.substr(2);
1146
1147     bool IsNegative = Name.startswith("no-");
1148     if (IsNegative)
1149       Name = Name.substr(3);
1150
1151     unsigned& Prev = PrevFeature[Name];
1152     if (Prev)
1153       Features[Prev - 1] = 0;
1154     Prev = Features.size() + 1;
1155     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1156   }
1157   for (unsigned i = 0; i < Features.size(); i++) {
1158     if (Features[i]) {
1159       CmdArgs.push_back("-target-feature");
1160       CmdArgs.push_back(Features[i]);
1161     }
1162   }
1163 }
1164
1165 static Arg* getLastHexagonArchArg (const ArgList &Args)
1166 {
1167   Arg * A = NULL;
1168
1169   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
1170        it != ie; ++it) {
1171     if ((*it)->getOption().matches(options::OPT_march_EQ) ||
1172         (*it)->getOption().matches(options::OPT_mcpu_EQ)) {
1173       A = *it;
1174       A->claim();
1175     }
1176     else if ((*it)->getOption().matches(options::OPT_m_Joined)){
1177       StringRef Value = (*it)->getValue(Args,0);
1178       if (Value.startswith("v")) {
1179         A = *it;
1180         A->claim();
1181       }
1182     }
1183   }
1184   return A;
1185 }
1186
1187 static StringRef getHexagonTargetCPU(const ArgList &Args)
1188 {
1189   Arg *A;
1190   llvm::StringRef WhichHexagon;
1191
1192   // Select the default CPU (v4) if none was given or detection failed.
1193   if ((A = getLastHexagonArchArg (Args))) {
1194     WhichHexagon = A->getValue(Args);
1195     if (WhichHexagon == "")
1196       return "v4";
1197     else
1198       return WhichHexagon;
1199   }
1200   else
1201     return "v4";
1202 }
1203
1204 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1205                                  ArgStringList &CmdArgs) const {
1206   llvm::Triple Triple = getToolChain().getTriple();
1207
1208   CmdArgs.push_back("-target-cpu");
1209   CmdArgs.push_back(Args.MakeArgString("hexagon" + getHexagonTargetCPU(Args)));
1210   CmdArgs.push_back("-fno-signed-char");
1211   CmdArgs.push_back("-nobuiltininc");
1212
1213   if (Args.hasArg(options::OPT_mqdsp6_compat))
1214     CmdArgs.push_back("-mqdsp6-compat");
1215
1216   if (Arg *A = Args.getLastArg(options::OPT_G,
1217                                options::OPT_msmall_data_threshold_EQ)) {
1218     std::string SmallDataThreshold="-small-data-threshold=";
1219     SmallDataThreshold += A->getValue(Args);
1220     CmdArgs.push_back ("-mllvm");
1221     CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
1222     A->claim();
1223   }
1224
1225   if (!Args.hasArg(options::OPT_fno_short_enums))
1226     CmdArgs.push_back("-fshort-enums");
1227   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1228     CmdArgs.push_back ("-mllvm");
1229     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
1230   }
1231   CmdArgs.push_back ("-mllvm");
1232   CmdArgs.push_back ("-machine-sink-split=0");
1233 }
1234
1235 static bool
1236 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
1237                                           const llvm::Triple &Triple) {
1238   // We use the zero-cost exception tables for Objective-C if the non-fragile
1239   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
1240   // later.
1241   if (runtime.isNonFragile())
1242     return true;
1243
1244   if (!Triple.isOSDarwin())
1245     return false;
1246
1247   return (!Triple.isMacOSXVersionLT(10,5) &&
1248           (Triple.getArch() == llvm::Triple::x86_64 ||
1249            Triple.getArch() == llvm::Triple::arm));
1250 }
1251
1252 /// addExceptionArgs - Adds exception related arguments to the driver command
1253 /// arguments. There's a master flag, -fexceptions and also language specific
1254 /// flags to enable/disable C++ and Objective-C exceptions.
1255 /// This makes it possible to for example disable C++ exceptions but enable
1256 /// Objective-C exceptions.
1257 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
1258                              const llvm::Triple &Triple,
1259                              bool KernelOrKext,
1260                              const ObjCRuntime &objcRuntime,
1261                              ArgStringList &CmdArgs) {
1262   if (KernelOrKext) {
1263     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
1264     // arguments now to avoid warnings about unused arguments.
1265     Args.ClaimAllArgs(options::OPT_fexceptions);
1266     Args.ClaimAllArgs(options::OPT_fno_exceptions);
1267     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
1268     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
1269     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
1270     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
1271     return;
1272   }
1273
1274   // Exceptions are enabled by default.
1275   bool ExceptionsEnabled = true;
1276
1277   // This keeps track of whether exceptions were explicitly turned on or off.
1278   bool DidHaveExplicitExceptionFlag = false;
1279
1280   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
1281                                options::OPT_fno_exceptions)) {
1282     if (A->getOption().matches(options::OPT_fexceptions))
1283       ExceptionsEnabled = true;
1284     else
1285       ExceptionsEnabled = false;
1286
1287     DidHaveExplicitExceptionFlag = true;
1288   }
1289
1290   bool ShouldUseExceptionTables = false;
1291
1292   // Exception tables and cleanups can be enabled with -fexceptions even if the
1293   // language itself doesn't support exceptions.
1294   if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
1295     ShouldUseExceptionTables = true;
1296
1297   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
1298   // is not necessarily sensible, but follows GCC.
1299   if (types::isObjC(InputType) &&
1300       Args.hasFlag(options::OPT_fobjc_exceptions,
1301                    options::OPT_fno_objc_exceptions,
1302                    true)) {
1303     CmdArgs.push_back("-fobjc-exceptions");
1304
1305     ShouldUseExceptionTables |=
1306       shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
1307   }
1308
1309   if (types::isCXX(InputType)) {
1310     bool CXXExceptionsEnabled = ExceptionsEnabled;
1311
1312     if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
1313                                  options::OPT_fno_cxx_exceptions,
1314                                  options::OPT_fexceptions,
1315                                  options::OPT_fno_exceptions)) {
1316       if (A->getOption().matches(options::OPT_fcxx_exceptions))
1317         CXXExceptionsEnabled = true;
1318       else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
1319         CXXExceptionsEnabled = false;
1320     }
1321
1322     if (CXXExceptionsEnabled) {
1323       CmdArgs.push_back("-fcxx-exceptions");
1324
1325       ShouldUseExceptionTables = true;
1326     }
1327   }
1328
1329   if (ShouldUseExceptionTables)
1330     CmdArgs.push_back("-fexceptions");
1331 }
1332
1333 static bool ShouldDisableCFI(const ArgList &Args,
1334                              const ToolChain &TC) {
1335   bool Default = true;
1336   if (TC.getTriple().isOSDarwin()) {
1337     // The native darwin assembler doesn't support cfi directives, so
1338     // we disable them if we think the .s file will be passed to it.
1339     Default = Args.hasFlag(options::OPT_integrated_as,
1340                            options::OPT_no_integrated_as,
1341                            TC.IsIntegratedAssemblerDefault());
1342   }
1343   return !Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
1344                        options::OPT_fno_dwarf2_cfi_asm,
1345                        Default);
1346 }
1347
1348 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
1349                                         const ToolChain &TC) {
1350   bool IsIADefault = TC.IsIntegratedAssemblerDefault();
1351   bool UseIntegratedAs = Args.hasFlag(options::OPT_integrated_as,
1352                                       options::OPT_no_integrated_as,
1353                                       IsIADefault);
1354   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
1355                                         options::OPT_fno_dwarf_directory_asm,
1356                                         UseIntegratedAs);
1357   return !UseDwarfDirectory;
1358 }
1359
1360 /// \brief Check whether the given input tree contains any compilation actions.
1361 static bool ContainsCompileAction(const Action *A) {
1362   if (isa<CompileJobAction>(A))
1363     return true;
1364
1365   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
1366     if (ContainsCompileAction(*it))
1367       return true;
1368
1369   return false;
1370 }
1371
1372 /// \brief Check if -relax-all should be passed to the internal assembler.
1373 /// This is done by default when compiling non-assembler source with -O0.
1374 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
1375   bool RelaxDefault = true;
1376
1377   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1378     RelaxDefault = A->getOption().matches(options::OPT_O0);
1379
1380   if (RelaxDefault) {
1381     RelaxDefault = false;
1382     for (ActionList::const_iterator it = C.getActions().begin(),
1383            ie = C.getActions().end(); it != ie; ++it) {
1384       if (ContainsCompileAction(*it)) {
1385         RelaxDefault = true;
1386         break;
1387       }
1388     }
1389   }
1390
1391   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1392     RelaxDefault);
1393 }
1394
1395 /// If AddressSanitizer is enabled, add appropriate linker flags (Linux).
1396 /// This needs to be called before we add the C run-time (malloc, etc).
1397 static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
1398                            ArgStringList &CmdArgs) {
1399   if (!Args.hasFlag(options::OPT_faddress_sanitizer,
1400                     options::OPT_fno_address_sanitizer, false))
1401     return;
1402   if(TC.getTriple().getEnvironment() == llvm::Triple::ANDROIDEABI) {
1403     if (!Args.hasArg(options::OPT_shared)) {
1404       if (!Args.hasArg(options::OPT_pie))
1405         TC.getDriver().Diag(diag::err_drv_asan_android_requires_pie);
1406       // For an executable, we add a .preinit_array stub.
1407       CmdArgs.push_back("-u");
1408       CmdArgs.push_back("__asan_preinit");
1409       CmdArgs.push_back("-lasan");
1410     }
1411
1412     CmdArgs.push_back("-lasan_preload");
1413     CmdArgs.push_back("-ldl");
1414   } else {
1415     if (!Args.hasArg(options::OPT_shared)) {
1416       // LibAsan is "libclang_rt.asan-<ArchName>.a" in the Linux library
1417       // resource directory.
1418       SmallString<128> LibAsan(TC.getDriver().ResourceDir);
1419       llvm::sys::path::append(LibAsan, "lib", "linux",
1420                               (Twine("libclang_rt.asan-") +
1421                                TC.getArchName() + ".a"));
1422       CmdArgs.push_back(Args.MakeArgString(LibAsan));
1423       CmdArgs.push_back("-lpthread");
1424       CmdArgs.push_back("-ldl");
1425       CmdArgs.push_back("-export-dynamic");
1426     }
1427   }
1428 }
1429
1430 /// If ThreadSanitizer is enabled, add appropriate linker flags (Linux).
1431 /// This needs to be called before we add the C run-time (malloc, etc).
1432 static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args,
1433                            ArgStringList &CmdArgs) {
1434   if (!Args.hasFlag(options::OPT_fthread_sanitizer,
1435                     options::OPT_fno_thread_sanitizer, false))
1436     return;
1437   if (!Args.hasArg(options::OPT_shared)) {
1438     // LibTsan is "libclang_rt.tsan-<ArchName>.a" in the Linux library
1439     // resource directory.
1440     SmallString<128> LibTsan(TC.getDriver().ResourceDir);
1441     llvm::sys::path::append(LibTsan, "lib", "linux",
1442                             (Twine("libclang_rt.tsan-") +
1443                              TC.getArchName() + ".a"));
1444     CmdArgs.push_back(Args.MakeArgString(LibTsan));
1445     CmdArgs.push_back("-lpthread");
1446     CmdArgs.push_back("-ldl");
1447     CmdArgs.push_back("-export-dynamic");
1448   }
1449 }
1450
1451 static bool shouldUseFramePointer(const ArgList &Args,
1452                                   const llvm::Triple &Triple) {
1453   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
1454                                options::OPT_fomit_frame_pointer))
1455     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
1456
1457   // Don't use a frame pointer on linux x86 and x86_64 if optimizing.
1458   if ((Triple.getArch() == llvm::Triple::x86_64 ||
1459        Triple.getArch() == llvm::Triple::x86) &&
1460       Triple.getOS() == llvm::Triple::Linux) {
1461     if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1462       if (!A->getOption().matches(options::OPT_O0))
1463         return false;
1464   }
1465
1466   return true;
1467 }
1468
1469 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
1470                          const InputInfo &Output,
1471                          const InputInfoList &Inputs,
1472                          const ArgList &Args,
1473                          const char *LinkingOutput) const {
1474   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
1475                                   options::OPT_fapple_kext);
1476   const Driver &D = getToolChain().getDriver();
1477   ArgStringList CmdArgs;
1478
1479   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
1480
1481   // Invoke ourselves in -cc1 mode.
1482   //
1483   // FIXME: Implement custom jobs for internal actions.
1484   CmdArgs.push_back("-cc1");
1485
1486   // Add the "effective" target triple.
1487   CmdArgs.push_back("-triple");
1488   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1489   CmdArgs.push_back(Args.MakeArgString(TripleStr));
1490
1491   // Select the appropriate action.
1492   RewriteKind rewriteKind = RK_None;
1493   
1494   if (isa<AnalyzeJobAction>(JA)) {
1495     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
1496     CmdArgs.push_back("-analyze");
1497   } else if (isa<MigrateJobAction>(JA)) {
1498     CmdArgs.push_back("-migrate");
1499   } else if (isa<PreprocessJobAction>(JA)) {
1500     if (Output.getType() == types::TY_Dependencies)
1501       CmdArgs.push_back("-Eonly");
1502     else
1503       CmdArgs.push_back("-E");
1504   } else if (isa<AssembleJobAction>(JA)) {
1505     CmdArgs.push_back("-emit-obj");
1506
1507     if (UseRelaxAll(C, Args))
1508       CmdArgs.push_back("-mrelax-all");
1509
1510     // When using an integrated assembler, translate -Wa, and -Xassembler
1511     // options.
1512     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
1513                                                options::OPT_Xassembler),
1514            ie = Args.filtered_end(); it != ie; ++it) {
1515       const Arg *A = *it;
1516       A->claim();
1517
1518       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
1519         StringRef Value = A->getValue(Args, i);
1520
1521         if (Value == "-force_cpusubtype_ALL") {
1522           // Do nothing, this is the default and we don't support anything else.
1523         } else if (Value == "-L") {
1524           CmdArgs.push_back("-msave-temp-labels");
1525         } else if (Value == "--fatal-warnings") {
1526           CmdArgs.push_back("-mllvm");
1527           CmdArgs.push_back("-fatal-assembler-warnings");
1528         } else if (Value == "--noexecstack") {
1529           CmdArgs.push_back("-mnoexecstack");
1530         } else {
1531           D.Diag(diag::err_drv_unsupported_option_argument)
1532             << A->getOption().getName() << Value;
1533         }
1534       }
1535     }
1536
1537     // Also ignore explicit -force_cpusubtype_ALL option.
1538     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
1539   } else if (isa<PrecompileJobAction>(JA)) {
1540     // Use PCH if the user requested it.
1541     bool UsePCH = D.CCCUsePCH;
1542
1543     if (JA.getType() == types::TY_Nothing)
1544       CmdArgs.push_back("-fsyntax-only");
1545     else if (UsePCH)
1546       CmdArgs.push_back("-emit-pch");
1547     else
1548       CmdArgs.push_back("-emit-pth");
1549   } else {
1550     assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
1551
1552     if (JA.getType() == types::TY_Nothing) {
1553       CmdArgs.push_back("-fsyntax-only");
1554     } else if (JA.getType() == types::TY_LLVM_IR ||
1555                JA.getType() == types::TY_LTO_IR) {
1556       CmdArgs.push_back("-emit-llvm");
1557     } else if (JA.getType() == types::TY_LLVM_BC ||
1558                JA.getType() == types::TY_LTO_BC) {
1559       CmdArgs.push_back("-emit-llvm-bc");
1560     } else if (JA.getType() == types::TY_PP_Asm) {
1561       CmdArgs.push_back("-S");
1562     } else if (JA.getType() == types::TY_AST) {
1563       CmdArgs.push_back("-emit-pch");
1564     } else if (JA.getType() == types::TY_RewrittenObjC) {
1565       CmdArgs.push_back("-rewrite-objc");
1566       rewriteKind = RK_NonFragile;
1567     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
1568       CmdArgs.push_back("-rewrite-objc");
1569       rewriteKind = RK_Fragile;
1570     } else {
1571       assert(JA.getType() == types::TY_PP_Asm &&
1572              "Unexpected output type!");
1573     }
1574   }
1575
1576   // The make clang go fast button.
1577   CmdArgs.push_back("-disable-free");
1578
1579   // Disable the verification pass in -asserts builds.
1580 #ifdef NDEBUG
1581   CmdArgs.push_back("-disable-llvm-verifier");
1582 #endif
1583
1584   // Set the main file name, so that debug info works even with
1585   // -save-temps.
1586   CmdArgs.push_back("-main-file-name");
1587   CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
1588
1589   // Some flags which affect the language (via preprocessor
1590   // defines). See darwin::CC1::AddCPPArgs.
1591   if (Args.hasArg(options::OPT_static))
1592     CmdArgs.push_back("-static-define");
1593
1594   if (isa<AnalyzeJobAction>(JA)) {
1595     // Enable region store model by default.
1596     CmdArgs.push_back("-analyzer-store=region");
1597
1598     // Treat blocks as analysis entry points.
1599     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
1600
1601     CmdArgs.push_back("-analyzer-eagerly-assume");
1602
1603     CmdArgs.push_back("-analyzer-ipa=inlining");
1604
1605     // Add default argument set.
1606     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
1607       CmdArgs.push_back("-analyzer-checker=core");
1608
1609       if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
1610         CmdArgs.push_back("-analyzer-checker=unix");
1611
1612       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
1613         CmdArgs.push_back("-analyzer-checker=osx");
1614       
1615       CmdArgs.push_back("-analyzer-checker=deadcode");
1616       
1617       // Enable the following experimental checkers for testing. 
1618       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
1619       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
1620       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
1621       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");      
1622       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
1623       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
1624     }
1625
1626     // Set the output format. The default is plist, for (lame) historical
1627     // reasons.
1628     CmdArgs.push_back("-analyzer-output");
1629     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
1630       CmdArgs.push_back(A->getValue(Args));
1631     else
1632       CmdArgs.push_back("plist");
1633
1634     // Disable the presentation of standard compiler warnings when
1635     // using --analyze.  We only want to show static analyzer diagnostics
1636     // or frontend errors.
1637     CmdArgs.push_back("-w");
1638
1639     // Add -Xanalyzer arguments when running as analyzer.
1640     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
1641   }
1642
1643   CheckCodeGenerationOptions(D, Args);
1644
1645   // Perform argument translation for LLVM backend. This
1646   // takes some care in reconciling with llvm-gcc. The
1647   // issue is that llvm-gcc translates these options based on
1648   // the values in cc1, whereas we are processing based on
1649   // the driver arguments.
1650
1651   // This comes from the default translation the driver + cc1
1652   // would do to enable flag_pic.
1653
1654   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1655                                     options::OPT_fpic, options::OPT_fno_pic,
1656                                     options::OPT_fPIE, options::OPT_fno_PIE,
1657                                     options::OPT_fpie, options::OPT_fno_pie);
1658   bool PICDisabled = false;
1659   bool PICEnabled = false;
1660   bool PICForPIE = false;
1661   if (LastPICArg) {
1662     PICForPIE = (LastPICArg->getOption().matches(options::OPT_fPIE) ||
1663                  LastPICArg->getOption().matches(options::OPT_fpie));
1664     PICEnabled = (PICForPIE ||
1665                   LastPICArg->getOption().matches(options::OPT_fPIC) ||
1666                   LastPICArg->getOption().matches(options::OPT_fpic));
1667     PICDisabled = !PICEnabled;
1668   }
1669   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
1670   // PIC or PIE options above, if these show up, PIC is disabled.
1671   if (Args.hasArg(options::OPT_mkernel))
1672     PICDisabled = true;
1673   if (Args.hasArg(options::OPT_static))
1674     PICDisabled = true;
1675   bool DynamicNoPIC = Args.hasArg(options::OPT_mdynamic_no_pic);
1676
1677   // Select the relocation model.
1678   const char *Model = getToolChain().GetForcedPicModel();
1679   if (!Model) {
1680     if (DynamicNoPIC)
1681       Model = "dynamic-no-pic";
1682     else if (PICDisabled)
1683       Model = "static";
1684     else if (PICEnabled)
1685       Model = "pic";
1686     else
1687       Model = getToolChain().GetDefaultRelocationModel();
1688   }
1689   StringRef ModelStr = Model ? Model : "";
1690   if (Model && ModelStr != "pic") {
1691     CmdArgs.push_back("-mrelocation-model");
1692     CmdArgs.push_back(Model);
1693   }
1694
1695   // Infer the __PIC__ and __PIE__ values.
1696   if (ModelStr == "pic" && PICForPIE) {
1697     CmdArgs.push_back("-pie-level");
1698     CmdArgs.push_back((LastPICArg &&
1699                        LastPICArg->getOption().matches(options::OPT_fPIE)) ?
1700                       "2" : "1");
1701   } else if (ModelStr == "pic" || ModelStr == "dynamic-no-pic") {
1702     CmdArgs.push_back("-pic-level");
1703     CmdArgs.push_back(((ModelStr != "dynamic-no-pic" && LastPICArg &&
1704                         LastPICArg->getOption().matches(options::OPT_fPIC)) ||
1705                        getToolChain().getTriple().isOSDarwin()) ? "2" : "1");
1706   }
1707
1708   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
1709                     options::OPT_fno_merge_all_constants))
1710     CmdArgs.push_back("-fno-merge-all-constants");
1711
1712   // LLVM Code Generator Options.
1713
1714   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1715     CmdArgs.push_back("-mregparm");
1716     CmdArgs.push_back(A->getValue(Args));
1717   }
1718
1719   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
1720     CmdArgs.push_back("-mrtd");
1721
1722   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
1723     CmdArgs.push_back("-mdisable-fp-elim");
1724   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
1725                     options::OPT_fno_zero_initialized_in_bss))
1726     CmdArgs.push_back("-mno-zero-initialized-in-bss");
1727   if (!Args.hasFlag(options::OPT_fstrict_aliasing,
1728                     options::OPT_fno_strict_aliasing,
1729                     getToolChain().IsStrictAliasingDefault()))
1730     CmdArgs.push_back("-relaxed-aliasing");
1731   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
1732                    false))
1733     CmdArgs.push_back("-fstrict-enums");
1734   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
1735                     options::OPT_fno_optimize_sibling_calls))
1736     CmdArgs.push_back("-mdisable-tail-calls");
1737
1738   // Handle various floating point optimization flags, mapping them to the
1739   // appropriate LLVM code generation flags. The pattern for all of these is to
1740   // default off the codegen optimizations, and if any flag enables them and no
1741   // flag disables them after the flag enabling them, enable the codegen
1742   // optimization. This is complicated by several "umbrella" flags.
1743   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1744                                options::OPT_ffinite_math_only,
1745                                options::OPT_fno_finite_math_only,
1746                                options::OPT_fhonor_infinities,
1747                                options::OPT_fno_honor_infinities))
1748     if (A->getOption().getID() != options::OPT_fno_finite_math_only &&
1749         A->getOption().getID() != options::OPT_fhonor_infinities)
1750       CmdArgs.push_back("-menable-no-infs");
1751   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1752                                options::OPT_ffinite_math_only,
1753                                options::OPT_fno_finite_math_only,
1754                                options::OPT_fhonor_nans,
1755                                options::OPT_fno_honor_nans))
1756     if (A->getOption().getID() != options::OPT_fno_finite_math_only &&
1757         A->getOption().getID() != options::OPT_fhonor_nans)
1758       CmdArgs.push_back("-menable-no-nans");
1759
1760   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
1761   bool MathErrno = getToolChain().IsMathErrnoDefault();
1762   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1763                                options::OPT_fmath_errno,
1764                                options::OPT_fno_math_errno))
1765     MathErrno = A->getOption().getID() == options::OPT_fmath_errno;
1766   if (MathErrno)
1767     CmdArgs.push_back("-fmath-errno");
1768
1769   // There are several flags which require disabling very specific
1770   // optimizations. Any of these being disabled forces us to turn off the
1771   // entire set of LLVM optimizations, so collect them through all the flag
1772   // madness.
1773   bool AssociativeMath = false;
1774   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1775                                options::OPT_funsafe_math_optimizations,
1776                                options::OPT_fno_unsafe_math_optimizations,
1777                                options::OPT_fassociative_math,
1778                                options::OPT_fno_associative_math))
1779     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1780         A->getOption().getID() != options::OPT_fno_associative_math)
1781       AssociativeMath = true;
1782   bool ReciprocalMath = false;
1783   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1784                                options::OPT_funsafe_math_optimizations,
1785                                options::OPT_fno_unsafe_math_optimizations,
1786                                options::OPT_freciprocal_math,
1787                                options::OPT_fno_reciprocal_math))
1788     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1789         A->getOption().getID() != options::OPT_fno_reciprocal_math)
1790       ReciprocalMath = true;
1791   bool SignedZeros = true;
1792   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1793                                options::OPT_funsafe_math_optimizations,
1794                                options::OPT_fno_unsafe_math_optimizations,
1795                                options::OPT_fsigned_zeros,
1796                                options::OPT_fno_signed_zeros))
1797     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1798         A->getOption().getID() != options::OPT_fsigned_zeros)
1799       SignedZeros = false;
1800   bool TrappingMath = true;
1801   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1802                                options::OPT_funsafe_math_optimizations,
1803                                options::OPT_fno_unsafe_math_optimizations,
1804                                options::OPT_ftrapping_math,
1805                                options::OPT_fno_trapping_math))
1806     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1807         A->getOption().getID() != options::OPT_ftrapping_math)
1808       TrappingMath = false;
1809   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
1810       !TrappingMath)
1811     CmdArgs.push_back("-menable-unsafe-fp-math");
1812
1813
1814   // Validate and pass through -fp-contract option. 
1815   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1816                                options::OPT_ffp_contract)) {
1817     if (A->getOption().getID() == options::OPT_ffp_contract) {
1818       StringRef Val = A->getValue(Args);
1819       if (Val == "fast" || Val == "on" || Val == "off") {
1820         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
1821       } else {
1822         D.Diag(diag::err_drv_unsupported_option_argument)
1823           << A->getOption().getName() << Val;
1824       }
1825     } else { // A is OPT_ffast_math
1826       // If fast-math is set then set the fp-contract mode to fast.
1827       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
1828     }
1829   }
1830
1831   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
1832   // and if we find them, tell the frontend to provide the appropriate
1833   // preprocessor macros. This is distinct from enabling any optimizations as
1834   // these options induce language changes which must survive serialization
1835   // and deserialization, etc.
1836   if (Args.hasArg(options::OPT_ffast_math))
1837     CmdArgs.push_back("-ffast-math");
1838   if (Args.hasArg(options::OPT_ffinite_math_only))
1839     CmdArgs.push_back("-ffinite-math-only");
1840
1841   // Decide whether to use verbose asm. Verbose assembly is the default on
1842   // toolchains which have the integrated assembler on by default.
1843   bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
1844   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
1845                    IsVerboseAsmDefault) ||
1846       Args.hasArg(options::OPT_dA))
1847     CmdArgs.push_back("-masm-verbose");
1848
1849   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
1850     CmdArgs.push_back("-mdebug-pass");
1851     CmdArgs.push_back("Structure");
1852   }
1853   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
1854     CmdArgs.push_back("-mdebug-pass");
1855     CmdArgs.push_back("Arguments");
1856   }
1857
1858   // Enable -mconstructor-aliases except on darwin, where we have to
1859   // work around a linker bug;  see <rdar://problem/7651567>.
1860   if (!getToolChain().getTriple().isOSDarwin())
1861     CmdArgs.push_back("-mconstructor-aliases");
1862
1863   // Darwin's kernel doesn't support guard variables; just die if we
1864   // try to use them.
1865   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
1866     CmdArgs.push_back("-fforbid-guard-variables");
1867
1868   if (Args.hasArg(options::OPT_mms_bitfields)) {
1869     CmdArgs.push_back("-mms-bitfields");
1870   }
1871
1872   // This is a coarse approximation of what llvm-gcc actually does, both
1873   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
1874   // complicated ways.
1875   bool AsynchronousUnwindTables =
1876     Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
1877                  options::OPT_fno_asynchronous_unwind_tables,
1878                  getToolChain().IsUnwindTablesDefault() &&
1879                  !KernelOrKext);
1880   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
1881                    AsynchronousUnwindTables))
1882     CmdArgs.push_back("-munwind-tables");
1883
1884   getToolChain().addClangTargetOptions(CmdArgs);
1885
1886   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
1887     CmdArgs.push_back("-mlimit-float-precision");
1888     CmdArgs.push_back(A->getValue(Args));
1889   }
1890
1891   // FIXME: Handle -mtune=.
1892   (void) Args.hasArg(options::OPT_mtune_EQ);
1893
1894   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
1895     CmdArgs.push_back("-mcode-model");
1896     CmdArgs.push_back(A->getValue(Args));
1897   }
1898
1899   // Add target specific cpu and features flags.
1900   switch(getToolChain().getTriple().getArch()) {
1901   default:
1902     break;
1903
1904   case llvm::Triple::arm:
1905   case llvm::Triple::thumb:
1906     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
1907     break;
1908
1909   case llvm::Triple::mips:
1910   case llvm::Triple::mipsel:
1911   case llvm::Triple::mips64:
1912   case llvm::Triple::mips64el:
1913     AddMIPSTargetArgs(Args, CmdArgs);
1914     break;
1915
1916   case llvm::Triple::ppc:
1917   case llvm::Triple::ppc64:
1918     AddPPCTargetArgs(Args, CmdArgs);
1919     break;
1920
1921   case llvm::Triple::sparc:
1922     AddSparcTargetArgs(Args, CmdArgs);
1923     break;
1924
1925   case llvm::Triple::x86:
1926   case llvm::Triple::x86_64:
1927     AddX86TargetArgs(Args, CmdArgs);
1928     break;
1929
1930   case llvm::Triple::hexagon:
1931     AddHexagonTargetArgs(Args, CmdArgs);
1932     break;
1933   }
1934
1935
1936
1937   // Pass the linker version in use.
1938   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
1939     CmdArgs.push_back("-target-linker-version");
1940     CmdArgs.push_back(A->getValue(Args));
1941   }
1942
1943   // -mno-omit-leaf-frame-pointer is the default on Darwin.
1944   if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
1945                    options::OPT_mno_omit_leaf_frame_pointer,
1946                    !getToolChain().getTriple().isOSDarwin()))
1947     CmdArgs.push_back("-momit-leaf-frame-pointer");
1948
1949   // Explicitly error on some things we know we don't support and can't just
1950   // ignore.
1951   types::ID InputType = Inputs[0].getType();
1952   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
1953     Arg *Unsupported;
1954     if (types::isCXX(InputType) &&
1955         getToolChain().getTriple().isOSDarwin() &&
1956         getToolChain().getTriple().getArch() == llvm::Triple::x86) {
1957       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
1958           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
1959         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
1960           << Unsupported->getOption().getName();
1961     }
1962   }
1963
1964   Args.AddAllArgs(CmdArgs, options::OPT_v);
1965   Args.AddLastArg(CmdArgs, options::OPT_H);
1966   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
1967     CmdArgs.push_back("-header-include-file");
1968     CmdArgs.push_back(D.CCPrintHeadersFilename ?
1969                       D.CCPrintHeadersFilename : "-");
1970   }
1971   Args.AddLastArg(CmdArgs, options::OPT_P);
1972   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
1973
1974   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
1975     CmdArgs.push_back("-diagnostic-log-file");
1976     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
1977                       D.CCLogDiagnosticsFilename : "-");
1978   }
1979
1980   // Use the last option from "-g" group. "-gline-tables-only" is
1981   // preserved, all other debug options are substituted with "-g".
1982   Args.ClaimAllArgs(options::OPT_g_Group);
1983   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
1984     if (A->getOption().matches(options::OPT_gline_tables_only)) {
1985       CmdArgs.push_back("-gline-tables-only");
1986     } else if (!A->getOption().matches(options::OPT_g0) &&
1987                !A->getOption().matches(options::OPT_ggdb0)) {
1988       CmdArgs.push_back("-g");
1989     }
1990   }
1991
1992   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
1993   Args.ClaimAllArgs(options::OPT_g_flags_Group);
1994
1995   Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
1996   Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
1997
1998   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
1999
2000   if (Args.hasArg(options::OPT_ftest_coverage) ||
2001       Args.hasArg(options::OPT_coverage))
2002     CmdArgs.push_back("-femit-coverage-notes");
2003   if (Args.hasArg(options::OPT_fprofile_arcs) ||
2004       Args.hasArg(options::OPT_coverage))
2005     CmdArgs.push_back("-femit-coverage-data");
2006
2007   if (C.getArgs().hasArg(options::OPT_c) ||
2008       C.getArgs().hasArg(options::OPT_S)) {
2009     if (Output.isFilename()) {
2010       CmdArgs.push_back("-coverage-file");
2011       CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
2012     }
2013   }
2014
2015   // Pass options for controlling the default header search paths.
2016   if (Args.hasArg(options::OPT_nostdinc)) {
2017     CmdArgs.push_back("-nostdsysteminc");
2018     CmdArgs.push_back("-nobuiltininc");
2019   } else {
2020     if (Args.hasArg(options::OPT_nostdlibinc))
2021         CmdArgs.push_back("-nostdsysteminc");
2022     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2023     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2024   }
2025
2026   // Pass the path to compiler resource files.
2027   CmdArgs.push_back("-resource-dir");
2028   CmdArgs.push_back(D.ResourceDir.c_str());
2029
2030   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2031
2032   bool ARCMTEnabled = false;
2033   if (!Args.hasArg(options::OPT_fno_objc_arc)) {
2034     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2035                                        options::OPT_ccc_arcmt_modify,
2036                                        options::OPT_ccc_arcmt_migrate)) {
2037       ARCMTEnabled = true;
2038       switch (A->getOption().getID()) {
2039       default:
2040         llvm_unreachable("missed a case");
2041       case options::OPT_ccc_arcmt_check:
2042         CmdArgs.push_back("-arcmt-check");
2043         break;
2044       case options::OPT_ccc_arcmt_modify:
2045         CmdArgs.push_back("-arcmt-modify");
2046         break;
2047       case options::OPT_ccc_arcmt_migrate:
2048         CmdArgs.push_back("-arcmt-migrate");
2049         CmdArgs.push_back("-mt-migrate-directory");
2050         CmdArgs.push_back(A->getValue(Args));
2051
2052         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2053         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2054         break;
2055       }
2056     }
2057   }
2058
2059   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2060     if (ARCMTEnabled) {
2061       D.Diag(diag::err_drv_argument_not_allowed_with)
2062         << A->getAsString(Args) << "-ccc-arcmt-migrate";
2063     }
2064     CmdArgs.push_back("-mt-migrate-directory");
2065     CmdArgs.push_back(A->getValue(Args));
2066
2067     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2068                      options::OPT_objcmt_migrate_subscripting)) {
2069       // None specified, means enable them all.
2070       CmdArgs.push_back("-objcmt-migrate-literals");
2071       CmdArgs.push_back("-objcmt-migrate-subscripting");
2072     } else {
2073       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2074       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2075     }
2076   }
2077
2078   // Add preprocessing options like -I, -D, etc. if we are using the
2079   // preprocessor.
2080   //
2081   // FIXME: Support -fpreprocessed
2082   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2083     AddPreprocessingOptions(C, D, Args, CmdArgs, Output, Inputs);
2084
2085   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2086   // that "The compiler can only warn and ignore the option if not recognized".
2087   // When building with ccache, it will pass -D options to clang even on
2088   // preprocessed inputs and configure concludes that -fPIC is not supported.
2089   Args.ClaimAllArgs(options::OPT_D);
2090
2091   // Manually translate -O to -O2 and -O4 to -O3; let clang reject
2092   // others.
2093   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2094     if (A->getOption().matches(options::OPT_O4))
2095       CmdArgs.push_back("-O3");
2096     else if (A->getOption().matches(options::OPT_O) &&
2097              A->getValue(Args)[0] == '\0')
2098       CmdArgs.push_back("-O2");
2099     else
2100       A->render(Args, CmdArgs);
2101   }
2102
2103   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2104   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2105     CmdArgs.push_back("-pedantic");
2106   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2107   Args.AddLastArg(CmdArgs, options::OPT_w);
2108
2109   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2110   // (-ansi is equivalent to -std=c89).
2111   //
2112   // If a std is supplied, only add -trigraphs if it follows the
2113   // option.
2114   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2115     if (Std->getOption().matches(options::OPT_ansi))
2116       if (types::isCXX(InputType))
2117         CmdArgs.push_back("-std=c++98");
2118       else
2119         CmdArgs.push_back("-std=c89");
2120     else
2121       Std->render(Args, CmdArgs);
2122
2123     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
2124                                  options::OPT_trigraphs))
2125       if (A != Std)
2126         A->render(Args, CmdArgs);
2127   } else {
2128     // Honor -std-default.
2129     //
2130     // FIXME: Clang doesn't correctly handle -std= when the input language
2131     // doesn't match. For the time being just ignore this for C++ inputs;
2132     // eventually we want to do all the standard defaulting here instead of
2133     // splitting it between the driver and clang -cc1.
2134     if (!types::isCXX(InputType))
2135         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2136                                   "-std=", /*Joined=*/true);
2137     Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
2138   }
2139
2140   // Map the bizarre '-Wwrite-strings' flag to a more sensible
2141   // '-fconst-strings'; this better indicates its actual behavior.
2142   if (Args.hasFlag(options::OPT_Wwrite_strings, options::OPT_Wno_write_strings,
2143                    false)) {
2144     // For perfect compatibility with GCC, we do this even in the presence of
2145     // '-w'. This flag names something other than a warning for GCC.
2146     CmdArgs.push_back("-fconst-strings");
2147   }
2148
2149   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
2150   // during C++ compilation, which it is by default. GCC keeps this define even
2151   // in the presence of '-w', match this behavior bug-for-bug.
2152   if (types::isCXX(InputType) &&
2153       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
2154                    true)) {
2155     CmdArgs.push_back("-fdeprecated-macro");
2156   }
2157
2158   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
2159   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
2160     if (Asm->getOption().matches(options::OPT_fasm))
2161       CmdArgs.push_back("-fgnu-keywords");
2162     else
2163       CmdArgs.push_back("-fno-gnu-keywords");
2164   }
2165
2166   if (ShouldDisableCFI(Args, getToolChain()))
2167     CmdArgs.push_back("-fno-dwarf2-cfi-asm");
2168
2169   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
2170     CmdArgs.push_back("-fno-dwarf-directory-asm");
2171
2172   if (const char *pwd = ::getenv("PWD")) {
2173     // GCC also verifies that stat(pwd) and stat(".") have the same inode
2174     // number. Not doing those because stats are slow, but we could.
2175     if (llvm::sys::path::is_absolute(pwd)) {
2176       std::string CompDir = pwd;
2177       CmdArgs.push_back("-fdebug-compilation-dir");
2178       CmdArgs.push_back(Args.MakeArgString(CompDir));
2179     }
2180   }
2181
2182   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
2183                                options::OPT_ftemplate_depth_EQ)) {
2184     CmdArgs.push_back("-ftemplate-depth");
2185     CmdArgs.push_back(A->getValue(Args));
2186   }
2187
2188   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
2189     CmdArgs.push_back("-fconstexpr-depth");
2190     CmdArgs.push_back(A->getValue(Args));
2191   }
2192
2193   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
2194                                options::OPT_Wlarge_by_value_copy_def)) {
2195     if (A->getNumValues()) {
2196       StringRef bytes = A->getValue(Args);
2197       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
2198     } else
2199       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
2200   }
2201
2202   if (Arg *A = Args.getLastArg(options::OPT_fbounds_checking,
2203                                options::OPT_fbounds_checking_EQ)) {
2204     if (A->getNumValues()) {
2205       StringRef val = A->getValue(Args);
2206       CmdArgs.push_back(Args.MakeArgString("-fbounds-checking=" + val));
2207     } else
2208       CmdArgs.push_back("-fbounds-checking=1");
2209   }
2210
2211   if (Args.hasArg(options::OPT__relocatable_pch))
2212     CmdArgs.push_back("-relocatable-pch");
2213
2214   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
2215     CmdArgs.push_back("-fconstant-string-class");
2216     CmdArgs.push_back(A->getValue(Args));
2217   }
2218
2219   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
2220     CmdArgs.push_back("-ftabstop");
2221     CmdArgs.push_back(A->getValue(Args));
2222   }
2223
2224   CmdArgs.push_back("-ferror-limit");
2225   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
2226     CmdArgs.push_back(A->getValue(Args));
2227   else
2228     CmdArgs.push_back("19");
2229
2230   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
2231     CmdArgs.push_back("-fmacro-backtrace-limit");
2232     CmdArgs.push_back(A->getValue(Args));
2233   }
2234
2235   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
2236     CmdArgs.push_back("-ftemplate-backtrace-limit");
2237     CmdArgs.push_back(A->getValue(Args));
2238   }
2239
2240   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
2241     CmdArgs.push_back("-fconstexpr-backtrace-limit");
2242     CmdArgs.push_back(A->getValue(Args));
2243   }
2244
2245   // Pass -fmessage-length=.
2246   CmdArgs.push_back("-fmessage-length");
2247   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
2248     CmdArgs.push_back(A->getValue(Args));
2249   } else {
2250     // If -fmessage-length=N was not specified, determine whether this is a
2251     // terminal and, if so, implicitly define -fmessage-length appropriately.
2252     unsigned N = llvm::sys::Process::StandardErrColumns();
2253     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
2254   }
2255
2256   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) {
2257     CmdArgs.push_back("-fvisibility");
2258     CmdArgs.push_back(A->getValue(Args));
2259   }
2260
2261   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
2262
2263   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
2264
2265   // -fhosted is default.
2266   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
2267       KernelOrKext)
2268     CmdArgs.push_back("-ffreestanding");
2269
2270   // Forward -f (flag) options which we can pass directly.
2271   Args.AddLastArg(CmdArgs, options::OPT_fcatch_undefined_behavior);
2272   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
2273   Args.AddLastArg(CmdArgs, options::OPT_fformat_extensions);
2274   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
2275   Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
2276   Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
2277   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
2278   Args.AddLastArg(CmdArgs, options::OPT_faltivec);
2279   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
2280   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
2281
2282   // Report and error for -faltivec on anything other then PowerPC.
2283   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
2284     if (!(getToolChain().getTriple().getArch() == llvm::Triple::ppc ||
2285           getToolChain().getTriple().getArch() == llvm::Triple::ppc64))
2286       D.Diag(diag::err_drv_argument_only_allowed_with)
2287         << A->getAsString(Args) << "ppc/ppc64";
2288
2289   if (getToolChain().SupportsProfiling())
2290     Args.AddLastArg(CmdArgs, options::OPT_pg);
2291
2292   if (Args.hasFlag(options::OPT_faddress_sanitizer,
2293                    options::OPT_fno_address_sanitizer, false))
2294     CmdArgs.push_back("-faddress-sanitizer");
2295
2296   if (Args.hasFlag(options::OPT_fthread_sanitizer,
2297                    options::OPT_fno_thread_sanitizer, false))
2298     CmdArgs.push_back("-fthread-sanitizer");
2299
2300   // -flax-vector-conversions is default.
2301   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
2302                     options::OPT_fno_lax_vector_conversions))
2303     CmdArgs.push_back("-fno-lax-vector-conversions");
2304
2305   if (Args.getLastArg(options::OPT_fapple_kext))
2306     CmdArgs.push_back("-fapple-kext");
2307
2308   if (Args.hasFlag(options::OPT_frewrite_includes,
2309                    options::OPT_fno_rewrite_includes, false))
2310     CmdArgs.push_back("-frewrite-includes");
2311
2312   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
2313   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
2314   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
2315   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
2316   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
2317
2318   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
2319     CmdArgs.push_back("-ftrapv-handler");
2320     CmdArgs.push_back(A->getValue(Args));
2321   }
2322
2323   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
2324
2325   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
2326   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
2327   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
2328                                options::OPT_fno_wrapv)) {
2329     if (A->getOption().matches(options::OPT_fwrapv))
2330       CmdArgs.push_back("-fwrapv");
2331   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
2332                                       options::OPT_fno_strict_overflow)) {
2333     if (A->getOption().matches(options::OPT_fno_strict_overflow))
2334       CmdArgs.push_back("-fwrapv");
2335   }
2336   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
2337   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
2338
2339   Args.AddLastArg(CmdArgs, options::OPT_pthread);
2340
2341   // -stack-protector=0 is default.
2342   unsigned StackProtectorLevel = 0;
2343   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2344                                options::OPT_fstack_protector_all,
2345                                options::OPT_fstack_protector)) {
2346     if (A->getOption().matches(options::OPT_fstack_protector))
2347       StackProtectorLevel = 1;
2348     else if (A->getOption().matches(options::OPT_fstack_protector_all))
2349       StackProtectorLevel = 2;
2350   } else {
2351     StackProtectorLevel =
2352       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
2353   }
2354   if (StackProtectorLevel) {
2355     CmdArgs.push_back("-stack-protector");
2356     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2357   }
2358
2359   // Translate -mstackrealign
2360   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
2361                    false)) {
2362     CmdArgs.push_back("-backend-option");
2363     CmdArgs.push_back("-force-align-stack");
2364   }
2365   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
2366                    false)) {
2367     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
2368   }
2369
2370   if (Args.hasArg(options::OPT_mstack_alignment)) {
2371     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
2372     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
2373   }
2374
2375   // Forward -f options with positive and negative forms; we translate
2376   // these by hand.
2377
2378   if (Args.hasArg(options::OPT_mkernel)) {
2379     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
2380       CmdArgs.push_back("-fapple-kext");
2381     if (!Args.hasArg(options::OPT_fbuiltin))
2382       CmdArgs.push_back("-fno-builtin");
2383     Args.ClaimAllArgs(options::OPT_fno_builtin);
2384   }
2385   // -fbuiltin is default.
2386   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
2387     CmdArgs.push_back("-fno-builtin");
2388
2389   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
2390                     options::OPT_fno_assume_sane_operator_new))
2391     CmdArgs.push_back("-fno-assume-sane-operator-new");
2392
2393   // -fblocks=0 is default.
2394   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
2395                    getToolChain().IsBlocksDefault()) ||
2396         (Args.hasArg(options::OPT_fgnu_runtime) &&
2397          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
2398          !Args.hasArg(options::OPT_fno_blocks))) {
2399     CmdArgs.push_back("-fblocks");
2400
2401     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
2402         !getToolChain().hasBlocksRuntime())
2403       CmdArgs.push_back("-fblocks-runtime-optional");
2404   }
2405
2406   // -fmodules enables modules (off by default). However, for C++/Objective-C++,
2407   // users must also pass -fcxx-modules. The latter flag will disappear once the
2408   // modules implementation is solid for C++/Objective-C++ programs as well.
2409   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2410     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
2411                                      options::OPT_fno_cxx_modules, 
2412                                      false);
2413     if (AllowedInCXX || !types::isCXX(InputType))
2414       CmdArgs.push_back("-fmodules");
2415   }
2416
2417   // -faccess-control is default.
2418   if (Args.hasFlag(options::OPT_fno_access_control,
2419                    options::OPT_faccess_control,
2420                    false))
2421     CmdArgs.push_back("-fno-access-control");
2422
2423   // -felide-constructors is the default.
2424   if (Args.hasFlag(options::OPT_fno_elide_constructors,
2425                    options::OPT_felide_constructors,
2426                    false))
2427     CmdArgs.push_back("-fno-elide-constructors");
2428
2429   // -frtti is default.
2430   if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
2431       KernelOrKext)
2432     CmdArgs.push_back("-fno-rtti");
2433
2434   // -fshort-enums=0 is default for all architectures except Hexagon.
2435   if (Args.hasFlag(options::OPT_fshort_enums,
2436                    options::OPT_fno_short_enums,
2437                    getToolChain().getTriple().getArch() ==
2438                    llvm::Triple::hexagon))
2439     CmdArgs.push_back("-fshort-enums");
2440
2441   // -fsigned-char is default.
2442   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
2443                     isSignedCharDefault(getToolChain().getTriple())))
2444     CmdArgs.push_back("-fno-signed-char");
2445
2446   // -fthreadsafe-static is default.
2447   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
2448                     options::OPT_fno_threadsafe_statics))
2449     CmdArgs.push_back("-fno-threadsafe-statics");
2450
2451   // -fuse-cxa-atexit is default.
2452   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
2453                     options::OPT_fno_use_cxa_atexit,
2454                    getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
2455                   getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 &&
2456               getToolChain().getTriple().getArch() != llvm::Triple::hexagon) ||
2457       KernelOrKext)
2458     CmdArgs.push_back("-fno-use-cxa-atexit");
2459
2460   // -fms-extensions=0 is default.
2461   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2462                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2463     CmdArgs.push_back("-fms-extensions");
2464
2465   // -fms-inline-asm.
2466   if (Args.hasArg(options::OPT_fenable_experimental_ms_inline_asm))
2467     CmdArgs.push_back("-fenable-experimental-ms-inline-asm");
2468
2469   // -fms-compatibility=0 is default.
2470   if (Args.hasFlag(options::OPT_fms_compatibility, 
2471                    options::OPT_fno_ms_compatibility,
2472                    (getToolChain().getTriple().getOS() == llvm::Triple::Win32 &&
2473                     Args.hasFlag(options::OPT_fms_extensions, 
2474                                  options::OPT_fno_ms_extensions,
2475                                  true))))
2476     CmdArgs.push_back("-fms-compatibility");
2477
2478   // -fmsc-version=1300 is default.
2479   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2480                    getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
2481       Args.hasArg(options::OPT_fmsc_version)) {
2482     StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
2483     if (msc_ver.empty())
2484       CmdArgs.push_back("-fmsc-version=1300");
2485     else
2486       CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
2487   }
2488
2489
2490   // -fborland-extensions=0 is default.
2491   if (Args.hasFlag(options::OPT_fborland_extensions,
2492                    options::OPT_fno_borland_extensions, false))
2493     CmdArgs.push_back("-fborland-extensions");
2494
2495   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
2496   // needs it.
2497   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
2498                    options::OPT_fno_delayed_template_parsing,
2499                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2500     CmdArgs.push_back("-fdelayed-template-parsing");
2501
2502   // -fgnu-keywords default varies depending on language; only pass if
2503   // specified.
2504   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
2505                                options::OPT_fno_gnu_keywords))
2506     A->render(Args, CmdArgs);
2507
2508   if (Args.hasFlag(options::OPT_fgnu89_inline,
2509                    options::OPT_fno_gnu89_inline,
2510                    false))
2511     CmdArgs.push_back("-fgnu89-inline");
2512
2513   if (Args.hasArg(options::OPT_fno_inline))
2514     CmdArgs.push_back("-fno-inline");
2515
2516   if (Args.hasArg(options::OPT_fno_inline_functions))
2517     CmdArgs.push_back("-fno-inline-functions");
2518
2519   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
2520
2521   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
2522   // legacy is the default.
2523   if (objcRuntime.isNonFragile()) {
2524     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2525                       options::OPT_fno_objc_legacy_dispatch,
2526                       objcRuntime.isLegacyDispatchDefaultForArch(
2527                         getToolChain().getTriple().getArch()))) {
2528       if (getToolChain().UseObjCMixedDispatch())
2529         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2530       else
2531         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2532     }
2533   }
2534
2535   // -fobjc-default-synthesize-properties=1 is default. This only has an effect
2536   // if the nonfragile objc abi is used.
2537   if (getToolChain().IsObjCDefaultSynthPropertiesDefault()) {
2538     CmdArgs.push_back("-fobjc-default-synthesize-properties");
2539   }
2540
2541   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2542   // NOTE: This logic is duplicated in ToolChains.cpp.
2543   bool ARC = isObjCAutoRefCount(Args);
2544   if (ARC) {
2545     if (!getToolChain().SupportsObjCARC())
2546       D.Diag(diag::err_arc_unsupported);
2547
2548     CmdArgs.push_back("-fobjc-arc");
2549
2550     // FIXME: It seems like this entire block, and several around it should be
2551     // wrapped in isObjC, but for now we just use it here as this is where it
2552     // was being used previously.
2553     if (types::isCXX(InputType) && types::isObjC(InputType)) {
2554       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2555         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2556       else
2557         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2558     }
2559
2560     // Allow the user to enable full exceptions code emission.
2561     // We define off for Objective-CC, on for Objective-C++.
2562     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2563                      options::OPT_fno_objc_arc_exceptions,
2564                      /*default*/ types::isCXX(InputType)))
2565       CmdArgs.push_back("-fobjc-arc-exceptions");
2566   }
2567
2568   // -fobjc-infer-related-result-type is the default, except in the Objective-C
2569   // rewriter.
2570   if (rewriteKind != RK_None)
2571     CmdArgs.push_back("-fno-objc-infer-related-result-type");
2572
2573   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
2574   // takes precedence.
2575   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
2576   if (!GCArg)
2577     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
2578   if (GCArg) {
2579     if (ARC) {
2580       D.Diag(diag::err_drv_objc_gc_arr)
2581         << GCArg->getAsString(Args);
2582     } else if (getToolChain().SupportsObjCGC()) {
2583       GCArg->render(Args, CmdArgs);
2584     } else {
2585       // FIXME: We should move this to a hard error.
2586       D.Diag(diag::warn_drv_objc_gc_unsupported)
2587         << GCArg->getAsString(Args);
2588     }
2589   }
2590
2591   // Add exception args.
2592   addExceptionArgs(Args, InputType, getToolChain().getTriple(),
2593                    KernelOrKext, objcRuntime, CmdArgs);
2594
2595   if (getToolChain().UseSjLjExceptions())
2596     CmdArgs.push_back("-fsjlj-exceptions");
2597
2598   // C++ "sane" operator new.
2599   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
2600                     options::OPT_fno_assume_sane_operator_new))
2601     CmdArgs.push_back("-fno-assume-sane-operator-new");
2602
2603   // -fconstant-cfstrings is default, and may be subject to argument translation
2604   // on Darwin.
2605   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
2606                     options::OPT_fno_constant_cfstrings) ||
2607       !Args.hasFlag(options::OPT_mconstant_cfstrings,
2608                     options::OPT_mno_constant_cfstrings))
2609     CmdArgs.push_back("-fno-constant-cfstrings");
2610
2611   // -fshort-wchar default varies depending on platform; only
2612   // pass if specified.
2613   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
2614     A->render(Args, CmdArgs);
2615
2616   // -fno-pascal-strings is default, only pass non-default. If the tool chain
2617   // happened to translate to -mpascal-strings, we want to back translate here.
2618   //
2619   // FIXME: This is gross; that translation should be pulled from the
2620   // tool chain.
2621   if (Args.hasFlag(options::OPT_fpascal_strings,
2622                    options::OPT_fno_pascal_strings,
2623                    false) ||
2624       Args.hasFlag(options::OPT_mpascal_strings,
2625                    options::OPT_mno_pascal_strings,
2626                    false))
2627     CmdArgs.push_back("-fpascal-strings");
2628
2629   // Honor -fpack-struct= and -fpack-struct, if given. Note that
2630   // -fno-pack-struct doesn't apply to -fpack-struct=.
2631   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
2632     std::string PackStructStr = "-fpack-struct=";
2633     PackStructStr += A->getValue(Args);
2634     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
2635   } else if (Args.hasFlag(options::OPT_fpack_struct,
2636                           options::OPT_fno_pack_struct, false)) {
2637     CmdArgs.push_back("-fpack-struct=1");
2638   }
2639
2640   if (Args.hasArg(options::OPT_mkernel) ||
2641       Args.hasArg(options::OPT_fapple_kext)) {
2642     if (!Args.hasArg(options::OPT_fcommon))
2643       CmdArgs.push_back("-fno-common");
2644     Args.ClaimAllArgs(options::OPT_fno_common);
2645   }
2646
2647   // -fcommon is default, only pass non-default.
2648   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
2649     CmdArgs.push_back("-fno-common");
2650
2651   // -fsigned-bitfields is default, and clang doesn't yet support
2652   // -funsigned-bitfields.
2653   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
2654                     options::OPT_funsigned_bitfields))
2655     D.Diag(diag::warn_drv_clang_unsupported)
2656       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
2657
2658   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
2659   if (!Args.hasFlag(options::OPT_ffor_scope,
2660                     options::OPT_fno_for_scope))
2661     D.Diag(diag::err_drv_clang_unsupported)
2662       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
2663
2664   // -fcaret-diagnostics is default.
2665   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2666                     options::OPT_fno_caret_diagnostics, true))
2667     CmdArgs.push_back("-fno-caret-diagnostics");
2668
2669   // -fdiagnostics-fixit-info is default, only pass non-default.
2670   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2671                     options::OPT_fno_diagnostics_fixit_info))
2672     CmdArgs.push_back("-fno-diagnostics-fixit-info");
2673
2674   // Enable -fdiagnostics-show-option by default.
2675   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2676                    options::OPT_fno_diagnostics_show_option))
2677     CmdArgs.push_back("-fdiagnostics-show-option");
2678
2679   if (const Arg *A =
2680         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2681     CmdArgs.push_back("-fdiagnostics-show-category");
2682     CmdArgs.push_back(A->getValue(Args));
2683   }
2684
2685   if (const Arg *A =
2686         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2687     CmdArgs.push_back("-fdiagnostics-format");
2688     CmdArgs.push_back(A->getValue(Args));
2689   }
2690
2691   if (Arg *A = Args.getLastArg(
2692       options::OPT_fdiagnostics_show_note_include_stack,
2693       options::OPT_fno_diagnostics_show_note_include_stack)) {
2694     if (A->getOption().matches(
2695         options::OPT_fdiagnostics_show_note_include_stack))
2696       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2697     else
2698       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2699   }
2700
2701   // Color diagnostics are the default, unless the terminal doesn't support
2702   // them.
2703   if (Args.hasFlag(options::OPT_fcolor_diagnostics,
2704                    options::OPT_fno_color_diagnostics,
2705                    llvm::sys::Process::StandardErrHasColors()))
2706     CmdArgs.push_back("-fcolor-diagnostics");
2707
2708   if (!Args.hasFlag(options::OPT_fshow_source_location,
2709                     options::OPT_fno_show_source_location))
2710     CmdArgs.push_back("-fno-show-source-location");
2711
2712   if (!Args.hasFlag(options::OPT_fshow_column,
2713                     options::OPT_fno_show_column,
2714                     true))
2715     CmdArgs.push_back("-fno-show-column");
2716
2717   if (!Args.hasFlag(options::OPT_fspell_checking,
2718                     options::OPT_fno_spell_checking))
2719     CmdArgs.push_back("-fno-spell-checking");
2720
2721
2722   // Silently ignore -fasm-blocks for now.
2723   (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
2724                       false);
2725
2726   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
2727     A->render(Args, CmdArgs);
2728
2729   // -fdollars-in-identifiers default varies depending on platform and
2730   // language; only pass if specified.
2731   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
2732                                options::OPT_fno_dollars_in_identifiers)) {
2733     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
2734       CmdArgs.push_back("-fdollars-in-identifiers");
2735     else
2736       CmdArgs.push_back("-fno-dollars-in-identifiers");
2737   }
2738
2739   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
2740   // practical purposes.
2741   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
2742                                options::OPT_fno_unit_at_a_time)) {
2743     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
2744       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
2745   }
2746
2747   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
2748                    options::OPT_fno_apple_pragma_pack, false))
2749     CmdArgs.push_back("-fapple-pragma-pack");
2750
2751   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
2752   //
2753   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
2754 #if 0
2755   if (getToolChain().getTriple().isOSDarwin() &&
2756       (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2757        getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
2758     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
2759       CmdArgs.push_back("-fno-builtin-strcat");
2760     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
2761       CmdArgs.push_back("-fno-builtin-strcpy");
2762   }
2763 #endif
2764
2765   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
2766   if (Arg *A = Args.getLastArg(options::OPT_traditional,
2767                                options::OPT_traditional_cpp)) {
2768     if (isa<PreprocessJobAction>(JA))
2769       CmdArgs.push_back("-traditional-cpp");
2770     else
2771       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2772   }
2773
2774   Args.AddLastArg(CmdArgs, options::OPT_dM);
2775   Args.AddLastArg(CmdArgs, options::OPT_dD);
2776   
2777   // Handle serialized diagnostics.
2778   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
2779     CmdArgs.push_back("-serialize-diagnostic-file");
2780     CmdArgs.push_back(Args.MakeArgString(A->getValue(Args)));
2781   }
2782
2783   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
2784   // parser.
2785   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
2786   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
2787          ie = Args.filtered_end(); it != ie; ++it) {
2788     (*it)->claim();
2789
2790     // We translate this by hand to the -cc1 argument, since nightly test uses
2791     // it and developers have been trained to spell it with -mllvm.
2792     if (StringRef((*it)->getValue(Args, 0)) == "-disable-llvm-optzns")
2793       CmdArgs.push_back("-disable-llvm-optzns");
2794     else
2795       (*it)->render(Args, CmdArgs);
2796   }
2797
2798   if (Output.getType() == types::TY_Dependencies) {
2799     // Handled with other dependency code.
2800   } else if (Output.isFilename()) {
2801     CmdArgs.push_back("-o");
2802     CmdArgs.push_back(Output.getFilename());
2803   } else {
2804     assert(Output.isNothing() && "Invalid output.");
2805   }
2806
2807   for (InputInfoList::const_iterator
2808          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2809     const InputInfo &II = *it;
2810     CmdArgs.push_back("-x");
2811     CmdArgs.push_back(types::getTypeName(II.getType()));
2812     if (II.isFilename())
2813       CmdArgs.push_back(II.getFilename());
2814     else
2815       II.getInputArg().renderAsInput(Args, CmdArgs);
2816   }
2817
2818   Args.AddAllArgs(CmdArgs, options::OPT_undef);
2819
2820   const char *Exec = getToolChain().getDriver().getClangProgramPath();
2821
2822   // Optionally embed the -cc1 level arguments into the debug info, for build
2823   // analysis.
2824   if (getToolChain().UseDwarfDebugFlags()) {
2825     ArgStringList OriginalArgs;
2826     for (ArgList::const_iterator it = Args.begin(),
2827            ie = Args.end(); it != ie; ++it)
2828       (*it)->render(Args, OriginalArgs);
2829
2830     SmallString<256> Flags;
2831     Flags += Exec;
2832     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
2833       Flags += " ";
2834       Flags += OriginalArgs[i];
2835     }
2836     CmdArgs.push_back("-dwarf-debug-flags");
2837     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
2838   }
2839
2840   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2841
2842   if (Arg *A = Args.getLastArg(options::OPT_pg))
2843     if (Args.hasArg(options::OPT_fomit_frame_pointer))
2844       D.Diag(diag::err_drv_argument_not_allowed_with)
2845         << "-fomit-frame-pointer" << A->getAsString(Args);
2846
2847   // Claim some arguments which clang supports automatically.
2848
2849   // -fpch-preprocess is used with gcc to add a special marker in the output to
2850   // include the PCH file. Clang's PTH solution is completely transparent, so we
2851   // do not need to deal with it at all.
2852   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
2853
2854   // Claim some arguments which clang doesn't support, but we don't
2855   // care to warn the user about.
2856   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
2857   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
2858
2859   // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
2860   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
2861   Args.ClaimAllArgs(options::OPT_emit_llvm);
2862 }
2863
2864 void ClangAs::AddARMTargetArgs(const ArgList &Args,
2865                                ArgStringList &CmdArgs) const {
2866   const Driver &D = getToolChain().getDriver();
2867   llvm::Triple Triple = getToolChain().getTriple();
2868
2869   // Set the CPU based on -march= and -mcpu=.
2870   CmdArgs.push_back("-target-cpu");
2871   CmdArgs.push_back(Args.MakeArgString(getARMTargetCPU(Args, Triple)));
2872
2873   // Honor -mfpu=.
2874   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
2875     addFPUArgs(D, A, Args, CmdArgs);
2876
2877   // Honor -mfpmath=.
2878   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ))
2879     addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
2880 }
2881
2882 /// Add options related to the Objective-C runtime/ABI.
2883 ///
2884 /// Returns true if the runtime is non-fragile.
2885 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
2886                                       ArgStringList &cmdArgs,
2887                                       RewriteKind rewriteKind) const {
2888   // Look for the controlling runtime option.
2889   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
2890                                     options::OPT_fgnu_runtime,
2891                                     options::OPT_fobjc_runtime_EQ);
2892
2893   // Just forward -fobjc-runtime= to the frontend.  This supercedes
2894   // options about fragility.
2895   if (runtimeArg &&
2896       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
2897     ObjCRuntime runtime;
2898     StringRef value = runtimeArg->getValue(args);
2899     if (runtime.tryParse(value)) {
2900       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
2901         << value;
2902     }
2903
2904     runtimeArg->render(args, cmdArgs);
2905     return runtime;
2906   }
2907
2908   // Otherwise, we'll need the ABI "version".  Version numbers are
2909   // slightly confusing for historical reasons:
2910   //   1 - Traditional "fragile" ABI
2911   //   2 - Non-fragile ABI, version 1
2912   //   3 - Non-fragile ABI, version 2
2913   unsigned objcABIVersion = 1;
2914   // If -fobjc-abi-version= is present, use that to set the version.
2915   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
2916     StringRef value = abiArg->getValue(args);
2917     if (value == "1")
2918       objcABIVersion = 1;
2919     else if (value == "2")
2920       objcABIVersion = 2;
2921     else if (value == "3")
2922       objcABIVersion = 3;
2923     else
2924       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
2925         << value;
2926   } else {
2927     // Otherwise, determine if we are using the non-fragile ABI.
2928     bool nonFragileABIIsDefault = 
2929       (rewriteKind == RK_NonFragile || 
2930        (rewriteKind == RK_None &&
2931         getToolChain().IsObjCNonFragileABIDefault()));
2932     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
2933                      options::OPT_fno_objc_nonfragile_abi,
2934                      nonFragileABIIsDefault)) {
2935       // Determine the non-fragile ABI version to use.
2936 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
2937       unsigned nonFragileABIVersion = 1;
2938 #else
2939       unsigned nonFragileABIVersion = 2;
2940 #endif
2941
2942       if (Arg *abiArg = args.getLastArg(
2943             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
2944         StringRef value = abiArg->getValue(args);
2945         if (value == "1")
2946           nonFragileABIVersion = 1;
2947         else if (value == "2")
2948           nonFragileABIVersion = 2;
2949         else
2950           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
2951             << value;
2952       }
2953
2954       objcABIVersion = 1 + nonFragileABIVersion;
2955     } else {
2956       objcABIVersion = 1;
2957     }
2958   }
2959
2960   // We don't actually care about the ABI version other than whether
2961   // it's non-fragile.
2962   bool isNonFragile = objcABIVersion != 1;
2963
2964   // If we have no runtime argument, ask the toolchain for its default runtime.
2965   // However, the rewriter only really supports the Mac runtime, so assume that.
2966   ObjCRuntime runtime;
2967   if (!runtimeArg) {
2968     switch (rewriteKind) {
2969     case RK_None:
2970       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
2971       break;
2972     case RK_Fragile:
2973       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
2974       break;
2975     case RK_NonFragile:
2976       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
2977       break;
2978     }
2979
2980   // -fnext-runtime
2981   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
2982     // On Darwin, make this use the default behavior for the toolchain.
2983     if (getToolChain().getTriple().isOSDarwin()) {
2984       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
2985
2986     // Otherwise, build for a generic macosx port.
2987     } else {
2988       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
2989     }
2990
2991   // -fgnu-runtime
2992   } else {
2993     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
2994     // Legacy behaviour is to target the gnustep runtime if we are i
2995     // non-fragile mode or the GCC runtime in fragile mode.
2996     if (isNonFragile)
2997       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple());
2998     else
2999       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
3000   }
3001
3002   cmdArgs.push_back(args.MakeArgString(
3003                                  "-fobjc-runtime=" + runtime.getAsString()));
3004   return runtime;
3005 }
3006
3007 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
3008                            const InputInfo &Output,
3009                            const InputInfoList &Inputs,
3010                            const ArgList &Args,
3011                            const char *LinkingOutput) const {
3012   ArgStringList CmdArgs;
3013
3014   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
3015   const InputInfo &Input = Inputs[0];
3016
3017   // Don't warn about "clang -w -c foo.s"
3018   Args.ClaimAllArgs(options::OPT_w);
3019   // and "clang -emit-llvm -c foo.s"
3020   Args.ClaimAllArgs(options::OPT_emit_llvm);
3021   // and "clang -use-gold-plugin -c foo.s"
3022   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
3023
3024   // Invoke ourselves in -cc1as mode.
3025   //
3026   // FIXME: Implement custom jobs for internal actions.
3027   CmdArgs.push_back("-cc1as");
3028
3029   // Add the "effective" target triple.
3030   CmdArgs.push_back("-triple");
3031   std::string TripleStr = 
3032     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
3033   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3034
3035   // Set the output mode, we currently only expect to be used as a real
3036   // assembler.
3037   CmdArgs.push_back("-filetype");
3038   CmdArgs.push_back("obj");
3039
3040   if (UseRelaxAll(C, Args))
3041     CmdArgs.push_back("-relax-all");
3042
3043   // Add target specific cpu and features flags.
3044   switch(getToolChain().getTriple().getArch()) {
3045   default:
3046     break;
3047
3048   case llvm::Triple::arm:
3049   case llvm::Triple::thumb:
3050     AddARMTargetArgs(Args, CmdArgs);
3051     break;
3052   }
3053
3054   // Ignore explicit -force_cpusubtype_ALL option.
3055   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
3056
3057   // Determine the original source input.
3058   const Action *SourceAction = &JA;
3059   while (SourceAction->getKind() != Action::InputClass) {
3060     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
3061     SourceAction = SourceAction->getInputs()[0];
3062   }
3063
3064   // Forward -g, assuming we are dealing with an actual assembly file.
3065   if (SourceAction->getType() == types::TY_Asm ||
3066       SourceAction->getType() == types::TY_PP_Asm) {
3067     Args.ClaimAllArgs(options::OPT_g_Group);
3068     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
3069       if (!A->getOption().matches(options::OPT_g0))
3070         CmdArgs.push_back("-g");
3071   }
3072
3073   // Optionally embed the -cc1as level arguments into the debug info, for build
3074   // analysis.
3075   if (getToolChain().UseDwarfDebugFlags()) {
3076     ArgStringList OriginalArgs;
3077     for (ArgList::const_iterator it = Args.begin(),
3078            ie = Args.end(); it != ie; ++it)
3079       (*it)->render(Args, OriginalArgs);
3080
3081     SmallString<256> Flags;
3082     const char *Exec = getToolChain().getDriver().getClangProgramPath();
3083     Flags += Exec;
3084     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3085       Flags += " ";
3086       Flags += OriginalArgs[i];
3087     }
3088     CmdArgs.push_back("-dwarf-debug-flags");
3089     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3090   }
3091
3092   // FIXME: Add -static support, once we have it.
3093
3094   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3095                        options::OPT_Xassembler);
3096   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
3097
3098   assert(Output.isFilename() && "Unexpected lipo output.");
3099   CmdArgs.push_back("-o");
3100   CmdArgs.push_back(Output.getFilename());
3101
3102   assert(Input.isFilename() && "Invalid input.");
3103   CmdArgs.push_back(Input.getFilename());
3104
3105   const char *Exec = getToolChain().getDriver().getClangProgramPath();
3106   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3107 }
3108
3109 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
3110                                const InputInfo &Output,
3111                                const InputInfoList &Inputs,
3112                                const ArgList &Args,
3113                                const char *LinkingOutput) const {
3114   const Driver &D = getToolChain().getDriver();
3115   ArgStringList CmdArgs;
3116
3117   for (ArgList::const_iterator
3118          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
3119     Arg *A = *it;
3120     if (A->getOption().hasForwardToGCC()) {
3121       // Don't forward any -g arguments to assembly steps.
3122       if (isa<AssembleJobAction>(JA) &&
3123           A->getOption().matches(options::OPT_g_Group))
3124         continue;
3125
3126       // It is unfortunate that we have to claim here, as this means
3127       // we will basically never report anything interesting for
3128       // platforms using a generic gcc, even if we are just using gcc
3129       // to get to the assembler.
3130       A->claim();
3131       A->render(Args, CmdArgs);
3132     }
3133   }
3134
3135   RenderExtraToolArgs(JA, CmdArgs);
3136
3137   // If using a driver driver, force the arch.
3138   const std::string &Arch = getToolChain().getArchName();
3139   if (getToolChain().getTriple().isOSDarwin()) {
3140     CmdArgs.push_back("-arch");
3141
3142     // FIXME: Remove these special cases.
3143     if (Arch == "powerpc")
3144       CmdArgs.push_back("ppc");
3145     else if (Arch == "powerpc64")
3146       CmdArgs.push_back("ppc64");
3147     else
3148       CmdArgs.push_back(Args.MakeArgString(Arch));
3149   }
3150
3151   // Try to force gcc to match the tool chain we want, if we recognize
3152   // the arch.
3153   //
3154   // FIXME: The triple class should directly provide the information we want
3155   // here.
3156   if (Arch == "i386" || Arch == "powerpc")
3157     CmdArgs.push_back("-m32");
3158   else if (Arch == "x86_64" || Arch == "powerpc64")
3159     CmdArgs.push_back("-m64");
3160
3161   if (Output.isFilename()) {
3162     CmdArgs.push_back("-o");
3163     CmdArgs.push_back(Output.getFilename());
3164   } else {
3165     assert(Output.isNothing() && "Unexpected output");
3166     CmdArgs.push_back("-fsyntax-only");
3167   }
3168
3169   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3170                        options::OPT_Xassembler);
3171
3172   // Only pass -x if gcc will understand it; otherwise hope gcc
3173   // understands the suffix correctly. The main use case this would go
3174   // wrong in is for linker inputs if they happened to have an odd
3175   // suffix; really the only way to get this to happen is a command
3176   // like '-x foobar a.c' which will treat a.c like a linker input.
3177   //
3178   // FIXME: For the linker case specifically, can we safely convert
3179   // inputs into '-Wl,' options?
3180   for (InputInfoList::const_iterator
3181          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3182     const InputInfo &II = *it;
3183
3184     // Don't try to pass LLVM or AST inputs to a generic gcc.
3185     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3186         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3187       D.Diag(diag::err_drv_no_linker_llvm_support)
3188         << getToolChain().getTripleString();
3189     else if (II.getType() == types::TY_AST)
3190       D.Diag(diag::err_drv_no_ast_support)
3191         << getToolChain().getTripleString();
3192
3193     if (types::canTypeBeUserSpecified(II.getType())) {
3194       CmdArgs.push_back("-x");
3195       CmdArgs.push_back(types::getTypeName(II.getType()));
3196     }
3197
3198     if (II.isFilename())
3199       CmdArgs.push_back(II.getFilename());
3200     else {
3201       const Arg &A = II.getInputArg();
3202
3203       // Reverse translate some rewritten options.
3204       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
3205         CmdArgs.push_back("-lstdc++");
3206         continue;
3207       }
3208
3209       // Don't render as input, we need gcc to do the translations.
3210       A.render(Args, CmdArgs);
3211     }
3212   }
3213
3214   const std::string customGCCName = D.getCCCGenericGCCName();
3215   const char *GCCName;
3216   if (!customGCCName.empty())
3217     GCCName = customGCCName.c_str();
3218   else if (D.CCCIsCXX) {
3219     GCCName = "g++";
3220   } else
3221     GCCName = "gcc";
3222
3223   const char *Exec =
3224     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3225   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3226 }
3227
3228 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
3229                                           ArgStringList &CmdArgs) const {
3230   CmdArgs.push_back("-E");
3231 }
3232
3233 void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
3234                                           ArgStringList &CmdArgs) const {
3235   // The type is good enough.
3236 }
3237
3238 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
3239                                        ArgStringList &CmdArgs) const {
3240   const Driver &D = getToolChain().getDriver();
3241
3242   // If -flto, etc. are present then make sure not to force assembly output.
3243   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
3244       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
3245     CmdArgs.push_back("-c");
3246   else {
3247     if (JA.getType() != types::TY_PP_Asm)
3248       D.Diag(diag::err_drv_invalid_gcc_output_type)
3249         << getTypeName(JA.getType());
3250
3251     CmdArgs.push_back("-S");
3252   }
3253 }
3254
3255 void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
3256                                         ArgStringList &CmdArgs) const {
3257   CmdArgs.push_back("-c");
3258 }
3259
3260 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
3261                                     ArgStringList &CmdArgs) const {
3262   // The types are (hopefully) good enough.
3263 }
3264
3265 // Hexagon tools start.
3266 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
3267                                         ArgStringList &CmdArgs) const {
3268
3269 }
3270 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3271                                const InputInfo &Output,
3272                                const InputInfoList &Inputs,
3273                                const ArgList &Args,
3274                                const char *LinkingOutput) const {
3275
3276   const Driver &D = getToolChain().getDriver();
3277   ArgStringList CmdArgs;
3278
3279   std::string MarchString = "-march=";
3280   MarchString += getHexagonTargetCPU(Args);
3281   CmdArgs.push_back(Args.MakeArgString(MarchString));
3282
3283   RenderExtraToolArgs(JA, CmdArgs);
3284
3285   if (Output.isFilename()) {
3286     CmdArgs.push_back("-o");
3287     CmdArgs.push_back(Output.getFilename());
3288   } else {
3289     assert(Output.isNothing() && "Unexpected output");
3290     CmdArgs.push_back("-fsyntax-only");
3291   }
3292
3293
3294   // Only pass -x if gcc will understand it; otherwise hope gcc
3295   // understands the suffix correctly. The main use case this would go
3296   // wrong in is for linker inputs if they happened to have an odd
3297   // suffix; really the only way to get this to happen is a command
3298   // like '-x foobar a.c' which will treat a.c like a linker input.
3299   //
3300   // FIXME: For the linker case specifically, can we safely convert
3301   // inputs into '-Wl,' options?
3302   for (InputInfoList::const_iterator
3303          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3304     const InputInfo &II = *it;
3305
3306     // Don't try to pass LLVM or AST inputs to a generic gcc.
3307     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3308         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3309       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3310         << getToolChain().getTripleString();
3311     else if (II.getType() == types::TY_AST)
3312       D.Diag(clang::diag::err_drv_no_ast_support)
3313         << getToolChain().getTripleString();
3314
3315     if (II.isFilename())
3316       CmdArgs.push_back(II.getFilename());
3317     else
3318       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
3319       II.getInputArg().render(Args, CmdArgs);
3320   }
3321
3322   const char *GCCName = "hexagon-as";
3323   const char *Exec =
3324     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3325   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3326
3327 }
3328 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
3329                                     ArgStringList &CmdArgs) const {
3330   // The types are (hopefully) good enough.
3331 }
3332
3333 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
3334                                const InputInfo &Output,
3335                                const InputInfoList &Inputs,
3336                                const ArgList &Args,
3337                                const char *LinkingOutput) const {
3338
3339   const Driver &D = getToolChain().getDriver();
3340   ArgStringList CmdArgs;
3341
3342   for (ArgList::const_iterator
3343          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
3344     Arg *A = *it;
3345     if (A->getOption().hasForwardToGCC()) {
3346       // Don't forward any -g arguments to assembly steps.
3347       if (isa<AssembleJobAction>(JA) &&
3348           A->getOption().matches(options::OPT_g_Group))
3349         continue;
3350
3351       // It is unfortunate that we have to claim here, as this means
3352       // we will basically never report anything interesting for
3353       // platforms using a generic gcc, even if we are just using gcc
3354       // to get to the assembler.
3355       A->claim();
3356       A->render(Args, CmdArgs);
3357     }
3358   }
3359
3360   RenderExtraToolArgs(JA, CmdArgs);
3361
3362   // Add Arch Information
3363   Arg *A;
3364   if ((A = getLastHexagonArchArg(Args))) {
3365     if (A->getOption().matches(options::OPT_m_Joined))
3366       A->render(Args, CmdArgs);
3367     else
3368       CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
3369   }
3370   else {
3371     CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
3372   }
3373
3374   CmdArgs.push_back("-mqdsp6-compat");
3375
3376   const char *GCCName;
3377   if (C.getDriver().CCCIsCXX)
3378     GCCName = "hexagon-g++";
3379   else
3380     GCCName = "hexagon-gcc";
3381   const char *Exec =
3382     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3383
3384   if (Output.isFilename()) {
3385     CmdArgs.push_back("-o");
3386     CmdArgs.push_back(Output.getFilename());
3387   }
3388
3389   for (InputInfoList::const_iterator
3390          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3391     const InputInfo &II = *it;
3392
3393     // Don't try to pass LLVM or AST inputs to a generic gcc.
3394     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3395         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3396       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3397         << getToolChain().getTripleString();
3398     else if (II.getType() == types::TY_AST)
3399       D.Diag(clang::diag::err_drv_no_ast_support)
3400         << getToolChain().getTripleString();
3401
3402     if (II.isFilename())
3403       CmdArgs.push_back(II.getFilename());
3404     else
3405       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
3406       II.getInputArg().render(Args, CmdArgs);
3407   }
3408   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3409
3410 }
3411 // Hexagon tools end.
3412
3413
3414 const char *darwin::CC1::getCC1Name(types::ID Type) const {
3415   switch (Type) {
3416   default:
3417     llvm_unreachable("Unexpected type for Darwin CC1 tool.");
3418   case types::TY_Asm:
3419   case types::TY_C: case types::TY_CHeader:
3420   case types::TY_PP_C: case types::TY_PP_CHeader:
3421     return "cc1";
3422   case types::TY_ObjC: case types::TY_ObjCHeader:
3423   case types::TY_PP_ObjC: case types::TY_PP_ObjC_Alias:
3424   case types::TY_PP_ObjCHeader:
3425     return "cc1obj";
3426   case types::TY_CXX: case types::TY_CXXHeader:
3427   case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
3428     return "cc1plus";
3429   case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
3430   case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXX_Alias:
3431   case types::TY_PP_ObjCXXHeader:
3432     return "cc1objplus";
3433   }
3434 }
3435
3436 void darwin::CC1::anchor() {}
3437
3438 const char *darwin::CC1::getBaseInputName(const ArgList &Args,
3439                                           const InputInfoList &Inputs) {
3440   return Args.MakeArgString(
3441     llvm::sys::path::filename(Inputs[0].getBaseInput()));
3442 }
3443
3444 const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
3445                                           const InputInfoList &Inputs) {
3446   const char *Str = getBaseInputName(Args, Inputs);
3447
3448   if (const char *End = strrchr(Str, '.'))
3449     return Args.MakeArgString(std::string(Str, End));
3450
3451   return Str;
3452 }
3453
3454 const char *
3455 darwin::CC1::getDependencyFileName(const ArgList &Args,
3456                                    const InputInfoList &Inputs) {
3457   // FIXME: Think about this more.
3458   std::string Res;
3459
3460   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
3461     std::string Str(OutputOpt->getValue(Args));
3462     Res = Str.substr(0, Str.rfind('.'));
3463   } else {
3464     Res = darwin::CC1::getBaseInputStem(Args, Inputs);
3465   }
3466   return Args.MakeArgString(Res + ".d");
3467 }
3468
3469 void darwin::CC1::RemoveCC1UnsupportedArgs(ArgStringList &CmdArgs) const {
3470   for (ArgStringList::iterator it = CmdArgs.begin(), ie = CmdArgs.end();
3471        it != ie;) {
3472
3473     StringRef Option = *it;
3474     bool RemoveOption = false;
3475
3476     // Erase both -fmodule-cache-path and its argument.
3477     if (Option.equals("-fmodule-cache-path") && it+2 != ie) {
3478       it = CmdArgs.erase(it, it+2);
3479       ie = CmdArgs.end();
3480       continue;
3481     }
3482
3483     // Remove unsupported -f options.
3484     if (Option.startswith("-f")) {
3485       // Remove -f/-fno- to reduce the number of cases.
3486       if (Option.startswith("-fno-"))
3487         Option = Option.substr(5);
3488       else
3489         Option = Option.substr(2);
3490       RemoveOption = llvm::StringSwitch<bool>(Option)
3491         .Case("altivec", true)
3492         .Case("modules", true)
3493         .Case("diagnostics-show-note-include-stack", true)
3494         .Default(false);
3495     }
3496
3497     // Handle machine specific options.
3498     if (Option.startswith("-m")) {
3499       RemoveOption = llvm::StringSwitch<bool>(Option)
3500         .Case("-mthumb", true)
3501         .Case("-mno-thumb", true)
3502         .Case("-mno-fused-madd", true)
3503         .Case("-mlong-branch", true)
3504         .Case("-mlongcall", true)
3505         .Case("-mcpu=G4", true)
3506         .Case("-mcpu=G5", true)
3507         .Default(false);
3508     }
3509     
3510     // Handle warning options.
3511     if (Option.startswith("-W")) {
3512       // Remove -W/-Wno- to reduce the number of cases.
3513       if (Option.startswith("-Wno-"))
3514         Option = Option.substr(5);
3515       else
3516         Option = Option.substr(2);
3517       
3518       RemoveOption = llvm::StringSwitch<bool>(Option)
3519         .Case("address-of-temporary", true)
3520         .Case("ambiguous-member-template", true)
3521         .Case("analyzer-incompatible-plugin", true)
3522         .Case("array-bounds", true)
3523         .Case("array-bounds-pointer-arithmetic", true)
3524         .Case("bind-to-temporary-copy", true)
3525         .Case("bitwise-op-parentheses", true)
3526         .Case("bool-conversions", true)
3527         .Case("builtin-macro-redefined", true)
3528         .Case("c++-hex-floats", true)
3529         .Case("c++0x-compat", true)
3530         .Case("c++0x-extensions", true)
3531         .Case("c++0x-narrowing", true)
3532         .Case("c++11-compat", true)
3533         .Case("c++11-extensions", true)
3534         .Case("c++11-narrowing", true)
3535         .Case("conditional-uninitialized", true)
3536         .Case("constant-conversion", true)
3537         .Case("conversion-null", true)
3538         .Case("CFString-literal", true)
3539         .Case("constant-logical-operand", true)
3540         .Case("custom-atomic-properties", true)
3541         .Case("default-arg-special-member", true)
3542         .Case("delegating-ctor-cycles", true)
3543         .Case("delete-non-virtual-dtor", true)
3544         .Case("deprecated-implementations", true)
3545         .Case("deprecated-writable-strings", true)
3546         .Case("distributed-object-modifiers", true)
3547         .Case("duplicate-method-arg", true)
3548         .Case("dynamic-class-memaccess", true)
3549         .Case("enum-compare", true)
3550         .Case("exit-time-destructors", true)
3551         .Case("gnu", true)
3552         .Case("gnu-designator", true)
3553         .Case("header-hygiene", true)
3554         .Case("idiomatic-parentheses", true)
3555         .Case("ignored-qualifiers", true)
3556         .Case("implicit-atomic-properties", true)
3557         .Case("incompatible-pointer-types", true)
3558         .Case("incomplete-implementation", true)
3559         .Case("initializer-overrides", true)
3560         .Case("invalid-noreturn", true)
3561         .Case("invalid-token-paste", true)
3562         .Case("language-extension-token", true)
3563         .Case("literal-conversion", true)
3564         .Case("literal-range", true)
3565         .Case("local-type-template-args", true)
3566         .Case("logical-op-parentheses", true)
3567         .Case("method-signatures", true)
3568         .Case("microsoft", true)
3569         .Case("mismatched-tags", true)
3570         .Case("missing-method-return-type", true)
3571         .Case("non-pod-varargs", true)
3572         .Case("nonfragile-abi2", true)
3573         .Case("null-arithmetic", true)
3574         .Case("null-dereference", true)
3575         .Case("out-of-line-declaration", true)
3576         .Case("overriding-method-mismatch", true)
3577         .Case("readonly-setter-attrs", true)
3578         .Case("return-stack-address", true)
3579         .Case("self-assign", true)
3580         .Case("semicolon-before-method-body", true)
3581         .Case("sentinel", true)
3582         .Case("shift-overflow", true)
3583         .Case("shift-sign-overflow", true)
3584         .Case("sign-conversion", true)
3585         .Case("sizeof-array-argument", true)
3586         .Case("sizeof-pointer-memaccess", true)
3587         .Case("string-compare", true)
3588         .Case("super-class-method-mismatch", true)
3589         .Case("tautological-compare", true)
3590         .Case("typedef-redefinition", true)
3591         .Case("typename-missing", true)
3592         .Case("undefined-reinterpret-cast", true)
3593         .Case("unknown-warning-option", true)
3594         .Case("unnamed-type-template-args", true)
3595         .Case("unneeded-internal-declaration", true)
3596         .Case("unneeded-member-function", true)
3597         .Case("unused-comparison", true)
3598         .Case("unused-exception-parameter", true)
3599         .Case("unused-member-function", true)
3600         .Case("unused-result", true)
3601         .Case("vector-conversions", true)
3602         .Case("vla", true)
3603         .Case("used-but-marked-unused", true)
3604         .Case("weak-vtables", true)
3605         .Default(false);
3606     } // if (Option.startswith("-W"))
3607     if (RemoveOption) {
3608       it = CmdArgs.erase(it);
3609       ie = CmdArgs.end();
3610     } else {
3611       ++it;
3612     }
3613   }
3614 }
3615
3616 void darwin::CC1::AddCC1Args(const ArgList &Args,
3617                              ArgStringList &CmdArgs) const {
3618   const Driver &D = getToolChain().getDriver();
3619
3620   CheckCodeGenerationOptions(D, Args);
3621
3622   // Derived from cc1 spec.
3623   if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) &&
3624       !Args.hasArg(options::OPT_mdynamic_no_pic))
3625     CmdArgs.push_back("-fPIC");
3626
3627   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
3628       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
3629     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
3630       CmdArgs.push_back("-fno-builtin-strcat");
3631     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
3632       CmdArgs.push_back("-fno-builtin-strcpy");
3633   }
3634
3635   if (Args.hasArg(options::OPT_g_Flag) &&
3636       !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
3637     CmdArgs.push_back("-feliminate-unused-debug-symbols");
3638 }
3639
3640 void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
3641                                     const InputInfoList &Inputs,
3642                                     const ArgStringList &OutputArgs) const {
3643   const Driver &D = getToolChain().getDriver();
3644
3645   // Derived from cc1_options spec.
3646   if (Args.hasArg(options::OPT_fast) ||
3647       Args.hasArg(options::OPT_fastf) ||
3648       Args.hasArg(options::OPT_fastcp))
3649     CmdArgs.push_back("-O3");
3650
3651   if (Arg *A = Args.getLastArg(options::OPT_pg))
3652     if (Args.hasArg(options::OPT_fomit_frame_pointer))
3653       D.Diag(diag::err_drv_argument_not_allowed_with)
3654         << A->getAsString(Args) << "-fomit-frame-pointer";
3655
3656   AddCC1Args(Args, CmdArgs);
3657
3658   if (!Args.hasArg(options::OPT_Q))
3659     CmdArgs.push_back("-quiet");
3660
3661   CmdArgs.push_back("-dumpbase");
3662   CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
3663
3664   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
3665
3666   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
3667   Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
3668
3669   // FIXME: The goal is to use the user provided -o if that is our
3670   // final output, otherwise to drive from the original input
3671   // name. Find a clean way to go about this.
3672   if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
3673       Args.hasArg(options::OPT_o)) {
3674     Arg *OutputOpt = Args.getLastArg(options::OPT_o);
3675     CmdArgs.push_back("-auxbase-strip");
3676     CmdArgs.push_back(OutputOpt->getValue(Args));
3677   } else {
3678     CmdArgs.push_back("-auxbase");
3679     CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
3680   }
3681
3682   Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
3683
3684   Args.AddAllArgs(CmdArgs, options::OPT_O);
3685   // FIXME: -Wall is getting some special treatment. Investigate.
3686   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
3687   Args.AddLastArg(CmdArgs, options::OPT_w);
3688   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
3689                   options::OPT_trigraphs);
3690   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3691     // Honor -std-default.
3692     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3693                               "-std=", /*Joined=*/true);
3694   }
3695
3696   if (Args.hasArg(options::OPT_v))
3697     CmdArgs.push_back("-version");
3698   if (Args.hasArg(options::OPT_pg) &&
3699       getToolChain().SupportsProfiling())
3700     CmdArgs.push_back("-p");
3701   Args.AddLastArg(CmdArgs, options::OPT_p);
3702
3703   // The driver treats -fsyntax-only specially.
3704   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
3705       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
3706     // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
3707     // used to inhibit the default -fno-builtin-str{cat,cpy}.
3708     //
3709     // FIXME: Should we grow a better way to deal with "removing" args?
3710     for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
3711                                                options::OPT_fsyntax_only),
3712            ie = Args.filtered_end(); it != ie; ++it) {
3713       if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) &&
3714           !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) {
3715         (*it)->claim();
3716         (*it)->render(Args, CmdArgs);
3717       }
3718     }
3719   } else
3720     Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
3721
3722   // Claim Clang only -f options, they aren't worth warning about.
3723   Args.ClaimAllArgs(options::OPT_f_clang_Group);
3724
3725   Args.AddAllArgs(CmdArgs, options::OPT_undef);
3726   if (Args.hasArg(options::OPT_Qn))
3727     CmdArgs.push_back("-fno-ident");
3728
3729   // FIXME: This isn't correct.
3730   //Args.AddLastArg(CmdArgs, options::OPT__help)
3731   //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
3732
3733   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3734
3735   // FIXME: Still don't get what is happening here. Investigate.
3736   Args.AddAllArgs(CmdArgs, options::OPT__param);
3737
3738   if (Args.hasArg(options::OPT_fmudflap) ||
3739       Args.hasArg(options::OPT_fmudflapth)) {
3740     CmdArgs.push_back("-fno-builtin");
3741     CmdArgs.push_back("-fno-merge-constants");
3742   }
3743
3744   if (Args.hasArg(options::OPT_coverage)) {
3745     CmdArgs.push_back("-fprofile-arcs");
3746     CmdArgs.push_back("-ftest-coverage");
3747   }
3748
3749   if (types::isCXX(Inputs[0].getType()))
3750     CmdArgs.push_back("-D__private_extern__=extern");
3751 }
3752
3753 void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
3754                                     const InputInfoList &Inputs,
3755                                     const ArgStringList &OutputArgs) const {
3756   // Derived from cpp_options
3757   AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
3758
3759   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3760
3761   AddCC1Args(Args, CmdArgs);
3762
3763   // NOTE: The code below has some commonality with cpp_options, but
3764   // in classic gcc style ends up sending things in different
3765   // orders. This may be a good merge candidate once we drop pedantic
3766   // compatibility.
3767
3768   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
3769   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
3770                   options::OPT_trigraphs);
3771   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3772     // Honor -std-default.
3773     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3774                               "-std=", /*Joined=*/true);
3775   }
3776   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
3777   Args.AddLastArg(CmdArgs, options::OPT_w);
3778
3779   // The driver treats -fsyntax-only specially.
3780   Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
3781
3782   // Claim Clang only -f options, they aren't worth warning about.
3783   Args.ClaimAllArgs(options::OPT_f_clang_Group);
3784
3785   if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
3786       !Args.hasArg(options::OPT_fno_working_directory))
3787     CmdArgs.push_back("-fworking-directory");
3788
3789   Args.AddAllArgs(CmdArgs, options::OPT_O);
3790   Args.AddAllArgs(CmdArgs, options::OPT_undef);
3791   if (Args.hasArg(options::OPT_save_temps))
3792     CmdArgs.push_back("-fpch-preprocess");
3793 }
3794
3795 void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
3796                                           ArgStringList &CmdArgs,
3797                                           const InputInfoList &Inputs) const {
3798   const Driver &D = getToolChain().getDriver();
3799
3800   CheckPreprocessingOptions(D, Args);
3801
3802   // Derived from cpp_unique_options.
3803   // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
3804   Args.AddLastArg(CmdArgs, options::OPT_C);
3805   Args.AddLastArg(CmdArgs, options::OPT_CC);
3806   if (!Args.hasArg(options::OPT_Q))
3807     CmdArgs.push_back("-quiet");
3808   Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
3809   Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
3810   Args.AddLastArg(CmdArgs, options::OPT_v);
3811   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
3812   Args.AddLastArg(CmdArgs, options::OPT_P);
3813
3814   // FIXME: Handle %I properly.
3815   if (getToolChain().getArchName() == "x86_64") {
3816     CmdArgs.push_back("-imultilib");
3817     CmdArgs.push_back("x86_64");
3818   }
3819
3820   if (Args.hasArg(options::OPT_MD)) {
3821     CmdArgs.push_back("-MD");
3822     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
3823   }
3824
3825   if (Args.hasArg(options::OPT_MMD)) {
3826     CmdArgs.push_back("-MMD");
3827     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
3828   }
3829
3830   Args.AddLastArg(CmdArgs, options::OPT_M);
3831   Args.AddLastArg(CmdArgs, options::OPT_MM);
3832   Args.AddAllArgs(CmdArgs, options::OPT_MF);
3833   Args.AddLastArg(CmdArgs, options::OPT_MG);
3834   Args.AddLastArg(CmdArgs, options::OPT_MP);
3835   Args.AddAllArgs(CmdArgs, options::OPT_MQ);
3836   Args.AddAllArgs(CmdArgs, options::OPT_MT);
3837   if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
3838       (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
3839     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
3840       CmdArgs.push_back("-MQ");
3841       CmdArgs.push_back(OutputOpt->getValue(Args));
3842     }
3843   }
3844
3845   Args.AddLastArg(CmdArgs, options::OPT_remap);
3846   if (Args.hasArg(options::OPT_g3))
3847     CmdArgs.push_back("-dD");
3848   Args.AddLastArg(CmdArgs, options::OPT_H);
3849
3850   AddCPPArgs(Args, CmdArgs);
3851
3852   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
3853   Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
3854
3855   for (InputInfoList::const_iterator
3856          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3857     const InputInfo &II = *it;
3858
3859     CmdArgs.push_back(II.getFilename());
3860   }
3861
3862   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
3863                        options::OPT_Xpreprocessor);
3864
3865   if (Args.hasArg(options::OPT_fmudflap)) {
3866     CmdArgs.push_back("-D_MUDFLAP");
3867     CmdArgs.push_back("-include");
3868     CmdArgs.push_back("mf-runtime.h");
3869   }
3870
3871   if (Args.hasArg(options::OPT_fmudflapth)) {
3872     CmdArgs.push_back("-D_MUDFLAP");
3873     CmdArgs.push_back("-D_MUDFLAPTH");
3874     CmdArgs.push_back("-include");
3875     CmdArgs.push_back("mf-runtime.h");
3876   }
3877 }
3878
3879 void darwin::CC1::AddCPPArgs(const ArgList &Args,
3880                              ArgStringList &CmdArgs) const {
3881   // Derived from cpp spec.
3882
3883   if (Args.hasArg(options::OPT_static)) {
3884     // The gcc spec is broken here, it refers to dynamic but
3885     // that has been translated. Start by being bug compatible.
3886
3887     // if (!Args.hasArg(arglist.parser.dynamicOption))
3888     CmdArgs.push_back("-D__STATIC__");
3889   } else
3890     CmdArgs.push_back("-D__DYNAMIC__");
3891
3892   if (Args.hasArg(options::OPT_pthread))
3893     CmdArgs.push_back("-D_REENTRANT");
3894 }
3895
3896 void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
3897                                       const InputInfo &Output,
3898                                       const InputInfoList &Inputs,
3899                                       const ArgList &Args,
3900                                       const char *LinkingOutput) const {
3901   ArgStringList CmdArgs;
3902
3903   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
3904
3905   CmdArgs.push_back("-E");
3906
3907   if (Args.hasArg(options::OPT_traditional) ||
3908       Args.hasArg(options::OPT_traditional_cpp))
3909     CmdArgs.push_back("-traditional-cpp");
3910
3911   ArgStringList OutputArgs;
3912   assert(Output.isFilename() && "Unexpected CC1 output.");
3913   OutputArgs.push_back("-o");
3914   OutputArgs.push_back(Output.getFilename());
3915
3916   if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) {
3917     AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
3918   } else {
3919     AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
3920     CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3921   }
3922
3923   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
3924
3925   RemoveCC1UnsupportedArgs(CmdArgs);
3926
3927   const char *CC1Name = getCC1Name(Inputs[0].getType());
3928   const char *Exec =
3929     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
3930   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3931 }
3932
3933 void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
3934                                    const InputInfo &Output,
3935                                    const InputInfoList &Inputs,
3936                                    const ArgList &Args,
3937                                    const char *LinkingOutput) const {
3938   const Driver &D = getToolChain().getDriver();
3939   ArgStringList CmdArgs;
3940
3941   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
3942
3943   // Silence warning about unused --serialize-diagnostics
3944   Args.ClaimAllArgs(options::OPT__serialize_diags);
3945
3946   types::ID InputType = Inputs[0].getType();
3947   if (const Arg *A = Args.getLastArg(options::OPT_traditional))
3948     D.Diag(diag::err_drv_argument_only_allowed_with)
3949       << A->getAsString(Args) << "-E";
3950
3951   if (JA.getType() == types::TY_LLVM_IR ||
3952       JA.getType() == types::TY_LTO_IR)
3953     CmdArgs.push_back("-emit-llvm");
3954   else if (JA.getType() == types::TY_LLVM_BC ||
3955            JA.getType() == types::TY_LTO_BC)
3956     CmdArgs.push_back("-emit-llvm-bc");
3957   else if (Output.getType() == types::TY_AST)
3958     D.Diag(diag::err_drv_no_ast_support)
3959       << getToolChain().getTripleString();
3960   else if (JA.getType() != types::TY_PP_Asm &&
3961            JA.getType() != types::TY_PCH)
3962     D.Diag(diag::err_drv_invalid_gcc_output_type)
3963       << getTypeName(JA.getType());
3964
3965   ArgStringList OutputArgs;
3966   if (Output.getType() != types::TY_PCH) {
3967     OutputArgs.push_back("-o");
3968     if (Output.isNothing())
3969       OutputArgs.push_back("/dev/null");
3970     else
3971       OutputArgs.push_back(Output.getFilename());
3972   }
3973
3974   // There is no need for this level of compatibility, but it makes
3975   // diffing easier.
3976   bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
3977                           Args.hasArg(options::OPT_S));
3978
3979   if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
3980     AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
3981     if (OutputArgsEarly) {
3982       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
3983     } else {
3984       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
3985       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3986     }
3987   } else {
3988     CmdArgs.push_back("-fpreprocessed");
3989
3990     for (InputInfoList::const_iterator
3991            it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3992       const InputInfo &II = *it;
3993
3994       // Reject AST inputs.
3995       if (II.getType() == types::TY_AST) {
3996         D.Diag(diag::err_drv_no_ast_support)
3997           << getToolChain().getTripleString();
3998         return;
3999       }
4000
4001       CmdArgs.push_back(II.getFilename());
4002     }
4003
4004     if (OutputArgsEarly) {
4005       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
4006     } else {
4007       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
4008       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
4009     }
4010   }
4011
4012   if (Output.getType() == types::TY_PCH) {
4013     assert(Output.isFilename() && "Invalid PCH output.");
4014
4015     CmdArgs.push_back("-o");
4016     // NOTE: gcc uses a temp .s file for this, but there doesn't seem
4017     // to be a good reason.
4018     const char *TmpPath = C.getArgs().MakeArgString(
4019       D.GetTemporaryPath("cc", "s"));
4020     C.addTempFile(TmpPath);
4021     CmdArgs.push_back(TmpPath);
4022
4023     // If we're emitting a pch file with the last 4 characters of ".pth"
4024     // and falling back to llvm-gcc we want to use ".gch" instead.
4025     std::string OutputFile(Output.getFilename());
4026     size_t loc = OutputFile.rfind(".pth");
4027     if (loc != std::string::npos)
4028       OutputFile.replace(loc, 4, ".gch");
4029     const char *Tmp = C.getArgs().MakeArgString("--output-pch="+OutputFile);
4030     CmdArgs.push_back(Tmp);
4031   }
4032
4033   RemoveCC1UnsupportedArgs(CmdArgs);
4034
4035   const char *CC1Name = getCC1Name(Inputs[0].getType());
4036   const char *Exec =
4037     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
4038   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4039 }
4040
4041 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4042                                     const InputInfo &Output,
4043                                     const InputInfoList &Inputs,
4044                                     const ArgList &Args,
4045                                     const char *LinkingOutput) const {
4046   ArgStringList CmdArgs;
4047
4048   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4049   const InputInfo &Input = Inputs[0];
4050
4051   // Determine the original source input.
4052   const Action *SourceAction = &JA;
4053   while (SourceAction->getKind() != Action::InputClass) {
4054     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4055     SourceAction = SourceAction->getInputs()[0];
4056   }
4057
4058   // Forward -g, assuming we are dealing with an actual assembly file.
4059   if (SourceAction->getType() == types::TY_Asm ||
4060       SourceAction->getType() == types::TY_PP_Asm) {
4061     if (Args.hasArg(options::OPT_gstabs))
4062       CmdArgs.push_back("--gstabs");
4063     else if (Args.hasArg(options::OPT_g_Group))
4064       CmdArgs.push_back("-g");
4065   }
4066
4067   // Derived from asm spec.
4068   AddDarwinArch(Args, CmdArgs);
4069
4070   // Use -force_cpusubtype_ALL on x86 by default.
4071   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
4072       getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
4073       Args.hasArg(options::OPT_force__cpusubtype__ALL))
4074     CmdArgs.push_back("-force_cpusubtype_ALL");
4075
4076   if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
4077       (Args.hasArg(options::OPT_mkernel) ||
4078        Args.hasArg(options::OPT_static) ||
4079        Args.hasArg(options::OPT_fapple_kext)))
4080     CmdArgs.push_back("-static");
4081
4082   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4083                        options::OPT_Xassembler);
4084
4085   assert(Output.isFilename() && "Unexpected lipo output.");
4086   CmdArgs.push_back("-o");
4087   CmdArgs.push_back(Output.getFilename());
4088
4089   assert(Input.isFilename() && "Invalid input.");
4090   CmdArgs.push_back(Input.getFilename());
4091
4092   // asm_final spec is empty.
4093
4094   const char *Exec =
4095     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4096   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4097 }
4098
4099 void darwin::DarwinTool::anchor() {}
4100
4101 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
4102                                        ArgStringList &CmdArgs) const {
4103   StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
4104
4105   // Derived from darwin_arch spec.
4106   CmdArgs.push_back("-arch");
4107   CmdArgs.push_back(Args.MakeArgString(ArchName));
4108
4109   // FIXME: Is this needed anymore?
4110   if (ArchName == "arm")
4111     CmdArgs.push_back("-force_cpusubtype_ALL");
4112 }
4113
4114 void darwin::Link::AddLinkArgs(Compilation &C,
4115                                const ArgList &Args,
4116                                ArgStringList &CmdArgs) const {
4117   const Driver &D = getToolChain().getDriver();
4118   const toolchains::Darwin &DarwinTC = getDarwinToolChain();
4119
4120   unsigned Version[3] = { 0, 0, 0 };
4121   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4122     bool HadExtra;
4123     if (!Driver::GetReleaseVersion(A->getValue(Args), Version[0],
4124                                    Version[1], Version[2], HadExtra) ||
4125         HadExtra)
4126       D.Diag(diag::err_drv_invalid_version_number)
4127         << A->getAsString(Args);
4128   }
4129
4130   // Newer linkers support -demangle, pass it if supported and not disabled by
4131   // the user.
4132   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
4133     // Don't pass -demangle to ld_classic.
4134     //
4135     // FIXME: This is a temporary workaround, ld should be handling this.
4136     bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
4137                           Args.hasArg(options::OPT_static));
4138     if (getToolChain().getArch() == llvm::Triple::x86) {
4139       for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
4140                                                  options::OPT_Wl_COMMA),
4141              ie = Args.filtered_end(); it != ie; ++it) {
4142         const Arg *A = *it;
4143         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
4144           if (StringRef(A->getValue(Args, i)) == "-kext")
4145             UsesLdClassic = true;
4146       }
4147     }
4148     if (!UsesLdClassic)
4149       CmdArgs.push_back("-demangle");
4150   }
4151
4152   // If we are using LTO, then automatically create a temporary file path for
4153   // the linker to use, so that it's lifetime will extend past a possible
4154   // dsymutil step.
4155   if (Version[0] >= 116 && D.IsUsingLTO(Args)) {
4156     const char *TmpPath = C.getArgs().MakeArgString(
4157       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
4158     C.addTempFile(TmpPath);
4159     CmdArgs.push_back("-object_path_lto");
4160     CmdArgs.push_back(TmpPath);
4161   }
4162
4163   // Derived from the "link" spec.
4164   Args.AddAllArgs(CmdArgs, options::OPT_static);
4165   if (!Args.hasArg(options::OPT_static))
4166     CmdArgs.push_back("-dynamic");
4167   if (Args.hasArg(options::OPT_fgnu_runtime)) {
4168     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
4169     // here. How do we wish to handle such things?
4170   }
4171
4172   if (!Args.hasArg(options::OPT_dynamiclib)) {
4173     AddDarwinArch(Args, CmdArgs);
4174     // FIXME: Why do this only on this path?
4175     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
4176
4177     Args.AddLastArg(CmdArgs, options::OPT_bundle);
4178     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
4179     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
4180
4181     Arg *A;
4182     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
4183         (A = Args.getLastArg(options::OPT_current__version)) ||
4184         (A = Args.getLastArg(options::OPT_install__name)))
4185       D.Diag(diag::err_drv_argument_only_allowed_with)
4186         << A->getAsString(Args) << "-dynamiclib";
4187
4188     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
4189     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
4190     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
4191   } else {
4192     CmdArgs.push_back("-dylib");
4193
4194     Arg *A;
4195     if ((A = Args.getLastArg(options::OPT_bundle)) ||
4196         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
4197         (A = Args.getLastArg(options::OPT_client__name)) ||
4198         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
4199         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
4200         (A = Args.getLastArg(options::OPT_private__bundle)))
4201       D.Diag(diag::err_drv_argument_not_allowed_with)
4202         << A->getAsString(Args) << "-dynamiclib";
4203
4204     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
4205                               "-dylib_compatibility_version");
4206     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
4207                               "-dylib_current_version");
4208
4209     AddDarwinArch(Args, CmdArgs);
4210
4211     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
4212                               "-dylib_install_name");
4213   }
4214
4215   Args.AddLastArg(CmdArgs, options::OPT_all__load);
4216   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
4217   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
4218   if (DarwinTC.isTargetIPhoneOS())
4219     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
4220   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
4221   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
4222   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
4223   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
4224   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
4225   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
4226   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
4227   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
4228   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
4229   Args.AddAllArgs(CmdArgs, options::OPT_init);
4230
4231   // Add the deployment target.
4232   VersionTuple TargetVersion = DarwinTC.getTargetVersion();
4233
4234   // If we had an explicit -mios-simulator-version-min argument, honor that,
4235   // otherwise use the traditional deployment targets. We can't just check the
4236   // is-sim attribute because existing code follows this path, and the linker
4237   // may not handle the argument.
4238   //
4239   // FIXME: We may be able to remove this, once we can verify no one depends on
4240   // it.
4241   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
4242     CmdArgs.push_back("-ios_simulator_version_min");
4243   else if (DarwinTC.isTargetIPhoneOS())
4244     CmdArgs.push_back("-iphoneos_version_min");
4245   else
4246     CmdArgs.push_back("-macosx_version_min");
4247   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
4248
4249   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
4250   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
4251   Args.AddLastArg(CmdArgs, options::OPT_single__module);
4252   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
4253   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
4254
4255   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
4256                                      options::OPT_fno_pie,
4257                                      options::OPT_fno_PIE)) {
4258     if (A->getOption().matches(options::OPT_fpie) ||
4259         A->getOption().matches(options::OPT_fPIE))
4260       CmdArgs.push_back("-pie");
4261     else
4262       CmdArgs.push_back("-no_pie");
4263   }
4264
4265   Args.AddLastArg(CmdArgs, options::OPT_prebind);
4266   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
4267   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
4268   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
4269   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
4270   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
4271   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
4272   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
4273   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
4274   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
4275   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
4276   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
4277   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
4278   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
4279   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
4280   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
4281
4282   // Give --sysroot= preference, over the Apple specific behavior to also use
4283   // --isysroot as the syslibroot.
4284   StringRef sysroot = C.getSysRoot();
4285   if (sysroot != "") {
4286     CmdArgs.push_back("-syslibroot");
4287     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
4288   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4289     CmdArgs.push_back("-syslibroot");
4290     CmdArgs.push_back(A->getValue(Args));
4291   }
4292
4293   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
4294   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
4295   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
4296   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
4297   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
4298   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
4299   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
4300   Args.AddAllArgs(CmdArgs, options::OPT_y);
4301   Args.AddLastArg(CmdArgs, options::OPT_w);
4302   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
4303   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
4304   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
4305   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
4306   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
4307   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
4308   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
4309   Args.AddLastArg(CmdArgs, options::OPT_whyload);
4310   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
4311   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
4312   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
4313   Args.AddLastArg(CmdArgs, options::OPT_Mach);
4314 }
4315
4316 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
4317                                 const InputInfo &Output,
4318                                 const InputInfoList &Inputs,
4319                                 const ArgList &Args,
4320                                 const char *LinkingOutput) const {
4321   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
4322
4323   // The logic here is derived from gcc's behavior; most of which
4324   // comes from specs (starting with link_command). Consult gcc for
4325   // more information.
4326   ArgStringList CmdArgs;
4327
4328   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
4329   if (Args.hasArg(options::OPT_ccc_arcmt_check,
4330                   options::OPT_ccc_arcmt_migrate)) {
4331     for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
4332       (*I)->claim();
4333     const char *Exec =
4334       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
4335     CmdArgs.push_back(Output.getFilename());
4336     C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4337     return;
4338   }
4339
4340   // I'm not sure why this particular decomposition exists in gcc, but
4341   // we follow suite for ease of comparison.
4342   AddLinkArgs(C, Args, CmdArgs);
4343
4344   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
4345   Args.AddAllArgs(CmdArgs, options::OPT_s);
4346   Args.AddAllArgs(CmdArgs, options::OPT_t);
4347   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
4348   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4349   Args.AddLastArg(CmdArgs, options::OPT_e);
4350   Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
4351   Args.AddAllArgs(CmdArgs, options::OPT_r);
4352
4353   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
4354   // members of static archive libraries which implement Objective-C classes or
4355   // categories.
4356   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
4357     CmdArgs.push_back("-ObjC");
4358
4359   CmdArgs.push_back("-o");
4360   CmdArgs.push_back(Output.getFilename());
4361
4362   if (!Args.hasArg(options::OPT_nostdlib) &&
4363       !Args.hasArg(options::OPT_nostartfiles)) {
4364     // Derived from startfile spec.
4365     if (Args.hasArg(options::OPT_dynamiclib)) {
4366       // Derived from darwin_dylib1 spec.
4367       if (getDarwinToolChain().isTargetIOSSimulator()) {
4368         // The simulator doesn't have a versioned crt1 file.
4369         CmdArgs.push_back("-ldylib1.o");
4370       } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4371         if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4372           CmdArgs.push_back("-ldylib1.o");
4373       } else {
4374         if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4375           CmdArgs.push_back("-ldylib1.o");
4376         else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4377           CmdArgs.push_back("-ldylib1.10.5.o");
4378       }
4379     } else {
4380       if (Args.hasArg(options::OPT_bundle)) {
4381         if (!Args.hasArg(options::OPT_static)) {
4382           // Derived from darwin_bundle1 spec.
4383           if (getDarwinToolChain().isTargetIOSSimulator()) {
4384             // The simulator doesn't have a versioned crt1 file.
4385             CmdArgs.push_back("-lbundle1.o");
4386           } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4387             if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4388               CmdArgs.push_back("-lbundle1.o");
4389           } else {
4390             if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4391               CmdArgs.push_back("-lbundle1.o");
4392           }
4393         }
4394       } else {
4395         if (Args.hasArg(options::OPT_pg) &&
4396             getToolChain().SupportsProfiling()) {
4397           if (Args.hasArg(options::OPT_static) ||
4398               Args.hasArg(options::OPT_object) ||
4399               Args.hasArg(options::OPT_preload)) {
4400             CmdArgs.push_back("-lgcrt0.o");
4401           } else {
4402             CmdArgs.push_back("-lgcrt1.o");
4403
4404             // darwin_crt2 spec is empty.
4405           }
4406           // By default on OS X 10.8 and later, we don't link with a crt1.o
4407           // file and the linker knows to use _main as the entry point.  But,
4408           // when compiling with -pg, we need to link with the gcrt1.o file,
4409           // so pass the -no_new_main option to tell the linker to use the
4410           // "start" symbol as the entry point.
4411           if (getDarwinToolChain().isTargetMacOS() &&
4412               !getDarwinToolChain().isMacosxVersionLT(10, 8))
4413             CmdArgs.push_back("-no_new_main");
4414         } else {
4415           if (Args.hasArg(options::OPT_static) ||
4416               Args.hasArg(options::OPT_object) ||
4417               Args.hasArg(options::OPT_preload)) {
4418             CmdArgs.push_back("-lcrt0.o");
4419           } else {
4420             // Derived from darwin_crt1 spec.
4421             if (getDarwinToolChain().isTargetIOSSimulator()) {
4422               // The simulator doesn't have a versioned crt1 file.
4423               CmdArgs.push_back("-lcrt1.o");
4424             } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4425               if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4426                 CmdArgs.push_back("-lcrt1.o");
4427               else
4428                 CmdArgs.push_back("-lcrt1.3.1.o");
4429             } else {
4430               if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4431                 CmdArgs.push_back("-lcrt1.o");
4432               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4433                 CmdArgs.push_back("-lcrt1.10.5.o");
4434               else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
4435                 CmdArgs.push_back("-lcrt1.10.6.o");
4436
4437               // darwin_crt2 spec is empty.
4438             }
4439           }
4440         }
4441       }
4442     }
4443
4444     if (!getDarwinToolChain().isTargetIPhoneOS() &&
4445         Args.hasArg(options::OPT_shared_libgcc) &&
4446         getDarwinToolChain().isMacosxVersionLT(10, 5)) {
4447       const char *Str =
4448         Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
4449       CmdArgs.push_back(Str);
4450     }
4451   }
4452
4453   Args.AddAllArgs(CmdArgs, options::OPT_L);
4454
4455   // If we're building a dynamic lib with -faddress-sanitizer, unresolved
4456   // symbols may appear. Mark all of them as dynamic_lookup.
4457   // Linking executables is handled in lib/Driver/ToolChains.cpp.
4458   if (Args.hasFlag(options::OPT_faddress_sanitizer,
4459                    options::OPT_fno_address_sanitizer, false)) {
4460     if (Args.hasArg(options::OPT_dynamiclib) ||
4461         Args.hasArg(options::OPT_bundle)) {
4462       CmdArgs.push_back("-undefined");
4463       CmdArgs.push_back("dynamic_lookup");
4464     }
4465   }
4466
4467   if (Args.hasArg(options::OPT_fopenmp))
4468     // This is more complicated in gcc...
4469     CmdArgs.push_back("-lgomp");
4470
4471   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4472   
4473   if (isObjCRuntimeLinked(Args) &&
4474       !Args.hasArg(options::OPT_nostdlib) &&
4475       !Args.hasArg(options::OPT_nodefaultlibs)) {
4476     // Avoid linking compatibility stubs on i386 mac.
4477     if (!getDarwinToolChain().isTargetMacOS() ||
4478         getDarwinToolChain().getArchName() != "i386") {
4479       // If we don't have ARC or subscripting runtime support, link in the
4480       // runtime stubs.  We have to do this *before* adding any of the normal
4481       // linker inputs so that its initializer gets run first.
4482       ObjCRuntime runtime =
4483         getDarwinToolChain().getDefaultObjCRuntime(/*nonfragile*/ true);
4484       // We use arclite library for both ARC and subscripting support.
4485       if ((!runtime.hasARC() && isObjCAutoRefCount(Args)) ||
4486           !runtime.hasSubscripting())
4487         getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
4488     }
4489     CmdArgs.push_back("-framework");
4490     CmdArgs.push_back("Foundation");
4491     // Link libobj.
4492     CmdArgs.push_back("-lobjc");
4493   }
4494
4495   if (LinkingOutput) {
4496     CmdArgs.push_back("-arch_multiple");
4497     CmdArgs.push_back("-final_output");
4498     CmdArgs.push_back(LinkingOutput);
4499   }
4500
4501   if (Args.hasArg(options::OPT_fnested_functions))
4502     CmdArgs.push_back("-allow_stack_execute");
4503
4504   if (!Args.hasArg(options::OPT_nostdlib) &&
4505       !Args.hasArg(options::OPT_nodefaultlibs)) {
4506     if (getToolChain().getDriver().CCCIsCXX)
4507       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4508
4509     // link_ssp spec is empty.
4510
4511     // Let the tool chain choose which runtime library to link.
4512     getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
4513   }
4514
4515   if (!Args.hasArg(options::OPT_nostdlib) &&
4516       !Args.hasArg(options::OPT_nostartfiles)) {
4517     // endfile_spec is empty.
4518   }
4519
4520   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4521   Args.AddAllArgs(CmdArgs, options::OPT_F);
4522
4523   const char *Exec =
4524     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4525   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4526 }
4527
4528 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
4529                                 const InputInfo &Output,
4530                                 const InputInfoList &Inputs,
4531                                 const ArgList &Args,
4532                                 const char *LinkingOutput) const {
4533   ArgStringList CmdArgs;
4534
4535   CmdArgs.push_back("-create");
4536   assert(Output.isFilename() && "Unexpected lipo output.");
4537
4538   CmdArgs.push_back("-output");
4539   CmdArgs.push_back(Output.getFilename());
4540
4541   for (InputInfoList::const_iterator
4542          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4543     const InputInfo &II = *it;
4544     assert(II.isFilename() && "Unexpected lipo input.");
4545     CmdArgs.push_back(II.getFilename());
4546   }
4547   const char *Exec =
4548     Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
4549   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4550 }
4551
4552 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
4553                                     const InputInfo &Output,
4554                                     const InputInfoList &Inputs,
4555                                     const ArgList &Args,
4556                                     const char *LinkingOutput) const {
4557   ArgStringList CmdArgs;
4558
4559   CmdArgs.push_back("-o");
4560   CmdArgs.push_back(Output.getFilename());
4561
4562   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4563   const InputInfo &Input = Inputs[0];
4564   assert(Input.isFilename() && "Unexpected dsymutil input.");
4565   CmdArgs.push_back(Input.getFilename());
4566
4567   const char *Exec =
4568     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
4569   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4570 }
4571
4572 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
4573                                        const InputInfo &Output,
4574                                        const InputInfoList &Inputs,
4575                                        const ArgList &Args,
4576                                        const char *LinkingOutput) const {
4577   ArgStringList CmdArgs;
4578   CmdArgs.push_back("--verify");
4579   CmdArgs.push_back("--debug-info");
4580   CmdArgs.push_back("--eh-frame");
4581   CmdArgs.push_back("--quiet");
4582
4583   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4584   const InputInfo &Input = Inputs[0];
4585   assert(Input.isFilename() && "Unexpected verify input");
4586
4587   // Grabbing the output of the earlier dsymutil run.
4588   CmdArgs.push_back(Input.getFilename());
4589
4590   const char *Exec =
4591     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
4592   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4593 }
4594
4595 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4596                                       const InputInfo &Output,
4597                                       const InputInfoList &Inputs,
4598                                       const ArgList &Args,
4599                                       const char *LinkingOutput) const {
4600   ArgStringList CmdArgs;
4601
4602   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4603                        options::OPT_Xassembler);
4604
4605   CmdArgs.push_back("-o");
4606   CmdArgs.push_back(Output.getFilename());
4607
4608   for (InputInfoList::const_iterator
4609          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4610     const InputInfo &II = *it;
4611     CmdArgs.push_back(II.getFilename());
4612   }
4613
4614   const char *Exec =
4615     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4616   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4617 }
4618
4619
4620 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
4621                                   const InputInfo &Output,
4622                                   const InputInfoList &Inputs,
4623                                   const ArgList &Args,
4624                                   const char *LinkingOutput) const {
4625   // FIXME: Find a real GCC, don't hard-code versions here
4626   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
4627   const llvm::Triple &T = getToolChain().getTriple();
4628   std::string LibPath = "/usr/lib/";
4629   llvm::Triple::ArchType Arch = T.getArch();
4630   switch (Arch) {
4631         case llvm::Triple::x86:
4632           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4633               T.getOSName()).str() + "/4.5.2/";
4634           break;
4635         case llvm::Triple::x86_64:
4636           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4637               T.getOSName()).str();
4638           GCCLibPath += "/4.5.2/amd64/";
4639           LibPath += "amd64/";
4640           break;
4641         default:
4642           assert(0 && "Unsupported architecture");
4643   }
4644
4645   ArgStringList CmdArgs;
4646
4647   // Demangle C++ names in errors
4648   CmdArgs.push_back("-C");
4649
4650   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4651       (!Args.hasArg(options::OPT_shared))) {
4652     CmdArgs.push_back("-e");
4653     CmdArgs.push_back("_start");
4654   }
4655
4656   if (Args.hasArg(options::OPT_static)) {
4657     CmdArgs.push_back("-Bstatic");
4658     CmdArgs.push_back("-dn");
4659   } else {
4660     CmdArgs.push_back("-Bdynamic");
4661     if (Args.hasArg(options::OPT_shared)) {
4662       CmdArgs.push_back("-shared");
4663     } else {
4664       CmdArgs.push_back("--dynamic-linker");
4665       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
4666     }
4667   }
4668
4669   if (Output.isFilename()) {
4670     CmdArgs.push_back("-o");
4671     CmdArgs.push_back(Output.getFilename());
4672   } else {
4673     assert(Output.isNothing() && "Invalid output.");
4674   }
4675
4676   if (!Args.hasArg(options::OPT_nostdlib) &&
4677       !Args.hasArg(options::OPT_nostartfiles)) {
4678     if (!Args.hasArg(options::OPT_shared)) {
4679       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
4680       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4681       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4682       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4683     } else {
4684       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4685       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4686       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4687     }
4688     if (getToolChain().getDriver().CCCIsCXX)
4689       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
4690   }
4691
4692   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
4693
4694   Args.AddAllArgs(CmdArgs, options::OPT_L);
4695   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4696   Args.AddAllArgs(CmdArgs, options::OPT_e);
4697   Args.AddAllArgs(CmdArgs, options::OPT_r);
4698
4699   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4700
4701   if (!Args.hasArg(options::OPT_nostdlib) &&
4702       !Args.hasArg(options::OPT_nodefaultlibs)) {
4703     if (getToolChain().getDriver().CCCIsCXX)
4704       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4705     CmdArgs.push_back("-lgcc_s");
4706     if (!Args.hasArg(options::OPT_shared)) {
4707       CmdArgs.push_back("-lgcc");
4708       CmdArgs.push_back("-lc");
4709       CmdArgs.push_back("-lm");
4710     }
4711   }
4712
4713   if (!Args.hasArg(options::OPT_nostdlib) &&
4714       !Args.hasArg(options::OPT_nostartfiles)) {
4715     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
4716   }
4717   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
4718
4719   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4720
4721   const char *Exec =
4722     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4723   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4724 }
4725
4726 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4727                                       const InputInfo &Output,
4728                                       const InputInfoList &Inputs,
4729                                       const ArgList &Args,
4730                                       const char *LinkingOutput) const {
4731   ArgStringList CmdArgs;
4732
4733   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4734                        options::OPT_Xassembler);
4735
4736   CmdArgs.push_back("-o");
4737   CmdArgs.push_back(Output.getFilename());
4738
4739   for (InputInfoList::const_iterator
4740          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4741     const InputInfo &II = *it;
4742     CmdArgs.push_back(II.getFilename());
4743   }
4744
4745   const char *Exec =
4746     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
4747   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4748 }
4749
4750 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
4751                                   const InputInfo &Output,
4752                                   const InputInfoList &Inputs,
4753                                   const ArgList &Args,
4754                                   const char *LinkingOutput) const {
4755   ArgStringList CmdArgs;
4756
4757   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4758       (!Args.hasArg(options::OPT_shared))) {
4759     CmdArgs.push_back("-e");
4760     CmdArgs.push_back("_start");
4761   }
4762
4763   if (Args.hasArg(options::OPT_static)) {
4764     CmdArgs.push_back("-Bstatic");
4765     CmdArgs.push_back("-dn");
4766   } else {
4767 //    CmdArgs.push_back("--eh-frame-hdr");
4768     CmdArgs.push_back("-Bdynamic");
4769     if (Args.hasArg(options::OPT_shared)) {
4770       CmdArgs.push_back("-shared");
4771     } else {
4772       CmdArgs.push_back("--dynamic-linker");
4773       CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
4774     }
4775   }
4776
4777   if (Output.isFilename()) {
4778     CmdArgs.push_back("-o");
4779     CmdArgs.push_back(Output.getFilename());
4780   } else {
4781     assert(Output.isNothing() && "Invalid output.");
4782   }
4783
4784   if (!Args.hasArg(options::OPT_nostdlib) &&
4785       !Args.hasArg(options::OPT_nostartfiles)) {
4786     if (!Args.hasArg(options::OPT_shared)) {
4787       CmdArgs.push_back(Args.MakeArgString(
4788                                 getToolChain().GetFilePath("crt1.o")));
4789       CmdArgs.push_back(Args.MakeArgString(
4790                                 getToolChain().GetFilePath("crti.o")));
4791       CmdArgs.push_back(Args.MakeArgString(
4792                                 getToolChain().GetFilePath("crtbegin.o")));
4793     } else {
4794       CmdArgs.push_back(Args.MakeArgString(
4795                                 getToolChain().GetFilePath("crti.o")));
4796     }
4797     CmdArgs.push_back(Args.MakeArgString(
4798                                 getToolChain().GetFilePath("crtn.o")));
4799   }
4800
4801   CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
4802                                        + getToolChain().getTripleString()
4803                                        + "/4.2.4"));
4804
4805   Args.AddAllArgs(CmdArgs, options::OPT_L);
4806   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4807   Args.AddAllArgs(CmdArgs, options::OPT_e);
4808
4809   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4810
4811   if (!Args.hasArg(options::OPT_nostdlib) &&
4812       !Args.hasArg(options::OPT_nodefaultlibs)) {
4813     // FIXME: For some reason GCC passes -lgcc before adding
4814     // the default system libraries. Just mimic this for now.
4815     CmdArgs.push_back("-lgcc");
4816
4817     if (Args.hasArg(options::OPT_pthread))
4818       CmdArgs.push_back("-pthread");
4819     if (!Args.hasArg(options::OPT_shared))
4820       CmdArgs.push_back("-lc");
4821     CmdArgs.push_back("-lgcc");
4822   }
4823
4824   if (!Args.hasArg(options::OPT_nostdlib) &&
4825       !Args.hasArg(options::OPT_nostartfiles)) {
4826     if (!Args.hasArg(options::OPT_shared))
4827       CmdArgs.push_back(Args.MakeArgString(
4828                                 getToolChain().GetFilePath("crtend.o")));
4829   }
4830
4831   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4832
4833   const char *Exec =
4834     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4835   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4836 }
4837
4838 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4839                                      const InputInfo &Output,
4840                                      const InputInfoList &Inputs,
4841                                      const ArgList &Args,
4842                                      const char *LinkingOutput) const {
4843   ArgStringList CmdArgs;
4844
4845   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4846                        options::OPT_Xassembler);
4847
4848   CmdArgs.push_back("-o");
4849   CmdArgs.push_back(Output.getFilename());
4850
4851   for (InputInfoList::const_iterator
4852          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4853     const InputInfo &II = *it;
4854     CmdArgs.push_back(II.getFilename());
4855   }
4856
4857   const char *Exec =
4858     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4859   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4860 }
4861
4862 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
4863                                  const InputInfo &Output,
4864                                  const InputInfoList &Inputs,
4865                                  const ArgList &Args,
4866                                  const char *LinkingOutput) const {
4867   const Driver &D = getToolChain().getDriver();
4868   ArgStringList CmdArgs;
4869
4870   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4871       (!Args.hasArg(options::OPT_shared))) {
4872     CmdArgs.push_back("-e");
4873     CmdArgs.push_back("__start");
4874   }
4875
4876   if (Args.hasArg(options::OPT_static)) {
4877     CmdArgs.push_back("-Bstatic");
4878   } else {
4879     if (Args.hasArg(options::OPT_rdynamic))
4880       CmdArgs.push_back("-export-dynamic");
4881     CmdArgs.push_back("--eh-frame-hdr");
4882     CmdArgs.push_back("-Bdynamic");
4883     if (Args.hasArg(options::OPT_shared)) {
4884       CmdArgs.push_back("-shared");
4885     } else {
4886       CmdArgs.push_back("-dynamic-linker");
4887       CmdArgs.push_back("/usr/libexec/ld.so");
4888     }
4889   }
4890
4891   if (Output.isFilename()) {
4892     CmdArgs.push_back("-o");
4893     CmdArgs.push_back(Output.getFilename());
4894   } else {
4895     assert(Output.isNothing() && "Invalid output.");
4896   }
4897
4898   if (!Args.hasArg(options::OPT_nostdlib) &&
4899       !Args.hasArg(options::OPT_nostartfiles)) {
4900     if (!Args.hasArg(options::OPT_shared)) {
4901       if (Args.hasArg(options::OPT_pg))  
4902         CmdArgs.push_back(Args.MakeArgString(
4903                                 getToolChain().GetFilePath("gcrt0.o")));
4904       else
4905         CmdArgs.push_back(Args.MakeArgString(
4906                                 getToolChain().GetFilePath("crt0.o")));
4907       CmdArgs.push_back(Args.MakeArgString(
4908                               getToolChain().GetFilePath("crtbegin.o")));
4909     } else {
4910       CmdArgs.push_back(Args.MakeArgString(
4911                               getToolChain().GetFilePath("crtbeginS.o")));
4912     }
4913   }
4914
4915   std::string Triple = getToolChain().getTripleString();
4916   if (Triple.substr(0, 6) == "x86_64")
4917     Triple.replace(0, 6, "amd64");
4918   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
4919                                        "/4.2.1"));
4920
4921   Args.AddAllArgs(CmdArgs, options::OPT_L);
4922   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4923   Args.AddAllArgs(CmdArgs, options::OPT_e);
4924
4925   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4926
4927   if (!Args.hasArg(options::OPT_nostdlib) &&
4928       !Args.hasArg(options::OPT_nodefaultlibs)) {
4929     if (D.CCCIsCXX) {
4930       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4931       if (Args.hasArg(options::OPT_pg)) 
4932         CmdArgs.push_back("-lm_p");
4933       else
4934         CmdArgs.push_back("-lm");
4935     }
4936
4937     // FIXME: For some reason GCC passes -lgcc before adding
4938     // the default system libraries. Just mimic this for now.
4939     CmdArgs.push_back("-lgcc");
4940
4941     if (Args.hasArg(options::OPT_pthread))
4942       CmdArgs.push_back("-lpthread");
4943     if (!Args.hasArg(options::OPT_shared)) {
4944       if (Args.hasArg(options::OPT_pg)) 
4945          CmdArgs.push_back("-lc_p");
4946       else
4947          CmdArgs.push_back("-lc");
4948     }
4949     CmdArgs.push_back("-lgcc");
4950   }
4951
4952   if (!Args.hasArg(options::OPT_nostdlib) &&
4953       !Args.hasArg(options::OPT_nostartfiles)) {
4954     if (!Args.hasArg(options::OPT_shared))
4955       CmdArgs.push_back(Args.MakeArgString(
4956                               getToolChain().GetFilePath("crtend.o")));
4957     else
4958       CmdArgs.push_back(Args.MakeArgString(
4959                               getToolChain().GetFilePath("crtendS.o")));
4960   }
4961
4962   const char *Exec =
4963     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4964   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4965 }
4966
4967 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4968                                     const InputInfo &Output,
4969                                     const InputInfoList &Inputs,
4970                                     const ArgList &Args,
4971                                     const char *LinkingOutput) const {
4972   ArgStringList CmdArgs;
4973
4974   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4975                        options::OPT_Xassembler);
4976
4977   CmdArgs.push_back("-o");
4978   CmdArgs.push_back(Output.getFilename());
4979
4980   for (InputInfoList::const_iterator
4981          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4982     const InputInfo &II = *it;
4983     CmdArgs.push_back(II.getFilename());
4984   }
4985
4986   const char *Exec =
4987     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4988   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4989 }
4990
4991 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
4992                                 const InputInfo &Output,
4993                                 const InputInfoList &Inputs,
4994                                 const ArgList &Args,
4995                                 const char *LinkingOutput) const {
4996   const Driver &D = getToolChain().getDriver();
4997   ArgStringList CmdArgs;
4998
4999   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5000       (!Args.hasArg(options::OPT_shared))) {
5001     CmdArgs.push_back("-e");
5002     CmdArgs.push_back("__start");
5003   }
5004
5005   if (Args.hasArg(options::OPT_static)) {
5006     CmdArgs.push_back("-Bstatic");
5007   } else {
5008     if (Args.hasArg(options::OPT_rdynamic))
5009       CmdArgs.push_back("-export-dynamic");
5010     CmdArgs.push_back("--eh-frame-hdr");
5011     CmdArgs.push_back("-Bdynamic");
5012     if (Args.hasArg(options::OPT_shared)) {
5013       CmdArgs.push_back("-shared");
5014     } else {
5015       CmdArgs.push_back("-dynamic-linker");
5016       CmdArgs.push_back("/usr/libexec/ld.so");
5017     }
5018   }
5019
5020   if (Output.isFilename()) {
5021     CmdArgs.push_back("-o");
5022     CmdArgs.push_back(Output.getFilename());
5023   } else {
5024     assert(Output.isNothing() && "Invalid output.");
5025   }
5026
5027   if (!Args.hasArg(options::OPT_nostdlib) &&
5028       !Args.hasArg(options::OPT_nostartfiles)) {
5029     if (!Args.hasArg(options::OPT_shared)) {
5030       if (Args.hasArg(options::OPT_pg))
5031         CmdArgs.push_back(Args.MakeArgString(
5032                                 getToolChain().GetFilePath("gcrt0.o")));
5033       else
5034         CmdArgs.push_back(Args.MakeArgString(
5035                                 getToolChain().GetFilePath("crt0.o")));
5036       CmdArgs.push_back(Args.MakeArgString(
5037                               getToolChain().GetFilePath("crtbegin.o")));
5038     } else {
5039       CmdArgs.push_back(Args.MakeArgString(
5040                               getToolChain().GetFilePath("crtbeginS.o")));
5041     }
5042   }
5043
5044   Args.AddAllArgs(CmdArgs, options::OPT_L);
5045   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5046   Args.AddAllArgs(CmdArgs, options::OPT_e);
5047
5048   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5049
5050   if (!Args.hasArg(options::OPT_nostdlib) &&
5051       !Args.hasArg(options::OPT_nodefaultlibs)) {
5052     if (D.CCCIsCXX) {
5053       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5054       if (Args.hasArg(options::OPT_pg))
5055         CmdArgs.push_back("-lm_p");
5056       else
5057         CmdArgs.push_back("-lm");
5058     }
5059
5060     if (Args.hasArg(options::OPT_pthread))
5061       CmdArgs.push_back("-lpthread");
5062     if (!Args.hasArg(options::OPT_shared)) {
5063       if (Args.hasArg(options::OPT_pg))
5064         CmdArgs.push_back("-lc_p");
5065       else
5066         CmdArgs.push_back("-lc");
5067     }
5068
5069     std::string myarch = "-lclang_rt.";
5070     const llvm::Triple &T = getToolChain().getTriple();
5071     llvm::Triple::ArchType Arch = T.getArch();
5072     switch (Arch) {
5073           case llvm::Triple::arm:
5074             myarch += ("arm");
5075             break;
5076           case llvm::Triple::x86:
5077             myarch += ("i386");
5078             break;
5079           case llvm::Triple::x86_64:
5080             myarch += ("amd64");
5081             break;
5082           default:
5083             assert(0 && "Unsupported architecture");
5084      }
5085      CmdArgs.push_back(Args.MakeArgString(myarch));
5086   }
5087
5088   if (!Args.hasArg(options::OPT_nostdlib) &&
5089       !Args.hasArg(options::OPT_nostartfiles)) {
5090     if (!Args.hasArg(options::OPT_shared))
5091       CmdArgs.push_back(Args.MakeArgString(
5092                               getToolChain().GetFilePath("crtend.o")));
5093     else
5094       CmdArgs.push_back(Args.MakeArgString(
5095                               getToolChain().GetFilePath("crtendS.o")));
5096   }
5097
5098   const char *Exec =
5099     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5100   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5101 }
5102
5103 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5104                                      const InputInfo &Output,
5105                                      const InputInfoList &Inputs,
5106                                      const ArgList &Args,
5107                                      const char *LinkingOutput) const {
5108   ArgStringList CmdArgs;
5109
5110   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5111   // instruct as in the base system to assemble 32-bit code.
5112   if (getToolChain().getArchName() == "i386")
5113     CmdArgs.push_back("--32");
5114
5115   if (getToolChain().getArchName() == "powerpc")
5116     CmdArgs.push_back("-a32");
5117
5118   // Set byte order explicitly
5119   if (getToolChain().getArchName() == "mips")
5120     CmdArgs.push_back("-EB");
5121   else if (getToolChain().getArchName() == "mipsel")
5122     CmdArgs.push_back("-EL");
5123
5124   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5125                        options::OPT_Xassembler);
5126
5127   CmdArgs.push_back("-o");
5128   CmdArgs.push_back(Output.getFilename());
5129
5130   for (InputInfoList::const_iterator
5131          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5132     const InputInfo &II = *it;
5133     CmdArgs.push_back(II.getFilename());
5134   }
5135
5136   const char *Exec =
5137     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5138   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5139 }
5140
5141 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5142                                  const InputInfo &Output,
5143                                  const InputInfoList &Inputs,
5144                                  const ArgList &Args,
5145                                  const char *LinkingOutput) const {
5146   const Driver &D = getToolChain().getDriver();
5147   ArgStringList CmdArgs;
5148
5149   // Silence warning for "clang -g foo.o -o foo"
5150   Args.ClaimAllArgs(options::OPT_g_Group);
5151   // and "clang -emit-llvm foo.o -o foo"
5152   Args.ClaimAllArgs(options::OPT_emit_llvm);
5153   // and for "clang -w foo.o -o foo". Other warning options are already
5154   // handled somewhere else.
5155   Args.ClaimAllArgs(options::OPT_w);
5156
5157   if (!D.SysRoot.empty())
5158     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5159
5160   if (Args.hasArg(options::OPT_static)) {
5161     CmdArgs.push_back("-Bstatic");
5162   } else {
5163     if (Args.hasArg(options::OPT_rdynamic))
5164       CmdArgs.push_back("-export-dynamic");
5165     CmdArgs.push_back("--eh-frame-hdr");
5166     if (Args.hasArg(options::OPT_shared)) {
5167       CmdArgs.push_back("-Bshareable");
5168     } else {
5169       CmdArgs.push_back("-dynamic-linker");
5170       CmdArgs.push_back("/libexec/ld-elf.so.1");
5171     }
5172     if (getToolChain().getTriple().getOSMajorVersion() >= 9) {
5173       llvm::Triple::ArchType Arch = getToolChain().getArch();
5174       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
5175           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5176         CmdArgs.push_back("--hash-style=both");
5177       }
5178     }
5179     CmdArgs.push_back("--enable-new-dtags");
5180   }
5181
5182   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5183   // instruct ld in the base system to link 32-bit code.
5184   if (getToolChain().getArchName() == "i386") {
5185     CmdArgs.push_back("-m");
5186     CmdArgs.push_back("elf_i386_fbsd");
5187   }
5188
5189   if (getToolChain().getArchName() == "powerpc") {
5190     CmdArgs.push_back("-m");
5191     CmdArgs.push_back("elf32ppc_fbsd");
5192   }
5193
5194   if (Output.isFilename()) {
5195     CmdArgs.push_back("-o");
5196     CmdArgs.push_back(Output.getFilename());
5197   } else {
5198     assert(Output.isNothing() && "Invalid output.");
5199   }
5200
5201   if (!Args.hasArg(options::OPT_nostdlib) &&
5202       !Args.hasArg(options::OPT_nostartfiles)) {
5203     if (!Args.hasArg(options::OPT_shared)) {
5204       if (Args.hasArg(options::OPT_pg))
5205         CmdArgs.push_back(Args.MakeArgString(
5206                                 getToolChain().GetFilePath("gcrt1.o")));
5207       else {
5208         const char *crt = Args.hasArg(options::OPT_pie) ? "Scrt1.o" : "crt1.o";
5209         CmdArgs.push_back(Args.MakeArgString(
5210                                 getToolChain().GetFilePath(crt)));
5211       }
5212       CmdArgs.push_back(Args.MakeArgString(
5213                               getToolChain().GetFilePath("crti.o")));
5214       CmdArgs.push_back(Args.MakeArgString(
5215                               getToolChain().GetFilePath("crtbegin.o")));
5216     } else {
5217       CmdArgs.push_back(Args.MakeArgString(
5218                               getToolChain().GetFilePath("crti.o")));
5219       CmdArgs.push_back(Args.MakeArgString(
5220                               getToolChain().GetFilePath("crtbeginS.o")));
5221     }
5222   }
5223
5224   Args.AddAllArgs(CmdArgs, options::OPT_L);
5225   const ToolChain::path_list Paths = getToolChain().getFilePaths();
5226   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5227        i != e; ++i)
5228     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5229   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5230   Args.AddAllArgs(CmdArgs, options::OPT_e);
5231   Args.AddAllArgs(CmdArgs, options::OPT_s);
5232   Args.AddAllArgs(CmdArgs, options::OPT_t);
5233   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5234   Args.AddAllArgs(CmdArgs, options::OPT_r);
5235
5236   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5237
5238   if (!Args.hasArg(options::OPT_nostdlib) &&
5239       !Args.hasArg(options::OPT_nodefaultlibs)) {
5240     if (D.CCCIsCXX) {
5241       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5242       if (Args.hasArg(options::OPT_pg))
5243         CmdArgs.push_back("-lm_p");
5244       else
5245         CmdArgs.push_back("-lm");
5246     }
5247     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5248     // the default system libraries. Just mimic this for now.
5249     if (Args.hasArg(options::OPT_pg))
5250       CmdArgs.push_back("-lgcc_p");
5251     else
5252       CmdArgs.push_back("-lgcc");
5253     if (Args.hasArg(options::OPT_static)) {
5254       CmdArgs.push_back("-lgcc_eh");
5255     } else if (Args.hasArg(options::OPT_pg)) {
5256       CmdArgs.push_back("-lgcc_eh_p");
5257     } else {
5258       CmdArgs.push_back("--as-needed");
5259       CmdArgs.push_back("-lgcc_s");
5260       CmdArgs.push_back("--no-as-needed");
5261     }
5262
5263     if (Args.hasArg(options::OPT_pthread)) {
5264       if (Args.hasArg(options::OPT_pg))
5265         CmdArgs.push_back("-lpthread_p");
5266       else
5267         CmdArgs.push_back("-lpthread");
5268     }
5269
5270     if (Args.hasArg(options::OPT_pg)) {
5271       if (Args.hasArg(options::OPT_shared))
5272         CmdArgs.push_back("-lc");
5273       else
5274         CmdArgs.push_back("-lc_p");
5275       CmdArgs.push_back("-lgcc_p");
5276     } else {
5277       CmdArgs.push_back("-lc");
5278       CmdArgs.push_back("-lgcc");
5279     }
5280
5281     if (Args.hasArg(options::OPT_static)) {
5282       CmdArgs.push_back("-lgcc_eh");
5283     } else if (Args.hasArg(options::OPT_pg)) {
5284       CmdArgs.push_back("-lgcc_eh_p");
5285     } else {
5286       CmdArgs.push_back("--as-needed");
5287       CmdArgs.push_back("-lgcc_s");
5288       CmdArgs.push_back("--no-as-needed");
5289     }
5290   }
5291
5292   if (!Args.hasArg(options::OPT_nostdlib) &&
5293       !Args.hasArg(options::OPT_nostartfiles)) {
5294     if (!Args.hasArg(options::OPT_shared))
5295       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5296                                                                   "crtend.o")));
5297     else
5298       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5299                                                                  "crtendS.o")));
5300     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5301                                                                     "crtn.o")));
5302   }
5303
5304   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5305
5306   const char *Exec =
5307     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5308   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5309 }
5310
5311 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5312                                      const InputInfo &Output,
5313                                      const InputInfoList &Inputs,
5314                                      const ArgList &Args,
5315                                      const char *LinkingOutput) const {
5316   ArgStringList CmdArgs;
5317
5318   // When building 32-bit code on NetBSD/amd64, we have to explicitly
5319   // instruct as in the base system to assemble 32-bit code.
5320   if (getToolChain().getArch() == llvm::Triple::x86)
5321     CmdArgs.push_back("--32");
5322
5323   // Set byte order explicitly
5324   if (getToolChain().getArchName() == "mips")
5325     CmdArgs.push_back("-EB");
5326   else if (getToolChain().getArchName() == "mipsel")
5327     CmdArgs.push_back("-EL");
5328
5329   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5330                        options::OPT_Xassembler);
5331
5332   CmdArgs.push_back("-o");
5333   CmdArgs.push_back(Output.getFilename());
5334
5335   for (InputInfoList::const_iterator
5336          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5337     const InputInfo &II = *it;
5338     CmdArgs.push_back(II.getFilename());
5339   }
5340
5341   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
5342   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5343 }
5344
5345 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5346                                  const InputInfo &Output,
5347                                  const InputInfoList &Inputs,
5348                                  const ArgList &Args,
5349                                  const char *LinkingOutput) const {
5350   const Driver &D = getToolChain().getDriver();
5351   ArgStringList CmdArgs;
5352
5353   if (!D.SysRoot.empty())
5354     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5355
5356   if (Args.hasArg(options::OPT_static)) {
5357     CmdArgs.push_back("-Bstatic");
5358   } else {
5359     if (Args.hasArg(options::OPT_rdynamic))
5360       CmdArgs.push_back("-export-dynamic");
5361     CmdArgs.push_back("--eh-frame-hdr");
5362     if (Args.hasArg(options::OPT_shared)) {
5363       CmdArgs.push_back("-Bshareable");
5364     } else {
5365       CmdArgs.push_back("-dynamic-linker");
5366       CmdArgs.push_back("/libexec/ld.elf_so");
5367     }
5368   }
5369
5370   // When building 32-bit code on NetBSD/amd64, we have to explicitly
5371   // instruct ld in the base system to link 32-bit code.
5372   if (getToolChain().getArch() == llvm::Triple::x86) {
5373     CmdArgs.push_back("-m");
5374     CmdArgs.push_back("elf_i386");
5375   }
5376
5377   if (Output.isFilename()) {
5378     CmdArgs.push_back("-o");
5379     CmdArgs.push_back(Output.getFilename());
5380   } else {
5381     assert(Output.isNothing() && "Invalid output.");
5382   }
5383
5384   if (!Args.hasArg(options::OPT_nostdlib) &&
5385       !Args.hasArg(options::OPT_nostartfiles)) {
5386     if (!Args.hasArg(options::OPT_shared)) {
5387       CmdArgs.push_back(Args.MakeArgString(
5388                               getToolChain().GetFilePath("crt0.o")));
5389       CmdArgs.push_back(Args.MakeArgString(
5390                               getToolChain().GetFilePath("crti.o")));
5391       CmdArgs.push_back(Args.MakeArgString(
5392                               getToolChain().GetFilePath("crtbegin.o")));
5393     } else {
5394       CmdArgs.push_back(Args.MakeArgString(
5395                               getToolChain().GetFilePath("crti.o")));
5396       CmdArgs.push_back(Args.MakeArgString(
5397                               getToolChain().GetFilePath("crtbeginS.o")));
5398     }
5399   }
5400
5401   Args.AddAllArgs(CmdArgs, options::OPT_L);
5402   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5403   Args.AddAllArgs(CmdArgs, options::OPT_e);
5404   Args.AddAllArgs(CmdArgs, options::OPT_s);
5405   Args.AddAllArgs(CmdArgs, options::OPT_t);
5406   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5407   Args.AddAllArgs(CmdArgs, options::OPT_r);
5408
5409   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5410
5411   if (!Args.hasArg(options::OPT_nostdlib) &&
5412       !Args.hasArg(options::OPT_nodefaultlibs)) {
5413     if (D.CCCIsCXX) {
5414       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5415       CmdArgs.push_back("-lm");
5416     }
5417     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5418     // the default system libraries. Just mimic this for now.
5419     if (Args.hasArg(options::OPT_static)) {
5420       CmdArgs.push_back("-lgcc_eh");
5421     } else {
5422       CmdArgs.push_back("--as-needed");
5423       CmdArgs.push_back("-lgcc_s");
5424       CmdArgs.push_back("--no-as-needed");
5425     }
5426     CmdArgs.push_back("-lgcc");
5427
5428     if (Args.hasArg(options::OPT_pthread))
5429       CmdArgs.push_back("-lpthread");
5430     CmdArgs.push_back("-lc");
5431
5432     CmdArgs.push_back("-lgcc");
5433     if (Args.hasArg(options::OPT_static)) {
5434       CmdArgs.push_back("-lgcc_eh");
5435     } else {
5436       CmdArgs.push_back("--as-needed");
5437       CmdArgs.push_back("-lgcc_s");
5438       CmdArgs.push_back("--no-as-needed");
5439     }
5440   }
5441
5442   if (!Args.hasArg(options::OPT_nostdlib) &&
5443       !Args.hasArg(options::OPT_nostartfiles)) {
5444     if (!Args.hasArg(options::OPT_shared))
5445       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5446                                                                   "crtend.o")));
5447     else
5448       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5449                                                                  "crtendS.o")));
5450     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5451                                                                     "crtn.o")));
5452   }
5453
5454   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5455
5456   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5457   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5458 }
5459
5460 void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5461                                         const InputInfo &Output,
5462                                         const InputInfoList &Inputs,
5463                                         const ArgList &Args,
5464                                         const char *LinkingOutput) const {
5465   ArgStringList CmdArgs;
5466
5467   // Add --32/--64 to make sure we get the format we want.
5468   // This is incomplete
5469   if (getToolChain().getArch() == llvm::Triple::x86) {
5470     CmdArgs.push_back("--32");
5471   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
5472     CmdArgs.push_back("--64");
5473   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
5474     CmdArgs.push_back("-a32");
5475     CmdArgs.push_back("-mppc");
5476     CmdArgs.push_back("-many");
5477   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
5478     CmdArgs.push_back("-a64");
5479     CmdArgs.push_back("-mppc64");
5480     CmdArgs.push_back("-many");
5481   } else if (getToolChain().getArch() == llvm::Triple::arm) {
5482     StringRef MArch = getToolChain().getArchName();
5483     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
5484       CmdArgs.push_back("-mfpu=neon");
5485
5486     StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
5487                                            getToolChain().getTriple());
5488     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
5489
5490     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
5491     Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
5492     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
5493   } else if (getToolChain().getArch() == llvm::Triple::mips ||
5494              getToolChain().getArch() == llvm::Triple::mipsel ||
5495              getToolChain().getArch() == llvm::Triple::mips64 ||
5496              getToolChain().getArch() == llvm::Triple::mips64el) {
5497     StringRef CPUName;
5498     StringRef ABIName;
5499     getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
5500
5501     CmdArgs.push_back("-march");
5502     CmdArgs.push_back(CPUName.data());
5503
5504     // Convert ABI name to the GNU tools acceptable variant.
5505     if (ABIName == "o32")
5506       ABIName = "32";
5507     else if (ABIName == "n64")
5508       ABIName = "64";
5509
5510     CmdArgs.push_back("-mabi");
5511     CmdArgs.push_back(ABIName.data());
5512
5513     if (getToolChain().getArch() == llvm::Triple::mips ||
5514         getToolChain().getArch() == llvm::Triple::mips64)
5515       CmdArgs.push_back("-EB");
5516     else
5517       CmdArgs.push_back("-EL");
5518
5519     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5520                                       options::OPT_fpic, options::OPT_fno_pic,
5521                                       options::OPT_fPIE, options::OPT_fno_PIE,
5522                                       options::OPT_fpie, options::OPT_fno_pie);
5523     if (LastPICArg &&
5524         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5525          LastPICArg->getOption().matches(options::OPT_fpic) ||
5526          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5527          LastPICArg->getOption().matches(options::OPT_fpie))) {
5528       CmdArgs.push_back("-KPIC");
5529     }
5530   }
5531
5532   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5533                        options::OPT_Xassembler);
5534
5535   CmdArgs.push_back("-o");
5536   CmdArgs.push_back(Output.getFilename());
5537
5538   for (InputInfoList::const_iterator
5539          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5540     const InputInfo &II = *it;
5541     CmdArgs.push_back(II.getFilename());
5542   }
5543
5544   const char *Exec =
5545     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5546   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5547 }
5548
5549 static void AddLibgcc(llvm::Triple Triple, const Driver &D,
5550                       ArgStringList &CmdArgs, const ArgList &Args) {
5551   bool isAndroid = Triple.getEnvironment() == llvm::Triple::ANDROIDEABI;
5552   bool StaticLibgcc = isAndroid || Args.hasArg(options::OPT_static) ||
5553     Args.hasArg(options::OPT_static_libgcc);
5554   if (!D.CCCIsCXX)
5555     CmdArgs.push_back("-lgcc");
5556
5557   if (StaticLibgcc) {
5558     if (D.CCCIsCXX)
5559       CmdArgs.push_back("-lgcc");
5560   } else {
5561     if (!D.CCCIsCXX)
5562       CmdArgs.push_back("--as-needed");
5563     CmdArgs.push_back("-lgcc_s");
5564     if (!D.CCCIsCXX)
5565       CmdArgs.push_back("--no-as-needed");
5566   }
5567
5568   if (StaticLibgcc && !isAndroid)
5569     CmdArgs.push_back("-lgcc_eh");
5570   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
5571     CmdArgs.push_back("-lgcc");
5572 }
5573
5574 void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
5575                                     const InputInfo &Output,
5576                                     const InputInfoList &Inputs,
5577                                     const ArgList &Args,
5578                                     const char *LinkingOutput) const {
5579   const toolchains::Linux& ToolChain =
5580     static_cast<const toolchains::Linux&>(getToolChain());
5581   const Driver &D = ToolChain.getDriver();
5582   const bool isAndroid = ToolChain.getTriple().getEnvironment() ==
5583     llvm::Triple::ANDROIDEABI;
5584
5585   ArgStringList CmdArgs;
5586
5587   // Silence warning for "clang -g foo.o -o foo"
5588   Args.ClaimAllArgs(options::OPT_g_Group);
5589   // and "clang -emit-llvm foo.o -o foo"
5590   Args.ClaimAllArgs(options::OPT_emit_llvm);
5591   // and for "clang -w foo.o -o foo". Other warning options are already
5592   // handled somewhere else.
5593   Args.ClaimAllArgs(options::OPT_w);
5594
5595   if (!D.SysRoot.empty())
5596     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5597
5598   if (Args.hasArg(options::OPT_pie))
5599     CmdArgs.push_back("-pie");
5600
5601   if (Args.hasArg(options::OPT_rdynamic))
5602     CmdArgs.push_back("-export-dynamic");
5603
5604   if (Args.hasArg(options::OPT_s))
5605     CmdArgs.push_back("-s");
5606
5607   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
5608          e = ToolChain.ExtraOpts.end();
5609        i != e; ++i)
5610     CmdArgs.push_back(i->c_str());
5611
5612   if (!Args.hasArg(options::OPT_static)) {
5613     CmdArgs.push_back("--eh-frame-hdr");
5614   }
5615
5616   CmdArgs.push_back("-m");
5617   if (ToolChain.getArch() == llvm::Triple::x86)
5618     CmdArgs.push_back("elf_i386");
5619   else if (ToolChain.getArch() == llvm::Triple::arm
5620            ||  ToolChain.getArch() == llvm::Triple::thumb)
5621     CmdArgs.push_back("armelf_linux_eabi");
5622   else if (ToolChain.getArch() == llvm::Triple::ppc)
5623     CmdArgs.push_back("elf32ppclinux");
5624   else if (ToolChain.getArch() == llvm::Triple::ppc64)
5625     CmdArgs.push_back("elf64ppc");
5626   else if (ToolChain.getArch() == llvm::Triple::mips)
5627     CmdArgs.push_back("elf32btsmip");
5628   else if (ToolChain.getArch() == llvm::Triple::mipsel)
5629     CmdArgs.push_back("elf32ltsmip");
5630   else if (ToolChain.getArch() == llvm::Triple::mips64)
5631     CmdArgs.push_back("elf64btsmip");
5632   else if (ToolChain.getArch() == llvm::Triple::mips64el)
5633     CmdArgs.push_back("elf64ltsmip");
5634   else
5635     CmdArgs.push_back("elf_x86_64");
5636
5637   if (Args.hasArg(options::OPT_static)) {
5638     if (ToolChain.getArch() == llvm::Triple::arm
5639         || ToolChain.getArch() == llvm::Triple::thumb)
5640       CmdArgs.push_back("-Bstatic");
5641     else
5642       CmdArgs.push_back("-static");
5643   } else if (Args.hasArg(options::OPT_shared)) {
5644     CmdArgs.push_back("-shared");
5645     if ((ToolChain.getArch() == llvm::Triple::arm
5646          || ToolChain.getArch() == llvm::Triple::thumb) && isAndroid) {
5647       CmdArgs.push_back("-Bsymbolic");
5648     }
5649   }
5650
5651   if (ToolChain.getArch() == llvm::Triple::arm ||
5652       ToolChain.getArch() == llvm::Triple::thumb ||
5653       (!Args.hasArg(options::OPT_static) &&
5654        !Args.hasArg(options::OPT_shared))) {
5655     CmdArgs.push_back("-dynamic-linker");
5656     if (isAndroid)
5657       CmdArgs.push_back("/system/bin/linker");
5658     else if (ToolChain.getArch() == llvm::Triple::x86)
5659       CmdArgs.push_back("/lib/ld-linux.so.2");
5660     else if (ToolChain.getArch() == llvm::Triple::arm ||
5661              ToolChain.getArch() == llvm::Triple::thumb) {
5662       if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
5663         CmdArgs.push_back("/lib/ld-linux-armhf.so.3");
5664       else
5665         CmdArgs.push_back("/lib/ld-linux.so.3");
5666     }
5667     else if (ToolChain.getArch() == llvm::Triple::mips ||
5668              ToolChain.getArch() == llvm::Triple::mipsel)
5669       CmdArgs.push_back("/lib/ld.so.1");
5670     else if (ToolChain.getArch() == llvm::Triple::mips64 ||
5671              ToolChain.getArch() == llvm::Triple::mips64el)
5672       CmdArgs.push_back("/lib64/ld.so.1");
5673     else if (ToolChain.getArch() == llvm::Triple::ppc)
5674       CmdArgs.push_back("/lib/ld.so.1");
5675     else if (ToolChain.getArch() == llvm::Triple::ppc64)
5676       CmdArgs.push_back("/lib64/ld64.so.1");
5677     else
5678       CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
5679   }
5680
5681   CmdArgs.push_back("-o");
5682   CmdArgs.push_back(Output.getFilename());
5683
5684   if (!Args.hasArg(options::OPT_nostdlib) &&
5685       !Args.hasArg(options::OPT_nostartfiles)) {
5686     if (!isAndroid) {
5687       const char *crt1 = NULL;
5688       if (!Args.hasArg(options::OPT_shared)){
5689         if (Args.hasArg(options::OPT_pie))
5690           crt1 = "Scrt1.o";
5691         else
5692           crt1 = "crt1.o";
5693       }
5694       if (crt1)
5695         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5696
5697       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5698     }
5699
5700     const char *crtbegin;
5701     if (Args.hasArg(options::OPT_static))
5702       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
5703     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5704       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
5705     else
5706       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
5707     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5708   }
5709
5710   Args.AddAllArgs(CmdArgs, options::OPT_L);
5711
5712   const ToolChain::path_list Paths = ToolChain.getFilePaths();
5713
5714   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5715        i != e; ++i)
5716     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5717
5718   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
5719   // as gold requires -plugin to come before any -plugin-opt that -Wl might
5720   // forward.
5721   if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
5722     CmdArgs.push_back("-plugin");
5723     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
5724     CmdArgs.push_back(Args.MakeArgString(Plugin));
5725   }
5726
5727   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
5728     CmdArgs.push_back("--no-demangle");
5729
5730   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5731
5732   if (D.CCCIsCXX &&
5733       !Args.hasArg(options::OPT_nostdlib) &&
5734       !Args.hasArg(options::OPT_nodefaultlibs)) {
5735     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
5736       !Args.hasArg(options::OPT_static);
5737     if (OnlyLibstdcxxStatic)
5738       CmdArgs.push_back("-Bstatic");
5739     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5740     if (OnlyLibstdcxxStatic)
5741       CmdArgs.push_back("-Bdynamic");
5742     CmdArgs.push_back("-lm");
5743   }
5744
5745   // Call this before we add the C run-time.
5746   addAsanRTLinux(getToolChain(), Args, CmdArgs);
5747   addTsanRTLinux(getToolChain(), Args, CmdArgs);
5748
5749   if (!Args.hasArg(options::OPT_nostdlib)) {
5750     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
5751       if (Args.hasArg(options::OPT_static))
5752         CmdArgs.push_back("--start-group");
5753
5754       AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
5755
5756       if (Args.hasArg(options::OPT_pthread) ||
5757           Args.hasArg(options::OPT_pthreads))
5758         CmdArgs.push_back("-lpthread");
5759
5760       CmdArgs.push_back("-lc");
5761
5762       if (Args.hasArg(options::OPT_static))
5763         CmdArgs.push_back("--end-group");
5764       else
5765         AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
5766     }
5767
5768     if (!Args.hasArg(options::OPT_nostartfiles)) {
5769       const char *crtend;
5770       if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5771         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
5772       else
5773         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
5774
5775       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
5776       if (!isAndroid)
5777         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
5778     }
5779   }
5780
5781   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5782
5783   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
5784 }
5785
5786 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5787                                    const InputInfo &Output,
5788                                    const InputInfoList &Inputs,
5789                                    const ArgList &Args,
5790                                    const char *LinkingOutput) const {
5791   ArgStringList CmdArgs;
5792
5793   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5794                        options::OPT_Xassembler);
5795
5796   CmdArgs.push_back("-o");
5797   CmdArgs.push_back(Output.getFilename());
5798
5799   for (InputInfoList::const_iterator
5800          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5801     const InputInfo &II = *it;
5802     CmdArgs.push_back(II.getFilename());
5803   }
5804
5805   const char *Exec =
5806     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5807   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5808 }
5809
5810 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
5811                                const InputInfo &Output,
5812                                const InputInfoList &Inputs,
5813                                const ArgList &Args,
5814                                const char *LinkingOutput) const {
5815   const Driver &D = getToolChain().getDriver();
5816   ArgStringList CmdArgs;
5817
5818   if (Output.isFilename()) {
5819     CmdArgs.push_back("-o");
5820     CmdArgs.push_back(Output.getFilename());
5821   } else {
5822     assert(Output.isNothing() && "Invalid output.");
5823   }
5824
5825   if (!Args.hasArg(options::OPT_nostdlib) &&
5826       !Args.hasArg(options::OPT_nostartfiles)) {
5827       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
5828       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
5829       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
5830       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
5831   }
5832
5833   Args.AddAllArgs(CmdArgs, options::OPT_L);
5834   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5835   Args.AddAllArgs(CmdArgs, options::OPT_e);
5836
5837   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5838
5839   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5840
5841   if (!Args.hasArg(options::OPT_nostdlib) &&
5842       !Args.hasArg(options::OPT_nodefaultlibs)) {
5843     if (D.CCCIsCXX) {
5844       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5845       CmdArgs.push_back("-lm");
5846     }
5847   }
5848
5849   if (!Args.hasArg(options::OPT_nostdlib) &&
5850       !Args.hasArg(options::OPT_nostartfiles)) {
5851     if (Args.hasArg(options::OPT_pthread))
5852       CmdArgs.push_back("-lpthread");
5853     CmdArgs.push_back("-lc");
5854     CmdArgs.push_back("-lCompilerRT-Generic");
5855     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
5856     CmdArgs.push_back(
5857          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
5858   }
5859
5860   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5861   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5862 }
5863
5864 /// DragonFly Tools
5865
5866 // For now, DragonFly Assemble does just about the same as for
5867 // FreeBSD, but this may change soon.
5868 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5869                                        const InputInfo &Output,
5870                                        const InputInfoList &Inputs,
5871                                        const ArgList &Args,
5872                                        const char *LinkingOutput) const {
5873   ArgStringList CmdArgs;
5874
5875   // When building 32-bit code on DragonFly/pc64, we have to explicitly
5876   // instruct as in the base system to assemble 32-bit code.
5877   if (getToolChain().getArchName() == "i386")
5878     CmdArgs.push_back("--32");
5879
5880   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5881                        options::OPT_Xassembler);
5882
5883   CmdArgs.push_back("-o");
5884   CmdArgs.push_back(Output.getFilename());
5885
5886   for (InputInfoList::const_iterator
5887          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5888     const InputInfo &II = *it;
5889     CmdArgs.push_back(II.getFilename());
5890   }
5891
5892   const char *Exec =
5893     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5894   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5895 }
5896
5897 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
5898                                    const InputInfo &Output,
5899                                    const InputInfoList &Inputs,
5900                                    const ArgList &Args,
5901                                    const char *LinkingOutput) const {
5902   const Driver &D = getToolChain().getDriver();
5903   ArgStringList CmdArgs;
5904
5905   if (!D.SysRoot.empty())
5906     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5907
5908   if (Args.hasArg(options::OPT_static)) {
5909     CmdArgs.push_back("-Bstatic");
5910   } else {
5911     if (Args.hasArg(options::OPT_shared))
5912       CmdArgs.push_back("-Bshareable");
5913     else {
5914       CmdArgs.push_back("-dynamic-linker");
5915       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
5916     }
5917   }
5918
5919   // When building 32-bit code on DragonFly/pc64, we have to explicitly
5920   // instruct ld in the base system to link 32-bit code.
5921   if (getToolChain().getArchName() == "i386") {
5922     CmdArgs.push_back("-m");
5923     CmdArgs.push_back("elf_i386");
5924   }
5925
5926   if (Output.isFilename()) {
5927     CmdArgs.push_back("-o");
5928     CmdArgs.push_back(Output.getFilename());
5929   } else {
5930     assert(Output.isNothing() && "Invalid output.");
5931   }
5932
5933   if (!Args.hasArg(options::OPT_nostdlib) &&
5934       !Args.hasArg(options::OPT_nostartfiles)) {
5935     if (!Args.hasArg(options::OPT_shared)) {
5936       CmdArgs.push_back(
5937             Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
5938       CmdArgs.push_back(
5939             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
5940       CmdArgs.push_back(
5941             Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
5942     } else {
5943       CmdArgs.push_back(
5944             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
5945       CmdArgs.push_back(
5946             Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
5947     }
5948   }
5949
5950   Args.AddAllArgs(CmdArgs, options::OPT_L);
5951   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5952   Args.AddAllArgs(CmdArgs, options::OPT_e);
5953
5954   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5955
5956   if (!Args.hasArg(options::OPT_nostdlib) &&
5957       !Args.hasArg(options::OPT_nodefaultlibs)) {
5958     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
5959     //         rpaths
5960     CmdArgs.push_back("-L/usr/lib/gcc41");
5961
5962     if (!Args.hasArg(options::OPT_static)) {
5963       CmdArgs.push_back("-rpath");
5964       CmdArgs.push_back("/usr/lib/gcc41");
5965
5966       CmdArgs.push_back("-rpath-link");
5967       CmdArgs.push_back("/usr/lib/gcc41");
5968
5969       CmdArgs.push_back("-rpath");
5970       CmdArgs.push_back("/usr/lib");
5971
5972       CmdArgs.push_back("-rpath-link");
5973       CmdArgs.push_back("/usr/lib");
5974     }
5975
5976     if (D.CCCIsCXX) {
5977       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5978       CmdArgs.push_back("-lm");
5979     }
5980
5981     if (Args.hasArg(options::OPT_shared)) {
5982       CmdArgs.push_back("-lgcc_pic");
5983     } else {
5984       CmdArgs.push_back("-lgcc");
5985     }
5986
5987
5988     if (Args.hasArg(options::OPT_pthread))
5989       CmdArgs.push_back("-lpthread");
5990
5991     if (!Args.hasArg(options::OPT_nolibc)) {
5992       CmdArgs.push_back("-lc");
5993     }
5994
5995     if (Args.hasArg(options::OPT_shared)) {
5996       CmdArgs.push_back("-lgcc_pic");
5997     } else {
5998       CmdArgs.push_back("-lgcc");
5999     }
6000   }
6001
6002   if (!Args.hasArg(options::OPT_nostdlib) &&
6003       !Args.hasArg(options::OPT_nostartfiles)) {
6004     if (!Args.hasArg(options::OPT_shared))
6005       CmdArgs.push_back(Args.MakeArgString(
6006                               getToolChain().GetFilePath("crtend.o")));
6007     else
6008       CmdArgs.push_back(Args.MakeArgString(
6009                               getToolChain().GetFilePath("crtendS.o")));
6010     CmdArgs.push_back(Args.MakeArgString(
6011                               getToolChain().GetFilePath("crtn.o")));
6012   }
6013
6014   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6015
6016   const char *Exec =
6017     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6018   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6019 }
6020
6021 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
6022                                       const InputInfo &Output,
6023                                       const InputInfoList &Inputs,
6024                                       const ArgList &Args,
6025                                       const char *LinkingOutput) const {
6026   ArgStringList CmdArgs;
6027
6028   if (Output.isFilename()) {
6029     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
6030                                          Output.getFilename()));
6031   } else {
6032     assert(Output.isNothing() && "Invalid output.");
6033   }
6034
6035   if (!Args.hasArg(options::OPT_nostdlib) &&
6036     !Args.hasArg(options::OPT_nostartfiles)) {
6037     CmdArgs.push_back("-defaultlib:libcmt");
6038   }
6039
6040   CmdArgs.push_back("-nologo");
6041
6042   Args.AddAllArgValues(CmdArgs, options::OPT_l);
6043
6044   // Add filenames immediately.
6045   for (InputInfoList::const_iterator
6046        it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6047     if (it->isFilename())
6048       CmdArgs.push_back(it->getFilename());
6049   }
6050
6051   const char *Exec =
6052     Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
6053   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6054 }