]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Driver/Tools.cpp
Vendor import of clang trunk r162107:
[FreeBSD/FreeBSD.git] / 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_fheinous_gnu_extensions);
2274   Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
2275   Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
2276   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
2277   Args.AddLastArg(CmdArgs, options::OPT_faltivec);
2278   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
2279   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
2280
2281   // Report and error for -faltivec on anything other then PowerPC.
2282   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
2283     if (!(getToolChain().getTriple().getArch() == llvm::Triple::ppc ||
2284           getToolChain().getTriple().getArch() == llvm::Triple::ppc64))
2285       D.Diag(diag::err_drv_argument_only_allowed_with)
2286         << A->getAsString(Args) << "ppc/ppc64";
2287
2288   if (getToolChain().SupportsProfiling())
2289     Args.AddLastArg(CmdArgs, options::OPT_pg);
2290
2291   if (Args.hasFlag(options::OPT_faddress_sanitizer,
2292                    options::OPT_fno_address_sanitizer, false))
2293     CmdArgs.push_back("-faddress-sanitizer");
2294
2295   if (Args.hasFlag(options::OPT_fthread_sanitizer,
2296                    options::OPT_fno_thread_sanitizer, false))
2297     CmdArgs.push_back("-fthread-sanitizer");
2298
2299   // -flax-vector-conversions is default.
2300   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
2301                     options::OPT_fno_lax_vector_conversions))
2302     CmdArgs.push_back("-fno-lax-vector-conversions");
2303
2304   if (Args.getLastArg(options::OPT_fapple_kext))
2305     CmdArgs.push_back("-fapple-kext");
2306
2307   if (Args.hasFlag(options::OPT_frewrite_includes,
2308                    options::OPT_fno_rewrite_includes, false))
2309     CmdArgs.push_back("-frewrite-includes");
2310
2311   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
2312   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
2313   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
2314   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
2315   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
2316
2317   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
2318     CmdArgs.push_back("-ftrapv-handler");
2319     CmdArgs.push_back(A->getValue(Args));
2320   }
2321
2322   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
2323
2324   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
2325   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
2326   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
2327                                options::OPT_fno_wrapv)) {
2328     if (A->getOption().matches(options::OPT_fwrapv))
2329       CmdArgs.push_back("-fwrapv");
2330   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
2331                                       options::OPT_fno_strict_overflow)) {
2332     if (A->getOption().matches(options::OPT_fno_strict_overflow))
2333       CmdArgs.push_back("-fwrapv");
2334   }
2335   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
2336   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
2337
2338   Args.AddLastArg(CmdArgs, options::OPT_pthread);
2339
2340   // -stack-protector=0 is default.
2341   unsigned StackProtectorLevel = 0;
2342   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2343                                options::OPT_fstack_protector_all,
2344                                options::OPT_fstack_protector)) {
2345     if (A->getOption().matches(options::OPT_fstack_protector))
2346       StackProtectorLevel = 1;
2347     else if (A->getOption().matches(options::OPT_fstack_protector_all))
2348       StackProtectorLevel = 2;
2349   } else {
2350     StackProtectorLevel =
2351       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
2352   }
2353   if (StackProtectorLevel) {
2354     CmdArgs.push_back("-stack-protector");
2355     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2356   }
2357
2358   // Translate -mstackrealign
2359   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
2360                    false)) {
2361     CmdArgs.push_back("-backend-option");
2362     CmdArgs.push_back("-force-align-stack");
2363   }
2364   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
2365                    false)) {
2366     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
2367   }
2368
2369   if (Args.hasArg(options::OPT_mstack_alignment)) {
2370     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
2371     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
2372   }
2373
2374   // Forward -f options with positive and negative forms; we translate
2375   // these by hand.
2376
2377   if (Args.hasArg(options::OPT_mkernel)) {
2378     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
2379       CmdArgs.push_back("-fapple-kext");
2380     if (!Args.hasArg(options::OPT_fbuiltin))
2381       CmdArgs.push_back("-fno-builtin");
2382     Args.ClaimAllArgs(options::OPT_fno_builtin);
2383   }
2384   // -fbuiltin is default.
2385   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
2386     CmdArgs.push_back("-fno-builtin");
2387
2388   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
2389                     options::OPT_fno_assume_sane_operator_new))
2390     CmdArgs.push_back("-fno-assume-sane-operator-new");
2391
2392   // -fblocks=0 is default.
2393   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
2394                    getToolChain().IsBlocksDefault()) ||
2395         (Args.hasArg(options::OPT_fgnu_runtime) &&
2396          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
2397          !Args.hasArg(options::OPT_fno_blocks))) {
2398     CmdArgs.push_back("-fblocks");
2399
2400     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
2401         !getToolChain().hasBlocksRuntime())
2402       CmdArgs.push_back("-fblocks-runtime-optional");
2403   }
2404
2405   // -fmodules enables modules (off by default). However, for C++/Objective-C++,
2406   // users must also pass -fcxx-modules. The latter flag will disappear once the
2407   // modules implementation is solid for C++/Objective-C++ programs as well.
2408   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2409     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
2410                                      options::OPT_fno_cxx_modules, 
2411                                      false);
2412     if (AllowedInCXX || !types::isCXX(InputType))
2413       CmdArgs.push_back("-fmodules");
2414   }
2415
2416   // -faccess-control is default.
2417   if (Args.hasFlag(options::OPT_fno_access_control,
2418                    options::OPT_faccess_control,
2419                    false))
2420     CmdArgs.push_back("-fno-access-control");
2421
2422   // -felide-constructors is the default.
2423   if (Args.hasFlag(options::OPT_fno_elide_constructors,
2424                    options::OPT_felide_constructors,
2425                    false))
2426     CmdArgs.push_back("-fno-elide-constructors");
2427
2428   // -frtti is default.
2429   if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
2430       KernelOrKext)
2431     CmdArgs.push_back("-fno-rtti");
2432
2433   // -fshort-enums=0 is default for all architectures except Hexagon.
2434   if (Args.hasFlag(options::OPT_fshort_enums,
2435                    options::OPT_fno_short_enums,
2436                    getToolChain().getTriple().getArch() ==
2437                    llvm::Triple::hexagon))
2438     CmdArgs.push_back("-fshort-enums");
2439
2440   // -fsigned-char is default.
2441   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
2442                     isSignedCharDefault(getToolChain().getTriple())))
2443     CmdArgs.push_back("-fno-signed-char");
2444
2445   // -fthreadsafe-static is default.
2446   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
2447                     options::OPT_fno_threadsafe_statics))
2448     CmdArgs.push_back("-fno-threadsafe-statics");
2449
2450   // -fuse-cxa-atexit is default.
2451   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
2452                     options::OPT_fno_use_cxa_atexit,
2453                    getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
2454                   getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 &&
2455               getToolChain().getTriple().getArch() != llvm::Triple::hexagon) ||
2456       KernelOrKext)
2457     CmdArgs.push_back("-fno-use-cxa-atexit");
2458
2459   // -fms-extensions=0 is default.
2460   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2461                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2462     CmdArgs.push_back("-fms-extensions");
2463
2464   // -fms-inline-asm.
2465   if (Args.hasArg(options::OPT_fenable_experimental_ms_inline_asm))
2466     CmdArgs.push_back("-fenable-experimental-ms-inline-asm");
2467
2468   // -fms-compatibility=0 is default.
2469   if (Args.hasFlag(options::OPT_fms_compatibility, 
2470                    options::OPT_fno_ms_compatibility,
2471                    (getToolChain().getTriple().getOS() == llvm::Triple::Win32 &&
2472                     Args.hasFlag(options::OPT_fms_extensions, 
2473                                  options::OPT_fno_ms_extensions,
2474                                  true))))
2475     CmdArgs.push_back("-fms-compatibility");
2476
2477   // -fmsc-version=1300 is default.
2478   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2479                    getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
2480       Args.hasArg(options::OPT_fmsc_version)) {
2481     StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
2482     if (msc_ver.empty())
2483       CmdArgs.push_back("-fmsc-version=1300");
2484     else
2485       CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
2486   }
2487
2488
2489   // -fborland-extensions=0 is default.
2490   if (Args.hasFlag(options::OPT_fborland_extensions,
2491                    options::OPT_fno_borland_extensions, false))
2492     CmdArgs.push_back("-fborland-extensions");
2493
2494   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
2495   // needs it.
2496   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
2497                    options::OPT_fno_delayed_template_parsing,
2498                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2499     CmdArgs.push_back("-fdelayed-template-parsing");
2500
2501   // -fgnu-keywords default varies depending on language; only pass if
2502   // specified.
2503   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
2504                                options::OPT_fno_gnu_keywords))
2505     A->render(Args, CmdArgs);
2506
2507   if (Args.hasFlag(options::OPT_fgnu89_inline,
2508                    options::OPT_fno_gnu89_inline,
2509                    false))
2510     CmdArgs.push_back("-fgnu89-inline");
2511
2512   if (Args.hasArg(options::OPT_fno_inline))
2513     CmdArgs.push_back("-fno-inline");
2514
2515   if (Args.hasArg(options::OPT_fno_inline_functions))
2516     CmdArgs.push_back("-fno-inline-functions");
2517
2518   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
2519
2520   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
2521   // legacy is the default.
2522   if (objcRuntime.isNonFragile()) {
2523     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2524                       options::OPT_fno_objc_legacy_dispatch,
2525                       objcRuntime.isLegacyDispatchDefaultForArch(
2526                         getToolChain().getTriple().getArch()))) {
2527       if (getToolChain().UseObjCMixedDispatch())
2528         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2529       else
2530         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2531     }
2532   }
2533
2534   // -fobjc-default-synthesize-properties=1 is default. This only has an effect
2535   // if the nonfragile objc abi is used.
2536   if (getToolChain().IsObjCDefaultSynthPropertiesDefault()) {
2537     CmdArgs.push_back("-fobjc-default-synthesize-properties");
2538   }
2539
2540   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2541   // NOTE: This logic is duplicated in ToolChains.cpp.
2542   bool ARC = isObjCAutoRefCount(Args);
2543   if (ARC) {
2544     if (!getToolChain().SupportsObjCARC())
2545       D.Diag(diag::err_arc_unsupported);
2546
2547     CmdArgs.push_back("-fobjc-arc");
2548
2549     // FIXME: It seems like this entire block, and several around it should be
2550     // wrapped in isObjC, but for now we just use it here as this is where it
2551     // was being used previously.
2552     if (types::isCXX(InputType) && types::isObjC(InputType)) {
2553       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2554         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2555       else
2556         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2557     }
2558
2559     // Allow the user to enable full exceptions code emission.
2560     // We define off for Objective-CC, on for Objective-C++.
2561     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2562                      options::OPT_fno_objc_arc_exceptions,
2563                      /*default*/ types::isCXX(InputType)))
2564       CmdArgs.push_back("-fobjc-arc-exceptions");
2565   }
2566
2567   // -fobjc-infer-related-result-type is the default, except in the Objective-C
2568   // rewriter.
2569   if (rewriteKind != RK_None)
2570     CmdArgs.push_back("-fno-objc-infer-related-result-type");
2571
2572   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
2573   // takes precedence.
2574   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
2575   if (!GCArg)
2576     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
2577   if (GCArg) {
2578     if (ARC) {
2579       D.Diag(diag::err_drv_objc_gc_arr)
2580         << GCArg->getAsString(Args);
2581     } else if (getToolChain().SupportsObjCGC()) {
2582       GCArg->render(Args, CmdArgs);
2583     } else {
2584       // FIXME: We should move this to a hard error.
2585       D.Diag(diag::warn_drv_objc_gc_unsupported)
2586         << GCArg->getAsString(Args);
2587     }
2588   }
2589
2590   // Add exception args.
2591   addExceptionArgs(Args, InputType, getToolChain().getTriple(),
2592                    KernelOrKext, objcRuntime, CmdArgs);
2593
2594   if (getToolChain().UseSjLjExceptions())
2595     CmdArgs.push_back("-fsjlj-exceptions");
2596
2597   // C++ "sane" operator new.
2598   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
2599                     options::OPT_fno_assume_sane_operator_new))
2600     CmdArgs.push_back("-fno-assume-sane-operator-new");
2601
2602   // -fconstant-cfstrings is default, and may be subject to argument translation
2603   // on Darwin.
2604   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
2605                     options::OPT_fno_constant_cfstrings) ||
2606       !Args.hasFlag(options::OPT_mconstant_cfstrings,
2607                     options::OPT_mno_constant_cfstrings))
2608     CmdArgs.push_back("-fno-constant-cfstrings");
2609
2610   // -fshort-wchar default varies depending on platform; only
2611   // pass if specified.
2612   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
2613     A->render(Args, CmdArgs);
2614
2615   // -fno-pascal-strings is default, only pass non-default. If the tool chain
2616   // happened to translate to -mpascal-strings, we want to back translate here.
2617   //
2618   // FIXME: This is gross; that translation should be pulled from the
2619   // tool chain.
2620   if (Args.hasFlag(options::OPT_fpascal_strings,
2621                    options::OPT_fno_pascal_strings,
2622                    false) ||
2623       Args.hasFlag(options::OPT_mpascal_strings,
2624                    options::OPT_mno_pascal_strings,
2625                    false))
2626     CmdArgs.push_back("-fpascal-strings");
2627
2628   // Honor -fpack-struct= and -fpack-struct, if given. Note that
2629   // -fno-pack-struct doesn't apply to -fpack-struct=.
2630   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
2631     std::string PackStructStr = "-fpack-struct=";
2632     PackStructStr += A->getValue(Args);
2633     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
2634   } else if (Args.hasFlag(options::OPT_fpack_struct,
2635                           options::OPT_fno_pack_struct, false)) {
2636     CmdArgs.push_back("-fpack-struct=1");
2637   }
2638
2639   if (Args.hasArg(options::OPT_mkernel) ||
2640       Args.hasArg(options::OPT_fapple_kext)) {
2641     if (!Args.hasArg(options::OPT_fcommon))
2642       CmdArgs.push_back("-fno-common");
2643     Args.ClaimAllArgs(options::OPT_fno_common);
2644   }
2645
2646   // -fcommon is default, only pass non-default.
2647   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
2648     CmdArgs.push_back("-fno-common");
2649
2650   // -fsigned-bitfields is default, and clang doesn't yet support
2651   // -funsigned-bitfields.
2652   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
2653                     options::OPT_funsigned_bitfields))
2654     D.Diag(diag::warn_drv_clang_unsupported)
2655       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
2656
2657   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
2658   if (!Args.hasFlag(options::OPT_ffor_scope,
2659                     options::OPT_fno_for_scope))
2660     D.Diag(diag::err_drv_clang_unsupported)
2661       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
2662
2663   // -fcaret-diagnostics is default.
2664   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2665                     options::OPT_fno_caret_diagnostics, true))
2666     CmdArgs.push_back("-fno-caret-diagnostics");
2667
2668   // -fdiagnostics-fixit-info is default, only pass non-default.
2669   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2670                     options::OPT_fno_diagnostics_fixit_info))
2671     CmdArgs.push_back("-fno-diagnostics-fixit-info");
2672
2673   // Enable -fdiagnostics-show-option by default.
2674   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2675                    options::OPT_fno_diagnostics_show_option))
2676     CmdArgs.push_back("-fdiagnostics-show-option");
2677
2678   if (const Arg *A =
2679         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2680     CmdArgs.push_back("-fdiagnostics-show-category");
2681     CmdArgs.push_back(A->getValue(Args));
2682   }
2683
2684   if (const Arg *A =
2685         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2686     CmdArgs.push_back("-fdiagnostics-format");
2687     CmdArgs.push_back(A->getValue(Args));
2688   }
2689
2690   if (Arg *A = Args.getLastArg(
2691       options::OPT_fdiagnostics_show_note_include_stack,
2692       options::OPT_fno_diagnostics_show_note_include_stack)) {
2693     if (A->getOption().matches(
2694         options::OPT_fdiagnostics_show_note_include_stack))
2695       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2696     else
2697       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2698   }
2699
2700   // Color diagnostics are the default, unless the terminal doesn't support
2701   // them.
2702   if (Args.hasFlag(options::OPT_fcolor_diagnostics,
2703                    options::OPT_fno_color_diagnostics,
2704                    llvm::sys::Process::StandardErrHasColors()))
2705     CmdArgs.push_back("-fcolor-diagnostics");
2706
2707   if (!Args.hasFlag(options::OPT_fshow_source_location,
2708                     options::OPT_fno_show_source_location))
2709     CmdArgs.push_back("-fno-show-source-location");
2710
2711   if (!Args.hasFlag(options::OPT_fshow_column,
2712                     options::OPT_fno_show_column,
2713                     true))
2714     CmdArgs.push_back("-fno-show-column");
2715
2716   if (!Args.hasFlag(options::OPT_fspell_checking,
2717                     options::OPT_fno_spell_checking))
2718     CmdArgs.push_back("-fno-spell-checking");
2719
2720
2721   // Silently ignore -fasm-blocks for now.
2722   (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
2723                       false);
2724
2725   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
2726     A->render(Args, CmdArgs);
2727
2728   // -fdollars-in-identifiers default varies depending on platform and
2729   // language; only pass if specified.
2730   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
2731                                options::OPT_fno_dollars_in_identifiers)) {
2732     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
2733       CmdArgs.push_back("-fdollars-in-identifiers");
2734     else
2735       CmdArgs.push_back("-fno-dollars-in-identifiers");
2736   }
2737
2738   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
2739   // practical purposes.
2740   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
2741                                options::OPT_fno_unit_at_a_time)) {
2742     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
2743       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
2744   }
2745
2746   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
2747                    options::OPT_fno_apple_pragma_pack, false))
2748     CmdArgs.push_back("-fapple-pragma-pack");
2749
2750   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
2751   //
2752   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
2753 #if 0
2754   if (getToolChain().getTriple().isOSDarwin() &&
2755       (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2756        getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
2757     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
2758       CmdArgs.push_back("-fno-builtin-strcat");
2759     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
2760       CmdArgs.push_back("-fno-builtin-strcpy");
2761   }
2762 #endif
2763
2764   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
2765   if (Arg *A = Args.getLastArg(options::OPT_traditional,
2766                                options::OPT_traditional_cpp)) {
2767     if (isa<PreprocessJobAction>(JA))
2768       CmdArgs.push_back("-traditional-cpp");
2769     else
2770       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2771   }
2772
2773   Args.AddLastArg(CmdArgs, options::OPT_dM);
2774   Args.AddLastArg(CmdArgs, options::OPT_dD);
2775   
2776   // Handle serialized diagnostics.
2777   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
2778     CmdArgs.push_back("-serialize-diagnostic-file");
2779     CmdArgs.push_back(Args.MakeArgString(A->getValue(Args)));
2780   }
2781
2782   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
2783   // parser.
2784   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
2785   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
2786          ie = Args.filtered_end(); it != ie; ++it) {
2787     (*it)->claim();
2788
2789     // We translate this by hand to the -cc1 argument, since nightly test uses
2790     // it and developers have been trained to spell it with -mllvm.
2791     if (StringRef((*it)->getValue(Args, 0)) == "-disable-llvm-optzns")
2792       CmdArgs.push_back("-disable-llvm-optzns");
2793     else
2794       (*it)->render(Args, CmdArgs);
2795   }
2796
2797   if (Output.getType() == types::TY_Dependencies) {
2798     // Handled with other dependency code.
2799   } else if (Output.isFilename()) {
2800     CmdArgs.push_back("-o");
2801     CmdArgs.push_back(Output.getFilename());
2802   } else {
2803     assert(Output.isNothing() && "Invalid output.");
2804   }
2805
2806   for (InputInfoList::const_iterator
2807          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2808     const InputInfo &II = *it;
2809     CmdArgs.push_back("-x");
2810     CmdArgs.push_back(types::getTypeName(II.getType()));
2811     if (II.isFilename())
2812       CmdArgs.push_back(II.getFilename());
2813     else
2814       II.getInputArg().renderAsInput(Args, CmdArgs);
2815   }
2816
2817   Args.AddAllArgs(CmdArgs, options::OPT_undef);
2818
2819   const char *Exec = getToolChain().getDriver().getClangProgramPath();
2820
2821   // Optionally embed the -cc1 level arguments into the debug info, for build
2822   // analysis.
2823   if (getToolChain().UseDwarfDebugFlags()) {
2824     ArgStringList OriginalArgs;
2825     for (ArgList::const_iterator it = Args.begin(),
2826            ie = Args.end(); it != ie; ++it)
2827       (*it)->render(Args, OriginalArgs);
2828
2829     SmallString<256> Flags;
2830     Flags += Exec;
2831     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
2832       Flags += " ";
2833       Flags += OriginalArgs[i];
2834     }
2835     CmdArgs.push_back("-dwarf-debug-flags");
2836     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
2837   }
2838
2839   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2840
2841   if (Arg *A = Args.getLastArg(options::OPT_pg))
2842     if (Args.hasArg(options::OPT_fomit_frame_pointer))
2843       D.Diag(diag::err_drv_argument_not_allowed_with)
2844         << "-fomit-frame-pointer" << A->getAsString(Args);
2845
2846   // Claim some arguments which clang supports automatically.
2847
2848   // -fpch-preprocess is used with gcc to add a special marker in the output to
2849   // include the PCH file. Clang's PTH solution is completely transparent, so we
2850   // do not need to deal with it at all.
2851   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
2852
2853   // Claim some arguments which clang doesn't support, but we don't
2854   // care to warn the user about.
2855   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
2856   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
2857
2858   // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
2859   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
2860   Args.ClaimAllArgs(options::OPT_emit_llvm);
2861 }
2862
2863 void ClangAs::AddARMTargetArgs(const ArgList &Args,
2864                                ArgStringList &CmdArgs) const {
2865   const Driver &D = getToolChain().getDriver();
2866   llvm::Triple Triple = getToolChain().getTriple();
2867
2868   // Set the CPU based on -march= and -mcpu=.
2869   CmdArgs.push_back("-target-cpu");
2870   CmdArgs.push_back(Args.MakeArgString(getARMTargetCPU(Args, Triple)));
2871
2872   // Honor -mfpu=.
2873   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
2874     addFPUArgs(D, A, Args, CmdArgs);
2875
2876   // Honor -mfpmath=.
2877   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ))
2878     addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
2879 }
2880
2881 /// Add options related to the Objective-C runtime/ABI.
2882 ///
2883 /// Returns true if the runtime is non-fragile.
2884 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
2885                                       ArgStringList &cmdArgs,
2886                                       RewriteKind rewriteKind) const {
2887   // Look for the controlling runtime option.
2888   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
2889                                     options::OPT_fgnu_runtime,
2890                                     options::OPT_fobjc_runtime_EQ);
2891
2892   // Just forward -fobjc-runtime= to the frontend.  This supercedes
2893   // options about fragility.
2894   if (runtimeArg &&
2895       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
2896     ObjCRuntime runtime;
2897     StringRef value = runtimeArg->getValue(args);
2898     if (runtime.tryParse(value)) {
2899       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
2900         << value;
2901     }
2902
2903     runtimeArg->render(args, cmdArgs);
2904     return runtime;
2905   }
2906
2907   // Otherwise, we'll need the ABI "version".  Version numbers are
2908   // slightly confusing for historical reasons:
2909   //   1 - Traditional "fragile" ABI
2910   //   2 - Non-fragile ABI, version 1
2911   //   3 - Non-fragile ABI, version 2
2912   unsigned objcABIVersion = 1;
2913   // If -fobjc-abi-version= is present, use that to set the version.
2914   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
2915     StringRef value = abiArg->getValue(args);
2916     if (value == "1")
2917       objcABIVersion = 1;
2918     else if (value == "2")
2919       objcABIVersion = 2;
2920     else if (value == "3")
2921       objcABIVersion = 3;
2922     else
2923       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
2924         << value;
2925   } else {
2926     // Otherwise, determine if we are using the non-fragile ABI.
2927     bool nonFragileABIIsDefault = 
2928       (rewriteKind == RK_NonFragile || 
2929        (rewriteKind == RK_None &&
2930         getToolChain().IsObjCNonFragileABIDefault()));
2931     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
2932                      options::OPT_fno_objc_nonfragile_abi,
2933                      nonFragileABIIsDefault)) {
2934       // Determine the non-fragile ABI version to use.
2935 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
2936       unsigned nonFragileABIVersion = 1;
2937 #else
2938       unsigned nonFragileABIVersion = 2;
2939 #endif
2940
2941       if (Arg *abiArg = args.getLastArg(
2942             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
2943         StringRef value = abiArg->getValue(args);
2944         if (value == "1")
2945           nonFragileABIVersion = 1;
2946         else if (value == "2")
2947           nonFragileABIVersion = 2;
2948         else
2949           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
2950             << value;
2951       }
2952
2953       objcABIVersion = 1 + nonFragileABIVersion;
2954     } else {
2955       objcABIVersion = 1;
2956     }
2957   }
2958
2959   // We don't actually care about the ABI version other than whether
2960   // it's non-fragile.
2961   bool isNonFragile = objcABIVersion != 1;
2962
2963   // If we have no runtime argument, ask the toolchain for its default runtime.
2964   // However, the rewriter only really supports the Mac runtime, so assume that.
2965   ObjCRuntime runtime;
2966   if (!runtimeArg) {
2967     switch (rewriteKind) {
2968     case RK_None:
2969       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
2970       break;
2971     case RK_Fragile:
2972       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
2973       break;
2974     case RK_NonFragile:
2975       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
2976       break;
2977     }
2978
2979   // -fnext-runtime
2980   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
2981     // On Darwin, make this use the default behavior for the toolchain.
2982     if (getToolChain().getTriple().isOSDarwin()) {
2983       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
2984
2985     // Otherwise, build for a generic macosx port.
2986     } else {
2987       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
2988     }
2989
2990   // -fgnu-runtime
2991   } else {
2992     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
2993     // Legacy behaviour is to target the gnustep runtime if we are i
2994     // non-fragile mode or the GCC runtime in fragile mode.
2995     if (isNonFragile)
2996       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple());
2997     else
2998       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
2999   }
3000
3001   cmdArgs.push_back(args.MakeArgString(
3002                                  "-fobjc-runtime=" + runtime.getAsString()));
3003   return runtime;
3004 }
3005
3006 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
3007                            const InputInfo &Output,
3008                            const InputInfoList &Inputs,
3009                            const ArgList &Args,
3010                            const char *LinkingOutput) const {
3011   ArgStringList CmdArgs;
3012
3013   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
3014   const InputInfo &Input = Inputs[0];
3015
3016   // Don't warn about "clang -w -c foo.s"
3017   Args.ClaimAllArgs(options::OPT_w);
3018   // and "clang -emit-llvm -c foo.s"
3019   Args.ClaimAllArgs(options::OPT_emit_llvm);
3020   // and "clang -use-gold-plugin -c foo.s"
3021   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
3022
3023   // Invoke ourselves in -cc1as mode.
3024   //
3025   // FIXME: Implement custom jobs for internal actions.
3026   CmdArgs.push_back("-cc1as");
3027
3028   // Add the "effective" target triple.
3029   CmdArgs.push_back("-triple");
3030   std::string TripleStr = 
3031     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
3032   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3033
3034   // Set the output mode, we currently only expect to be used as a real
3035   // assembler.
3036   CmdArgs.push_back("-filetype");
3037   CmdArgs.push_back("obj");
3038
3039   if (UseRelaxAll(C, Args))
3040     CmdArgs.push_back("-relax-all");
3041
3042   // Add target specific cpu and features flags.
3043   switch(getToolChain().getTriple().getArch()) {
3044   default:
3045     break;
3046
3047   case llvm::Triple::arm:
3048   case llvm::Triple::thumb:
3049     AddARMTargetArgs(Args, CmdArgs);
3050     break;
3051   }
3052
3053   // Ignore explicit -force_cpusubtype_ALL option.
3054   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
3055
3056   // Determine the original source input.
3057   const Action *SourceAction = &JA;
3058   while (SourceAction->getKind() != Action::InputClass) {
3059     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
3060     SourceAction = SourceAction->getInputs()[0];
3061   }
3062
3063   // Forward -g, assuming we are dealing with an actual assembly file.
3064   if (SourceAction->getType() == types::TY_Asm ||
3065       SourceAction->getType() == types::TY_PP_Asm) {
3066     Args.ClaimAllArgs(options::OPT_g_Group);
3067     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
3068       if (!A->getOption().matches(options::OPT_g0))
3069         CmdArgs.push_back("-g");
3070   }
3071
3072   // Optionally embed the -cc1as level arguments into the debug info, for build
3073   // analysis.
3074   if (getToolChain().UseDwarfDebugFlags()) {
3075     ArgStringList OriginalArgs;
3076     for (ArgList::const_iterator it = Args.begin(),
3077            ie = Args.end(); it != ie; ++it)
3078       (*it)->render(Args, OriginalArgs);
3079
3080     SmallString<256> Flags;
3081     const char *Exec = getToolChain().getDriver().getClangProgramPath();
3082     Flags += Exec;
3083     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3084       Flags += " ";
3085       Flags += OriginalArgs[i];
3086     }
3087     CmdArgs.push_back("-dwarf-debug-flags");
3088     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3089   }
3090
3091   // FIXME: Add -static support, once we have it.
3092
3093   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3094                        options::OPT_Xassembler);
3095   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
3096
3097   assert(Output.isFilename() && "Unexpected lipo output.");
3098   CmdArgs.push_back("-o");
3099   CmdArgs.push_back(Output.getFilename());
3100
3101   assert(Input.isFilename() && "Invalid input.");
3102   CmdArgs.push_back(Input.getFilename());
3103
3104   const char *Exec = getToolChain().getDriver().getClangProgramPath();
3105   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3106 }
3107
3108 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
3109                                const InputInfo &Output,
3110                                const InputInfoList &Inputs,
3111                                const ArgList &Args,
3112                                const char *LinkingOutput) const {
3113   const Driver &D = getToolChain().getDriver();
3114   ArgStringList CmdArgs;
3115
3116   for (ArgList::const_iterator
3117          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
3118     Arg *A = *it;
3119     if (A->getOption().hasForwardToGCC()) {
3120       // Don't forward any -g arguments to assembly steps.
3121       if (isa<AssembleJobAction>(JA) &&
3122           A->getOption().matches(options::OPT_g_Group))
3123         continue;
3124
3125       // It is unfortunate that we have to claim here, as this means
3126       // we will basically never report anything interesting for
3127       // platforms using a generic gcc, even if we are just using gcc
3128       // to get to the assembler.
3129       A->claim();
3130       A->render(Args, CmdArgs);
3131     }
3132   }
3133
3134   RenderExtraToolArgs(JA, CmdArgs);
3135
3136   // If using a driver driver, force the arch.
3137   const std::string &Arch = getToolChain().getArchName();
3138   if (getToolChain().getTriple().isOSDarwin()) {
3139     CmdArgs.push_back("-arch");
3140
3141     // FIXME: Remove these special cases.
3142     if (Arch == "powerpc")
3143       CmdArgs.push_back("ppc");
3144     else if (Arch == "powerpc64")
3145       CmdArgs.push_back("ppc64");
3146     else
3147       CmdArgs.push_back(Args.MakeArgString(Arch));
3148   }
3149
3150   // Try to force gcc to match the tool chain we want, if we recognize
3151   // the arch.
3152   //
3153   // FIXME: The triple class should directly provide the information we want
3154   // here.
3155   if (Arch == "i386" || Arch == "powerpc")
3156     CmdArgs.push_back("-m32");
3157   else if (Arch == "x86_64" || Arch == "powerpc64")
3158     CmdArgs.push_back("-m64");
3159
3160   if (Output.isFilename()) {
3161     CmdArgs.push_back("-o");
3162     CmdArgs.push_back(Output.getFilename());
3163   } else {
3164     assert(Output.isNothing() && "Unexpected output");
3165     CmdArgs.push_back("-fsyntax-only");
3166   }
3167
3168   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3169                        options::OPT_Xassembler);
3170
3171   // Only pass -x if gcc will understand it; otherwise hope gcc
3172   // understands the suffix correctly. The main use case this would go
3173   // wrong in is for linker inputs if they happened to have an odd
3174   // suffix; really the only way to get this to happen is a command
3175   // like '-x foobar a.c' which will treat a.c like a linker input.
3176   //
3177   // FIXME: For the linker case specifically, can we safely convert
3178   // inputs into '-Wl,' options?
3179   for (InputInfoList::const_iterator
3180          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3181     const InputInfo &II = *it;
3182
3183     // Don't try to pass LLVM or AST inputs to a generic gcc.
3184     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3185         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3186       D.Diag(diag::err_drv_no_linker_llvm_support)
3187         << getToolChain().getTripleString();
3188     else if (II.getType() == types::TY_AST)
3189       D.Diag(diag::err_drv_no_ast_support)
3190         << getToolChain().getTripleString();
3191
3192     if (types::canTypeBeUserSpecified(II.getType())) {
3193       CmdArgs.push_back("-x");
3194       CmdArgs.push_back(types::getTypeName(II.getType()));
3195     }
3196
3197     if (II.isFilename())
3198       CmdArgs.push_back(II.getFilename());
3199     else {
3200       const Arg &A = II.getInputArg();
3201
3202       // Reverse translate some rewritten options.
3203       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
3204         CmdArgs.push_back("-lstdc++");
3205         continue;
3206       }
3207
3208       // Don't render as input, we need gcc to do the translations.
3209       A.render(Args, CmdArgs);
3210     }
3211   }
3212
3213   const std::string customGCCName = D.getCCCGenericGCCName();
3214   const char *GCCName;
3215   if (!customGCCName.empty())
3216     GCCName = customGCCName.c_str();
3217   else if (D.CCCIsCXX) {
3218     GCCName = "g++";
3219   } else
3220     GCCName = "gcc";
3221
3222   const char *Exec =
3223     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3224   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3225 }
3226
3227 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
3228                                           ArgStringList &CmdArgs) const {
3229   CmdArgs.push_back("-E");
3230 }
3231
3232 void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
3233                                           ArgStringList &CmdArgs) const {
3234   // The type is good enough.
3235 }
3236
3237 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
3238                                        ArgStringList &CmdArgs) const {
3239   const Driver &D = getToolChain().getDriver();
3240
3241   // If -flto, etc. are present then make sure not to force assembly output.
3242   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
3243       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
3244     CmdArgs.push_back("-c");
3245   else {
3246     if (JA.getType() != types::TY_PP_Asm)
3247       D.Diag(diag::err_drv_invalid_gcc_output_type)
3248         << getTypeName(JA.getType());
3249
3250     CmdArgs.push_back("-S");
3251   }
3252 }
3253
3254 void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
3255                                         ArgStringList &CmdArgs) const {
3256   CmdArgs.push_back("-c");
3257 }
3258
3259 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
3260                                     ArgStringList &CmdArgs) const {
3261   // The types are (hopefully) good enough.
3262 }
3263
3264 // Hexagon tools start.
3265 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
3266                                         ArgStringList &CmdArgs) const {
3267
3268 }
3269 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3270                                const InputInfo &Output,
3271                                const InputInfoList &Inputs,
3272                                const ArgList &Args,
3273                                const char *LinkingOutput) const {
3274
3275   const Driver &D = getToolChain().getDriver();
3276   ArgStringList CmdArgs;
3277
3278   std::string MarchString = "-march=";
3279   MarchString += getHexagonTargetCPU(Args);
3280   CmdArgs.push_back(Args.MakeArgString(MarchString));
3281
3282   RenderExtraToolArgs(JA, CmdArgs);
3283
3284   if (Output.isFilename()) {
3285     CmdArgs.push_back("-o");
3286     CmdArgs.push_back(Output.getFilename());
3287   } else {
3288     assert(Output.isNothing() && "Unexpected output");
3289     CmdArgs.push_back("-fsyntax-only");
3290   }
3291
3292
3293   // Only pass -x if gcc will understand it; otherwise hope gcc
3294   // understands the suffix correctly. The main use case this would go
3295   // wrong in is for linker inputs if they happened to have an odd
3296   // suffix; really the only way to get this to happen is a command
3297   // like '-x foobar a.c' which will treat a.c like a linker input.
3298   //
3299   // FIXME: For the linker case specifically, can we safely convert
3300   // inputs into '-Wl,' options?
3301   for (InputInfoList::const_iterator
3302          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3303     const InputInfo &II = *it;
3304
3305     // Don't try to pass LLVM or AST inputs to a generic gcc.
3306     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3307         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3308       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3309         << getToolChain().getTripleString();
3310     else if (II.getType() == types::TY_AST)
3311       D.Diag(clang::diag::err_drv_no_ast_support)
3312         << getToolChain().getTripleString();
3313
3314     if (II.isFilename())
3315       CmdArgs.push_back(II.getFilename());
3316     else
3317       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
3318       II.getInputArg().render(Args, CmdArgs);
3319   }
3320
3321   const char *GCCName = "hexagon-as";
3322   const char *Exec =
3323     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3324   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3325
3326 }
3327 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
3328                                     ArgStringList &CmdArgs) const {
3329   // The types are (hopefully) good enough.
3330 }
3331
3332 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
3333                                const InputInfo &Output,
3334                                const InputInfoList &Inputs,
3335                                const ArgList &Args,
3336                                const char *LinkingOutput) const {
3337
3338   const Driver &D = getToolChain().getDriver();
3339   ArgStringList CmdArgs;
3340
3341   for (ArgList::const_iterator
3342          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
3343     Arg *A = *it;
3344     if (A->getOption().hasForwardToGCC()) {
3345       // Don't forward any -g arguments to assembly steps.
3346       if (isa<AssembleJobAction>(JA) &&
3347           A->getOption().matches(options::OPT_g_Group))
3348         continue;
3349
3350       // It is unfortunate that we have to claim here, as this means
3351       // we will basically never report anything interesting for
3352       // platforms using a generic gcc, even if we are just using gcc
3353       // to get to the assembler.
3354       A->claim();
3355       A->render(Args, CmdArgs);
3356     }
3357   }
3358
3359   RenderExtraToolArgs(JA, CmdArgs);
3360
3361   // Add Arch Information
3362   Arg *A;
3363   if ((A = getLastHexagonArchArg(Args))) {
3364     if (A->getOption().matches(options::OPT_m_Joined))
3365       A->render(Args, CmdArgs);
3366     else
3367       CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
3368   }
3369   else {
3370     CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
3371   }
3372
3373   CmdArgs.push_back("-mqdsp6-compat");
3374
3375   const char *GCCName;
3376   if (C.getDriver().CCCIsCXX)
3377     GCCName = "hexagon-g++";
3378   else
3379     GCCName = "hexagon-gcc";
3380   const char *Exec =
3381     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3382
3383   if (Output.isFilename()) {
3384     CmdArgs.push_back("-o");
3385     CmdArgs.push_back(Output.getFilename());
3386   }
3387
3388   for (InputInfoList::const_iterator
3389          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3390     const InputInfo &II = *it;
3391
3392     // Don't try to pass LLVM or AST inputs to a generic gcc.
3393     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3394         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3395       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3396         << getToolChain().getTripleString();
3397     else if (II.getType() == types::TY_AST)
3398       D.Diag(clang::diag::err_drv_no_ast_support)
3399         << getToolChain().getTripleString();
3400
3401     if (II.isFilename())
3402       CmdArgs.push_back(II.getFilename());
3403     else
3404       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
3405       II.getInputArg().render(Args, CmdArgs);
3406   }
3407   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3408
3409 }
3410 // Hexagon tools end.
3411
3412
3413 const char *darwin::CC1::getCC1Name(types::ID Type) const {
3414   switch (Type) {
3415   default:
3416     llvm_unreachable("Unexpected type for Darwin CC1 tool.");
3417   case types::TY_Asm:
3418   case types::TY_C: case types::TY_CHeader:
3419   case types::TY_PP_C: case types::TY_PP_CHeader:
3420     return "cc1";
3421   case types::TY_ObjC: case types::TY_ObjCHeader:
3422   case types::TY_PP_ObjC: case types::TY_PP_ObjC_Alias:
3423   case types::TY_PP_ObjCHeader:
3424     return "cc1obj";
3425   case types::TY_CXX: case types::TY_CXXHeader:
3426   case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
3427     return "cc1plus";
3428   case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
3429   case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXX_Alias:
3430   case types::TY_PP_ObjCXXHeader:
3431     return "cc1objplus";
3432   }
3433 }
3434
3435 void darwin::CC1::anchor() {}
3436
3437 const char *darwin::CC1::getBaseInputName(const ArgList &Args,
3438                                           const InputInfoList &Inputs) {
3439   return Args.MakeArgString(
3440     llvm::sys::path::filename(Inputs[0].getBaseInput()));
3441 }
3442
3443 const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
3444                                           const InputInfoList &Inputs) {
3445   const char *Str = getBaseInputName(Args, Inputs);
3446
3447   if (const char *End = strrchr(Str, '.'))
3448     return Args.MakeArgString(std::string(Str, End));
3449
3450   return Str;
3451 }
3452
3453 const char *
3454 darwin::CC1::getDependencyFileName(const ArgList &Args,
3455                                    const InputInfoList &Inputs) {
3456   // FIXME: Think about this more.
3457   std::string Res;
3458
3459   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
3460     std::string Str(OutputOpt->getValue(Args));
3461     Res = Str.substr(0, Str.rfind('.'));
3462   } else {
3463     Res = darwin::CC1::getBaseInputStem(Args, Inputs);
3464   }
3465   return Args.MakeArgString(Res + ".d");
3466 }
3467
3468 void darwin::CC1::RemoveCC1UnsupportedArgs(ArgStringList &CmdArgs) const {
3469   for (ArgStringList::iterator it = CmdArgs.begin(), ie = CmdArgs.end();
3470        it != ie;) {
3471
3472     StringRef Option = *it;
3473     bool RemoveOption = false;
3474
3475     // Erase both -fmodule-cache-path and its argument.
3476     if (Option.equals("-fmodule-cache-path") && it+2 != ie) {
3477       it = CmdArgs.erase(it, it+2);
3478       ie = CmdArgs.end();
3479       continue;
3480     }
3481
3482     // Remove unsupported -f options.
3483     if (Option.startswith("-f")) {
3484       // Remove -f/-fno- to reduce the number of cases.
3485       if (Option.startswith("-fno-"))
3486         Option = Option.substr(5);
3487       else
3488         Option = Option.substr(2);
3489       RemoveOption = llvm::StringSwitch<bool>(Option)
3490         .Case("altivec", true)
3491         .Case("modules", true)
3492         .Case("diagnostics-show-note-include-stack", true)
3493         .Default(false);
3494     }
3495
3496     // Handle machine specific options.
3497     if (Option.startswith("-m")) {
3498       RemoveOption = llvm::StringSwitch<bool>(Option)
3499         .Case("-mthumb", true)
3500         .Case("-mno-thumb", true)
3501         .Case("-mno-fused-madd", true)
3502         .Case("-mlong-branch", true)
3503         .Case("-mlongcall", true)
3504         .Case("-mcpu=G4", true)
3505         .Case("-mcpu=G5", true)
3506         .Default(false);
3507     }
3508     
3509     // Handle warning options.
3510     if (Option.startswith("-W")) {
3511       // Remove -W/-Wno- to reduce the number of cases.
3512       if (Option.startswith("-Wno-"))
3513         Option = Option.substr(5);
3514       else
3515         Option = Option.substr(2);
3516       
3517       RemoveOption = llvm::StringSwitch<bool>(Option)
3518         .Case("address-of-temporary", true)
3519         .Case("ambiguous-member-template", true)
3520         .Case("analyzer-incompatible-plugin", true)
3521         .Case("array-bounds", true)
3522         .Case("array-bounds-pointer-arithmetic", true)
3523         .Case("bind-to-temporary-copy", true)
3524         .Case("bitwise-op-parentheses", true)
3525         .Case("bool-conversions", true)
3526         .Case("builtin-macro-redefined", true)
3527         .Case("c++-hex-floats", true)
3528         .Case("c++0x-compat", true)
3529         .Case("c++0x-extensions", true)
3530         .Case("c++0x-narrowing", true)
3531         .Case("c++11-compat", true)
3532         .Case("c++11-extensions", true)
3533         .Case("c++11-narrowing", true)
3534         .Case("conditional-uninitialized", true)
3535         .Case("constant-conversion", true)
3536         .Case("conversion-null", true)
3537         .Case("CFString-literal", true)
3538         .Case("constant-logical-operand", true)
3539         .Case("custom-atomic-properties", true)
3540         .Case("default-arg-special-member", true)
3541         .Case("delegating-ctor-cycles", true)
3542         .Case("delete-non-virtual-dtor", true)
3543         .Case("deprecated-implementations", true)
3544         .Case("deprecated-writable-strings", true)
3545         .Case("distributed-object-modifiers", true)
3546         .Case("duplicate-method-arg", true)
3547         .Case("dynamic-class-memaccess", true)
3548         .Case("enum-compare", true)
3549         .Case("exit-time-destructors", true)
3550         .Case("gnu", true)
3551         .Case("gnu-designator", true)
3552         .Case("header-hygiene", true)
3553         .Case("idiomatic-parentheses", true)
3554         .Case("ignored-qualifiers", true)
3555         .Case("implicit-atomic-properties", true)
3556         .Case("incompatible-pointer-types", true)
3557         .Case("incomplete-implementation", true)
3558         .Case("initializer-overrides", true)
3559         .Case("invalid-noreturn", true)
3560         .Case("invalid-token-paste", true)
3561         .Case("language-extension-token", true)
3562         .Case("literal-conversion", true)
3563         .Case("literal-range", true)
3564         .Case("local-type-template-args", true)
3565         .Case("logical-op-parentheses", true)
3566         .Case("method-signatures", true)
3567         .Case("microsoft", true)
3568         .Case("mismatched-tags", true)
3569         .Case("missing-method-return-type", true)
3570         .Case("non-pod-varargs", true)
3571         .Case("nonfragile-abi2", true)
3572         .Case("null-arithmetic", true)
3573         .Case("null-dereference", true)
3574         .Case("out-of-line-declaration", true)
3575         .Case("overriding-method-mismatch", true)
3576         .Case("readonly-setter-attrs", true)
3577         .Case("return-stack-address", true)
3578         .Case("self-assign", true)
3579         .Case("semicolon-before-method-body", true)
3580         .Case("sentinel", true)
3581         .Case("shift-overflow", true)
3582         .Case("shift-sign-overflow", true)
3583         .Case("sign-conversion", true)
3584         .Case("sizeof-array-argument", true)
3585         .Case("sizeof-pointer-memaccess", true)
3586         .Case("string-compare", true)
3587         .Case("super-class-method-mismatch", true)
3588         .Case("tautological-compare", true)
3589         .Case("typedef-redefinition", true)
3590         .Case("typename-missing", true)
3591         .Case("undefined-reinterpret-cast", true)
3592         .Case("unknown-warning-option", true)
3593         .Case("unnamed-type-template-args", true)
3594         .Case("unneeded-internal-declaration", true)
3595         .Case("unneeded-member-function", true)
3596         .Case("unused-comparison", true)
3597         .Case("unused-exception-parameter", true)
3598         .Case("unused-member-function", true)
3599         .Case("unused-result", true)
3600         .Case("vector-conversions", true)
3601         .Case("vla", true)
3602         .Case("used-but-marked-unused", true)
3603         .Case("weak-vtables", true)
3604         .Default(false);
3605     } // if (Option.startswith("-W"))
3606     if (RemoveOption) {
3607       it = CmdArgs.erase(it);
3608       ie = CmdArgs.end();
3609     } else {
3610       ++it;
3611     }
3612   }
3613 }
3614
3615 void darwin::CC1::AddCC1Args(const ArgList &Args,
3616                              ArgStringList &CmdArgs) const {
3617   const Driver &D = getToolChain().getDriver();
3618
3619   CheckCodeGenerationOptions(D, Args);
3620
3621   // Derived from cc1 spec.
3622   if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) &&
3623       !Args.hasArg(options::OPT_mdynamic_no_pic))
3624     CmdArgs.push_back("-fPIC");
3625
3626   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
3627       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
3628     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
3629       CmdArgs.push_back("-fno-builtin-strcat");
3630     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
3631       CmdArgs.push_back("-fno-builtin-strcpy");
3632   }
3633
3634   if (Args.hasArg(options::OPT_g_Flag) &&
3635       !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
3636     CmdArgs.push_back("-feliminate-unused-debug-symbols");
3637 }
3638
3639 void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
3640                                     const InputInfoList &Inputs,
3641                                     const ArgStringList &OutputArgs) const {
3642   const Driver &D = getToolChain().getDriver();
3643
3644   // Derived from cc1_options spec.
3645   if (Args.hasArg(options::OPT_fast) ||
3646       Args.hasArg(options::OPT_fastf) ||
3647       Args.hasArg(options::OPT_fastcp))
3648     CmdArgs.push_back("-O3");
3649
3650   if (Arg *A = Args.getLastArg(options::OPT_pg))
3651     if (Args.hasArg(options::OPT_fomit_frame_pointer))
3652       D.Diag(diag::err_drv_argument_not_allowed_with)
3653         << A->getAsString(Args) << "-fomit-frame-pointer";
3654
3655   AddCC1Args(Args, CmdArgs);
3656
3657   if (!Args.hasArg(options::OPT_Q))
3658     CmdArgs.push_back("-quiet");
3659
3660   CmdArgs.push_back("-dumpbase");
3661   CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
3662
3663   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
3664
3665   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
3666   Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
3667
3668   // FIXME: The goal is to use the user provided -o if that is our
3669   // final output, otherwise to drive from the original input
3670   // name. Find a clean way to go about this.
3671   if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
3672       Args.hasArg(options::OPT_o)) {
3673     Arg *OutputOpt = Args.getLastArg(options::OPT_o);
3674     CmdArgs.push_back("-auxbase-strip");
3675     CmdArgs.push_back(OutputOpt->getValue(Args));
3676   } else {
3677     CmdArgs.push_back("-auxbase");
3678     CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
3679   }
3680
3681   Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
3682
3683   Args.AddAllArgs(CmdArgs, options::OPT_O);
3684   // FIXME: -Wall is getting some special treatment. Investigate.
3685   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
3686   Args.AddLastArg(CmdArgs, options::OPT_w);
3687   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
3688                   options::OPT_trigraphs);
3689   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3690     // Honor -std-default.
3691     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3692                               "-std=", /*Joined=*/true);
3693   }
3694
3695   if (Args.hasArg(options::OPT_v))
3696     CmdArgs.push_back("-version");
3697   if (Args.hasArg(options::OPT_pg) &&
3698       getToolChain().SupportsProfiling())
3699     CmdArgs.push_back("-p");
3700   Args.AddLastArg(CmdArgs, options::OPT_p);
3701
3702   // The driver treats -fsyntax-only specially.
3703   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
3704       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
3705     // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
3706     // used to inhibit the default -fno-builtin-str{cat,cpy}.
3707     //
3708     // FIXME: Should we grow a better way to deal with "removing" args?
3709     for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
3710                                                options::OPT_fsyntax_only),
3711            ie = Args.filtered_end(); it != ie; ++it) {
3712       if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) &&
3713           !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) {
3714         (*it)->claim();
3715         (*it)->render(Args, CmdArgs);
3716       }
3717     }
3718   } else
3719     Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
3720
3721   // Claim Clang only -f options, they aren't worth warning about.
3722   Args.ClaimAllArgs(options::OPT_f_clang_Group);
3723
3724   Args.AddAllArgs(CmdArgs, options::OPT_undef);
3725   if (Args.hasArg(options::OPT_Qn))
3726     CmdArgs.push_back("-fno-ident");
3727
3728   // FIXME: This isn't correct.
3729   //Args.AddLastArg(CmdArgs, options::OPT__help)
3730   //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
3731
3732   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3733
3734   // FIXME: Still don't get what is happening here. Investigate.
3735   Args.AddAllArgs(CmdArgs, options::OPT__param);
3736
3737   if (Args.hasArg(options::OPT_fmudflap) ||
3738       Args.hasArg(options::OPT_fmudflapth)) {
3739     CmdArgs.push_back("-fno-builtin");
3740     CmdArgs.push_back("-fno-merge-constants");
3741   }
3742
3743   if (Args.hasArg(options::OPT_coverage)) {
3744     CmdArgs.push_back("-fprofile-arcs");
3745     CmdArgs.push_back("-ftest-coverage");
3746   }
3747
3748   if (types::isCXX(Inputs[0].getType()))
3749     CmdArgs.push_back("-D__private_extern__=extern");
3750 }
3751
3752 void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
3753                                     const InputInfoList &Inputs,
3754                                     const ArgStringList &OutputArgs) const {
3755   // Derived from cpp_options
3756   AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
3757
3758   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3759
3760   AddCC1Args(Args, CmdArgs);
3761
3762   // NOTE: The code below has some commonality with cpp_options, but
3763   // in classic gcc style ends up sending things in different
3764   // orders. This may be a good merge candidate once we drop pedantic
3765   // compatibility.
3766
3767   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
3768   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
3769                   options::OPT_trigraphs);
3770   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3771     // Honor -std-default.
3772     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3773                               "-std=", /*Joined=*/true);
3774   }
3775   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
3776   Args.AddLastArg(CmdArgs, options::OPT_w);
3777
3778   // The driver treats -fsyntax-only specially.
3779   Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
3780
3781   // Claim Clang only -f options, they aren't worth warning about.
3782   Args.ClaimAllArgs(options::OPT_f_clang_Group);
3783
3784   if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
3785       !Args.hasArg(options::OPT_fno_working_directory))
3786     CmdArgs.push_back("-fworking-directory");
3787
3788   Args.AddAllArgs(CmdArgs, options::OPT_O);
3789   Args.AddAllArgs(CmdArgs, options::OPT_undef);
3790   if (Args.hasArg(options::OPT_save_temps))
3791     CmdArgs.push_back("-fpch-preprocess");
3792 }
3793
3794 void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
3795                                           ArgStringList &CmdArgs,
3796                                           const InputInfoList &Inputs) const {
3797   const Driver &D = getToolChain().getDriver();
3798
3799   CheckPreprocessingOptions(D, Args);
3800
3801   // Derived from cpp_unique_options.
3802   // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
3803   Args.AddLastArg(CmdArgs, options::OPT_C);
3804   Args.AddLastArg(CmdArgs, options::OPT_CC);
3805   if (!Args.hasArg(options::OPT_Q))
3806     CmdArgs.push_back("-quiet");
3807   Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
3808   Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
3809   Args.AddLastArg(CmdArgs, options::OPT_v);
3810   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
3811   Args.AddLastArg(CmdArgs, options::OPT_P);
3812
3813   // FIXME: Handle %I properly.
3814   if (getToolChain().getArchName() == "x86_64") {
3815     CmdArgs.push_back("-imultilib");
3816     CmdArgs.push_back("x86_64");
3817   }
3818
3819   if (Args.hasArg(options::OPT_MD)) {
3820     CmdArgs.push_back("-MD");
3821     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
3822   }
3823
3824   if (Args.hasArg(options::OPT_MMD)) {
3825     CmdArgs.push_back("-MMD");
3826     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
3827   }
3828
3829   Args.AddLastArg(CmdArgs, options::OPT_M);
3830   Args.AddLastArg(CmdArgs, options::OPT_MM);
3831   Args.AddAllArgs(CmdArgs, options::OPT_MF);
3832   Args.AddLastArg(CmdArgs, options::OPT_MG);
3833   Args.AddLastArg(CmdArgs, options::OPT_MP);
3834   Args.AddAllArgs(CmdArgs, options::OPT_MQ);
3835   Args.AddAllArgs(CmdArgs, options::OPT_MT);
3836   if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
3837       (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
3838     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
3839       CmdArgs.push_back("-MQ");
3840       CmdArgs.push_back(OutputOpt->getValue(Args));
3841     }
3842   }
3843
3844   Args.AddLastArg(CmdArgs, options::OPT_remap);
3845   if (Args.hasArg(options::OPT_g3))
3846     CmdArgs.push_back("-dD");
3847   Args.AddLastArg(CmdArgs, options::OPT_H);
3848
3849   AddCPPArgs(Args, CmdArgs);
3850
3851   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
3852   Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
3853
3854   for (InputInfoList::const_iterator
3855          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3856     const InputInfo &II = *it;
3857
3858     CmdArgs.push_back(II.getFilename());
3859   }
3860
3861   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
3862                        options::OPT_Xpreprocessor);
3863
3864   if (Args.hasArg(options::OPT_fmudflap)) {
3865     CmdArgs.push_back("-D_MUDFLAP");
3866     CmdArgs.push_back("-include");
3867     CmdArgs.push_back("mf-runtime.h");
3868   }
3869
3870   if (Args.hasArg(options::OPT_fmudflapth)) {
3871     CmdArgs.push_back("-D_MUDFLAP");
3872     CmdArgs.push_back("-D_MUDFLAPTH");
3873     CmdArgs.push_back("-include");
3874     CmdArgs.push_back("mf-runtime.h");
3875   }
3876 }
3877
3878 void darwin::CC1::AddCPPArgs(const ArgList &Args,
3879                              ArgStringList &CmdArgs) const {
3880   // Derived from cpp spec.
3881
3882   if (Args.hasArg(options::OPT_static)) {
3883     // The gcc spec is broken here, it refers to dynamic but
3884     // that has been translated. Start by being bug compatible.
3885
3886     // if (!Args.hasArg(arglist.parser.dynamicOption))
3887     CmdArgs.push_back("-D__STATIC__");
3888   } else
3889     CmdArgs.push_back("-D__DYNAMIC__");
3890
3891   if (Args.hasArg(options::OPT_pthread))
3892     CmdArgs.push_back("-D_REENTRANT");
3893 }
3894
3895 void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
3896                                       const InputInfo &Output,
3897                                       const InputInfoList &Inputs,
3898                                       const ArgList &Args,
3899                                       const char *LinkingOutput) const {
3900   ArgStringList CmdArgs;
3901
3902   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
3903
3904   CmdArgs.push_back("-E");
3905
3906   if (Args.hasArg(options::OPT_traditional) ||
3907       Args.hasArg(options::OPT_traditional_cpp))
3908     CmdArgs.push_back("-traditional-cpp");
3909
3910   ArgStringList OutputArgs;
3911   assert(Output.isFilename() && "Unexpected CC1 output.");
3912   OutputArgs.push_back("-o");
3913   OutputArgs.push_back(Output.getFilename());
3914
3915   if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) {
3916     AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
3917   } else {
3918     AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
3919     CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3920   }
3921
3922   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
3923
3924   RemoveCC1UnsupportedArgs(CmdArgs);
3925
3926   const char *CC1Name = getCC1Name(Inputs[0].getType());
3927   const char *Exec =
3928     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
3929   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3930 }
3931
3932 void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
3933                                    const InputInfo &Output,
3934                                    const InputInfoList &Inputs,
3935                                    const ArgList &Args,
3936                                    const char *LinkingOutput) const {
3937   const Driver &D = getToolChain().getDriver();
3938   ArgStringList CmdArgs;
3939
3940   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
3941
3942   // Silence warning about unused --serialize-diagnostics
3943   Args.ClaimAllArgs(options::OPT__serialize_diags);
3944
3945   types::ID InputType = Inputs[0].getType();
3946   if (const Arg *A = Args.getLastArg(options::OPT_traditional))
3947     D.Diag(diag::err_drv_argument_only_allowed_with)
3948       << A->getAsString(Args) << "-E";
3949
3950   if (JA.getType() == types::TY_LLVM_IR ||
3951       JA.getType() == types::TY_LTO_IR)
3952     CmdArgs.push_back("-emit-llvm");
3953   else if (JA.getType() == types::TY_LLVM_BC ||
3954            JA.getType() == types::TY_LTO_BC)
3955     CmdArgs.push_back("-emit-llvm-bc");
3956   else if (Output.getType() == types::TY_AST)
3957     D.Diag(diag::err_drv_no_ast_support)
3958       << getToolChain().getTripleString();
3959   else if (JA.getType() != types::TY_PP_Asm &&
3960            JA.getType() != types::TY_PCH)
3961     D.Diag(diag::err_drv_invalid_gcc_output_type)
3962       << getTypeName(JA.getType());
3963
3964   ArgStringList OutputArgs;
3965   if (Output.getType() != types::TY_PCH) {
3966     OutputArgs.push_back("-o");
3967     if (Output.isNothing())
3968       OutputArgs.push_back("/dev/null");
3969     else
3970       OutputArgs.push_back(Output.getFilename());
3971   }
3972
3973   // There is no need for this level of compatibility, but it makes
3974   // diffing easier.
3975   bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
3976                           Args.hasArg(options::OPT_S));
3977
3978   if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
3979     AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
3980     if (OutputArgsEarly) {
3981       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
3982     } else {
3983       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
3984       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3985     }
3986   } else {
3987     CmdArgs.push_back("-fpreprocessed");
3988
3989     for (InputInfoList::const_iterator
3990            it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3991       const InputInfo &II = *it;
3992
3993       // Reject AST inputs.
3994       if (II.getType() == types::TY_AST) {
3995         D.Diag(diag::err_drv_no_ast_support)
3996           << getToolChain().getTripleString();
3997         return;
3998       }
3999
4000       CmdArgs.push_back(II.getFilename());
4001     }
4002
4003     if (OutputArgsEarly) {
4004       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
4005     } else {
4006       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
4007       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
4008     }
4009   }
4010
4011   if (Output.getType() == types::TY_PCH) {
4012     assert(Output.isFilename() && "Invalid PCH output.");
4013
4014     CmdArgs.push_back("-o");
4015     // NOTE: gcc uses a temp .s file for this, but there doesn't seem
4016     // to be a good reason.
4017     const char *TmpPath = C.getArgs().MakeArgString(
4018       D.GetTemporaryPath("cc", "s"));
4019     C.addTempFile(TmpPath);
4020     CmdArgs.push_back(TmpPath);
4021
4022     // If we're emitting a pch file with the last 4 characters of ".pth"
4023     // and falling back to llvm-gcc we want to use ".gch" instead.
4024     std::string OutputFile(Output.getFilename());
4025     size_t loc = OutputFile.rfind(".pth");
4026     if (loc != std::string::npos)
4027       OutputFile.replace(loc, 4, ".gch");
4028     const char *Tmp = C.getArgs().MakeArgString("--output-pch="+OutputFile);
4029     CmdArgs.push_back(Tmp);
4030   }
4031
4032   RemoveCC1UnsupportedArgs(CmdArgs);
4033
4034   const char *CC1Name = getCC1Name(Inputs[0].getType());
4035   const char *Exec =
4036     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
4037   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4038 }
4039
4040 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4041                                     const InputInfo &Output,
4042                                     const InputInfoList &Inputs,
4043                                     const ArgList &Args,
4044                                     const char *LinkingOutput) const {
4045   ArgStringList CmdArgs;
4046
4047   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4048   const InputInfo &Input = Inputs[0];
4049
4050   // Determine the original source input.
4051   const Action *SourceAction = &JA;
4052   while (SourceAction->getKind() != Action::InputClass) {
4053     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4054     SourceAction = SourceAction->getInputs()[0];
4055   }
4056
4057   // Forward -g, assuming we are dealing with an actual assembly file.
4058   if (SourceAction->getType() == types::TY_Asm ||
4059       SourceAction->getType() == types::TY_PP_Asm) {
4060     if (Args.hasArg(options::OPT_gstabs))
4061       CmdArgs.push_back("--gstabs");
4062     else if (Args.hasArg(options::OPT_g_Group))
4063       CmdArgs.push_back("-g");
4064   }
4065
4066   // Derived from asm spec.
4067   AddDarwinArch(Args, CmdArgs);
4068
4069   // Use -force_cpusubtype_ALL on x86 by default.
4070   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
4071       getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
4072       Args.hasArg(options::OPT_force__cpusubtype__ALL))
4073     CmdArgs.push_back("-force_cpusubtype_ALL");
4074
4075   if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
4076       (Args.hasArg(options::OPT_mkernel) ||
4077        Args.hasArg(options::OPT_static) ||
4078        Args.hasArg(options::OPT_fapple_kext)))
4079     CmdArgs.push_back("-static");
4080
4081   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4082                        options::OPT_Xassembler);
4083
4084   assert(Output.isFilename() && "Unexpected lipo output.");
4085   CmdArgs.push_back("-o");
4086   CmdArgs.push_back(Output.getFilename());
4087
4088   assert(Input.isFilename() && "Invalid input.");
4089   CmdArgs.push_back(Input.getFilename());
4090
4091   // asm_final spec is empty.
4092
4093   const char *Exec =
4094     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4095   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4096 }
4097
4098 void darwin::DarwinTool::anchor() {}
4099
4100 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
4101                                        ArgStringList &CmdArgs) const {
4102   StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
4103
4104   // Derived from darwin_arch spec.
4105   CmdArgs.push_back("-arch");
4106   CmdArgs.push_back(Args.MakeArgString(ArchName));
4107
4108   // FIXME: Is this needed anymore?
4109   if (ArchName == "arm")
4110     CmdArgs.push_back("-force_cpusubtype_ALL");
4111 }
4112
4113 void darwin::Link::AddLinkArgs(Compilation &C,
4114                                const ArgList &Args,
4115                                ArgStringList &CmdArgs) const {
4116   const Driver &D = getToolChain().getDriver();
4117   const toolchains::Darwin &DarwinTC = getDarwinToolChain();
4118
4119   unsigned Version[3] = { 0, 0, 0 };
4120   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4121     bool HadExtra;
4122     if (!Driver::GetReleaseVersion(A->getValue(Args), Version[0],
4123                                    Version[1], Version[2], HadExtra) ||
4124         HadExtra)
4125       D.Diag(diag::err_drv_invalid_version_number)
4126         << A->getAsString(Args);
4127   }
4128
4129   // Newer linkers support -demangle, pass it if supported and not disabled by
4130   // the user.
4131   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
4132     // Don't pass -demangle to ld_classic.
4133     //
4134     // FIXME: This is a temporary workaround, ld should be handling this.
4135     bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
4136                           Args.hasArg(options::OPT_static));
4137     if (getToolChain().getArch() == llvm::Triple::x86) {
4138       for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
4139                                                  options::OPT_Wl_COMMA),
4140              ie = Args.filtered_end(); it != ie; ++it) {
4141         const Arg *A = *it;
4142         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
4143           if (StringRef(A->getValue(Args, i)) == "-kext")
4144             UsesLdClassic = true;
4145       }
4146     }
4147     if (!UsesLdClassic)
4148       CmdArgs.push_back("-demangle");
4149   }
4150
4151   // If we are using LTO, then automatically create a temporary file path for
4152   // the linker to use, so that it's lifetime will extend past a possible
4153   // dsymutil step.
4154   if (Version[0] >= 116 && D.IsUsingLTO(Args)) {
4155     const char *TmpPath = C.getArgs().MakeArgString(
4156       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
4157     C.addTempFile(TmpPath);
4158     CmdArgs.push_back("-object_path_lto");
4159     CmdArgs.push_back(TmpPath);
4160   }
4161
4162   // Derived from the "link" spec.
4163   Args.AddAllArgs(CmdArgs, options::OPT_static);
4164   if (!Args.hasArg(options::OPT_static))
4165     CmdArgs.push_back("-dynamic");
4166   if (Args.hasArg(options::OPT_fgnu_runtime)) {
4167     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
4168     // here. How do we wish to handle such things?
4169   }
4170
4171   if (!Args.hasArg(options::OPT_dynamiclib)) {
4172     AddDarwinArch(Args, CmdArgs);
4173     // FIXME: Why do this only on this path?
4174     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
4175
4176     Args.AddLastArg(CmdArgs, options::OPT_bundle);
4177     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
4178     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
4179
4180     Arg *A;
4181     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
4182         (A = Args.getLastArg(options::OPT_current__version)) ||
4183         (A = Args.getLastArg(options::OPT_install__name)))
4184       D.Diag(diag::err_drv_argument_only_allowed_with)
4185         << A->getAsString(Args) << "-dynamiclib";
4186
4187     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
4188     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
4189     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
4190   } else {
4191     CmdArgs.push_back("-dylib");
4192
4193     Arg *A;
4194     if ((A = Args.getLastArg(options::OPT_bundle)) ||
4195         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
4196         (A = Args.getLastArg(options::OPT_client__name)) ||
4197         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
4198         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
4199         (A = Args.getLastArg(options::OPT_private__bundle)))
4200       D.Diag(diag::err_drv_argument_not_allowed_with)
4201         << A->getAsString(Args) << "-dynamiclib";
4202
4203     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
4204                               "-dylib_compatibility_version");
4205     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
4206                               "-dylib_current_version");
4207
4208     AddDarwinArch(Args, CmdArgs);
4209
4210     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
4211                               "-dylib_install_name");
4212   }
4213
4214   Args.AddLastArg(CmdArgs, options::OPT_all__load);
4215   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
4216   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
4217   if (DarwinTC.isTargetIPhoneOS())
4218     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
4219   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
4220   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
4221   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
4222   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
4223   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
4224   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
4225   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
4226   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
4227   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
4228   Args.AddAllArgs(CmdArgs, options::OPT_init);
4229
4230   // Add the deployment target.
4231   VersionTuple TargetVersion = DarwinTC.getTargetVersion();
4232
4233   // If we had an explicit -mios-simulator-version-min argument, honor that,
4234   // otherwise use the traditional deployment targets. We can't just check the
4235   // is-sim attribute because existing code follows this path, and the linker
4236   // may not handle the argument.
4237   //
4238   // FIXME: We may be able to remove this, once we can verify no one depends on
4239   // it.
4240   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
4241     CmdArgs.push_back("-ios_simulator_version_min");
4242   else if (DarwinTC.isTargetIPhoneOS())
4243     CmdArgs.push_back("-iphoneos_version_min");
4244   else
4245     CmdArgs.push_back("-macosx_version_min");
4246   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
4247
4248   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
4249   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
4250   Args.AddLastArg(CmdArgs, options::OPT_single__module);
4251   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
4252   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
4253
4254   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
4255                                      options::OPT_fno_pie,
4256                                      options::OPT_fno_PIE)) {
4257     if (A->getOption().matches(options::OPT_fpie) ||
4258         A->getOption().matches(options::OPT_fPIE))
4259       CmdArgs.push_back("-pie");
4260     else
4261       CmdArgs.push_back("-no_pie");
4262   }
4263
4264   Args.AddLastArg(CmdArgs, options::OPT_prebind);
4265   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
4266   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
4267   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
4268   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
4269   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
4270   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
4271   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
4272   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
4273   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
4274   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
4275   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
4276   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
4277   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
4278   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
4279   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
4280
4281   // Give --sysroot= preference, over the Apple specific behavior to also use
4282   // --isysroot as the syslibroot.
4283   StringRef sysroot = C.getSysRoot();
4284   if (sysroot != "") {
4285     CmdArgs.push_back("-syslibroot");
4286     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
4287   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4288     CmdArgs.push_back("-syslibroot");
4289     CmdArgs.push_back(A->getValue(Args));
4290   }
4291
4292   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
4293   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
4294   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
4295   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
4296   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
4297   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
4298   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
4299   Args.AddAllArgs(CmdArgs, options::OPT_y);
4300   Args.AddLastArg(CmdArgs, options::OPT_w);
4301   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
4302   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
4303   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
4304   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
4305   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
4306   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
4307   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
4308   Args.AddLastArg(CmdArgs, options::OPT_whyload);
4309   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
4310   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
4311   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
4312   Args.AddLastArg(CmdArgs, options::OPT_Mach);
4313 }
4314
4315 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
4316                                 const InputInfo &Output,
4317                                 const InputInfoList &Inputs,
4318                                 const ArgList &Args,
4319                                 const char *LinkingOutput) const {
4320   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
4321
4322   // The logic here is derived from gcc's behavior; most of which
4323   // comes from specs (starting with link_command). Consult gcc for
4324   // more information.
4325   ArgStringList CmdArgs;
4326
4327   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
4328   if (Args.hasArg(options::OPT_ccc_arcmt_check,
4329                   options::OPT_ccc_arcmt_migrate)) {
4330     for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
4331       (*I)->claim();
4332     const char *Exec =
4333       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
4334     CmdArgs.push_back(Output.getFilename());
4335     C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4336     return;
4337   }
4338
4339   // I'm not sure why this particular decomposition exists in gcc, but
4340   // we follow suite for ease of comparison.
4341   AddLinkArgs(C, Args, CmdArgs);
4342
4343   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
4344   Args.AddAllArgs(CmdArgs, options::OPT_s);
4345   Args.AddAllArgs(CmdArgs, options::OPT_t);
4346   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
4347   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4348   Args.AddLastArg(CmdArgs, options::OPT_e);
4349   Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
4350   Args.AddAllArgs(CmdArgs, options::OPT_r);
4351
4352   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
4353   // members of static archive libraries which implement Objective-C classes or
4354   // categories.
4355   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
4356     CmdArgs.push_back("-ObjC");
4357
4358   CmdArgs.push_back("-o");
4359   CmdArgs.push_back(Output.getFilename());
4360
4361   if (!Args.hasArg(options::OPT_nostdlib) &&
4362       !Args.hasArg(options::OPT_nostartfiles)) {
4363     // Derived from startfile spec.
4364     if (Args.hasArg(options::OPT_dynamiclib)) {
4365       // Derived from darwin_dylib1 spec.
4366       if (getDarwinToolChain().isTargetIOSSimulator()) {
4367         // The simulator doesn't have a versioned crt1 file.
4368         CmdArgs.push_back("-ldylib1.o");
4369       } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4370         if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4371           CmdArgs.push_back("-ldylib1.o");
4372       } else {
4373         if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4374           CmdArgs.push_back("-ldylib1.o");
4375         else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4376           CmdArgs.push_back("-ldylib1.10.5.o");
4377       }
4378     } else {
4379       if (Args.hasArg(options::OPT_bundle)) {
4380         if (!Args.hasArg(options::OPT_static)) {
4381           // Derived from darwin_bundle1 spec.
4382           if (getDarwinToolChain().isTargetIOSSimulator()) {
4383             // The simulator doesn't have a versioned crt1 file.
4384             CmdArgs.push_back("-lbundle1.o");
4385           } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4386             if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4387               CmdArgs.push_back("-lbundle1.o");
4388           } else {
4389             if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4390               CmdArgs.push_back("-lbundle1.o");
4391           }
4392         }
4393       } else {
4394         if (Args.hasArg(options::OPT_pg) &&
4395             getToolChain().SupportsProfiling()) {
4396           if (Args.hasArg(options::OPT_static) ||
4397               Args.hasArg(options::OPT_object) ||
4398               Args.hasArg(options::OPT_preload)) {
4399             CmdArgs.push_back("-lgcrt0.o");
4400           } else {
4401             CmdArgs.push_back("-lgcrt1.o");
4402
4403             // darwin_crt2 spec is empty.
4404           }
4405           // By default on OS X 10.8 and later, we don't link with a crt1.o
4406           // file and the linker knows to use _main as the entry point.  But,
4407           // when compiling with -pg, we need to link with the gcrt1.o file,
4408           // so pass the -no_new_main option to tell the linker to use the
4409           // "start" symbol as the entry point.
4410           if (getDarwinToolChain().isTargetMacOS() &&
4411               !getDarwinToolChain().isMacosxVersionLT(10, 8))
4412             CmdArgs.push_back("-no_new_main");
4413         } else {
4414           if (Args.hasArg(options::OPT_static) ||
4415               Args.hasArg(options::OPT_object) ||
4416               Args.hasArg(options::OPT_preload)) {
4417             CmdArgs.push_back("-lcrt0.o");
4418           } else {
4419             // Derived from darwin_crt1 spec.
4420             if (getDarwinToolChain().isTargetIOSSimulator()) {
4421               // The simulator doesn't have a versioned crt1 file.
4422               CmdArgs.push_back("-lcrt1.o");
4423             } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4424               if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4425                 CmdArgs.push_back("-lcrt1.o");
4426               else
4427                 CmdArgs.push_back("-lcrt1.3.1.o");
4428             } else {
4429               if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4430                 CmdArgs.push_back("-lcrt1.o");
4431               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4432                 CmdArgs.push_back("-lcrt1.10.5.o");
4433               else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
4434                 CmdArgs.push_back("-lcrt1.10.6.o");
4435
4436               // darwin_crt2 spec is empty.
4437             }
4438           }
4439         }
4440       }
4441     }
4442
4443     if (!getDarwinToolChain().isTargetIPhoneOS() &&
4444         Args.hasArg(options::OPT_shared_libgcc) &&
4445         getDarwinToolChain().isMacosxVersionLT(10, 5)) {
4446       const char *Str =
4447         Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
4448       CmdArgs.push_back(Str);
4449     }
4450   }
4451
4452   Args.AddAllArgs(CmdArgs, options::OPT_L);
4453
4454   // If we're building a dynamic lib with -faddress-sanitizer, unresolved
4455   // symbols may appear. Mark all of them as dynamic_lookup.
4456   // Linking executables is handled in lib/Driver/ToolChains.cpp.
4457   if (Args.hasFlag(options::OPT_faddress_sanitizer,
4458                    options::OPT_fno_address_sanitizer, false)) {
4459     if (Args.hasArg(options::OPT_dynamiclib) ||
4460         Args.hasArg(options::OPT_bundle)) {
4461       CmdArgs.push_back("-undefined");
4462       CmdArgs.push_back("dynamic_lookup");
4463     }
4464   }
4465
4466   if (Args.hasArg(options::OPT_fopenmp))
4467     // This is more complicated in gcc...
4468     CmdArgs.push_back("-lgomp");
4469
4470   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4471   
4472   if (isObjCRuntimeLinked(Args) &&
4473       !Args.hasArg(options::OPT_nostdlib) &&
4474       !Args.hasArg(options::OPT_nodefaultlibs)) {
4475     // Avoid linking compatibility stubs on i386 mac.
4476     if (!getDarwinToolChain().isTargetMacOS() ||
4477         getDarwinToolChain().getArchName() != "i386") {
4478       // If we don't have ARC or subscripting runtime support, link in the
4479       // runtime stubs.  We have to do this *before* adding any of the normal
4480       // linker inputs so that its initializer gets run first.
4481       ObjCRuntime runtime =
4482         getDarwinToolChain().getDefaultObjCRuntime(/*nonfragile*/ true);
4483       // We use arclite library for both ARC and subscripting support.
4484       if ((!runtime.hasARC() && isObjCAutoRefCount(Args)) ||
4485           !runtime.hasSubscripting())
4486         getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
4487     }
4488     CmdArgs.push_back("-framework");
4489     CmdArgs.push_back("Foundation");
4490     // Link libobj.
4491     CmdArgs.push_back("-lobjc");
4492   }
4493
4494   if (LinkingOutput) {
4495     CmdArgs.push_back("-arch_multiple");
4496     CmdArgs.push_back("-final_output");
4497     CmdArgs.push_back(LinkingOutput);
4498   }
4499
4500   if (Args.hasArg(options::OPT_fnested_functions))
4501     CmdArgs.push_back("-allow_stack_execute");
4502
4503   if (!Args.hasArg(options::OPT_nostdlib) &&
4504       !Args.hasArg(options::OPT_nodefaultlibs)) {
4505     if (getToolChain().getDriver().CCCIsCXX)
4506       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4507
4508     // link_ssp spec is empty.
4509
4510     // Let the tool chain choose which runtime library to link.
4511     getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
4512   }
4513
4514   if (!Args.hasArg(options::OPT_nostdlib) &&
4515       !Args.hasArg(options::OPT_nostartfiles)) {
4516     // endfile_spec is empty.
4517   }
4518
4519   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4520   Args.AddAllArgs(CmdArgs, options::OPT_F);
4521
4522   const char *Exec =
4523     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4524   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4525 }
4526
4527 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
4528                                 const InputInfo &Output,
4529                                 const InputInfoList &Inputs,
4530                                 const ArgList &Args,
4531                                 const char *LinkingOutput) const {
4532   ArgStringList CmdArgs;
4533
4534   CmdArgs.push_back("-create");
4535   assert(Output.isFilename() && "Unexpected lipo output.");
4536
4537   CmdArgs.push_back("-output");
4538   CmdArgs.push_back(Output.getFilename());
4539
4540   for (InputInfoList::const_iterator
4541          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4542     const InputInfo &II = *it;
4543     assert(II.isFilename() && "Unexpected lipo input.");
4544     CmdArgs.push_back(II.getFilename());
4545   }
4546   const char *Exec =
4547     Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
4548   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4549 }
4550
4551 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
4552                                     const InputInfo &Output,
4553                                     const InputInfoList &Inputs,
4554                                     const ArgList &Args,
4555                                     const char *LinkingOutput) const {
4556   ArgStringList CmdArgs;
4557
4558   CmdArgs.push_back("-o");
4559   CmdArgs.push_back(Output.getFilename());
4560
4561   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4562   const InputInfo &Input = Inputs[0];
4563   assert(Input.isFilename() && "Unexpected dsymutil input.");
4564   CmdArgs.push_back(Input.getFilename());
4565
4566   const char *Exec =
4567     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
4568   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4569 }
4570
4571 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
4572                                        const InputInfo &Output,
4573                                        const InputInfoList &Inputs,
4574                                        const ArgList &Args,
4575                                        const char *LinkingOutput) const {
4576   ArgStringList CmdArgs;
4577   CmdArgs.push_back("--verify");
4578   CmdArgs.push_back("--debug-info");
4579   CmdArgs.push_back("--eh-frame");
4580   CmdArgs.push_back("--quiet");
4581
4582   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4583   const InputInfo &Input = Inputs[0];
4584   assert(Input.isFilename() && "Unexpected verify input");
4585
4586   // Grabbing the output of the earlier dsymutil run.
4587   CmdArgs.push_back(Input.getFilename());
4588
4589   const char *Exec =
4590     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
4591   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4592 }
4593
4594 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4595                                       const InputInfo &Output,
4596                                       const InputInfoList &Inputs,
4597                                       const ArgList &Args,
4598                                       const char *LinkingOutput) const {
4599   ArgStringList CmdArgs;
4600
4601   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4602                        options::OPT_Xassembler);
4603
4604   CmdArgs.push_back("-o");
4605   CmdArgs.push_back(Output.getFilename());
4606
4607   for (InputInfoList::const_iterator
4608          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4609     const InputInfo &II = *it;
4610     CmdArgs.push_back(II.getFilename());
4611   }
4612
4613   const char *Exec =
4614     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4615   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4616 }
4617
4618
4619 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
4620                                   const InputInfo &Output,
4621                                   const InputInfoList &Inputs,
4622                                   const ArgList &Args,
4623                                   const char *LinkingOutput) const {
4624   // FIXME: Find a real GCC, don't hard-code versions here
4625   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
4626   const llvm::Triple &T = getToolChain().getTriple();
4627   std::string LibPath = "/usr/lib/";
4628   llvm::Triple::ArchType Arch = T.getArch();
4629   switch (Arch) {
4630         case llvm::Triple::x86:
4631           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4632               T.getOSName()).str() + "/4.5.2/";
4633           break;
4634         case llvm::Triple::x86_64:
4635           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4636               T.getOSName()).str();
4637           GCCLibPath += "/4.5.2/amd64/";
4638           LibPath += "amd64/";
4639           break;
4640         default:
4641           assert(0 && "Unsupported architecture");
4642   }
4643
4644   ArgStringList CmdArgs;
4645
4646   // Demangle C++ names in errors
4647   CmdArgs.push_back("-C");
4648
4649   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4650       (!Args.hasArg(options::OPT_shared))) {
4651     CmdArgs.push_back("-e");
4652     CmdArgs.push_back("_start");
4653   }
4654
4655   if (Args.hasArg(options::OPT_static)) {
4656     CmdArgs.push_back("-Bstatic");
4657     CmdArgs.push_back("-dn");
4658   } else {
4659     CmdArgs.push_back("-Bdynamic");
4660     if (Args.hasArg(options::OPT_shared)) {
4661       CmdArgs.push_back("-shared");
4662     } else {
4663       CmdArgs.push_back("--dynamic-linker");
4664       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
4665     }
4666   }
4667
4668   if (Output.isFilename()) {
4669     CmdArgs.push_back("-o");
4670     CmdArgs.push_back(Output.getFilename());
4671   } else {
4672     assert(Output.isNothing() && "Invalid output.");
4673   }
4674
4675   if (!Args.hasArg(options::OPT_nostdlib) &&
4676       !Args.hasArg(options::OPT_nostartfiles)) {
4677     if (!Args.hasArg(options::OPT_shared)) {
4678       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
4679       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4680       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4681       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4682     } else {
4683       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4684       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4685       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4686     }
4687     if (getToolChain().getDriver().CCCIsCXX)
4688       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
4689   }
4690
4691   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
4692
4693   Args.AddAllArgs(CmdArgs, options::OPT_L);
4694   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4695   Args.AddAllArgs(CmdArgs, options::OPT_e);
4696   Args.AddAllArgs(CmdArgs, options::OPT_r);
4697
4698   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4699
4700   if (!Args.hasArg(options::OPT_nostdlib) &&
4701       !Args.hasArg(options::OPT_nodefaultlibs)) {
4702     if (getToolChain().getDriver().CCCIsCXX)
4703       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4704     CmdArgs.push_back("-lgcc_s");
4705     if (!Args.hasArg(options::OPT_shared)) {
4706       CmdArgs.push_back("-lgcc");
4707       CmdArgs.push_back("-lc");
4708       CmdArgs.push_back("-lm");
4709     }
4710   }
4711
4712   if (!Args.hasArg(options::OPT_nostdlib) &&
4713       !Args.hasArg(options::OPT_nostartfiles)) {
4714     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
4715   }
4716   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
4717
4718   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4719
4720   const char *Exec =
4721     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4722   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4723 }
4724
4725 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4726                                       const InputInfo &Output,
4727                                       const InputInfoList &Inputs,
4728                                       const ArgList &Args,
4729                                       const char *LinkingOutput) const {
4730   ArgStringList CmdArgs;
4731
4732   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4733                        options::OPT_Xassembler);
4734
4735   CmdArgs.push_back("-o");
4736   CmdArgs.push_back(Output.getFilename());
4737
4738   for (InputInfoList::const_iterator
4739          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4740     const InputInfo &II = *it;
4741     CmdArgs.push_back(II.getFilename());
4742   }
4743
4744   const char *Exec =
4745     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
4746   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4747 }
4748
4749 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
4750                                   const InputInfo &Output,
4751                                   const InputInfoList &Inputs,
4752                                   const ArgList &Args,
4753                                   const char *LinkingOutput) const {
4754   ArgStringList CmdArgs;
4755
4756   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4757       (!Args.hasArg(options::OPT_shared))) {
4758     CmdArgs.push_back("-e");
4759     CmdArgs.push_back("_start");
4760   }
4761
4762   if (Args.hasArg(options::OPT_static)) {
4763     CmdArgs.push_back("-Bstatic");
4764     CmdArgs.push_back("-dn");
4765   } else {
4766 //    CmdArgs.push_back("--eh-frame-hdr");
4767     CmdArgs.push_back("-Bdynamic");
4768     if (Args.hasArg(options::OPT_shared)) {
4769       CmdArgs.push_back("-shared");
4770     } else {
4771       CmdArgs.push_back("--dynamic-linker");
4772       CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
4773     }
4774   }
4775
4776   if (Output.isFilename()) {
4777     CmdArgs.push_back("-o");
4778     CmdArgs.push_back(Output.getFilename());
4779   } else {
4780     assert(Output.isNothing() && "Invalid output.");
4781   }
4782
4783   if (!Args.hasArg(options::OPT_nostdlib) &&
4784       !Args.hasArg(options::OPT_nostartfiles)) {
4785     if (!Args.hasArg(options::OPT_shared)) {
4786       CmdArgs.push_back(Args.MakeArgString(
4787                                 getToolChain().GetFilePath("crt1.o")));
4788       CmdArgs.push_back(Args.MakeArgString(
4789                                 getToolChain().GetFilePath("crti.o")));
4790       CmdArgs.push_back(Args.MakeArgString(
4791                                 getToolChain().GetFilePath("crtbegin.o")));
4792     } else {
4793       CmdArgs.push_back(Args.MakeArgString(
4794                                 getToolChain().GetFilePath("crti.o")));
4795     }
4796     CmdArgs.push_back(Args.MakeArgString(
4797                                 getToolChain().GetFilePath("crtn.o")));
4798   }
4799
4800   CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
4801                                        + getToolChain().getTripleString()
4802                                        + "/4.2.4"));
4803
4804   Args.AddAllArgs(CmdArgs, options::OPT_L);
4805   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4806   Args.AddAllArgs(CmdArgs, options::OPT_e);
4807
4808   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4809
4810   if (!Args.hasArg(options::OPT_nostdlib) &&
4811       !Args.hasArg(options::OPT_nodefaultlibs)) {
4812     // FIXME: For some reason GCC passes -lgcc before adding
4813     // the default system libraries. Just mimic this for now.
4814     CmdArgs.push_back("-lgcc");
4815
4816     if (Args.hasArg(options::OPT_pthread))
4817       CmdArgs.push_back("-pthread");
4818     if (!Args.hasArg(options::OPT_shared))
4819       CmdArgs.push_back("-lc");
4820     CmdArgs.push_back("-lgcc");
4821   }
4822
4823   if (!Args.hasArg(options::OPT_nostdlib) &&
4824       !Args.hasArg(options::OPT_nostartfiles)) {
4825     if (!Args.hasArg(options::OPT_shared))
4826       CmdArgs.push_back(Args.MakeArgString(
4827                                 getToolChain().GetFilePath("crtend.o")));
4828   }
4829
4830   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4831
4832   const char *Exec =
4833     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4834   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4835 }
4836
4837 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4838                                      const InputInfo &Output,
4839                                      const InputInfoList &Inputs,
4840                                      const ArgList &Args,
4841                                      const char *LinkingOutput) const {
4842   ArgStringList CmdArgs;
4843
4844   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4845                        options::OPT_Xassembler);
4846
4847   CmdArgs.push_back("-o");
4848   CmdArgs.push_back(Output.getFilename());
4849
4850   for (InputInfoList::const_iterator
4851          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4852     const InputInfo &II = *it;
4853     CmdArgs.push_back(II.getFilename());
4854   }
4855
4856   const char *Exec =
4857     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4858   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4859 }
4860
4861 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
4862                                  const InputInfo &Output,
4863                                  const InputInfoList &Inputs,
4864                                  const ArgList &Args,
4865                                  const char *LinkingOutput) const {
4866   const Driver &D = getToolChain().getDriver();
4867   ArgStringList CmdArgs;
4868
4869   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4870       (!Args.hasArg(options::OPT_shared))) {
4871     CmdArgs.push_back("-e");
4872     CmdArgs.push_back("__start");
4873   }
4874
4875   if (Args.hasArg(options::OPT_static)) {
4876     CmdArgs.push_back("-Bstatic");
4877   } else {
4878     if (Args.hasArg(options::OPT_rdynamic))
4879       CmdArgs.push_back("-export-dynamic");
4880     CmdArgs.push_back("--eh-frame-hdr");
4881     CmdArgs.push_back("-Bdynamic");
4882     if (Args.hasArg(options::OPT_shared)) {
4883       CmdArgs.push_back("-shared");
4884     } else {
4885       CmdArgs.push_back("-dynamic-linker");
4886       CmdArgs.push_back("/usr/libexec/ld.so");
4887     }
4888   }
4889
4890   if (Output.isFilename()) {
4891     CmdArgs.push_back("-o");
4892     CmdArgs.push_back(Output.getFilename());
4893   } else {
4894     assert(Output.isNothing() && "Invalid output.");
4895   }
4896
4897   if (!Args.hasArg(options::OPT_nostdlib) &&
4898       !Args.hasArg(options::OPT_nostartfiles)) {
4899     if (!Args.hasArg(options::OPT_shared)) {
4900       if (Args.hasArg(options::OPT_pg))  
4901         CmdArgs.push_back(Args.MakeArgString(
4902                                 getToolChain().GetFilePath("gcrt0.o")));
4903       else
4904         CmdArgs.push_back(Args.MakeArgString(
4905                                 getToolChain().GetFilePath("crt0.o")));
4906       CmdArgs.push_back(Args.MakeArgString(
4907                               getToolChain().GetFilePath("crtbegin.o")));
4908     } else {
4909       CmdArgs.push_back(Args.MakeArgString(
4910                               getToolChain().GetFilePath("crtbeginS.o")));
4911     }
4912   }
4913
4914   std::string Triple = getToolChain().getTripleString();
4915   if (Triple.substr(0, 6) == "x86_64")
4916     Triple.replace(0, 6, "amd64");
4917   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
4918                                        "/4.2.1"));
4919
4920   Args.AddAllArgs(CmdArgs, options::OPT_L);
4921   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4922   Args.AddAllArgs(CmdArgs, options::OPT_e);
4923
4924   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4925
4926   if (!Args.hasArg(options::OPT_nostdlib) &&
4927       !Args.hasArg(options::OPT_nodefaultlibs)) {
4928     if (D.CCCIsCXX) {
4929       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4930       if (Args.hasArg(options::OPT_pg)) 
4931         CmdArgs.push_back("-lm_p");
4932       else
4933         CmdArgs.push_back("-lm");
4934     }
4935
4936     // FIXME: For some reason GCC passes -lgcc before adding
4937     // the default system libraries. Just mimic this for now.
4938     CmdArgs.push_back("-lgcc");
4939
4940     if (Args.hasArg(options::OPT_pthread))
4941       CmdArgs.push_back("-lpthread");
4942     if (!Args.hasArg(options::OPT_shared)) {
4943       if (Args.hasArg(options::OPT_pg)) 
4944          CmdArgs.push_back("-lc_p");
4945       else
4946          CmdArgs.push_back("-lc");
4947     }
4948     CmdArgs.push_back("-lgcc");
4949   }
4950
4951   if (!Args.hasArg(options::OPT_nostdlib) &&
4952       !Args.hasArg(options::OPT_nostartfiles)) {
4953     if (!Args.hasArg(options::OPT_shared))
4954       CmdArgs.push_back(Args.MakeArgString(
4955                               getToolChain().GetFilePath("crtend.o")));
4956     else
4957       CmdArgs.push_back(Args.MakeArgString(
4958                               getToolChain().GetFilePath("crtendS.o")));
4959   }
4960
4961   const char *Exec =
4962     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4963   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4964 }
4965
4966 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4967                                     const InputInfo &Output,
4968                                     const InputInfoList &Inputs,
4969                                     const ArgList &Args,
4970                                     const char *LinkingOutput) const {
4971   ArgStringList CmdArgs;
4972
4973   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4974                        options::OPT_Xassembler);
4975
4976   CmdArgs.push_back("-o");
4977   CmdArgs.push_back(Output.getFilename());
4978
4979   for (InputInfoList::const_iterator
4980          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4981     const InputInfo &II = *it;
4982     CmdArgs.push_back(II.getFilename());
4983   }
4984
4985   const char *Exec =
4986     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4987   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4988 }
4989
4990 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
4991                                 const InputInfo &Output,
4992                                 const InputInfoList &Inputs,
4993                                 const ArgList &Args,
4994                                 const char *LinkingOutput) const {
4995   const Driver &D = getToolChain().getDriver();
4996   ArgStringList CmdArgs;
4997
4998   if ((!Args.hasArg(options::OPT_nostdlib)) &&
4999       (!Args.hasArg(options::OPT_shared))) {
5000     CmdArgs.push_back("-e");
5001     CmdArgs.push_back("__start");
5002   }
5003
5004   if (Args.hasArg(options::OPT_static)) {
5005     CmdArgs.push_back("-Bstatic");
5006   } else {
5007     if (Args.hasArg(options::OPT_rdynamic))
5008       CmdArgs.push_back("-export-dynamic");
5009     CmdArgs.push_back("--eh-frame-hdr");
5010     CmdArgs.push_back("-Bdynamic");
5011     if (Args.hasArg(options::OPT_shared)) {
5012       CmdArgs.push_back("-shared");
5013     } else {
5014       CmdArgs.push_back("-dynamic-linker");
5015       CmdArgs.push_back("/usr/libexec/ld.so");
5016     }
5017   }
5018
5019   if (Output.isFilename()) {
5020     CmdArgs.push_back("-o");
5021     CmdArgs.push_back(Output.getFilename());
5022   } else {
5023     assert(Output.isNothing() && "Invalid output.");
5024   }
5025
5026   if (!Args.hasArg(options::OPT_nostdlib) &&
5027       !Args.hasArg(options::OPT_nostartfiles)) {
5028     if (!Args.hasArg(options::OPT_shared)) {
5029       if (Args.hasArg(options::OPT_pg))
5030         CmdArgs.push_back(Args.MakeArgString(
5031                                 getToolChain().GetFilePath("gcrt0.o")));
5032       else
5033         CmdArgs.push_back(Args.MakeArgString(
5034                                 getToolChain().GetFilePath("crt0.o")));
5035       CmdArgs.push_back(Args.MakeArgString(
5036                               getToolChain().GetFilePath("crtbegin.o")));
5037     } else {
5038       CmdArgs.push_back(Args.MakeArgString(
5039                               getToolChain().GetFilePath("crtbeginS.o")));
5040     }
5041   }
5042
5043   Args.AddAllArgs(CmdArgs, options::OPT_L);
5044   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5045   Args.AddAllArgs(CmdArgs, options::OPT_e);
5046
5047   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5048
5049   if (!Args.hasArg(options::OPT_nostdlib) &&
5050       !Args.hasArg(options::OPT_nodefaultlibs)) {
5051     if (D.CCCIsCXX) {
5052       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5053       if (Args.hasArg(options::OPT_pg))
5054         CmdArgs.push_back("-lm_p");
5055       else
5056         CmdArgs.push_back("-lm");
5057     }
5058
5059     if (Args.hasArg(options::OPT_pthread))
5060       CmdArgs.push_back("-lpthread");
5061     if (!Args.hasArg(options::OPT_shared)) {
5062       if (Args.hasArg(options::OPT_pg))
5063         CmdArgs.push_back("-lc_p");
5064       else
5065         CmdArgs.push_back("-lc");
5066     }
5067
5068     std::string myarch = "-lclang_rt.";
5069     const llvm::Triple &T = getToolChain().getTriple();
5070     llvm::Triple::ArchType Arch = T.getArch();
5071     switch (Arch) {
5072           case llvm::Triple::arm:
5073             myarch += ("arm");
5074             break;
5075           case llvm::Triple::x86:
5076             myarch += ("i386");
5077             break;
5078           case llvm::Triple::x86_64:
5079             myarch += ("amd64");
5080             break;
5081           default:
5082             assert(0 && "Unsupported architecture");
5083      }
5084      CmdArgs.push_back(Args.MakeArgString(myarch));
5085   }
5086
5087   if (!Args.hasArg(options::OPT_nostdlib) &&
5088       !Args.hasArg(options::OPT_nostartfiles)) {
5089     if (!Args.hasArg(options::OPT_shared))
5090       CmdArgs.push_back(Args.MakeArgString(
5091                               getToolChain().GetFilePath("crtend.o")));
5092     else
5093       CmdArgs.push_back(Args.MakeArgString(
5094                               getToolChain().GetFilePath("crtendS.o")));
5095   }
5096
5097   const char *Exec =
5098     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5099   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5100 }
5101
5102 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5103                                      const InputInfo &Output,
5104                                      const InputInfoList &Inputs,
5105                                      const ArgList &Args,
5106                                      const char *LinkingOutput) const {
5107   ArgStringList CmdArgs;
5108
5109   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5110   // instruct as in the base system to assemble 32-bit code.
5111   if (getToolChain().getArchName() == "i386")
5112     CmdArgs.push_back("--32");
5113
5114   if (getToolChain().getArchName() == "powerpc")
5115     CmdArgs.push_back("-a32");
5116
5117   // Set byte order explicitly
5118   if (getToolChain().getArchName() == "mips")
5119     CmdArgs.push_back("-EB");
5120   else if (getToolChain().getArchName() == "mipsel")
5121     CmdArgs.push_back("-EL");
5122
5123   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5124                        options::OPT_Xassembler);
5125
5126   CmdArgs.push_back("-o");
5127   CmdArgs.push_back(Output.getFilename());
5128
5129   for (InputInfoList::const_iterator
5130          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5131     const InputInfo &II = *it;
5132     CmdArgs.push_back(II.getFilename());
5133   }
5134
5135   const char *Exec =
5136     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5137   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5138 }
5139
5140 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5141                                  const InputInfo &Output,
5142                                  const InputInfoList &Inputs,
5143                                  const ArgList &Args,
5144                                  const char *LinkingOutput) const {
5145   const Driver &D = getToolChain().getDriver();
5146   ArgStringList CmdArgs;
5147
5148   // Silence warning for "clang -g foo.o -o foo"
5149   Args.ClaimAllArgs(options::OPT_g_Group);
5150   // and "clang -emit-llvm foo.o -o foo"
5151   Args.ClaimAllArgs(options::OPT_emit_llvm);
5152   // and for "clang -w foo.o -o foo". Other warning options are already
5153   // handled somewhere else.
5154   Args.ClaimAllArgs(options::OPT_w);
5155
5156   if (!D.SysRoot.empty())
5157     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5158
5159   if (Args.hasArg(options::OPT_static)) {
5160     CmdArgs.push_back("-Bstatic");
5161   } else {
5162     if (Args.hasArg(options::OPT_rdynamic))
5163       CmdArgs.push_back("-export-dynamic");
5164     CmdArgs.push_back("--eh-frame-hdr");
5165     if (Args.hasArg(options::OPT_shared)) {
5166       CmdArgs.push_back("-Bshareable");
5167     } else {
5168       CmdArgs.push_back("-dynamic-linker");
5169       CmdArgs.push_back("/libexec/ld-elf.so.1");
5170     }
5171     if (getToolChain().getTriple().getOSMajorVersion() >= 9) {
5172       llvm::Triple::ArchType Arch = getToolChain().getArch();
5173       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
5174           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5175         CmdArgs.push_back("--hash-style=both");
5176       }
5177     }
5178     CmdArgs.push_back("--enable-new-dtags");
5179   }
5180
5181   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5182   // instruct ld in the base system to link 32-bit code.
5183   if (getToolChain().getArchName() == "i386") {
5184     CmdArgs.push_back("-m");
5185     CmdArgs.push_back("elf_i386_fbsd");
5186   }
5187
5188   if (getToolChain().getArchName() == "powerpc") {
5189     CmdArgs.push_back("-m");
5190     CmdArgs.push_back("elf32ppc_fbsd");
5191   }
5192
5193   if (Output.isFilename()) {
5194     CmdArgs.push_back("-o");
5195     CmdArgs.push_back(Output.getFilename());
5196   } else {
5197     assert(Output.isNothing() && "Invalid output.");
5198   }
5199
5200   if (!Args.hasArg(options::OPT_nostdlib) &&
5201       !Args.hasArg(options::OPT_nostartfiles)) {
5202     if (!Args.hasArg(options::OPT_shared)) {
5203       if (Args.hasArg(options::OPT_pg))
5204         CmdArgs.push_back(Args.MakeArgString(
5205                                 getToolChain().GetFilePath("gcrt1.o")));
5206       else {
5207         const char *crt = Args.hasArg(options::OPT_pie) ? "Scrt1.o" : "crt1.o";
5208         CmdArgs.push_back(Args.MakeArgString(
5209                                 getToolChain().GetFilePath(crt)));
5210       }
5211       CmdArgs.push_back(Args.MakeArgString(
5212                               getToolChain().GetFilePath("crti.o")));
5213       CmdArgs.push_back(Args.MakeArgString(
5214                               getToolChain().GetFilePath("crtbegin.o")));
5215     } else {
5216       CmdArgs.push_back(Args.MakeArgString(
5217                               getToolChain().GetFilePath("crti.o")));
5218       CmdArgs.push_back(Args.MakeArgString(
5219                               getToolChain().GetFilePath("crtbeginS.o")));
5220     }
5221   }
5222
5223   Args.AddAllArgs(CmdArgs, options::OPT_L);
5224   const ToolChain::path_list Paths = getToolChain().getFilePaths();
5225   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5226        i != e; ++i)
5227     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5228   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5229   Args.AddAllArgs(CmdArgs, options::OPT_e);
5230   Args.AddAllArgs(CmdArgs, options::OPT_s);
5231   Args.AddAllArgs(CmdArgs, options::OPT_t);
5232   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5233   Args.AddAllArgs(CmdArgs, options::OPT_r);
5234
5235   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5236
5237   if (!Args.hasArg(options::OPT_nostdlib) &&
5238       !Args.hasArg(options::OPT_nodefaultlibs)) {
5239     if (D.CCCIsCXX) {
5240       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5241       if (Args.hasArg(options::OPT_pg))
5242         CmdArgs.push_back("-lm_p");
5243       else
5244         CmdArgs.push_back("-lm");
5245     }
5246     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5247     // the default system libraries. Just mimic this for now.
5248     if (Args.hasArg(options::OPT_pg))
5249       CmdArgs.push_back("-lgcc_p");
5250     else
5251       CmdArgs.push_back("-lgcc");
5252     if (Args.hasArg(options::OPT_static)) {
5253       CmdArgs.push_back("-lgcc_eh");
5254     } else if (Args.hasArg(options::OPT_pg)) {
5255       CmdArgs.push_back("-lgcc_eh_p");
5256     } else {
5257       CmdArgs.push_back("--as-needed");
5258       CmdArgs.push_back("-lgcc_s");
5259       CmdArgs.push_back("--no-as-needed");
5260     }
5261
5262     if (Args.hasArg(options::OPT_pthread)) {
5263       if (Args.hasArg(options::OPT_pg))
5264         CmdArgs.push_back("-lpthread_p");
5265       else
5266         CmdArgs.push_back("-lpthread");
5267     }
5268
5269     if (Args.hasArg(options::OPT_pg)) {
5270       if (Args.hasArg(options::OPT_shared))
5271         CmdArgs.push_back("-lc");
5272       else
5273         CmdArgs.push_back("-lc_p");
5274       CmdArgs.push_back("-lgcc_p");
5275     } else {
5276       CmdArgs.push_back("-lc");
5277       CmdArgs.push_back("-lgcc");
5278     }
5279
5280     if (Args.hasArg(options::OPT_static)) {
5281       CmdArgs.push_back("-lgcc_eh");
5282     } else if (Args.hasArg(options::OPT_pg)) {
5283       CmdArgs.push_back("-lgcc_eh_p");
5284     } else {
5285       CmdArgs.push_back("--as-needed");
5286       CmdArgs.push_back("-lgcc_s");
5287       CmdArgs.push_back("--no-as-needed");
5288     }
5289   }
5290
5291   if (!Args.hasArg(options::OPT_nostdlib) &&
5292       !Args.hasArg(options::OPT_nostartfiles)) {
5293     if (!Args.hasArg(options::OPT_shared))
5294       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5295                                                                   "crtend.o")));
5296     else
5297       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5298                                                                  "crtendS.o")));
5299     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5300                                                                     "crtn.o")));
5301   }
5302
5303   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5304
5305   const char *Exec =
5306     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5307   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5308 }
5309
5310 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5311                                      const InputInfo &Output,
5312                                      const InputInfoList &Inputs,
5313                                      const ArgList &Args,
5314                                      const char *LinkingOutput) const {
5315   ArgStringList CmdArgs;
5316
5317   // When building 32-bit code on NetBSD/amd64, we have to explicitly
5318   // instruct as in the base system to assemble 32-bit code.
5319   if (getToolChain().getArch() == llvm::Triple::x86)
5320     CmdArgs.push_back("--32");
5321
5322   // Set byte order explicitly
5323   if (getToolChain().getArchName() == "mips")
5324     CmdArgs.push_back("-EB");
5325   else if (getToolChain().getArchName() == "mipsel")
5326     CmdArgs.push_back("-EL");
5327
5328   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5329                        options::OPT_Xassembler);
5330
5331   CmdArgs.push_back("-o");
5332   CmdArgs.push_back(Output.getFilename());
5333
5334   for (InputInfoList::const_iterator
5335          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5336     const InputInfo &II = *it;
5337     CmdArgs.push_back(II.getFilename());
5338   }
5339
5340   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
5341   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5342 }
5343
5344 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5345                                  const InputInfo &Output,
5346                                  const InputInfoList &Inputs,
5347                                  const ArgList &Args,
5348                                  const char *LinkingOutput) const {
5349   const Driver &D = getToolChain().getDriver();
5350   ArgStringList CmdArgs;
5351
5352   if (!D.SysRoot.empty())
5353     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5354
5355   if (Args.hasArg(options::OPT_static)) {
5356     CmdArgs.push_back("-Bstatic");
5357   } else {
5358     if (Args.hasArg(options::OPT_rdynamic))
5359       CmdArgs.push_back("-export-dynamic");
5360     CmdArgs.push_back("--eh-frame-hdr");
5361     if (Args.hasArg(options::OPT_shared)) {
5362       CmdArgs.push_back("-Bshareable");
5363     } else {
5364       CmdArgs.push_back("-dynamic-linker");
5365       CmdArgs.push_back("/libexec/ld.elf_so");
5366     }
5367   }
5368
5369   // When building 32-bit code on NetBSD/amd64, we have to explicitly
5370   // instruct ld in the base system to link 32-bit code.
5371   if (getToolChain().getArch() == llvm::Triple::x86) {
5372     CmdArgs.push_back("-m");
5373     CmdArgs.push_back("elf_i386");
5374   }
5375
5376   if (Output.isFilename()) {
5377     CmdArgs.push_back("-o");
5378     CmdArgs.push_back(Output.getFilename());
5379   } else {
5380     assert(Output.isNothing() && "Invalid output.");
5381   }
5382
5383   if (!Args.hasArg(options::OPT_nostdlib) &&
5384       !Args.hasArg(options::OPT_nostartfiles)) {
5385     if (!Args.hasArg(options::OPT_shared)) {
5386       CmdArgs.push_back(Args.MakeArgString(
5387                               getToolChain().GetFilePath("crt0.o")));
5388       CmdArgs.push_back(Args.MakeArgString(
5389                               getToolChain().GetFilePath("crti.o")));
5390       CmdArgs.push_back(Args.MakeArgString(
5391                               getToolChain().GetFilePath("crtbegin.o")));
5392     } else {
5393       CmdArgs.push_back(Args.MakeArgString(
5394                               getToolChain().GetFilePath("crti.o")));
5395       CmdArgs.push_back(Args.MakeArgString(
5396                               getToolChain().GetFilePath("crtbeginS.o")));
5397     }
5398   }
5399
5400   Args.AddAllArgs(CmdArgs, options::OPT_L);
5401   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5402   Args.AddAllArgs(CmdArgs, options::OPT_e);
5403   Args.AddAllArgs(CmdArgs, options::OPT_s);
5404   Args.AddAllArgs(CmdArgs, options::OPT_t);
5405   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5406   Args.AddAllArgs(CmdArgs, options::OPT_r);
5407
5408   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5409
5410   if (!Args.hasArg(options::OPT_nostdlib) &&
5411       !Args.hasArg(options::OPT_nodefaultlibs)) {
5412     if (D.CCCIsCXX) {
5413       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5414       CmdArgs.push_back("-lm");
5415     }
5416     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5417     // the default system libraries. Just mimic this for now.
5418     if (Args.hasArg(options::OPT_static)) {
5419       CmdArgs.push_back("-lgcc_eh");
5420     } else {
5421       CmdArgs.push_back("--as-needed");
5422       CmdArgs.push_back("-lgcc_s");
5423       CmdArgs.push_back("--no-as-needed");
5424     }
5425     CmdArgs.push_back("-lgcc");
5426
5427     if (Args.hasArg(options::OPT_pthread))
5428       CmdArgs.push_back("-lpthread");
5429     CmdArgs.push_back("-lc");
5430
5431     CmdArgs.push_back("-lgcc");
5432     if (Args.hasArg(options::OPT_static)) {
5433       CmdArgs.push_back("-lgcc_eh");
5434     } else {
5435       CmdArgs.push_back("--as-needed");
5436       CmdArgs.push_back("-lgcc_s");
5437       CmdArgs.push_back("--no-as-needed");
5438     }
5439   }
5440
5441   if (!Args.hasArg(options::OPT_nostdlib) &&
5442       !Args.hasArg(options::OPT_nostartfiles)) {
5443     if (!Args.hasArg(options::OPT_shared))
5444       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5445                                                                   "crtend.o")));
5446     else
5447       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5448                                                                  "crtendS.o")));
5449     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5450                                                                     "crtn.o")));
5451   }
5452
5453   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5454
5455   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5456   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5457 }
5458
5459 void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5460                                         const InputInfo &Output,
5461                                         const InputInfoList &Inputs,
5462                                         const ArgList &Args,
5463                                         const char *LinkingOutput) const {
5464   ArgStringList CmdArgs;
5465
5466   // Add --32/--64 to make sure we get the format we want.
5467   // This is incomplete
5468   if (getToolChain().getArch() == llvm::Triple::x86) {
5469     CmdArgs.push_back("--32");
5470   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
5471     CmdArgs.push_back("--64");
5472   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
5473     CmdArgs.push_back("-a32");
5474     CmdArgs.push_back("-mppc");
5475     CmdArgs.push_back("-many");
5476   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
5477     CmdArgs.push_back("-a64");
5478     CmdArgs.push_back("-mppc64");
5479     CmdArgs.push_back("-many");
5480   } else if (getToolChain().getArch() == llvm::Triple::arm) {
5481     StringRef MArch = getToolChain().getArchName();
5482     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
5483       CmdArgs.push_back("-mfpu=neon");
5484
5485     StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
5486                                            getToolChain().getTriple());
5487     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
5488
5489     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
5490     Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
5491     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
5492   } else if (getToolChain().getArch() == llvm::Triple::mips ||
5493              getToolChain().getArch() == llvm::Triple::mipsel ||
5494              getToolChain().getArch() == llvm::Triple::mips64 ||
5495              getToolChain().getArch() == llvm::Triple::mips64el) {
5496     StringRef CPUName;
5497     StringRef ABIName;
5498     getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
5499
5500     CmdArgs.push_back("-march");
5501     CmdArgs.push_back(CPUName.data());
5502
5503     // Convert ABI name to the GNU tools acceptable variant.
5504     if (ABIName == "o32")
5505       ABIName = "32";
5506     else if (ABIName == "n64")
5507       ABIName = "64";
5508
5509     CmdArgs.push_back("-mabi");
5510     CmdArgs.push_back(ABIName.data());
5511
5512     if (getToolChain().getArch() == llvm::Triple::mips ||
5513         getToolChain().getArch() == llvm::Triple::mips64)
5514       CmdArgs.push_back("-EB");
5515     else
5516       CmdArgs.push_back("-EL");
5517
5518     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5519                                       options::OPT_fpic, options::OPT_fno_pic,
5520                                       options::OPT_fPIE, options::OPT_fno_PIE,
5521                                       options::OPT_fpie, options::OPT_fno_pie);
5522     if (LastPICArg &&
5523         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5524          LastPICArg->getOption().matches(options::OPT_fpic) ||
5525          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5526          LastPICArg->getOption().matches(options::OPT_fpie))) {
5527       CmdArgs.push_back("-KPIC");
5528     }
5529   }
5530
5531   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5532                        options::OPT_Xassembler);
5533
5534   CmdArgs.push_back("-o");
5535   CmdArgs.push_back(Output.getFilename());
5536
5537   for (InputInfoList::const_iterator
5538          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5539     const InputInfo &II = *it;
5540     CmdArgs.push_back(II.getFilename());
5541   }
5542
5543   const char *Exec =
5544     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5545   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5546 }
5547
5548 static void AddLibgcc(llvm::Triple Triple, const Driver &D,
5549                       ArgStringList &CmdArgs, const ArgList &Args) {
5550   bool isAndroid = Triple.getEnvironment() == llvm::Triple::ANDROIDEABI;
5551   bool StaticLibgcc = isAndroid || Args.hasArg(options::OPT_static) ||
5552     Args.hasArg(options::OPT_static_libgcc);
5553   if (!D.CCCIsCXX)
5554     CmdArgs.push_back("-lgcc");
5555
5556   if (StaticLibgcc) {
5557     if (D.CCCIsCXX)
5558       CmdArgs.push_back("-lgcc");
5559   } else {
5560     if (!D.CCCIsCXX)
5561       CmdArgs.push_back("--as-needed");
5562     CmdArgs.push_back("-lgcc_s");
5563     if (!D.CCCIsCXX)
5564       CmdArgs.push_back("--no-as-needed");
5565   }
5566
5567   if (StaticLibgcc && !isAndroid)
5568     CmdArgs.push_back("-lgcc_eh");
5569   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
5570     CmdArgs.push_back("-lgcc");
5571 }
5572
5573 void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
5574                                     const InputInfo &Output,
5575                                     const InputInfoList &Inputs,
5576                                     const ArgList &Args,
5577                                     const char *LinkingOutput) const {
5578   const toolchains::Linux& ToolChain =
5579     static_cast<const toolchains::Linux&>(getToolChain());
5580   const Driver &D = ToolChain.getDriver();
5581   const bool isAndroid = ToolChain.getTriple().getEnvironment() ==
5582     llvm::Triple::ANDROIDEABI;
5583
5584   ArgStringList CmdArgs;
5585
5586   // Silence warning for "clang -g foo.o -o foo"
5587   Args.ClaimAllArgs(options::OPT_g_Group);
5588   // and "clang -emit-llvm foo.o -o foo"
5589   Args.ClaimAllArgs(options::OPT_emit_llvm);
5590   // and for "clang -w foo.o -o foo". Other warning options are already
5591   // handled somewhere else.
5592   Args.ClaimAllArgs(options::OPT_w);
5593
5594   if (!D.SysRoot.empty())
5595     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5596
5597   if (Args.hasArg(options::OPT_pie))
5598     CmdArgs.push_back("-pie");
5599
5600   if (Args.hasArg(options::OPT_rdynamic))
5601     CmdArgs.push_back("-export-dynamic");
5602
5603   if (Args.hasArg(options::OPT_s))
5604     CmdArgs.push_back("-s");
5605
5606   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
5607          e = ToolChain.ExtraOpts.end();
5608        i != e; ++i)
5609     CmdArgs.push_back(i->c_str());
5610
5611   if (!Args.hasArg(options::OPT_static)) {
5612     CmdArgs.push_back("--eh-frame-hdr");
5613   }
5614
5615   CmdArgs.push_back("-m");
5616   if (ToolChain.getArch() == llvm::Triple::x86)
5617     CmdArgs.push_back("elf_i386");
5618   else if (ToolChain.getArch() == llvm::Triple::arm
5619            ||  ToolChain.getArch() == llvm::Triple::thumb)
5620     CmdArgs.push_back("armelf_linux_eabi");
5621   else if (ToolChain.getArch() == llvm::Triple::ppc)
5622     CmdArgs.push_back("elf32ppclinux");
5623   else if (ToolChain.getArch() == llvm::Triple::ppc64)
5624     CmdArgs.push_back("elf64ppc");
5625   else if (ToolChain.getArch() == llvm::Triple::mips)
5626     CmdArgs.push_back("elf32btsmip");
5627   else if (ToolChain.getArch() == llvm::Triple::mipsel)
5628     CmdArgs.push_back("elf32ltsmip");
5629   else if (ToolChain.getArch() == llvm::Triple::mips64)
5630     CmdArgs.push_back("elf64btsmip");
5631   else if (ToolChain.getArch() == llvm::Triple::mips64el)
5632     CmdArgs.push_back("elf64ltsmip");
5633   else
5634     CmdArgs.push_back("elf_x86_64");
5635
5636   if (Args.hasArg(options::OPT_static)) {
5637     if (ToolChain.getArch() == llvm::Triple::arm
5638         || ToolChain.getArch() == llvm::Triple::thumb)
5639       CmdArgs.push_back("-Bstatic");
5640     else
5641       CmdArgs.push_back("-static");
5642   } else if (Args.hasArg(options::OPT_shared)) {
5643     CmdArgs.push_back("-shared");
5644     if ((ToolChain.getArch() == llvm::Triple::arm
5645          || ToolChain.getArch() == llvm::Triple::thumb) && isAndroid) {
5646       CmdArgs.push_back("-Bsymbolic");
5647     }
5648   }
5649
5650   if (ToolChain.getArch() == llvm::Triple::arm ||
5651       ToolChain.getArch() == llvm::Triple::thumb ||
5652       (!Args.hasArg(options::OPT_static) &&
5653        !Args.hasArg(options::OPT_shared))) {
5654     CmdArgs.push_back("-dynamic-linker");
5655     if (isAndroid)
5656       CmdArgs.push_back("/system/bin/linker");
5657     else if (ToolChain.getArch() == llvm::Triple::x86)
5658       CmdArgs.push_back("/lib/ld-linux.so.2");
5659     else if (ToolChain.getArch() == llvm::Triple::arm ||
5660              ToolChain.getArch() == llvm::Triple::thumb) {
5661       if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
5662         CmdArgs.push_back("/lib/ld-linux-armhf.so.3");
5663       else
5664         CmdArgs.push_back("/lib/ld-linux.so.3");
5665     }
5666     else if (ToolChain.getArch() == llvm::Triple::mips ||
5667              ToolChain.getArch() == llvm::Triple::mipsel)
5668       CmdArgs.push_back("/lib/ld.so.1");
5669     else if (ToolChain.getArch() == llvm::Triple::mips64 ||
5670              ToolChain.getArch() == llvm::Triple::mips64el)
5671       CmdArgs.push_back("/lib64/ld.so.1");
5672     else if (ToolChain.getArch() == llvm::Triple::ppc)
5673       CmdArgs.push_back("/lib/ld.so.1");
5674     else if (ToolChain.getArch() == llvm::Triple::ppc64)
5675       CmdArgs.push_back("/lib64/ld64.so.1");
5676     else
5677       CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
5678   }
5679
5680   CmdArgs.push_back("-o");
5681   CmdArgs.push_back(Output.getFilename());
5682
5683   if (!Args.hasArg(options::OPT_nostdlib) &&
5684       !Args.hasArg(options::OPT_nostartfiles)) {
5685     if (!isAndroid) {
5686       const char *crt1 = NULL;
5687       if (!Args.hasArg(options::OPT_shared)){
5688         if (Args.hasArg(options::OPT_pie))
5689           crt1 = "Scrt1.o";
5690         else
5691           crt1 = "crt1.o";
5692       }
5693       if (crt1)
5694         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5695
5696       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5697     }
5698
5699     const char *crtbegin;
5700     if (Args.hasArg(options::OPT_static))
5701       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
5702     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5703       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
5704     else
5705       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
5706     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5707   }
5708
5709   Args.AddAllArgs(CmdArgs, options::OPT_L);
5710
5711   const ToolChain::path_list Paths = ToolChain.getFilePaths();
5712
5713   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5714        i != e; ++i)
5715     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5716
5717   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
5718   // as gold requires -plugin to come before any -plugin-opt that -Wl might
5719   // forward.
5720   if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
5721     CmdArgs.push_back("-plugin");
5722     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
5723     CmdArgs.push_back(Args.MakeArgString(Plugin));
5724   }
5725
5726   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
5727     CmdArgs.push_back("--no-demangle");
5728
5729   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5730
5731   if (D.CCCIsCXX &&
5732       !Args.hasArg(options::OPT_nostdlib) &&
5733       !Args.hasArg(options::OPT_nodefaultlibs)) {
5734     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
5735       !Args.hasArg(options::OPT_static);
5736     if (OnlyLibstdcxxStatic)
5737       CmdArgs.push_back("-Bstatic");
5738     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5739     if (OnlyLibstdcxxStatic)
5740       CmdArgs.push_back("-Bdynamic");
5741     CmdArgs.push_back("-lm");
5742   }
5743
5744   // Call this before we add the C run-time.
5745   addAsanRTLinux(getToolChain(), Args, CmdArgs);
5746   addTsanRTLinux(getToolChain(), Args, CmdArgs);
5747
5748   if (!Args.hasArg(options::OPT_nostdlib)) {
5749     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
5750       if (Args.hasArg(options::OPT_static))
5751         CmdArgs.push_back("--start-group");
5752
5753       AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
5754
5755       if (Args.hasArg(options::OPT_pthread) ||
5756           Args.hasArg(options::OPT_pthreads))
5757         CmdArgs.push_back("-lpthread");
5758
5759       CmdArgs.push_back("-lc");
5760
5761       if (Args.hasArg(options::OPT_static))
5762         CmdArgs.push_back("--end-group");
5763       else
5764         AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
5765     }
5766
5767     if (!Args.hasArg(options::OPT_nostartfiles)) {
5768       const char *crtend;
5769       if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5770         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
5771       else
5772         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
5773
5774       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
5775       if (!isAndroid)
5776         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
5777     }
5778   }
5779
5780   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5781
5782   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
5783 }
5784
5785 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5786                                    const InputInfo &Output,
5787                                    const InputInfoList &Inputs,
5788                                    const ArgList &Args,
5789                                    const char *LinkingOutput) const {
5790   ArgStringList CmdArgs;
5791
5792   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5793                        options::OPT_Xassembler);
5794
5795   CmdArgs.push_back("-o");
5796   CmdArgs.push_back(Output.getFilename());
5797
5798   for (InputInfoList::const_iterator
5799          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5800     const InputInfo &II = *it;
5801     CmdArgs.push_back(II.getFilename());
5802   }
5803
5804   const char *Exec =
5805     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5806   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5807 }
5808
5809 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
5810                                const InputInfo &Output,
5811                                const InputInfoList &Inputs,
5812                                const ArgList &Args,
5813                                const char *LinkingOutput) const {
5814   const Driver &D = getToolChain().getDriver();
5815   ArgStringList CmdArgs;
5816
5817   if (Output.isFilename()) {
5818     CmdArgs.push_back("-o");
5819     CmdArgs.push_back(Output.getFilename());
5820   } else {
5821     assert(Output.isNothing() && "Invalid output.");
5822   }
5823
5824   if (!Args.hasArg(options::OPT_nostdlib) &&
5825       !Args.hasArg(options::OPT_nostartfiles)) {
5826       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
5827       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
5828       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
5829       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
5830   }
5831
5832   Args.AddAllArgs(CmdArgs, options::OPT_L);
5833   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5834   Args.AddAllArgs(CmdArgs, options::OPT_e);
5835
5836   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5837
5838   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5839
5840   if (!Args.hasArg(options::OPT_nostdlib) &&
5841       !Args.hasArg(options::OPT_nodefaultlibs)) {
5842     if (D.CCCIsCXX) {
5843       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5844       CmdArgs.push_back("-lm");
5845     }
5846   }
5847
5848   if (!Args.hasArg(options::OPT_nostdlib) &&
5849       !Args.hasArg(options::OPT_nostartfiles)) {
5850     if (Args.hasArg(options::OPT_pthread))
5851       CmdArgs.push_back("-lpthread");
5852     CmdArgs.push_back("-lc");
5853     CmdArgs.push_back("-lCompilerRT-Generic");
5854     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
5855     CmdArgs.push_back(
5856          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
5857   }
5858
5859   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5860   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5861 }
5862
5863 /// DragonFly Tools
5864
5865 // For now, DragonFly Assemble does just about the same as for
5866 // FreeBSD, but this may change soon.
5867 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5868                                        const InputInfo &Output,
5869                                        const InputInfoList &Inputs,
5870                                        const ArgList &Args,
5871                                        const char *LinkingOutput) const {
5872   ArgStringList CmdArgs;
5873
5874   // When building 32-bit code on DragonFly/pc64, we have to explicitly
5875   // instruct as in the base system to assemble 32-bit code.
5876   if (getToolChain().getArchName() == "i386")
5877     CmdArgs.push_back("--32");
5878
5879   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5880                        options::OPT_Xassembler);
5881
5882   CmdArgs.push_back("-o");
5883   CmdArgs.push_back(Output.getFilename());
5884
5885   for (InputInfoList::const_iterator
5886          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5887     const InputInfo &II = *it;
5888     CmdArgs.push_back(II.getFilename());
5889   }
5890
5891   const char *Exec =
5892     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5893   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5894 }
5895
5896 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
5897                                    const InputInfo &Output,
5898                                    const InputInfoList &Inputs,
5899                                    const ArgList &Args,
5900                                    const char *LinkingOutput) const {
5901   const Driver &D = getToolChain().getDriver();
5902   ArgStringList CmdArgs;
5903
5904   if (!D.SysRoot.empty())
5905     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5906
5907   if (Args.hasArg(options::OPT_static)) {
5908     CmdArgs.push_back("-Bstatic");
5909   } else {
5910     if (Args.hasArg(options::OPT_shared))
5911       CmdArgs.push_back("-Bshareable");
5912     else {
5913       CmdArgs.push_back("-dynamic-linker");
5914       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
5915     }
5916   }
5917
5918   // When building 32-bit code on DragonFly/pc64, we have to explicitly
5919   // instruct ld in the base system to link 32-bit code.
5920   if (getToolChain().getArchName() == "i386") {
5921     CmdArgs.push_back("-m");
5922     CmdArgs.push_back("elf_i386");
5923   }
5924
5925   if (Output.isFilename()) {
5926     CmdArgs.push_back("-o");
5927     CmdArgs.push_back(Output.getFilename());
5928   } else {
5929     assert(Output.isNothing() && "Invalid output.");
5930   }
5931
5932   if (!Args.hasArg(options::OPT_nostdlib) &&
5933       !Args.hasArg(options::OPT_nostartfiles)) {
5934     if (!Args.hasArg(options::OPT_shared)) {
5935       CmdArgs.push_back(
5936             Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
5937       CmdArgs.push_back(
5938             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
5939       CmdArgs.push_back(
5940             Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
5941     } else {
5942       CmdArgs.push_back(
5943             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
5944       CmdArgs.push_back(
5945             Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
5946     }
5947   }
5948
5949   Args.AddAllArgs(CmdArgs, options::OPT_L);
5950   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5951   Args.AddAllArgs(CmdArgs, options::OPT_e);
5952
5953   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5954
5955   if (!Args.hasArg(options::OPT_nostdlib) &&
5956       !Args.hasArg(options::OPT_nodefaultlibs)) {
5957     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
5958     //         rpaths
5959     CmdArgs.push_back("-L/usr/lib/gcc41");
5960
5961     if (!Args.hasArg(options::OPT_static)) {
5962       CmdArgs.push_back("-rpath");
5963       CmdArgs.push_back("/usr/lib/gcc41");
5964
5965       CmdArgs.push_back("-rpath-link");
5966       CmdArgs.push_back("/usr/lib/gcc41");
5967
5968       CmdArgs.push_back("-rpath");
5969       CmdArgs.push_back("/usr/lib");
5970
5971       CmdArgs.push_back("-rpath-link");
5972       CmdArgs.push_back("/usr/lib");
5973     }
5974
5975     if (D.CCCIsCXX) {
5976       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5977       CmdArgs.push_back("-lm");
5978     }
5979
5980     if (Args.hasArg(options::OPT_shared)) {
5981       CmdArgs.push_back("-lgcc_pic");
5982     } else {
5983       CmdArgs.push_back("-lgcc");
5984     }
5985
5986
5987     if (Args.hasArg(options::OPT_pthread))
5988       CmdArgs.push_back("-lpthread");
5989
5990     if (!Args.hasArg(options::OPT_nolibc)) {
5991       CmdArgs.push_back("-lc");
5992     }
5993
5994     if (Args.hasArg(options::OPT_shared)) {
5995       CmdArgs.push_back("-lgcc_pic");
5996     } else {
5997       CmdArgs.push_back("-lgcc");
5998     }
5999   }
6000
6001   if (!Args.hasArg(options::OPT_nostdlib) &&
6002       !Args.hasArg(options::OPT_nostartfiles)) {
6003     if (!Args.hasArg(options::OPT_shared))
6004       CmdArgs.push_back(Args.MakeArgString(
6005                               getToolChain().GetFilePath("crtend.o")));
6006     else
6007       CmdArgs.push_back(Args.MakeArgString(
6008                               getToolChain().GetFilePath("crtendS.o")));
6009     CmdArgs.push_back(Args.MakeArgString(
6010                               getToolChain().GetFilePath("crtn.o")));
6011   }
6012
6013   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6014
6015   const char *Exec =
6016     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6017   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6018 }
6019
6020 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
6021                                       const InputInfo &Output,
6022                                       const InputInfoList &Inputs,
6023                                       const ArgList &Args,
6024                                       const char *LinkingOutput) const {
6025   ArgStringList CmdArgs;
6026
6027   if (Output.isFilename()) {
6028     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
6029                                          Output.getFilename()));
6030   } else {
6031     assert(Output.isNothing() && "Invalid output.");
6032   }
6033
6034   if (!Args.hasArg(options::OPT_nostdlib) &&
6035     !Args.hasArg(options::OPT_nostartfiles)) {
6036     CmdArgs.push_back("-defaultlib:libcmt");
6037   }
6038
6039   CmdArgs.push_back("-nologo");
6040
6041   Args.AddAllArgValues(CmdArgs, options::OPT_l);
6042
6043   // Add filenames immediately.
6044   for (InputInfoList::const_iterator
6045        it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6046     if (it->isFilename())
6047       CmdArgs.push_back(it->getFilename());
6048   }
6049
6050   const char *Exec =
6051     Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
6052   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6053 }