]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
MFC r265925:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Driver / Tools.cpp
1 //===--- Tools.cpp - Tools Implementations --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Tools.h"
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/ObjCRuntime.h"
14 #include "clang/Basic/Version.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/ToolChain.h"
23 #include "clang/Driver/Util.h"
24 #include "clang/Sema/SemaDiagnostic.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Option/Arg.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/Option.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Program.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <sys/stat.h>
41
42 using namespace clang::driver;
43 using namespace clang::driver::tools;
44 using namespace clang;
45 using namespace llvm::opt;
46
47 /// CheckPreprocessingOptions - Perform some validation of preprocessing
48 /// arguments that is shared with gcc.
49 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
50   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
51     if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP())
52       D.Diag(diag::err_drv_argument_only_allowed_with)
53         << A->getAsString(Args) << "-E";
54 }
55
56 /// CheckCodeGenerationOptions - Perform some validation of code generation
57 /// arguments that is shared with gcc.
58 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
59   // In gcc, only ARM checks this, but it seems reasonable to check universally.
60   if (Args.hasArg(options::OPT_static))
61     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
62                                        options::OPT_mdynamic_no_pic))
63       D.Diag(diag::err_drv_argument_not_allowed_with)
64         << A->getAsString(Args) << "-static";
65 }
66
67 // Quote target names for inclusion in GNU Make dependency files.
68 // Only the characters '$', '#', ' ', '\t' are quoted.
69 static void QuoteTarget(StringRef Target,
70                         SmallVectorImpl<char> &Res) {
71   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
72     switch (Target[i]) {
73     case ' ':
74     case '\t':
75       // Escape the preceding backslashes
76       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
77         Res.push_back('\\');
78
79       // Escape the space/tab
80       Res.push_back('\\');
81       break;
82     case '$':
83       Res.push_back('$');
84       break;
85     case '#':
86       Res.push_back('\\');
87       break;
88     default:
89       break;
90     }
91
92     Res.push_back(Target[i]);
93   }
94 }
95
96 static void addDirectoryList(const ArgList &Args,
97                              ArgStringList &CmdArgs,
98                              const char *ArgName,
99                              const char *EnvVar) {
100   const char *DirList = ::getenv(EnvVar);
101   bool CombinedArg = false;
102
103   if (!DirList)
104     return; // Nothing to do.
105
106   StringRef Name(ArgName);
107   if (Name.equals("-I") || Name.equals("-L"))
108     CombinedArg = true;
109
110   StringRef Dirs(DirList);
111   if (Dirs.empty()) // Empty string should not add '.'.
112     return;
113
114   StringRef::size_type Delim;
115   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
116     if (Delim == 0) { // Leading colon.
117       if (CombinedArg) {
118         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
119       } else {
120         CmdArgs.push_back(ArgName);
121         CmdArgs.push_back(".");
122       }
123     } else {
124       if (CombinedArg) {
125         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
126       } else {
127         CmdArgs.push_back(ArgName);
128         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
129       }
130     }
131     Dirs = Dirs.substr(Delim + 1);
132   }
133
134   if (Dirs.empty()) { // Trailing colon.
135     if (CombinedArg) {
136       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
137     } else {
138       CmdArgs.push_back(ArgName);
139       CmdArgs.push_back(".");
140     }
141   } else { // Add the last path.
142     if (CombinedArg) {
143       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
144     } else {
145       CmdArgs.push_back(ArgName);
146       CmdArgs.push_back(Args.MakeArgString(Dirs));
147     }
148   }
149 }
150
151 static void AddLinkerInputs(const ToolChain &TC,
152                             const InputInfoList &Inputs, const ArgList &Args,
153                             ArgStringList &CmdArgs) {
154   const Driver &D = TC.getDriver();
155
156   // Add extra linker input arguments which are not treated as inputs
157   // (constructed via -Xarch_).
158   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
159
160   for (InputInfoList::const_iterator
161          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
162     const InputInfo &II = *it;
163
164     if (!TC.HasNativeLLVMSupport()) {
165       // Don't try to pass LLVM inputs unless we have native support.
166       if (II.getType() == types::TY_LLVM_IR ||
167           II.getType() == types::TY_LTO_IR ||
168           II.getType() == types::TY_LLVM_BC ||
169           II.getType() == types::TY_LTO_BC)
170         D.Diag(diag::err_drv_no_linker_llvm_support)
171           << TC.getTripleString();
172     }
173
174     // Add filenames immediately.
175     if (II.isFilename()) {
176       CmdArgs.push_back(II.getFilename());
177       continue;
178     }
179
180     // Otherwise, this is a linker input argument.
181     const Arg &A = II.getInputArg();
182
183     // Handle reserved library options.
184     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
185       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
186     } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
187       TC.AddCCKextLibArgs(Args, CmdArgs);
188     } else
189       A.renderAsInput(Args, CmdArgs);
190   }
191
192   // LIBRARY_PATH - included following the user specified library paths.
193   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
194 }
195
196 /// \brief Determine whether Objective-C automated reference counting is
197 /// enabled.
198 static bool isObjCAutoRefCount(const ArgList &Args) {
199   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
200 }
201
202 /// \brief Determine whether we are linking the ObjC runtime.
203 static bool isObjCRuntimeLinked(const ArgList &Args) {
204   if (isObjCAutoRefCount(Args)) {
205     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
206     return true;
207   }
208   return Args.hasArg(options::OPT_fobjc_link_runtime);
209 }
210
211 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
212                          ArgStringList &CmdArgs,
213                          llvm::Triple Triple) {
214   if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
215         Args.hasArg(options::OPT_fprofile_generate) ||
216         Args.hasArg(options::OPT_fcreate_profile) ||
217         Args.hasArg(options::OPT_coverage)))
218     return;
219
220   // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lgcov to
221   // the link line. We cannot do the same thing because unlike gcov there is a
222   // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but that is
223   // not supported by old linkers.
224   std::string ProfileRT =
225     std::string(TC.getDriver().Dir) + "/../lib/libprofile_rt.a";
226
227   CmdArgs.push_back(Args.MakeArgString(ProfileRT));
228 }
229
230 static bool forwardToGCC(const Option &O) {
231   // Don't forward inputs from the original command line.  They are added from
232   // InputInfoList.
233   return O.getKind() != Option::InputClass &&
234          !O.hasFlag(options::DriverOption) &&
235          !O.hasFlag(options::LinkerInput);
236 }
237
238 void Clang::AddPreprocessingOptions(Compilation &C,
239                                     const JobAction &JA,
240                                     const Driver &D,
241                                     const ArgList &Args,
242                                     ArgStringList &CmdArgs,
243                                     const InputInfo &Output,
244                                     const InputInfoList &Inputs) const {
245   Arg *A;
246
247   CheckPreprocessingOptions(D, Args);
248
249   Args.AddLastArg(CmdArgs, options::OPT_C);
250   Args.AddLastArg(CmdArgs, options::OPT_CC);
251
252   // Handle dependency file generation.
253   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
254       (A = Args.getLastArg(options::OPT_MD)) ||
255       (A = Args.getLastArg(options::OPT_MMD))) {
256     // Determine the output location.
257     const char *DepFile;
258     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
259       DepFile = MF->getValue();
260       C.addFailureResultFile(DepFile, &JA);
261     } else if (Output.getType() == types::TY_Dependencies) {
262       DepFile = Output.getFilename();
263     } else if (A->getOption().matches(options::OPT_M) ||
264                A->getOption().matches(options::OPT_MM)) {
265       DepFile = "-";
266     } else {
267       DepFile = getDependencyFileName(Args, Inputs);
268       C.addFailureResultFile(DepFile, &JA);
269     }
270     CmdArgs.push_back("-dependency-file");
271     CmdArgs.push_back(DepFile);
272
273     // Add a default target if one wasn't specified.
274     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
275       const char *DepTarget;
276
277       // If user provided -o, that is the dependency target, except
278       // when we are only generating a dependency file.
279       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
280       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
281         DepTarget = OutputOpt->getValue();
282       } else {
283         // Otherwise derive from the base input.
284         //
285         // FIXME: This should use the computed output file location.
286         SmallString<128> P(Inputs[0].getBaseInput());
287         llvm::sys::path::replace_extension(P, "o");
288         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
289       }
290
291       CmdArgs.push_back("-MT");
292       SmallString<128> Quoted;
293       QuoteTarget(DepTarget, Quoted);
294       CmdArgs.push_back(Args.MakeArgString(Quoted));
295     }
296
297     if (A->getOption().matches(options::OPT_M) ||
298         A->getOption().matches(options::OPT_MD))
299       CmdArgs.push_back("-sys-header-deps");
300   }
301
302   if (Args.hasArg(options::OPT_MG)) {
303     if (!A || A->getOption().matches(options::OPT_MD) ||
304               A->getOption().matches(options::OPT_MMD))
305       D.Diag(diag::err_drv_mg_requires_m_or_mm);
306     CmdArgs.push_back("-MG");
307   }
308
309   Args.AddLastArg(CmdArgs, options::OPT_MP);
310
311   // Convert all -MQ <target> args to -MT <quoted target>
312   for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
313                                              options::OPT_MQ),
314          ie = Args.filtered_end(); it != ie; ++it) {
315     const Arg *A = *it;
316     A->claim();
317
318     if (A->getOption().matches(options::OPT_MQ)) {
319       CmdArgs.push_back("-MT");
320       SmallString<128> Quoted;
321       QuoteTarget(A->getValue(), Quoted);
322       CmdArgs.push_back(Args.MakeArgString(Quoted));
323
324     // -MT flag - no change
325     } else {
326       A->render(Args, CmdArgs);
327     }
328   }
329
330   // Add -i* options, and automatically translate to
331   // -include-pch/-include-pth for transparent PCH support. It's
332   // wonky, but we include looking for .gch so we can support seamless
333   // replacement into a build system already set up to be generating
334   // .gch files.
335   bool RenderedImplicitInclude = false;
336   for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
337          ie = Args.filtered_end(); it != ie; ++it) {
338     const Arg *A = it;
339
340     if (A->getOption().matches(options::OPT_include)) {
341       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
342       RenderedImplicitInclude = true;
343
344       // Use PCH if the user requested it.
345       bool UsePCH = D.CCCUsePCH;
346
347       bool FoundPTH = false;
348       bool FoundPCH = false;
349       SmallString<128> P(A->getValue());
350       // We want the files to have a name like foo.h.pch. Add a dummy extension
351       // so that replace_extension does the right thing.
352       P += ".dummy";
353       if (UsePCH) {
354         llvm::sys::path::replace_extension(P, "pch");
355         if (llvm::sys::fs::exists(P.str()))
356           FoundPCH = true;
357       }
358
359       if (!FoundPCH) {
360         llvm::sys::path::replace_extension(P, "pth");
361         if (llvm::sys::fs::exists(P.str()))
362           FoundPTH = true;
363       }
364
365       if (!FoundPCH && !FoundPTH) {
366         llvm::sys::path::replace_extension(P, "gch");
367         if (llvm::sys::fs::exists(P.str())) {
368           FoundPCH = UsePCH;
369           FoundPTH = !UsePCH;
370         }
371       }
372
373       if (FoundPCH || FoundPTH) {
374         if (IsFirstImplicitInclude) {
375           A->claim();
376           if (UsePCH)
377             CmdArgs.push_back("-include-pch");
378           else
379             CmdArgs.push_back("-include-pth");
380           CmdArgs.push_back(Args.MakeArgString(P.str()));
381           continue;
382         } else {
383           // Ignore the PCH if not first on command line and emit warning.
384           D.Diag(diag::warn_drv_pch_not_first_include)
385               << P.str() << A->getAsString(Args);
386         }
387       }
388     }
389
390     // Not translated, render as usual.
391     A->claim();
392     A->render(Args, CmdArgs);
393   }
394
395   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
396   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
397                   options::OPT_index_header_map);
398
399   // Add -Wp, and -Xassembler if using the preprocessor.
400
401   // FIXME: There is a very unfortunate problem here, some troubled
402   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
403   // really support that we would have to parse and then translate
404   // those options. :(
405   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
406                        options::OPT_Xpreprocessor);
407
408   // -I- is a deprecated GCC feature, reject it.
409   if (Arg *A = Args.getLastArg(options::OPT_I_))
410     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
411
412   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
413   // -isysroot to the CC1 invocation.
414   StringRef sysroot = C.getSysRoot();
415   if (sysroot != "") {
416     if (!Args.hasArg(options::OPT_isysroot)) {
417       CmdArgs.push_back("-isysroot");
418       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
419     }
420   }
421
422   // Parse additional include paths from environment variables.
423   // FIXME: We should probably sink the logic for handling these from the
424   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
425   // CPATH - included following the user specified includes (but prior to
426   // builtin and standard includes).
427   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
428   // C_INCLUDE_PATH - system includes enabled when compiling C.
429   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
430   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
431   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
432   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
433   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
434   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
435   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
436
437   // Add C++ include arguments, if needed.
438   if (types::isCXX(Inputs[0].getType()))
439     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
440
441   // Add system include arguments.
442   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
443 }
444
445 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
446 /// CPU.
447 //
448 // FIXME: This is redundant with -mcpu, why does LLVM use this.
449 // FIXME: tblgen this, or kill it!
450 static const char *getLLVMArchSuffixForARM(StringRef CPU) {
451   return llvm::StringSwitch<const char *>(CPU)
452     .Case("strongarm", "v4")
453     .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
454     .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
455     .Cases("arm920", "arm920t", "arm922t", "v4t")
456     .Cases("arm940t", "ep9312","v4t")
457     .Cases("arm10tdmi",  "arm1020t", "v5")
458     .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
459     .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
460     .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
461     .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
462     .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
463     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
464     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
465     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "v7")
466     .Cases("cortex-r4", "cortex-r5", "v7r")
467     .Case("cortex-m0", "v6m")
468     .Case("cortex-m3", "v7m")
469     .Case("cortex-m4", "v7em")
470     .Case("cortex-a9-mp", "v7f")
471     .Case("swift", "v7s")
472     .Cases("cortex-a53", "cortex-a57", "v8")
473     .Default("");
474 }
475
476 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
477 //
478 // FIXME: tblgen this.
479 static std::string getARMTargetCPU(const ArgList &Args,
480                                    const llvm::Triple &Triple) {
481   // FIXME: Warn on inconsistent use of -mcpu and -march.
482
483   // If we have -mcpu=, use that.
484   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
485     StringRef MCPU = A->getValue();
486     // Handle -mcpu=native.
487     if (MCPU == "native")
488       return llvm::sys::getHostCPUName();
489     else
490       return MCPU;
491   }
492
493   StringRef MArch;
494   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
495     // Otherwise, if we have -march= choose the base CPU for that arch.
496     MArch = A->getValue();
497   } else {
498     // Otherwise, use the Arch from the triple.
499     MArch = Triple.getArchName();
500   }
501
502   if (Triple.getOS() == llvm::Triple::NetBSD) {
503     if (MArch == "armv6")
504       return "arm1176jzf-s";
505   }
506
507   // Handle -march=native.
508   std::string NativeMArch;
509   if (MArch == "native") {
510     std::string CPU = llvm::sys::getHostCPUName();
511     if (CPU != "generic") {
512       // Translate the native cpu into the architecture. The switch below will
513       // then chose the minimum cpu for that arch.
514       NativeMArch = std::string("arm") + getLLVMArchSuffixForARM(CPU);
515       MArch = NativeMArch;
516     }
517   }
518
519   return llvm::StringSwitch<const char *>(MArch)
520     .Cases("armv2", "armv2a","arm2")
521     .Case("armv3", "arm6")
522     .Case("armv3m", "arm7m")
523     .Case("armv4", "strongarm")
524     .Case("armv4t", "arm7tdmi")
525     .Cases("armv5", "armv5t", "arm10tdmi")
526     .Cases("armv5e", "armv5te", "arm1022e")
527     .Case("armv5tej", "arm926ej-s")
528     .Cases("armv6", "armv6k", "arm1136jf-s")
529     .Case("armv6j", "arm1136j-s")
530     .Cases("armv6z", "armv6zk", "arm1176jzf-s")
531     .Case("armv6t2", "arm1156t2-s")
532     .Cases("armv6m", "armv6-m", "cortex-m0")
533     .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
534     .Cases("armv7em", "armv7e-m", "cortex-m4")
535     .Cases("armv7f", "armv7-f", "cortex-a9-mp")
536     .Cases("armv7s", "armv7-s", "swift")
537     .Cases("armv7r", "armv7-r", "cortex-r4")
538     .Cases("armv7m", "armv7-m", "cortex-m3")
539     .Cases("armv8", "armv8a", "armv8-a", "cortex-a53")
540     .Case("ep9312", "ep9312")
541     .Case("iwmmxt", "iwmmxt")
542     .Case("xscale", "xscale")
543     // If all else failed, return the most base CPU with thumb interworking
544     // supported by LLVM.
545     .Default("arm7tdmi");
546 }
547
548 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are targeting.
549 //
550 // FIXME: tblgen this.
551 static std::string getAArch64TargetCPU(const ArgList &Args,
552                                        const llvm::Triple &Triple) {
553   // FIXME: Warn on inconsistent use of -mcpu and -march.
554
555   // If we have -mcpu=, use that.
556   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
557     StringRef MCPU = A->getValue();
558     // Handle -mcpu=native.
559     if (MCPU == "native")
560       return llvm::sys::getHostCPUName();
561     else
562       return MCPU;
563   }
564
565   return "generic";
566 }
567
568 // FIXME: Move to target hook.
569 static bool isSignedCharDefault(const llvm::Triple &Triple) {
570   switch (Triple.getArch()) {
571   default:
572     return true;
573
574   case llvm::Triple::aarch64:
575   case llvm::Triple::arm:
576   case llvm::Triple::ppc:
577   case llvm::Triple::ppc64:
578     if (Triple.isOSDarwin())
579       return true;
580     return false;
581
582   case llvm::Triple::ppc64le:
583   case llvm::Triple::systemz:
584   case llvm::Triple::xcore:
585     return false;
586   }
587 }
588
589 static bool isNoCommonDefault(const llvm::Triple &Triple) {
590   switch (Triple.getArch()) {
591   default:
592     return false;
593
594   case llvm::Triple::xcore:
595     return true;
596   }
597 }
598
599 // Handle -mfpu=.
600 //
601 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
602 // frontend target.
603 static void getAArch64FPUFeatures(const Driver &D, const Arg *A,
604                                   const ArgList &Args,
605                                   std::vector<const char *> &Features) {
606   StringRef FPU = A->getValue();
607   if (FPU == "fp-armv8") {
608     Features.push_back("+fp-armv8");
609   } else if (FPU == "neon-fp-armv8") {
610     Features.push_back("+fp-armv8");
611     Features.push_back("+neon");
612   } else if (FPU == "crypto-neon-fp-armv8") {
613     Features.push_back("+fp-armv8");
614     Features.push_back("+neon");
615     Features.push_back("+crypto");
616   } else if (FPU == "neon") {
617     Features.push_back("+neon");
618   } else if (FPU == "none") {
619     Features.push_back("-fp-armv8");
620     Features.push_back("-crypto");
621     Features.push_back("-neon");
622   } else
623     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
624 }
625
626 // Handle -mhwdiv=.
627 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
628                               const ArgList &Args,
629                               std::vector<const char *> &Features) {
630   StringRef HWDiv = A->getValue();
631   if (HWDiv == "arm") {
632     Features.push_back("+hwdiv-arm");
633     Features.push_back("-hwdiv");
634   } else if (HWDiv == "thumb") {
635     Features.push_back("-hwdiv-arm");
636     Features.push_back("+hwdiv");
637   } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
638     Features.push_back("+hwdiv-arm");
639     Features.push_back("+hwdiv");
640   } else if (HWDiv == "none") {
641     Features.push_back("-hwdiv-arm");
642     Features.push_back("-hwdiv");
643   } else
644     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
645 }
646  
647 // Handle -mfpu=.
648 //
649 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
650 // frontend target.
651 static void getARMFPUFeatures(const Driver &D, const Arg *A,
652                               const ArgList &Args,
653                               std::vector<const char *> &Features) {
654   StringRef FPU = A->getValue();
655
656   // Set the target features based on the FPU.
657   if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
658     // Disable any default FPU support.
659     Features.push_back("-vfp2");
660     Features.push_back("-vfp3");
661     Features.push_back("-neon");
662   } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
663     Features.push_back("+vfp3");
664     Features.push_back("+d16");
665     Features.push_back("-neon");
666   } else if (FPU == "vfp") {
667     Features.push_back("+vfp2");
668     Features.push_back("-neon");
669   } else if (FPU == "vfp3" || FPU == "vfpv3") {
670     Features.push_back("+vfp3");
671     Features.push_back("-neon");
672   } else if (FPU == "fp-armv8") {
673     Features.push_back("+fp-armv8");
674     Features.push_back("-neon");
675     Features.push_back("-crypto");
676   } else if (FPU == "neon-fp-armv8") {
677     Features.push_back("+fp-armv8");
678     Features.push_back("+neon");
679     Features.push_back("-crypto");
680   } else if (FPU == "crypto-neon-fp-armv8") {
681     Features.push_back("+fp-armv8");
682     Features.push_back("+neon");
683     Features.push_back("+crypto");
684   } else if (FPU == "neon") {
685     Features.push_back("+neon");
686   } else if (FPU == "none") {
687     Features.push_back("-vfp2");
688     Features.push_back("-vfp3");
689     Features.push_back("-vfp4");
690     Features.push_back("-fp-armv8");
691     Features.push_back("-crypto");
692     Features.push_back("-neon");
693   } else
694     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
695 }
696
697 // Select the float ABI as determined by -msoft-float, -mhard-float, and
698 // -mfloat-abi=.
699 static StringRef getARMFloatABI(const Driver &D,
700                                 const ArgList &Args,
701                                 const llvm::Triple &Triple) {
702   StringRef FloatABI;
703   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
704                                options::OPT_mhard_float,
705                                options::OPT_mfloat_abi_EQ)) {
706     if (A->getOption().matches(options::OPT_msoft_float))
707       FloatABI = "soft";
708     else if (A->getOption().matches(options::OPT_mhard_float))
709       FloatABI = "hard";
710     else {
711       FloatABI = A->getValue();
712       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
713         D.Diag(diag::err_drv_invalid_mfloat_abi)
714           << A->getAsString(Args);
715         FloatABI = "soft";
716       }
717     }
718   }
719
720   // If unspecified, choose the default based on the platform.
721   if (FloatABI.empty()) {
722     switch (Triple.getOS()) {
723     case llvm::Triple::Darwin:
724     case llvm::Triple::MacOSX:
725     case llvm::Triple::IOS: {
726       // Darwin defaults to "softfp" for v6 and v7.
727       //
728       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
729       std::string ArchName =
730         getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
731       if (StringRef(ArchName).startswith("v6") ||
732           StringRef(ArchName).startswith("v7"))
733         FloatABI = "softfp";
734       else
735         FloatABI = "soft";
736       break;
737     }
738
739     case llvm::Triple::FreeBSD:
740       // FreeBSD defaults to soft float
741       FloatABI = "soft";
742       break;
743
744     default:
745       switch(Triple.getEnvironment()) {
746       case llvm::Triple::GNUEABIHF:
747         FloatABI = "hard";
748         break;
749       case llvm::Triple::GNUEABI:
750         FloatABI = "softfp";
751         break;
752       case llvm::Triple::EABI:
753         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
754         FloatABI = "softfp";
755         break;
756       case llvm::Triple::Android: {
757         std::string ArchName =
758           getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
759         if (StringRef(ArchName).startswith("v7"))
760           FloatABI = "softfp";
761         else
762           FloatABI = "soft";
763         break;
764       }
765       default:
766         // Assume "soft", but warn the user we are guessing.
767         FloatABI = "soft";
768         D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
769         break;
770       }
771     }
772   }
773
774   return FloatABI;
775 }
776
777 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
778                                  const ArgList &Args,
779                                  std::vector<const char *> &Features) {
780   StringRef FloatABI = getARMFloatABI(D, Args, Triple);
781   // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
782   // yet (it uses the -mfloat-abi and -msoft-float options), and it is
783   // stripped out by the ARM target.
784   // Use software floating point operations?
785   if (FloatABI == "soft")
786     Features.push_back("+soft-float");
787
788   // Use software floating point argument passing?
789   if (FloatABI != "hard")
790     Features.push_back("+soft-float-abi");
791
792   // Honor -mfpu=.
793   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
794     getARMFPUFeatures(D, A, Args, Features);
795   if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
796     getARMHWDivFeatures(D, A, Args, Features);
797
798   // Setting -msoft-float effectively disables NEON because of the GCC
799   // implementation, although the same isn't true of VFP or VFP3.
800   if (FloatABI == "soft")
801     Features.push_back("-neon");
802
803   // En/disable crc
804   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
805                                options::OPT_mnocrc)) {
806     if (A->getOption().matches(options::OPT_mcrc))
807       Features.push_back("+crc");
808     else
809       Features.push_back("-crc");
810   }
811 }
812
813 void Clang::AddARMTargetArgs(const ArgList &Args,
814                              ArgStringList &CmdArgs,
815                              bool KernelOrKext) const {
816   const Driver &D = getToolChain().getDriver();
817   // Get the effective triple, which takes into account the deployment target.
818   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
819   llvm::Triple Triple(TripleStr);
820   std::string CPUName = getARMTargetCPU(Args, Triple);
821
822   // Select the ABI to use.
823   //
824   // FIXME: Support -meabi.
825   const char *ABIName = 0;
826   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
827     ABIName = A->getValue();
828   } else if (Triple.isOSDarwin()) {
829     // The backend is hardwired to assume AAPCS for M-class processors, ensure
830     // the frontend matches that.
831     if (Triple.getEnvironment() == llvm::Triple::EABI ||
832         StringRef(CPUName).startswith("cortex-m")) {
833       ABIName = "aapcs";
834     } else {
835       ABIName = "apcs-gnu";
836     }
837   } else {
838     // Select the default based on the platform.
839     switch(Triple.getEnvironment()) {
840     case llvm::Triple::Android:
841     case llvm::Triple::GNUEABI:
842     case llvm::Triple::GNUEABIHF:
843       ABIName = "aapcs-linux";
844       break;
845     case llvm::Triple::EABI:
846       ABIName = "aapcs";
847       break;
848     default:
849       ABIName = "apcs-gnu";
850     }
851   }
852   CmdArgs.push_back("-target-abi");
853   CmdArgs.push_back(ABIName);
854
855   // Determine floating point ABI from the options & target defaults.
856   StringRef FloatABI = getARMFloatABI(D, Args, Triple);
857   if (FloatABI == "soft") {
858     // Floating point operations and argument passing are soft.
859     //
860     // FIXME: This changes CPP defines, we need -target-soft-float.
861     CmdArgs.push_back("-msoft-float");
862     CmdArgs.push_back("-mfloat-abi");
863     CmdArgs.push_back("soft");
864   } else if (FloatABI == "softfp") {
865     // Floating point operations are hard, but argument passing is soft.
866     CmdArgs.push_back("-mfloat-abi");
867     CmdArgs.push_back("soft");
868   } else {
869     // Floating point operations and argument passing are hard.
870     assert(FloatABI == "hard" && "Invalid float abi!");
871     CmdArgs.push_back("-mfloat-abi");
872     CmdArgs.push_back("hard");
873   }
874
875   // Kernel code has more strict alignment requirements.
876   if (KernelOrKext) {
877     if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
878       CmdArgs.push_back("-backend-option");
879       CmdArgs.push_back("-arm-long-calls");
880     }
881
882     CmdArgs.push_back("-backend-option");
883     CmdArgs.push_back("-arm-strict-align");
884
885     // The kext linker doesn't know how to deal with movw/movt.
886     CmdArgs.push_back("-backend-option");
887     CmdArgs.push_back("-arm-use-movt=0");
888   }
889
890   // Setting -mno-global-merge disables the codegen global merge pass. Setting 
891   // -mglobal-merge has no effect as the pass is enabled by default.
892   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
893                                options::OPT_mno_global_merge)) {
894     if (A->getOption().matches(options::OPT_mno_global_merge))
895       CmdArgs.push_back("-mno-global-merge");
896   }
897
898   if (!Args.hasFlag(options::OPT_mimplicit_float,
899                     options::OPT_mno_implicit_float,
900                     true))
901     CmdArgs.push_back("-no-implicit-float");
902
903     // llvm does not support reserving registers in general. There is support
904     // for reserving r9 on ARM though (defined as a platform-specific register
905     // in ARM EABI).
906     if (Args.hasArg(options::OPT_ffixed_r9)) {
907       CmdArgs.push_back("-backend-option");
908       CmdArgs.push_back("-arm-reserve-r9");
909     }
910 }
911
912 // Get CPU and ABI names. They are not independent
913 // so we have to calculate them together.
914 static void getMipsCPUAndABI(const ArgList &Args,
915                              const llvm::Triple &Triple,
916                              StringRef &CPUName,
917                              StringRef &ABIName) {
918   const char *DefMips32CPU = "mips32";
919   const char *DefMips64CPU = "mips64";
920
921   if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
922                                options::OPT_mcpu_EQ))
923     CPUName = A->getValue();
924
925   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
926     ABIName = A->getValue();
927     // Convert a GNU style Mips ABI name to the name
928     // accepted by LLVM Mips backend.
929     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
930       .Case("32", "o32")
931       .Case("64", "n64")
932       .Default(ABIName);
933   }
934
935   // Setup default CPU and ABI names.
936   if (CPUName.empty() && ABIName.empty()) {
937     switch (Triple.getArch()) {
938     default:
939       llvm_unreachable("Unexpected triple arch name");
940     case llvm::Triple::mips:
941     case llvm::Triple::mipsel:
942       CPUName = DefMips32CPU;
943       break;
944     case llvm::Triple::mips64:
945     case llvm::Triple::mips64el:
946       CPUName = DefMips64CPU;
947       break;
948     }
949   }
950
951   if (!ABIName.empty()) {
952     // Deduce CPU name from ABI name.
953     CPUName = llvm::StringSwitch<const char *>(ABIName)
954       .Cases("32", "o32", "eabi", DefMips32CPU)
955       .Cases("n32", "n64", "64", DefMips64CPU)
956       .Default("");
957   }
958   else if (!CPUName.empty()) {
959     // Deduce ABI name from CPU name.
960     ABIName = llvm::StringSwitch<const char *>(CPUName)
961       .Cases("mips32", "mips32r2", "o32")
962       .Cases("mips64", "mips64r2", "n64")
963       .Default("");
964   }
965
966   // FIXME: Warn on inconsistent cpu and abi usage.
967 }
968
969 // Convert ABI name to the GNU tools acceptable variant.
970 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
971   return llvm::StringSwitch<llvm::StringRef>(ABI)
972     .Case("o32", "32")
973     .Case("n64", "64")
974     .Default(ABI);
975 }
976
977 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
978 // and -mfloat-abi=.
979 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
980   StringRef FloatABI;
981   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
982                                options::OPT_mhard_float,
983                                options::OPT_mfloat_abi_EQ)) {
984     if (A->getOption().matches(options::OPT_msoft_float))
985       FloatABI = "soft";
986     else if (A->getOption().matches(options::OPT_mhard_float))
987       FloatABI = "hard";
988     else {
989       FloatABI = A->getValue();
990       if (FloatABI != "soft" && FloatABI != "hard") {
991         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
992         FloatABI = "hard";
993       }
994     }
995   }
996
997   // If unspecified, choose the default based on the platform.
998   if (FloatABI.empty()) {
999     // Assume "hard", because it's a default value used by gcc.
1000     // When we start to recognize specific target MIPS processors,
1001     // we will be able to select the default more correctly.
1002     FloatABI = "hard";
1003   }
1004
1005   return FloatABI;
1006 }
1007
1008 static void AddTargetFeature(const ArgList &Args,
1009                              std::vector<const char *> &Features,
1010                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1011                              StringRef FeatureName) {
1012   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1013     if (A->getOption().matches(OnOpt))
1014       Features.push_back(Args.MakeArgString("+" + FeatureName));
1015     else
1016       Features.push_back(Args.MakeArgString("-" + FeatureName));
1017   }
1018 }
1019
1020 static void getMIPSTargetFeatures(const Driver &D, const ArgList &Args,
1021                                   std::vector<const char *> &Features) {
1022   StringRef FloatABI = getMipsFloatABI(D, Args);
1023   bool IsMips16 = Args.getLastArg(options::OPT_mips16) != NULL;
1024   if (FloatABI == "soft" || (FloatABI == "hard" && IsMips16)) {
1025     // FIXME: Note, this is a hack. We need to pass the selected float
1026     // mode to the MipsTargetInfoBase to define appropriate macros there.
1027     // Now it is the only method.
1028     Features.push_back("+soft-float");
1029   }
1030
1031   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1032     if (StringRef(A->getValue()) == "2008")
1033       Features.push_back("+nan2008");
1034   }
1035
1036   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1037                    options::OPT_mdouble_float, "single-float");
1038   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1039                    "mips16");
1040   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1041                    options::OPT_mno_micromips, "micromips");
1042   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1043                    "dsp");
1044   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1045                    "dspr2");
1046   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1047                    "msa");
1048   AddTargetFeature(Args, Features, options::OPT_mfp64, options::OPT_mfp32,
1049                    "fp64");
1050 }
1051
1052 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1053                               ArgStringList &CmdArgs) const {
1054   const Driver &D = getToolChain().getDriver();
1055   StringRef CPUName;
1056   StringRef ABIName;
1057   const llvm::Triple &Triple = getToolChain().getTriple();
1058   getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1059
1060   CmdArgs.push_back("-target-abi");
1061   CmdArgs.push_back(ABIName.data());
1062
1063   StringRef FloatABI = getMipsFloatABI(D, Args);
1064
1065   bool IsMips16 = Args.getLastArg(options::OPT_mips16) != NULL;
1066
1067   if (FloatABI == "soft" || (FloatABI == "hard" && IsMips16)) {
1068     // Floating point operations and argument passing are soft.
1069     CmdArgs.push_back("-msoft-float");
1070     CmdArgs.push_back("-mfloat-abi");
1071     CmdArgs.push_back("soft");
1072
1073     if (FloatABI == "hard" && IsMips16) {
1074       CmdArgs.push_back("-mllvm");
1075       CmdArgs.push_back("-mips16-hard-float");
1076     }
1077   }
1078   else {
1079     // Floating point operations and argument passing are hard.
1080     assert(FloatABI == "hard" && "Invalid float abi!");
1081     CmdArgs.push_back("-mfloat-abi");
1082     CmdArgs.push_back("hard");
1083   }
1084
1085   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1086     if (A->getOption().matches(options::OPT_mxgot)) {
1087       CmdArgs.push_back("-mllvm");
1088       CmdArgs.push_back("-mxgot");
1089     }
1090   }
1091
1092   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1093                                options::OPT_mno_ldc1_sdc1)) {
1094     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1095       CmdArgs.push_back("-mllvm");
1096       CmdArgs.push_back("-mno-ldc1-sdc1");
1097     }
1098   }
1099
1100   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1101                                options::OPT_mno_check_zero_division)) {
1102     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1103       CmdArgs.push_back("-mllvm");
1104       CmdArgs.push_back("-mno-check-zero-division");
1105     }
1106   }
1107
1108   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1109     StringRef v = A->getValue();
1110     CmdArgs.push_back("-mllvm");
1111     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1112     A->claim();
1113   }
1114 }
1115
1116 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1117 static std::string getPPCTargetCPU(const ArgList &Args) {
1118   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1119     StringRef CPUName = A->getValue();
1120
1121     if (CPUName == "native") {
1122       std::string CPU = llvm::sys::getHostCPUName();
1123       if (!CPU.empty() && CPU != "generic")
1124         return CPU;
1125       else
1126         return "";
1127     }
1128
1129     return llvm::StringSwitch<const char *>(CPUName)
1130       .Case("common", "generic")
1131       .Case("440", "440")
1132       .Case("440fp", "440")
1133       .Case("450", "450")
1134       .Case("601", "601")
1135       .Case("602", "602")
1136       .Case("603", "603")
1137       .Case("603e", "603e")
1138       .Case("603ev", "603ev")
1139       .Case("604", "604")
1140       .Case("604e", "604e")
1141       .Case("620", "620")
1142       .Case("630", "pwr3")
1143       .Case("G3", "g3")
1144       .Case("7400", "7400")
1145       .Case("G4", "g4")
1146       .Case("7450", "7450")
1147       .Case("G4+", "g4+")
1148       .Case("750", "750")
1149       .Case("970", "970")
1150       .Case("G5", "g5")
1151       .Case("a2", "a2")
1152       .Case("a2q", "a2q")
1153       .Case("e500mc", "e500mc")
1154       .Case("e5500", "e5500")
1155       .Case("power3", "pwr3")
1156       .Case("power4", "pwr4")
1157       .Case("power5", "pwr5")
1158       .Case("power5x", "pwr5x")
1159       .Case("power6", "pwr6")
1160       .Case("power6x", "pwr6x")
1161       .Case("power7", "pwr7")
1162       .Case("pwr3", "pwr3")
1163       .Case("pwr4", "pwr4")
1164       .Case("pwr5", "pwr5")
1165       .Case("pwr5x", "pwr5x")
1166       .Case("pwr6", "pwr6")
1167       .Case("pwr6x", "pwr6x")
1168       .Case("pwr7", "pwr7")
1169       .Case("powerpc", "ppc")
1170       .Case("powerpc64", "ppc64")
1171       .Case("powerpc64le", "ppc64le")
1172       .Default("");
1173   }
1174
1175   return "";
1176 }
1177
1178 static void getPPCTargetFeatures(const ArgList &Args,
1179                                  std::vector<const char *> &Features) {
1180   for (arg_iterator it = Args.filtered_begin(options::OPT_m_ppc_Features_Group),
1181                     ie = Args.filtered_end();
1182        it != ie; ++it) {
1183     StringRef Name = (*it)->getOption().getName();
1184     (*it)->claim();
1185
1186     // Skip over "-m".
1187     assert(Name.startswith("m") && "Invalid feature name.");
1188     Name = Name.substr(1);
1189
1190     bool IsNegative = Name.startswith("no-");
1191     if (IsNegative)
1192       Name = Name.substr(3);
1193
1194     // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1195     // pass the correct option to the backend while calling the frontend
1196     // option the same.
1197     // TODO: Change the LLVM backend option maybe?
1198     if (Name == "mfcrf")
1199       Name = "mfocrf";
1200
1201     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1202   }
1203
1204   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1205   AddTargetFeature(Args, Features, options::OPT_faltivec,
1206                    options::OPT_fno_altivec, "altivec");
1207 }
1208
1209 /// Get the (LLVM) name of the R600 gpu we are targeting.
1210 static std::string getR600TargetGPU(const ArgList &Args) {
1211   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1212     const char *GPUName = A->getValue();
1213     return llvm::StringSwitch<const char *>(GPUName)
1214       .Cases("rv630", "rv635", "r600")
1215       .Cases("rv610", "rv620", "rs780", "rs880")
1216       .Case("rv740", "rv770")
1217       .Case("palm", "cedar")
1218       .Cases("sumo", "sumo2", "sumo")
1219       .Case("hemlock", "cypress")
1220       .Case("aruba", "cayman")
1221       .Default(GPUName);
1222   }
1223   return "";
1224 }
1225
1226 static void getSparcTargetFeatures(const ArgList &Args,
1227                                    std::vector<const char *> Features) {
1228   bool SoftFloatABI = true;
1229   if (Arg *A =
1230           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1231     if (A->getOption().matches(options::OPT_mhard_float))
1232       SoftFloatABI = false;
1233   }
1234   if (SoftFloatABI)
1235     Features.push_back("+soft-float");
1236 }
1237
1238 void Clang::AddSparcTargetArgs(const ArgList &Args,
1239                              ArgStringList &CmdArgs) const {
1240   const Driver &D = getToolChain().getDriver();
1241
1242   // Select the float ABI as determined by -msoft-float, -mhard-float, and
1243   StringRef FloatABI;
1244   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1245                                options::OPT_mhard_float)) {
1246     if (A->getOption().matches(options::OPT_msoft_float))
1247       FloatABI = "soft";
1248     else if (A->getOption().matches(options::OPT_mhard_float))
1249       FloatABI = "hard";
1250   }
1251
1252   // If unspecified, choose the default based on the platform.
1253   if (FloatABI.empty()) {
1254     // Assume "soft", but warn the user we are guessing.
1255     FloatABI = "soft";
1256     D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
1257   }
1258
1259   if (FloatABI == "soft") {
1260     // Floating point operations and argument passing are soft.
1261     //
1262     // FIXME: This changes CPP defines, we need -target-soft-float.
1263     CmdArgs.push_back("-msoft-float");
1264   } else {
1265     assert(FloatABI == "hard" && "Invalid float abi!");
1266     CmdArgs.push_back("-mhard-float");
1267   }
1268 }
1269
1270 static const char *getSystemZTargetCPU(const ArgList &Args) {
1271   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1272     return A->getValue();
1273   return "z10";
1274 }
1275
1276 static const char *getX86TargetCPU(const ArgList &Args,
1277                                    const llvm::Triple &Triple) {
1278   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1279     if (StringRef(A->getValue()) != "native") {
1280       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1281         return "core-avx2";
1282
1283       return A->getValue();
1284     }
1285
1286     // FIXME: Reject attempts to use -march=native unless the target matches
1287     // the host.
1288     //
1289     // FIXME: We should also incorporate the detected target features for use
1290     // with -native.
1291     std::string CPU = llvm::sys::getHostCPUName();
1292     if (!CPU.empty() && CPU != "generic")
1293       return Args.MakeArgString(CPU);
1294   }
1295
1296   // Select the default CPU if none was given (or detection failed).
1297
1298   if (Triple.getArch() != llvm::Triple::x86_64 &&
1299       Triple.getArch() != llvm::Triple::x86)
1300     return 0; // This routine is only handling x86 targets.
1301
1302   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1303
1304   // FIXME: Need target hooks.
1305   if (Triple.isOSDarwin()) {
1306     if (Triple.getArchName() == "x86_64h")
1307       return "core-avx2";
1308     return Is64Bit ? "core2" : "yonah";
1309   }
1310
1311   // All x86 devices running Android have core2 as their common
1312   // denominator. This makes a better choice than pentium4.
1313   if (Triple.getEnvironment() == llvm::Triple::Android)
1314     return "core2";
1315
1316   // Everything else goes to x86-64 in 64-bit mode.
1317   if (Is64Bit)
1318     return "x86-64";
1319
1320   switch (Triple.getOS()) {
1321   case llvm::Triple::FreeBSD:
1322   case llvm::Triple::NetBSD:
1323   case llvm::Triple::OpenBSD:
1324     return "i486";
1325   case llvm::Triple::Haiku:
1326     return "i586";
1327   case llvm::Triple::Bitrig:
1328     return "i686";
1329   default:
1330     // Fallback to p4.
1331     return "pentium4";
1332   }
1333 }
1334
1335 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1336   switch(T.getArch()) {
1337   default:
1338     return "";
1339
1340   case llvm::Triple::aarch64:
1341     return getAArch64TargetCPU(Args, T);
1342
1343   case llvm::Triple::arm:
1344   case llvm::Triple::thumb:
1345     return getARMTargetCPU(Args, T);
1346
1347   case llvm::Triple::mips:
1348   case llvm::Triple::mipsel:
1349   case llvm::Triple::mips64:
1350   case llvm::Triple::mips64el: {
1351     StringRef CPUName;
1352     StringRef ABIName;
1353     getMipsCPUAndABI(Args, T, CPUName, ABIName);
1354     return CPUName;
1355   }
1356
1357   case llvm::Triple::ppc:
1358   case llvm::Triple::ppc64:
1359   case llvm::Triple::ppc64le: {
1360     std::string TargetCPUName = getPPCTargetCPU(Args);
1361     // LLVM may default to generating code for the native CPU,
1362     // but, like gcc, we default to a more generic option for
1363     // each architecture. (except on Darwin)
1364     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1365       if (T.getArch() == llvm::Triple::ppc64)
1366         TargetCPUName = "ppc64";
1367       else if (T.getArch() == llvm::Triple::ppc64le)
1368         TargetCPUName = "ppc64le";
1369       else
1370         TargetCPUName = "ppc";
1371     }
1372     return TargetCPUName;
1373   }
1374
1375   case llvm::Triple::sparc:
1376   case llvm::Triple::sparcv9:
1377     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1378       return A->getValue();
1379     return "";
1380
1381   case llvm::Triple::x86:
1382   case llvm::Triple::x86_64:
1383     return getX86TargetCPU(Args, T);
1384
1385   case llvm::Triple::hexagon:
1386     return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1387
1388   case llvm::Triple::systemz:
1389     return getSystemZTargetCPU(Args);
1390
1391   case llvm::Triple::r600:
1392     return getR600TargetGPU(Args);
1393   }
1394 }
1395
1396 static void getX86TargetFeatures(const llvm::Triple &Triple,
1397                                  const ArgList &Args,
1398                                  std::vector<const char *> &Features) {
1399   if (Triple.getArchName() == "x86_64h") {
1400     // x86_64h implies quite a few of the more modern subtarget features
1401     // for Haswell class CPUs, but not all of them. Opt-out of a few.
1402     Features.push_back("-rdrnd");
1403     Features.push_back("-aes");
1404     Features.push_back("-pclmul");
1405     Features.push_back("-rtm");
1406     Features.push_back("-hle");
1407     Features.push_back("-fsgsbase");
1408   }
1409
1410   // Now add any that the user explicitly requested on the command line,
1411   // which may override the defaults.
1412   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
1413                     ie = Args.filtered_end();
1414        it != ie; ++it) {
1415     StringRef Name = (*it)->getOption().getName();
1416     (*it)->claim();
1417
1418     // Skip over "-m".
1419     assert(Name.startswith("m") && "Invalid feature name.");
1420     Name = Name.substr(1);
1421
1422     bool IsNegative = Name.startswith("no-");
1423     if (IsNegative)
1424       Name = Name.substr(3);
1425
1426     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1427   }
1428 }
1429
1430 void Clang::AddX86TargetArgs(const ArgList &Args,
1431                              ArgStringList &CmdArgs) const {
1432   if (!Args.hasFlag(options::OPT_mred_zone,
1433                     options::OPT_mno_red_zone,
1434                     true) ||
1435       Args.hasArg(options::OPT_mkernel) ||
1436       Args.hasArg(options::OPT_fapple_kext))
1437     CmdArgs.push_back("-disable-red-zone");
1438
1439   // Default to avoid implicit floating-point for kernel/kext code, but allow
1440   // that to be overridden with -mno-soft-float.
1441   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1442                           Args.hasArg(options::OPT_fapple_kext));
1443   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1444                                options::OPT_mno_soft_float,
1445                                options::OPT_mimplicit_float,
1446                                options::OPT_mno_implicit_float)) {
1447     const Option &O = A->getOption();
1448     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1449                        O.matches(options::OPT_msoft_float));
1450   }
1451   if (NoImplicitFloat)
1452     CmdArgs.push_back("-no-implicit-float");
1453 }
1454
1455 static inline bool HasPICArg(const ArgList &Args) {
1456   return Args.hasArg(options::OPT_fPIC)
1457     || Args.hasArg(options::OPT_fpic);
1458 }
1459
1460 static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) {
1461   return Args.getLastArg(options::OPT_G,
1462                          options::OPT_G_EQ,
1463                          options::OPT_msmall_data_threshold_EQ);
1464 }
1465
1466 static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) {
1467   std::string value;
1468   if (HasPICArg(Args))
1469     value = "0";
1470   else if (Arg *A = GetLastSmallDataThresholdArg(Args)) {
1471     value = A->getValue();
1472     A->claim();
1473   }
1474   return value;
1475 }
1476
1477 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1478                                  ArgStringList &CmdArgs) const {
1479   CmdArgs.push_back("-fno-signed-char");
1480   CmdArgs.push_back("-mqdsp6-compat");
1481   CmdArgs.push_back("-Wreturn-type");
1482
1483   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
1484   if (!SmallDataThreshold.empty()) {
1485     CmdArgs.push_back ("-mllvm");
1486     CmdArgs.push_back(Args.MakeArgString(
1487                         "-hexagon-small-data-threshold=" + SmallDataThreshold));
1488   }
1489
1490   if (!Args.hasArg(options::OPT_fno_short_enums))
1491     CmdArgs.push_back("-fshort-enums");
1492   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1493     CmdArgs.push_back ("-mllvm");
1494     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
1495   }
1496   CmdArgs.push_back ("-mllvm");
1497   CmdArgs.push_back ("-machine-sink-split=0");
1498 }
1499
1500 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1501                                      std::vector<const char *> &Features) {
1502   // Honor -mfpu=.
1503   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
1504     getAArch64FPUFeatures(D, A, Args, Features);
1505 }
1506
1507 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1508                               const ArgList &Args, ArgStringList &CmdArgs) {
1509   std::vector<const char *> Features;
1510   switch (Triple.getArch()) {
1511   default:
1512     break;
1513   case llvm::Triple::mips:
1514   case llvm::Triple::mipsel:
1515   case llvm::Triple::mips64:
1516   case llvm::Triple::mips64el:
1517     getMIPSTargetFeatures(D, Args, Features);
1518     break;
1519
1520   case llvm::Triple::arm:
1521   case llvm::Triple::thumb:
1522     getARMTargetFeatures(D, Triple, Args, Features);
1523     break;
1524
1525   case llvm::Triple::ppc:
1526   case llvm::Triple::ppc64:
1527   case llvm::Triple::ppc64le:
1528     getPPCTargetFeatures(Args, Features);
1529     break;
1530   case llvm::Triple::sparc:
1531     getSparcTargetFeatures(Args, Features);
1532     break;
1533   case llvm::Triple::aarch64:
1534     getAArch64TargetFeatures(D, Args, Features);
1535     break;
1536   case llvm::Triple::x86:
1537   case llvm::Triple::x86_64:
1538     getX86TargetFeatures(Triple, Args, Features);
1539     break;
1540   }
1541
1542   // Find the last of each feature.
1543   llvm::StringMap<unsigned> LastOpt;
1544   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1545     const char *Name = Features[I];
1546     assert(Name[0] == '-' || Name[0] == '+');
1547     LastOpt[Name + 1] = I;
1548   }
1549
1550   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1551     // If this feature was overridden, ignore it.
1552     const char *Name = Features[I];
1553     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
1554     assert(LastI != LastOpt.end());
1555     unsigned Last = LastI->second;
1556     if (Last != I)
1557       continue;
1558
1559     CmdArgs.push_back("-target-feature");
1560     CmdArgs.push_back(Name);
1561   }
1562 }
1563
1564 static bool
1565 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
1566                                           const llvm::Triple &Triple) {
1567   // We use the zero-cost exception tables for Objective-C if the non-fragile
1568   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
1569   // later.
1570   if (runtime.isNonFragile())
1571     return true;
1572
1573   if (!Triple.isOSDarwin())
1574     return false;
1575
1576   return (!Triple.isMacOSXVersionLT(10,5) &&
1577           (Triple.getArch() == llvm::Triple::x86_64 ||
1578            Triple.getArch() == llvm::Triple::arm));
1579 }
1580
1581 /// addExceptionArgs - Adds exception related arguments to the driver command
1582 /// arguments. There's a master flag, -fexceptions and also language specific
1583 /// flags to enable/disable C++ and Objective-C exceptions.
1584 /// This makes it possible to for example disable C++ exceptions but enable
1585 /// Objective-C exceptions.
1586 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
1587                              const llvm::Triple &Triple,
1588                              bool KernelOrKext,
1589                              const ObjCRuntime &objcRuntime,
1590                              ArgStringList &CmdArgs) {
1591   if (KernelOrKext) {
1592     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
1593     // arguments now to avoid warnings about unused arguments.
1594     Args.ClaimAllArgs(options::OPT_fexceptions);
1595     Args.ClaimAllArgs(options::OPT_fno_exceptions);
1596     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
1597     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
1598     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
1599     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
1600     return;
1601   }
1602
1603   // Exceptions are enabled by default.
1604   bool ExceptionsEnabled = true;
1605
1606   // This keeps track of whether exceptions were explicitly turned on or off.
1607   bool DidHaveExplicitExceptionFlag = false;
1608
1609   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
1610                                options::OPT_fno_exceptions)) {
1611     if (A->getOption().matches(options::OPT_fexceptions))
1612       ExceptionsEnabled = true;
1613     else
1614       ExceptionsEnabled = false;
1615
1616     DidHaveExplicitExceptionFlag = true;
1617   }
1618
1619   bool ShouldUseExceptionTables = false;
1620
1621   // Exception tables and cleanups can be enabled with -fexceptions even if the
1622   // language itself doesn't support exceptions.
1623   if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
1624     ShouldUseExceptionTables = true;
1625
1626   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
1627   // is not necessarily sensible, but follows GCC.
1628   if (types::isObjC(InputType) &&
1629       Args.hasFlag(options::OPT_fobjc_exceptions,
1630                    options::OPT_fno_objc_exceptions,
1631                    true)) {
1632     CmdArgs.push_back("-fobjc-exceptions");
1633
1634     ShouldUseExceptionTables |=
1635       shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
1636   }
1637
1638   if (types::isCXX(InputType)) {
1639     bool CXXExceptionsEnabled = ExceptionsEnabled;
1640
1641     if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
1642                                  options::OPT_fno_cxx_exceptions,
1643                                  options::OPT_fexceptions,
1644                                  options::OPT_fno_exceptions)) {
1645       if (A->getOption().matches(options::OPT_fcxx_exceptions))
1646         CXXExceptionsEnabled = true;
1647       else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
1648         CXXExceptionsEnabled = false;
1649     }
1650
1651     if (CXXExceptionsEnabled) {
1652       CmdArgs.push_back("-fcxx-exceptions");
1653
1654       ShouldUseExceptionTables = true;
1655     }
1656   }
1657
1658   if (ShouldUseExceptionTables)
1659     CmdArgs.push_back("-fexceptions");
1660 }
1661
1662 static bool ShouldDisableAutolink(const ArgList &Args,
1663                              const ToolChain &TC) {
1664   bool Default = true;
1665   if (TC.getTriple().isOSDarwin()) {
1666     // The native darwin assembler doesn't support the linker_option directives,
1667     // so we disable them if we think the .s file will be passed to it.
1668     Default = TC.useIntegratedAs();
1669   }
1670   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
1671                        Default);
1672 }
1673
1674 static bool ShouldDisableCFI(const ArgList &Args,
1675                              const ToolChain &TC) {
1676   bool Default = true;
1677   if (TC.getTriple().isOSDarwin()) {
1678     // The native darwin assembler doesn't support cfi directives, so
1679     // we disable them if we think the .s file will be passed to it.
1680     Default = TC.useIntegratedAs();
1681   }
1682   return !Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
1683                        options::OPT_fno_dwarf2_cfi_asm,
1684                        Default);
1685 }
1686
1687 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
1688                                         const ToolChain &TC) {
1689   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
1690                                         options::OPT_fno_dwarf_directory_asm,
1691                                         TC.useIntegratedAs());
1692   return !UseDwarfDirectory;
1693 }
1694
1695 /// \brief Check whether the given input tree contains any compilation actions.
1696 static bool ContainsCompileAction(const Action *A) {
1697   if (isa<CompileJobAction>(A))
1698     return true;
1699
1700   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
1701     if (ContainsCompileAction(*it))
1702       return true;
1703
1704   return false;
1705 }
1706
1707 /// \brief Check if -relax-all should be passed to the internal assembler.
1708 /// This is done by default when compiling non-assembler source with -O0.
1709 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
1710   bool RelaxDefault = true;
1711
1712   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1713     RelaxDefault = A->getOption().matches(options::OPT_O0);
1714
1715   if (RelaxDefault) {
1716     RelaxDefault = false;
1717     for (ActionList::const_iterator it = C.getActions().begin(),
1718            ie = C.getActions().end(); it != ie; ++it) {
1719       if (ContainsCompileAction(*it)) {
1720         RelaxDefault = true;
1721         break;
1722       }
1723     }
1724   }
1725
1726   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1727     RelaxDefault);
1728 }
1729
1730 static void CollectArgsForIntegratedAssembler(Compilation &C,
1731                                               const ArgList &Args,
1732                                               ArgStringList &CmdArgs,
1733                                               const Driver &D) {
1734     if (UseRelaxAll(C, Args))
1735       CmdArgs.push_back("-mrelax-all");
1736
1737     // When passing -I arguments to the assembler we sometimes need to
1738     // unconditionally take the next argument.  For example, when parsing
1739     // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1740     // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1741     // arg after parsing the '-I' arg.
1742     bool TakeNextArg = false;
1743
1744     // When using an integrated assembler, translate -Wa, and -Xassembler
1745     // options.
1746     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
1747                                                options::OPT_Xassembler),
1748            ie = Args.filtered_end(); it != ie; ++it) {
1749       const Arg *A = *it;
1750       A->claim();
1751
1752       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
1753         StringRef Value = A->getValue(i);
1754         if (TakeNextArg) {
1755           CmdArgs.push_back(Value.data());
1756           TakeNextArg = false;
1757           continue;
1758         }
1759
1760         if (Value == "-force_cpusubtype_ALL") {
1761           // Do nothing, this is the default and we don't support anything else.
1762         } else if (Value == "-L") {
1763           CmdArgs.push_back("-msave-temp-labels");
1764         } else if (Value == "--fatal-warnings") {
1765           CmdArgs.push_back("-mllvm");
1766           CmdArgs.push_back("-fatal-assembler-warnings");
1767         } else if (Value == "--noexecstack") {
1768           CmdArgs.push_back("-mnoexecstack");
1769         } else if (Value.startswith("-I")) {
1770           CmdArgs.push_back(Value.data());
1771           // We need to consume the next argument if the current arg is a plain
1772           // -I. The next arg will be the include directory.
1773           if (Value == "-I")
1774             TakeNextArg = true;
1775         } else {
1776           D.Diag(diag::err_drv_unsupported_option_argument)
1777             << A->getOption().getName() << Value;
1778         }
1779       }
1780     }
1781 }
1782
1783 static void addProfileRTLinux(
1784     const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
1785   if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
1786         Args.hasArg(options::OPT_fprofile_generate) ||
1787         Args.hasArg(options::OPT_fcreate_profile) ||
1788         Args.hasArg(options::OPT_coverage)))
1789     return;
1790
1791   // The profile runtime is located in the Linux library directory and has name
1792   // "libclang_rt.profile-<ArchName>.a".
1793   SmallString<128> LibProfile(TC.getDriver().ResourceDir);
1794   llvm::sys::path::append(
1795       LibProfile, "lib", "linux",
1796       Twine("libclang_rt.profile-") + TC.getArchName() + ".a");
1797
1798   CmdArgs.push_back(Args.MakeArgString(LibProfile));
1799 }
1800
1801 static void addSanitizerRTLinkFlagsLinux(
1802     const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs,
1803     const StringRef Sanitizer, bool BeforeLibStdCXX,
1804     bool ExportSymbols = true) {
1805   // Sanitizer runtime is located in the Linux library directory and
1806   // has name "libclang_rt.<Sanitizer>-<ArchName>.a".
1807   SmallString<128> LibSanitizer(TC.getDriver().ResourceDir);
1808   llvm::sys::path::append(
1809       LibSanitizer, "lib", "linux",
1810       (Twine("libclang_rt.") + Sanitizer + "-" + TC.getArchName() + ".a"));
1811
1812   // Sanitizer runtime may need to come before -lstdc++ (or -lc++, libstdc++.a,
1813   // etc.) so that the linker picks custom versions of the global 'operator
1814   // new' and 'operator delete' symbols. We take the extreme (but simple)
1815   // strategy of inserting it at the front of the link command. It also
1816   // needs to be forced to end up in the executable, so wrap it in
1817   // whole-archive.
1818   SmallVector<const char *, 3> LibSanitizerArgs;
1819   LibSanitizerArgs.push_back("-whole-archive");
1820   LibSanitizerArgs.push_back(Args.MakeArgString(LibSanitizer));
1821   LibSanitizerArgs.push_back("-no-whole-archive");
1822
1823   CmdArgs.insert(BeforeLibStdCXX ? CmdArgs.begin() : CmdArgs.end(),
1824                  LibSanitizerArgs.begin(), LibSanitizerArgs.end());
1825
1826   CmdArgs.push_back("-lpthread");
1827   CmdArgs.push_back("-lrt");
1828   CmdArgs.push_back("-ldl");
1829   CmdArgs.push_back("-lm");
1830
1831   // If possible, use a dynamic symbols file to export the symbols from the
1832   // runtime library. If we can't do so, use -export-dynamic instead to export
1833   // all symbols from the binary.
1834   if (ExportSymbols) {
1835     if (llvm::sys::fs::exists(LibSanitizer + ".syms"))
1836       CmdArgs.push_back(
1837           Args.MakeArgString("--dynamic-list=" + LibSanitizer + ".syms"));
1838     else
1839       CmdArgs.push_back("-export-dynamic");
1840   }
1841 }
1842
1843 /// If AddressSanitizer is enabled, add appropriate linker flags (Linux).
1844 /// This needs to be called before we add the C run-time (malloc, etc).
1845 static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
1846                            ArgStringList &CmdArgs) {
1847   if (TC.getTriple().getEnvironment() == llvm::Triple::Android) {
1848     SmallString<128> LibAsan(TC.getDriver().ResourceDir);
1849     llvm::sys::path::append(LibAsan, "lib", "linux",
1850         (Twine("libclang_rt.asan-") +
1851             TC.getArchName() + "-android.so"));
1852     CmdArgs.insert(CmdArgs.begin(), Args.MakeArgString(LibAsan));
1853   } else {
1854     if (!Args.hasArg(options::OPT_shared))
1855       addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "asan", true);
1856   }
1857 }
1858
1859 /// If ThreadSanitizer is enabled, add appropriate linker flags (Linux).
1860 /// This needs to be called before we add the C run-time (malloc, etc).
1861 static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args,
1862                            ArgStringList &CmdArgs) {
1863   if (!Args.hasArg(options::OPT_shared))
1864     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "tsan", true);
1865 }
1866
1867 /// If MemorySanitizer is enabled, add appropriate linker flags (Linux).
1868 /// This needs to be called before we add the C run-time (malloc, etc).
1869 static void addMsanRTLinux(const ToolChain &TC, const ArgList &Args,
1870                            ArgStringList &CmdArgs) {
1871   if (!Args.hasArg(options::OPT_shared))
1872     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "msan", true);
1873 }
1874
1875 /// If LeakSanitizer is enabled, add appropriate linker flags (Linux).
1876 /// This needs to be called before we add the C run-time (malloc, etc).
1877 static void addLsanRTLinux(const ToolChain &TC, const ArgList &Args,
1878                            ArgStringList &CmdArgs) {
1879   if (!Args.hasArg(options::OPT_shared))
1880     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "lsan", true);
1881 }
1882
1883 /// If UndefinedBehaviorSanitizer is enabled, add appropriate linker flags
1884 /// (Linux).
1885 static void addUbsanRTLinux(const ToolChain &TC, const ArgList &Args,
1886                             ArgStringList &CmdArgs, bool IsCXX,
1887                             bool HasOtherSanitizerRt) {
1888   // Need a copy of sanitizer_common. This could come from another sanitizer
1889   // runtime; if we're not including one, include our own copy.
1890   if (!HasOtherSanitizerRt)
1891     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "san", true, false);
1892
1893   addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan", false);
1894
1895   // Only include the bits of the runtime which need a C++ ABI library if
1896   // we're linking in C++ mode.
1897   if (IsCXX)
1898     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan_cxx", false);
1899 }
1900
1901 static void addDfsanRTLinux(const ToolChain &TC, const ArgList &Args,
1902                             ArgStringList &CmdArgs) {
1903   if (!Args.hasArg(options::OPT_shared))
1904     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "dfsan", true);
1905 }
1906
1907 static bool shouldUseFramePointerForTarget(const ArgList &Args,
1908                                            const llvm::Triple &Triple) {
1909   switch (Triple.getArch()) {
1910   // Don't use a frame pointer on linux if optimizing for certain targets.
1911   case llvm::Triple::mips64:
1912   case llvm::Triple::mips64el:
1913   case llvm::Triple::mips:
1914   case llvm::Triple::mipsel:
1915   case llvm::Triple::systemz:
1916   case llvm::Triple::x86:
1917   case llvm::Triple::x86_64:
1918     if (Triple.isOSLinux())
1919       if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1920         if (!A->getOption().matches(options::OPT_O0))
1921           return false;
1922     return true;
1923   case llvm::Triple::xcore:
1924     return false;
1925   default:
1926     return true;
1927   }
1928 }
1929
1930 static bool shouldUseFramePointer(const ArgList &Args,
1931                                   const llvm::Triple &Triple) {
1932   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
1933                                options::OPT_fomit_frame_pointer))
1934     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
1935
1936   return shouldUseFramePointerForTarget(Args, Triple);
1937 }
1938
1939 static bool shouldUseLeafFramePointer(const ArgList &Args,
1940                                       const llvm::Triple &Triple) {
1941   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
1942                                options::OPT_momit_leaf_frame_pointer))
1943     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
1944
1945   return shouldUseFramePointerForTarget(Args, Triple);
1946 }
1947
1948 /// Add a CC1 option to specify the debug compilation directory.
1949 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
1950   SmallString<128> cwd;
1951   if (!llvm::sys::fs::current_path(cwd)) {
1952     CmdArgs.push_back("-fdebug-compilation-dir");
1953     CmdArgs.push_back(Args.MakeArgString(cwd));
1954   }
1955 }
1956
1957 static const char *SplitDebugName(const ArgList &Args,
1958                                   const InputInfoList &Inputs) {
1959   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1960   if (FinalOutput && Args.hasArg(options::OPT_c)) {
1961     SmallString<128> T(FinalOutput->getValue());
1962     llvm::sys::path::replace_extension(T, "dwo");
1963     return Args.MakeArgString(T);
1964   } else {
1965     // Use the compilation dir.
1966     SmallString<128> T(Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
1967     SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput()));
1968     llvm::sys::path::replace_extension(F, "dwo");
1969     T += F;
1970     return Args.MakeArgString(F);
1971   }
1972 }
1973
1974 static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
1975                            const Tool &T, const JobAction &JA,
1976                            const ArgList &Args, const InputInfo &Output,
1977                            const char *OutFile) {
1978   ArgStringList ExtractArgs;
1979   ExtractArgs.push_back("--extract-dwo");
1980
1981   ArgStringList StripArgs;
1982   StripArgs.push_back("--strip-dwo");
1983
1984   // Grabbing the output of the earlier compile step.
1985   StripArgs.push_back(Output.getFilename());
1986   ExtractArgs.push_back(Output.getFilename());
1987   ExtractArgs.push_back(OutFile);
1988
1989   const char *Exec =
1990     Args.MakeArgString(TC.GetProgramPath("objcopy"));
1991
1992   // First extract the dwo sections.
1993   C.addCommand(new Command(JA, T, Exec, ExtractArgs));
1994
1995   // Then remove them from the original .o file.
1996   C.addCommand(new Command(JA, T, Exec, StripArgs));
1997 }
1998
1999 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2000 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args) {
2001   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2002     if (A->getOption().matches(options::OPT_O4) ||
2003         A->getOption().matches(options::OPT_Ofast))
2004       return true;
2005
2006     if (A->getOption().matches(options::OPT_O0))
2007       return false;
2008
2009     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2010
2011     // Vectorize -Os.
2012     StringRef S(A->getValue());
2013     if (S == "s")
2014       return true;
2015
2016     // Don't vectorize -Oz.
2017     if (S == "z")
2018       return false;
2019
2020     unsigned OptLevel = 0;
2021     if (S.getAsInteger(10, OptLevel))
2022       return false;
2023
2024     return OptLevel > 1;
2025   }
2026
2027   return false;
2028 }
2029
2030 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2031                          const InputInfo &Output,
2032                          const InputInfoList &Inputs,
2033                          const ArgList &Args,
2034                          const char *LinkingOutput) const {
2035   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
2036                                   options::OPT_fapple_kext);
2037   const Driver &D = getToolChain().getDriver();
2038   ArgStringList CmdArgs;
2039
2040   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2041
2042   // Invoke ourselves in -cc1 mode.
2043   //
2044   // FIXME: Implement custom jobs for internal actions.
2045   CmdArgs.push_back("-cc1");
2046
2047   // Add the "effective" target triple.
2048   CmdArgs.push_back("-triple");
2049   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2050   CmdArgs.push_back(Args.MakeArgString(TripleStr));
2051
2052   // Select the appropriate action.
2053   RewriteKind rewriteKind = RK_None;
2054   
2055   if (isa<AnalyzeJobAction>(JA)) {
2056     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2057     CmdArgs.push_back("-analyze");
2058   } else if (isa<MigrateJobAction>(JA)) {
2059     CmdArgs.push_back("-migrate");
2060   } else if (isa<PreprocessJobAction>(JA)) {
2061     if (Output.getType() == types::TY_Dependencies)
2062       CmdArgs.push_back("-Eonly");
2063     else {
2064       CmdArgs.push_back("-E");
2065       if (Args.hasArg(options::OPT_rewrite_objc) &&
2066           !Args.hasArg(options::OPT_g_Group))
2067         CmdArgs.push_back("-P");
2068     }
2069   } else if (isa<AssembleJobAction>(JA)) {
2070     CmdArgs.push_back("-emit-obj");
2071
2072     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2073
2074     // Also ignore explicit -force_cpusubtype_ALL option.
2075     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
2076   } else if (isa<PrecompileJobAction>(JA)) {
2077     // Use PCH if the user requested it.
2078     bool UsePCH = D.CCCUsePCH;
2079
2080     if (JA.getType() == types::TY_Nothing)
2081       CmdArgs.push_back("-fsyntax-only");
2082     else if (UsePCH)
2083       CmdArgs.push_back("-emit-pch");
2084     else
2085       CmdArgs.push_back("-emit-pth");
2086   } else {
2087     assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
2088
2089     if (JA.getType() == types::TY_Nothing) {
2090       CmdArgs.push_back("-fsyntax-only");
2091     } else if (JA.getType() == types::TY_LLVM_IR ||
2092                JA.getType() == types::TY_LTO_IR) {
2093       CmdArgs.push_back("-emit-llvm");
2094     } else if (JA.getType() == types::TY_LLVM_BC ||
2095                JA.getType() == types::TY_LTO_BC) {
2096       CmdArgs.push_back("-emit-llvm-bc");
2097     } else if (JA.getType() == types::TY_PP_Asm) {
2098       CmdArgs.push_back("-S");
2099     } else if (JA.getType() == types::TY_AST) {
2100       CmdArgs.push_back("-emit-pch");
2101     } else if (JA.getType() == types::TY_ModuleFile) {
2102       CmdArgs.push_back("-module-file-info");
2103     } else if (JA.getType() == types::TY_RewrittenObjC) {
2104       CmdArgs.push_back("-rewrite-objc");
2105       rewriteKind = RK_NonFragile;
2106     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2107       CmdArgs.push_back("-rewrite-objc");
2108       rewriteKind = RK_Fragile;
2109     } else {
2110       assert(JA.getType() == types::TY_PP_Asm &&
2111              "Unexpected output type!");
2112     }
2113   }
2114
2115   // The make clang go fast button.
2116   CmdArgs.push_back("-disable-free");
2117
2118   // Disable the verification pass in -asserts builds.
2119 #ifdef NDEBUG
2120   CmdArgs.push_back("-disable-llvm-verifier");
2121 #endif
2122
2123   // Set the main file name, so that debug info works even with
2124   // -save-temps.
2125   CmdArgs.push_back("-main-file-name");
2126   CmdArgs.push_back(getBaseInputName(Args, Inputs));
2127
2128   // Some flags which affect the language (via preprocessor
2129   // defines).
2130   if (Args.hasArg(options::OPT_static))
2131     CmdArgs.push_back("-static-define");
2132
2133   if (isa<AnalyzeJobAction>(JA)) {
2134     // Enable region store model by default.
2135     CmdArgs.push_back("-analyzer-store=region");
2136
2137     // Treat blocks as analysis entry points.
2138     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2139
2140     CmdArgs.push_back("-analyzer-eagerly-assume");
2141
2142     // Add default argument set.
2143     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2144       CmdArgs.push_back("-analyzer-checker=core");
2145
2146       if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
2147         CmdArgs.push_back("-analyzer-checker=unix");
2148
2149       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2150         CmdArgs.push_back("-analyzer-checker=osx");
2151       
2152       CmdArgs.push_back("-analyzer-checker=deadcode");
2153       
2154       if (types::isCXX(Inputs[0].getType()))
2155         CmdArgs.push_back("-analyzer-checker=cplusplus");
2156
2157       // Enable the following experimental checkers for testing. 
2158       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2159       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2160       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2161       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");      
2162       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2163       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2164     }
2165
2166     // Set the output format. The default is plist, for (lame) historical
2167     // reasons.
2168     CmdArgs.push_back("-analyzer-output");
2169     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2170       CmdArgs.push_back(A->getValue());
2171     else
2172       CmdArgs.push_back("plist");
2173
2174     // Disable the presentation of standard compiler warnings when
2175     // using --analyze.  We only want to show static analyzer diagnostics
2176     // or frontend errors.
2177     CmdArgs.push_back("-w");
2178
2179     // Add -Xanalyzer arguments when running as analyzer.
2180     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2181   }
2182
2183   CheckCodeGenerationOptions(D, Args);
2184
2185   bool PIE = getToolChain().isPIEDefault();
2186   bool PIC = PIE || getToolChain().isPICDefault();
2187   bool IsPICLevelTwo = PIC;
2188
2189   // For the PIC and PIE flag options, this logic is different from the
2190   // legacy logic in very old versions of GCC, as that logic was just
2191   // a bug no one had ever fixed. This logic is both more rational and
2192   // consistent with GCC's new logic now that the bugs are fixed. The last
2193   // argument relating to either PIC or PIE wins, and no other argument is
2194   // used. If the last argument is any flavor of the '-fno-...' arguments,
2195   // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
2196   // at the same level.
2197   Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
2198                                  options::OPT_fpic, options::OPT_fno_pic,
2199                                  options::OPT_fPIE, options::OPT_fno_PIE,
2200                                  options::OPT_fpie, options::OPT_fno_pie);
2201   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2202   // is forced, then neither PIC nor PIE flags will have no effect.
2203   if (!getToolChain().isPICDefaultForced()) {
2204     if (LastPICArg) {
2205       Option O = LastPICArg->getOption();
2206       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
2207           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
2208         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
2209         PIC = PIE || O.matches(options::OPT_fPIC) ||
2210               O.matches(options::OPT_fpic);
2211         IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
2212                         O.matches(options::OPT_fPIC);
2213       } else {
2214         PIE = PIC = false;
2215       }
2216     }
2217   }
2218
2219   // Introduce a Darwin-specific hack. If the default is PIC but the flags
2220   // specified while enabling PIC enabled level 1 PIC, just force it back to
2221   // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
2222   // informal testing).
2223   if (PIC && getToolChain().getTriple().isOSDarwin())
2224     IsPICLevelTwo |= getToolChain().isPICDefault();
2225
2226   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
2227   // PIC or PIE options above, if these show up, PIC is disabled.
2228   llvm::Triple Triple(TripleStr);
2229   if (KernelOrKext &&
2230       (!Triple.isiOS() || Triple.isOSVersionLT(6)))
2231     PIC = PIE = false;
2232   if (Args.hasArg(options::OPT_static))
2233     PIC = PIE = false;
2234
2235   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
2236     // This is a very special mode. It trumps the other modes, almost no one
2237     // uses it, and it isn't even valid on any OS but Darwin.
2238     if (!getToolChain().getTriple().isOSDarwin())
2239       D.Diag(diag::err_drv_unsupported_opt_for_target)
2240         << A->getSpelling() << getToolChain().getTriple().str();
2241
2242     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
2243
2244     CmdArgs.push_back("-mrelocation-model");
2245     CmdArgs.push_back("dynamic-no-pic");
2246
2247     // Only a forced PIC mode can cause the actual compile to have PIC defines
2248     // etc., no flags are sufficient. This behavior was selected to closely
2249     // match that of llvm-gcc and Apple GCC before that.
2250     if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
2251       CmdArgs.push_back("-pic-level");
2252       CmdArgs.push_back("2");
2253     }
2254   } else {
2255     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
2256     // handled in Clang's IRGen by the -pie-level flag.
2257     CmdArgs.push_back("-mrelocation-model");
2258     CmdArgs.push_back(PIC ? "pic" : "static");
2259
2260     if (PIC) {
2261       CmdArgs.push_back("-pic-level");
2262       CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2263       if (PIE) {
2264         CmdArgs.push_back("-pie-level");
2265         CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2266       }
2267     }
2268   }
2269
2270   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2271                     options::OPT_fno_merge_all_constants))
2272     CmdArgs.push_back("-fno-merge-all-constants");
2273
2274   // LLVM Code Generator Options.
2275
2276   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2277     CmdArgs.push_back("-mregparm");
2278     CmdArgs.push_back(A->getValue());
2279   }
2280
2281   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2282                                options::OPT_freg_struct_return)) {
2283     if (getToolChain().getArch() != llvm::Triple::x86) {
2284       D.Diag(diag::err_drv_unsupported_opt_for_target)
2285         << A->getSpelling() << getToolChain().getTriple().str();
2286     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2287       CmdArgs.push_back("-fpcc-struct-return");
2288     } else {
2289       assert(A->getOption().matches(options::OPT_freg_struct_return));
2290       CmdArgs.push_back("-freg-struct-return");
2291     }
2292   }
2293
2294   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2295     CmdArgs.push_back("-mrtd");
2296
2297   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2298     CmdArgs.push_back("-mdisable-fp-elim");
2299   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2300                     options::OPT_fno_zero_initialized_in_bss))
2301     CmdArgs.push_back("-mno-zero-initialized-in-bss");
2302
2303   bool OFastEnabled = isOptimizationLevelFast(Args);
2304   // If -Ofast is the optimization level, then -fstrict-aliasing should be
2305   // enabled.  This alias option is being used to simplify the hasFlag logic.
2306   OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
2307     options::OPT_fstrict_aliasing;
2308   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2309                     options::OPT_fno_strict_aliasing, true))
2310     CmdArgs.push_back("-relaxed-aliasing");
2311   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2312                     options::OPT_fno_struct_path_tbaa))
2313     CmdArgs.push_back("-no-struct-path-tbaa");
2314   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2315                    false))
2316     CmdArgs.push_back("-fstrict-enums");
2317   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2318                     options::OPT_fno_optimize_sibling_calls))
2319     CmdArgs.push_back("-mdisable-tail-calls");
2320
2321   // Handle segmented stacks.
2322   if (Args.hasArg(options::OPT_fsplit_stack))
2323     CmdArgs.push_back("-split-stacks");
2324
2325   // If -Ofast is the optimization level, then -ffast-math should be enabled.
2326   // This alias option is being used to simplify the getLastArg logic.
2327   OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
2328     options::OPT_ffast_math;
2329   
2330   // Handle various floating point optimization flags, mapping them to the
2331   // appropriate LLVM code generation flags. The pattern for all of these is to
2332   // default off the codegen optimizations, and if any flag enables them and no
2333   // flag disables them after the flag enabling them, enable the codegen
2334   // optimization. This is complicated by several "umbrella" flags.
2335   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2336                                options::OPT_fno_fast_math,
2337                                options::OPT_ffinite_math_only,
2338                                options::OPT_fno_finite_math_only,
2339                                options::OPT_fhonor_infinities,
2340                                options::OPT_fno_honor_infinities))
2341     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2342         A->getOption().getID() != options::OPT_fno_finite_math_only &&
2343         A->getOption().getID() != options::OPT_fhonor_infinities)
2344       CmdArgs.push_back("-menable-no-infs");
2345   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2346                                options::OPT_fno_fast_math,
2347                                options::OPT_ffinite_math_only,
2348                                options::OPT_fno_finite_math_only,
2349                                options::OPT_fhonor_nans,
2350                                options::OPT_fno_honor_nans))
2351     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2352         A->getOption().getID() != options::OPT_fno_finite_math_only &&
2353         A->getOption().getID() != options::OPT_fhonor_nans)
2354       CmdArgs.push_back("-menable-no-nans");
2355
2356   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2357   bool MathErrno = getToolChain().IsMathErrnoDefault();
2358   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2359                                options::OPT_fno_fast_math,
2360                                options::OPT_fmath_errno,
2361                                options::OPT_fno_math_errno)) {
2362     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
2363     // However, turning *off* -ffast_math merely restores the toolchain default
2364     // (which may be false).
2365     if (A->getOption().getID() == options::OPT_fno_math_errno ||
2366         A->getOption().getID() == options::OPT_ffast_math ||
2367         A->getOption().getID() == options::OPT_Ofast)
2368       MathErrno = false;
2369     else if (A->getOption().getID() == options::OPT_fmath_errno)
2370       MathErrno = true;
2371   }
2372   if (MathErrno)
2373     CmdArgs.push_back("-fmath-errno");
2374
2375   // There are several flags which require disabling very specific
2376   // optimizations. Any of these being disabled forces us to turn off the
2377   // entire set of LLVM optimizations, so collect them through all the flag
2378   // madness.
2379   bool AssociativeMath = false;
2380   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2381                                options::OPT_fno_fast_math,
2382                                options::OPT_funsafe_math_optimizations,
2383                                options::OPT_fno_unsafe_math_optimizations,
2384                                options::OPT_fassociative_math,
2385                                options::OPT_fno_associative_math))
2386     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2387         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2388         A->getOption().getID() != options::OPT_fno_associative_math)
2389       AssociativeMath = true;
2390   bool ReciprocalMath = false;
2391   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2392                                options::OPT_fno_fast_math,
2393                                options::OPT_funsafe_math_optimizations,
2394                                options::OPT_fno_unsafe_math_optimizations,
2395                                options::OPT_freciprocal_math,
2396                                options::OPT_fno_reciprocal_math))
2397     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2398         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2399         A->getOption().getID() != options::OPT_fno_reciprocal_math)
2400       ReciprocalMath = true;
2401   bool SignedZeros = true;
2402   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2403                                options::OPT_fno_fast_math,
2404                                options::OPT_funsafe_math_optimizations,
2405                                options::OPT_fno_unsafe_math_optimizations,
2406                                options::OPT_fsigned_zeros,
2407                                options::OPT_fno_signed_zeros))
2408     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2409         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2410         A->getOption().getID() != options::OPT_fsigned_zeros)
2411       SignedZeros = false;
2412   bool TrappingMath = true;
2413   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2414                                options::OPT_fno_fast_math,
2415                                options::OPT_funsafe_math_optimizations,
2416                                options::OPT_fno_unsafe_math_optimizations,
2417                                options::OPT_ftrapping_math,
2418                                options::OPT_fno_trapping_math))
2419     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2420         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2421         A->getOption().getID() != options::OPT_ftrapping_math)
2422       TrappingMath = false;
2423   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2424       !TrappingMath)
2425     CmdArgs.push_back("-menable-unsafe-fp-math");
2426
2427
2428   // Validate and pass through -fp-contract option. 
2429   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2430                                options::OPT_fno_fast_math,
2431                                options::OPT_ffp_contract)) {
2432     if (A->getOption().getID() == options::OPT_ffp_contract) {
2433       StringRef Val = A->getValue();
2434       if (Val == "fast" || Val == "on" || Val == "off") {
2435         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
2436       } else {
2437         D.Diag(diag::err_drv_unsupported_option_argument)
2438           << A->getOption().getName() << Val;
2439       }
2440     } else if (A->getOption().matches(options::OPT_ffast_math) ||
2441                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
2442       // If fast-math is set then set the fp-contract mode to fast.
2443       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2444     }
2445   }
2446
2447   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
2448   // and if we find them, tell the frontend to provide the appropriate
2449   // preprocessor macros. This is distinct from enabling any optimizations as
2450   // these options induce language changes which must survive serialization
2451   // and deserialization, etc.
2452   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2453                                options::OPT_fno_fast_math))
2454       if (!A->getOption().matches(options::OPT_fno_fast_math))
2455         CmdArgs.push_back("-ffast-math");
2456   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only, options::OPT_fno_fast_math))
2457     if (A->getOption().matches(options::OPT_ffinite_math_only))
2458       CmdArgs.push_back("-ffinite-math-only");
2459
2460   // Decide whether to use verbose asm. Verbose assembly is the default on
2461   // toolchains which have the integrated assembler on by default.
2462   bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
2463   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2464                    IsVerboseAsmDefault) ||
2465       Args.hasArg(options::OPT_dA))
2466     CmdArgs.push_back("-masm-verbose");
2467
2468   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2469     CmdArgs.push_back("-mdebug-pass");
2470     CmdArgs.push_back("Structure");
2471   }
2472   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2473     CmdArgs.push_back("-mdebug-pass");
2474     CmdArgs.push_back("Arguments");
2475   }
2476
2477   // Enable -mconstructor-aliases except on darwin, where we have to
2478   // work around a linker bug;  see <rdar://problem/7651567>.
2479   if (!getToolChain().getTriple().isOSDarwin())
2480     CmdArgs.push_back("-mconstructor-aliases");
2481
2482   // Darwin's kernel doesn't support guard variables; just die if we
2483   // try to use them.
2484   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2485     CmdArgs.push_back("-fforbid-guard-variables");
2486
2487   if (Args.hasArg(options::OPT_mms_bitfields)) {
2488     CmdArgs.push_back("-mms-bitfields");
2489   }
2490
2491   // This is a coarse approximation of what llvm-gcc actually does, both
2492   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2493   // complicated ways.
2494   bool AsynchronousUnwindTables =
2495     Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2496                  options::OPT_fno_asynchronous_unwind_tables,
2497                  getToolChain().IsUnwindTablesDefault() &&
2498                  !KernelOrKext);
2499   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2500                    AsynchronousUnwindTables))
2501     CmdArgs.push_back("-munwind-tables");
2502
2503   getToolChain().addClangTargetOptions(Args, CmdArgs);
2504
2505   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2506     CmdArgs.push_back("-mlimit-float-precision");
2507     CmdArgs.push_back(A->getValue());
2508   }
2509
2510   // FIXME: Handle -mtune=.
2511   (void) Args.hasArg(options::OPT_mtune_EQ);
2512
2513   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2514     CmdArgs.push_back("-mcode-model");
2515     CmdArgs.push_back(A->getValue());
2516   }
2517
2518   // Add the target cpu
2519   std::string ETripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2520   llvm::Triple ETriple(ETripleStr);
2521   std::string CPU = getCPUName(Args, ETriple);
2522   if (!CPU.empty()) {
2523     CmdArgs.push_back("-target-cpu");
2524     CmdArgs.push_back(Args.MakeArgString(CPU));
2525   }
2526
2527   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2528     CmdArgs.push_back("-mfpmath");
2529     CmdArgs.push_back(A->getValue());
2530   }
2531
2532   // Add the target features
2533   getTargetFeatures(D, ETriple, Args, CmdArgs);
2534
2535   // Add target specific flags.
2536   switch(getToolChain().getArch()) {
2537   default:
2538     break;
2539
2540   case llvm::Triple::arm:
2541   case llvm::Triple::thumb:
2542     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
2543     break;
2544
2545   case llvm::Triple::mips:
2546   case llvm::Triple::mipsel:
2547   case llvm::Triple::mips64:
2548   case llvm::Triple::mips64el:
2549     AddMIPSTargetArgs(Args, CmdArgs);
2550     break;
2551
2552   case llvm::Triple::sparc:
2553     AddSparcTargetArgs(Args, CmdArgs);
2554     break;
2555
2556   case llvm::Triple::x86:
2557   case llvm::Triple::x86_64:
2558     AddX86TargetArgs(Args, CmdArgs);
2559     break;
2560
2561   case llvm::Triple::hexagon:
2562     AddHexagonTargetArgs(Args, CmdArgs);
2563     break;
2564   }
2565
2566   // Add clang-cl arguments.
2567   if (getToolChain().getDriver().IsCLMode())
2568     AddClangCLArgs(Args, CmdArgs);
2569
2570   // Pass the linker version in use.
2571   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2572     CmdArgs.push_back("-target-linker-version");
2573     CmdArgs.push_back(A->getValue());
2574   }
2575
2576   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
2577     CmdArgs.push_back("-momit-leaf-frame-pointer");
2578
2579   // Explicitly error on some things we know we don't support and can't just
2580   // ignore.
2581   types::ID InputType = Inputs[0].getType();
2582   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2583     Arg *Unsupported;
2584     if (types::isCXX(InputType) &&
2585         getToolChain().getTriple().isOSDarwin() &&
2586         getToolChain().getArch() == llvm::Triple::x86) {
2587       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2588           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2589         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2590           << Unsupported->getOption().getName();
2591     }
2592   }
2593
2594   Args.AddAllArgs(CmdArgs, options::OPT_v);
2595   Args.AddLastArg(CmdArgs, options::OPT_H);
2596   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2597     CmdArgs.push_back("-header-include-file");
2598     CmdArgs.push_back(D.CCPrintHeadersFilename ?
2599                       D.CCPrintHeadersFilename : "-");
2600   }
2601   Args.AddLastArg(CmdArgs, options::OPT_P);
2602   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2603
2604   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2605     CmdArgs.push_back("-diagnostic-log-file");
2606     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
2607                       D.CCLogDiagnosticsFilename : "-");
2608   }
2609
2610   // Use the last option from "-g" group. "-gline-tables-only"
2611   // is preserved, all other debug options are substituted with "-g".
2612   Args.ClaimAllArgs(options::OPT_g_Group);
2613   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2614     if (A->getOption().matches(options::OPT_gline_tables_only))
2615       CmdArgs.push_back("-gline-tables-only");
2616     else if (A->getOption().matches(options::OPT_gdwarf_2))
2617       CmdArgs.push_back("-gdwarf-2");
2618     else if (A->getOption().matches(options::OPT_gdwarf_3))
2619       CmdArgs.push_back("-gdwarf-3");
2620     else if (A->getOption().matches(options::OPT_gdwarf_4))
2621       CmdArgs.push_back("-gdwarf-4");
2622     else if (!A->getOption().matches(options::OPT_g0) &&
2623              !A->getOption().matches(options::OPT_ggdb0)) {
2624       // Default is dwarf-2 for darwin and FreeBSD.
2625       const llvm::Triple &Triple = getToolChain().getTriple();
2626       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::FreeBSD)
2627         CmdArgs.push_back("-gdwarf-2");
2628       else
2629         CmdArgs.push_back("-g");
2630     }
2631   }
2632
2633   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
2634   Args.ClaimAllArgs(options::OPT_g_flags_Group);
2635   if (Args.hasArg(options::OPT_gcolumn_info))
2636     CmdArgs.push_back("-dwarf-column-info");
2637
2638   // FIXME: Move backend command line options to the module.
2639   // -gsplit-dwarf should turn on -g and enable the backend dwarf
2640   // splitting and extraction.
2641   // FIXME: Currently only works on Linux.
2642   if (getToolChain().getTriple().isOSLinux() &&
2643       Args.hasArg(options::OPT_gsplit_dwarf)) {
2644     CmdArgs.push_back("-g");
2645     CmdArgs.push_back("-backend-option");
2646     CmdArgs.push_back("-split-dwarf=Enable");
2647   }
2648
2649   // -ggnu-pubnames turns on gnu style pubnames in the backend.
2650   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2651     CmdArgs.push_back("-backend-option");
2652     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2653   }
2654
2655   Args.AddAllArgs(CmdArgs, options::OPT_fdebug_types_section);
2656
2657   Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
2658   Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
2659
2660   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2661
2662   if (Args.hasArg(options::OPT_ftest_coverage) ||
2663       Args.hasArg(options::OPT_coverage))
2664     CmdArgs.push_back("-femit-coverage-notes");
2665   if (Args.hasArg(options::OPT_fprofile_arcs) ||
2666       Args.hasArg(options::OPT_coverage))
2667     CmdArgs.push_back("-femit-coverage-data");
2668
2669   if (C.getArgs().hasArg(options::OPT_c) ||
2670       C.getArgs().hasArg(options::OPT_S)) {
2671     if (Output.isFilename()) {
2672       CmdArgs.push_back("-coverage-file");
2673       SmallString<128> CoverageFilename(Output.getFilename());
2674       if (llvm::sys::path::is_relative(CoverageFilename.str())) {
2675         SmallString<128> Pwd;
2676         if (!llvm::sys::fs::current_path(Pwd)) {
2677           llvm::sys::path::append(Pwd, CoverageFilename.str());
2678           CoverageFilename.swap(Pwd);
2679         }
2680       }
2681       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
2682     }
2683   }
2684
2685   // Pass options for controlling the default header search paths.
2686   if (Args.hasArg(options::OPT_nostdinc)) {
2687     CmdArgs.push_back("-nostdsysteminc");
2688     CmdArgs.push_back("-nobuiltininc");
2689   } else {
2690     if (Args.hasArg(options::OPT_nostdlibinc))
2691         CmdArgs.push_back("-nostdsysteminc");
2692     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2693     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2694   }
2695
2696   // Pass the path to compiler resource files.
2697   CmdArgs.push_back("-resource-dir");
2698   CmdArgs.push_back(D.ResourceDir.c_str());
2699
2700   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2701
2702   bool ARCMTEnabled = false;
2703   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2704     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2705                                        options::OPT_ccc_arcmt_modify,
2706                                        options::OPT_ccc_arcmt_migrate)) {
2707       ARCMTEnabled = true;
2708       switch (A->getOption().getID()) {
2709       default:
2710         llvm_unreachable("missed a case");
2711       case options::OPT_ccc_arcmt_check:
2712         CmdArgs.push_back("-arcmt-check");
2713         break;
2714       case options::OPT_ccc_arcmt_modify:
2715         CmdArgs.push_back("-arcmt-modify");
2716         break;
2717       case options::OPT_ccc_arcmt_migrate:
2718         CmdArgs.push_back("-arcmt-migrate");
2719         CmdArgs.push_back("-mt-migrate-directory");
2720         CmdArgs.push_back(A->getValue());
2721
2722         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2723         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2724         break;
2725       }
2726     }
2727   } else {
2728     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2729     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2730     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2731   }
2732
2733   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2734     if (ARCMTEnabled) {
2735       D.Diag(diag::err_drv_argument_not_allowed_with)
2736         << A->getAsString(Args) << "-ccc-arcmt-migrate";
2737     }
2738     CmdArgs.push_back("-mt-migrate-directory");
2739     CmdArgs.push_back(A->getValue());
2740
2741     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2742                      options::OPT_objcmt_migrate_subscripting,
2743                      options::OPT_objcmt_migrate_property)) {
2744       // None specified, means enable them all.
2745       CmdArgs.push_back("-objcmt-migrate-literals");
2746       CmdArgs.push_back("-objcmt-migrate-subscripting");
2747       CmdArgs.push_back("-objcmt-migrate-property");
2748     } else {
2749       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2750       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2751       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2752     }
2753   } else {
2754     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2755     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2756     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2757     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2758     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2759     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2760     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2761     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2762     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2763     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2764     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2765     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2766     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2767     Args.AddLastArg(CmdArgs, options::OPT_objcmt_white_list_dir_path);
2768   }
2769
2770   // Add preprocessing options like -I, -D, etc. if we are using the
2771   // preprocessor.
2772   //
2773   // FIXME: Support -fpreprocessed
2774   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2775     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
2776
2777   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2778   // that "The compiler can only warn and ignore the option if not recognized".
2779   // When building with ccache, it will pass -D options to clang even on
2780   // preprocessed inputs and configure concludes that -fPIC is not supported.
2781   Args.ClaimAllArgs(options::OPT_D);
2782
2783   // Manually translate -O4 to -O3; let clang reject others.
2784   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2785     if (A->getOption().matches(options::OPT_O4)) {
2786       CmdArgs.push_back("-O3");
2787       D.Diag(diag::warn_O4_is_O3);
2788     } else {
2789       A->render(Args, CmdArgs);
2790     }
2791   }
2792
2793   // Don't warn about unused -flto.  This can happen when we're preprocessing or
2794   // precompiling.
2795   Args.ClaimAllArgs(options::OPT_flto);
2796
2797   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2798   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2799     CmdArgs.push_back("-pedantic");
2800   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2801   Args.AddLastArg(CmdArgs, options::OPT_w);
2802
2803   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2804   // (-ansi is equivalent to -std=c89 or -std=c++98).
2805   //
2806   // If a std is supplied, only add -trigraphs if it follows the
2807   // option.
2808   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2809     if (Std->getOption().matches(options::OPT_ansi))
2810       if (types::isCXX(InputType))
2811         CmdArgs.push_back("-std=c++98");
2812       else
2813         CmdArgs.push_back("-std=c89");
2814     else
2815       Std->render(Args, CmdArgs);
2816
2817     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
2818                                  options::OPT_trigraphs))
2819       if (A != Std)
2820         A->render(Args, CmdArgs);
2821   } else {
2822     // Honor -std-default.
2823     //
2824     // FIXME: Clang doesn't correctly handle -std= when the input language
2825     // doesn't match. For the time being just ignore this for C++ inputs;
2826     // eventually we want to do all the standard defaulting here instead of
2827     // splitting it between the driver and clang -cc1.
2828     if (!types::isCXX(InputType))
2829       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2830                                 "-std=", /*Joined=*/true);
2831     else if (getToolChain().getTriple().getOS() == llvm::Triple::Win32)
2832       CmdArgs.push_back("-std=c++11");
2833
2834     Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
2835   }
2836
2837   // GCC's behavior for -Wwrite-strings is a bit strange:
2838   //  * In C, this "warning flag" changes the types of string literals from
2839   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
2840   //    for the discarded qualifier.
2841   //  * In C++, this is just a normal warning flag.
2842   //
2843   // Implementing this warning correctly in C is hard, so we follow GCC's
2844   // behavior for now. FIXME: Directly diagnose uses of a string literal as
2845   // a non-const char* in C, rather than using this crude hack.
2846   if (!types::isCXX(InputType)) {
2847     DiagnosticsEngine::Level DiagLevel = D.getDiags().getDiagnosticLevel(
2848         diag::warn_deprecated_string_literal_conversion_c, SourceLocation());
2849     if (DiagLevel > DiagnosticsEngine::Ignored)
2850       CmdArgs.push_back("-fconst-strings");
2851   }
2852
2853   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
2854   // during C++ compilation, which it is by default. GCC keeps this define even
2855   // in the presence of '-w', match this behavior bug-for-bug.
2856   if (types::isCXX(InputType) &&
2857       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
2858                    true)) {
2859     CmdArgs.push_back("-fdeprecated-macro");
2860   }
2861
2862   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
2863   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
2864     if (Asm->getOption().matches(options::OPT_fasm))
2865       CmdArgs.push_back("-fgnu-keywords");
2866     else
2867       CmdArgs.push_back("-fno-gnu-keywords");
2868   }
2869
2870   if (ShouldDisableCFI(Args, getToolChain()))
2871     CmdArgs.push_back("-fno-dwarf2-cfi-asm");
2872
2873   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
2874     CmdArgs.push_back("-fno-dwarf-directory-asm");
2875
2876   if (ShouldDisableAutolink(Args, getToolChain()))
2877     CmdArgs.push_back("-fno-autolink");
2878
2879   // Add in -fdebug-compilation-dir if necessary.
2880   addDebugCompDirArg(Args, CmdArgs);
2881
2882   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
2883                                options::OPT_ftemplate_depth_EQ)) {
2884     CmdArgs.push_back("-ftemplate-depth");
2885     CmdArgs.push_back(A->getValue());
2886   }
2887
2888   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
2889     CmdArgs.push_back("-foperator-arrow-depth");
2890     CmdArgs.push_back(A->getValue());
2891   }
2892
2893   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
2894     CmdArgs.push_back("-fconstexpr-depth");
2895     CmdArgs.push_back(A->getValue());
2896   }
2897
2898   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
2899     CmdArgs.push_back("-fconstexpr-steps");
2900     CmdArgs.push_back(A->getValue());
2901   }
2902
2903   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
2904     CmdArgs.push_back("-fbracket-depth");
2905     CmdArgs.push_back(A->getValue());
2906   }
2907
2908   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
2909                                options::OPT_Wlarge_by_value_copy_def)) {
2910     if (A->getNumValues()) {
2911       StringRef bytes = A->getValue();
2912       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
2913     } else
2914       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
2915   }
2916
2917
2918   if (Args.hasArg(options::OPT_relocatable_pch))
2919     CmdArgs.push_back("-relocatable-pch");
2920
2921   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
2922     CmdArgs.push_back("-fconstant-string-class");
2923     CmdArgs.push_back(A->getValue());
2924   }
2925
2926   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
2927     CmdArgs.push_back("-ftabstop");
2928     CmdArgs.push_back(A->getValue());
2929   }
2930
2931   CmdArgs.push_back("-ferror-limit");
2932   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
2933     CmdArgs.push_back(A->getValue());
2934   else
2935     CmdArgs.push_back("19");
2936
2937   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
2938     CmdArgs.push_back("-fmacro-backtrace-limit");
2939     CmdArgs.push_back(A->getValue());
2940   }
2941
2942   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
2943     CmdArgs.push_back("-ftemplate-backtrace-limit");
2944     CmdArgs.push_back(A->getValue());
2945   }
2946
2947   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
2948     CmdArgs.push_back("-fconstexpr-backtrace-limit");
2949     CmdArgs.push_back(A->getValue());
2950   }
2951
2952   // Pass -fmessage-length=.
2953   CmdArgs.push_back("-fmessage-length");
2954   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
2955     CmdArgs.push_back(A->getValue());
2956   } else {
2957     // If -fmessage-length=N was not specified, determine whether this is a
2958     // terminal and, if so, implicitly define -fmessage-length appropriately.
2959     unsigned N = llvm::sys::Process::StandardErrColumns();
2960     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
2961   }
2962
2963   // -fvisibility= and -fvisibility-ms-compat are of a piece.
2964   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
2965                                      options::OPT_fvisibility_ms_compat)) {
2966     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
2967       CmdArgs.push_back("-fvisibility");
2968       CmdArgs.push_back(A->getValue());
2969     } else {
2970       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
2971       CmdArgs.push_back("-fvisibility");
2972       CmdArgs.push_back("hidden");
2973       CmdArgs.push_back("-ftype-visibility");
2974       CmdArgs.push_back("default");
2975     }
2976   }
2977
2978   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
2979
2980   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
2981
2982   // -fhosted is default.
2983   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
2984       KernelOrKext)
2985     CmdArgs.push_back("-ffreestanding");
2986
2987   // Forward -f (flag) options which we can pass directly.
2988   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
2989   Args.AddLastArg(CmdArgs, options::OPT_fformat_extensions);
2990   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
2991   Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
2992   Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
2993   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
2994   // AltiVec language extensions aren't relevant for assembling.
2995   if (!isa<PreprocessJobAction>(JA) || 
2996       Output.getType() != types::TY_PP_Asm)
2997     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
2998   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
2999   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3000
3001   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3002   Sanitize.addArgs(Args, CmdArgs);
3003
3004   if (!Args.hasFlag(options::OPT_fsanitize_recover,
3005                     options::OPT_fno_sanitize_recover,
3006                     true))
3007     CmdArgs.push_back("-fno-sanitize-recover");
3008
3009   if (Args.hasArg(options::OPT_fcatch_undefined_behavior) ||
3010       Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
3011                    options::OPT_fno_sanitize_undefined_trap_on_error, false))
3012     CmdArgs.push_back("-fsanitize-undefined-trap-on-error");
3013
3014   // Report an error for -faltivec on anything other than PowerPC.
3015   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
3016     if (!(getToolChain().getArch() == llvm::Triple::ppc ||
3017           getToolChain().getArch() == llvm::Triple::ppc64 ||
3018           getToolChain().getArch() == llvm::Triple::ppc64le))
3019       D.Diag(diag::err_drv_argument_only_allowed_with)
3020         << A->getAsString(Args) << "ppc/ppc64/ppc64le";
3021
3022   if (getToolChain().SupportsProfiling())
3023     Args.AddLastArg(CmdArgs, options::OPT_pg);
3024
3025   // -flax-vector-conversions is default.
3026   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3027                     options::OPT_fno_lax_vector_conversions))
3028     CmdArgs.push_back("-fno-lax-vector-conversions");
3029
3030   if (Args.getLastArg(options::OPT_fapple_kext))
3031     CmdArgs.push_back("-fapple-kext");
3032
3033   if (Args.hasFlag(options::OPT_frewrite_includes,
3034                    options::OPT_fno_rewrite_includes, false))
3035     CmdArgs.push_back("-frewrite-includes");
3036
3037   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3038   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3039   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3040   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3041   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3042
3043   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3044     CmdArgs.push_back("-ftrapv-handler");
3045     CmdArgs.push_back(A->getValue());
3046   }
3047
3048   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3049
3050   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3051   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3052   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
3053                                options::OPT_fno_wrapv)) {
3054     if (A->getOption().matches(options::OPT_fwrapv))
3055       CmdArgs.push_back("-fwrapv");
3056   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3057                                       options::OPT_fno_strict_overflow)) {
3058     if (A->getOption().matches(options::OPT_fno_strict_overflow))
3059       CmdArgs.push_back("-fwrapv");
3060   }
3061
3062   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3063                                options::OPT_fno_reroll_loops))
3064     if (A->getOption().matches(options::OPT_freroll_loops))
3065       CmdArgs.push_back("-freroll-loops");
3066
3067   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3068   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3069                   options::OPT_fno_unroll_loops);
3070
3071   Args.AddLastArg(CmdArgs, options::OPT_pthread);
3072
3073
3074   // -stack-protector=0 is default.
3075   unsigned StackProtectorLevel = 0;
3076   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3077                                options::OPT_fstack_protector_all,
3078                                options::OPT_fstack_protector)) {
3079     if (A->getOption().matches(options::OPT_fstack_protector))
3080       StackProtectorLevel = 1;
3081     else if (A->getOption().matches(options::OPT_fstack_protector_all))
3082       StackProtectorLevel = 2;
3083   } else {
3084     StackProtectorLevel =
3085       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3086   }
3087   if (StackProtectorLevel) {
3088     CmdArgs.push_back("-stack-protector");
3089     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3090   }
3091
3092   // --param ssp-buffer-size=
3093   for (arg_iterator it = Args.filtered_begin(options::OPT__param),
3094        ie = Args.filtered_end(); it != ie; ++it) {
3095     StringRef Str((*it)->getValue());
3096     if (Str.startswith("ssp-buffer-size=")) {
3097       if (StackProtectorLevel) {
3098         CmdArgs.push_back("-stack-protector-buffer-size");
3099         // FIXME: Verify the argument is a valid integer.
3100         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3101       }
3102       (*it)->claim();
3103     }
3104   }
3105
3106   // Translate -mstackrealign
3107   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3108                    false)) {
3109     CmdArgs.push_back("-backend-option");
3110     CmdArgs.push_back("-force-align-stack");
3111   }
3112   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
3113                    false)) {
3114     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3115   }
3116
3117   if (Args.hasArg(options::OPT_mstack_alignment)) {
3118     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3119     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3120   }
3121   // -mkernel implies -mstrict-align; don't add the redundant option.
3122   if (!KernelOrKext) {
3123     if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
3124                                  options::OPT_munaligned_access)) {
3125       if (A->getOption().matches(options::OPT_mno_unaligned_access)) {
3126         CmdArgs.push_back("-backend-option");
3127         CmdArgs.push_back("-arm-strict-align");
3128       } else {
3129         CmdArgs.push_back("-backend-option");
3130         CmdArgs.push_back("-arm-no-strict-align");
3131       }
3132     }
3133   }
3134
3135   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3136                                options::OPT_mno_restrict_it)) {
3137     if (A->getOption().matches(options::OPT_mrestrict_it)) {
3138       CmdArgs.push_back("-backend-option");
3139       CmdArgs.push_back("-arm-restrict-it");
3140     } else {
3141       CmdArgs.push_back("-backend-option");
3142       CmdArgs.push_back("-arm-no-restrict-it");
3143     }
3144   }
3145
3146   // Forward -f options with positive and negative forms; we translate
3147   // these by hand.
3148   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
3149     StringRef fname = A->getValue();
3150     if (!llvm::sys::fs::exists(fname))
3151       D.Diag(diag::err_drv_no_such_file) << fname;
3152     else
3153       A->render(Args, CmdArgs);
3154   }
3155
3156   if (Args.hasArg(options::OPT_mkernel)) {
3157     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
3158       CmdArgs.push_back("-fapple-kext");
3159     if (!Args.hasArg(options::OPT_fbuiltin))
3160       CmdArgs.push_back("-fno-builtin");
3161     Args.ClaimAllArgs(options::OPT_fno_builtin);
3162   }
3163   // -fbuiltin is default.
3164   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
3165     CmdArgs.push_back("-fno-builtin");
3166
3167   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3168                     options::OPT_fno_assume_sane_operator_new))
3169     CmdArgs.push_back("-fno-assume-sane-operator-new");
3170
3171   // -fblocks=0 is default.
3172   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3173                    getToolChain().IsBlocksDefault()) ||
3174         (Args.hasArg(options::OPT_fgnu_runtime) &&
3175          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3176          !Args.hasArg(options::OPT_fno_blocks))) {
3177     CmdArgs.push_back("-fblocks");
3178
3179     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
3180         !getToolChain().hasBlocksRuntime())
3181       CmdArgs.push_back("-fblocks-runtime-optional");
3182   }
3183
3184   // -fmodules enables modules (off by default). However, for C++/Objective-C++,
3185   // users must also pass -fcxx-modules. The latter flag will disappear once the
3186   // modules implementation is solid for C++/Objective-C++ programs as well.
3187   bool HaveModules = false;
3188   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3189     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
3190                                      options::OPT_fno_cxx_modules, 
3191                                      false);
3192     if (AllowedInCXX || !types::isCXX(InputType)) {
3193       CmdArgs.push_back("-fmodules");
3194       HaveModules = true;
3195     }
3196   }
3197
3198   // -fmodule-maps enables module map processing (off by default) for header
3199   // checking.  It is implied by -fmodules.
3200   if (Args.hasFlag(options::OPT_fmodule_maps, options::OPT_fno_module_maps,
3201                    false)) {
3202     CmdArgs.push_back("-fmodule-maps");
3203   }
3204
3205   // -fmodules-decluse checks that modules used are declared so (off by
3206   // default).
3207   if (Args.hasFlag(options::OPT_fmodules_decluse,
3208                    options::OPT_fno_modules_decluse,
3209                    false)) {
3210     CmdArgs.push_back("-fmodules-decluse");
3211   }
3212
3213   // -fmodule-name specifies the module that is currently being built (or
3214   // used for header checking by -fmodule-maps).
3215   if (Arg *A = Args.getLastArg(options::OPT_fmodule_name)) {
3216     A->claim();
3217     A->render(Args, CmdArgs);
3218   }
3219
3220   // -fmodule-map-file can be used to specify a file containing module
3221   // definitions.
3222   if (Arg *A = Args.getLastArg(options::OPT_fmodule_map_file)) {
3223     A->claim();
3224     A->render(Args, CmdArgs);
3225   }
3226
3227   // If a module path was provided, pass it along. Otherwise, use a temporary
3228   // directory.
3229   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path)) {
3230     A->claim();
3231     if (HaveModules) {
3232       A->render(Args, CmdArgs);
3233     }
3234   } else if (HaveModules) {
3235     SmallString<128> DefaultModuleCache;
3236     llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
3237                                            DefaultModuleCache);
3238     llvm::sys::path::append(DefaultModuleCache, "org.llvm.clang");
3239     llvm::sys::path::append(DefaultModuleCache, "ModuleCache");
3240     const char Arg[] = "-fmodules-cache-path=";
3241     DefaultModuleCache.insert(DefaultModuleCache.begin(),
3242                               Arg, Arg + strlen(Arg));
3243     CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache));
3244   }
3245
3246   // Pass through all -fmodules-ignore-macro arguments.
3247   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3248   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3249   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3250
3251   // -faccess-control is default.
3252   if (Args.hasFlag(options::OPT_fno_access_control,
3253                    options::OPT_faccess_control,
3254                    false))
3255     CmdArgs.push_back("-fno-access-control");
3256
3257   // -felide-constructors is the default.
3258   if (Args.hasFlag(options::OPT_fno_elide_constructors,
3259                    options::OPT_felide_constructors,
3260                    false))
3261     CmdArgs.push_back("-fno-elide-constructors");
3262
3263   // -frtti is default.
3264   if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
3265       KernelOrKext) {
3266     CmdArgs.push_back("-fno-rtti");
3267
3268     // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
3269     if (Sanitize.sanitizesVptr()) {
3270       std::string NoRttiArg =
3271         Args.getLastArg(options::OPT_mkernel,
3272                         options::OPT_fapple_kext,
3273                         options::OPT_fno_rtti)->getAsString(Args);
3274       D.Diag(diag::err_drv_argument_not_allowed_with)
3275         << "-fsanitize=vptr" << NoRttiArg;
3276     }
3277   }
3278
3279   // -fshort-enums=0 is default for all architectures except Hexagon.
3280   if (Args.hasFlag(options::OPT_fshort_enums,
3281                    options::OPT_fno_short_enums,
3282                    getToolChain().getArch() ==
3283                    llvm::Triple::hexagon))
3284     CmdArgs.push_back("-fshort-enums");
3285
3286   // -fsigned-char is default.
3287   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
3288                     isSignedCharDefault(getToolChain().getTriple())))
3289     CmdArgs.push_back("-fno-signed-char");
3290
3291   // -fthreadsafe-static is default.
3292   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3293                     options::OPT_fno_threadsafe_statics))
3294     CmdArgs.push_back("-fno-threadsafe-statics");
3295
3296   // -fuse-cxa-atexit is default.
3297   if (!Args.hasFlag(
3298            options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
3299            getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
3300                getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 &&
3301                getToolChain().getArch() != llvm::Triple::hexagon &&
3302                getToolChain().getArch() != llvm::Triple::xcore) ||
3303       KernelOrKext)
3304     CmdArgs.push_back("-fno-use-cxa-atexit");
3305
3306   // -fms-extensions=0 is default.
3307   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3308                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
3309     CmdArgs.push_back("-fms-extensions");
3310
3311   // -fms-compatibility=0 is default.
3312   if (Args.hasFlag(options::OPT_fms_compatibility, 
3313                    options::OPT_fno_ms_compatibility,
3314                    (getToolChain().getTriple().getOS() == llvm::Triple::Win32 &&
3315                     Args.hasFlag(options::OPT_fms_extensions, 
3316                                  options::OPT_fno_ms_extensions,
3317                                  true))))
3318     CmdArgs.push_back("-fms-compatibility");
3319
3320   // -fmsc-version=1700 is default.
3321   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3322                    getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
3323       Args.hasArg(options::OPT_fmsc_version)) {
3324     StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
3325     if (msc_ver.empty())
3326       CmdArgs.push_back("-fmsc-version=1700");
3327     else
3328       CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
3329   }
3330
3331
3332   // -fno-borland-extensions is default.
3333   if (Args.hasFlag(options::OPT_fborland_extensions,
3334                    options::OPT_fno_borland_extensions, false))
3335     CmdArgs.push_back("-fborland-extensions");
3336
3337   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3338   // needs it.
3339   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3340                    options::OPT_fno_delayed_template_parsing,
3341                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
3342     CmdArgs.push_back("-fdelayed-template-parsing");
3343
3344   // -fgnu-keywords default varies depending on language; only pass if
3345   // specified.
3346   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3347                                options::OPT_fno_gnu_keywords))
3348     A->render(Args, CmdArgs);
3349
3350   if (Args.hasFlag(options::OPT_fgnu89_inline,
3351                    options::OPT_fno_gnu89_inline,
3352                    false))
3353     CmdArgs.push_back("-fgnu89-inline");
3354
3355   if (Args.hasArg(options::OPT_fno_inline))
3356     CmdArgs.push_back("-fno-inline");
3357
3358   if (Args.hasArg(options::OPT_fno_inline_functions))
3359     CmdArgs.push_back("-fno-inline-functions");
3360
3361   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3362
3363   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3364   // legacy is the default. Next runtime is always legacy dispatch and
3365   // -fno-objc-legacy-dispatch gets ignored silently.
3366   if (objcRuntime.isNonFragile() && !objcRuntime.isNeXTFamily()) {
3367     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3368                       options::OPT_fno_objc_legacy_dispatch,
3369                       objcRuntime.isLegacyDispatchDefaultForArch(
3370                         getToolChain().getArch()))) {
3371       if (getToolChain().UseObjCMixedDispatch())
3372         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3373       else
3374         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3375     }
3376   }
3377
3378   // When ObjectiveC legacy runtime is in effect on MacOSX,
3379   // turn on the option to do Array/Dictionary subscripting
3380   // by default.
3381   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 &&
3382       getToolChain().getTriple().isMacOSX() &&
3383       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3384       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3385       objcRuntime.isNeXTFamily())
3386     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3387   
3388   // -fencode-extended-block-signature=1 is default.
3389   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3390     CmdArgs.push_back("-fencode-extended-block-signature");
3391   }
3392   
3393   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3394   // NOTE: This logic is duplicated in ToolChains.cpp.
3395   bool ARC = isObjCAutoRefCount(Args);
3396   if (ARC) {
3397     getToolChain().CheckObjCARC();
3398
3399     CmdArgs.push_back("-fobjc-arc");
3400
3401     // FIXME: It seems like this entire block, and several around it should be
3402     // wrapped in isObjC, but for now we just use it here as this is where it
3403     // was being used previously.
3404     if (types::isCXX(InputType) && types::isObjC(InputType)) {
3405       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3406         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3407       else
3408         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3409     }
3410
3411     // Allow the user to enable full exceptions code emission.
3412     // We define off for Objective-CC, on for Objective-C++.
3413     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3414                      options::OPT_fno_objc_arc_exceptions,
3415                      /*default*/ types::isCXX(InputType)))
3416       CmdArgs.push_back("-fobjc-arc-exceptions");
3417   }
3418
3419   // -fobjc-infer-related-result-type is the default, except in the Objective-C
3420   // rewriter.
3421   if (rewriteKind != RK_None)
3422     CmdArgs.push_back("-fno-objc-infer-related-result-type");
3423
3424   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
3425   // takes precedence.
3426   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
3427   if (!GCArg)
3428     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
3429   if (GCArg) {
3430     if (ARC) {
3431       D.Diag(diag::err_drv_objc_gc_arr)
3432         << GCArg->getAsString(Args);
3433     } else if (getToolChain().SupportsObjCGC()) {
3434       GCArg->render(Args, CmdArgs);
3435     } else {
3436       // FIXME: We should move this to a hard error.
3437       D.Diag(diag::warn_drv_objc_gc_unsupported)
3438         << GCArg->getAsString(Args);
3439     }
3440   }
3441
3442   // Add exception args.
3443   addExceptionArgs(Args, InputType, getToolChain().getTriple(),
3444                    KernelOrKext, objcRuntime, CmdArgs);
3445
3446   if (getToolChain().UseSjLjExceptions())
3447     CmdArgs.push_back("-fsjlj-exceptions");
3448
3449   // C++ "sane" operator new.
3450   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3451                     options::OPT_fno_assume_sane_operator_new))
3452     CmdArgs.push_back("-fno-assume-sane-operator-new");
3453
3454   // -fconstant-cfstrings is default, and may be subject to argument translation
3455   // on Darwin.
3456   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3457                     options::OPT_fno_constant_cfstrings) ||
3458       !Args.hasFlag(options::OPT_mconstant_cfstrings,
3459                     options::OPT_mno_constant_cfstrings))
3460     CmdArgs.push_back("-fno-constant-cfstrings");
3461
3462   // -fshort-wchar default varies depending on platform; only
3463   // pass if specified.
3464   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
3465     A->render(Args, CmdArgs);
3466
3467   // -fno-pascal-strings is default, only pass non-default.
3468   if (Args.hasFlag(options::OPT_fpascal_strings,
3469                    options::OPT_fno_pascal_strings,
3470                    false))
3471     CmdArgs.push_back("-fpascal-strings");
3472
3473   // Honor -fpack-struct= and -fpack-struct, if given. Note that
3474   // -fno-pack-struct doesn't apply to -fpack-struct=.
3475   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
3476     std::string PackStructStr = "-fpack-struct=";
3477     PackStructStr += A->getValue();
3478     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
3479   } else if (Args.hasFlag(options::OPT_fpack_struct,
3480                           options::OPT_fno_pack_struct, false)) {
3481     CmdArgs.push_back("-fpack-struct=1");
3482   }
3483
3484   if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
3485     if (!Args.hasArg(options::OPT_fcommon))
3486       CmdArgs.push_back("-fno-common");
3487     Args.ClaimAllArgs(options::OPT_fno_common);
3488   }
3489
3490   // -fcommon is default, only pass non-default.
3491   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
3492     CmdArgs.push_back("-fno-common");
3493
3494   // -fsigned-bitfields is default, and clang doesn't yet support
3495   // -funsigned-bitfields.
3496   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
3497                     options::OPT_funsigned_bitfields))
3498     D.Diag(diag::warn_drv_clang_unsupported)
3499       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
3500
3501   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
3502   if (!Args.hasFlag(options::OPT_ffor_scope,
3503                     options::OPT_fno_for_scope))
3504     D.Diag(diag::err_drv_clang_unsupported)
3505       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
3506
3507   // -fcaret-diagnostics is default.
3508   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3509                     options::OPT_fno_caret_diagnostics, true))
3510     CmdArgs.push_back("-fno-caret-diagnostics");
3511
3512   // -fdiagnostics-fixit-info is default, only pass non-default.
3513   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3514                     options::OPT_fno_diagnostics_fixit_info))
3515     CmdArgs.push_back("-fno-diagnostics-fixit-info");
3516
3517   // Enable -fdiagnostics-show-option by default.
3518   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3519                    options::OPT_fno_diagnostics_show_option))
3520     CmdArgs.push_back("-fdiagnostics-show-option");
3521
3522   if (const Arg *A =
3523         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3524     CmdArgs.push_back("-fdiagnostics-show-category");
3525     CmdArgs.push_back(A->getValue());
3526   }
3527
3528   if (const Arg *A =
3529         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3530     CmdArgs.push_back("-fdiagnostics-format");
3531     CmdArgs.push_back(A->getValue());
3532   }
3533
3534   if (Arg *A = Args.getLastArg(
3535       options::OPT_fdiagnostics_show_note_include_stack,
3536       options::OPT_fno_diagnostics_show_note_include_stack)) {
3537     if (A->getOption().matches(
3538         options::OPT_fdiagnostics_show_note_include_stack))
3539       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3540     else
3541       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3542   }
3543
3544   // Color diagnostics are the default, unless the terminal doesn't support
3545   // them.
3546   // Support both clang's -f[no-]color-diagnostics and gcc's
3547   // -f[no-]diagnostics-colors[=never|always|auto].
3548   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
3549   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
3550        it != ie; ++it) {
3551     const Option &O = (*it)->getOption();
3552     if (!O.matches(options::OPT_fcolor_diagnostics) &&
3553         !O.matches(options::OPT_fdiagnostics_color) &&
3554         !O.matches(options::OPT_fno_color_diagnostics) &&
3555         !O.matches(options::OPT_fno_diagnostics_color) &&
3556         !O.matches(options::OPT_fdiagnostics_color_EQ))
3557       continue;
3558
3559     (*it)->claim();
3560     if (O.matches(options::OPT_fcolor_diagnostics) ||
3561         O.matches(options::OPT_fdiagnostics_color)) {
3562       ShowColors = Colors_On;
3563     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
3564                O.matches(options::OPT_fno_diagnostics_color)) {
3565       ShowColors = Colors_Off;
3566     } else {
3567       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
3568       StringRef value((*it)->getValue());
3569       if (value == "always")
3570         ShowColors = Colors_On;
3571       else if (value == "never")
3572         ShowColors = Colors_Off;
3573       else if (value == "auto")
3574         ShowColors = Colors_Auto;
3575       else
3576         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3577           << ("-fdiagnostics-color=" + value).str();
3578     }
3579   }
3580   if (ShowColors == Colors_On ||
3581       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
3582     CmdArgs.push_back("-fcolor-diagnostics");
3583
3584   if (Args.hasArg(options::OPT_fansi_escape_codes))
3585     CmdArgs.push_back("-fansi-escape-codes");
3586
3587   if (!Args.hasFlag(options::OPT_fshow_source_location,
3588                     options::OPT_fno_show_source_location))
3589     CmdArgs.push_back("-fno-show-source-location");
3590
3591   if (!Args.hasFlag(options::OPT_fshow_column,
3592                     options::OPT_fno_show_column,
3593                     true))
3594     CmdArgs.push_back("-fno-show-column");
3595
3596   if (!Args.hasFlag(options::OPT_fspell_checking,
3597                     options::OPT_fno_spell_checking))
3598     CmdArgs.push_back("-fno-spell-checking");
3599
3600
3601   // -fno-asm-blocks is default.
3602   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
3603                    false))
3604     CmdArgs.push_back("-fasm-blocks");
3605
3606   // Enable vectorization per default according to the optimization level
3607   // selected. For optimization levels that want vectorization we use the alias
3608   // option to simplify the hasFlag logic.
3609   bool EnableVec = shouldEnableVectorizerAtOLevel(Args);
3610   OptSpecifier VectorizeAliasOption = EnableVec ? options::OPT_O_Group :
3611     options::OPT_fvectorize;
3612   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
3613                    options::OPT_fno_vectorize, EnableVec))
3614     CmdArgs.push_back("-vectorize-loops");
3615
3616   // -fslp-vectorize is default.
3617   if (Args.hasFlag(options::OPT_fslp_vectorize,
3618                    options::OPT_fno_slp_vectorize, true))
3619     CmdArgs.push_back("-vectorize-slp");
3620
3621   // -fno-slp-vectorize-aggressive is default.
3622   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
3623                    options::OPT_fno_slp_vectorize_aggressive, false))
3624     CmdArgs.push_back("-vectorize-slp-aggressive");
3625
3626   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
3627     A->render(Args, CmdArgs);
3628
3629   // -fdollars-in-identifiers default varies depending on platform and
3630   // language; only pass if specified.
3631   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
3632                                options::OPT_fno_dollars_in_identifiers)) {
3633     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
3634       CmdArgs.push_back("-fdollars-in-identifiers");
3635     else
3636       CmdArgs.push_back("-fno-dollars-in-identifiers");
3637   }
3638
3639   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
3640   // practical purposes.
3641   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
3642                                options::OPT_fno_unit_at_a_time)) {
3643     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
3644       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
3645   }
3646
3647   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
3648                    options::OPT_fno_apple_pragma_pack, false))
3649     CmdArgs.push_back("-fapple-pragma-pack");
3650
3651   // le32-specific flags: 
3652   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3653   //                     by default.
3654   if (getToolChain().getArch() == llvm::Triple::le32) {
3655     CmdArgs.push_back("-fno-math-builtin");
3656   }
3657
3658   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
3659   //
3660   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
3661 #if 0
3662   if (getToolChain().getTriple().isOSDarwin() &&
3663       (getToolChain().getArch() == llvm::Triple::arm ||
3664        getToolChain().getArch() == llvm::Triple::thumb)) {
3665     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
3666       CmdArgs.push_back("-fno-builtin-strcat");
3667     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
3668       CmdArgs.push_back("-fno-builtin-strcpy");
3669   }
3670 #endif
3671
3672   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
3673   if (Arg *A = Args.getLastArg(options::OPT_traditional,
3674                                options::OPT_traditional_cpp)) {
3675     if (isa<PreprocessJobAction>(JA))
3676       CmdArgs.push_back("-traditional-cpp");
3677     else
3678       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
3679   }
3680
3681   Args.AddLastArg(CmdArgs, options::OPT_dM);
3682   Args.AddLastArg(CmdArgs, options::OPT_dD);
3683   
3684   // Handle serialized diagnostics.
3685   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
3686     CmdArgs.push_back("-serialize-diagnostic-file");
3687     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
3688   }
3689
3690   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
3691     CmdArgs.push_back("-fretain-comments-from-system-headers");
3692
3693   // Forward -fcomment-block-commands to -cc1.
3694   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
3695   // Forward -fparse-all-comments to -cc1.
3696   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
3697
3698   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
3699   // parser.
3700   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
3701   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
3702          ie = Args.filtered_end(); it != ie; ++it) {
3703     (*it)->claim();
3704
3705     // We translate this by hand to the -cc1 argument, since nightly test uses
3706     // it and developers have been trained to spell it with -mllvm.
3707     if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns")
3708       CmdArgs.push_back("-disable-llvm-optzns");
3709     else
3710       (*it)->render(Args, CmdArgs);
3711   }
3712
3713   if (Output.getType() == types::TY_Dependencies) {
3714     // Handled with other dependency code.
3715   } else if (Output.isFilename()) {
3716     CmdArgs.push_back("-o");
3717     CmdArgs.push_back(Output.getFilename());
3718   } else {
3719     assert(Output.isNothing() && "Invalid output.");
3720   }
3721
3722   for (InputInfoList::const_iterator
3723          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3724     const InputInfo &II = *it;
3725     CmdArgs.push_back("-x");
3726     if (Args.hasArg(options::OPT_rewrite_objc))
3727       CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3728     else
3729       CmdArgs.push_back(types::getTypeName(II.getType()));
3730     if (II.isFilename())
3731       CmdArgs.push_back(II.getFilename());
3732     else
3733       II.getInputArg().renderAsInput(Args, CmdArgs);
3734   }
3735
3736   Args.AddAllArgs(CmdArgs, options::OPT_undef);
3737
3738   const char *Exec = getToolChain().getDriver().getClangProgramPath();
3739
3740   // Optionally embed the -cc1 level arguments into the debug info, for build
3741   // analysis.
3742   if (getToolChain().UseDwarfDebugFlags()) {
3743     ArgStringList OriginalArgs;
3744     for (ArgList::const_iterator it = Args.begin(),
3745            ie = Args.end(); it != ie; ++it)
3746       (*it)->render(Args, OriginalArgs);
3747
3748     SmallString<256> Flags;
3749     Flags += Exec;
3750     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3751       Flags += " ";
3752       Flags += OriginalArgs[i];
3753     }
3754     CmdArgs.push_back("-dwarf-debug-flags");
3755     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3756   }
3757
3758   // Add the split debug info name to the command lines here so we
3759   // can propagate it to the backend.
3760   bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
3761     getToolChain().getTriple().isOSLinux() &&
3762     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA));
3763   const char *SplitDwarfOut;
3764   if (SplitDwarf) {
3765     CmdArgs.push_back("-split-dwarf-file");
3766     SplitDwarfOut = SplitDebugName(Args, Inputs);
3767     CmdArgs.push_back(SplitDwarfOut);
3768   }
3769
3770   // Finally add the compile command to the compilation.
3771   if (Args.hasArg(options::OPT__SLASH_fallback)) {
3772     tools::visualstudio::Compile CL(getToolChain());
3773     Command *CLCommand = CL.GetCommand(C, JA, Output, Inputs, Args,
3774                                        LinkingOutput);
3775     C.addCommand(new FallbackCommand(JA, *this, Exec, CmdArgs, CLCommand));
3776   } else {
3777     C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3778   }
3779
3780
3781   // Handle the debug info splitting at object creation time if we're
3782   // creating an object.
3783   // TODO: Currently only works on linux with newer objcopy.
3784   if (SplitDwarf && !isa<CompileJobAction>(JA))
3785     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
3786
3787   if (Arg *A = Args.getLastArg(options::OPT_pg))
3788     if (Args.hasArg(options::OPT_fomit_frame_pointer))
3789       D.Diag(diag::err_drv_argument_not_allowed_with)
3790         << "-fomit-frame-pointer" << A->getAsString(Args);
3791
3792   // Claim some arguments which clang supports automatically.
3793
3794   // -fpch-preprocess is used with gcc to add a special marker in the output to
3795   // include the PCH file. Clang's PTH solution is completely transparent, so we
3796   // do not need to deal with it at all.
3797   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
3798
3799   // Claim some arguments which clang doesn't support, but we don't
3800   // care to warn the user about.
3801   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
3802   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
3803
3804   // Disable warnings for clang -E -emit-llvm foo.c
3805   Args.ClaimAllArgs(options::OPT_emit_llvm);
3806 }
3807
3808 /// Add options related to the Objective-C runtime/ABI.
3809 ///
3810 /// Returns true if the runtime is non-fragile.
3811 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
3812                                       ArgStringList &cmdArgs,
3813                                       RewriteKind rewriteKind) const {
3814   // Look for the controlling runtime option.
3815   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
3816                                     options::OPT_fgnu_runtime,
3817                                     options::OPT_fobjc_runtime_EQ);
3818
3819   // Just forward -fobjc-runtime= to the frontend.  This supercedes
3820   // options about fragility.
3821   if (runtimeArg &&
3822       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
3823     ObjCRuntime runtime;
3824     StringRef value = runtimeArg->getValue();
3825     if (runtime.tryParse(value)) {
3826       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
3827         << value;
3828     }
3829
3830     runtimeArg->render(args, cmdArgs);
3831     return runtime;
3832   }
3833
3834   // Otherwise, we'll need the ABI "version".  Version numbers are
3835   // slightly confusing for historical reasons:
3836   //   1 - Traditional "fragile" ABI
3837   //   2 - Non-fragile ABI, version 1
3838   //   3 - Non-fragile ABI, version 2
3839   unsigned objcABIVersion = 1;
3840   // If -fobjc-abi-version= is present, use that to set the version.
3841   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
3842     StringRef value = abiArg->getValue();
3843     if (value == "1")
3844       objcABIVersion = 1;
3845     else if (value == "2")
3846       objcABIVersion = 2;
3847     else if (value == "3")
3848       objcABIVersion = 3;
3849     else
3850       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3851         << value;
3852   } else {
3853     // Otherwise, determine if we are using the non-fragile ABI.
3854     bool nonFragileABIIsDefault = 
3855       (rewriteKind == RK_NonFragile || 
3856        (rewriteKind == RK_None &&
3857         getToolChain().IsObjCNonFragileABIDefault()));
3858     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
3859                      options::OPT_fno_objc_nonfragile_abi,
3860                      nonFragileABIIsDefault)) {
3861       // Determine the non-fragile ABI version to use.
3862 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
3863       unsigned nonFragileABIVersion = 1;
3864 #else
3865       unsigned nonFragileABIVersion = 2;
3866 #endif
3867
3868       if (Arg *abiArg = args.getLastArg(
3869             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
3870         StringRef value = abiArg->getValue();
3871         if (value == "1")
3872           nonFragileABIVersion = 1;
3873         else if (value == "2")
3874           nonFragileABIVersion = 2;
3875         else
3876           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3877             << value;
3878       }
3879
3880       objcABIVersion = 1 + nonFragileABIVersion;
3881     } else {
3882       objcABIVersion = 1;
3883     }
3884   }
3885
3886   // We don't actually care about the ABI version other than whether
3887   // it's non-fragile.
3888   bool isNonFragile = objcABIVersion != 1;
3889
3890   // If we have no runtime argument, ask the toolchain for its default runtime.
3891   // However, the rewriter only really supports the Mac runtime, so assume that.
3892   ObjCRuntime runtime;
3893   if (!runtimeArg) {
3894     switch (rewriteKind) {
3895     case RK_None:
3896       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3897       break;
3898     case RK_Fragile:
3899       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
3900       break;
3901     case RK_NonFragile:
3902       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3903       break;
3904     }
3905
3906   // -fnext-runtime
3907   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
3908     // On Darwin, make this use the default behavior for the toolchain.
3909     if (getToolChain().getTriple().isOSDarwin()) {
3910       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3911
3912     // Otherwise, build for a generic macosx port.
3913     } else {
3914       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3915     }
3916
3917   // -fgnu-runtime
3918   } else {
3919     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
3920     // Legacy behaviour is to target the gnustep runtime if we are i
3921     // non-fragile mode or the GCC runtime in fragile mode.
3922     if (isNonFragile)
3923       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
3924     else
3925       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
3926   }
3927
3928   cmdArgs.push_back(args.MakeArgString(
3929                                  "-fobjc-runtime=" + runtime.getAsString()));
3930   return runtime;
3931 }
3932
3933 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
3934   unsigned RTOptionID = options::OPT__SLASH_MT;
3935
3936   if (Args.hasArg(options::OPT__SLASH_LDd))
3937     // The /LDd option implies /MTd. The dependent lib part can be overridden,
3938     // but defining _DEBUG is sticky.
3939     RTOptionID = options::OPT__SLASH_MTd;
3940
3941   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
3942     RTOptionID = A->getOption().getID();
3943
3944   switch(RTOptionID) {
3945     case options::OPT__SLASH_MD:
3946       if (Args.hasArg(options::OPT__SLASH_LDd))
3947         CmdArgs.push_back("-D_DEBUG");
3948       CmdArgs.push_back("-D_MT");
3949       CmdArgs.push_back("-D_DLL");
3950       CmdArgs.push_back("--dependent-lib=msvcrt");
3951       break;
3952     case options::OPT__SLASH_MDd:
3953       CmdArgs.push_back("-D_DEBUG");
3954       CmdArgs.push_back("-D_MT");
3955       CmdArgs.push_back("-D_DLL");
3956       CmdArgs.push_back("--dependent-lib=msvcrtd");
3957       break;
3958     case options::OPT__SLASH_MT:
3959       if (Args.hasArg(options::OPT__SLASH_LDd))
3960         CmdArgs.push_back("-D_DEBUG");
3961       CmdArgs.push_back("-D_MT");
3962       CmdArgs.push_back("--dependent-lib=libcmt");
3963       break;
3964     case options::OPT__SLASH_MTd:
3965       CmdArgs.push_back("-D_DEBUG");
3966       CmdArgs.push_back("-D_MT");
3967       CmdArgs.push_back("--dependent-lib=libcmtd");
3968       break;
3969     default:
3970       llvm_unreachable("Unexpected option ID.");
3971   }
3972
3973   // This provides POSIX compatibility (maps 'open' to '_open'), which most
3974   // users want.  The /Za flag to cl.exe turns this off, but it's not
3975   // implemented in clang.
3976   CmdArgs.push_back("--dependent-lib=oldnames");
3977
3978   // FIXME: Make this default for the win32 triple.
3979   CmdArgs.push_back("-cxx-abi");
3980   CmdArgs.push_back("microsoft");
3981
3982   if (Arg *A = Args.getLastArg(options::OPT_show_includes))
3983     A->render(Args, CmdArgs);
3984
3985   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
3986     CmdArgs.push_back("-fdiagnostics-format");
3987     if (Args.hasArg(options::OPT__SLASH_fallback))
3988       CmdArgs.push_back("msvc-fallback");
3989     else
3990       CmdArgs.push_back("msvc");
3991   }
3992 }
3993
3994 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
3995                            const InputInfo &Output,
3996                            const InputInfoList &Inputs,
3997                            const ArgList &Args,
3998                            const char *LinkingOutput) const {
3999   ArgStringList CmdArgs;
4000
4001   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4002   const InputInfo &Input = Inputs[0];
4003
4004   // Don't warn about "clang -w -c foo.s"
4005   Args.ClaimAllArgs(options::OPT_w);
4006   // and "clang -emit-llvm -c foo.s"
4007   Args.ClaimAllArgs(options::OPT_emit_llvm);
4008
4009   // Invoke ourselves in -cc1as mode.
4010   //
4011   // FIXME: Implement custom jobs for internal actions.
4012   CmdArgs.push_back("-cc1as");
4013
4014   // Add the "effective" target triple.
4015   CmdArgs.push_back("-triple");
4016   std::string TripleStr = 
4017     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
4018   CmdArgs.push_back(Args.MakeArgString(TripleStr));
4019
4020   // Set the output mode, we currently only expect to be used as a real
4021   // assembler.
4022   CmdArgs.push_back("-filetype");
4023   CmdArgs.push_back("obj");
4024
4025   // Set the main file name, so that debug info works even with
4026   // -save-temps or preprocessed assembly.
4027   CmdArgs.push_back("-main-file-name");
4028   CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs));
4029
4030   // Add the target cpu
4031   const llvm::Triple &Triple = getToolChain().getTriple();
4032   std::string CPU = getCPUName(Args, Triple);
4033   if (!CPU.empty()) {
4034     CmdArgs.push_back("-target-cpu");
4035     CmdArgs.push_back(Args.MakeArgString(CPU));
4036   }
4037
4038   // Add the target features
4039   const Driver &D = getToolChain().getDriver();
4040   getTargetFeatures(D, Triple, Args, CmdArgs);
4041
4042   // Ignore explicit -force_cpusubtype_ALL option.
4043   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
4044
4045   // Determine the original source input.
4046   const Action *SourceAction = &JA;
4047   while (SourceAction->getKind() != Action::InputClass) {
4048     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4049     SourceAction = SourceAction->getInputs()[0];
4050   }
4051
4052   // Forward -g and handle debug info related flags, assuming we are dealing
4053   // with an actual assembly file.
4054   if (SourceAction->getType() == types::TY_Asm ||
4055       SourceAction->getType() == types::TY_PP_Asm) {
4056     Args.ClaimAllArgs(options::OPT_g_Group);
4057     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
4058       if (!A->getOption().matches(options::OPT_g0))
4059         CmdArgs.push_back("-g");
4060
4061     // Add the -fdebug-compilation-dir flag if needed.
4062     addDebugCompDirArg(Args, CmdArgs);
4063
4064     // Set the AT_producer to the clang version when using the integrated
4065     // assembler on assembly source files.
4066     CmdArgs.push_back("-dwarf-debug-producer");
4067     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
4068   }
4069
4070   // Optionally embed the -cc1as level arguments into the debug info, for build
4071   // analysis.
4072   if (getToolChain().UseDwarfDebugFlags()) {
4073     ArgStringList OriginalArgs;
4074     for (ArgList::const_iterator it = Args.begin(),
4075            ie = Args.end(); it != ie; ++it)
4076       (*it)->render(Args, OriginalArgs);
4077
4078     SmallString<256> Flags;
4079     const char *Exec = getToolChain().getDriver().getClangProgramPath();
4080     Flags += Exec;
4081     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
4082       Flags += " ";
4083       Flags += OriginalArgs[i];
4084     }
4085     CmdArgs.push_back("-dwarf-debug-flags");
4086     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
4087   }
4088
4089   // FIXME: Add -static support, once we have it.
4090
4091   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
4092                                     getToolChain().getDriver());
4093
4094   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
4095
4096   assert(Output.isFilename() && "Unexpected lipo output.");
4097   CmdArgs.push_back("-o");
4098   CmdArgs.push_back(Output.getFilename());
4099
4100   assert(Input.isFilename() && "Invalid input.");
4101   CmdArgs.push_back(Input.getFilename());
4102
4103   const char *Exec = getToolChain().getDriver().getClangProgramPath();
4104   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4105
4106   // Handle the debug info splitting at object creation time if we're
4107   // creating an object.
4108   // TODO: Currently only works on linux with newer objcopy.
4109   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
4110       getToolChain().getTriple().isOSLinux())
4111     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
4112                    SplitDebugName(Args, Inputs));
4113 }
4114
4115 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
4116                                const InputInfo &Output,
4117                                const InputInfoList &Inputs,
4118                                const ArgList &Args,
4119                                const char *LinkingOutput) const {
4120   const Driver &D = getToolChain().getDriver();
4121   ArgStringList CmdArgs;
4122
4123   for (ArgList::const_iterator
4124          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
4125     Arg *A = *it;
4126     if (forwardToGCC(A->getOption())) {
4127       // Don't forward any -g arguments to assembly steps.
4128       if (isa<AssembleJobAction>(JA) &&
4129           A->getOption().matches(options::OPT_g_Group))
4130         continue;
4131
4132       // Don't forward any -W arguments to assembly and link steps.
4133       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
4134           A->getOption().matches(options::OPT_W_Group))
4135         continue;
4136
4137       // It is unfortunate that we have to claim here, as this means
4138       // we will basically never report anything interesting for
4139       // platforms using a generic gcc, even if we are just using gcc
4140       // to get to the assembler.
4141       A->claim();
4142       A->render(Args, CmdArgs);
4143     }
4144   }
4145
4146   RenderExtraToolArgs(JA, CmdArgs);
4147
4148   // If using a driver driver, force the arch.
4149   llvm::Triple::ArchType Arch = getToolChain().getArch();
4150   if (getToolChain().getTriple().isOSDarwin()) {
4151     CmdArgs.push_back("-arch");
4152
4153     // FIXME: Remove these special cases.
4154     if (Arch == llvm::Triple::ppc)
4155       CmdArgs.push_back("ppc");
4156     else if (Arch == llvm::Triple::ppc64)
4157       CmdArgs.push_back("ppc64");
4158     else if (Arch == llvm::Triple::ppc64le)
4159       CmdArgs.push_back("ppc64le");
4160     else
4161       CmdArgs.push_back(Args.MakeArgString(getToolChain().getArchName()));
4162   }
4163
4164   // Try to force gcc to match the tool chain we want, if we recognize
4165   // the arch.
4166   //
4167   // FIXME: The triple class should directly provide the information we want
4168   // here.
4169   if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
4170     CmdArgs.push_back("-m32");
4171   else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
4172            Arch == llvm::Triple::ppc64le)
4173     CmdArgs.push_back("-m64");
4174
4175   if (Output.isFilename()) {
4176     CmdArgs.push_back("-o");
4177     CmdArgs.push_back(Output.getFilename());
4178   } else {
4179     assert(Output.isNothing() && "Unexpected output");
4180     CmdArgs.push_back("-fsyntax-only");
4181   }
4182
4183   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4184                        options::OPT_Xassembler);
4185
4186   // Only pass -x if gcc will understand it; otherwise hope gcc
4187   // understands the suffix correctly. The main use case this would go
4188   // wrong in is for linker inputs if they happened to have an odd
4189   // suffix; really the only way to get this to happen is a command
4190   // like '-x foobar a.c' which will treat a.c like a linker input.
4191   //
4192   // FIXME: For the linker case specifically, can we safely convert
4193   // inputs into '-Wl,' options?
4194   for (InputInfoList::const_iterator
4195          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4196     const InputInfo &II = *it;
4197
4198     // Don't try to pass LLVM or AST inputs to a generic gcc.
4199     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
4200         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
4201       D.Diag(diag::err_drv_no_linker_llvm_support)
4202         << getToolChain().getTripleString();
4203     else if (II.getType() == types::TY_AST)
4204       D.Diag(diag::err_drv_no_ast_support)
4205         << getToolChain().getTripleString();
4206     else if (II.getType() == types::TY_ModuleFile)
4207       D.Diag(diag::err_drv_no_module_support)
4208         << getToolChain().getTripleString();
4209
4210     if (types::canTypeBeUserSpecified(II.getType())) {
4211       CmdArgs.push_back("-x");
4212       CmdArgs.push_back(types::getTypeName(II.getType()));
4213     }
4214
4215     if (II.isFilename())
4216       CmdArgs.push_back(II.getFilename());
4217     else {
4218       const Arg &A = II.getInputArg();
4219
4220       // Reverse translate some rewritten options.
4221       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
4222         CmdArgs.push_back("-lstdc++");
4223         continue;
4224       }
4225
4226       // Don't render as input, we need gcc to do the translations.
4227       A.render(Args, CmdArgs);
4228     }
4229   }
4230
4231   const std::string customGCCName = D.getCCCGenericGCCName();
4232   const char *GCCName;
4233   if (!customGCCName.empty())
4234     GCCName = customGCCName.c_str();
4235   else if (D.CCCIsCXX()) {
4236     GCCName = "g++";
4237   } else
4238     GCCName = "gcc";
4239
4240   const char *Exec =
4241     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
4242   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4243 }
4244
4245 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
4246                                           ArgStringList &CmdArgs) const {
4247   CmdArgs.push_back("-E");
4248 }
4249
4250 void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
4251                                           ArgStringList &CmdArgs) const {
4252   // The type is good enough.
4253 }
4254
4255 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
4256                                        ArgStringList &CmdArgs) const {
4257   const Driver &D = getToolChain().getDriver();
4258
4259   // If -flto, etc. are present then make sure not to force assembly output.
4260   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
4261       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
4262     CmdArgs.push_back("-c");
4263   else {
4264     if (JA.getType() != types::TY_PP_Asm)
4265       D.Diag(diag::err_drv_invalid_gcc_output_type)
4266         << getTypeName(JA.getType());
4267
4268     CmdArgs.push_back("-S");
4269   }
4270 }
4271
4272 void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
4273                                         ArgStringList &CmdArgs) const {
4274   CmdArgs.push_back("-c");
4275 }
4276
4277 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
4278                                     ArgStringList &CmdArgs) const {
4279   // The types are (hopefully) good enough.
4280 }
4281
4282 // Hexagon tools start.
4283 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
4284                                         ArgStringList &CmdArgs) const {
4285
4286 }
4287 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4288                                const InputInfo &Output,
4289                                const InputInfoList &Inputs,
4290                                const ArgList &Args,
4291                                const char *LinkingOutput) const {
4292
4293   const Driver &D = getToolChain().getDriver();
4294   ArgStringList CmdArgs;
4295
4296   std::string MarchString = "-march=";
4297   MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
4298   CmdArgs.push_back(Args.MakeArgString(MarchString));
4299
4300   RenderExtraToolArgs(JA, CmdArgs);
4301
4302   if (Output.isFilename()) {
4303     CmdArgs.push_back("-o");
4304     CmdArgs.push_back(Output.getFilename());
4305   } else {
4306     assert(Output.isNothing() && "Unexpected output");
4307     CmdArgs.push_back("-fsyntax-only");
4308   }
4309
4310   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
4311   if (!SmallDataThreshold.empty())
4312     CmdArgs.push_back(
4313       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
4314
4315   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4316                        options::OPT_Xassembler);
4317
4318   // Only pass -x if gcc will understand it; otherwise hope gcc
4319   // understands the suffix correctly. The main use case this would go
4320   // wrong in is for linker inputs if they happened to have an odd
4321   // suffix; really the only way to get this to happen is a command
4322   // like '-x foobar a.c' which will treat a.c like a linker input.
4323   //
4324   // FIXME: For the linker case specifically, can we safely convert
4325   // inputs into '-Wl,' options?
4326   for (InputInfoList::const_iterator
4327          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4328     const InputInfo &II = *it;
4329
4330     // Don't try to pass LLVM or AST inputs to a generic gcc.
4331     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
4332         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
4333       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
4334         << getToolChain().getTripleString();
4335     else if (II.getType() == types::TY_AST)
4336       D.Diag(clang::diag::err_drv_no_ast_support)
4337         << getToolChain().getTripleString();
4338     else if (II.getType() == types::TY_ModuleFile)
4339       D.Diag(diag::err_drv_no_module_support)
4340       << getToolChain().getTripleString();
4341
4342     if (II.isFilename())
4343       CmdArgs.push_back(II.getFilename());
4344     else
4345       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
4346       II.getInputArg().render(Args, CmdArgs);
4347   }
4348
4349   const char *GCCName = "hexagon-as";
4350   const char *Exec =
4351     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
4352   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4353
4354 }
4355 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
4356                                     ArgStringList &CmdArgs) const {
4357   // The types are (hopefully) good enough.
4358 }
4359
4360 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
4361                                const InputInfo &Output,
4362                                const InputInfoList &Inputs,
4363                                const ArgList &Args,
4364                                const char *LinkingOutput) const {
4365
4366   const toolchains::Hexagon_TC& ToolChain =
4367     static_cast<const toolchains::Hexagon_TC&>(getToolChain());
4368   const Driver &D = ToolChain.getDriver();
4369
4370   ArgStringList CmdArgs;
4371
4372   //----------------------------------------------------------------------------
4373   //
4374   //----------------------------------------------------------------------------
4375   bool hasStaticArg = Args.hasArg(options::OPT_static);
4376   bool buildingLib = Args.hasArg(options::OPT_shared);
4377   bool buildPIE = Args.hasArg(options::OPT_pie);
4378   bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
4379   bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
4380   bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
4381   bool useShared = buildingLib && !hasStaticArg;
4382
4383   //----------------------------------------------------------------------------
4384   // Silence warnings for various options
4385   //----------------------------------------------------------------------------
4386
4387   Args.ClaimAllArgs(options::OPT_g_Group);
4388   Args.ClaimAllArgs(options::OPT_emit_llvm);
4389   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
4390                                      // handled somewhere else.
4391   Args.ClaimAllArgs(options::OPT_static_libgcc);
4392
4393   //----------------------------------------------------------------------------
4394   //
4395   //----------------------------------------------------------------------------
4396   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
4397          e = ToolChain.ExtraOpts.end();
4398        i != e; ++i)
4399     CmdArgs.push_back(i->c_str());
4400
4401   std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
4402   CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
4403
4404   if (buildingLib) {
4405     CmdArgs.push_back("-shared");
4406     CmdArgs.push_back("-call_shared"); // should be the default, but doing as
4407                                        // hexagon-gcc does
4408   }
4409
4410   if (hasStaticArg)
4411     CmdArgs.push_back("-static");
4412
4413   if (buildPIE && !buildingLib)
4414     CmdArgs.push_back("-pie");
4415
4416   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
4417   if (!SmallDataThreshold.empty()) {
4418     CmdArgs.push_back(
4419       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
4420   }
4421
4422   //----------------------------------------------------------------------------
4423   //
4424   //----------------------------------------------------------------------------
4425   CmdArgs.push_back("-o");
4426   CmdArgs.push_back(Output.getFilename());
4427
4428   const std::string MarchSuffix = "/" + MarchString;
4429   const std::string G0Suffix = "/G0";
4430   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
4431   const std::string RootDir = toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir)
4432                               + "/";
4433   const std::string StartFilesDir = RootDir
4434                                     + "hexagon/lib"
4435                                     + (buildingLib
4436                                        ? MarchG0Suffix : MarchSuffix);
4437
4438   //----------------------------------------------------------------------------
4439   // moslib
4440   //----------------------------------------------------------------------------
4441   std::vector<std::string> oslibs;
4442   bool hasStandalone= false;
4443
4444   for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ),
4445          ie = Args.filtered_end(); it != ie; ++it) {
4446     (*it)->claim();
4447     oslibs.push_back((*it)->getValue());
4448     hasStandalone = hasStandalone || (oslibs.back() == "standalone");
4449   }
4450   if (oslibs.empty()) {
4451     oslibs.push_back("standalone");
4452     hasStandalone = true;
4453   }
4454
4455   //----------------------------------------------------------------------------
4456   // Start Files
4457   //----------------------------------------------------------------------------
4458   if (incStdLib && incStartFiles) {
4459
4460     if (!buildingLib) {
4461       if (hasStandalone) {
4462         CmdArgs.push_back(
4463           Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
4464       }
4465       CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
4466     }
4467     std::string initObj = useShared ? "/initS.o" : "/init.o";
4468     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
4469   }
4470
4471   //----------------------------------------------------------------------------
4472   // Library Search Paths
4473   //----------------------------------------------------------------------------
4474   const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
4475   for (ToolChain::path_list::const_iterator
4476          i = LibPaths.begin(),
4477          e = LibPaths.end();
4478        i != e;
4479        ++i)
4480     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
4481
4482   //----------------------------------------------------------------------------
4483   //
4484   //----------------------------------------------------------------------------
4485   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4486   Args.AddAllArgs(CmdArgs, options::OPT_e);
4487   Args.AddAllArgs(CmdArgs, options::OPT_s);
4488   Args.AddAllArgs(CmdArgs, options::OPT_t);
4489   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4490
4491   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
4492
4493   //----------------------------------------------------------------------------
4494   // Libraries
4495   //----------------------------------------------------------------------------
4496   if (incStdLib && incDefLibs) {
4497     if (D.CCCIsCXX()) {
4498       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
4499       CmdArgs.push_back("-lm");
4500     }
4501
4502     CmdArgs.push_back("--start-group");
4503
4504     if (!buildingLib) {
4505       for(std::vector<std::string>::iterator i = oslibs.begin(),
4506             e = oslibs.end(); i != e; ++i)
4507         CmdArgs.push_back(Args.MakeArgString("-l" + *i));
4508       CmdArgs.push_back("-lc");
4509     }
4510     CmdArgs.push_back("-lgcc");
4511
4512     CmdArgs.push_back("--end-group");
4513   }
4514
4515   //----------------------------------------------------------------------------
4516   // End files
4517   //----------------------------------------------------------------------------
4518   if (incStdLib && incStartFiles) {
4519     std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
4520     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
4521   }
4522
4523   std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
4524   C.addCommand(new Command(JA, *this, Args.MakeArgString(Linker), CmdArgs));
4525 }
4526 // Hexagon tools end.
4527
4528 llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Str) {
4529   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
4530   // archs which Darwin doesn't use.
4531
4532   // The matching this routine does is fairly pointless, since it is neither the
4533   // complete architecture list, nor a reasonable subset. The problem is that
4534   // historically the driver driver accepts this and also ties its -march=
4535   // handling to the architecture name, so we need to be careful before removing
4536   // support for it.
4537
4538   // This code must be kept in sync with Clang's Darwin specific argument
4539   // translation.
4540
4541   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
4542     .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
4543     .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
4544     .Case("ppc64", llvm::Triple::ppc64)
4545     .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
4546     .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
4547            llvm::Triple::x86)
4548     .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
4549     // This is derived from the driver driver.
4550     .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
4551     .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm)
4552     .Cases("armv7s", "xscale", llvm::Triple::arm)
4553     .Case("r600", llvm::Triple::r600)
4554     .Case("nvptx", llvm::Triple::nvptx)
4555     .Case("nvptx64", llvm::Triple::nvptx64)
4556     .Case("amdil", llvm::Triple::amdil)
4557     .Case("spir", llvm::Triple::spir)
4558     .Default(llvm::Triple::UnknownArch);
4559 }
4560
4561 const char *Clang::getBaseInputName(const ArgList &Args,
4562                                     const InputInfoList &Inputs) {
4563   return Args.MakeArgString(
4564     llvm::sys::path::filename(Inputs[0].getBaseInput()));
4565 }
4566
4567 const char *Clang::getBaseInputStem(const ArgList &Args,
4568                                     const InputInfoList &Inputs) {
4569   const char *Str = getBaseInputName(Args, Inputs);
4570
4571   if (const char *End = strrchr(Str, '.'))
4572     return Args.MakeArgString(std::string(Str, End));
4573
4574   return Str;
4575 }
4576
4577 const char *Clang::getDependencyFileName(const ArgList &Args,
4578                                          const InputInfoList &Inputs) {
4579   // FIXME: Think about this more.
4580   std::string Res;
4581
4582   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4583     std::string Str(OutputOpt->getValue());
4584     Res = Str.substr(0, Str.rfind('.'));
4585   } else {
4586     Res = getBaseInputStem(Args, Inputs);
4587   }
4588   return Args.MakeArgString(Res + ".d");
4589 }
4590
4591 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4592                                     const InputInfo &Output,
4593                                     const InputInfoList &Inputs,
4594                                     const ArgList &Args,
4595                                     const char *LinkingOutput) const {
4596   ArgStringList CmdArgs;
4597
4598   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4599   const InputInfo &Input = Inputs[0];
4600
4601   // Determine the original source input.
4602   const Action *SourceAction = &JA;
4603   while (SourceAction->getKind() != Action::InputClass) {
4604     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4605     SourceAction = SourceAction->getInputs()[0];
4606   }
4607
4608   // If -no_integrated_as is used add -Q to the darwin assember driver to make
4609   // sure it runs its system assembler not clang's integrated assembler.
4610   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
4611   // FIXME: at run-time detect assembler capabilities or rely on version
4612   // information forwarded by -target-assembler-version (future)
4613   if (Args.hasArg(options::OPT_no_integrated_as)) {
4614     const llvm::Triple& t(getToolChain().getTriple());
4615     if (!(t.isMacOSX() && t.isMacOSXVersionLT(10, 7)))
4616       CmdArgs.push_back("-Q");
4617   }
4618
4619   // Forward -g, assuming we are dealing with an actual assembly file.
4620   if (SourceAction->getType() == types::TY_Asm ||
4621       SourceAction->getType() == types::TY_PP_Asm) {
4622     if (Args.hasArg(options::OPT_gstabs))
4623       CmdArgs.push_back("--gstabs");
4624     else if (Args.hasArg(options::OPT_g_Group))
4625       CmdArgs.push_back("-g");
4626   }
4627
4628   // Derived from asm spec.
4629   AddDarwinArch(Args, CmdArgs);
4630
4631   // Use -force_cpusubtype_ALL on x86 by default.
4632   if (getToolChain().getArch() == llvm::Triple::x86 ||
4633       getToolChain().getArch() == llvm::Triple::x86_64 ||
4634       Args.hasArg(options::OPT_force__cpusubtype__ALL))
4635     CmdArgs.push_back("-force_cpusubtype_ALL");
4636
4637   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
4638       (((Args.hasArg(options::OPT_mkernel) ||
4639          Args.hasArg(options::OPT_fapple_kext)) &&
4640         (!getDarwinToolChain().isTargetIPhoneOS() ||
4641          getDarwinToolChain().isIPhoneOSVersionLT(6, 0))) ||
4642        Args.hasArg(options::OPT_static)))
4643     CmdArgs.push_back("-static");
4644
4645   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4646                        options::OPT_Xassembler);
4647
4648   assert(Output.isFilename() && "Unexpected lipo output.");
4649   CmdArgs.push_back("-o");
4650   CmdArgs.push_back(Output.getFilename());
4651
4652   assert(Input.isFilename() && "Invalid input.");
4653   CmdArgs.push_back(Input.getFilename());
4654
4655   // asm_final spec is empty.
4656
4657   const char *Exec =
4658     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4659   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4660 }
4661
4662 void darwin::DarwinTool::anchor() {}
4663
4664 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
4665                                        ArgStringList &CmdArgs) const {
4666   StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
4667
4668   // Derived from darwin_arch spec.
4669   CmdArgs.push_back("-arch");
4670   CmdArgs.push_back(Args.MakeArgString(ArchName));
4671
4672   // FIXME: Is this needed anymore?
4673   if (ArchName == "arm")
4674     CmdArgs.push_back("-force_cpusubtype_ALL");
4675 }
4676
4677 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
4678   // We only need to generate a temp path for LTO if we aren't compiling object
4679   // files. When compiling source files, we run 'dsymutil' after linking. We
4680   // don't run 'dsymutil' when compiling object files.
4681   for (InputInfoList::const_iterator
4682          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it)
4683     if (it->getType() != types::TY_Object)
4684       return true;
4685
4686   return false;
4687 }
4688
4689 void darwin::Link::AddLinkArgs(Compilation &C,
4690                                const ArgList &Args,
4691                                ArgStringList &CmdArgs,
4692                                const InputInfoList &Inputs) const {
4693   const Driver &D = getToolChain().getDriver();
4694   const toolchains::Darwin &DarwinTC = getDarwinToolChain();
4695
4696   unsigned Version[3] = { 0, 0, 0 };
4697   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4698     bool HadExtra;
4699     if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
4700                                    Version[1], Version[2], HadExtra) ||
4701         HadExtra)
4702       D.Diag(diag::err_drv_invalid_version_number)
4703         << A->getAsString(Args);
4704   }
4705
4706   // Newer linkers support -demangle, pass it if supported and not disabled by
4707   // the user.
4708   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
4709     // Don't pass -demangle to ld_classic.
4710     //
4711     // FIXME: This is a temporary workaround, ld should be handling this.
4712     bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
4713                           Args.hasArg(options::OPT_static));
4714     if (getToolChain().getArch() == llvm::Triple::x86) {
4715       for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
4716                                                  options::OPT_Wl_COMMA),
4717              ie = Args.filtered_end(); it != ie; ++it) {
4718         const Arg *A = *it;
4719         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
4720           if (StringRef(A->getValue(i)) == "-kext")
4721             UsesLdClassic = true;
4722       }
4723     }
4724     if (!UsesLdClassic)
4725       CmdArgs.push_back("-demangle");
4726   }
4727
4728   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
4729     CmdArgs.push_back("-export_dynamic");
4730
4731   // If we are using LTO, then automatically create a temporary file path for
4732   // the linker to use, so that it's lifetime will extend past a possible
4733   // dsymutil step.
4734   if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
4735     const char *TmpPath = C.getArgs().MakeArgString(
4736       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
4737     C.addTempFile(TmpPath);
4738     CmdArgs.push_back("-object_path_lto");
4739     CmdArgs.push_back(TmpPath);
4740   }
4741
4742   // Derived from the "link" spec.
4743   Args.AddAllArgs(CmdArgs, options::OPT_static);
4744   if (!Args.hasArg(options::OPT_static))
4745     CmdArgs.push_back("-dynamic");
4746   if (Args.hasArg(options::OPT_fgnu_runtime)) {
4747     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
4748     // here. How do we wish to handle such things?
4749   }
4750
4751   if (!Args.hasArg(options::OPT_dynamiclib)) {
4752     AddDarwinArch(Args, CmdArgs);
4753     // FIXME: Why do this only on this path?
4754     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
4755
4756     Args.AddLastArg(CmdArgs, options::OPT_bundle);
4757     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
4758     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
4759
4760     Arg *A;
4761     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
4762         (A = Args.getLastArg(options::OPT_current__version)) ||
4763         (A = Args.getLastArg(options::OPT_install__name)))
4764       D.Diag(diag::err_drv_argument_only_allowed_with)
4765         << A->getAsString(Args) << "-dynamiclib";
4766
4767     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
4768     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
4769     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
4770   } else {
4771     CmdArgs.push_back("-dylib");
4772
4773     Arg *A;
4774     if ((A = Args.getLastArg(options::OPT_bundle)) ||
4775         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
4776         (A = Args.getLastArg(options::OPT_client__name)) ||
4777         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
4778         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
4779         (A = Args.getLastArg(options::OPT_private__bundle)))
4780       D.Diag(diag::err_drv_argument_not_allowed_with)
4781         << A->getAsString(Args) << "-dynamiclib";
4782
4783     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
4784                               "-dylib_compatibility_version");
4785     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
4786                               "-dylib_current_version");
4787
4788     AddDarwinArch(Args, CmdArgs);
4789
4790     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
4791                               "-dylib_install_name");
4792   }
4793
4794   Args.AddLastArg(CmdArgs, options::OPT_all__load);
4795   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
4796   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
4797   if (DarwinTC.isTargetIPhoneOS())
4798     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
4799   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
4800   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
4801   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
4802   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
4803   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
4804   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
4805   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
4806   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
4807   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
4808   Args.AddAllArgs(CmdArgs, options::OPT_init);
4809
4810   // Add the deployment target.
4811   VersionTuple TargetVersion = DarwinTC.getTargetVersion();
4812
4813   // If we had an explicit -mios-simulator-version-min argument, honor that,
4814   // otherwise use the traditional deployment targets. We can't just check the
4815   // is-sim attribute because existing code follows this path, and the linker
4816   // may not handle the argument.
4817   //
4818   // FIXME: We may be able to remove this, once we can verify no one depends on
4819   // it.
4820   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
4821     CmdArgs.push_back("-ios_simulator_version_min");
4822   else if (DarwinTC.isTargetIPhoneOS())
4823     CmdArgs.push_back("-iphoneos_version_min");
4824   else
4825     CmdArgs.push_back("-macosx_version_min");
4826   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
4827
4828   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
4829   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
4830   Args.AddLastArg(CmdArgs, options::OPT_single__module);
4831   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
4832   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
4833
4834   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
4835                                      options::OPT_fno_pie,
4836                                      options::OPT_fno_PIE)) {
4837     if (A->getOption().matches(options::OPT_fpie) ||
4838         A->getOption().matches(options::OPT_fPIE))
4839       CmdArgs.push_back("-pie");
4840     else
4841       CmdArgs.push_back("-no_pie");
4842   }
4843
4844   Args.AddLastArg(CmdArgs, options::OPT_prebind);
4845   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
4846   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
4847   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
4848   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
4849   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
4850   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
4851   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
4852   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
4853   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
4854   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
4855   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
4856   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
4857   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
4858   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
4859   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
4860
4861   // Give --sysroot= preference, over the Apple specific behavior to also use
4862   // --isysroot as the syslibroot.
4863   StringRef sysroot = C.getSysRoot();
4864   if (sysroot != "") {
4865     CmdArgs.push_back("-syslibroot");
4866     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
4867   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4868     CmdArgs.push_back("-syslibroot");
4869     CmdArgs.push_back(A->getValue());
4870   }
4871
4872   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
4873   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
4874   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
4875   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
4876   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
4877   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
4878   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
4879   Args.AddAllArgs(CmdArgs, options::OPT_y);
4880   Args.AddLastArg(CmdArgs, options::OPT_w);
4881   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
4882   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
4883   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
4884   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
4885   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
4886   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
4887   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
4888   Args.AddLastArg(CmdArgs, options::OPT_whyload);
4889   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
4890   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
4891   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
4892   Args.AddLastArg(CmdArgs, options::OPT_Mach);
4893 }
4894
4895 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
4896                                 const InputInfo &Output,
4897                                 const InputInfoList &Inputs,
4898                                 const ArgList &Args,
4899                                 const char *LinkingOutput) const {
4900   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
4901
4902   // The logic here is derived from gcc's behavior; most of which
4903   // comes from specs (starting with link_command). Consult gcc for
4904   // more information.
4905   ArgStringList CmdArgs;
4906
4907   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
4908   if (Args.hasArg(options::OPT_ccc_arcmt_check,
4909                   options::OPT_ccc_arcmt_migrate)) {
4910     for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
4911       (*I)->claim();
4912     const char *Exec =
4913       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
4914     CmdArgs.push_back(Output.getFilename());
4915     C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4916     return;
4917   }
4918
4919   // I'm not sure why this particular decomposition exists in gcc, but
4920   // we follow suite for ease of comparison.
4921   AddLinkArgs(C, Args, CmdArgs, Inputs);
4922
4923   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
4924   Args.AddAllArgs(CmdArgs, options::OPT_s);
4925   Args.AddAllArgs(CmdArgs, options::OPT_t);
4926   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
4927   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4928   Args.AddLastArg(CmdArgs, options::OPT_e);
4929   Args.AddAllArgs(CmdArgs, options::OPT_r);
4930
4931   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
4932   // members of static archive libraries which implement Objective-C classes or
4933   // categories.
4934   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
4935     CmdArgs.push_back("-ObjC");
4936
4937   CmdArgs.push_back("-o");
4938   CmdArgs.push_back(Output.getFilename());
4939
4940   if (!Args.hasArg(options::OPT_nostdlib) &&
4941       !Args.hasArg(options::OPT_nostartfiles)) {
4942     // Derived from startfile spec.
4943     if (Args.hasArg(options::OPT_dynamiclib)) {
4944       // Derived from darwin_dylib1 spec.
4945       if (getDarwinToolChain().isTargetIOSSimulator()) {
4946         // The simulator doesn't have a versioned crt1 file.
4947         CmdArgs.push_back("-ldylib1.o");
4948       } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4949         if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4950           CmdArgs.push_back("-ldylib1.o");
4951       } else {
4952         if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4953           CmdArgs.push_back("-ldylib1.o");
4954         else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4955           CmdArgs.push_back("-ldylib1.10.5.o");
4956       }
4957     } else {
4958       if (Args.hasArg(options::OPT_bundle)) {
4959         if (!Args.hasArg(options::OPT_static)) {
4960           // Derived from darwin_bundle1 spec.
4961           if (getDarwinToolChain().isTargetIOSSimulator()) {
4962             // The simulator doesn't have a versioned crt1 file.
4963             CmdArgs.push_back("-lbundle1.o");
4964           } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4965             if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4966               CmdArgs.push_back("-lbundle1.o");
4967           } else {
4968             if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4969               CmdArgs.push_back("-lbundle1.o");
4970           }
4971         }
4972       } else {
4973         if (Args.hasArg(options::OPT_pg) &&
4974             getToolChain().SupportsProfiling()) {
4975           if (Args.hasArg(options::OPT_static) ||
4976               Args.hasArg(options::OPT_object) ||
4977               Args.hasArg(options::OPT_preload)) {
4978             CmdArgs.push_back("-lgcrt0.o");
4979           } else {
4980             CmdArgs.push_back("-lgcrt1.o");
4981
4982             // darwin_crt2 spec is empty.
4983           }
4984           // By default on OS X 10.8 and later, we don't link with a crt1.o
4985           // file and the linker knows to use _main as the entry point.  But,
4986           // when compiling with -pg, we need to link with the gcrt1.o file,
4987           // so pass the -no_new_main option to tell the linker to use the
4988           // "start" symbol as the entry point.
4989           if (getDarwinToolChain().isTargetMacOS() &&
4990               !getDarwinToolChain().isMacosxVersionLT(10, 8))
4991             CmdArgs.push_back("-no_new_main");
4992         } else {
4993           if (Args.hasArg(options::OPT_static) ||
4994               Args.hasArg(options::OPT_object) ||
4995               Args.hasArg(options::OPT_preload)) {
4996             CmdArgs.push_back("-lcrt0.o");
4997           } else {
4998             // Derived from darwin_crt1 spec.
4999             if (getDarwinToolChain().isTargetIOSSimulator()) {
5000               // The simulator doesn't have a versioned crt1 file.
5001               CmdArgs.push_back("-lcrt1.o");
5002             } else if (getDarwinToolChain().isTargetIPhoneOS()) {
5003               if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
5004                 CmdArgs.push_back("-lcrt1.o");
5005               else if (getDarwinToolChain().isIPhoneOSVersionLT(6, 0))
5006                 CmdArgs.push_back("-lcrt1.3.1.o");
5007             } else {
5008               if (getDarwinToolChain().isMacosxVersionLT(10, 5))
5009                 CmdArgs.push_back("-lcrt1.o");
5010               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
5011                 CmdArgs.push_back("-lcrt1.10.5.o");
5012               else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
5013                 CmdArgs.push_back("-lcrt1.10.6.o");
5014
5015               // darwin_crt2 spec is empty.
5016             }
5017           }
5018         }
5019       }
5020     }
5021
5022     if (!getDarwinToolChain().isTargetIPhoneOS() &&
5023         Args.hasArg(options::OPT_shared_libgcc) &&
5024         getDarwinToolChain().isMacosxVersionLT(10, 5)) {
5025       const char *Str =
5026         Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
5027       CmdArgs.push_back(Str);
5028     }
5029   }
5030
5031   Args.AddAllArgs(CmdArgs, options::OPT_L);
5032
5033   if (Args.hasArg(options::OPT_fopenmp))
5034     // This is more complicated in gcc...
5035     CmdArgs.push_back("-lgomp");
5036
5037   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5038   
5039   if (isObjCRuntimeLinked(Args) &&
5040       !Args.hasArg(options::OPT_nostdlib) &&
5041       !Args.hasArg(options::OPT_nodefaultlibs)) {
5042     // Avoid linking compatibility stubs on i386 mac.
5043     if (!getDarwinToolChain().isTargetMacOS() ||
5044         getDarwinToolChain().getArch() != llvm::Triple::x86) {
5045       // If we don't have ARC or subscripting runtime support, link in the
5046       // runtime stubs.  We have to do this *before* adding any of the normal
5047       // linker inputs so that its initializer gets run first.
5048       ObjCRuntime runtime =
5049         getDarwinToolChain().getDefaultObjCRuntime(/*nonfragile*/ true);
5050       // We use arclite library for both ARC and subscripting support.
5051       if ((!runtime.hasNativeARC() && isObjCAutoRefCount(Args)) ||
5052           !runtime.hasSubscripting())
5053         getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
5054     }
5055     CmdArgs.push_back("-framework");
5056     CmdArgs.push_back("Foundation");
5057     // Link libobj.
5058     CmdArgs.push_back("-lobjc");
5059   }
5060
5061   if (LinkingOutput) {
5062     CmdArgs.push_back("-arch_multiple");
5063     CmdArgs.push_back("-final_output");
5064     CmdArgs.push_back(LinkingOutput);
5065   }
5066
5067   if (Args.hasArg(options::OPT_fnested_functions))
5068     CmdArgs.push_back("-allow_stack_execute");
5069
5070   if (!Args.hasArg(options::OPT_nostdlib) &&
5071       !Args.hasArg(options::OPT_nodefaultlibs)) {
5072     if (getToolChain().getDriver().CCCIsCXX())
5073       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5074
5075     // link_ssp spec is empty.
5076
5077     // Let the tool chain choose which runtime library to link.
5078     getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
5079   }
5080
5081   if (!Args.hasArg(options::OPT_nostdlib) &&
5082       !Args.hasArg(options::OPT_nostartfiles)) {
5083     // endfile_spec is empty.
5084   }
5085
5086   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5087   Args.AddAllArgs(CmdArgs, options::OPT_F);
5088
5089   const char *Exec =
5090     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5091   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5092 }
5093
5094 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
5095                                 const InputInfo &Output,
5096                                 const InputInfoList &Inputs,
5097                                 const ArgList &Args,
5098                                 const char *LinkingOutput) const {
5099   ArgStringList CmdArgs;
5100
5101   CmdArgs.push_back("-create");
5102   assert(Output.isFilename() && "Unexpected lipo output.");
5103
5104   CmdArgs.push_back("-output");
5105   CmdArgs.push_back(Output.getFilename());
5106
5107   for (InputInfoList::const_iterator
5108          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5109     const InputInfo &II = *it;
5110     assert(II.isFilename() && "Unexpected lipo input.");
5111     CmdArgs.push_back(II.getFilename());
5112   }
5113   const char *Exec =
5114     Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
5115   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5116 }
5117
5118 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
5119                                     const InputInfo &Output,
5120                                     const InputInfoList &Inputs,
5121                                     const ArgList &Args,
5122                                     const char *LinkingOutput) const {
5123   ArgStringList CmdArgs;
5124
5125   CmdArgs.push_back("-o");
5126   CmdArgs.push_back(Output.getFilename());
5127
5128   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5129   const InputInfo &Input = Inputs[0];
5130   assert(Input.isFilename() && "Unexpected dsymutil input.");
5131   CmdArgs.push_back(Input.getFilename());
5132
5133   const char *Exec =
5134     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
5135   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5136 }
5137
5138 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
5139                                        const InputInfo &Output,
5140                                        const InputInfoList &Inputs,
5141                                        const ArgList &Args,
5142                                        const char *LinkingOutput) const {
5143   ArgStringList CmdArgs;
5144   CmdArgs.push_back("--verify");
5145   CmdArgs.push_back("--debug-info");
5146   CmdArgs.push_back("--eh-frame");
5147   CmdArgs.push_back("--quiet");
5148
5149   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5150   const InputInfo &Input = Inputs[0];
5151   assert(Input.isFilename() && "Unexpected verify input");
5152
5153   // Grabbing the output of the earlier dsymutil run.
5154   CmdArgs.push_back(Input.getFilename());
5155
5156   const char *Exec =
5157     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
5158   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5159 }
5160
5161 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5162                                       const InputInfo &Output,
5163                                       const InputInfoList &Inputs,
5164                                       const ArgList &Args,
5165                                       const char *LinkingOutput) const {
5166   ArgStringList CmdArgs;
5167
5168   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5169                        options::OPT_Xassembler);
5170
5171   CmdArgs.push_back("-o");
5172   CmdArgs.push_back(Output.getFilename());
5173
5174   for (InputInfoList::const_iterator
5175          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5176     const InputInfo &II = *it;
5177     CmdArgs.push_back(II.getFilename());
5178   }
5179
5180   const char *Exec =
5181     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5182   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5183 }
5184
5185
5186 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
5187                                   const InputInfo &Output,
5188                                   const InputInfoList &Inputs,
5189                                   const ArgList &Args,
5190                                   const char *LinkingOutput) const {
5191   // FIXME: Find a real GCC, don't hard-code versions here
5192   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
5193   const llvm::Triple &T = getToolChain().getTriple();
5194   std::string LibPath = "/usr/lib/";
5195   llvm::Triple::ArchType Arch = T.getArch();
5196   switch (Arch) {
5197   case llvm::Triple::x86:
5198     GCCLibPath +=
5199         ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
5200     break;
5201   case llvm::Triple::x86_64:
5202     GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
5203     GCCLibPath += "/4.5.2/amd64/";
5204     LibPath += "amd64/";
5205     break;
5206   default:
5207     llvm_unreachable("Unsupported architecture");
5208   }
5209
5210   ArgStringList CmdArgs;
5211
5212   // Demangle C++ names in errors
5213   CmdArgs.push_back("-C");
5214
5215   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5216       (!Args.hasArg(options::OPT_shared))) {
5217     CmdArgs.push_back("-e");
5218     CmdArgs.push_back("_start");
5219   }
5220
5221   if (Args.hasArg(options::OPT_static)) {
5222     CmdArgs.push_back("-Bstatic");
5223     CmdArgs.push_back("-dn");
5224   } else {
5225     CmdArgs.push_back("-Bdynamic");
5226     if (Args.hasArg(options::OPT_shared)) {
5227       CmdArgs.push_back("-shared");
5228     } else {
5229       CmdArgs.push_back("--dynamic-linker");
5230       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
5231     }
5232   }
5233
5234   if (Output.isFilename()) {
5235     CmdArgs.push_back("-o");
5236     CmdArgs.push_back(Output.getFilename());
5237   } else {
5238     assert(Output.isNothing() && "Invalid output.");
5239   }
5240
5241   if (!Args.hasArg(options::OPT_nostdlib) &&
5242       !Args.hasArg(options::OPT_nostartfiles)) {
5243     if (!Args.hasArg(options::OPT_shared)) {
5244       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
5245       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5246       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5247       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5248     } else {
5249       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5250       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5251       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5252     }
5253     if (getToolChain().getDriver().CCCIsCXX())
5254       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
5255   }
5256
5257   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
5258
5259   Args.AddAllArgs(CmdArgs, options::OPT_L);
5260   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5261   Args.AddAllArgs(CmdArgs, options::OPT_e);
5262   Args.AddAllArgs(CmdArgs, options::OPT_r);
5263
5264   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5265
5266   if (!Args.hasArg(options::OPT_nostdlib) &&
5267       !Args.hasArg(options::OPT_nodefaultlibs)) {
5268     if (getToolChain().getDriver().CCCIsCXX())
5269       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5270     CmdArgs.push_back("-lgcc_s");
5271     if (!Args.hasArg(options::OPT_shared)) {
5272       CmdArgs.push_back("-lgcc");
5273       CmdArgs.push_back("-lc");
5274       CmdArgs.push_back("-lm");
5275     }
5276   }
5277
5278   if (!Args.hasArg(options::OPT_nostdlib) &&
5279       !Args.hasArg(options::OPT_nostartfiles)) {
5280     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
5281   }
5282   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
5283
5284   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5285
5286   const char *Exec =
5287     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5288   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5289 }
5290
5291 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5292                                       const InputInfo &Output,
5293                                       const InputInfoList &Inputs,
5294                                       const ArgList &Args,
5295                                       const char *LinkingOutput) const {
5296   ArgStringList CmdArgs;
5297
5298   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5299                        options::OPT_Xassembler);
5300
5301   CmdArgs.push_back("-o");
5302   CmdArgs.push_back(Output.getFilename());
5303
5304   for (InputInfoList::const_iterator
5305          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5306     const InputInfo &II = *it;
5307     CmdArgs.push_back(II.getFilename());
5308   }
5309
5310   const char *Exec =
5311     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
5312   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5313 }
5314
5315 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
5316                                   const InputInfo &Output,
5317                                   const InputInfoList &Inputs,
5318                                   const ArgList &Args,
5319                                   const char *LinkingOutput) const {
5320   ArgStringList CmdArgs;
5321
5322   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5323       (!Args.hasArg(options::OPT_shared))) {
5324     CmdArgs.push_back("-e");
5325     CmdArgs.push_back("_start");
5326   }
5327
5328   if (Args.hasArg(options::OPT_static)) {
5329     CmdArgs.push_back("-Bstatic");
5330     CmdArgs.push_back("-dn");
5331   } else {
5332 //    CmdArgs.push_back("--eh-frame-hdr");
5333     CmdArgs.push_back("-Bdynamic");
5334     if (Args.hasArg(options::OPT_shared)) {
5335       CmdArgs.push_back("-shared");
5336     } else {
5337       CmdArgs.push_back("--dynamic-linker");
5338       CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
5339     }
5340   }
5341
5342   if (Output.isFilename()) {
5343     CmdArgs.push_back("-o");
5344     CmdArgs.push_back(Output.getFilename());
5345   } else {
5346     assert(Output.isNothing() && "Invalid output.");
5347   }
5348
5349   if (!Args.hasArg(options::OPT_nostdlib) &&
5350       !Args.hasArg(options::OPT_nostartfiles)) {
5351     if (!Args.hasArg(options::OPT_shared)) {
5352       CmdArgs.push_back(Args.MakeArgString(
5353                                 getToolChain().GetFilePath("crt1.o")));
5354       CmdArgs.push_back(Args.MakeArgString(
5355                                 getToolChain().GetFilePath("crti.o")));
5356       CmdArgs.push_back(Args.MakeArgString(
5357                                 getToolChain().GetFilePath("crtbegin.o")));
5358     } else {
5359       CmdArgs.push_back(Args.MakeArgString(
5360                                 getToolChain().GetFilePath("crti.o")));
5361     }
5362     CmdArgs.push_back(Args.MakeArgString(
5363                                 getToolChain().GetFilePath("crtn.o")));
5364   }
5365
5366   CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
5367                                        + getToolChain().getTripleString()
5368                                        + "/4.2.4"));
5369
5370   Args.AddAllArgs(CmdArgs, options::OPT_L);
5371   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5372   Args.AddAllArgs(CmdArgs, options::OPT_e);
5373
5374   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5375
5376   if (!Args.hasArg(options::OPT_nostdlib) &&
5377       !Args.hasArg(options::OPT_nodefaultlibs)) {
5378     // FIXME: For some reason GCC passes -lgcc before adding
5379     // the default system libraries. Just mimic this for now.
5380     CmdArgs.push_back("-lgcc");
5381
5382     if (Args.hasArg(options::OPT_pthread))
5383       CmdArgs.push_back("-pthread");
5384     if (!Args.hasArg(options::OPT_shared))
5385       CmdArgs.push_back("-lc");
5386     CmdArgs.push_back("-lgcc");
5387   }
5388
5389   if (!Args.hasArg(options::OPT_nostdlib) &&
5390       !Args.hasArg(options::OPT_nostartfiles)) {
5391     if (!Args.hasArg(options::OPT_shared))
5392       CmdArgs.push_back(Args.MakeArgString(
5393                                 getToolChain().GetFilePath("crtend.o")));
5394   }
5395
5396   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5397
5398   const char *Exec =
5399     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5400   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5401 }
5402
5403 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5404                                      const InputInfo &Output,
5405                                      const InputInfoList &Inputs,
5406                                      const ArgList &Args,
5407                                      const char *LinkingOutput) const {
5408   ArgStringList CmdArgs;
5409
5410   // When building 32-bit code on OpenBSD/amd64, we have to explicitly
5411   // instruct as in the base system to assemble 32-bit code.
5412   if (getToolChain().getArch() == llvm::Triple::x86)
5413     CmdArgs.push_back("--32");
5414   else if (getToolChain().getArch() == llvm::Triple::ppc) {
5415     CmdArgs.push_back("-mppc");
5416     CmdArgs.push_back("-many");
5417   } else if (getToolChain().getArch() == llvm::Triple::mips64 ||
5418              getToolChain().getArch() == llvm::Triple::mips64el) {
5419     StringRef CPUName;
5420     StringRef ABIName;
5421     getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
5422
5423     CmdArgs.push_back("-mabi");
5424     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
5425
5426     if (getToolChain().getArch() == llvm::Triple::mips64)
5427       CmdArgs.push_back("-EB");
5428     else
5429       CmdArgs.push_back("-EL");
5430
5431     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5432                                       options::OPT_fpic, options::OPT_fno_pic,
5433                                       options::OPT_fPIE, options::OPT_fno_PIE,
5434                                       options::OPT_fpie, options::OPT_fno_pie);
5435     if (LastPICArg &&
5436         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5437          LastPICArg->getOption().matches(options::OPT_fpic) ||
5438          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5439          LastPICArg->getOption().matches(options::OPT_fpie))) {
5440       CmdArgs.push_back("-KPIC");
5441     }
5442   }
5443
5444   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5445                        options::OPT_Xassembler);
5446
5447   CmdArgs.push_back("-o");
5448   CmdArgs.push_back(Output.getFilename());
5449
5450   for (InputInfoList::const_iterator
5451          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5452     const InputInfo &II = *it;
5453     CmdArgs.push_back(II.getFilename());
5454   }
5455
5456   const char *Exec =
5457     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5458   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5459 }
5460
5461 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5462                                  const InputInfo &Output,
5463                                  const InputInfoList &Inputs,
5464                                  const ArgList &Args,
5465                                  const char *LinkingOutput) const {
5466   const Driver &D = getToolChain().getDriver();
5467   ArgStringList CmdArgs;
5468
5469   // Silence warning for "clang -g foo.o -o foo"
5470   Args.ClaimAllArgs(options::OPT_g_Group);
5471   // and "clang -emit-llvm foo.o -o foo"
5472   Args.ClaimAllArgs(options::OPT_emit_llvm);
5473   // and for "clang -w foo.o -o foo". Other warning options are already
5474   // handled somewhere else.
5475   Args.ClaimAllArgs(options::OPT_w);
5476
5477   if (getToolChain().getArch() == llvm::Triple::mips64)
5478     CmdArgs.push_back("-EB");
5479   else if (getToolChain().getArch() == llvm::Triple::mips64el)
5480     CmdArgs.push_back("-EL");
5481
5482   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5483       (!Args.hasArg(options::OPT_shared))) {
5484     CmdArgs.push_back("-e");
5485     CmdArgs.push_back("__start");
5486   }
5487
5488   if (Args.hasArg(options::OPT_static)) {
5489     CmdArgs.push_back("-Bstatic");
5490   } else {
5491     if (Args.hasArg(options::OPT_rdynamic))
5492       CmdArgs.push_back("-export-dynamic");
5493     CmdArgs.push_back("--eh-frame-hdr");
5494     CmdArgs.push_back("-Bdynamic");
5495     if (Args.hasArg(options::OPT_shared)) {
5496       CmdArgs.push_back("-shared");
5497     } else {
5498       CmdArgs.push_back("-dynamic-linker");
5499       CmdArgs.push_back("/usr/libexec/ld.so");
5500     }
5501   }
5502
5503   if (Args.hasArg(options::OPT_nopie))
5504     CmdArgs.push_back("-nopie");
5505
5506   if (Output.isFilename()) {
5507     CmdArgs.push_back("-o");
5508     CmdArgs.push_back(Output.getFilename());
5509   } else {
5510     assert(Output.isNothing() && "Invalid output.");
5511   }
5512
5513   if (!Args.hasArg(options::OPT_nostdlib) &&
5514       !Args.hasArg(options::OPT_nostartfiles)) {
5515     if (!Args.hasArg(options::OPT_shared)) {
5516       if (Args.hasArg(options::OPT_pg))  
5517         CmdArgs.push_back(Args.MakeArgString(
5518                                 getToolChain().GetFilePath("gcrt0.o")));
5519       else
5520         CmdArgs.push_back(Args.MakeArgString(
5521                                 getToolChain().GetFilePath("crt0.o")));
5522       CmdArgs.push_back(Args.MakeArgString(
5523                               getToolChain().GetFilePath("crtbegin.o")));
5524     } else {
5525       CmdArgs.push_back(Args.MakeArgString(
5526                               getToolChain().GetFilePath("crtbeginS.o")));
5527     }
5528   }
5529
5530   std::string Triple = getToolChain().getTripleString();
5531   if (Triple.substr(0, 6) == "x86_64")
5532     Triple.replace(0, 6, "amd64");
5533   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
5534                                        "/4.2.1"));
5535
5536   Args.AddAllArgs(CmdArgs, options::OPT_L);
5537   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5538   Args.AddAllArgs(CmdArgs, options::OPT_e);
5539   Args.AddAllArgs(CmdArgs, options::OPT_s);
5540   Args.AddAllArgs(CmdArgs, options::OPT_t);
5541   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5542   Args.AddAllArgs(CmdArgs, options::OPT_r);
5543
5544   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5545
5546   if (!Args.hasArg(options::OPT_nostdlib) &&
5547       !Args.hasArg(options::OPT_nodefaultlibs)) {
5548     if (D.CCCIsCXX()) {
5549       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5550       if (Args.hasArg(options::OPT_pg)) 
5551         CmdArgs.push_back("-lm_p");
5552       else
5553         CmdArgs.push_back("-lm");
5554     }
5555
5556     // FIXME: For some reason GCC passes -lgcc before adding
5557     // the default system libraries. Just mimic this for now.
5558     CmdArgs.push_back("-lgcc");
5559
5560     if (Args.hasArg(options::OPT_pthread)) {
5561       if (!Args.hasArg(options::OPT_shared) &&
5562           Args.hasArg(options::OPT_pg))
5563          CmdArgs.push_back("-lpthread_p");
5564       else
5565          CmdArgs.push_back("-lpthread");
5566     }
5567
5568     if (!Args.hasArg(options::OPT_shared)) {
5569       if (Args.hasArg(options::OPT_pg))
5570          CmdArgs.push_back("-lc_p");
5571       else
5572          CmdArgs.push_back("-lc");
5573     }
5574
5575     CmdArgs.push_back("-lgcc");
5576   }
5577
5578   if (!Args.hasArg(options::OPT_nostdlib) &&
5579       !Args.hasArg(options::OPT_nostartfiles)) {
5580     if (!Args.hasArg(options::OPT_shared))
5581       CmdArgs.push_back(Args.MakeArgString(
5582                               getToolChain().GetFilePath("crtend.o")));
5583     else
5584       CmdArgs.push_back(Args.MakeArgString(
5585                               getToolChain().GetFilePath("crtendS.o")));
5586   }
5587
5588   const char *Exec =
5589     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5590   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5591 }
5592
5593 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5594                                     const InputInfo &Output,
5595                                     const InputInfoList &Inputs,
5596                                     const ArgList &Args,
5597                                     const char *LinkingOutput) const {
5598   ArgStringList CmdArgs;
5599
5600   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5601                        options::OPT_Xassembler);
5602
5603   CmdArgs.push_back("-o");
5604   CmdArgs.push_back(Output.getFilename());
5605
5606   for (InputInfoList::const_iterator
5607          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5608     const InputInfo &II = *it;
5609     CmdArgs.push_back(II.getFilename());
5610   }
5611
5612   const char *Exec =
5613     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5614   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5615 }
5616
5617 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
5618                                 const InputInfo &Output,
5619                                 const InputInfoList &Inputs,
5620                                 const ArgList &Args,
5621                                 const char *LinkingOutput) const {
5622   const Driver &D = getToolChain().getDriver();
5623   ArgStringList CmdArgs;
5624
5625   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5626       (!Args.hasArg(options::OPT_shared))) {
5627     CmdArgs.push_back("-e");
5628     CmdArgs.push_back("__start");
5629   }
5630
5631   if (Args.hasArg(options::OPT_static)) {
5632     CmdArgs.push_back("-Bstatic");
5633   } else {
5634     if (Args.hasArg(options::OPT_rdynamic))
5635       CmdArgs.push_back("-export-dynamic");
5636     CmdArgs.push_back("--eh-frame-hdr");
5637     CmdArgs.push_back("-Bdynamic");
5638     if (Args.hasArg(options::OPT_shared)) {
5639       CmdArgs.push_back("-shared");
5640     } else {
5641       CmdArgs.push_back("-dynamic-linker");
5642       CmdArgs.push_back("/usr/libexec/ld.so");
5643     }
5644   }
5645
5646   if (Output.isFilename()) {
5647     CmdArgs.push_back("-o");
5648     CmdArgs.push_back(Output.getFilename());
5649   } else {
5650     assert(Output.isNothing() && "Invalid output.");
5651   }
5652
5653   if (!Args.hasArg(options::OPT_nostdlib) &&
5654       !Args.hasArg(options::OPT_nostartfiles)) {
5655     if (!Args.hasArg(options::OPT_shared)) {
5656       if (Args.hasArg(options::OPT_pg))
5657         CmdArgs.push_back(Args.MakeArgString(
5658                                 getToolChain().GetFilePath("gcrt0.o")));
5659       else
5660         CmdArgs.push_back(Args.MakeArgString(
5661                                 getToolChain().GetFilePath("crt0.o")));
5662       CmdArgs.push_back(Args.MakeArgString(
5663                               getToolChain().GetFilePath("crtbegin.o")));
5664     } else {
5665       CmdArgs.push_back(Args.MakeArgString(
5666                               getToolChain().GetFilePath("crtbeginS.o")));
5667     }
5668   }
5669
5670   Args.AddAllArgs(CmdArgs, options::OPT_L);
5671   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5672   Args.AddAllArgs(CmdArgs, options::OPT_e);
5673
5674   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5675
5676   if (!Args.hasArg(options::OPT_nostdlib) &&
5677       !Args.hasArg(options::OPT_nodefaultlibs)) {
5678     if (D.CCCIsCXX()) {
5679       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5680       if (Args.hasArg(options::OPT_pg))
5681         CmdArgs.push_back("-lm_p");
5682       else
5683         CmdArgs.push_back("-lm");
5684     }
5685
5686     if (Args.hasArg(options::OPT_pthread)) {
5687       if (!Args.hasArg(options::OPT_shared) &&
5688           Args.hasArg(options::OPT_pg))
5689         CmdArgs.push_back("-lpthread_p");
5690       else
5691         CmdArgs.push_back("-lpthread");
5692     }
5693
5694     if (!Args.hasArg(options::OPT_shared)) {
5695       if (Args.hasArg(options::OPT_pg))
5696         CmdArgs.push_back("-lc_p");
5697       else
5698         CmdArgs.push_back("-lc");
5699     }
5700
5701     StringRef MyArch;
5702     switch (getToolChain().getTriple().getArch()) {
5703     case llvm::Triple::arm:
5704       MyArch = "arm";
5705       break;
5706     case llvm::Triple::x86:
5707       MyArch = "i386";
5708       break;
5709     case llvm::Triple::x86_64:
5710       MyArch = "amd64";
5711       break;
5712     default:
5713       llvm_unreachable("Unsupported architecture");
5714     }
5715     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
5716   }
5717
5718   if (!Args.hasArg(options::OPT_nostdlib) &&
5719       !Args.hasArg(options::OPT_nostartfiles)) {
5720     if (!Args.hasArg(options::OPT_shared))
5721       CmdArgs.push_back(Args.MakeArgString(
5722                               getToolChain().GetFilePath("crtend.o")));
5723     else
5724       CmdArgs.push_back(Args.MakeArgString(
5725                               getToolChain().GetFilePath("crtendS.o")));
5726   }
5727
5728   const char *Exec =
5729     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5730   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5731 }
5732
5733 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5734                                      const InputInfo &Output,
5735                                      const InputInfoList &Inputs,
5736                                      const ArgList &Args,
5737                                      const char *LinkingOutput) const {
5738   ArgStringList CmdArgs;
5739
5740   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5741   // instruct as in the base system to assemble 32-bit code.
5742   if (getToolChain().getArch() == llvm::Triple::x86)
5743     CmdArgs.push_back("--32");
5744   else if (getToolChain().getArch() == llvm::Triple::ppc)
5745     CmdArgs.push_back("-a32");
5746   else if (getToolChain().getArch() == llvm::Triple::mips ||
5747            getToolChain().getArch() == llvm::Triple::mipsel ||
5748            getToolChain().getArch() == llvm::Triple::mips64 ||
5749            getToolChain().getArch() == llvm::Triple::mips64el) {
5750     StringRef CPUName;
5751     StringRef ABIName;
5752     getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
5753
5754     CmdArgs.push_back("-march");
5755     CmdArgs.push_back(CPUName.data());
5756
5757     CmdArgs.push_back("-mabi");
5758     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
5759
5760     if (getToolChain().getArch() == llvm::Triple::mips ||
5761         getToolChain().getArch() == llvm::Triple::mips64)
5762       CmdArgs.push_back("-EB");
5763     else
5764       CmdArgs.push_back("-EL");
5765
5766     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5767                                       options::OPT_fpic, options::OPT_fno_pic,
5768                                       options::OPT_fPIE, options::OPT_fno_PIE,
5769                                       options::OPT_fpie, options::OPT_fno_pie);
5770     if (LastPICArg &&
5771         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5772          LastPICArg->getOption().matches(options::OPT_fpic) ||
5773          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5774          LastPICArg->getOption().matches(options::OPT_fpie))) {
5775       CmdArgs.push_back("-KPIC");
5776     }
5777   } else if (getToolChain().getArch() == llvm::Triple::arm ||
5778              getToolChain().getArch() == llvm::Triple::thumb) {
5779     CmdArgs.push_back("-mfpu=softvfp");
5780     switch(getToolChain().getTriple().getEnvironment()) {
5781     case llvm::Triple::GNUEABI:
5782     case llvm::Triple::EABI:
5783       CmdArgs.push_back("-meabi=5");
5784       break;
5785
5786     default:
5787       CmdArgs.push_back("-matpcs");
5788     }
5789   } else if (getToolChain().getArch() == llvm::Triple::sparc ||
5790              getToolChain().getArch() == llvm::Triple::sparcv9) {
5791     if (getToolChain().getArch() == llvm::Triple::sparc)
5792       CmdArgs.push_back("-Av8plusa");
5793     else
5794       CmdArgs.push_back("-Av9a");
5795
5796     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5797                                       options::OPT_fpic, options::OPT_fno_pic,
5798                                       options::OPT_fPIE, options::OPT_fno_PIE,
5799                                       options::OPT_fpie, options::OPT_fno_pie);
5800     if (LastPICArg &&
5801         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5802          LastPICArg->getOption().matches(options::OPT_fpic) ||
5803          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5804          LastPICArg->getOption().matches(options::OPT_fpie))) {
5805       CmdArgs.push_back("-KPIC");
5806     }
5807   }
5808
5809   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5810                        options::OPT_Xassembler);
5811
5812   CmdArgs.push_back("-o");
5813   CmdArgs.push_back(Output.getFilename());
5814
5815   for (InputInfoList::const_iterator
5816          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5817     const InputInfo &II = *it;
5818     CmdArgs.push_back(II.getFilename());
5819   }
5820
5821   const char *Exec =
5822     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5823   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5824 }
5825
5826 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5827                                  const InputInfo &Output,
5828                                  const InputInfoList &Inputs,
5829                                  const ArgList &Args,
5830                                  const char *LinkingOutput) const {
5831   const toolchains::FreeBSD& ToolChain = 
5832     static_cast<const toolchains::FreeBSD&>(getToolChain());
5833   const Driver &D = ToolChain.getDriver();
5834   ArgStringList CmdArgs;
5835
5836   // Silence warning for "clang -g foo.o -o foo"
5837   Args.ClaimAllArgs(options::OPT_g_Group);
5838   // and "clang -emit-llvm foo.o -o foo"
5839   Args.ClaimAllArgs(options::OPT_emit_llvm);
5840   // and for "clang -w foo.o -o foo". Other warning options are already
5841   // handled somewhere else.
5842   Args.ClaimAllArgs(options::OPT_w);
5843
5844   if (!D.SysRoot.empty())
5845     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5846
5847   if (Args.hasArg(options::OPT_pie))
5848     CmdArgs.push_back("-pie");
5849
5850   if (Args.hasArg(options::OPT_static)) {
5851     CmdArgs.push_back("-Bstatic");
5852   } else {
5853     if (Args.hasArg(options::OPT_rdynamic))
5854       CmdArgs.push_back("-export-dynamic");
5855     CmdArgs.push_back("--eh-frame-hdr");
5856     if (Args.hasArg(options::OPT_shared)) {
5857       CmdArgs.push_back("-Bshareable");
5858     } else {
5859       CmdArgs.push_back("-dynamic-linker");
5860       CmdArgs.push_back("/libexec/ld-elf.so.1");
5861     }
5862     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
5863       llvm::Triple::ArchType Arch = ToolChain.getArch();
5864       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
5865           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5866         CmdArgs.push_back("--hash-style=both");
5867       }
5868     }
5869     CmdArgs.push_back("--enable-new-dtags");
5870   }
5871
5872   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5873   // instruct ld in the base system to link 32-bit code.
5874   if (ToolChain.getArch() == llvm::Triple::x86) {
5875     CmdArgs.push_back("-m");
5876     CmdArgs.push_back("elf_i386_fbsd");
5877   }
5878
5879   if (ToolChain.getArch() == llvm::Triple::ppc) {
5880     CmdArgs.push_back("-m");
5881     CmdArgs.push_back("elf32ppc");
5882   }
5883
5884   if (Output.isFilename()) {
5885     CmdArgs.push_back("-o");
5886     CmdArgs.push_back(Output.getFilename());
5887   } else {
5888     assert(Output.isNothing() && "Invalid output.");
5889   }
5890
5891   if (!Args.hasArg(options::OPT_nostdlib) &&
5892       !Args.hasArg(options::OPT_nostartfiles)) {
5893     const char *crt1 = NULL;
5894     if (!Args.hasArg(options::OPT_shared)) {
5895       if (Args.hasArg(options::OPT_pg))
5896         crt1 = "gcrt1.o";
5897       else if (Args.hasArg(options::OPT_pie))
5898         crt1 = "Scrt1.o";
5899       else
5900         crt1 = "crt1.o";
5901     }
5902     if (crt1)
5903       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5904
5905     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5906
5907     const char *crtbegin = NULL;
5908     if (Args.hasArg(options::OPT_static))
5909       crtbegin = "crtbeginT.o";
5910     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5911       crtbegin = "crtbeginS.o";
5912     else
5913       crtbegin = "crtbegin.o";
5914
5915     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5916   }
5917
5918   Args.AddAllArgs(CmdArgs, options::OPT_L);
5919   const ToolChain::path_list Paths = ToolChain.getFilePaths();
5920   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5921        i != e; ++i)
5922     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5923   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5924   Args.AddAllArgs(CmdArgs, options::OPT_e);
5925   Args.AddAllArgs(CmdArgs, options::OPT_s);
5926   Args.AddAllArgs(CmdArgs, options::OPT_t);
5927   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5928   Args.AddAllArgs(CmdArgs, options::OPT_r);
5929
5930   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
5931   // as gold requires -plugin to come before any -plugin-opt that -Wl might
5932   // forward.
5933   if (D.IsUsingLTO(Args)) {
5934     CmdArgs.push_back("-plugin");
5935     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
5936     CmdArgs.push_back(Args.MakeArgString(Plugin));
5937
5938     // Try to pass driver level flags relevant to LTO code generation down to
5939     // the plugin.
5940
5941     // Handle flags for selecting CPU variants.
5942     std::string CPU = getCPUName(Args, ToolChain.getTriple());
5943     if (!CPU.empty()) {
5944       CmdArgs.push_back(
5945                         Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
5946                                            CPU));
5947     }
5948   }
5949
5950   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5951
5952   if (!Args.hasArg(options::OPT_nostdlib) &&
5953       !Args.hasArg(options::OPT_nodefaultlibs)) {
5954     if (D.CCCIsCXX()) {
5955       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5956       if (Args.hasArg(options::OPT_pg))
5957         CmdArgs.push_back("-lm_p");
5958       else
5959         CmdArgs.push_back("-lm");
5960     }
5961     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5962     // the default system libraries. Just mimic this for now.
5963     if (Args.hasArg(options::OPT_pg))
5964       CmdArgs.push_back("-lgcc_p");
5965     else
5966       CmdArgs.push_back("-lgcc");
5967     if (Args.hasArg(options::OPT_static)) {
5968       CmdArgs.push_back("-lgcc_eh");
5969     } else if (Args.hasArg(options::OPT_pg)) {
5970       CmdArgs.push_back("-lgcc_eh_p");
5971     } else {
5972       CmdArgs.push_back("--as-needed");
5973       CmdArgs.push_back("-lgcc_s");
5974       CmdArgs.push_back("--no-as-needed");
5975     }
5976
5977     if (Args.hasArg(options::OPT_pthread)) {
5978       if (Args.hasArg(options::OPT_pg))
5979         CmdArgs.push_back("-lpthread_p");
5980       else
5981         CmdArgs.push_back("-lpthread");
5982     }
5983
5984     if (Args.hasArg(options::OPT_pg)) {
5985       if (Args.hasArg(options::OPT_shared))
5986         CmdArgs.push_back("-lc");
5987       else
5988         CmdArgs.push_back("-lc_p");
5989       CmdArgs.push_back("-lgcc_p");
5990     } else {
5991       CmdArgs.push_back("-lc");
5992       CmdArgs.push_back("-lgcc");
5993     }
5994
5995     if (Args.hasArg(options::OPT_static)) {
5996       CmdArgs.push_back("-lgcc_eh");
5997     } else if (Args.hasArg(options::OPT_pg)) {
5998       CmdArgs.push_back("-lgcc_eh_p");
5999     } else {
6000       CmdArgs.push_back("--as-needed");
6001       CmdArgs.push_back("-lgcc_s");
6002       CmdArgs.push_back("--no-as-needed");
6003     }
6004   }
6005
6006   if (!Args.hasArg(options::OPT_nostdlib) &&
6007       !Args.hasArg(options::OPT_nostartfiles)) {
6008     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6009       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
6010     else
6011       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6012     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6013   }
6014
6015   addProfileRT(ToolChain, Args, CmdArgs, ToolChain.getTriple());
6016
6017   const char *Exec =
6018     Args.MakeArgString(ToolChain.GetProgramPath("ld"));
6019   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6020 }
6021
6022 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6023                                      const InputInfo &Output,
6024                                      const InputInfoList &Inputs,
6025                                      const ArgList &Args,
6026                                      const char *LinkingOutput) const {
6027   ArgStringList CmdArgs;
6028
6029   // When building 32-bit code on NetBSD/amd64, we have to explicitly
6030   // instruct as in the base system to assemble 32-bit code.
6031   if (getToolChain().getArch() == llvm::Triple::x86)
6032     CmdArgs.push_back("--32");
6033
6034   // Pass the target CPU to GNU as for ARM, since the source code might
6035   // not have the correct .cpu annotation.
6036   if (getToolChain().getArch() == llvm::Triple::arm) {
6037     std::string MArch(getARMTargetCPU(Args, getToolChain().getTriple()));
6038     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
6039   }
6040
6041   if (getToolChain().getArch() == llvm::Triple::mips ||
6042       getToolChain().getArch() == llvm::Triple::mipsel ||
6043       getToolChain().getArch() == llvm::Triple::mips64 ||
6044       getToolChain().getArch() == llvm::Triple::mips64el) {
6045     StringRef CPUName;
6046     StringRef ABIName;
6047     getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6048
6049     CmdArgs.push_back("-march");
6050     CmdArgs.push_back(CPUName.data());
6051
6052     CmdArgs.push_back("-mabi");
6053     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6054
6055     if (getToolChain().getArch() == llvm::Triple::mips ||
6056         getToolChain().getArch() == llvm::Triple::mips64)
6057       CmdArgs.push_back("-EB");
6058     else
6059       CmdArgs.push_back("-EL");
6060
6061     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
6062                                       options::OPT_fpic, options::OPT_fno_pic,
6063                                       options::OPT_fPIE, options::OPT_fno_PIE,
6064                                       options::OPT_fpie, options::OPT_fno_pie);
6065     if (LastPICArg &&
6066         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
6067          LastPICArg->getOption().matches(options::OPT_fpic) ||
6068          LastPICArg->getOption().matches(options::OPT_fPIE) ||
6069          LastPICArg->getOption().matches(options::OPT_fpie))) {
6070       CmdArgs.push_back("-KPIC");
6071     }
6072   }
6073
6074   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6075                        options::OPT_Xassembler);
6076
6077   CmdArgs.push_back("-o");
6078   CmdArgs.push_back(Output.getFilename());
6079
6080   for (InputInfoList::const_iterator
6081          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6082     const InputInfo &II = *it;
6083     CmdArgs.push_back(II.getFilename());
6084   }
6085
6086   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
6087   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6088 }
6089
6090 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6091                                  const InputInfo &Output,
6092                                  const InputInfoList &Inputs,
6093                                  const ArgList &Args,
6094                                  const char *LinkingOutput) const {
6095   const Driver &D = getToolChain().getDriver();
6096   ArgStringList CmdArgs;
6097
6098   if (!D.SysRoot.empty())
6099     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6100
6101   if (Args.hasArg(options::OPT_static)) {
6102     CmdArgs.push_back("-Bstatic");
6103   } else {
6104     if (Args.hasArg(options::OPT_rdynamic))
6105       CmdArgs.push_back("-export-dynamic");
6106     CmdArgs.push_back("--eh-frame-hdr");
6107     if (Args.hasArg(options::OPT_shared)) {
6108       CmdArgs.push_back("-Bshareable");
6109     } else {
6110       CmdArgs.push_back("-dynamic-linker");
6111       CmdArgs.push_back("/libexec/ld.elf_so");
6112     }
6113   }
6114
6115   // When building 32-bit code on NetBSD/amd64, we have to explicitly
6116   // instruct ld in the base system to link 32-bit code.
6117   if (getToolChain().getArch() == llvm::Triple::x86) {
6118     CmdArgs.push_back("-m");
6119     CmdArgs.push_back("elf_i386");
6120   }
6121
6122   if (Output.isFilename()) {
6123     CmdArgs.push_back("-o");
6124     CmdArgs.push_back(Output.getFilename());
6125   } else {
6126     assert(Output.isNothing() && "Invalid output.");
6127   }
6128
6129   if (!Args.hasArg(options::OPT_nostdlib) &&
6130       !Args.hasArg(options::OPT_nostartfiles)) {
6131     if (!Args.hasArg(options::OPT_shared)) {
6132       CmdArgs.push_back(Args.MakeArgString(
6133                               getToolChain().GetFilePath("crt0.o")));
6134       CmdArgs.push_back(Args.MakeArgString(
6135                               getToolChain().GetFilePath("crti.o")));
6136       CmdArgs.push_back(Args.MakeArgString(
6137                               getToolChain().GetFilePath("crtbegin.o")));
6138     } else {
6139       CmdArgs.push_back(Args.MakeArgString(
6140                               getToolChain().GetFilePath("crti.o")));
6141       CmdArgs.push_back(Args.MakeArgString(
6142                               getToolChain().GetFilePath("crtbeginS.o")));
6143     }
6144   }
6145
6146   Args.AddAllArgs(CmdArgs, options::OPT_L);
6147   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6148   Args.AddAllArgs(CmdArgs, options::OPT_e);
6149   Args.AddAllArgs(CmdArgs, options::OPT_s);
6150   Args.AddAllArgs(CmdArgs, options::OPT_t);
6151   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6152   Args.AddAllArgs(CmdArgs, options::OPT_r);
6153
6154   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6155
6156   unsigned Major, Minor, Micro;
6157   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
6158   bool useLibgcc = true;
6159   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 23) || Major == 0) {
6160     if (getToolChain().getArch() == llvm::Triple::x86 ||
6161         getToolChain().getArch() == llvm::Triple::x86_64)
6162       useLibgcc = false;
6163   }
6164
6165   if (!Args.hasArg(options::OPT_nostdlib) &&
6166       !Args.hasArg(options::OPT_nodefaultlibs)) {
6167     if (D.CCCIsCXX()) {
6168       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6169       CmdArgs.push_back("-lm");
6170     }
6171     if (Args.hasArg(options::OPT_pthread))
6172       CmdArgs.push_back("-lpthread");
6173     CmdArgs.push_back("-lc");
6174
6175     if (useLibgcc) {
6176       if (Args.hasArg(options::OPT_static)) {
6177         // libgcc_eh depends on libc, so resolve as much as possible,
6178         // pull in any new requirements from libc and then get the rest
6179         // of libgcc.
6180         CmdArgs.push_back("-lgcc_eh");
6181         CmdArgs.push_back("-lc");
6182         CmdArgs.push_back("-lgcc");
6183       } else {
6184         CmdArgs.push_back("-lgcc");
6185         CmdArgs.push_back("--as-needed");
6186         CmdArgs.push_back("-lgcc_s");
6187         CmdArgs.push_back("--no-as-needed");
6188       }
6189     }
6190   }
6191
6192   if (!Args.hasArg(options::OPT_nostdlib) &&
6193       !Args.hasArg(options::OPT_nostartfiles)) {
6194     if (!Args.hasArg(options::OPT_shared))
6195       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6196                                                                   "crtend.o")));
6197     else
6198       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6199                                                                  "crtendS.o")));
6200     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6201                                                                     "crtn.o")));
6202   }
6203
6204   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6205
6206   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6207   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6208 }
6209
6210 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6211                                       const InputInfo &Output,
6212                                       const InputInfoList &Inputs,
6213                                       const ArgList &Args,
6214                                       const char *LinkingOutput) const {
6215   ArgStringList CmdArgs;
6216   bool NeedsKPIC = false;
6217
6218   // Add --32/--64 to make sure we get the format we want.
6219   // This is incomplete
6220   if (getToolChain().getArch() == llvm::Triple::x86) {
6221     CmdArgs.push_back("--32");
6222   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
6223     CmdArgs.push_back("--64");
6224   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
6225     CmdArgs.push_back("-a32");
6226     CmdArgs.push_back("-mppc");
6227     CmdArgs.push_back("-many");
6228   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
6229     CmdArgs.push_back("-a64");
6230     CmdArgs.push_back("-mppc64");
6231     CmdArgs.push_back("-many");
6232   } else if (getToolChain().getArch() == llvm::Triple::ppc64le) {
6233     CmdArgs.push_back("-a64");
6234     CmdArgs.push_back("-mppc64le");
6235     CmdArgs.push_back("-many");
6236   } else if (getToolChain().getArch() == llvm::Triple::sparc) {
6237     CmdArgs.push_back("-32");
6238     CmdArgs.push_back("-Av8plusa");
6239     NeedsKPIC = true;
6240   } else if (getToolChain().getArch() == llvm::Triple::sparcv9) {
6241     CmdArgs.push_back("-64");
6242     CmdArgs.push_back("-Av9a");
6243     NeedsKPIC = true;
6244   } else if (getToolChain().getArch() == llvm::Triple::arm) {
6245     StringRef MArch = getToolChain().getArchName();
6246     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
6247       CmdArgs.push_back("-mfpu=neon");
6248     if (MArch == "armv8" || MArch == "armv8a" || MArch == "armv8-a")
6249       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
6250
6251     StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
6252                                            getToolChain().getTriple());
6253     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
6254
6255     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
6256     Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
6257     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
6258   } else if (getToolChain().getArch() == llvm::Triple::mips ||
6259              getToolChain().getArch() == llvm::Triple::mipsel ||
6260              getToolChain().getArch() == llvm::Triple::mips64 ||
6261              getToolChain().getArch() == llvm::Triple::mips64el) {
6262     StringRef CPUName;
6263     StringRef ABIName;
6264     getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6265
6266     CmdArgs.push_back("-march");
6267     CmdArgs.push_back(CPUName.data());
6268
6269     CmdArgs.push_back("-mabi");
6270     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6271
6272     if (getToolChain().getArch() == llvm::Triple::mips ||
6273         getToolChain().getArch() == llvm::Triple::mips64)
6274       CmdArgs.push_back("-EB");
6275     else
6276       CmdArgs.push_back("-EL");
6277
6278     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
6279       if (StringRef(A->getValue()) == "2008")
6280         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
6281     }
6282
6283     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfp64)) {
6284       if (A->getOption().matches(options::OPT_mfp32))
6285         CmdArgs.push_back(Args.MakeArgString("-mfp32"));
6286       else
6287         CmdArgs.push_back(Args.MakeArgString("-mfp64"));
6288     }
6289
6290     Args.AddLastArg(CmdArgs, options::OPT_mips16, options::OPT_mno_mips16);
6291     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
6292                     options::OPT_mno_micromips);
6293     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
6294     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
6295
6296     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
6297       // Do not use AddLastArg because not all versions of MIPS assembler
6298       // support -mmsa / -mno-msa options.
6299       if (A->getOption().matches(options::OPT_mmsa))
6300         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
6301     }
6302
6303     NeedsKPIC = true;
6304   } else if (getToolChain().getArch() == llvm::Triple::systemz) {
6305     // Always pass an -march option, since our default of z10 is later
6306     // than the GNU assembler's default.
6307     StringRef CPUName = getSystemZTargetCPU(Args);
6308     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
6309   }
6310
6311   if (NeedsKPIC) {
6312     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
6313                                       options::OPT_fpic, options::OPT_fno_pic,
6314                                       options::OPT_fPIE, options::OPT_fno_PIE,
6315                                       options::OPT_fpie, options::OPT_fno_pie);
6316     if (LastPICArg &&
6317         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
6318          LastPICArg->getOption().matches(options::OPT_fpic) ||
6319          LastPICArg->getOption().matches(options::OPT_fPIE) ||
6320          LastPICArg->getOption().matches(options::OPT_fpie))) {
6321       CmdArgs.push_back("-KPIC");
6322     }
6323   }
6324
6325   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6326                        options::OPT_Xassembler);
6327
6328   CmdArgs.push_back("-o");
6329   CmdArgs.push_back(Output.getFilename());
6330
6331   for (InputInfoList::const_iterator
6332          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6333     const InputInfo &II = *it;
6334     CmdArgs.push_back(II.getFilename());
6335   }
6336
6337   const char *Exec =
6338     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6339   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6340
6341   // Handle the debug info splitting at object creation time if we're
6342   // creating an object.
6343   // TODO: Currently only works on linux with newer objcopy.
6344   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6345       getToolChain().getTriple().isOSLinux())
6346     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6347                    SplitDebugName(Args, Inputs));
6348 }
6349
6350 static void AddLibgcc(llvm::Triple Triple, const Driver &D,
6351                       ArgStringList &CmdArgs, const ArgList &Args) {
6352   bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
6353   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
6354                       Args.hasArg(options::OPT_static);
6355   if (!D.CCCIsCXX())
6356     CmdArgs.push_back("-lgcc");
6357
6358   if (StaticLibgcc || isAndroid) {
6359     if (D.CCCIsCXX())
6360       CmdArgs.push_back("-lgcc");
6361   } else {
6362     if (!D.CCCIsCXX())
6363       CmdArgs.push_back("--as-needed");
6364     CmdArgs.push_back("-lgcc_s");
6365     if (!D.CCCIsCXX())
6366       CmdArgs.push_back("--no-as-needed");
6367   }
6368
6369   if (StaticLibgcc && !isAndroid)
6370     CmdArgs.push_back("-lgcc_eh");
6371   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
6372     CmdArgs.push_back("-lgcc");
6373
6374   // According to Android ABI, we have to link with libdl if we are
6375   // linking with non-static libgcc.
6376   //
6377   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
6378   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
6379   if (isAndroid && !StaticLibgcc)
6380     CmdArgs.push_back("-ldl");
6381 }
6382
6383 static bool hasMipsN32ABIArg(const ArgList &Args) {
6384   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6385   return A && (A->getValue() == StringRef("n32"));
6386 }
6387
6388 static StringRef getLinuxDynamicLinker(const ArgList &Args,
6389                                        const toolchains::Linux &ToolChain) {
6390   if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android)
6391     return "/system/bin/linker";
6392   else if (ToolChain.getArch() == llvm::Triple::x86 ||
6393            ToolChain.getArch() == llvm::Triple::sparc)
6394     return "/lib/ld-linux.so.2";
6395   else if (ToolChain.getArch() == llvm::Triple::aarch64)
6396     return "/lib/ld-linux-aarch64.so.1";
6397   else if (ToolChain.getArch() == llvm::Triple::arm ||
6398            ToolChain.getArch() == llvm::Triple::thumb) {
6399     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
6400       return "/lib/ld-linux-armhf.so.3";
6401     else
6402       return "/lib/ld-linux.so.3";
6403   } else if (ToolChain.getArch() == llvm::Triple::mips ||
6404              ToolChain.getArch() == llvm::Triple::mipsel)
6405     return "/lib/ld.so.1";
6406   else if (ToolChain.getArch() == llvm::Triple::mips64 ||
6407            ToolChain.getArch() == llvm::Triple::mips64el) {
6408     if (hasMipsN32ABIArg(Args))
6409       return "/lib32/ld.so.1";
6410     else
6411       return "/lib64/ld.so.1";
6412   } else if (ToolChain.getArch() == llvm::Triple::ppc)
6413     return "/lib/ld.so.1";
6414   else if (ToolChain.getArch() == llvm::Triple::ppc64 ||
6415            ToolChain.getArch() == llvm::Triple::ppc64le ||
6416            ToolChain.getArch() == llvm::Triple::systemz)
6417     return "/lib64/ld64.so.1";
6418   else if (ToolChain.getArch() == llvm::Triple::sparcv9)
6419     return "/lib64/ld-linux.so.2";
6420   else
6421     return "/lib64/ld-linux-x86-64.so.2";
6422 }
6423
6424 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
6425                                   const InputInfo &Output,
6426                                   const InputInfoList &Inputs,
6427                                   const ArgList &Args,
6428                                   const char *LinkingOutput) const {
6429   const toolchains::Linux& ToolChain =
6430     static_cast<const toolchains::Linux&>(getToolChain());
6431   const Driver &D = ToolChain.getDriver();
6432   const bool isAndroid =
6433     ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
6434   const SanitizerArgs &Sanitize = ToolChain.getSanitizerArgs();
6435   const bool IsPIE =
6436     !Args.hasArg(options::OPT_shared) &&
6437     (Args.hasArg(options::OPT_pie) || Sanitize.hasZeroBaseShadow());
6438
6439   ArgStringList CmdArgs;
6440
6441   // Silence warning for "clang -g foo.o -o foo"
6442   Args.ClaimAllArgs(options::OPT_g_Group);
6443   // and "clang -emit-llvm foo.o -o foo"
6444   Args.ClaimAllArgs(options::OPT_emit_llvm);
6445   // and for "clang -w foo.o -o foo". Other warning options are already
6446   // handled somewhere else.
6447   Args.ClaimAllArgs(options::OPT_w);
6448
6449   if (!D.SysRoot.empty())
6450     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6451
6452   if (IsPIE)
6453     CmdArgs.push_back("-pie");
6454
6455   if (Args.hasArg(options::OPT_rdynamic))
6456     CmdArgs.push_back("-export-dynamic");
6457
6458   if (Args.hasArg(options::OPT_s))
6459     CmdArgs.push_back("-s");
6460
6461   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
6462          e = ToolChain.ExtraOpts.end();
6463        i != e; ++i)
6464     CmdArgs.push_back(i->c_str());
6465
6466   if (!Args.hasArg(options::OPT_static)) {
6467     CmdArgs.push_back("--eh-frame-hdr");
6468   }
6469
6470   CmdArgs.push_back("-m");
6471   if (ToolChain.getArch() == llvm::Triple::x86)
6472     CmdArgs.push_back("elf_i386");
6473   else if (ToolChain.getArch() == llvm::Triple::aarch64)
6474     CmdArgs.push_back("aarch64linux");
6475   else if (ToolChain.getArch() == llvm::Triple::arm
6476            ||  ToolChain.getArch() == llvm::Triple::thumb)
6477     CmdArgs.push_back("armelf_linux_eabi");
6478   else if (ToolChain.getArch() == llvm::Triple::ppc)
6479     CmdArgs.push_back("elf32ppclinux");
6480   else if (ToolChain.getArch() == llvm::Triple::ppc64)
6481     CmdArgs.push_back("elf64ppc");
6482   else if (ToolChain.getArch() == llvm::Triple::sparc)
6483     CmdArgs.push_back("elf32_sparc");
6484   else if (ToolChain.getArch() == llvm::Triple::sparcv9)
6485     CmdArgs.push_back("elf64_sparc");
6486   else if (ToolChain.getArch() == llvm::Triple::mips)
6487     CmdArgs.push_back("elf32btsmip");
6488   else if (ToolChain.getArch() == llvm::Triple::mipsel)
6489     CmdArgs.push_back("elf32ltsmip");
6490   else if (ToolChain.getArch() == llvm::Triple::mips64) {
6491     if (hasMipsN32ABIArg(Args))
6492       CmdArgs.push_back("elf32btsmipn32");
6493     else
6494       CmdArgs.push_back("elf64btsmip");
6495   }
6496   else if (ToolChain.getArch() == llvm::Triple::mips64el) {
6497     if (hasMipsN32ABIArg(Args))
6498       CmdArgs.push_back("elf32ltsmipn32");
6499     else
6500       CmdArgs.push_back("elf64ltsmip");
6501   }
6502   else if (ToolChain.getArch() == llvm::Triple::systemz)
6503     CmdArgs.push_back("elf64_s390");
6504   else
6505     CmdArgs.push_back("elf_x86_64");
6506
6507   if (Args.hasArg(options::OPT_static)) {
6508     if (ToolChain.getArch() == llvm::Triple::arm
6509         || ToolChain.getArch() == llvm::Triple::thumb)
6510       CmdArgs.push_back("-Bstatic");
6511     else
6512       CmdArgs.push_back("-static");
6513   } else if (Args.hasArg(options::OPT_shared)) {
6514     CmdArgs.push_back("-shared");
6515     if (isAndroid) {
6516       CmdArgs.push_back("-Bsymbolic");
6517     }
6518   }
6519
6520   if (ToolChain.getArch() == llvm::Triple::arm ||
6521       ToolChain.getArch() == llvm::Triple::thumb ||
6522       (!Args.hasArg(options::OPT_static) &&
6523        !Args.hasArg(options::OPT_shared))) {
6524     CmdArgs.push_back("-dynamic-linker");
6525     CmdArgs.push_back(Args.MakeArgString(
6526         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
6527   }
6528
6529   CmdArgs.push_back("-o");
6530   CmdArgs.push_back(Output.getFilename());
6531
6532   if (!Args.hasArg(options::OPT_nostdlib) &&
6533       !Args.hasArg(options::OPT_nostartfiles)) {
6534     if (!isAndroid) {
6535       const char *crt1 = NULL;
6536       if (!Args.hasArg(options::OPT_shared)){
6537         if (Args.hasArg(options::OPT_pg))
6538           crt1 = "gcrt1.o";
6539         else if (IsPIE)
6540           crt1 = "Scrt1.o";
6541         else
6542           crt1 = "crt1.o";
6543       }
6544       if (crt1)
6545         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
6546
6547       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
6548     }
6549
6550     const char *crtbegin;
6551     if (Args.hasArg(options::OPT_static))
6552       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
6553     else if (Args.hasArg(options::OPT_shared))
6554       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
6555     else if (IsPIE)
6556       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
6557     else
6558       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
6559     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
6560
6561     // Add crtfastmath.o if available and fast math is enabled.
6562     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
6563   }
6564
6565   Args.AddAllArgs(CmdArgs, options::OPT_L);
6566
6567   const ToolChain::path_list Paths = ToolChain.getFilePaths();
6568
6569   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
6570        i != e; ++i)
6571     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
6572
6573   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
6574   // as gold requires -plugin to come before any -plugin-opt that -Wl might
6575   // forward.
6576   if (D.IsUsingLTO(Args)) {
6577     CmdArgs.push_back("-plugin");
6578     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
6579     CmdArgs.push_back(Args.MakeArgString(Plugin));
6580
6581     // Try to pass driver level flags relevant to LTO code generation down to
6582     // the plugin.
6583
6584     // Handle flags for selecting CPU variants.
6585     std::string CPU = getCPUName(Args, ToolChain.getTriple());
6586     if (!CPU.empty()) {
6587       CmdArgs.push_back(
6588                         Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
6589                                            CPU));
6590     }
6591   }
6592
6593
6594   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6595     CmdArgs.push_back("--no-demangle");
6596
6597   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6598
6599   // Call these before we add the C++ ABI library.
6600   if (Sanitize.needsUbsanRt())
6601     addUbsanRTLinux(getToolChain(), Args, CmdArgs, D.CCCIsCXX(),
6602                     Sanitize.needsAsanRt() || Sanitize.needsTsanRt() ||
6603                     Sanitize.needsMsanRt() || Sanitize.needsLsanRt());
6604   if (Sanitize.needsAsanRt())
6605     addAsanRTLinux(getToolChain(), Args, CmdArgs);
6606   if (Sanitize.needsTsanRt())
6607     addTsanRTLinux(getToolChain(), Args, CmdArgs);
6608   if (Sanitize.needsMsanRt())
6609     addMsanRTLinux(getToolChain(), Args, CmdArgs);
6610   if (Sanitize.needsLsanRt())
6611     addLsanRTLinux(getToolChain(), Args, CmdArgs);
6612   if (Sanitize.needsDfsanRt())
6613     addDfsanRTLinux(getToolChain(), Args, CmdArgs);
6614
6615   // The profile runtime also needs access to system libraries.
6616   addProfileRTLinux(getToolChain(), Args, CmdArgs);
6617
6618   if (D.CCCIsCXX() &&
6619       !Args.hasArg(options::OPT_nostdlib) &&
6620       !Args.hasArg(options::OPT_nodefaultlibs)) {
6621     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
6622       !Args.hasArg(options::OPT_static);
6623     if (OnlyLibstdcxxStatic)
6624       CmdArgs.push_back("-Bstatic");
6625     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6626     if (OnlyLibstdcxxStatic)
6627       CmdArgs.push_back("-Bdynamic");
6628     CmdArgs.push_back("-lm");
6629   }
6630
6631   if (!Args.hasArg(options::OPT_nostdlib)) {
6632     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
6633       if (Args.hasArg(options::OPT_static))
6634         CmdArgs.push_back("--start-group");
6635
6636       bool OpenMP = Args.hasArg(options::OPT_fopenmp);
6637       if (OpenMP) {
6638         CmdArgs.push_back("-lgomp");
6639
6640         // FIXME: Exclude this for platforms whith libgomp that doesn't require
6641         // librt. Most modern Linux platfroms require it, but some may not.
6642         CmdArgs.push_back("-lrt");
6643       }
6644
6645       AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6646
6647       if (Args.hasArg(options::OPT_pthread) ||
6648           Args.hasArg(options::OPT_pthreads) || OpenMP)
6649         CmdArgs.push_back("-lpthread");
6650
6651       CmdArgs.push_back("-lc");
6652
6653       if (Args.hasArg(options::OPT_static))
6654         CmdArgs.push_back("--end-group");
6655       else
6656         AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6657     }
6658
6659     if (!Args.hasArg(options::OPT_nostartfiles)) {
6660       const char *crtend;
6661       if (Args.hasArg(options::OPT_shared))
6662         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
6663       else if (IsPIE)
6664         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
6665       else
6666         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
6667
6668       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
6669       if (!isAndroid)
6670         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6671     }
6672   }
6673
6674   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
6675 }
6676
6677 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6678                                    const InputInfo &Output,
6679                                    const InputInfoList &Inputs,
6680                                    const ArgList &Args,
6681                                    const char *LinkingOutput) const {
6682   ArgStringList CmdArgs;
6683
6684   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6685                        options::OPT_Xassembler);
6686
6687   CmdArgs.push_back("-o");
6688   CmdArgs.push_back(Output.getFilename());
6689
6690   for (InputInfoList::const_iterator
6691          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6692     const InputInfo &II = *it;
6693     CmdArgs.push_back(II.getFilename());
6694   }
6695
6696   const char *Exec =
6697     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6698   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6699 }
6700
6701 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
6702                                const InputInfo &Output,
6703                                const InputInfoList &Inputs,
6704                                const ArgList &Args,
6705                                const char *LinkingOutput) const {
6706   const Driver &D = getToolChain().getDriver();
6707   ArgStringList CmdArgs;
6708
6709   if (Output.isFilename()) {
6710     CmdArgs.push_back("-o");
6711     CmdArgs.push_back(Output.getFilename());
6712   } else {
6713     assert(Output.isNothing() && "Invalid output.");
6714   }
6715
6716   if (!Args.hasArg(options::OPT_nostdlib) &&
6717       !Args.hasArg(options::OPT_nostartfiles)) {
6718       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
6719       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6720       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6721       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
6722   }
6723
6724   Args.AddAllArgs(CmdArgs, options::OPT_L);
6725   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6726   Args.AddAllArgs(CmdArgs, options::OPT_e);
6727
6728   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6729
6730   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6731
6732   if (!Args.hasArg(options::OPT_nostdlib) &&
6733       !Args.hasArg(options::OPT_nodefaultlibs)) {
6734     if (D.CCCIsCXX()) {
6735       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6736       CmdArgs.push_back("-lm");
6737     }
6738   }
6739
6740   if (!Args.hasArg(options::OPT_nostdlib) &&
6741       !Args.hasArg(options::OPT_nostartfiles)) {
6742     if (Args.hasArg(options::OPT_pthread))
6743       CmdArgs.push_back("-lpthread");
6744     CmdArgs.push_back("-lc");
6745     CmdArgs.push_back("-lCompilerRT-Generic");
6746     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
6747     CmdArgs.push_back(
6748          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
6749   }
6750
6751   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6752   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6753 }
6754
6755 /// DragonFly Tools
6756
6757 // For now, DragonFly Assemble does just about the same as for
6758 // FreeBSD, but this may change soon.
6759 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6760                                        const InputInfo &Output,
6761                                        const InputInfoList &Inputs,
6762                                        const ArgList &Args,
6763                                        const char *LinkingOutput) const {
6764   ArgStringList CmdArgs;
6765
6766   // When building 32-bit code on DragonFly/pc64, we have to explicitly
6767   // instruct as in the base system to assemble 32-bit code.
6768   if (getToolChain().getArch() == llvm::Triple::x86)
6769     CmdArgs.push_back("--32");
6770
6771   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6772                        options::OPT_Xassembler);
6773
6774   CmdArgs.push_back("-o");
6775   CmdArgs.push_back(Output.getFilename());
6776
6777   for (InputInfoList::const_iterator
6778          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6779     const InputInfo &II = *it;
6780     CmdArgs.push_back(II.getFilename());
6781   }
6782
6783   const char *Exec =
6784     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6785   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6786 }
6787
6788 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
6789                                    const InputInfo &Output,
6790                                    const InputInfoList &Inputs,
6791                                    const ArgList &Args,
6792                                    const char *LinkingOutput) const {
6793   bool UseGCC47 = false;
6794   const Driver &D = getToolChain().getDriver();
6795   ArgStringList CmdArgs;
6796
6797   if (llvm::sys::fs::exists("/usr/lib/gcc47", UseGCC47))
6798     UseGCC47 = false;
6799
6800   if (!D.SysRoot.empty())
6801     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6802
6803   CmdArgs.push_back("--eh-frame-hdr");
6804   if (Args.hasArg(options::OPT_static)) {
6805     CmdArgs.push_back("-Bstatic");
6806   } else {
6807     if (Args.hasArg(options::OPT_rdynamic))
6808       CmdArgs.push_back("-export-dynamic");
6809     if (Args.hasArg(options::OPT_shared))
6810       CmdArgs.push_back("-Bshareable");
6811     else {
6812       CmdArgs.push_back("-dynamic-linker");
6813       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
6814     }
6815     CmdArgs.push_back("--hash-style=both");
6816   }
6817
6818   // When building 32-bit code on DragonFly/pc64, we have to explicitly
6819   // instruct ld in the base system to link 32-bit code.
6820   if (getToolChain().getArch() == llvm::Triple::x86) {
6821     CmdArgs.push_back("-m");
6822     CmdArgs.push_back("elf_i386");
6823   }
6824
6825   if (Output.isFilename()) {
6826     CmdArgs.push_back("-o");
6827     CmdArgs.push_back(Output.getFilename());
6828   } else {
6829     assert(Output.isNothing() && "Invalid output.");
6830   }
6831
6832   if (!Args.hasArg(options::OPT_nostdlib) &&
6833       !Args.hasArg(options::OPT_nostartfiles)) {
6834     if (!Args.hasArg(options::OPT_shared)) {
6835       if (Args.hasArg(options::OPT_pg))
6836         CmdArgs.push_back(Args.MakeArgString(
6837                                 getToolChain().GetFilePath("gcrt1.o")));
6838       else {
6839         if (Args.hasArg(options::OPT_pie))
6840           CmdArgs.push_back(Args.MakeArgString(
6841                                   getToolChain().GetFilePath("Scrt1.o")));
6842         else
6843           CmdArgs.push_back(Args.MakeArgString(
6844                                   getToolChain().GetFilePath("crt1.o")));
6845       }
6846     }
6847     CmdArgs.push_back(Args.MakeArgString(
6848                             getToolChain().GetFilePath("crti.o")));
6849     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6850       CmdArgs.push_back(Args.MakeArgString(
6851                               getToolChain().GetFilePath("crtbeginS.o")));
6852     else
6853       CmdArgs.push_back(Args.MakeArgString(
6854                               getToolChain().GetFilePath("crtbegin.o")));
6855   }
6856
6857   Args.AddAllArgs(CmdArgs, options::OPT_L);
6858   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6859   Args.AddAllArgs(CmdArgs, options::OPT_e);
6860
6861   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6862
6863   if (!Args.hasArg(options::OPT_nostdlib) &&
6864       !Args.hasArg(options::OPT_nodefaultlibs)) {
6865     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
6866     //         rpaths
6867     if (UseGCC47)
6868       CmdArgs.push_back("-L/usr/lib/gcc47");
6869     else
6870       CmdArgs.push_back("-L/usr/lib/gcc44");
6871
6872     if (!Args.hasArg(options::OPT_static)) {
6873       if (UseGCC47) {
6874         CmdArgs.push_back("-rpath");
6875         CmdArgs.push_back("/usr/lib/gcc47");
6876       } else {
6877         CmdArgs.push_back("-rpath");
6878         CmdArgs.push_back("/usr/lib/gcc44");
6879       }
6880     }
6881
6882     if (D.CCCIsCXX()) {
6883       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6884       CmdArgs.push_back("-lm");
6885     }
6886
6887     if (Args.hasArg(options::OPT_pthread))
6888       CmdArgs.push_back("-lpthread");
6889
6890     if (!Args.hasArg(options::OPT_nolibc)) {
6891       CmdArgs.push_back("-lc");
6892     }
6893
6894     if (UseGCC47) {
6895       if (Args.hasArg(options::OPT_static) ||
6896           Args.hasArg(options::OPT_static_libgcc)) {
6897         CmdArgs.push_back("-lgcc");
6898         CmdArgs.push_back("-lgcc_eh");
6899       } else {
6900         if (Args.hasArg(options::OPT_shared_libgcc)) {
6901           CmdArgs.push_back("-lgcc_pic");
6902           if (!Args.hasArg(options::OPT_shared))
6903             CmdArgs.push_back("-lgcc");
6904         } else {
6905           CmdArgs.push_back("-lgcc");
6906           CmdArgs.push_back("--as-needed");
6907           CmdArgs.push_back("-lgcc_pic");
6908           CmdArgs.push_back("--no-as-needed");
6909         }
6910       }
6911     } else {
6912       if (Args.hasArg(options::OPT_shared)) {
6913         CmdArgs.push_back("-lgcc_pic");
6914       } else {
6915         CmdArgs.push_back("-lgcc");
6916       }
6917     }
6918   }
6919
6920   if (!Args.hasArg(options::OPT_nostdlib) &&
6921       !Args.hasArg(options::OPT_nostartfiles)) {
6922     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6923       CmdArgs.push_back(Args.MakeArgString(
6924                               getToolChain().GetFilePath("crtendS.o")));
6925     else
6926       CmdArgs.push_back(Args.MakeArgString(
6927                               getToolChain().GetFilePath("crtend.o")));
6928     CmdArgs.push_back(Args.MakeArgString(
6929                             getToolChain().GetFilePath("crtn.o")));
6930   }
6931
6932   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6933
6934   const char *Exec =
6935     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6936   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6937 }
6938
6939 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
6940                                       const InputInfo &Output,
6941                                       const InputInfoList &Inputs,
6942                                       const ArgList &Args,
6943                                       const char *LinkingOutput) const {
6944   ArgStringList CmdArgs;
6945
6946   if (Output.isFilename()) {
6947     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
6948                                          Output.getFilename()));
6949   } else {
6950     assert(Output.isNothing() && "Invalid output.");
6951   }
6952
6953   if (!Args.hasArg(options::OPT_nostdlib) &&
6954       !Args.hasArg(options::OPT_nostartfiles) &&
6955       !C.getDriver().IsCLMode()) {
6956     CmdArgs.push_back("-defaultlib:libcmt");
6957   }
6958
6959   CmdArgs.push_back("-nologo");
6960
6961   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd);
6962
6963   if (DLL) {
6964     CmdArgs.push_back(Args.MakeArgString("-dll"));
6965
6966     SmallString<128> ImplibName(Output.getFilename());
6967     llvm::sys::path::replace_extension(ImplibName, "lib");
6968     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
6969                                          ImplibName.str()));
6970   }
6971
6972   if (getToolChain().getSanitizerArgs().needsAsanRt()) {
6973     CmdArgs.push_back(Args.MakeArgString("-debug"));
6974     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
6975     SmallString<128> LibSanitizer(getToolChain().getDriver().ResourceDir);
6976     llvm::sys::path::append(LibSanitizer, "lib", "windows");
6977     if (DLL) {
6978       llvm::sys::path::append(LibSanitizer, "clang_rt.asan_dll_thunk-i386.lib");
6979     } else {
6980       llvm::sys::path::append(LibSanitizer, "clang_rt.asan-i386.lib");
6981     }
6982     // FIXME: Handle 64-bit.
6983     CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
6984   }
6985
6986   Args.AddAllArgValues(CmdArgs, options::OPT_l);
6987   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
6988
6989   // Add filenames immediately.
6990   for (InputInfoList::const_iterator
6991        it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6992     if (it->isFilename())
6993       CmdArgs.push_back(it->getFilename());
6994     else
6995       it->getInputArg().renderAsInput(Args, CmdArgs);
6996   }
6997
6998   const char *Exec =
6999     Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
7000   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7001 }
7002
7003 void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
7004                                          const InputInfo &Output,
7005                                          const InputInfoList &Inputs,
7006                                          const ArgList &Args,
7007                                          const char *LinkingOutput) const {
7008   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
7009 }
7010
7011 // Try to find FallbackName on PATH that is not identical to ClangProgramPath.
7012 // If one cannot be found, return FallbackName.
7013 // We do this special search to prevent clang-cl from falling back onto itself
7014 // if it's available as cl.exe on the path.
7015 static std::string FindFallback(const char *FallbackName,
7016                                 const char *ClangProgramPath) {
7017   llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
7018   if (!OptPath.hasValue())
7019     return FallbackName;
7020
7021 #ifdef LLVM_ON_WIN32
7022   const StringRef PathSeparators = ";";
7023 #else
7024   const StringRef PathSeparators = ":";
7025 #endif
7026
7027   SmallVector<StringRef, 8> PathSegments;
7028   llvm::SplitString(OptPath.getValue(), PathSegments, PathSeparators);
7029
7030   for (size_t i = 0, e = PathSegments.size(); i != e; ++i) {
7031     const StringRef &PathSegment = PathSegments[i];
7032     if (PathSegment.empty())
7033       continue;
7034
7035     SmallString<128> FilePath(PathSegment);
7036     llvm::sys::path::append(FilePath, FallbackName);
7037     if (llvm::sys::fs::can_execute(Twine(FilePath)) &&
7038         !llvm::sys::fs::equivalent(Twine(FilePath), ClangProgramPath))
7039       return FilePath.str();
7040   }
7041
7042   return FallbackName;
7043 }
7044
7045 Command *visualstudio::Compile::GetCommand(Compilation &C, const JobAction &JA,
7046                                            const InputInfo &Output,
7047                                            const InputInfoList &Inputs,
7048                                            const ArgList &Args,
7049                                            const char *LinkingOutput) const {
7050   ArgStringList CmdArgs;
7051   CmdArgs.push_back("/nologo");
7052   CmdArgs.push_back("/c"); // Compile only.
7053   CmdArgs.push_back("/W0"); // No warnings.
7054
7055   // The goal is to be able to invoke this tool correctly based on
7056   // any flag accepted by clang-cl.
7057
7058   // These are spelled the same way in clang and cl.exe,.
7059   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
7060   Args.AddAllArgs(CmdArgs, options::OPT_I);
7061
7062   // Optimization level.
7063   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
7064     if (A->getOption().getID() == options::OPT_O0) {
7065       CmdArgs.push_back("/Od");
7066     } else {
7067       StringRef OptLevel = A->getValue();
7068       if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
7069         A->render(Args, CmdArgs);
7070       else if (OptLevel == "3")
7071         CmdArgs.push_back("/Ox");
7072     }
7073   }
7074
7075   // Flags for which clang-cl have an alias.
7076   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
7077
7078   if (Arg *A = Args.getLastArg(options::OPT_frtti, options::OPT_fno_rtti))
7079     CmdArgs.push_back(A->getOption().getID() == options::OPT_frtti ? "/GR"
7080                                                                    : "/GR-");
7081   if (Args.hasArg(options::OPT_fsyntax_only))
7082     CmdArgs.push_back("/Zs");
7083
7084   std::vector<std::string> Includes = Args.getAllArgValues(options::OPT_include);
7085   for (size_t I = 0, E = Includes.size(); I != E; ++I)
7086     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Includes[I]));
7087
7088   // Flags that can simply be passed through.
7089   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
7090   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
7091
7092   // The order of these flags is relevant, so pick the last one.
7093   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
7094                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
7095     A->render(Args, CmdArgs);
7096
7097
7098   // Input filename.
7099   assert(Inputs.size() == 1);
7100   const InputInfo &II = Inputs[0];
7101   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
7102   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
7103   if (II.isFilename())
7104     CmdArgs.push_back(II.getFilename());
7105   else
7106     II.getInputArg().renderAsInput(Args, CmdArgs);
7107
7108   // Output filename.
7109   assert(Output.getType() == types::TY_Object);
7110   const char *Fo = Args.MakeArgString(std::string("/Fo") +
7111                                       Output.getFilename());
7112   CmdArgs.push_back(Fo);
7113
7114   const Driver &D = getToolChain().getDriver();
7115   std::string Exec = FindFallback("cl.exe", D.getClangProgramPath());
7116
7117   return new Command(JA, *this, Args.MakeArgString(Exec), CmdArgs);
7118 }
7119
7120
7121 /// XCore Tools
7122 // We pass assemble and link construction to the xcc tool.
7123
7124 void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7125                                        const InputInfo &Output,
7126                                        const InputInfoList &Inputs,
7127                                        const ArgList &Args,
7128                                        const char *LinkingOutput) const {
7129   ArgStringList CmdArgs;
7130
7131   CmdArgs.push_back("-o");
7132   CmdArgs.push_back(Output.getFilename());
7133
7134   CmdArgs.push_back("-c");
7135
7136   if (Args.hasArg(options::OPT_g_Group)) {
7137     CmdArgs.push_back("-g");
7138   }
7139
7140   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7141                        options::OPT_Xassembler);
7142
7143   for (InputInfoList::const_iterator
7144        it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
7145     const InputInfo &II = *it;
7146     CmdArgs.push_back(II.getFilename());
7147   }
7148
7149   const char *Exec =
7150     Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
7151   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7152 }
7153
7154 void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
7155                                    const InputInfo &Output,
7156                                    const InputInfoList &Inputs,
7157                                    const ArgList &Args,
7158                                    const char *LinkingOutput) const {
7159   ArgStringList CmdArgs;
7160
7161   if (Output.isFilename()) {
7162     CmdArgs.push_back("-o");
7163     CmdArgs.push_back(Output.getFilename());
7164   } else {
7165     assert(Output.isNothing() && "Invalid output.");
7166   }
7167
7168   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7169
7170   const char *Exec =
7171     Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
7172   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7173 }