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   // Handle -march=native.
503   std::string NativeMArch;
504   if (MArch == "native") {
505     std::string CPU = llvm::sys::getHostCPUName();
506     if (CPU != "generic") {
507       // Translate the native cpu into the architecture. The switch below will
508       // then chose the minimum cpu for that arch.
509       NativeMArch = std::string("arm") + getLLVMArchSuffixForARM(CPU);
510       MArch = NativeMArch;
511     }
512   }
513 
514   return llvm::StringSwitch<const char *>(MArch)
515     .Cases("armv2", "armv2a","arm2")
516     .Case("armv3", "arm6")
517     .Case("armv3m", "arm7m")
518     .Case("armv4", "strongarm")
519     .Case("armv4t", "arm7tdmi")
520     .Cases("armv5", "armv5t", "arm10tdmi")
521     .Cases("armv5e", "armv5te", "arm1022e")
522     .Case("armv5tej", "arm926ej-s")
523     .Cases("armv6", "armv6k", "arm1136jf-s")
524     .Case("armv6j", "arm1136j-s")
525     .Cases("armv6z", "armv6zk", "arm1176jzf-s")
526     .Case("armv6t2", "arm1156t2-s")
527     .Cases("armv6m", "armv6-m", "cortex-m0")
528     .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
529     .Cases("armv7em", "armv7e-m", "cortex-m4")
530     .Cases("armv7f", "armv7-f", "cortex-a9-mp")
531     .Cases("armv7s", "armv7-s", "swift")
532     .Cases("armv7r", "armv7-r", "cortex-r4")
533     .Cases("armv7m", "armv7-m", "cortex-m3")
534     .Cases("armv8", "armv8a", "armv8-a", "cortex-a53")
535     .Case("ep9312", "ep9312")
536     .Case("iwmmxt", "iwmmxt")
537     .Case("xscale", "xscale")
538     // If all else failed, return the most base CPU with thumb interworking
539     // supported by LLVM.
540     .Default("arm7tdmi");
541 }
542 
543 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are targeting.
544 //
545 // FIXME: tblgen this.
546 static std::string getAArch64TargetCPU(const ArgList &Args,
547                                        const llvm::Triple &Triple) {
548   // FIXME: Warn on inconsistent use of -mcpu and -march.
549 
550   // If we have -mcpu=, use that.
551   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
552     StringRef MCPU = A->getValue();
553     // Handle -mcpu=native.
554     if (MCPU == "native")
555       return llvm::sys::getHostCPUName();
556     else
557       return MCPU;
558   }
559 
560   return "generic";
561 }
562 
563 // FIXME: Move to target hook.
564 static bool isSignedCharDefault(const llvm::Triple &Triple) {
565   switch (Triple.getArch()) {
566   default:
567     return true;
568 
569   case llvm::Triple::aarch64:
570   case llvm::Triple::arm:
571   case llvm::Triple::ppc:
572   case llvm::Triple::ppc64:
573     if (Triple.isOSDarwin())
574       return true;
575     return false;
576 
577   case llvm::Triple::ppc64le:
578   case llvm::Triple::systemz:
579   case llvm::Triple::xcore:
580     return false;
581   }
582 }
583 
584 static bool isNoCommonDefault(const llvm::Triple &Triple) {
585   switch (Triple.getArch()) {
586   default:
587     return false;
588 
589   case llvm::Triple::xcore:
590     return true;
591   }
592 }
593 
594 // Handle -mfpu=.
595 //
596 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
597 // frontend target.
598 static void getAArch64FPUFeatures(const Driver &D, const Arg *A,
599                                   const ArgList &Args,
600                                   std::vector<const char *> &Features) {
601   StringRef FPU = A->getValue();
602   if (FPU == "fp-armv8") {
603     Features.push_back("+fp-armv8");
604   } else if (FPU == "neon-fp-armv8") {
605     Features.push_back("+fp-armv8");
606     Features.push_back("+neon");
607   } else if (FPU == "crypto-neon-fp-armv8") {
608     Features.push_back("+fp-armv8");
609     Features.push_back("+neon");
610     Features.push_back("+crypto");
611   } else if (FPU == "neon") {
612     Features.push_back("+neon");
613   } else if (FPU == "none") {
614     Features.push_back("-fp-armv8");
615     Features.push_back("-crypto");
616     Features.push_back("-neon");
617   } else
618     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
619 }
620 
621 // Handle -mhwdiv=.
622 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
623                               const ArgList &Args,
624                               std::vector<const char *> &Features) {
625   StringRef HWDiv = A->getValue();
626   if (HWDiv == "arm") {
627     Features.push_back("+hwdiv-arm");
628     Features.push_back("-hwdiv");
629   } else if (HWDiv == "thumb") {
630     Features.push_back("-hwdiv-arm");
631     Features.push_back("+hwdiv");
632   } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
633     Features.push_back("+hwdiv-arm");
634     Features.push_back("+hwdiv");
635   } else if (HWDiv == "none") {
636     Features.push_back("-hwdiv-arm");
637     Features.push_back("-hwdiv");
638   } else
639     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
640 }
641 
642 // Handle -mfpu=.
643 //
644 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
645 // frontend target.
646 static void getARMFPUFeatures(const Driver &D, const Arg *A,
647                               const ArgList &Args,
648                               std::vector<const char *> &Features) {
649   StringRef FPU = A->getValue();
650 
651   // Set the target features based on the FPU.
652   if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
653     // Disable any default FPU support.
654     Features.push_back("-vfp2");
655     Features.push_back("-vfp3");
656     Features.push_back("-neon");
657   } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
658     Features.push_back("+vfp3");
659     Features.push_back("+d16");
660     Features.push_back("-neon");
661   } else if (FPU == "vfp") {
662     Features.push_back("+vfp2");
663     Features.push_back("-neon");
664   } else if (FPU == "vfp3" || FPU == "vfpv3") {
665     Features.push_back("+vfp3");
666     Features.push_back("-neon");
667   } else if (FPU == "fp-armv8") {
668     Features.push_back("+fp-armv8");
669     Features.push_back("-neon");
670     Features.push_back("-crypto");
671   } else if (FPU == "neon-fp-armv8") {
672     Features.push_back("+fp-armv8");
673     Features.push_back("+neon");
674     Features.push_back("-crypto");
675   } else if (FPU == "crypto-neon-fp-armv8") {
676     Features.push_back("+fp-armv8");
677     Features.push_back("+neon");
678     Features.push_back("+crypto");
679   } else if (FPU == "neon") {
680     Features.push_back("+neon");
681   } else if (FPU == "none") {
682     Features.push_back("-vfp2");
683     Features.push_back("-vfp3");
684     Features.push_back("-vfp4");
685     Features.push_back("-fp-armv8");
686     Features.push_back("-crypto");
687     Features.push_back("-neon");
688   } else
689     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
690 }
691 
692 // Select the float ABI as determined by -msoft-float, -mhard-float, and
693 // -mfloat-abi=.
694 static StringRef getARMFloatABI(const Driver &D,
695                                 const ArgList &Args,
696                                 const llvm::Triple &Triple) {
697   StringRef FloatABI;
698   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
699                                options::OPT_mhard_float,
700                                options::OPT_mfloat_abi_EQ)) {
701     if (A->getOption().matches(options::OPT_msoft_float))
702       FloatABI = "soft";
703     else if (A->getOption().matches(options::OPT_mhard_float))
704       FloatABI = "hard";
705     else {
706       FloatABI = A->getValue();
707       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
708         D.Diag(diag::err_drv_invalid_mfloat_abi)
709           << A->getAsString(Args);
710         FloatABI = "soft";
711       }
712     }
713   }
714 
715   // If unspecified, choose the default based on the platform.
716   if (FloatABI.empty()) {
717     switch (Triple.getOS()) {
718     case llvm::Triple::Darwin:
719     case llvm::Triple::MacOSX:
720     case llvm::Triple::IOS: {
721       // Darwin defaults to "softfp" for v6 and v7.
722       //
723       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
724       std::string ArchName =
725         getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
726       if (StringRef(ArchName).startswith("v6") ||
727           StringRef(ArchName).startswith("v7"))
728         FloatABI = "softfp";
729       else
730         FloatABI = "soft";
731       break;
732     }
733 
734     case llvm::Triple::FreeBSD:
735       // FreeBSD defaults to soft float
736       FloatABI = "soft";
737       break;
738 
739     default:
740       switch(Triple.getEnvironment()) {
741       case llvm::Triple::GNUEABIHF:
742         FloatABI = "hard";
743         break;
744       case llvm::Triple::GNUEABI:
745         FloatABI = "softfp";
746         break;
747       case llvm::Triple::EABI:
748         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
749         FloatABI = "softfp";
750         break;
751       case llvm::Triple::Android: {
752         std::string ArchName =
753           getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
754         if (StringRef(ArchName).startswith("v7"))
755           FloatABI = "softfp";
756         else
757           FloatABI = "soft";
758         break;
759       }
760       default:
761         // Assume "soft", but warn the user we are guessing.
762         FloatABI = "soft";
763         D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
764         break;
765       }
766     }
767   }
768 
769   return FloatABI;
770 }
771 
772 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
773                                  const ArgList &Args,
774                                  std::vector<const char *> &Features) {
775   StringRef FloatABI = getARMFloatABI(D, Args, Triple);
776   // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
777   // yet (it uses the -mfloat-abi and -msoft-float options), and it is
778   // stripped out by the ARM target.
779   // Use software floating point operations?
780   if (FloatABI == "soft")
781     Features.push_back("+soft-float");
782 
783   // Use software floating point argument passing?
784   if (FloatABI != "hard")
785     Features.push_back("+soft-float-abi");
786 
787   // Honor -mfpu=.
788   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
789     getARMFPUFeatures(D, A, Args, Features);
790   if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
791     getARMHWDivFeatures(D, A, Args, Features);
792 
793   // Setting -msoft-float effectively disables NEON because of the GCC
794   // implementation, although the same isn't true of VFP or VFP3.
795   if (FloatABI == "soft")
796     Features.push_back("-neon");
797 
798   // En/disable crc
799   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
800                                options::OPT_mnocrc)) {
801     if (A->getOption().matches(options::OPT_mcrc))
802       Features.push_back("+crc");
803     else
804       Features.push_back("-crc");
805   }
806 }
807 
808 void Clang::AddARMTargetArgs(const ArgList &Args,
809                              ArgStringList &CmdArgs,
810                              bool KernelOrKext) const {
811   const Driver &D = getToolChain().getDriver();
812   // Get the effective triple, which takes into account the deployment target.
813   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
814   llvm::Triple Triple(TripleStr);
815   std::string CPUName = getARMTargetCPU(Args, Triple);
816 
817   // Select the ABI to use.
818   //
819   // FIXME: Support -meabi.
820   const char *ABIName = 0;
821   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
822     ABIName = A->getValue();
823   } else if (Triple.isOSDarwin()) {
824     // The backend is hardwired to assume AAPCS for M-class processors, ensure
825     // the frontend matches that.
826     if (Triple.getEnvironment() == llvm::Triple::EABI ||
827         StringRef(CPUName).startswith("cortex-m")) {
828       ABIName = "aapcs";
829     } else {
830       ABIName = "apcs-gnu";
831     }
832   } else {
833     // Select the default based on the platform.
834     switch(Triple.getEnvironment()) {
835     case llvm::Triple::Android:
836     case llvm::Triple::GNUEABI:
837     case llvm::Triple::GNUEABIHF:
838       ABIName = "aapcs-linux";
839       break;
840     case llvm::Triple::EABI:
841       ABIName = "aapcs";
842       break;
843     default:
844       ABIName = "apcs-gnu";
845     }
846   }
847   CmdArgs.push_back("-target-abi");
848   CmdArgs.push_back(ABIName);
849 
850   // Determine floating point ABI from the options & target defaults.
851   StringRef FloatABI = getARMFloatABI(D, Args, Triple);
852   if (FloatABI == "soft") {
853     // Floating point operations and argument passing are soft.
854     //
855     // FIXME: This changes CPP defines, we need -target-soft-float.
856     CmdArgs.push_back("-msoft-float");
857     CmdArgs.push_back("-mfloat-abi");
858     CmdArgs.push_back("soft");
859   } else if (FloatABI == "softfp") {
860     // Floating point operations are hard, but argument passing is soft.
861     CmdArgs.push_back("-mfloat-abi");
862     CmdArgs.push_back("soft");
863   } else {
864     // Floating point operations and argument passing are hard.
865     assert(FloatABI == "hard" && "Invalid float abi!");
866     CmdArgs.push_back("-mfloat-abi");
867     CmdArgs.push_back("hard");
868   }
869 
870   // Kernel code has more strict alignment requirements.
871   if (KernelOrKext) {
872     if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
873       CmdArgs.push_back("-backend-option");
874       CmdArgs.push_back("-arm-long-calls");
875     }
876 
877     CmdArgs.push_back("-backend-option");
878     CmdArgs.push_back("-arm-strict-align");
879 
880     // The kext linker doesn't know how to deal with movw/movt.
881     CmdArgs.push_back("-backend-option");
882     CmdArgs.push_back("-arm-use-movt=0");
883   }
884 
885   // Setting -mno-global-merge disables the codegen global merge pass. Setting
886   // -mglobal-merge has no effect as the pass is enabled by default.
887   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
888                                options::OPT_mno_global_merge)) {
889     if (A->getOption().matches(options::OPT_mno_global_merge))
890       CmdArgs.push_back("-mno-global-merge");
891   }
892 
893   if (!Args.hasFlag(options::OPT_mimplicit_float,
894                     options::OPT_mno_implicit_float,
895                     true))
896     CmdArgs.push_back("-no-implicit-float");
897 
898     // llvm does not support reserving registers in general. There is support
899     // for reserving r9 on ARM though (defined as a platform-specific register
900     // in ARM EABI).
901     if (Args.hasArg(options::OPT_ffixed_r9)) {
902       CmdArgs.push_back("-backend-option");
903       CmdArgs.push_back("-arm-reserve-r9");
904     }
905 }
906 
907 // Get CPU and ABI names. They are not independent
908 // so we have to calculate them together.
909 static void getMipsCPUAndABI(const ArgList &Args,
910                              const llvm::Triple &Triple,
911                              StringRef &CPUName,
912                              StringRef &ABIName) {
913   const char *DefMips32CPU = "mips32";
914   const char *DefMips64CPU = "mips64";
915 
916   if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
917                                options::OPT_mcpu_EQ))
918     CPUName = A->getValue();
919 
920   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
921     ABIName = A->getValue();
922     // Convert a GNU style Mips ABI name to the name
923     // accepted by LLVM Mips backend.
924     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
925       .Case("32", "o32")
926       .Case("64", "n64")
927       .Default(ABIName);
928   }
929 
930   // Setup default CPU and ABI names.
931   if (CPUName.empty() && ABIName.empty()) {
932     switch (Triple.getArch()) {
933     default:
934       llvm_unreachable("Unexpected triple arch name");
935     case llvm::Triple::mips:
936     case llvm::Triple::mipsel:
937       CPUName = DefMips32CPU;
938       break;
939     case llvm::Triple::mips64:
940     case llvm::Triple::mips64el:
941       CPUName = DefMips64CPU;
942       break;
943     }
944   }
945 
946   if (!ABIName.empty()) {
947     // Deduce CPU name from ABI name.
948     CPUName = llvm::StringSwitch<const char *>(ABIName)
949       .Cases("32", "o32", "eabi", DefMips32CPU)
950       .Cases("n32", "n64", "64", DefMips64CPU)
951       .Default("");
952   }
953   else if (!CPUName.empty()) {
954     // Deduce ABI name from CPU name.
955     ABIName = llvm::StringSwitch<const char *>(CPUName)
956       .Cases("mips32", "mips32r2", "o32")
957       .Cases("mips64", "mips64r2", "n64")
958       .Default("");
959   }
960 
961   // FIXME: Warn on inconsistent cpu and abi usage.
962 }
963 
964 // Convert ABI name to the GNU tools acceptable variant.
965 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
966   return llvm::StringSwitch<llvm::StringRef>(ABI)
967     .Case("o32", "32")
968     .Case("n64", "64")
969     .Default(ABI);
970 }
971 
972 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
973 // and -mfloat-abi=.
974 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
975   StringRef FloatABI;
976   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
977                                options::OPT_mhard_float,
978                                options::OPT_mfloat_abi_EQ)) {
979     if (A->getOption().matches(options::OPT_msoft_float))
980       FloatABI = "soft";
981     else if (A->getOption().matches(options::OPT_mhard_float))
982       FloatABI = "hard";
983     else {
984       FloatABI = A->getValue();
985       if (FloatABI != "soft" && FloatABI != "hard") {
986         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
987         FloatABI = "hard";
988       }
989     }
990   }
991 
992   // If unspecified, choose the default based on the platform.
993   if (FloatABI.empty()) {
994     // Assume "hard", because it's a default value used by gcc.
995     // When we start to recognize specific target MIPS processors,
996     // we will be able to select the default more correctly.
997     FloatABI = "hard";
998   }
999 
1000   return FloatABI;
1001 }
1002 
1003 static void AddTargetFeature(const ArgList &Args,
1004                              std::vector<const char *> &Features,
1005                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1006                              StringRef FeatureName) {
1007   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1008     if (A->getOption().matches(OnOpt))
1009       Features.push_back(Args.MakeArgString("+" + FeatureName));
1010     else
1011       Features.push_back(Args.MakeArgString("-" + FeatureName));
1012   }
1013 }
1014 
1015 static void getMIPSTargetFeatures(const Driver &D, const ArgList &Args,
1016                                   std::vector<const char *> &Features) {
1017   StringRef FloatABI = getMipsFloatABI(D, Args);
1018   bool IsMips16 = Args.getLastArg(options::OPT_mips16) != NULL;
1019   if (FloatABI == "soft" || (FloatABI == "hard" && IsMips16)) {
1020     // FIXME: Note, this is a hack. We need to pass the selected float
1021     // mode to the MipsTargetInfoBase to define appropriate macros there.
1022     // Now it is the only method.
1023     Features.push_back("+soft-float");
1024   }
1025 
1026   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1027     if (StringRef(A->getValue()) == "2008")
1028       Features.push_back("+nan2008");
1029   }
1030 
1031   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1032                    options::OPT_mdouble_float, "single-float");
1033   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1034                    "mips16");
1035   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1036                    options::OPT_mno_micromips, "micromips");
1037   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1038                    "dsp");
1039   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1040                    "dspr2");
1041   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1042                    "msa");
1043   AddTargetFeature(Args, Features, options::OPT_mfp64, options::OPT_mfp32,
1044                    "fp64");
1045 }
1046 
1047 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1048                               ArgStringList &CmdArgs) const {
1049   const Driver &D = getToolChain().getDriver();
1050   StringRef CPUName;
1051   StringRef ABIName;
1052   const llvm::Triple &Triple = getToolChain().getTriple();
1053   getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1054 
1055   CmdArgs.push_back("-target-abi");
1056   CmdArgs.push_back(ABIName.data());
1057 
1058   StringRef FloatABI = getMipsFloatABI(D, Args);
1059 
1060   bool IsMips16 = Args.getLastArg(options::OPT_mips16) != NULL;
1061 
1062   if (FloatABI == "soft" || (FloatABI == "hard" && IsMips16)) {
1063     // Floating point operations and argument passing are soft.
1064     CmdArgs.push_back("-msoft-float");
1065     CmdArgs.push_back("-mfloat-abi");
1066     CmdArgs.push_back("soft");
1067 
1068     if (FloatABI == "hard" && IsMips16) {
1069       CmdArgs.push_back("-mllvm");
1070       CmdArgs.push_back("-mips16-hard-float");
1071     }
1072   }
1073   else {
1074     // Floating point operations and argument passing are hard.
1075     assert(FloatABI == "hard" && "Invalid float abi!");
1076     CmdArgs.push_back("-mfloat-abi");
1077     CmdArgs.push_back("hard");
1078   }
1079 
1080   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1081     if (A->getOption().matches(options::OPT_mxgot)) {
1082       CmdArgs.push_back("-mllvm");
1083       CmdArgs.push_back("-mxgot");
1084     }
1085   }
1086 
1087   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1088                                options::OPT_mno_ldc1_sdc1)) {
1089     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1090       CmdArgs.push_back("-mllvm");
1091       CmdArgs.push_back("-mno-ldc1-sdc1");
1092     }
1093   }
1094 
1095   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1096                                options::OPT_mno_check_zero_division)) {
1097     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1098       CmdArgs.push_back("-mllvm");
1099       CmdArgs.push_back("-mno-check-zero-division");
1100     }
1101   }
1102 
1103   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1104     StringRef v = A->getValue();
1105     CmdArgs.push_back("-mllvm");
1106     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1107     A->claim();
1108   }
1109 }
1110 
1111 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1112 static std::string getPPCTargetCPU(const ArgList &Args) {
1113   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1114     StringRef CPUName = A->getValue();
1115 
1116     if (CPUName == "native") {
1117       std::string CPU = llvm::sys::getHostCPUName();
1118       if (!CPU.empty() && CPU != "generic")
1119         return CPU;
1120       else
1121         return "";
1122     }
1123 
1124     return llvm::StringSwitch<const char *>(CPUName)
1125       .Case("common", "generic")
1126       .Case("440", "440")
1127       .Case("440fp", "440")
1128       .Case("450", "450")
1129       .Case("601", "601")
1130       .Case("602", "602")
1131       .Case("603", "603")
1132       .Case("603e", "603e")
1133       .Case("603ev", "603ev")
1134       .Case("604", "604")
1135       .Case("604e", "604e")
1136       .Case("620", "620")
1137       .Case("630", "pwr3")
1138       .Case("G3", "g3")
1139       .Case("7400", "7400")
1140       .Case("G4", "g4")
1141       .Case("7450", "7450")
1142       .Case("G4+", "g4+")
1143       .Case("750", "750")
1144       .Case("970", "970")
1145       .Case("G5", "g5")
1146       .Case("a2", "a2")
1147       .Case("a2q", "a2q")
1148       .Case("e500mc", "e500mc")
1149       .Case("e5500", "e5500")
1150       .Case("power3", "pwr3")
1151       .Case("power4", "pwr4")
1152       .Case("power5", "pwr5")
1153       .Case("power5x", "pwr5x")
1154       .Case("power6", "pwr6")
1155       .Case("power6x", "pwr6x")
1156       .Case("power7", "pwr7")
1157       .Case("pwr3", "pwr3")
1158       .Case("pwr4", "pwr4")
1159       .Case("pwr5", "pwr5")
1160       .Case("pwr5x", "pwr5x")
1161       .Case("pwr6", "pwr6")
1162       .Case("pwr6x", "pwr6x")
1163       .Case("pwr7", "pwr7")
1164       .Case("powerpc", "ppc")
1165       .Case("powerpc64", "ppc64")
1166       .Case("powerpc64le", "ppc64le")
1167       .Default("");
1168   }
1169 
1170   return "";
1171 }
1172 
1173 static void getPPCTargetFeatures(const ArgList &Args,
1174                                  std::vector<const char *> &Features) {
1175   for (arg_iterator it = Args.filtered_begin(options::OPT_m_ppc_Features_Group),
1176                     ie = Args.filtered_end();
1177        it != ie; ++it) {
1178     StringRef Name = (*it)->getOption().getName();
1179     (*it)->claim();
1180 
1181     // Skip over "-m".
1182     assert(Name.startswith("m") && "Invalid feature name.");
1183     Name = Name.substr(1);
1184 
1185     bool IsNegative = Name.startswith("no-");
1186     if (IsNegative)
1187       Name = Name.substr(3);
1188 
1189     // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1190     // pass the correct option to the backend while calling the frontend
1191     // option the same.
1192     // TODO: Change the LLVM backend option maybe?
1193     if (Name == "mfcrf")
1194       Name = "mfocrf";
1195 
1196     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1197   }
1198 
1199   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1200   AddTargetFeature(Args, Features, options::OPT_faltivec,
1201                    options::OPT_fno_altivec, "altivec");
1202 }
1203 
1204 /// Get the (LLVM) name of the R600 gpu we are targeting.
1205 static std::string getR600TargetGPU(const ArgList &Args) {
1206   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1207     const char *GPUName = A->getValue();
1208     return llvm::StringSwitch<const char *>(GPUName)
1209       .Cases("rv630", "rv635", "r600")
1210       .Cases("rv610", "rv620", "rs780", "rs880")
1211       .Case("rv740", "rv770")
1212       .Case("palm", "cedar")
1213       .Cases("sumo", "sumo2", "sumo")
1214       .Case("hemlock", "cypress")
1215       .Case("aruba", "cayman")
1216       .Default(GPUName);
1217   }
1218   return "";
1219 }
1220 
1221 static void getSparcTargetFeatures(const ArgList &Args,
1222                                    std::vector<const char *> Features) {
1223   bool SoftFloatABI = true;
1224   if (Arg *A =
1225           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1226     if (A->getOption().matches(options::OPT_mhard_float))
1227       SoftFloatABI = false;
1228   }
1229   if (SoftFloatABI)
1230     Features.push_back("+soft-float");
1231 }
1232 
1233 void Clang::AddSparcTargetArgs(const ArgList &Args,
1234                              ArgStringList &CmdArgs) const {
1235   const Driver &D = getToolChain().getDriver();
1236 
1237   // Select the float ABI as determined by -msoft-float, -mhard-float, and
1238   StringRef FloatABI;
1239   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1240                                options::OPT_mhard_float)) {
1241     if (A->getOption().matches(options::OPT_msoft_float))
1242       FloatABI = "soft";
1243     else if (A->getOption().matches(options::OPT_mhard_float))
1244       FloatABI = "hard";
1245   }
1246 
1247   // If unspecified, choose the default based on the platform.
1248   if (FloatABI.empty()) {
1249     // Assume "soft", but warn the user we are guessing.
1250     FloatABI = "soft";
1251     D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
1252   }
1253 
1254   if (FloatABI == "soft") {
1255     // Floating point operations and argument passing are soft.
1256     //
1257     // FIXME: This changes CPP defines, we need -target-soft-float.
1258     CmdArgs.push_back("-msoft-float");
1259   } else {
1260     assert(FloatABI == "hard" && "Invalid float abi!");
1261     CmdArgs.push_back("-mhard-float");
1262   }
1263 }
1264 
1265 static const char *getSystemZTargetCPU(const ArgList &Args) {
1266   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1267     return A->getValue();
1268   return "z10";
1269 }
1270 
1271 static const char *getX86TargetCPU(const ArgList &Args,
1272                                    const llvm::Triple &Triple) {
1273   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1274     if (StringRef(A->getValue()) != "native") {
1275       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1276         return "core-avx2";
1277 
1278       return A->getValue();
1279     }
1280 
1281     // FIXME: Reject attempts to use -march=native unless the target matches
1282     // the host.
1283     //
1284     // FIXME: We should also incorporate the detected target features for use
1285     // with -native.
1286     std::string CPU = llvm::sys::getHostCPUName();
1287     if (!CPU.empty() && CPU != "generic")
1288       return Args.MakeArgString(CPU);
1289   }
1290 
1291   // Select the default CPU if none was given (or detection failed).
1292 
1293   if (Triple.getArch() != llvm::Triple::x86_64 &&
1294       Triple.getArch() != llvm::Triple::x86)
1295     return 0; // This routine is only handling x86 targets.
1296 
1297   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1298 
1299   // FIXME: Need target hooks.
1300   if (Triple.isOSDarwin()) {
1301     if (Triple.getArchName() == "x86_64h")
1302       return "core-avx2";
1303     return Is64Bit ? "core2" : "yonah";
1304   }
1305 
1306   // All x86 devices running Android have core2 as their common
1307   // denominator. This makes a better choice than pentium4.
1308   if (Triple.getEnvironment() == llvm::Triple::Android)
1309     return "core2";
1310 
1311   // Everything else goes to x86-64 in 64-bit mode.
1312   if (Is64Bit)
1313     return "x86-64";
1314 
1315   switch (Triple.getOS()) {
1316   case llvm::Triple::FreeBSD:
1317   case llvm::Triple::NetBSD:
1318   case llvm::Triple::OpenBSD:
1319     return "i486";
1320   case llvm::Triple::Haiku:
1321   case llvm::Triple::Minix:
1322     return "i586";
1323   case llvm::Triple::Bitrig:
1324     return "i686";
1325   default:
1326     // Fallback to p4.
1327     return "pentium4";
1328   }
1329 }
1330 
1331 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1332   switch(T.getArch()) {
1333   default:
1334     return "";
1335 
1336   case llvm::Triple::aarch64:
1337     return getAArch64TargetCPU(Args, T);
1338 
1339   case llvm::Triple::arm:
1340   case llvm::Triple::thumb:
1341     return getARMTargetCPU(Args, T);
1342 
1343   case llvm::Triple::mips:
1344   case llvm::Triple::mipsel:
1345   case llvm::Triple::mips64:
1346   case llvm::Triple::mips64el: {
1347     StringRef CPUName;
1348     StringRef ABIName;
1349     getMipsCPUAndABI(Args, T, CPUName, ABIName);
1350     return CPUName;
1351   }
1352 
1353   case llvm::Triple::ppc:
1354   case llvm::Triple::ppc64:
1355   case llvm::Triple::ppc64le: {
1356     std::string TargetCPUName = getPPCTargetCPU(Args);
1357     // LLVM may default to generating code for the native CPU,
1358     // but, like gcc, we default to a more generic option for
1359     // each architecture. (except on Darwin)
1360     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1361       if (T.getArch() == llvm::Triple::ppc64)
1362         TargetCPUName = "ppc64";
1363       else if (T.getArch() == llvm::Triple::ppc64le)
1364         TargetCPUName = "ppc64le";
1365       else
1366         TargetCPUName = "ppc";
1367     }
1368     return TargetCPUName;
1369   }
1370 
1371   case llvm::Triple::sparc:
1372     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1373       return A->getValue();
1374     return "";
1375 
1376   case llvm::Triple::x86:
1377   case llvm::Triple::x86_64:
1378     return getX86TargetCPU(Args, T);
1379 
1380   case llvm::Triple::hexagon:
1381     return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1382 
1383   case llvm::Triple::systemz:
1384     return getSystemZTargetCPU(Args);
1385 
1386   case llvm::Triple::r600:
1387     return getR600TargetGPU(Args);
1388   }
1389 }
1390 
1391 static void getX86TargetFeatures(const llvm::Triple &Triple,
1392                                  const ArgList &Args,
1393                                  std::vector<const char *> &Features) {
1394   if (Triple.getArchName() == "x86_64h") {
1395     // x86_64h implies quite a few of the more modern subtarget features
1396     // for Haswell class CPUs, but not all of them. Opt-out of a few.
1397     Features.push_back("-rdrnd");
1398     Features.push_back("-aes");
1399     Features.push_back("-pclmul");
1400     Features.push_back("-rtm");
1401     Features.push_back("-hle");
1402     Features.push_back("-fsgsbase");
1403   }
1404 
1405   // Now add any that the user explicitly requested on the command line,
1406   // which may override the defaults.
1407   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
1408                     ie = Args.filtered_end();
1409        it != ie; ++it) {
1410     StringRef Name = (*it)->getOption().getName();
1411     (*it)->claim();
1412 
1413     // Skip over "-m".
1414     assert(Name.startswith("m") && "Invalid feature name.");
1415     Name = Name.substr(1);
1416 
1417     bool IsNegative = Name.startswith("no-");
1418     if (IsNegative)
1419       Name = Name.substr(3);
1420 
1421     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1422   }
1423 }
1424 
1425 void Clang::AddX86TargetArgs(const ArgList &Args,
1426                              ArgStringList &CmdArgs) const {
1427   if (!Args.hasFlag(options::OPT_mred_zone,
1428                     options::OPT_mno_red_zone,
1429                     true) ||
1430       Args.hasArg(options::OPT_mkernel) ||
1431       Args.hasArg(options::OPT_fapple_kext))
1432     CmdArgs.push_back("-disable-red-zone");
1433 
1434   // Default to avoid implicit floating-point for kernel/kext code, but allow
1435   // that to be overridden with -mno-soft-float.
1436   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1437                           Args.hasArg(options::OPT_fapple_kext));
1438   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1439                                options::OPT_mno_soft_float,
1440                                options::OPT_mimplicit_float,
1441                                options::OPT_mno_implicit_float)) {
1442     const Option &O = A->getOption();
1443     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1444                        O.matches(options::OPT_msoft_float));
1445   }
1446   if (NoImplicitFloat)
1447     CmdArgs.push_back("-no-implicit-float");
1448 }
1449 
1450 static inline bool HasPICArg(const ArgList &Args) {
1451   return Args.hasArg(options::OPT_fPIC)
1452     || Args.hasArg(options::OPT_fpic);
1453 }
1454 
1455 static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) {
1456   return Args.getLastArg(options::OPT_G,
1457                          options::OPT_G_EQ,
1458                          options::OPT_msmall_data_threshold_EQ);
1459 }
1460 
1461 static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) {
1462   std::string value;
1463   if (HasPICArg(Args))
1464     value = "0";
1465   else if (Arg *A = GetLastSmallDataThresholdArg(Args)) {
1466     value = A->getValue();
1467     A->claim();
1468   }
1469   return value;
1470 }
1471 
1472 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1473                                  ArgStringList &CmdArgs) const {
1474   CmdArgs.push_back("-fno-signed-char");
1475   CmdArgs.push_back("-mqdsp6-compat");
1476   CmdArgs.push_back("-Wreturn-type");
1477 
1478   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
1479   if (!SmallDataThreshold.empty()) {
1480     CmdArgs.push_back ("-mllvm");
1481     CmdArgs.push_back(Args.MakeArgString(
1482                         "-hexagon-small-data-threshold=" + SmallDataThreshold));
1483   }
1484 
1485   if (!Args.hasArg(options::OPT_fno_short_enums))
1486     CmdArgs.push_back("-fshort-enums");
1487   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1488     CmdArgs.push_back ("-mllvm");
1489     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
1490   }
1491   CmdArgs.push_back ("-mllvm");
1492   CmdArgs.push_back ("-machine-sink-split=0");
1493 }
1494 
1495 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1496                                      std::vector<const char *> &Features) {
1497   // Honor -mfpu=.
1498   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
1499     getAArch64FPUFeatures(D, A, Args, Features);
1500 }
1501 
1502 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1503                               const ArgList &Args, ArgStringList &CmdArgs) {
1504   std::vector<const char *> Features;
1505   switch (Triple.getArch()) {
1506   default:
1507     break;
1508   case llvm::Triple::mips:
1509   case llvm::Triple::mipsel:
1510   case llvm::Triple::mips64:
1511   case llvm::Triple::mips64el:
1512     getMIPSTargetFeatures(D, Args, Features);
1513     break;
1514 
1515   case llvm::Triple::arm:
1516   case llvm::Triple::thumb:
1517     getARMTargetFeatures(D, Triple, Args, Features);
1518     break;
1519 
1520   case llvm::Triple::ppc:
1521   case llvm::Triple::ppc64:
1522   case llvm::Triple::ppc64le:
1523     getPPCTargetFeatures(Args, Features);
1524     break;
1525   case llvm::Triple::sparc:
1526     getSparcTargetFeatures(Args, Features);
1527     break;
1528   case llvm::Triple::aarch64:
1529     getAArch64TargetFeatures(D, Args, Features);
1530     break;
1531   case llvm::Triple::x86:
1532   case llvm::Triple::x86_64:
1533     getX86TargetFeatures(Triple, Args, Features);
1534     break;
1535   }
1536 
1537   // Find the last of each feature.
1538   llvm::StringMap<unsigned> LastOpt;
1539   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1540     const char *Name = Features[I];
1541     assert(Name[0] == '-' || Name[0] == '+');
1542     LastOpt[Name + 1] = I;
1543   }
1544 
1545   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1546     // If this feature was overridden, ignore it.
1547     const char *Name = Features[I];
1548     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
1549     assert(LastI != LastOpt.end());
1550     unsigned Last = LastI->second;
1551     if (Last != I)
1552       continue;
1553 
1554     CmdArgs.push_back("-target-feature");
1555     CmdArgs.push_back(Name);
1556   }
1557 }
1558 
1559 static bool
1560 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
1561                                           const llvm::Triple &Triple) {
1562   // We use the zero-cost exception tables for Objective-C if the non-fragile
1563   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
1564   // later.
1565   if (runtime.isNonFragile())
1566     return true;
1567 
1568   if (!Triple.isOSDarwin())
1569     return false;
1570 
1571   return (!Triple.isMacOSXVersionLT(10,5) &&
1572           (Triple.getArch() == llvm::Triple::x86_64 ||
1573            Triple.getArch() == llvm::Triple::arm));
1574 }
1575 
1576 /// addExceptionArgs - Adds exception related arguments to the driver command
1577 /// arguments. There's a master flag, -fexceptions and also language specific
1578 /// flags to enable/disable C++ and Objective-C exceptions.
1579 /// This makes it possible to for example disable C++ exceptions but enable
1580 /// Objective-C exceptions.
1581 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
1582                              const llvm::Triple &Triple,
1583                              bool KernelOrKext,
1584                              const ObjCRuntime &objcRuntime,
1585                              ArgStringList &CmdArgs) {
1586   if (KernelOrKext) {
1587     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
1588     // arguments now to avoid warnings about unused arguments.
1589     Args.ClaimAllArgs(options::OPT_fexceptions);
1590     Args.ClaimAllArgs(options::OPT_fno_exceptions);
1591     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
1592     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
1593     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
1594     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
1595     return;
1596   }
1597 
1598   // Exceptions are enabled by default.
1599   bool ExceptionsEnabled = true;
1600 
1601   // This keeps track of whether exceptions were explicitly turned on or off.
1602   bool DidHaveExplicitExceptionFlag = false;
1603 
1604   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
1605                                options::OPT_fno_exceptions)) {
1606     if (A->getOption().matches(options::OPT_fexceptions))
1607       ExceptionsEnabled = true;
1608     else
1609       ExceptionsEnabled = false;
1610 
1611     DidHaveExplicitExceptionFlag = true;
1612   }
1613 
1614   bool ShouldUseExceptionTables = false;
1615 
1616   // Exception tables and cleanups can be enabled with -fexceptions even if the
1617   // language itself doesn't support exceptions.
1618   if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
1619     ShouldUseExceptionTables = true;
1620 
1621   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
1622   // is not necessarily sensible, but follows GCC.
1623   if (types::isObjC(InputType) &&
1624       Args.hasFlag(options::OPT_fobjc_exceptions,
1625                    options::OPT_fno_objc_exceptions,
1626                    true)) {
1627     CmdArgs.push_back("-fobjc-exceptions");
1628 
1629     ShouldUseExceptionTables |=
1630       shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
1631   }
1632 
1633   if (types::isCXX(InputType)) {
1634     bool CXXExceptionsEnabled = ExceptionsEnabled;
1635 
1636     if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
1637                                  options::OPT_fno_cxx_exceptions,
1638                                  options::OPT_fexceptions,
1639                                  options::OPT_fno_exceptions)) {
1640       if (A->getOption().matches(options::OPT_fcxx_exceptions))
1641         CXXExceptionsEnabled = true;
1642       else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
1643         CXXExceptionsEnabled = false;
1644     }
1645 
1646     if (CXXExceptionsEnabled) {
1647       CmdArgs.push_back("-fcxx-exceptions");
1648 
1649       ShouldUseExceptionTables = true;
1650     }
1651   }
1652 
1653   if (ShouldUseExceptionTables)
1654     CmdArgs.push_back("-fexceptions");
1655 }
1656 
1657 static bool ShouldDisableAutolink(const ArgList &Args,
1658                              const ToolChain &TC) {
1659   bool Default = true;
1660   if (TC.getTriple().isOSDarwin()) {
1661     // The native darwin assembler doesn't support the linker_option directives,
1662     // so we disable them if we think the .s file will be passed to it.
1663     Default = TC.useIntegratedAs();
1664   }
1665   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
1666                        Default);
1667 }
1668 
1669 static bool ShouldDisableCFI(const ArgList &Args,
1670                              const ToolChain &TC) {
1671   bool Default = true;
1672   if (TC.getTriple().isOSDarwin()) {
1673     // The native darwin assembler doesn't support cfi directives, so
1674     // we disable them if we think the .s file will be passed to it.
1675     Default = TC.useIntegratedAs();
1676   }
1677   return !Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
1678                        options::OPT_fno_dwarf2_cfi_asm,
1679                        Default);
1680 }
1681 
1682 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
1683                                         const ToolChain &TC) {
1684   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
1685                                         options::OPT_fno_dwarf_directory_asm,
1686                                         TC.useIntegratedAs());
1687   return !UseDwarfDirectory;
1688 }
1689 
1690 /// \brief Check whether the given input tree contains any compilation actions.
1691 static bool ContainsCompileAction(const Action *A) {
1692   if (isa<CompileJobAction>(A))
1693     return true;
1694 
1695   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
1696     if (ContainsCompileAction(*it))
1697       return true;
1698 
1699   return false;
1700 }
1701 
1702 /// \brief Check if -relax-all should be passed to the internal assembler.
1703 /// This is done by default when compiling non-assembler source with -O0.
1704 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
1705   bool RelaxDefault = true;
1706 
1707   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1708     RelaxDefault = A->getOption().matches(options::OPT_O0);
1709 
1710   if (RelaxDefault) {
1711     RelaxDefault = false;
1712     for (ActionList::const_iterator it = C.getActions().begin(),
1713            ie = C.getActions().end(); it != ie; ++it) {
1714       if (ContainsCompileAction(*it)) {
1715         RelaxDefault = true;
1716         break;
1717       }
1718     }
1719   }
1720 
1721   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1722     RelaxDefault);
1723 }
1724 
1725 static void CollectArgsForIntegratedAssembler(Compilation &C,
1726                                               const ArgList &Args,
1727                                               ArgStringList &CmdArgs,
1728                                               const Driver &D) {
1729     if (UseRelaxAll(C, Args))
1730       CmdArgs.push_back("-mrelax-all");
1731 
1732     // When passing -I arguments to the assembler we sometimes need to
1733     // unconditionally take the next argument.  For example, when parsing
1734     // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1735     // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1736     // arg after parsing the '-I' arg.
1737     bool TakeNextArg = false;
1738 
1739     // When using an integrated assembler, translate -Wa, and -Xassembler
1740     // options.
1741     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
1742                                                options::OPT_Xassembler),
1743            ie = Args.filtered_end(); it != ie; ++it) {
1744       const Arg *A = *it;
1745       A->claim();
1746 
1747       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
1748         StringRef Value = A->getValue(i);
1749         if (TakeNextArg) {
1750           CmdArgs.push_back(Value.data());
1751           TakeNextArg = false;
1752           continue;
1753         }
1754 
1755         if (Value == "-force_cpusubtype_ALL") {
1756           // Do nothing, this is the default and we don't support anything else.
1757         } else if (Value == "-L") {
1758           CmdArgs.push_back("-msave-temp-labels");
1759         } else if (Value == "--fatal-warnings") {
1760           CmdArgs.push_back("-mllvm");
1761           CmdArgs.push_back("-fatal-assembler-warnings");
1762         } else if (Value == "--noexecstack") {
1763           CmdArgs.push_back("-mnoexecstack");
1764         } else if (Value.startswith("-I")) {
1765           CmdArgs.push_back(Value.data());
1766           // We need to consume the next argument if the current arg is a plain
1767           // -I. The next arg will be the include directory.
1768           if (Value == "-I")
1769             TakeNextArg = true;
1770         } else {
1771           D.Diag(diag::err_drv_unsupported_option_argument)
1772             << A->getOption().getName() << Value;
1773         }
1774       }
1775     }
1776 }
1777 
1778 static void addProfileRTLinux(
1779     const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
1780   if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
1781         Args.hasArg(options::OPT_fprofile_generate) ||
1782         Args.hasArg(options::OPT_fcreate_profile) ||
1783         Args.hasArg(options::OPT_coverage)))
1784     return;
1785 
1786   // The profile runtime is located in the Linux library directory and has name
1787   // "libclang_rt.profile-<ArchName>.a".
1788   SmallString<128> LibProfile(TC.getDriver().ResourceDir);
1789   llvm::sys::path::append(
1790       LibProfile, "lib", "linux",
1791       Twine("libclang_rt.profile-") + TC.getArchName() + ".a");
1792 
1793   CmdArgs.push_back(Args.MakeArgString(LibProfile));
1794 }
1795 
1796 static void addSanitizerRTLinkFlagsLinux(
1797     const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs,
1798     const StringRef Sanitizer, bool BeforeLibStdCXX,
1799     bool ExportSymbols = true) {
1800   // Sanitizer runtime is located in the Linux library directory and
1801   // has name "libclang_rt.<Sanitizer>-<ArchName>.a".
1802   SmallString<128> LibSanitizer(TC.getDriver().ResourceDir);
1803   llvm::sys::path::append(
1804       LibSanitizer, "lib", "linux",
1805       (Twine("libclang_rt.") + Sanitizer + "-" + TC.getArchName() + ".a"));
1806 
1807   // Sanitizer runtime may need to come before -lstdc++ (or -lc++, libstdc++.a,
1808   // etc.) so that the linker picks custom versions of the global 'operator
1809   // new' and 'operator delete' symbols. We take the extreme (but simple)
1810   // strategy of inserting it at the front of the link command. It also
1811   // needs to be forced to end up in the executable, so wrap it in
1812   // whole-archive.
1813   SmallVector<const char *, 3> LibSanitizerArgs;
1814   LibSanitizerArgs.push_back("-whole-archive");
1815   LibSanitizerArgs.push_back(Args.MakeArgString(LibSanitizer));
1816   LibSanitizerArgs.push_back("-no-whole-archive");
1817 
1818   CmdArgs.insert(BeforeLibStdCXX ? CmdArgs.begin() : CmdArgs.end(),
1819                  LibSanitizerArgs.begin(), LibSanitizerArgs.end());
1820 
1821   CmdArgs.push_back("-lpthread");
1822   CmdArgs.push_back("-lrt");
1823   CmdArgs.push_back("-ldl");
1824   CmdArgs.push_back("-lm");
1825 
1826   // If possible, use a dynamic symbols file to export the symbols from the
1827   // runtime library. If we can't do so, use -export-dynamic instead to export
1828   // all symbols from the binary.
1829   if (ExportSymbols) {
1830     if (llvm::sys::fs::exists(LibSanitizer + ".syms"))
1831       CmdArgs.push_back(
1832           Args.MakeArgString("--dynamic-list=" + LibSanitizer + ".syms"));
1833     else
1834       CmdArgs.push_back("-export-dynamic");
1835   }
1836 }
1837 
1838 /// If AddressSanitizer is enabled, add appropriate linker flags (Linux).
1839 /// This needs to be called before we add the C run-time (malloc, etc).
1840 static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
1841                            ArgStringList &CmdArgs) {
1842   if (TC.getTriple().getEnvironment() == llvm::Triple::Android) {
1843     SmallString<128> LibAsan(TC.getDriver().ResourceDir);
1844     llvm::sys::path::append(LibAsan, "lib", "linux",
1845         (Twine("libclang_rt.asan-") +
1846             TC.getArchName() + "-android.so"));
1847     CmdArgs.insert(CmdArgs.begin(), Args.MakeArgString(LibAsan));
1848   } else {
1849     if (!Args.hasArg(options::OPT_shared))
1850       addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "asan", true);
1851   }
1852 }
1853 
1854 /// If ThreadSanitizer is enabled, add appropriate linker flags (Linux).
1855 /// This needs to be called before we add the C run-time (malloc, etc).
1856 static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args,
1857                            ArgStringList &CmdArgs) {
1858   if (!Args.hasArg(options::OPT_shared))
1859     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "tsan", true);
1860 }
1861 
1862 /// If MemorySanitizer is enabled, add appropriate linker flags (Linux).
1863 /// This needs to be called before we add the C run-time (malloc, etc).
1864 static void addMsanRTLinux(const ToolChain &TC, const ArgList &Args,
1865                            ArgStringList &CmdArgs) {
1866   if (!Args.hasArg(options::OPT_shared))
1867     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "msan", true);
1868 }
1869 
1870 /// If LeakSanitizer is enabled, add appropriate linker flags (Linux).
1871 /// This needs to be called before we add the C run-time (malloc, etc).
1872 static void addLsanRTLinux(const ToolChain &TC, const ArgList &Args,
1873                            ArgStringList &CmdArgs) {
1874   if (!Args.hasArg(options::OPT_shared))
1875     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "lsan", true);
1876 }
1877 
1878 /// If UndefinedBehaviorSanitizer is enabled, add appropriate linker flags
1879 /// (Linux).
1880 static void addUbsanRTLinux(const ToolChain &TC, const ArgList &Args,
1881                             ArgStringList &CmdArgs, bool IsCXX,
1882                             bool HasOtherSanitizerRt) {
1883   // Need a copy of sanitizer_common. This could come from another sanitizer
1884   // runtime; if we're not including one, include our own copy.
1885   if (!HasOtherSanitizerRt)
1886     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "san", true, false);
1887 
1888   addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan", false);
1889 
1890   // Only include the bits of the runtime which need a C++ ABI library if
1891   // we're linking in C++ mode.
1892   if (IsCXX)
1893     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan_cxx", false);
1894 }
1895 
1896 static void addDfsanRTLinux(const ToolChain &TC, const ArgList &Args,
1897                             ArgStringList &CmdArgs) {
1898   if (!Args.hasArg(options::OPT_shared))
1899     addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "dfsan", true);
1900 }
1901 
1902 static bool shouldUseFramePointerForTarget(const ArgList &Args,
1903                                            const llvm::Triple &Triple) {
1904   switch (Triple.getArch()) {
1905   // Don't use a frame pointer on linux if optimizing for certain targets.
1906   case llvm::Triple::mips64:
1907   case llvm::Triple::mips64el:
1908   case llvm::Triple::mips:
1909   case llvm::Triple::mipsel:
1910   case llvm::Triple::systemz:
1911   case llvm::Triple::x86:
1912   case llvm::Triple::x86_64:
1913     if (Triple.isOSLinux())
1914       if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1915         if (!A->getOption().matches(options::OPT_O0))
1916           return false;
1917     return true;
1918   case llvm::Triple::xcore:
1919     return false;
1920   default:
1921     return true;
1922   }
1923 }
1924 
1925 static bool shouldUseFramePointer(const ArgList &Args,
1926                                   const llvm::Triple &Triple) {
1927   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
1928                                options::OPT_fomit_frame_pointer))
1929     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
1930 
1931   return shouldUseFramePointerForTarget(Args, Triple);
1932 }
1933 
1934 static bool shouldUseLeafFramePointer(const ArgList &Args,
1935                                       const llvm::Triple &Triple) {
1936   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
1937                                options::OPT_momit_leaf_frame_pointer))
1938     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
1939 
1940   return shouldUseFramePointerForTarget(Args, Triple);
1941 }
1942 
1943 /// Add a CC1 option to specify the debug compilation directory.
1944 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
1945   SmallString<128> cwd;
1946   if (!llvm::sys::fs::current_path(cwd)) {
1947     CmdArgs.push_back("-fdebug-compilation-dir");
1948     CmdArgs.push_back(Args.MakeArgString(cwd));
1949   }
1950 }
1951 
1952 static const char *SplitDebugName(const ArgList &Args,
1953                                   const InputInfoList &Inputs) {
1954   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1955   if (FinalOutput && Args.hasArg(options::OPT_c)) {
1956     SmallString<128> T(FinalOutput->getValue());
1957     llvm::sys::path::replace_extension(T, "dwo");
1958     return Args.MakeArgString(T);
1959   } else {
1960     // Use the compilation dir.
1961     SmallString<128> T(Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
1962     SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput()));
1963     llvm::sys::path::replace_extension(F, "dwo");
1964     T += F;
1965     return Args.MakeArgString(F);
1966   }
1967 }
1968 
1969 static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
1970                            const Tool &T, const JobAction &JA,
1971                            const ArgList &Args, const InputInfo &Output,
1972                            const char *OutFile) {
1973   ArgStringList ExtractArgs;
1974   ExtractArgs.push_back("--extract-dwo");
1975 
1976   ArgStringList StripArgs;
1977   StripArgs.push_back("--strip-dwo");
1978 
1979   // Grabbing the output of the earlier compile step.
1980   StripArgs.push_back(Output.getFilename());
1981   ExtractArgs.push_back(Output.getFilename());
1982   ExtractArgs.push_back(OutFile);
1983 
1984   const char *Exec =
1985     Args.MakeArgString(TC.GetProgramPath("objcopy"));
1986 
1987   // First extract the dwo sections.
1988   C.addCommand(new Command(JA, T, Exec, ExtractArgs));
1989 
1990   // Then remove them from the original .o file.
1991   C.addCommand(new Command(JA, T, Exec, StripArgs));
1992 }
1993 
1994 static bool isOptimizationLevelFast(const ArgList &Args) {
1995   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1996     if (A->getOption().matches(options::OPT_Ofast))
1997       return true;
1998   return false;
1999 }
2000 
2001 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2002 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args) {
2003   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2004     if (A->getOption().matches(options::OPT_O4) ||
2005         A->getOption().matches(options::OPT_Ofast))
2006       return true;
2007 
2008     if (A->getOption().matches(options::OPT_O0))
2009       return false;
2010 
2011     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2012 
2013     // Vectorize -Os.
2014     StringRef S(A->getValue());
2015     if (S == "s")
2016       return true;
2017 
2018     // Don't vectorize -Oz.
2019     if (S == "z")
2020       return false;
2021 
2022     unsigned OptLevel = 0;
2023     if (S.getAsInteger(10, OptLevel))
2024       return false;
2025 
2026     return OptLevel > 1;
2027   }
2028 
2029   return false;
2030 }
2031 
2032 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2033                          const InputInfo &Output,
2034                          const InputInfoList &Inputs,
2035                          const ArgList &Args,
2036                          const char *LinkingOutput) const {
2037   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
2038                                   options::OPT_fapple_kext);
2039   const Driver &D = getToolChain().getDriver();
2040   ArgStringList CmdArgs;
2041 
2042   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2043 
2044   // Invoke ourselves in -cc1 mode.
2045   //
2046   // FIXME: Implement custom jobs for internal actions.
2047   CmdArgs.push_back("-cc1");
2048 
2049   // Add the "effective" target triple.
2050   CmdArgs.push_back("-triple");
2051   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2052   CmdArgs.push_back(Args.MakeArgString(TripleStr));
2053 
2054   // Select the appropriate action.
2055   RewriteKind rewriteKind = RK_None;
2056 
2057   if (isa<AnalyzeJobAction>(JA)) {
2058     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2059     CmdArgs.push_back("-analyze");
2060   } else if (isa<MigrateJobAction>(JA)) {
2061     CmdArgs.push_back("-migrate");
2062   } else if (isa<PreprocessJobAction>(JA)) {
2063     if (Output.getType() == types::TY_Dependencies)
2064       CmdArgs.push_back("-Eonly");
2065     else {
2066       CmdArgs.push_back("-E");
2067       if (Args.hasArg(options::OPT_rewrite_objc) &&
2068           !Args.hasArg(options::OPT_g_Group))
2069         CmdArgs.push_back("-P");
2070     }
2071   } else if (isa<AssembleJobAction>(JA)) {
2072     CmdArgs.push_back("-emit-obj");
2073 
2074     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2075 
2076     // Also ignore explicit -force_cpusubtype_ALL option.
2077     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
2078   } else if (isa<PrecompileJobAction>(JA)) {
2079     // Use PCH if the user requested it.
2080     bool UsePCH = D.CCCUsePCH;
2081 
2082     if (JA.getType() == types::TY_Nothing)
2083       CmdArgs.push_back("-fsyntax-only");
2084     else if (UsePCH)
2085       CmdArgs.push_back("-emit-pch");
2086     else
2087       CmdArgs.push_back("-emit-pth");
2088   } else {
2089     assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
2090 
2091     if (JA.getType() == types::TY_Nothing) {
2092       CmdArgs.push_back("-fsyntax-only");
2093     } else if (JA.getType() == types::TY_LLVM_IR ||
2094                JA.getType() == types::TY_LTO_IR) {
2095       CmdArgs.push_back("-emit-llvm");
2096     } else if (JA.getType() == types::TY_LLVM_BC ||
2097                JA.getType() == types::TY_LTO_BC) {
2098       CmdArgs.push_back("-emit-llvm-bc");
2099     } else if (JA.getType() == types::TY_PP_Asm) {
2100       CmdArgs.push_back("-S");
2101     } else if (JA.getType() == types::TY_AST) {
2102       CmdArgs.push_back("-emit-pch");
2103     } else if (JA.getType() == types::TY_ModuleFile) {
2104       CmdArgs.push_back("-module-file-info");
2105     } else if (JA.getType() == types::TY_RewrittenObjC) {
2106       CmdArgs.push_back("-rewrite-objc");
2107       rewriteKind = RK_NonFragile;
2108     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2109       CmdArgs.push_back("-rewrite-objc");
2110       rewriteKind = RK_Fragile;
2111     } else {
2112       assert(JA.getType() == types::TY_PP_Asm &&
2113              "Unexpected output type!");
2114     }
2115   }
2116 
2117   // The make clang go fast button.
2118   CmdArgs.push_back("-disable-free");
2119 
2120   // Disable the verification pass in -asserts builds.
2121 #ifdef NDEBUG
2122   CmdArgs.push_back("-disable-llvm-verifier");
2123 #endif
2124 
2125   // Set the main file name, so that debug info works even with
2126   // -save-temps.
2127   CmdArgs.push_back("-main-file-name");
2128   CmdArgs.push_back(getBaseInputName(Args, Inputs));
2129 
2130   // Some flags which affect the language (via preprocessor
2131   // defines).
2132   if (Args.hasArg(options::OPT_static))
2133     CmdArgs.push_back("-static-define");
2134 
2135   if (isa<AnalyzeJobAction>(JA)) {
2136     // Enable region store model by default.
2137     CmdArgs.push_back("-analyzer-store=region");
2138 
2139     // Treat blocks as analysis entry points.
2140     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2141 
2142     CmdArgs.push_back("-analyzer-eagerly-assume");
2143 
2144     // Add default argument set.
2145     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2146       CmdArgs.push_back("-analyzer-checker=core");
2147 
2148       if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
2149         CmdArgs.push_back("-analyzer-checker=unix");
2150 
2151       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2152         CmdArgs.push_back("-analyzer-checker=osx");
2153 
2154       CmdArgs.push_back("-analyzer-checker=deadcode");
2155 
2156       if (types::isCXX(Inputs[0].getType()))
2157         CmdArgs.push_back("-analyzer-checker=cplusplus");
2158 
2159       // Enable the following experimental checkers for testing.
2160       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2161       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2162       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2163       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2164       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2165       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2166     }
2167 
2168     // Set the output format. The default is plist, for (lame) historical
2169     // reasons.
2170     CmdArgs.push_back("-analyzer-output");
2171     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2172       CmdArgs.push_back(A->getValue());
2173     else
2174       CmdArgs.push_back("plist");
2175 
2176     // Disable the presentation of standard compiler warnings when
2177     // using --analyze.  We only want to show static analyzer diagnostics
2178     // or frontend errors.
2179     CmdArgs.push_back("-w");
2180 
2181     // Add -Xanalyzer arguments when running as analyzer.
2182     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2183   }
2184 
2185   CheckCodeGenerationOptions(D, Args);
2186 
2187   bool PIE = getToolChain().isPIEDefault();
2188   bool PIC = PIE || getToolChain().isPICDefault();
2189   bool IsPICLevelTwo = PIC;
2190 
2191   // For the PIC and PIE flag options, this logic is different from the
2192   // legacy logic in very old versions of GCC, as that logic was just
2193   // a bug no one had ever fixed. This logic is both more rational and
2194   // consistent with GCC's new logic now that the bugs are fixed. The last
2195   // argument relating to either PIC or PIE wins, and no other argument is
2196   // used. If the last argument is any flavor of the '-fno-...' arguments,
2197   // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
2198   // at the same level.
2199   Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
2200                                  options::OPT_fpic, options::OPT_fno_pic,
2201                                  options::OPT_fPIE, options::OPT_fno_PIE,
2202                                  options::OPT_fpie, options::OPT_fno_pie);
2203   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2204   // is forced, then neither PIC nor PIE flags will have no effect.
2205   if (!getToolChain().isPICDefaultForced()) {
2206     if (LastPICArg) {
2207       Option O = LastPICArg->getOption();
2208       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
2209           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
2210         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
2211         PIC = PIE || O.matches(options::OPT_fPIC) ||
2212               O.matches(options::OPT_fpic);
2213         IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
2214                         O.matches(options::OPT_fPIC);
2215       } else {
2216         PIE = PIC = false;
2217       }
2218     }
2219   }
2220 
2221   // Introduce a Darwin-specific hack. If the default is PIC but the flags
2222   // specified while enabling PIC enabled level 1 PIC, just force it back to
2223   // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
2224   // informal testing).
2225   if (PIC && getToolChain().getTriple().isOSDarwin())
2226     IsPICLevelTwo |= getToolChain().isPICDefault();
2227 
2228   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
2229   // PIC or PIE options above, if these show up, PIC is disabled.
2230   llvm::Triple Triple(TripleStr);
2231   if (KernelOrKext &&
2232       (!Triple.isiOS() || Triple.isOSVersionLT(6)))
2233     PIC = PIE = false;
2234   if (Args.hasArg(options::OPT_static))
2235     PIC = PIE = false;
2236 
2237   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
2238     // This is a very special mode. It trumps the other modes, almost no one
2239     // uses it, and it isn't even valid on any OS but Darwin.
2240     if (!getToolChain().getTriple().isOSDarwin())
2241       D.Diag(diag::err_drv_unsupported_opt_for_target)
2242         << A->getSpelling() << getToolChain().getTriple().str();
2243 
2244     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
2245 
2246     CmdArgs.push_back("-mrelocation-model");
2247     CmdArgs.push_back("dynamic-no-pic");
2248 
2249     // Only a forced PIC mode can cause the actual compile to have PIC defines
2250     // etc., no flags are sufficient. This behavior was selected to closely
2251     // match that of llvm-gcc and Apple GCC before that.
2252     if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
2253       CmdArgs.push_back("-pic-level");
2254       CmdArgs.push_back("2");
2255     }
2256   } else {
2257     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
2258     // handled in Clang's IRGen by the -pie-level flag.
2259     CmdArgs.push_back("-mrelocation-model");
2260     CmdArgs.push_back(PIC ? "pic" : "static");
2261 
2262     if (PIC) {
2263       CmdArgs.push_back("-pic-level");
2264       CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2265       if (PIE) {
2266         CmdArgs.push_back("-pie-level");
2267         CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2268       }
2269     }
2270   }
2271 
2272   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2273                     options::OPT_fno_merge_all_constants))
2274     CmdArgs.push_back("-fno-merge-all-constants");
2275 
2276   // LLVM Code Generator Options.
2277 
2278   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2279     CmdArgs.push_back("-mregparm");
2280     CmdArgs.push_back(A->getValue());
2281   }
2282 
2283   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2284                                options::OPT_freg_struct_return)) {
2285     if (getToolChain().getArch() != llvm::Triple::x86) {
2286       D.Diag(diag::err_drv_unsupported_opt_for_target)
2287         << A->getSpelling() << getToolChain().getTriple().str();
2288     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2289       CmdArgs.push_back("-fpcc-struct-return");
2290     } else {
2291       assert(A->getOption().matches(options::OPT_freg_struct_return));
2292       CmdArgs.push_back("-freg-struct-return");
2293     }
2294   }
2295 
2296   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2297     CmdArgs.push_back("-mrtd");
2298 
2299   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2300     CmdArgs.push_back("-mdisable-fp-elim");
2301   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2302                     options::OPT_fno_zero_initialized_in_bss))
2303     CmdArgs.push_back("-mno-zero-initialized-in-bss");
2304 
2305   bool OFastEnabled = isOptimizationLevelFast(Args);
2306   // If -Ofast is the optimization level, then -fstrict-aliasing should be
2307   // enabled.  This alias option is being used to simplify the hasFlag logic.
2308   OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
2309     options::OPT_fstrict_aliasing;
2310   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2311                     options::OPT_fno_strict_aliasing, true))
2312     CmdArgs.push_back("-relaxed-aliasing");
2313   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2314                     options::OPT_fno_struct_path_tbaa))
2315     CmdArgs.push_back("-no-struct-path-tbaa");
2316   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2317                    false))
2318     CmdArgs.push_back("-fstrict-enums");
2319   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2320                     options::OPT_fno_optimize_sibling_calls))
2321     CmdArgs.push_back("-mdisable-tail-calls");
2322 
2323   // Handle segmented stacks.
2324   if (Args.hasArg(options::OPT_fsplit_stack))
2325     CmdArgs.push_back("-split-stacks");
2326 
2327   // If -Ofast is the optimization level, then -ffast-math should be enabled.
2328   // This alias option is being used to simplify the getLastArg logic.
2329   OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
2330     options::OPT_ffast_math;
2331 
2332   // Handle various floating point optimization flags, mapping them to the
2333   // appropriate LLVM code generation flags. The pattern for all of these is to
2334   // default off the codegen optimizations, and if any flag enables them and no
2335   // flag disables them after the flag enabling them, enable the codegen
2336   // optimization. This is complicated by several "umbrella" flags.
2337   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2338                                options::OPT_fno_fast_math,
2339                                options::OPT_ffinite_math_only,
2340                                options::OPT_fno_finite_math_only,
2341                                options::OPT_fhonor_infinities,
2342                                options::OPT_fno_honor_infinities))
2343     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2344         A->getOption().getID() != options::OPT_fno_finite_math_only &&
2345         A->getOption().getID() != options::OPT_fhonor_infinities)
2346       CmdArgs.push_back("-menable-no-infs");
2347   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2348                                options::OPT_fno_fast_math,
2349                                options::OPT_ffinite_math_only,
2350                                options::OPT_fno_finite_math_only,
2351                                options::OPT_fhonor_nans,
2352                                options::OPT_fno_honor_nans))
2353     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2354         A->getOption().getID() != options::OPT_fno_finite_math_only &&
2355         A->getOption().getID() != options::OPT_fhonor_nans)
2356       CmdArgs.push_back("-menable-no-nans");
2357 
2358   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2359   bool MathErrno = getToolChain().IsMathErrnoDefault();
2360   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2361                                options::OPT_fno_fast_math,
2362                                options::OPT_fmath_errno,
2363                                options::OPT_fno_math_errno)) {
2364     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
2365     // However, turning *off* -ffast_math merely restores the toolchain default
2366     // (which may be false).
2367     if (A->getOption().getID() == options::OPT_fno_math_errno ||
2368         A->getOption().getID() == options::OPT_ffast_math ||
2369         A->getOption().getID() == options::OPT_Ofast)
2370       MathErrno = false;
2371     else if (A->getOption().getID() == options::OPT_fmath_errno)
2372       MathErrno = true;
2373   }
2374   if (MathErrno)
2375     CmdArgs.push_back("-fmath-errno");
2376 
2377   // There are several flags which require disabling very specific
2378   // optimizations. Any of these being disabled forces us to turn off the
2379   // entire set of LLVM optimizations, so collect them through all the flag
2380   // madness.
2381   bool AssociativeMath = false;
2382   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2383                                options::OPT_fno_fast_math,
2384                                options::OPT_funsafe_math_optimizations,
2385                                options::OPT_fno_unsafe_math_optimizations,
2386                                options::OPT_fassociative_math,
2387                                options::OPT_fno_associative_math))
2388     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2389         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2390         A->getOption().getID() != options::OPT_fno_associative_math)
2391       AssociativeMath = true;
2392   bool ReciprocalMath = false;
2393   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2394                                options::OPT_fno_fast_math,
2395                                options::OPT_funsafe_math_optimizations,
2396                                options::OPT_fno_unsafe_math_optimizations,
2397                                options::OPT_freciprocal_math,
2398                                options::OPT_fno_reciprocal_math))
2399     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2400         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2401         A->getOption().getID() != options::OPT_fno_reciprocal_math)
2402       ReciprocalMath = true;
2403   bool SignedZeros = true;
2404   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2405                                options::OPT_fno_fast_math,
2406                                options::OPT_funsafe_math_optimizations,
2407                                options::OPT_fno_unsafe_math_optimizations,
2408                                options::OPT_fsigned_zeros,
2409                                options::OPT_fno_signed_zeros))
2410     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2411         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2412         A->getOption().getID() != options::OPT_fsigned_zeros)
2413       SignedZeros = false;
2414   bool TrappingMath = true;
2415   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2416                                options::OPT_fno_fast_math,
2417                                options::OPT_funsafe_math_optimizations,
2418                                options::OPT_fno_unsafe_math_optimizations,
2419                                options::OPT_ftrapping_math,
2420                                options::OPT_fno_trapping_math))
2421     if (A->getOption().getID() != options::OPT_fno_fast_math &&
2422         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2423         A->getOption().getID() != options::OPT_ftrapping_math)
2424       TrappingMath = false;
2425   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2426       !TrappingMath)
2427     CmdArgs.push_back("-menable-unsafe-fp-math");
2428 
2429 
2430   // Validate and pass through -fp-contract option.
2431   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2432                                options::OPT_fno_fast_math,
2433                                options::OPT_ffp_contract)) {
2434     if (A->getOption().getID() == options::OPT_ffp_contract) {
2435       StringRef Val = A->getValue();
2436       if (Val == "fast" || Val == "on" || Val == "off") {
2437         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
2438       } else {
2439         D.Diag(diag::err_drv_unsupported_option_argument)
2440           << A->getOption().getName() << Val;
2441       }
2442     } else if (A->getOption().matches(options::OPT_ffast_math) ||
2443                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
2444       // If fast-math is set then set the fp-contract mode to fast.
2445       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2446     }
2447   }
2448 
2449   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
2450   // and if we find them, tell the frontend to provide the appropriate
2451   // preprocessor macros. This is distinct from enabling any optimizations as
2452   // these options induce language changes which must survive serialization
2453   // and deserialization, etc.
2454   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2455                                options::OPT_fno_fast_math))
2456       if (!A->getOption().matches(options::OPT_fno_fast_math))
2457         CmdArgs.push_back("-ffast-math");
2458   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only, options::OPT_fno_fast_math))
2459     if (A->getOption().matches(options::OPT_ffinite_math_only))
2460       CmdArgs.push_back("-ffinite-math-only");
2461 
2462   // Decide whether to use verbose asm. Verbose assembly is the default on
2463   // toolchains which have the integrated assembler on by default.
2464   bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
2465   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2466                    IsVerboseAsmDefault) ||
2467       Args.hasArg(options::OPT_dA))
2468     CmdArgs.push_back("-masm-verbose");
2469 
2470   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2471     CmdArgs.push_back("-mdebug-pass");
2472     CmdArgs.push_back("Structure");
2473   }
2474   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2475     CmdArgs.push_back("-mdebug-pass");
2476     CmdArgs.push_back("Arguments");
2477   }
2478 
2479   // Enable -mconstructor-aliases except on darwin, where we have to
2480   // work around a linker bug;  see <rdar://problem/7651567>.
2481   if (!getToolChain().getTriple().isOSDarwin())
2482     CmdArgs.push_back("-mconstructor-aliases");
2483 
2484   // Darwin's kernel doesn't support guard variables; just die if we
2485   // try to use them.
2486   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2487     CmdArgs.push_back("-fforbid-guard-variables");
2488 
2489   if (Args.hasArg(options::OPT_mms_bitfields)) {
2490     CmdArgs.push_back("-mms-bitfields");
2491   }
2492 
2493   // This is a coarse approximation of what llvm-gcc actually does, both
2494   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2495   // complicated ways.
2496   bool AsynchronousUnwindTables =
2497     Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2498                  options::OPT_fno_asynchronous_unwind_tables,
2499                  getToolChain().IsUnwindTablesDefault() &&
2500                  !KernelOrKext);
2501   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2502                    AsynchronousUnwindTables))
2503     CmdArgs.push_back("-munwind-tables");
2504 
2505   getToolChain().addClangTargetOptions(Args, CmdArgs);
2506 
2507   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2508     CmdArgs.push_back("-mlimit-float-precision");
2509     CmdArgs.push_back(A->getValue());
2510   }
2511 
2512   // FIXME: Handle -mtune=.
2513   (void) Args.hasArg(options::OPT_mtune_EQ);
2514 
2515   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2516     CmdArgs.push_back("-mcode-model");
2517     CmdArgs.push_back(A->getValue());
2518   }
2519 
2520   // Add the target cpu
2521   std::string ETripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2522   llvm::Triple ETriple(ETripleStr);
2523   std::string CPU = getCPUName(Args, ETriple);
2524   if (!CPU.empty()) {
2525     CmdArgs.push_back("-target-cpu");
2526     CmdArgs.push_back(Args.MakeArgString(CPU));
2527   }
2528 
2529   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2530     CmdArgs.push_back("-mfpmath");
2531     CmdArgs.push_back(A->getValue());
2532   }
2533 
2534   // Add the target features
2535   getTargetFeatures(D, ETriple, Args, CmdArgs);
2536 
2537   // Add target specific flags.
2538   switch(getToolChain().getArch()) {
2539   default:
2540     break;
2541 
2542   case llvm::Triple::arm:
2543   case llvm::Triple::thumb:
2544     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
2545     break;
2546 
2547   case llvm::Triple::mips:
2548   case llvm::Triple::mipsel:
2549   case llvm::Triple::mips64:
2550   case llvm::Triple::mips64el:
2551     AddMIPSTargetArgs(Args, CmdArgs);
2552     break;
2553 
2554   case llvm::Triple::sparc:
2555     AddSparcTargetArgs(Args, CmdArgs);
2556     break;
2557 
2558   case llvm::Triple::x86:
2559   case llvm::Triple::x86_64:
2560     AddX86TargetArgs(Args, CmdArgs);
2561     break;
2562 
2563   case llvm::Triple::hexagon:
2564     AddHexagonTargetArgs(Args, CmdArgs);
2565     break;
2566   }
2567 
2568   // Add clang-cl arguments.
2569   if (getToolChain().getDriver().IsCLMode())
2570     AddClangCLArgs(Args, CmdArgs);
2571 
2572   // Pass the linker version in use.
2573   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2574     CmdArgs.push_back("-target-linker-version");
2575     CmdArgs.push_back(A->getValue());
2576   }
2577 
2578   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
2579     CmdArgs.push_back("-momit-leaf-frame-pointer");
2580 
2581   // Explicitly error on some things we know we don't support and can't just
2582   // ignore.
2583   types::ID InputType = Inputs[0].getType();
2584   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2585     Arg *Unsupported;
2586     if (types::isCXX(InputType) &&
2587         getToolChain().getTriple().isOSDarwin() &&
2588         getToolChain().getArch() == llvm::Triple::x86) {
2589       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2590           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2591         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2592           << Unsupported->getOption().getName();
2593     }
2594   }
2595 
2596   Args.AddAllArgs(CmdArgs, options::OPT_v);
2597   Args.AddLastArg(CmdArgs, options::OPT_H);
2598   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2599     CmdArgs.push_back("-header-include-file");
2600     CmdArgs.push_back(D.CCPrintHeadersFilename ?
2601                       D.CCPrintHeadersFilename : "-");
2602   }
2603   Args.AddLastArg(CmdArgs, options::OPT_P);
2604   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2605 
2606   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2607     CmdArgs.push_back("-diagnostic-log-file");
2608     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
2609                       D.CCLogDiagnosticsFilename : "-");
2610   }
2611 
2612   // Use the last option from "-g" group. "-gline-tables-only"
2613   // is preserved, all other debug options are substituted with "-g".
2614   Args.ClaimAllArgs(options::OPT_g_Group);
2615   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2616     if (A->getOption().matches(options::OPT_gline_tables_only))
2617       CmdArgs.push_back("-gline-tables-only");
2618     else if (A->getOption().matches(options::OPT_gdwarf_2))
2619       CmdArgs.push_back("-gdwarf-2");
2620     else if (A->getOption().matches(options::OPT_gdwarf_3))
2621       CmdArgs.push_back("-gdwarf-3");
2622     else if (A->getOption().matches(options::OPT_gdwarf_4))
2623       CmdArgs.push_back("-gdwarf-4");
2624     else if (!A->getOption().matches(options::OPT_g0) &&
2625              !A->getOption().matches(options::OPT_ggdb0)) {
2626       // Default is dwarf-2 for darwin.
2627       if (getToolChain().getTriple().isOSDarwin())
2628         CmdArgs.push_back("-gdwarf-2");
2629       else
2630         CmdArgs.push_back("-g");
2631     }
2632   }
2633 
2634   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
2635   Args.ClaimAllArgs(options::OPT_g_flags_Group);
2636   if (Args.hasArg(options::OPT_gcolumn_info))
2637     CmdArgs.push_back("-dwarf-column-info");
2638 
2639   // FIXME: Move backend command line options to the module.
2640   // -gsplit-dwarf should turn on -g and enable the backend dwarf
2641   // splitting and extraction.
2642   // FIXME: Currently only works on Linux.
2643   if (getToolChain().getTriple().isOSLinux() &&
2644       Args.hasArg(options::OPT_gsplit_dwarf)) {
2645     CmdArgs.push_back("-g");
2646     CmdArgs.push_back("-backend-option");
2647     CmdArgs.push_back("-split-dwarf=Enable");
2648   }
2649 
2650   // -ggnu-pubnames turns on gnu style pubnames in the backend.
2651   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2652     CmdArgs.push_back("-backend-option");
2653     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2654   }
2655 
2656   Args.AddAllArgs(CmdArgs, options::OPT_fdebug_types_section);
2657 
2658   Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
2659   Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
2660 
2661   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2662 
2663   if (Args.hasArg(options::OPT_ftest_coverage) ||
2664       Args.hasArg(options::OPT_coverage))
2665     CmdArgs.push_back("-femit-coverage-notes");
2666   if (Args.hasArg(options::OPT_fprofile_arcs) ||
2667       Args.hasArg(options::OPT_coverage))
2668     CmdArgs.push_back("-femit-coverage-data");
2669 
2670   if (C.getArgs().hasArg(options::OPT_c) ||
2671       C.getArgs().hasArg(options::OPT_S)) {
2672     if (Output.isFilename()) {
2673       CmdArgs.push_back("-coverage-file");
2674       SmallString<128> CoverageFilename(Output.getFilename());
2675       if (llvm::sys::path::is_relative(CoverageFilename.str())) {
2676         SmallString<128> Pwd;
2677         if (!llvm::sys::fs::current_path(Pwd)) {
2678           llvm::sys::path::append(Pwd, CoverageFilename.str());
2679           CoverageFilename.swap(Pwd);
2680         }
2681       }
2682       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
2683     }
2684   }
2685 
2686   // Pass options for controlling the default header search paths.
2687   if (Args.hasArg(options::OPT_nostdinc)) {
2688     CmdArgs.push_back("-nostdsysteminc");
2689     CmdArgs.push_back("-nobuiltininc");
2690   } else {
2691     if (Args.hasArg(options::OPT_nostdlibinc))
2692         CmdArgs.push_back("-nostdsysteminc");
2693     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2694     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2695   }
2696 
2697   // Pass the path to compiler resource files.
2698   CmdArgs.push_back("-resource-dir");
2699   CmdArgs.push_back(D.ResourceDir.c_str());
2700 
2701   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2702 
2703   bool ARCMTEnabled = false;
2704   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2705     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2706                                        options::OPT_ccc_arcmt_modify,
2707                                        options::OPT_ccc_arcmt_migrate)) {
2708       ARCMTEnabled = true;
2709       switch (A->getOption().getID()) {
2710       default:
2711         llvm_unreachable("missed a case");
2712       case options::OPT_ccc_arcmt_check:
2713         CmdArgs.push_back("-arcmt-check");
2714         break;
2715       case options::OPT_ccc_arcmt_modify:
2716         CmdArgs.push_back("-arcmt-modify");
2717         break;
2718       case options::OPT_ccc_arcmt_migrate:
2719         CmdArgs.push_back("-arcmt-migrate");
2720         CmdArgs.push_back("-mt-migrate-directory");
2721         CmdArgs.push_back(A->getValue());
2722 
2723         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2724         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2725         break;
2726       }
2727     }
2728   } else {
2729     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2730     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2731     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2732   }
2733 
2734   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2735     if (ARCMTEnabled) {
2736       D.Diag(diag::err_drv_argument_not_allowed_with)
2737         << A->getAsString(Args) << "-ccc-arcmt-migrate";
2738     }
2739     CmdArgs.push_back("-mt-migrate-directory");
2740     CmdArgs.push_back(A->getValue());
2741 
2742     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2743                      options::OPT_objcmt_migrate_subscripting,
2744                      options::OPT_objcmt_migrate_property)) {
2745       // None specified, means enable them all.
2746       CmdArgs.push_back("-objcmt-migrate-literals");
2747       CmdArgs.push_back("-objcmt-migrate-subscripting");
2748       CmdArgs.push_back("-objcmt-migrate-property");
2749     } else {
2750       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2751       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2752       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2753     }
2754   } else {
2755     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2756     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2757     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2758     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2759     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2760     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2761     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2762     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2763     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2764     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2765     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2766     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2767     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2768     Args.AddLastArg(CmdArgs, options::OPT_objcmt_white_list_dir_path);
2769   }
2770 
2771   // Add preprocessing options like -I, -D, etc. if we are using the
2772   // preprocessor.
2773   //
2774   // FIXME: Support -fpreprocessed
2775   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2776     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
2777 
2778   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2779   // that "The compiler can only warn and ignore the option if not recognized".
2780   // When building with ccache, it will pass -D options to clang even on
2781   // preprocessed inputs and configure concludes that -fPIC is not supported.
2782   Args.ClaimAllArgs(options::OPT_D);
2783 
2784   // Manually translate -O4 to -O3; let clang reject others.
2785   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2786     if (A->getOption().matches(options::OPT_O4)) {
2787       CmdArgs.push_back("-O3");
2788       D.Diag(diag::warn_O4_is_O3);
2789     } else {
2790       A->render(Args, CmdArgs);
2791     }
2792   }
2793 
2794   // Don't warn about unused -flto.  This can happen when we're preprocessing or
2795   // precompiling.
2796   Args.ClaimAllArgs(options::OPT_flto);
2797 
2798   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2799   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2800     CmdArgs.push_back("-pedantic");
2801   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2802   Args.AddLastArg(CmdArgs, options::OPT_w);
2803 
2804   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2805   // (-ansi is equivalent to -std=c89 or -std=c++98).
2806   //
2807   // If a std is supplied, only add -trigraphs if it follows the
2808   // option.
2809   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2810     if (Std->getOption().matches(options::OPT_ansi))
2811       if (types::isCXX(InputType))
2812         CmdArgs.push_back("-std=c++98");
2813       else
2814         CmdArgs.push_back("-std=c89");
2815     else
2816       Std->render(Args, CmdArgs);
2817 
2818     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
2819                                  options::OPT_trigraphs))
2820       if (A != Std)
2821         A->render(Args, CmdArgs);
2822   } else {
2823     // Honor -std-default.
2824     //
2825     // FIXME: Clang doesn't correctly handle -std= when the input language
2826     // doesn't match. For the time being just ignore this for C++ inputs;
2827     // eventually we want to do all the standard defaulting here instead of
2828     // splitting it between the driver and clang -cc1.
2829     if (!types::isCXX(InputType))
2830       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2831                                 "-std=", /*Joined=*/true);
2832     else if (getToolChain().getTriple().getOS() == llvm::Triple::Win32)
2833       CmdArgs.push_back("-std=c++11");
2834 
2835     Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
2836   }
2837 
2838   // GCC's behavior for -Wwrite-strings is a bit strange:
2839   //  * In C, this "warning flag" changes the types of string literals from
2840   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
2841   //    for the discarded qualifier.
2842   //  * In C++, this is just a normal warning flag.
2843   //
2844   // Implementing this warning correctly in C is hard, so we follow GCC's
2845   // behavior for now. FIXME: Directly diagnose uses of a string literal as
2846   // a non-const char* in C, rather than using this crude hack.
2847   if (!types::isCXX(InputType)) {
2848     DiagnosticsEngine::Level DiagLevel = D.getDiags().getDiagnosticLevel(
2849         diag::warn_deprecated_string_literal_conversion_c, SourceLocation());
2850     if (DiagLevel > DiagnosticsEngine::Ignored)
2851       CmdArgs.push_back("-fconst-strings");
2852   }
2853 
2854   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
2855   // during C++ compilation, which it is by default. GCC keeps this define even
2856   // in the presence of '-w', match this behavior bug-for-bug.
2857   if (types::isCXX(InputType) &&
2858       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
2859                    true)) {
2860     CmdArgs.push_back("-fdeprecated-macro");
2861   }
2862 
2863   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
2864   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
2865     if (Asm->getOption().matches(options::OPT_fasm))
2866       CmdArgs.push_back("-fgnu-keywords");
2867     else
2868       CmdArgs.push_back("-fno-gnu-keywords");
2869   }
2870 
2871   if (ShouldDisableCFI(Args, getToolChain()))
2872     CmdArgs.push_back("-fno-dwarf2-cfi-asm");
2873 
2874   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
2875     CmdArgs.push_back("-fno-dwarf-directory-asm");
2876 
2877   if (ShouldDisableAutolink(Args, getToolChain()))
2878     CmdArgs.push_back("-fno-autolink");
2879 
2880   // Add in -fdebug-compilation-dir if necessary.
2881   addDebugCompDirArg(Args, CmdArgs);
2882 
2883   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
2884                                options::OPT_ftemplate_depth_EQ)) {
2885     CmdArgs.push_back("-ftemplate-depth");
2886     CmdArgs.push_back(A->getValue());
2887   }
2888 
2889   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
2890     CmdArgs.push_back("-foperator-arrow-depth");
2891     CmdArgs.push_back(A->getValue());
2892   }
2893 
2894   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
2895     CmdArgs.push_back("-fconstexpr-depth");
2896     CmdArgs.push_back(A->getValue());
2897   }
2898 
2899   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
2900     CmdArgs.push_back("-fconstexpr-steps");
2901     CmdArgs.push_back(A->getValue());
2902   }
2903 
2904   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
2905     CmdArgs.push_back("-fbracket-depth");
2906     CmdArgs.push_back(A->getValue());
2907   }
2908 
2909   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
2910                                options::OPT_Wlarge_by_value_copy_def)) {
2911     if (A->getNumValues()) {
2912       StringRef bytes = A->getValue();
2913       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
2914     } else
2915       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
2916   }
2917 
2918 
2919   if (Args.hasArg(options::OPT_relocatable_pch))
2920     CmdArgs.push_back("-relocatable-pch");
2921 
2922   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
2923     CmdArgs.push_back("-fconstant-string-class");
2924     CmdArgs.push_back(A->getValue());
2925   }
2926 
2927   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
2928     CmdArgs.push_back("-ftabstop");
2929     CmdArgs.push_back(A->getValue());
2930   }
2931 
2932   CmdArgs.push_back("-ferror-limit");
2933   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
2934     CmdArgs.push_back(A->getValue());
2935   else
2936     CmdArgs.push_back("19");
2937 
2938   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
2939     CmdArgs.push_back("-fmacro-backtrace-limit");
2940     CmdArgs.push_back(A->getValue());
2941   }
2942 
2943   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
2944     CmdArgs.push_back("-ftemplate-backtrace-limit");
2945     CmdArgs.push_back(A->getValue());
2946   }
2947 
2948   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
2949     CmdArgs.push_back("-fconstexpr-backtrace-limit");
2950     CmdArgs.push_back(A->getValue());
2951   }
2952 
2953   // Pass -fmessage-length=.
2954   CmdArgs.push_back("-fmessage-length");
2955   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
2956     CmdArgs.push_back(A->getValue());
2957   } else {
2958     // If -fmessage-length=N was not specified, determine whether this is a
2959     // terminal and, if so, implicitly define -fmessage-length appropriately.
2960     unsigned N = llvm::sys::Process::StandardErrColumns();
2961     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
2962   }
2963 
2964   // -fvisibility= and -fvisibility-ms-compat are of a piece.
2965   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
2966                                      options::OPT_fvisibility_ms_compat)) {
2967     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
2968       CmdArgs.push_back("-fvisibility");
2969       CmdArgs.push_back(A->getValue());
2970     } else {
2971       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
2972       CmdArgs.push_back("-fvisibility");
2973       CmdArgs.push_back("hidden");
2974       CmdArgs.push_back("-ftype-visibility");
2975       CmdArgs.push_back("default");
2976     }
2977   }
2978 
2979   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
2980 
2981   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
2982 
2983   // -fhosted is default.
2984   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
2985       KernelOrKext)
2986     CmdArgs.push_back("-ffreestanding");
2987 
2988   // Forward -f (flag) options which we can pass directly.
2989   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
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   if (Args.hasArg(options::OPT_no_integrated_as))
4611     CmdArgs.push_back("-Q");
4612 
4613   // Forward -g, assuming we are dealing with an actual assembly file.
4614   if (SourceAction->getType() == types::TY_Asm ||
4615       SourceAction->getType() == types::TY_PP_Asm) {
4616     if (Args.hasArg(options::OPT_gstabs))
4617       CmdArgs.push_back("--gstabs");
4618     else if (Args.hasArg(options::OPT_g_Group))
4619       CmdArgs.push_back("-g");
4620   }
4621 
4622   // Derived from asm spec.
4623   AddDarwinArch(Args, CmdArgs);
4624 
4625   // Use -force_cpusubtype_ALL on x86 by default.
4626   if (getToolChain().getArch() == llvm::Triple::x86 ||
4627       getToolChain().getArch() == llvm::Triple::x86_64 ||
4628       Args.hasArg(options::OPT_force__cpusubtype__ALL))
4629     CmdArgs.push_back("-force_cpusubtype_ALL");
4630 
4631   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
4632       (((Args.hasArg(options::OPT_mkernel) ||
4633          Args.hasArg(options::OPT_fapple_kext)) &&
4634         (!getDarwinToolChain().isTargetIPhoneOS() ||
4635          getDarwinToolChain().isIPhoneOSVersionLT(6, 0))) ||
4636        Args.hasArg(options::OPT_static)))
4637     CmdArgs.push_back("-static");
4638 
4639   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4640                        options::OPT_Xassembler);
4641 
4642   assert(Output.isFilename() && "Unexpected lipo output.");
4643   CmdArgs.push_back("-o");
4644   CmdArgs.push_back(Output.getFilename());
4645 
4646   assert(Input.isFilename() && "Invalid input.");
4647   CmdArgs.push_back(Input.getFilename());
4648 
4649   // asm_final spec is empty.
4650 
4651   const char *Exec =
4652     Args.MakeArgString(getToolChain().GetProgramPath("as"));
4653   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4654 }
4655 
4656 void darwin::DarwinTool::anchor() {}
4657 
4658 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
4659                                        ArgStringList &CmdArgs) const {
4660   StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
4661 
4662   // Derived from darwin_arch spec.
4663   CmdArgs.push_back("-arch");
4664   CmdArgs.push_back(Args.MakeArgString(ArchName));
4665 
4666   // FIXME: Is this needed anymore?
4667   if (ArchName == "arm")
4668     CmdArgs.push_back("-force_cpusubtype_ALL");
4669 }
4670 
4671 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
4672   // We only need to generate a temp path for LTO if we aren't compiling object
4673   // files. When compiling source files, we run 'dsymutil' after linking. We
4674   // don't run 'dsymutil' when compiling object files.
4675   for (InputInfoList::const_iterator
4676          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it)
4677     if (it->getType() != types::TY_Object)
4678       return true;
4679 
4680   return false;
4681 }
4682 
4683 void darwin::Link::AddLinkArgs(Compilation &C,
4684                                const ArgList &Args,
4685                                ArgStringList &CmdArgs,
4686                                const InputInfoList &Inputs) const {
4687   const Driver &D = getToolChain().getDriver();
4688   const toolchains::Darwin &DarwinTC = getDarwinToolChain();
4689 
4690   unsigned Version[3] = { 0, 0, 0 };
4691   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4692     bool HadExtra;
4693     if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
4694                                    Version[1], Version[2], HadExtra) ||
4695         HadExtra)
4696       D.Diag(diag::err_drv_invalid_version_number)
4697         << A->getAsString(Args);
4698   }
4699 
4700   // Newer linkers support -demangle, pass it if supported and not disabled by
4701   // the user.
4702   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
4703     // Don't pass -demangle to ld_classic.
4704     //
4705     // FIXME: This is a temporary workaround, ld should be handling this.
4706     bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
4707                           Args.hasArg(options::OPT_static));
4708     if (getToolChain().getArch() == llvm::Triple::x86) {
4709       for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
4710                                                  options::OPT_Wl_COMMA),
4711              ie = Args.filtered_end(); it != ie; ++it) {
4712         const Arg *A = *it;
4713         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
4714           if (StringRef(A->getValue(i)) == "-kext")
4715             UsesLdClassic = true;
4716       }
4717     }
4718     if (!UsesLdClassic)
4719       CmdArgs.push_back("-demangle");
4720   }
4721 
4722   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
4723     CmdArgs.push_back("-export_dynamic");
4724 
4725   // If we are using LTO, then automatically create a temporary file path for
4726   // the linker to use, so that it's lifetime will extend past a possible
4727   // dsymutil step.
4728   if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
4729     const char *TmpPath = C.getArgs().MakeArgString(
4730       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
4731     C.addTempFile(TmpPath);
4732     CmdArgs.push_back("-object_path_lto");
4733     CmdArgs.push_back(TmpPath);
4734   }
4735 
4736   // Derived from the "link" spec.
4737   Args.AddAllArgs(CmdArgs, options::OPT_static);
4738   if (!Args.hasArg(options::OPT_static))
4739     CmdArgs.push_back("-dynamic");
4740   if (Args.hasArg(options::OPT_fgnu_runtime)) {
4741     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
4742     // here. How do we wish to handle such things?
4743   }
4744 
4745   if (!Args.hasArg(options::OPT_dynamiclib)) {
4746     AddDarwinArch(Args, CmdArgs);
4747     // FIXME: Why do this only on this path?
4748     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
4749 
4750     Args.AddLastArg(CmdArgs, options::OPT_bundle);
4751     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
4752     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
4753 
4754     Arg *A;
4755     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
4756         (A = Args.getLastArg(options::OPT_current__version)) ||
4757         (A = Args.getLastArg(options::OPT_install__name)))
4758       D.Diag(diag::err_drv_argument_only_allowed_with)
4759         << A->getAsString(Args) << "-dynamiclib";
4760 
4761     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
4762     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
4763     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
4764   } else {
4765     CmdArgs.push_back("-dylib");
4766 
4767     Arg *A;
4768     if ((A = Args.getLastArg(options::OPT_bundle)) ||
4769         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
4770         (A = Args.getLastArg(options::OPT_client__name)) ||
4771         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
4772         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
4773         (A = Args.getLastArg(options::OPT_private__bundle)))
4774       D.Diag(diag::err_drv_argument_not_allowed_with)
4775         << A->getAsString(Args) << "-dynamiclib";
4776 
4777     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
4778                               "-dylib_compatibility_version");
4779     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
4780                               "-dylib_current_version");
4781 
4782     AddDarwinArch(Args, CmdArgs);
4783 
4784     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
4785                               "-dylib_install_name");
4786   }
4787 
4788   Args.AddLastArg(CmdArgs, options::OPT_all__load);
4789   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
4790   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
4791   if (DarwinTC.isTargetIPhoneOS())
4792     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
4793   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
4794   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
4795   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
4796   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
4797   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
4798   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
4799   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
4800   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
4801   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
4802   Args.AddAllArgs(CmdArgs, options::OPT_init);
4803 
4804   // Add the deployment target.
4805   VersionTuple TargetVersion = DarwinTC.getTargetVersion();
4806 
4807   // If we had an explicit -mios-simulator-version-min argument, honor that,
4808   // otherwise use the traditional deployment targets. We can't just check the
4809   // is-sim attribute because existing code follows this path, and the linker
4810   // may not handle the argument.
4811   //
4812   // FIXME: We may be able to remove this, once we can verify no one depends on
4813   // it.
4814   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
4815     CmdArgs.push_back("-ios_simulator_version_min");
4816   else if (DarwinTC.isTargetIPhoneOS())
4817     CmdArgs.push_back("-iphoneos_version_min");
4818   else
4819     CmdArgs.push_back("-macosx_version_min");
4820   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
4821 
4822   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
4823   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
4824   Args.AddLastArg(CmdArgs, options::OPT_single__module);
4825   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
4826   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
4827 
4828   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
4829                                      options::OPT_fno_pie,
4830                                      options::OPT_fno_PIE)) {
4831     if (A->getOption().matches(options::OPT_fpie) ||
4832         A->getOption().matches(options::OPT_fPIE))
4833       CmdArgs.push_back("-pie");
4834     else
4835       CmdArgs.push_back("-no_pie");
4836   }
4837 
4838   Args.AddLastArg(CmdArgs, options::OPT_prebind);
4839   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
4840   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
4841   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
4842   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
4843   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
4844   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
4845   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
4846   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
4847   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
4848   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
4849   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
4850   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
4851   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
4852   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
4853   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
4854 
4855   // Give --sysroot= preference, over the Apple specific behavior to also use
4856   // --isysroot as the syslibroot.
4857   StringRef sysroot = C.getSysRoot();
4858   if (sysroot != "") {
4859     CmdArgs.push_back("-syslibroot");
4860     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
4861   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4862     CmdArgs.push_back("-syslibroot");
4863     CmdArgs.push_back(A->getValue());
4864   }
4865 
4866   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
4867   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
4868   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
4869   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
4870   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
4871   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
4872   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
4873   Args.AddAllArgs(CmdArgs, options::OPT_y);
4874   Args.AddLastArg(CmdArgs, options::OPT_w);
4875   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
4876   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
4877   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
4878   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
4879   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
4880   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
4881   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
4882   Args.AddLastArg(CmdArgs, options::OPT_whyload);
4883   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
4884   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
4885   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
4886   Args.AddLastArg(CmdArgs, options::OPT_Mach);
4887 }
4888 
4889 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
4890                                 const InputInfo &Output,
4891                                 const InputInfoList &Inputs,
4892                                 const ArgList &Args,
4893                                 const char *LinkingOutput) const {
4894   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
4895 
4896   // The logic here is derived from gcc's behavior; most of which
4897   // comes from specs (starting with link_command). Consult gcc for
4898   // more information.
4899   ArgStringList CmdArgs;
4900 
4901   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
4902   if (Args.hasArg(options::OPT_ccc_arcmt_check,
4903                   options::OPT_ccc_arcmt_migrate)) {
4904     for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
4905       (*I)->claim();
4906     const char *Exec =
4907       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
4908     CmdArgs.push_back(Output.getFilename());
4909     C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4910     return;
4911   }
4912 
4913   // I'm not sure why this particular decomposition exists in gcc, but
4914   // we follow suite for ease of comparison.
4915   AddLinkArgs(C, Args, CmdArgs, Inputs);
4916 
4917   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
4918   Args.AddAllArgs(CmdArgs, options::OPT_s);
4919   Args.AddAllArgs(CmdArgs, options::OPT_t);
4920   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
4921   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4922   Args.AddLastArg(CmdArgs, options::OPT_e);
4923   Args.AddAllArgs(CmdArgs, options::OPT_r);
4924 
4925   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
4926   // members of static archive libraries which implement Objective-C classes or
4927   // categories.
4928   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
4929     CmdArgs.push_back("-ObjC");
4930 
4931   CmdArgs.push_back("-o");
4932   CmdArgs.push_back(Output.getFilename());
4933 
4934   if (!Args.hasArg(options::OPT_nostdlib) &&
4935       !Args.hasArg(options::OPT_nostartfiles)) {
4936     // Derived from startfile spec.
4937     if (Args.hasArg(options::OPT_dynamiclib)) {
4938       // Derived from darwin_dylib1 spec.
4939       if (getDarwinToolChain().isTargetIOSSimulator()) {
4940         // The simulator doesn't have a versioned crt1 file.
4941         CmdArgs.push_back("-ldylib1.o");
4942       } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4943         if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4944           CmdArgs.push_back("-ldylib1.o");
4945       } else {
4946         if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4947           CmdArgs.push_back("-ldylib1.o");
4948         else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4949           CmdArgs.push_back("-ldylib1.10.5.o");
4950       }
4951     } else {
4952       if (Args.hasArg(options::OPT_bundle)) {
4953         if (!Args.hasArg(options::OPT_static)) {
4954           // Derived from darwin_bundle1 spec.
4955           if (getDarwinToolChain().isTargetIOSSimulator()) {
4956             // The simulator doesn't have a versioned crt1 file.
4957             CmdArgs.push_back("-lbundle1.o");
4958           } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4959             if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4960               CmdArgs.push_back("-lbundle1.o");
4961           } else {
4962             if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4963               CmdArgs.push_back("-lbundle1.o");
4964           }
4965         }
4966       } else {
4967         if (Args.hasArg(options::OPT_pg) &&
4968             getToolChain().SupportsProfiling()) {
4969           if (Args.hasArg(options::OPT_static) ||
4970               Args.hasArg(options::OPT_object) ||
4971               Args.hasArg(options::OPT_preload)) {
4972             CmdArgs.push_back("-lgcrt0.o");
4973           } else {
4974             CmdArgs.push_back("-lgcrt1.o");
4975 
4976             // darwin_crt2 spec is empty.
4977           }
4978           // By default on OS X 10.8 and later, we don't link with a crt1.o
4979           // file and the linker knows to use _main as the entry point.  But,
4980           // when compiling with -pg, we need to link with the gcrt1.o file,
4981           // so pass the -no_new_main option to tell the linker to use the
4982           // "start" symbol as the entry point.
4983           if (getDarwinToolChain().isTargetMacOS() &&
4984               !getDarwinToolChain().isMacosxVersionLT(10, 8))
4985             CmdArgs.push_back("-no_new_main");
4986         } else {
4987           if (Args.hasArg(options::OPT_static) ||
4988               Args.hasArg(options::OPT_object) ||
4989               Args.hasArg(options::OPT_preload)) {
4990             CmdArgs.push_back("-lcrt0.o");
4991           } else {
4992             // Derived from darwin_crt1 spec.
4993             if (getDarwinToolChain().isTargetIOSSimulator()) {
4994               // The simulator doesn't have a versioned crt1 file.
4995               CmdArgs.push_back("-lcrt1.o");
4996             } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4997               if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4998                 CmdArgs.push_back("-lcrt1.o");
4999               else if (getDarwinToolChain().isIPhoneOSVersionLT(6, 0))
5000                 CmdArgs.push_back("-lcrt1.3.1.o");
5001             } else {
5002               if (getDarwinToolChain().isMacosxVersionLT(10, 5))
5003                 CmdArgs.push_back("-lcrt1.o");
5004               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
5005                 CmdArgs.push_back("-lcrt1.10.5.o");
5006               else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
5007                 CmdArgs.push_back("-lcrt1.10.6.o");
5008 
5009               // darwin_crt2 spec is empty.
5010             }
5011           }
5012         }
5013       }
5014     }
5015 
5016     if (!getDarwinToolChain().isTargetIPhoneOS() &&
5017         Args.hasArg(options::OPT_shared_libgcc) &&
5018         getDarwinToolChain().isMacosxVersionLT(10, 5)) {
5019       const char *Str =
5020         Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
5021       CmdArgs.push_back(Str);
5022     }
5023   }
5024 
5025   Args.AddAllArgs(CmdArgs, options::OPT_L);
5026 
5027   if (Args.hasArg(options::OPT_fopenmp))
5028     // This is more complicated in gcc...
5029     CmdArgs.push_back("-lgomp");
5030 
5031   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5032 
5033   if (isObjCRuntimeLinked(Args) &&
5034       !Args.hasArg(options::OPT_nostdlib) &&
5035       !Args.hasArg(options::OPT_nodefaultlibs)) {
5036     // Avoid linking compatibility stubs on i386 mac.
5037     if (!getDarwinToolChain().isTargetMacOS() ||
5038         getDarwinToolChain().getArch() != llvm::Triple::x86) {
5039       // If we don't have ARC or subscripting runtime support, link in the
5040       // runtime stubs.  We have to do this *before* adding any of the normal
5041       // linker inputs so that its initializer gets run first.
5042       ObjCRuntime runtime =
5043         getDarwinToolChain().getDefaultObjCRuntime(/*nonfragile*/ true);
5044       // We use arclite library for both ARC and subscripting support.
5045       if ((!runtime.hasNativeARC() && isObjCAutoRefCount(Args)) ||
5046           !runtime.hasSubscripting())
5047         getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
5048     }
5049     CmdArgs.push_back("-framework");
5050     CmdArgs.push_back("Foundation");
5051     // Link libobj.
5052     CmdArgs.push_back("-lobjc");
5053   }
5054 
5055   if (LinkingOutput) {
5056     CmdArgs.push_back("-arch_multiple");
5057     CmdArgs.push_back("-final_output");
5058     CmdArgs.push_back(LinkingOutput);
5059   }
5060 
5061   if (Args.hasArg(options::OPT_fnested_functions))
5062     CmdArgs.push_back("-allow_stack_execute");
5063 
5064   if (!Args.hasArg(options::OPT_nostdlib) &&
5065       !Args.hasArg(options::OPT_nodefaultlibs)) {
5066     if (getToolChain().getDriver().CCCIsCXX())
5067       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5068 
5069     // link_ssp spec is empty.
5070 
5071     // Let the tool chain choose which runtime library to link.
5072     getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
5073   }
5074 
5075   if (!Args.hasArg(options::OPT_nostdlib) &&
5076       !Args.hasArg(options::OPT_nostartfiles)) {
5077     // endfile_spec is empty.
5078   }
5079 
5080   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5081   Args.AddAllArgs(CmdArgs, options::OPT_F);
5082 
5083   const char *Exec =
5084     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5085   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5086 }
5087 
5088 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
5089                                 const InputInfo &Output,
5090                                 const InputInfoList &Inputs,
5091                                 const ArgList &Args,
5092                                 const char *LinkingOutput) const {
5093   ArgStringList CmdArgs;
5094 
5095   CmdArgs.push_back("-create");
5096   assert(Output.isFilename() && "Unexpected lipo output.");
5097 
5098   CmdArgs.push_back("-output");
5099   CmdArgs.push_back(Output.getFilename());
5100 
5101   for (InputInfoList::const_iterator
5102          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5103     const InputInfo &II = *it;
5104     assert(II.isFilename() && "Unexpected lipo input.");
5105     CmdArgs.push_back(II.getFilename());
5106   }
5107   const char *Exec =
5108     Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
5109   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5110 }
5111 
5112 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
5113                                     const InputInfo &Output,
5114                                     const InputInfoList &Inputs,
5115                                     const ArgList &Args,
5116                                     const char *LinkingOutput) const {
5117   ArgStringList CmdArgs;
5118 
5119   CmdArgs.push_back("-o");
5120   CmdArgs.push_back(Output.getFilename());
5121 
5122   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5123   const InputInfo &Input = Inputs[0];
5124   assert(Input.isFilename() && "Unexpected dsymutil input.");
5125   CmdArgs.push_back(Input.getFilename());
5126 
5127   const char *Exec =
5128     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
5129   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5130 }
5131 
5132 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
5133                                        const InputInfo &Output,
5134                                        const InputInfoList &Inputs,
5135                                        const ArgList &Args,
5136                                        const char *LinkingOutput) const {
5137   ArgStringList CmdArgs;
5138   CmdArgs.push_back("--verify");
5139   CmdArgs.push_back("--debug-info");
5140   CmdArgs.push_back("--eh-frame");
5141   CmdArgs.push_back("--quiet");
5142 
5143   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5144   const InputInfo &Input = Inputs[0];
5145   assert(Input.isFilename() && "Unexpected verify input");
5146 
5147   // Grabbing the output of the earlier dsymutil run.
5148   CmdArgs.push_back(Input.getFilename());
5149 
5150   const char *Exec =
5151     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
5152   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5153 }
5154 
5155 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5156                                       const InputInfo &Output,
5157                                       const InputInfoList &Inputs,
5158                                       const ArgList &Args,
5159                                       const char *LinkingOutput) const {
5160   ArgStringList CmdArgs;
5161 
5162   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5163                        options::OPT_Xassembler);
5164 
5165   CmdArgs.push_back("-o");
5166   CmdArgs.push_back(Output.getFilename());
5167 
5168   for (InputInfoList::const_iterator
5169          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5170     const InputInfo &II = *it;
5171     CmdArgs.push_back(II.getFilename());
5172   }
5173 
5174   const char *Exec =
5175     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5176   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5177 }
5178 
5179 
5180 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
5181                                   const InputInfo &Output,
5182                                   const InputInfoList &Inputs,
5183                                   const ArgList &Args,
5184                                   const char *LinkingOutput) const {
5185   // FIXME: Find a real GCC, don't hard-code versions here
5186   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
5187   const llvm::Triple &T = getToolChain().getTriple();
5188   std::string LibPath = "/usr/lib/";
5189   llvm::Triple::ArchType Arch = T.getArch();
5190   switch (Arch) {
5191   case llvm::Triple::x86:
5192     GCCLibPath +=
5193         ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
5194     break;
5195   case llvm::Triple::x86_64:
5196     GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
5197     GCCLibPath += "/4.5.2/amd64/";
5198     LibPath += "amd64/";
5199     break;
5200   default:
5201     llvm_unreachable("Unsupported architecture");
5202   }
5203 
5204   ArgStringList CmdArgs;
5205 
5206   // Demangle C++ names in errors
5207   CmdArgs.push_back("-C");
5208 
5209   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5210       (!Args.hasArg(options::OPT_shared))) {
5211     CmdArgs.push_back("-e");
5212     CmdArgs.push_back("_start");
5213   }
5214 
5215   if (Args.hasArg(options::OPT_static)) {
5216     CmdArgs.push_back("-Bstatic");
5217     CmdArgs.push_back("-dn");
5218   } else {
5219     CmdArgs.push_back("-Bdynamic");
5220     if (Args.hasArg(options::OPT_shared)) {
5221       CmdArgs.push_back("-shared");
5222     } else {
5223       CmdArgs.push_back("--dynamic-linker");
5224       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
5225     }
5226   }
5227 
5228   if (Output.isFilename()) {
5229     CmdArgs.push_back("-o");
5230     CmdArgs.push_back(Output.getFilename());
5231   } else {
5232     assert(Output.isNothing() && "Invalid output.");
5233   }
5234 
5235   if (!Args.hasArg(options::OPT_nostdlib) &&
5236       !Args.hasArg(options::OPT_nostartfiles)) {
5237     if (!Args.hasArg(options::OPT_shared)) {
5238       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
5239       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5240       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5241       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5242     } else {
5243       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5244       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5245       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5246     }
5247     if (getToolChain().getDriver().CCCIsCXX())
5248       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
5249   }
5250 
5251   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
5252 
5253   Args.AddAllArgs(CmdArgs, options::OPT_L);
5254   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5255   Args.AddAllArgs(CmdArgs, options::OPT_e);
5256   Args.AddAllArgs(CmdArgs, options::OPT_r);
5257 
5258   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5259 
5260   if (!Args.hasArg(options::OPT_nostdlib) &&
5261       !Args.hasArg(options::OPT_nodefaultlibs)) {
5262     if (getToolChain().getDriver().CCCIsCXX())
5263       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5264     CmdArgs.push_back("-lgcc_s");
5265     if (!Args.hasArg(options::OPT_shared)) {
5266       CmdArgs.push_back("-lgcc");
5267       CmdArgs.push_back("-lc");
5268       CmdArgs.push_back("-lm");
5269     }
5270   }
5271 
5272   if (!Args.hasArg(options::OPT_nostdlib) &&
5273       !Args.hasArg(options::OPT_nostartfiles)) {
5274     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
5275   }
5276   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
5277 
5278   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5279 
5280   const char *Exec =
5281     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5282   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5283 }
5284 
5285 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5286                                       const InputInfo &Output,
5287                                       const InputInfoList &Inputs,
5288                                       const ArgList &Args,
5289                                       const char *LinkingOutput) const {
5290   ArgStringList CmdArgs;
5291 
5292   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5293                        options::OPT_Xassembler);
5294 
5295   CmdArgs.push_back("-o");
5296   CmdArgs.push_back(Output.getFilename());
5297 
5298   for (InputInfoList::const_iterator
5299          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5300     const InputInfo &II = *it;
5301     CmdArgs.push_back(II.getFilename());
5302   }
5303 
5304   const char *Exec =
5305     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
5306   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5307 }
5308 
5309 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
5310                                   const InputInfo &Output,
5311                                   const InputInfoList &Inputs,
5312                                   const ArgList &Args,
5313                                   const char *LinkingOutput) const {
5314   ArgStringList CmdArgs;
5315 
5316   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5317       (!Args.hasArg(options::OPT_shared))) {
5318     CmdArgs.push_back("-e");
5319     CmdArgs.push_back("_start");
5320   }
5321 
5322   if (Args.hasArg(options::OPT_static)) {
5323     CmdArgs.push_back("-Bstatic");
5324     CmdArgs.push_back("-dn");
5325   } else {
5326 //    CmdArgs.push_back("--eh-frame-hdr");
5327     CmdArgs.push_back("-Bdynamic");
5328     if (Args.hasArg(options::OPT_shared)) {
5329       CmdArgs.push_back("-shared");
5330     } else {
5331       CmdArgs.push_back("--dynamic-linker");
5332       CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
5333     }
5334   }
5335 
5336   if (Output.isFilename()) {
5337     CmdArgs.push_back("-o");
5338     CmdArgs.push_back(Output.getFilename());
5339   } else {
5340     assert(Output.isNothing() && "Invalid output.");
5341   }
5342 
5343   if (!Args.hasArg(options::OPT_nostdlib) &&
5344       !Args.hasArg(options::OPT_nostartfiles)) {
5345     if (!Args.hasArg(options::OPT_shared)) {
5346       CmdArgs.push_back(Args.MakeArgString(
5347                                 getToolChain().GetFilePath("crt1.o")));
5348       CmdArgs.push_back(Args.MakeArgString(
5349                                 getToolChain().GetFilePath("crti.o")));
5350       CmdArgs.push_back(Args.MakeArgString(
5351                                 getToolChain().GetFilePath("crtbegin.o")));
5352     } else {
5353       CmdArgs.push_back(Args.MakeArgString(
5354                                 getToolChain().GetFilePath("crti.o")));
5355     }
5356     CmdArgs.push_back(Args.MakeArgString(
5357                                 getToolChain().GetFilePath("crtn.o")));
5358   }
5359 
5360   CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
5361                                        + getToolChain().getTripleString()
5362                                        + "/4.2.4"));
5363 
5364   Args.AddAllArgs(CmdArgs, options::OPT_L);
5365   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5366   Args.AddAllArgs(CmdArgs, options::OPT_e);
5367 
5368   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5369 
5370   if (!Args.hasArg(options::OPT_nostdlib) &&
5371       !Args.hasArg(options::OPT_nodefaultlibs)) {
5372     // FIXME: For some reason GCC passes -lgcc before adding
5373     // the default system libraries. Just mimic this for now.
5374     CmdArgs.push_back("-lgcc");
5375 
5376     if (Args.hasArg(options::OPT_pthread))
5377       CmdArgs.push_back("-pthread");
5378     if (!Args.hasArg(options::OPT_shared))
5379       CmdArgs.push_back("-lc");
5380     CmdArgs.push_back("-lgcc");
5381   }
5382 
5383   if (!Args.hasArg(options::OPT_nostdlib) &&
5384       !Args.hasArg(options::OPT_nostartfiles)) {
5385     if (!Args.hasArg(options::OPT_shared))
5386       CmdArgs.push_back(Args.MakeArgString(
5387                                 getToolChain().GetFilePath("crtend.o")));
5388   }
5389 
5390   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5391 
5392   const char *Exec =
5393     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5394   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5395 }
5396 
5397 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5398                                      const InputInfo &Output,
5399                                      const InputInfoList &Inputs,
5400                                      const ArgList &Args,
5401                                      const char *LinkingOutput) const {
5402   ArgStringList CmdArgs;
5403 
5404   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5405                        options::OPT_Xassembler);
5406 
5407   CmdArgs.push_back("-o");
5408   CmdArgs.push_back(Output.getFilename());
5409 
5410   for (InputInfoList::const_iterator
5411          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5412     const InputInfo &II = *it;
5413     CmdArgs.push_back(II.getFilename());
5414   }
5415 
5416   const char *Exec =
5417     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5418   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5419 }
5420 
5421 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5422                                  const InputInfo &Output,
5423                                  const InputInfoList &Inputs,
5424                                  const ArgList &Args,
5425                                  const char *LinkingOutput) const {
5426   const Driver &D = getToolChain().getDriver();
5427   ArgStringList CmdArgs;
5428 
5429   // Silence warning for "clang -g foo.o -o foo"
5430   Args.ClaimAllArgs(options::OPT_g_Group);
5431   // and "clang -emit-llvm foo.o -o foo"
5432   Args.ClaimAllArgs(options::OPT_emit_llvm);
5433   // and for "clang -w foo.o -o foo". Other warning options are already
5434   // handled somewhere else.
5435   Args.ClaimAllArgs(options::OPT_w);
5436 
5437   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5438       (!Args.hasArg(options::OPT_shared))) {
5439     CmdArgs.push_back("-e");
5440     CmdArgs.push_back("__start");
5441   }
5442 
5443   if (Args.hasArg(options::OPT_static)) {
5444     CmdArgs.push_back("-Bstatic");
5445   } else {
5446     if (Args.hasArg(options::OPT_rdynamic))
5447       CmdArgs.push_back("-export-dynamic");
5448     CmdArgs.push_back("--eh-frame-hdr");
5449     CmdArgs.push_back("-Bdynamic");
5450     if (Args.hasArg(options::OPT_shared)) {
5451       CmdArgs.push_back("-shared");
5452     } else {
5453       CmdArgs.push_back("-dynamic-linker");
5454       CmdArgs.push_back("/usr/libexec/ld.so");
5455     }
5456   }
5457 
5458   if (Args.hasArg(options::OPT_nopie))
5459     CmdArgs.push_back("-nopie");
5460 
5461   if (Output.isFilename()) {
5462     CmdArgs.push_back("-o");
5463     CmdArgs.push_back(Output.getFilename());
5464   } else {
5465     assert(Output.isNothing() && "Invalid output.");
5466   }
5467 
5468   if (!Args.hasArg(options::OPT_nostdlib) &&
5469       !Args.hasArg(options::OPT_nostartfiles)) {
5470     if (!Args.hasArg(options::OPT_shared)) {
5471       if (Args.hasArg(options::OPT_pg))
5472         CmdArgs.push_back(Args.MakeArgString(
5473                                 getToolChain().GetFilePath("gcrt0.o")));
5474       else
5475         CmdArgs.push_back(Args.MakeArgString(
5476                                 getToolChain().GetFilePath("crt0.o")));
5477       CmdArgs.push_back(Args.MakeArgString(
5478                               getToolChain().GetFilePath("crtbegin.o")));
5479     } else {
5480       CmdArgs.push_back(Args.MakeArgString(
5481                               getToolChain().GetFilePath("crtbeginS.o")));
5482     }
5483   }
5484 
5485   std::string Triple = getToolChain().getTripleString();
5486   if (Triple.substr(0, 6) == "x86_64")
5487     Triple.replace(0, 6, "amd64");
5488   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
5489                                        "/4.2.1"));
5490 
5491   Args.AddAllArgs(CmdArgs, options::OPT_L);
5492   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5493   Args.AddAllArgs(CmdArgs, options::OPT_e);
5494   Args.AddAllArgs(CmdArgs, options::OPT_s);
5495   Args.AddAllArgs(CmdArgs, options::OPT_t);
5496   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5497   Args.AddAllArgs(CmdArgs, options::OPT_r);
5498 
5499   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5500 
5501   if (!Args.hasArg(options::OPT_nostdlib) &&
5502       !Args.hasArg(options::OPT_nodefaultlibs)) {
5503     if (D.CCCIsCXX()) {
5504       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5505       if (Args.hasArg(options::OPT_pg))
5506         CmdArgs.push_back("-lm_p");
5507       else
5508         CmdArgs.push_back("-lm");
5509     }
5510 
5511     // FIXME: For some reason GCC passes -lgcc before adding
5512     // the default system libraries. Just mimic this for now.
5513     CmdArgs.push_back("-lgcc");
5514 
5515     if (Args.hasArg(options::OPT_pthread)) {
5516       if (!Args.hasArg(options::OPT_shared) &&
5517           Args.hasArg(options::OPT_pg))
5518          CmdArgs.push_back("-lpthread_p");
5519       else
5520          CmdArgs.push_back("-lpthread");
5521     }
5522 
5523     if (!Args.hasArg(options::OPT_shared)) {
5524       if (Args.hasArg(options::OPT_pg))
5525          CmdArgs.push_back("-lc_p");
5526       else
5527          CmdArgs.push_back("-lc");
5528     }
5529 
5530     CmdArgs.push_back("-lgcc");
5531   }
5532 
5533   if (!Args.hasArg(options::OPT_nostdlib) &&
5534       !Args.hasArg(options::OPT_nostartfiles)) {
5535     if (!Args.hasArg(options::OPT_shared))
5536       CmdArgs.push_back(Args.MakeArgString(
5537                               getToolChain().GetFilePath("crtend.o")));
5538     else
5539       CmdArgs.push_back(Args.MakeArgString(
5540                               getToolChain().GetFilePath("crtendS.o")));
5541   }
5542 
5543   const char *Exec =
5544     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5545   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5546 }
5547 
5548 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5549                                     const InputInfo &Output,
5550                                     const InputInfoList &Inputs,
5551                                     const ArgList &Args,
5552                                     const char *LinkingOutput) const {
5553   ArgStringList CmdArgs;
5554 
5555   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5556                        options::OPT_Xassembler);
5557 
5558   CmdArgs.push_back("-o");
5559   CmdArgs.push_back(Output.getFilename());
5560 
5561   for (InputInfoList::const_iterator
5562          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5563     const InputInfo &II = *it;
5564     CmdArgs.push_back(II.getFilename());
5565   }
5566 
5567   const char *Exec =
5568     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5569   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5570 }
5571 
5572 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
5573                                 const InputInfo &Output,
5574                                 const InputInfoList &Inputs,
5575                                 const ArgList &Args,
5576                                 const char *LinkingOutput) const {
5577   const Driver &D = getToolChain().getDriver();
5578   ArgStringList CmdArgs;
5579 
5580   if ((!Args.hasArg(options::OPT_nostdlib)) &&
5581       (!Args.hasArg(options::OPT_shared))) {
5582     CmdArgs.push_back("-e");
5583     CmdArgs.push_back("__start");
5584   }
5585 
5586   if (Args.hasArg(options::OPT_static)) {
5587     CmdArgs.push_back("-Bstatic");
5588   } else {
5589     if (Args.hasArg(options::OPT_rdynamic))
5590       CmdArgs.push_back("-export-dynamic");
5591     CmdArgs.push_back("--eh-frame-hdr");
5592     CmdArgs.push_back("-Bdynamic");
5593     if (Args.hasArg(options::OPT_shared)) {
5594       CmdArgs.push_back("-shared");
5595     } else {
5596       CmdArgs.push_back("-dynamic-linker");
5597       CmdArgs.push_back("/usr/libexec/ld.so");
5598     }
5599   }
5600 
5601   if (Output.isFilename()) {
5602     CmdArgs.push_back("-o");
5603     CmdArgs.push_back(Output.getFilename());
5604   } else {
5605     assert(Output.isNothing() && "Invalid output.");
5606   }
5607 
5608   if (!Args.hasArg(options::OPT_nostdlib) &&
5609       !Args.hasArg(options::OPT_nostartfiles)) {
5610     if (!Args.hasArg(options::OPT_shared)) {
5611       if (Args.hasArg(options::OPT_pg))
5612         CmdArgs.push_back(Args.MakeArgString(
5613                                 getToolChain().GetFilePath("gcrt0.o")));
5614       else
5615         CmdArgs.push_back(Args.MakeArgString(
5616                                 getToolChain().GetFilePath("crt0.o")));
5617       CmdArgs.push_back(Args.MakeArgString(
5618                               getToolChain().GetFilePath("crtbegin.o")));
5619     } else {
5620       CmdArgs.push_back(Args.MakeArgString(
5621                               getToolChain().GetFilePath("crtbeginS.o")));
5622     }
5623   }
5624 
5625   Args.AddAllArgs(CmdArgs, options::OPT_L);
5626   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5627   Args.AddAllArgs(CmdArgs, options::OPT_e);
5628 
5629   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5630 
5631   if (!Args.hasArg(options::OPT_nostdlib) &&
5632       !Args.hasArg(options::OPT_nodefaultlibs)) {
5633     if (D.CCCIsCXX()) {
5634       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5635       if (Args.hasArg(options::OPT_pg))
5636         CmdArgs.push_back("-lm_p");
5637       else
5638         CmdArgs.push_back("-lm");
5639     }
5640 
5641     if (Args.hasArg(options::OPT_pthread)) {
5642       if (!Args.hasArg(options::OPT_shared) &&
5643           Args.hasArg(options::OPT_pg))
5644         CmdArgs.push_back("-lpthread_p");
5645       else
5646         CmdArgs.push_back("-lpthread");
5647     }
5648 
5649     if (!Args.hasArg(options::OPT_shared)) {
5650       if (Args.hasArg(options::OPT_pg))
5651         CmdArgs.push_back("-lc_p");
5652       else
5653         CmdArgs.push_back("-lc");
5654     }
5655 
5656     StringRef MyArch;
5657     switch (getToolChain().getTriple().getArch()) {
5658     case llvm::Triple::arm:
5659       MyArch = "arm";
5660       break;
5661     case llvm::Triple::x86:
5662       MyArch = "i386";
5663       break;
5664     case llvm::Triple::x86_64:
5665       MyArch = "amd64";
5666       break;
5667     default:
5668       llvm_unreachable("Unsupported architecture");
5669     }
5670     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
5671   }
5672 
5673   if (!Args.hasArg(options::OPT_nostdlib) &&
5674       !Args.hasArg(options::OPT_nostartfiles)) {
5675     if (!Args.hasArg(options::OPT_shared))
5676       CmdArgs.push_back(Args.MakeArgString(
5677                               getToolChain().GetFilePath("crtend.o")));
5678     else
5679       CmdArgs.push_back(Args.MakeArgString(
5680                               getToolChain().GetFilePath("crtendS.o")));
5681   }
5682 
5683   const char *Exec =
5684     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5685   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5686 }
5687 
5688 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5689                                      const InputInfo &Output,
5690                                      const InputInfoList &Inputs,
5691                                      const ArgList &Args,
5692                                      const char *LinkingOutput) const {
5693   ArgStringList CmdArgs;
5694 
5695   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5696   // instruct as in the base system to assemble 32-bit code.
5697   if (getToolChain().getArch() == llvm::Triple::x86)
5698     CmdArgs.push_back("--32");
5699   else if (getToolChain().getArch() == llvm::Triple::ppc)
5700     CmdArgs.push_back("-a32");
5701   else if (getToolChain().getArch() == llvm::Triple::mips ||
5702            getToolChain().getArch() == llvm::Triple::mipsel ||
5703            getToolChain().getArch() == llvm::Triple::mips64 ||
5704            getToolChain().getArch() == llvm::Triple::mips64el) {
5705     StringRef CPUName;
5706     StringRef ABIName;
5707     getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
5708 
5709     CmdArgs.push_back("-march");
5710     CmdArgs.push_back(CPUName.data());
5711 
5712     CmdArgs.push_back("-mabi");
5713     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
5714 
5715     if (getToolChain().getArch() == llvm::Triple::mips ||
5716         getToolChain().getArch() == llvm::Triple::mips64)
5717       CmdArgs.push_back("-EB");
5718     else
5719       CmdArgs.push_back("-EL");
5720 
5721     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5722                                       options::OPT_fpic, options::OPT_fno_pic,
5723                                       options::OPT_fPIE, options::OPT_fno_PIE,
5724                                       options::OPT_fpie, options::OPT_fno_pie);
5725     if (LastPICArg &&
5726         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5727          LastPICArg->getOption().matches(options::OPT_fpic) ||
5728          LastPICArg->getOption().matches(options::OPT_fPIE) ||
5729          LastPICArg->getOption().matches(options::OPT_fpie))) {
5730       CmdArgs.push_back("-KPIC");
5731     }
5732   } else if (getToolChain().getArch() == llvm::Triple::arm ||
5733              getToolChain().getArch() == llvm::Triple::thumb) {
5734     CmdArgs.push_back("-mfpu=softvfp");
5735     switch(getToolChain().getTriple().getEnvironment()) {
5736     case llvm::Triple::GNUEABI:
5737     case llvm::Triple::EABI:
5738       CmdArgs.push_back("-meabi=5");
5739       break;
5740 
5741     default:
5742       CmdArgs.push_back("-matpcs");
5743     }
5744   }
5745 
5746   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5747                        options::OPT_Xassembler);
5748 
5749   CmdArgs.push_back("-o");
5750   CmdArgs.push_back(Output.getFilename());
5751 
5752   for (InputInfoList::const_iterator
5753          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5754     const InputInfo &II = *it;
5755     CmdArgs.push_back(II.getFilename());
5756   }
5757 
5758   const char *Exec =
5759     Args.MakeArgString(getToolChain().GetProgramPath("as"));
5760   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5761 }
5762 
5763 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5764                                  const InputInfo &Output,
5765                                  const InputInfoList &Inputs,
5766                                  const ArgList &Args,
5767                                  const char *LinkingOutput) const {
5768   const toolchains::FreeBSD& ToolChain =
5769     static_cast<const toolchains::FreeBSD&>(getToolChain());
5770   const Driver &D = ToolChain.getDriver();
5771   ArgStringList CmdArgs;
5772 
5773   // Silence warning for "clang -g foo.o -o foo"
5774   Args.ClaimAllArgs(options::OPT_g_Group);
5775   // and "clang -emit-llvm foo.o -o foo"
5776   Args.ClaimAllArgs(options::OPT_emit_llvm);
5777   // and for "clang -w foo.o -o foo". Other warning options are already
5778   // handled somewhere else.
5779   Args.ClaimAllArgs(options::OPT_w);
5780 
5781   if (!D.SysRoot.empty())
5782     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5783 
5784   if (Args.hasArg(options::OPT_pie))
5785     CmdArgs.push_back("-pie");
5786 
5787   if (Args.hasArg(options::OPT_static)) {
5788     CmdArgs.push_back("-Bstatic");
5789   } else {
5790     if (Args.hasArg(options::OPT_rdynamic))
5791       CmdArgs.push_back("-export-dynamic");
5792     CmdArgs.push_back("--eh-frame-hdr");
5793     if (Args.hasArg(options::OPT_shared)) {
5794       CmdArgs.push_back("-Bshareable");
5795     } else {
5796       CmdArgs.push_back("-dynamic-linker");
5797       CmdArgs.push_back("/libexec/ld-elf.so.1");
5798     }
5799     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
5800       llvm::Triple::ArchType Arch = ToolChain.getArch();
5801       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
5802           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5803         CmdArgs.push_back("--hash-style=both");
5804       }
5805     }
5806     CmdArgs.push_back("--enable-new-dtags");
5807   }
5808 
5809   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5810   // instruct ld in the base system to link 32-bit code.
5811   if (ToolChain.getArch() == llvm::Triple::x86) {
5812     CmdArgs.push_back("-m");
5813     CmdArgs.push_back("elf_i386_fbsd");
5814   }
5815 
5816   if (ToolChain.getArch() == llvm::Triple::ppc) {
5817     CmdArgs.push_back("-m");
5818     CmdArgs.push_back("elf32ppc_fbsd");
5819   }
5820 
5821   if (Output.isFilename()) {
5822     CmdArgs.push_back("-o");
5823     CmdArgs.push_back(Output.getFilename());
5824   } else {
5825     assert(Output.isNothing() && "Invalid output.");
5826   }
5827 
5828   if (!Args.hasArg(options::OPT_nostdlib) &&
5829       !Args.hasArg(options::OPT_nostartfiles)) {
5830     const char *crt1 = NULL;
5831     if (!Args.hasArg(options::OPT_shared)) {
5832       if (Args.hasArg(options::OPT_pg))
5833         crt1 = "gcrt1.o";
5834       else if (Args.hasArg(options::OPT_pie))
5835         crt1 = "Scrt1.o";
5836       else
5837         crt1 = "crt1.o";
5838     }
5839     if (crt1)
5840       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5841 
5842     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5843 
5844     const char *crtbegin = NULL;
5845     if (Args.hasArg(options::OPT_static))
5846       crtbegin = "crtbeginT.o";
5847     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5848       crtbegin = "crtbeginS.o";
5849     else
5850       crtbegin = "crtbegin.o";
5851 
5852     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5853   }
5854 
5855   Args.AddAllArgs(CmdArgs, options::OPT_L);
5856   const ToolChain::path_list Paths = ToolChain.getFilePaths();
5857   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5858        i != e; ++i)
5859     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5860   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5861   Args.AddAllArgs(CmdArgs, options::OPT_e);
5862   Args.AddAllArgs(CmdArgs, options::OPT_s);
5863   Args.AddAllArgs(CmdArgs, options::OPT_t);
5864   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5865   Args.AddAllArgs(CmdArgs, options::OPT_r);
5866 
5867   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
5868   // as gold requires -plugin to come before any -plugin-opt that -Wl might
5869   // forward.
5870   if (D.IsUsingLTO(Args)) {
5871     CmdArgs.push_back("-plugin");
5872     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
5873     CmdArgs.push_back(Args.MakeArgString(Plugin));
5874 
5875     // Try to pass driver level flags relevant to LTO code generation down to
5876     // the plugin.
5877 
5878     // Handle flags for selecting CPU variants.
5879     std::string CPU = getCPUName(Args, ToolChain.getTriple());
5880     if (!CPU.empty()) {
5881       CmdArgs.push_back(
5882                         Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
5883                                            CPU));
5884     }
5885   }
5886 
5887   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5888 
5889   if (!Args.hasArg(options::OPT_nostdlib) &&
5890       !Args.hasArg(options::OPT_nodefaultlibs)) {
5891     if (D.CCCIsCXX()) {
5892       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5893       if (Args.hasArg(options::OPT_pg))
5894         CmdArgs.push_back("-lm_p");
5895       else
5896         CmdArgs.push_back("-lm");
5897     }
5898     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5899     // the default system libraries. Just mimic this for now.
5900     if (Args.hasArg(options::OPT_pg))
5901       CmdArgs.push_back("-lgcc_p");
5902     else
5903       CmdArgs.push_back("-lgcc");
5904     if (Args.hasArg(options::OPT_static)) {
5905       CmdArgs.push_back("-lgcc_eh");
5906     } else if (Args.hasArg(options::OPT_pg)) {
5907       CmdArgs.push_back("-lgcc_eh_p");
5908     } else {
5909       CmdArgs.push_back("--as-needed");
5910       CmdArgs.push_back("-lgcc_s");
5911       CmdArgs.push_back("--no-as-needed");
5912     }
5913 
5914     if (Args.hasArg(options::OPT_pthread)) {
5915       if (Args.hasArg(options::OPT_pg))
5916         CmdArgs.push_back("-lpthread_p");
5917       else
5918         CmdArgs.push_back("-lpthread");
5919     }
5920 
5921     if (Args.hasArg(options::OPT_pg)) {
5922       if (Args.hasArg(options::OPT_shared))
5923         CmdArgs.push_back("-lc");
5924       else
5925         CmdArgs.push_back("-lc_p");
5926       CmdArgs.push_back("-lgcc_p");
5927     } else {
5928       CmdArgs.push_back("-lc");
5929       CmdArgs.push_back("-lgcc");
5930     }
5931 
5932     if (Args.hasArg(options::OPT_static)) {
5933       CmdArgs.push_back("-lgcc_eh");
5934     } else if (Args.hasArg(options::OPT_pg)) {
5935       CmdArgs.push_back("-lgcc_eh_p");
5936     } else {
5937       CmdArgs.push_back("--as-needed");
5938       CmdArgs.push_back("-lgcc_s");
5939       CmdArgs.push_back("--no-as-needed");
5940     }
5941   }
5942 
5943   if (!Args.hasArg(options::OPT_nostdlib) &&
5944       !Args.hasArg(options::OPT_nostartfiles)) {
5945     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5946       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
5947     else
5948       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
5949     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
5950   }
5951 
5952   addProfileRT(ToolChain, Args, CmdArgs, ToolChain.getTriple());
5953 
5954   const char *Exec =
5955     Args.MakeArgString(ToolChain.GetProgramPath("ld"));
5956   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5957 }
5958 
5959 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5960                                      const InputInfo &Output,
5961                                      const InputInfoList &Inputs,
5962                                      const ArgList &Args,
5963                                      const char *LinkingOutput) const {
5964   ArgStringList CmdArgs;
5965 
5966   // When building 32-bit code on NetBSD/amd64, we have to explicitly
5967   // instruct as in the base system to assemble 32-bit code.
5968   if (getToolChain().getArch() == llvm::Triple::x86)
5969     CmdArgs.push_back("--32");
5970 
5971   // Set byte order explicitly
5972   if (getToolChain().getArch() == llvm::Triple::mips)
5973     CmdArgs.push_back("-EB");
5974   else if (getToolChain().getArch() == llvm::Triple::mipsel)
5975     CmdArgs.push_back("-EL");
5976 
5977   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5978                        options::OPT_Xassembler);
5979 
5980   CmdArgs.push_back("-o");
5981   CmdArgs.push_back(Output.getFilename());
5982 
5983   for (InputInfoList::const_iterator
5984          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5985     const InputInfo &II = *it;
5986     CmdArgs.push_back(II.getFilename());
5987   }
5988 
5989   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
5990   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5991 }
5992 
5993 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5994                                  const InputInfo &Output,
5995                                  const InputInfoList &Inputs,
5996                                  const ArgList &Args,
5997                                  const char *LinkingOutput) const {
5998   const Driver &D = getToolChain().getDriver();
5999   ArgStringList CmdArgs;
6000 
6001   if (!D.SysRoot.empty())
6002     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6003 
6004   if (Args.hasArg(options::OPT_static)) {
6005     CmdArgs.push_back("-Bstatic");
6006   } else {
6007     if (Args.hasArg(options::OPT_rdynamic))
6008       CmdArgs.push_back("-export-dynamic");
6009     CmdArgs.push_back("--eh-frame-hdr");
6010     if (Args.hasArg(options::OPT_shared)) {
6011       CmdArgs.push_back("-Bshareable");
6012     } else {
6013       CmdArgs.push_back("-dynamic-linker");
6014       CmdArgs.push_back("/libexec/ld.elf_so");
6015     }
6016   }
6017 
6018   // When building 32-bit code on NetBSD/amd64, we have to explicitly
6019   // instruct ld in the base system to link 32-bit code.
6020   if (getToolChain().getArch() == llvm::Triple::x86) {
6021     CmdArgs.push_back("-m");
6022     CmdArgs.push_back("elf_i386");
6023   }
6024 
6025   if (Output.isFilename()) {
6026     CmdArgs.push_back("-o");
6027     CmdArgs.push_back(Output.getFilename());
6028   } else {
6029     assert(Output.isNothing() && "Invalid output.");
6030   }
6031 
6032   if (!Args.hasArg(options::OPT_nostdlib) &&
6033       !Args.hasArg(options::OPT_nostartfiles)) {
6034     if (!Args.hasArg(options::OPT_shared)) {
6035       CmdArgs.push_back(Args.MakeArgString(
6036                               getToolChain().GetFilePath("crt0.o")));
6037       CmdArgs.push_back(Args.MakeArgString(
6038                               getToolChain().GetFilePath("crti.o")));
6039       CmdArgs.push_back(Args.MakeArgString(
6040                               getToolChain().GetFilePath("crtbegin.o")));
6041     } else {
6042       CmdArgs.push_back(Args.MakeArgString(
6043                               getToolChain().GetFilePath("crti.o")));
6044       CmdArgs.push_back(Args.MakeArgString(
6045                               getToolChain().GetFilePath("crtbeginS.o")));
6046     }
6047   }
6048 
6049   Args.AddAllArgs(CmdArgs, options::OPT_L);
6050   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6051   Args.AddAllArgs(CmdArgs, options::OPT_e);
6052   Args.AddAllArgs(CmdArgs, options::OPT_s);
6053   Args.AddAllArgs(CmdArgs, options::OPT_t);
6054   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6055   Args.AddAllArgs(CmdArgs, options::OPT_r);
6056 
6057   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6058 
6059   unsigned Major, Minor, Micro;
6060   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
6061   bool useLibgcc = true;
6062   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 23) || Major == 0) {
6063     if (getToolChain().getArch() == llvm::Triple::x86 ||
6064         getToolChain().getArch() == llvm::Triple::x86_64)
6065       useLibgcc = false;
6066   }
6067 
6068   if (!Args.hasArg(options::OPT_nostdlib) &&
6069       !Args.hasArg(options::OPT_nodefaultlibs)) {
6070     if (D.CCCIsCXX()) {
6071       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6072       CmdArgs.push_back("-lm");
6073     }
6074     if (Args.hasArg(options::OPT_pthread))
6075       CmdArgs.push_back("-lpthread");
6076     CmdArgs.push_back("-lc");
6077 
6078     if (useLibgcc) {
6079       if (Args.hasArg(options::OPT_static)) {
6080         // libgcc_eh depends on libc, so resolve as much as possible,
6081         // pull in any new requirements from libc and then get the rest
6082         // of libgcc.
6083         CmdArgs.push_back("-lgcc_eh");
6084         CmdArgs.push_back("-lc");
6085         CmdArgs.push_back("-lgcc");
6086       } else {
6087         CmdArgs.push_back("-lgcc");
6088         CmdArgs.push_back("--as-needed");
6089         CmdArgs.push_back("-lgcc_s");
6090         CmdArgs.push_back("--no-as-needed");
6091       }
6092     }
6093   }
6094 
6095   if (!Args.hasArg(options::OPT_nostdlib) &&
6096       !Args.hasArg(options::OPT_nostartfiles)) {
6097     if (!Args.hasArg(options::OPT_shared))
6098       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6099                                                                   "crtend.o")));
6100     else
6101       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6102                                                                  "crtendS.o")));
6103     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6104                                                                     "crtn.o")));
6105   }
6106 
6107   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6108 
6109   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6110   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6111 }
6112 
6113 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6114                                       const InputInfo &Output,
6115                                       const InputInfoList &Inputs,
6116                                       const ArgList &Args,
6117                                       const char *LinkingOutput) const {
6118   ArgStringList CmdArgs;
6119 
6120   // Add --32/--64 to make sure we get the format we want.
6121   // This is incomplete
6122   if (getToolChain().getArch() == llvm::Triple::x86) {
6123     CmdArgs.push_back("--32");
6124   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
6125     CmdArgs.push_back("--64");
6126   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
6127     CmdArgs.push_back("-a32");
6128     CmdArgs.push_back("-mppc");
6129     CmdArgs.push_back("-many");
6130   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
6131     CmdArgs.push_back("-a64");
6132     CmdArgs.push_back("-mppc64");
6133     CmdArgs.push_back("-many");
6134   } else if (getToolChain().getArch() == llvm::Triple::ppc64le) {
6135     CmdArgs.push_back("-a64");
6136     CmdArgs.push_back("-mppc64le");
6137     CmdArgs.push_back("-many");
6138   } else if (getToolChain().getArch() == llvm::Triple::arm) {
6139     StringRef MArch = getToolChain().getArchName();
6140     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
6141       CmdArgs.push_back("-mfpu=neon");
6142     if (MArch == "armv8" || MArch == "armv8a" || MArch == "armv8-a")
6143       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
6144 
6145     StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
6146                                            getToolChain().getTriple());
6147     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
6148 
6149     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
6150     Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
6151     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
6152   } else if (getToolChain().getArch() == llvm::Triple::mips ||
6153              getToolChain().getArch() == llvm::Triple::mipsel ||
6154              getToolChain().getArch() == llvm::Triple::mips64 ||
6155              getToolChain().getArch() == llvm::Triple::mips64el) {
6156     StringRef CPUName;
6157     StringRef ABIName;
6158     getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6159 
6160     CmdArgs.push_back("-march");
6161     CmdArgs.push_back(CPUName.data());
6162 
6163     CmdArgs.push_back("-mabi");
6164     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6165 
6166     if (getToolChain().getArch() == llvm::Triple::mips ||
6167         getToolChain().getArch() == llvm::Triple::mips64)
6168       CmdArgs.push_back("-EB");
6169     else
6170       CmdArgs.push_back("-EL");
6171 
6172     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
6173       if (StringRef(A->getValue()) == "2008")
6174         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
6175     }
6176 
6177     Args.AddLastArg(CmdArgs, options::OPT_mips16, options::OPT_mno_mips16);
6178     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
6179                     options::OPT_mno_micromips);
6180     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
6181     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
6182 
6183     Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
6184                                       options::OPT_fpic, options::OPT_fno_pic,
6185                                       options::OPT_fPIE, options::OPT_fno_PIE,
6186                                       options::OPT_fpie, options::OPT_fno_pie);
6187     if (LastPICArg &&
6188         (LastPICArg->getOption().matches(options::OPT_fPIC) ||
6189          LastPICArg->getOption().matches(options::OPT_fpic) ||
6190          LastPICArg->getOption().matches(options::OPT_fPIE) ||
6191          LastPICArg->getOption().matches(options::OPT_fpie))) {
6192       CmdArgs.push_back("-KPIC");
6193     }
6194   } else if (getToolChain().getArch() == llvm::Triple::systemz) {
6195     // Always pass an -march option, since our default of z10 is later
6196     // than the GNU assembler's default.
6197     StringRef CPUName = getSystemZTargetCPU(Args);
6198     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
6199   }
6200 
6201   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6202                        options::OPT_Xassembler);
6203 
6204   CmdArgs.push_back("-o");
6205   CmdArgs.push_back(Output.getFilename());
6206 
6207   for (InputInfoList::const_iterator
6208          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6209     const InputInfo &II = *it;
6210     CmdArgs.push_back(II.getFilename());
6211   }
6212 
6213   const char *Exec =
6214     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6215   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6216 
6217   // Handle the debug info splitting at object creation time if we're
6218   // creating an object.
6219   // TODO: Currently only works on linux with newer objcopy.
6220   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6221       getToolChain().getTriple().isOSLinux())
6222     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6223                    SplitDebugName(Args, Inputs));
6224 }
6225 
6226 static void AddLibgcc(llvm::Triple Triple, const Driver &D,
6227                       ArgStringList &CmdArgs, const ArgList &Args) {
6228   bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
6229   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
6230                       Args.hasArg(options::OPT_static);
6231   if (!D.CCCIsCXX())
6232     CmdArgs.push_back("-lgcc");
6233 
6234   if (StaticLibgcc || isAndroid) {
6235     if (D.CCCIsCXX())
6236       CmdArgs.push_back("-lgcc");
6237   } else {
6238     if (!D.CCCIsCXX())
6239       CmdArgs.push_back("--as-needed");
6240     CmdArgs.push_back("-lgcc_s");
6241     if (!D.CCCIsCXX())
6242       CmdArgs.push_back("--no-as-needed");
6243   }
6244 
6245   if (StaticLibgcc && !isAndroid)
6246     CmdArgs.push_back("-lgcc_eh");
6247   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
6248     CmdArgs.push_back("-lgcc");
6249 
6250   // According to Android ABI, we have to link with libdl if we are
6251   // linking with non-static libgcc.
6252   //
6253   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
6254   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
6255   if (isAndroid && !StaticLibgcc)
6256     CmdArgs.push_back("-ldl");
6257 }
6258 
6259 static bool hasMipsN32ABIArg(const ArgList &Args) {
6260   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6261   return A && (A->getValue() == StringRef("n32"));
6262 }
6263 
6264 static StringRef getLinuxDynamicLinker(const ArgList &Args,
6265                                        const toolchains::Linux &ToolChain) {
6266   if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android)
6267     return "/system/bin/linker";
6268   else if (ToolChain.getArch() == llvm::Triple::x86)
6269     return "/lib/ld-linux.so.2";
6270   else if (ToolChain.getArch() == llvm::Triple::aarch64)
6271     return "/lib/ld-linux-aarch64.so.1";
6272   else if (ToolChain.getArch() == llvm::Triple::arm ||
6273            ToolChain.getArch() == llvm::Triple::thumb) {
6274     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
6275       return "/lib/ld-linux-armhf.so.3";
6276     else
6277       return "/lib/ld-linux.so.3";
6278   } else if (ToolChain.getArch() == llvm::Triple::mips ||
6279              ToolChain.getArch() == llvm::Triple::mipsel)
6280     return "/lib/ld.so.1";
6281   else if (ToolChain.getArch() == llvm::Triple::mips64 ||
6282            ToolChain.getArch() == llvm::Triple::mips64el) {
6283     if (hasMipsN32ABIArg(Args))
6284       return "/lib32/ld.so.1";
6285     else
6286       return "/lib64/ld.so.1";
6287   } else if (ToolChain.getArch() == llvm::Triple::ppc)
6288     return "/lib/ld.so.1";
6289   else if (ToolChain.getArch() == llvm::Triple::ppc64 ||
6290            ToolChain.getArch() == llvm::Triple::ppc64le ||
6291            ToolChain.getArch() == llvm::Triple::systemz)
6292     return "/lib64/ld64.so.1";
6293   else
6294     return "/lib64/ld-linux-x86-64.so.2";
6295 }
6296 
6297 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
6298                                   const InputInfo &Output,
6299                                   const InputInfoList &Inputs,
6300                                   const ArgList &Args,
6301                                   const char *LinkingOutput) const {
6302   const toolchains::Linux& ToolChain =
6303     static_cast<const toolchains::Linux&>(getToolChain());
6304   const Driver &D = ToolChain.getDriver();
6305   const bool isAndroid =
6306     ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
6307   const SanitizerArgs &Sanitize = ToolChain.getSanitizerArgs();
6308   const bool IsPIE =
6309     !Args.hasArg(options::OPT_shared) &&
6310     (Args.hasArg(options::OPT_pie) || Sanitize.hasZeroBaseShadow());
6311 
6312   ArgStringList CmdArgs;
6313 
6314   // Silence warning for "clang -g foo.o -o foo"
6315   Args.ClaimAllArgs(options::OPT_g_Group);
6316   // and "clang -emit-llvm foo.o -o foo"
6317   Args.ClaimAllArgs(options::OPT_emit_llvm);
6318   // and for "clang -w foo.o -o foo". Other warning options are already
6319   // handled somewhere else.
6320   Args.ClaimAllArgs(options::OPT_w);
6321 
6322   if (!D.SysRoot.empty())
6323     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6324 
6325   if (IsPIE)
6326     CmdArgs.push_back("-pie");
6327 
6328   if (Args.hasArg(options::OPT_rdynamic))
6329     CmdArgs.push_back("-export-dynamic");
6330 
6331   if (Args.hasArg(options::OPT_s))
6332     CmdArgs.push_back("-s");
6333 
6334   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
6335          e = ToolChain.ExtraOpts.end();
6336        i != e; ++i)
6337     CmdArgs.push_back(i->c_str());
6338 
6339   if (!Args.hasArg(options::OPT_static)) {
6340     CmdArgs.push_back("--eh-frame-hdr");
6341   }
6342 
6343   CmdArgs.push_back("-m");
6344   if (ToolChain.getArch() == llvm::Triple::x86)
6345     CmdArgs.push_back("elf_i386");
6346   else if (ToolChain.getArch() == llvm::Triple::aarch64)
6347     CmdArgs.push_back("aarch64linux");
6348   else if (ToolChain.getArch() == llvm::Triple::arm
6349            ||  ToolChain.getArch() == llvm::Triple::thumb)
6350     CmdArgs.push_back("armelf_linux_eabi");
6351   else if (ToolChain.getArch() == llvm::Triple::ppc)
6352     CmdArgs.push_back("elf32ppclinux");
6353   else if (ToolChain.getArch() == llvm::Triple::ppc64)
6354     CmdArgs.push_back("elf64ppc");
6355   else if (ToolChain.getArch() == llvm::Triple::mips)
6356     CmdArgs.push_back("elf32btsmip");
6357   else if (ToolChain.getArch() == llvm::Triple::mipsel)
6358     CmdArgs.push_back("elf32ltsmip");
6359   else if (ToolChain.getArch() == llvm::Triple::mips64) {
6360     if (hasMipsN32ABIArg(Args))
6361       CmdArgs.push_back("elf32btsmipn32");
6362     else
6363       CmdArgs.push_back("elf64btsmip");
6364   }
6365   else if (ToolChain.getArch() == llvm::Triple::mips64el) {
6366     if (hasMipsN32ABIArg(Args))
6367       CmdArgs.push_back("elf32ltsmipn32");
6368     else
6369       CmdArgs.push_back("elf64ltsmip");
6370   }
6371   else if (ToolChain.getArch() == llvm::Triple::systemz)
6372     CmdArgs.push_back("elf64_s390");
6373   else
6374     CmdArgs.push_back("elf_x86_64");
6375 
6376   if (Args.hasArg(options::OPT_static)) {
6377     if (ToolChain.getArch() == llvm::Triple::arm
6378         || ToolChain.getArch() == llvm::Triple::thumb)
6379       CmdArgs.push_back("-Bstatic");
6380     else
6381       CmdArgs.push_back("-static");
6382   } else if (Args.hasArg(options::OPT_shared)) {
6383     CmdArgs.push_back("-shared");
6384     if (isAndroid) {
6385       CmdArgs.push_back("-Bsymbolic");
6386     }
6387   }
6388 
6389   if (ToolChain.getArch() == llvm::Triple::arm ||
6390       ToolChain.getArch() == llvm::Triple::thumb ||
6391       (!Args.hasArg(options::OPT_static) &&
6392        !Args.hasArg(options::OPT_shared))) {
6393     CmdArgs.push_back("-dynamic-linker");
6394     CmdArgs.push_back(Args.MakeArgString(
6395         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
6396   }
6397 
6398   CmdArgs.push_back("-o");
6399   CmdArgs.push_back(Output.getFilename());
6400 
6401   if (!Args.hasArg(options::OPT_nostdlib) &&
6402       !Args.hasArg(options::OPT_nostartfiles)) {
6403     if (!isAndroid) {
6404       const char *crt1 = NULL;
6405       if (!Args.hasArg(options::OPT_shared)){
6406         if (Args.hasArg(options::OPT_pg))
6407           crt1 = "gcrt1.o";
6408         else if (IsPIE)
6409           crt1 = "Scrt1.o";
6410         else
6411           crt1 = "crt1.o";
6412       }
6413       if (crt1)
6414         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
6415 
6416       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
6417     }
6418 
6419     const char *crtbegin;
6420     if (Args.hasArg(options::OPT_static))
6421       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
6422     else if (Args.hasArg(options::OPT_shared))
6423       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
6424     else if (IsPIE)
6425       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
6426     else
6427       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
6428     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
6429 
6430     // Add crtfastmath.o if available and fast math is enabled.
6431     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
6432   }
6433 
6434   Args.AddAllArgs(CmdArgs, options::OPT_L);
6435 
6436   const ToolChain::path_list Paths = ToolChain.getFilePaths();
6437 
6438   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
6439        i != e; ++i)
6440     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
6441 
6442   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
6443   // as gold requires -plugin to come before any -plugin-opt that -Wl might
6444   // forward.
6445   if (D.IsUsingLTO(Args)) {
6446     CmdArgs.push_back("-plugin");
6447     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
6448     CmdArgs.push_back(Args.MakeArgString(Plugin));
6449 
6450     // Try to pass driver level flags relevant to LTO code generation down to
6451     // the plugin.
6452 
6453     // Handle flags for selecting CPU variants.
6454     std::string CPU = getCPUName(Args, ToolChain.getTriple());
6455     if (!CPU.empty()) {
6456       CmdArgs.push_back(
6457                         Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
6458                                            CPU));
6459     }
6460   }
6461 
6462 
6463   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6464     CmdArgs.push_back("--no-demangle");
6465 
6466   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6467 
6468   // Call these before we add the C++ ABI library.
6469   if (Sanitize.needsUbsanRt())
6470     addUbsanRTLinux(getToolChain(), Args, CmdArgs, D.CCCIsCXX(),
6471                     Sanitize.needsAsanRt() || Sanitize.needsTsanRt() ||
6472                     Sanitize.needsMsanRt() || Sanitize.needsLsanRt());
6473   if (Sanitize.needsAsanRt())
6474     addAsanRTLinux(getToolChain(), Args, CmdArgs);
6475   if (Sanitize.needsTsanRt())
6476     addTsanRTLinux(getToolChain(), Args, CmdArgs);
6477   if (Sanitize.needsMsanRt())
6478     addMsanRTLinux(getToolChain(), Args, CmdArgs);
6479   if (Sanitize.needsLsanRt())
6480     addLsanRTLinux(getToolChain(), Args, CmdArgs);
6481   if (Sanitize.needsDfsanRt())
6482     addDfsanRTLinux(getToolChain(), Args, CmdArgs);
6483 
6484   // The profile runtime also needs access to system libraries.
6485   addProfileRTLinux(getToolChain(), Args, CmdArgs);
6486 
6487   if (D.CCCIsCXX() &&
6488       !Args.hasArg(options::OPT_nostdlib) &&
6489       !Args.hasArg(options::OPT_nodefaultlibs)) {
6490     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
6491       !Args.hasArg(options::OPT_static);
6492     if (OnlyLibstdcxxStatic)
6493       CmdArgs.push_back("-Bstatic");
6494     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6495     if (OnlyLibstdcxxStatic)
6496       CmdArgs.push_back("-Bdynamic");
6497     CmdArgs.push_back("-lm");
6498   }
6499 
6500   if (!Args.hasArg(options::OPT_nostdlib)) {
6501     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
6502       if (Args.hasArg(options::OPT_static))
6503         CmdArgs.push_back("--start-group");
6504 
6505       bool OpenMP = Args.hasArg(options::OPT_fopenmp);
6506       if (OpenMP) {
6507         CmdArgs.push_back("-lgomp");
6508 
6509         // FIXME: Exclude this for platforms whith libgomp that doesn't require
6510         // librt. Most modern Linux platfroms require it, but some may not.
6511         CmdArgs.push_back("-lrt");
6512       }
6513 
6514       AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6515 
6516       if (Args.hasArg(options::OPT_pthread) ||
6517           Args.hasArg(options::OPT_pthreads) || OpenMP)
6518         CmdArgs.push_back("-lpthread");
6519 
6520       CmdArgs.push_back("-lc");
6521 
6522       if (Args.hasArg(options::OPT_static))
6523         CmdArgs.push_back("--end-group");
6524       else
6525         AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6526     }
6527 
6528     if (!Args.hasArg(options::OPT_nostartfiles)) {
6529       const char *crtend;
6530       if (Args.hasArg(options::OPT_shared))
6531         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
6532       else if (IsPIE)
6533         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
6534       else
6535         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
6536 
6537       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
6538       if (!isAndroid)
6539         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6540     }
6541   }
6542 
6543   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
6544 }
6545 
6546 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6547                                      const InputInfo &Output,
6548                                      const InputInfoList &Inputs,
6549                                      const ArgList &Args,
6550                                      const char *LinkingOutput) const {
6551   ArgStringList CmdArgs;
6552 
6553   // When building 32-bit code on NetBSD/amd64, we have to explicitly
6554   // instruct as in the base system to assemble 32-bit code.
6555   if (getToolChain().getArch() == llvm::Triple::x86)
6556     CmdArgs.push_back("--32");
6557 
6558 #if 0 /* LSC: Not needed for MINIX (no mips port) but kept to ease comparison with NetBSD. */
6559   // Set byte order explicitly
6560   if (getToolChain().getArch() == llvm::Triple::mips)
6561     CmdArgs.push_back("-EB");
6562   else if (getToolChain().getArch() == llvm::Triple::mipsel)
6563     CmdArgs.push_back("-EL");
6564 #endif /* 0 */
6565 
6566   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6567                        options::OPT_Xassembler);
6568 
6569   CmdArgs.push_back("-o");
6570   CmdArgs.push_back(Output.getFilename());
6571 
6572   for (InputInfoList::const_iterator
6573          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6574     const InputInfo &II = *it;
6575     CmdArgs.push_back(II.getFilename());
6576   }
6577 
6578   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
6579   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6580 }
6581 
6582 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
6583                                  const InputInfo &Output,
6584                                  const InputInfoList &Inputs,
6585                                  const ArgList &Args,
6586                                  const char *LinkingOutput) const {
6587   const Driver &D = getToolChain().getDriver();
6588   ArgStringList CmdArgs;
6589 
6590   if (!D.SysRoot.empty())
6591     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6592 
6593   if (Args.hasArg(options::OPT_static)) {
6594     CmdArgs.push_back("-Bstatic");
6595   } else {
6596     if (Args.hasArg(options::OPT_rdynamic))
6597       CmdArgs.push_back("-export-dynamic");
6598     CmdArgs.push_back("--eh-frame-hdr");
6599     if (Args.hasArg(options::OPT_shared)) {
6600       CmdArgs.push_back("-Bshareable");
6601     } else {
6602       CmdArgs.push_back("-dynamic-linker");
6603       // LSC: Small deviation from the NetBSD version.
6604       //      Use the same linker path as gcc.
6605       CmdArgs.push_back("/usr/libexec/ld.elf_so");
6606     }
6607   }
6608 
6609   // When building 32-bit code on NetBSD/amd64, we have to explicitly
6610   // instruct ld in the base system to link 32-bit code.
6611   if (getToolChain().getArch() == llvm::Triple::x86) {
6612     CmdArgs.push_back("-m");
6613     CmdArgs.push_back("elf_i386_minix");
6614   }
6615 
6616   if (Output.isFilename()) {
6617     CmdArgs.push_back("-o");
6618     CmdArgs.push_back(Output.getFilename());
6619   } else {
6620     assert(Output.isNothing() && "Invalid output.");
6621   }
6622 
6623   if (!Args.hasArg(options::OPT_nostdlib) &&
6624       !Args.hasArg(options::OPT_nostartfiles)) {
6625     if (!Args.hasArg(options::OPT_shared)) {
6626       CmdArgs.push_back(Args.MakeArgString(
6627                               getToolChain().GetFilePath("crt0.o")));
6628       CmdArgs.push_back(Args.MakeArgString(
6629                               getToolChain().GetFilePath("crti.o")));
6630       CmdArgs.push_back(Args.MakeArgString(
6631                               getToolChain().GetFilePath("crtbegin.o")));
6632     } else {
6633       CmdArgs.push_back(Args.MakeArgString(
6634                               getToolChain().GetFilePath("crti.o")));
6635       CmdArgs.push_back(Args.MakeArgString(
6636                               getToolChain().GetFilePath("crtbeginS.o")));
6637     }
6638   }
6639 
6640   Args.AddAllArgs(CmdArgs, options::OPT_L);
6641   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6642   Args.AddAllArgs(CmdArgs, options::OPT_e);
6643   Args.AddAllArgs(CmdArgs, options::OPT_s);
6644   Args.AddAllArgs(CmdArgs, options::OPT_t);
6645   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6646   Args.AddAllArgs(CmdArgs, options::OPT_r);
6647 
6648   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6649 
6650 #if 0 /* LSC: Not needed for MINIX, but kept to ease comparison with NetBSD. */
6651   unsigned Major, Minor, Micro;
6652   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
6653   bool useLibgcc = true;
6654   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 23) || Major == 0) {
6655     if (getToolChain().getArch() == llvm::Triple::x86 ||
6656         getToolChain().getArch() == llvm::Triple::x86_64)
6657       useLibgcc = false;
6658   }
6659 #endif /* 0 */
6660 
6661   if (!Args.hasArg(options::OPT_nostdlib) &&
6662       !Args.hasArg(options::OPT_nodefaultlibs)) {
6663     if (D.CCCIsCXX()) {
6664       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6665       CmdArgs.push_back("-lm");
6666 
6667       /* LSC: Hack as lc++ is linked against mthread. */
6668       CmdArgs.push_back("-lmthread");
6669     }
6670     if (Args.hasArg(options::OPT_pthread))
6671       CmdArgs.push_back("-lpthread");
6672     CmdArgs.push_back("-lc");
6673 
6674 #if 0 /* LSC: Minix always use CompilerRT-Generic. */
6675     if (useLibgcc) {
6676       if (Args.hasArg(options::OPT_static)) {
6677         // libgcc_eh depends on libc, so resolve as much as possible,
6678         // pull in any new requirements from libc and then get the rest
6679         // of libgcc.
6680         CmdArgs.push_back("-lgcc_eh");
6681         CmdArgs.push_back("-lc");
6682         CmdArgs.push_back("-lgcc");
6683       } else {
6684         CmdArgs.push_back("-lgcc");
6685         CmdArgs.push_back("--as-needed");
6686         CmdArgs.push_back("-lgcc_s");
6687         CmdArgs.push_back("--no-as-needed");
6688       }
6689     }
6690 #else
6691     //CmdArgs.push_back("-lCompilerRT-Generic");
6692 #endif /* 0 */
6693   }
6694 
6695   if (!Args.hasArg(options::OPT_nostdlib) &&
6696       !Args.hasArg(options::OPT_nostartfiles)) {
6697     if (!Args.hasArg(options::OPT_shared))
6698       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6699                                                                   "crtend.o")));
6700     else
6701       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6702                                                                  "crtendS.o")));
6703     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6704                                                                     "crtn.o")));
6705   }
6706 
6707   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6708 
6709   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6710   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6711 }
6712 
6713 /// DragonFly Tools
6714 
6715 // For now, DragonFly Assemble does just about the same as for
6716 // FreeBSD, but this may change soon.
6717 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6718                                        const InputInfo &Output,
6719                                        const InputInfoList &Inputs,
6720                                        const ArgList &Args,
6721                                        const char *LinkingOutput) const {
6722   ArgStringList CmdArgs;
6723 
6724   // When building 32-bit code on DragonFly/pc64, we have to explicitly
6725   // instruct as in the base system to assemble 32-bit code.
6726   if (getToolChain().getArch() == llvm::Triple::x86)
6727     CmdArgs.push_back("--32");
6728 
6729   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6730                        options::OPT_Xassembler);
6731 
6732   CmdArgs.push_back("-o");
6733   CmdArgs.push_back(Output.getFilename());
6734 
6735   for (InputInfoList::const_iterator
6736          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6737     const InputInfo &II = *it;
6738     CmdArgs.push_back(II.getFilename());
6739   }
6740 
6741   const char *Exec =
6742     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6743   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6744 }
6745 
6746 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
6747                                    const InputInfo &Output,
6748                                    const InputInfoList &Inputs,
6749                                    const ArgList &Args,
6750                                    const char *LinkingOutput) const {
6751   bool UseGCC47 = false;
6752   const Driver &D = getToolChain().getDriver();
6753   ArgStringList CmdArgs;
6754 
6755   if (llvm::sys::fs::exists("/usr/lib/gcc47", UseGCC47))
6756     UseGCC47 = false;
6757 
6758   if (!D.SysRoot.empty())
6759     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6760 
6761   CmdArgs.push_back("--eh-frame-hdr");
6762   if (Args.hasArg(options::OPT_static)) {
6763     CmdArgs.push_back("-Bstatic");
6764   } else {
6765     if (Args.hasArg(options::OPT_rdynamic))
6766       CmdArgs.push_back("-export-dynamic");
6767     if (Args.hasArg(options::OPT_shared))
6768       CmdArgs.push_back("-Bshareable");
6769     else {
6770       CmdArgs.push_back("-dynamic-linker");
6771       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
6772     }
6773     CmdArgs.push_back("--hash-style=both");
6774   }
6775 
6776   // When building 32-bit code on DragonFly/pc64, we have to explicitly
6777   // instruct ld in the base system to link 32-bit code.
6778   if (getToolChain().getArch() == llvm::Triple::x86) {
6779     CmdArgs.push_back("-m");
6780     CmdArgs.push_back("elf_i386");
6781   }
6782 
6783   if (Output.isFilename()) {
6784     CmdArgs.push_back("-o");
6785     CmdArgs.push_back(Output.getFilename());
6786   } else {
6787     assert(Output.isNothing() && "Invalid output.");
6788   }
6789 
6790   if (!Args.hasArg(options::OPT_nostdlib) &&
6791       !Args.hasArg(options::OPT_nostartfiles)) {
6792     if (!Args.hasArg(options::OPT_shared)) {
6793       if (Args.hasArg(options::OPT_pg))
6794         CmdArgs.push_back(Args.MakeArgString(
6795                                 getToolChain().GetFilePath("gcrt1.o")));
6796       else {
6797         if (Args.hasArg(options::OPT_pie))
6798           CmdArgs.push_back(Args.MakeArgString(
6799                                   getToolChain().GetFilePath("Scrt1.o")));
6800         else
6801           CmdArgs.push_back(Args.MakeArgString(
6802                                   getToolChain().GetFilePath("crt1.o")));
6803       }
6804     }
6805     CmdArgs.push_back(Args.MakeArgString(
6806                             getToolChain().GetFilePath("crti.o")));
6807     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6808       CmdArgs.push_back(Args.MakeArgString(
6809                               getToolChain().GetFilePath("crtbeginS.o")));
6810     else
6811       CmdArgs.push_back(Args.MakeArgString(
6812                               getToolChain().GetFilePath("crtbegin.o")));
6813   }
6814 
6815   Args.AddAllArgs(CmdArgs, options::OPT_L);
6816   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6817   Args.AddAllArgs(CmdArgs, options::OPT_e);
6818 
6819   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6820 
6821   if (!Args.hasArg(options::OPT_nostdlib) &&
6822       !Args.hasArg(options::OPT_nodefaultlibs)) {
6823     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
6824     //         rpaths
6825     if (UseGCC47)
6826       CmdArgs.push_back("-L/usr/lib/gcc47");
6827     else
6828       CmdArgs.push_back("-L/usr/lib/gcc44");
6829 
6830     if (!Args.hasArg(options::OPT_static)) {
6831       if (UseGCC47) {
6832         CmdArgs.push_back("-rpath");
6833         CmdArgs.push_back("/usr/lib/gcc47");
6834       } else {
6835         CmdArgs.push_back("-rpath");
6836         CmdArgs.push_back("/usr/lib/gcc44");
6837       }
6838     }
6839 
6840     if (D.CCCIsCXX()) {
6841       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6842       CmdArgs.push_back("-lm");
6843     }
6844 
6845     if (Args.hasArg(options::OPT_pthread))
6846       CmdArgs.push_back("-lpthread");
6847 
6848     if (!Args.hasArg(options::OPT_nolibc)) {
6849       CmdArgs.push_back("-lc");
6850     }
6851 
6852     if (UseGCC47) {
6853       if (Args.hasArg(options::OPT_static) ||
6854           Args.hasArg(options::OPT_static_libgcc)) {
6855         CmdArgs.push_back("-lgcc");
6856         CmdArgs.push_back("-lgcc_eh");
6857       } else {
6858         if (Args.hasArg(options::OPT_shared_libgcc)) {
6859           CmdArgs.push_back("-lgcc_pic");
6860           if (!Args.hasArg(options::OPT_shared))
6861             CmdArgs.push_back("-lgcc");
6862         } else {
6863           CmdArgs.push_back("-lgcc");
6864           CmdArgs.push_back("--as-needed");
6865           CmdArgs.push_back("-lgcc_pic");
6866           CmdArgs.push_back("--no-as-needed");
6867         }
6868       }
6869     } else {
6870       if (Args.hasArg(options::OPT_shared)) {
6871         CmdArgs.push_back("-lgcc_pic");
6872       } else {
6873         CmdArgs.push_back("-lgcc");
6874       }
6875     }
6876   }
6877 
6878   if (!Args.hasArg(options::OPT_nostdlib) &&
6879       !Args.hasArg(options::OPT_nostartfiles)) {
6880     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6881       CmdArgs.push_back(Args.MakeArgString(
6882                               getToolChain().GetFilePath("crtendS.o")));
6883     else
6884       CmdArgs.push_back(Args.MakeArgString(
6885                               getToolChain().GetFilePath("crtend.o")));
6886     CmdArgs.push_back(Args.MakeArgString(
6887                             getToolChain().GetFilePath("crtn.o")));
6888   }
6889 
6890   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6891 
6892   const char *Exec =
6893     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6894   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6895 }
6896 
6897 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
6898                                       const InputInfo &Output,
6899                                       const InputInfoList &Inputs,
6900                                       const ArgList &Args,
6901                                       const char *LinkingOutput) const {
6902   ArgStringList CmdArgs;
6903 
6904   if (Output.isFilename()) {
6905     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
6906                                          Output.getFilename()));
6907   } else {
6908     assert(Output.isNothing() && "Invalid output.");
6909   }
6910 
6911   if (!Args.hasArg(options::OPT_nostdlib) &&
6912       !Args.hasArg(options::OPT_nostartfiles) &&
6913       !C.getDriver().IsCLMode()) {
6914     CmdArgs.push_back("-defaultlib:libcmt");
6915   }
6916 
6917   CmdArgs.push_back("-nologo");
6918 
6919   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd);
6920 
6921   if (DLL) {
6922     CmdArgs.push_back(Args.MakeArgString("-dll"));
6923 
6924     SmallString<128> ImplibName(Output.getFilename());
6925     llvm::sys::path::replace_extension(ImplibName, "lib");
6926     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
6927                                          ImplibName.str()));
6928   }
6929 
6930   if (getToolChain().getSanitizerArgs().needsAsanRt()) {
6931     CmdArgs.push_back(Args.MakeArgString("-debug"));
6932     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
6933     SmallString<128> LibSanitizer(getToolChain().getDriver().ResourceDir);
6934     llvm::sys::path::append(LibSanitizer, "lib", "windows");
6935     if (DLL) {
6936       llvm::sys::path::append(LibSanitizer, "clang_rt.asan_dll_thunk-i386.lib");
6937     } else {
6938       llvm::sys::path::append(LibSanitizer, "clang_rt.asan-i386.lib");
6939     }
6940     // FIXME: Handle 64-bit.
6941     CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
6942   }
6943 
6944   Args.AddAllArgValues(CmdArgs, options::OPT_l);
6945   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
6946 
6947   // Add filenames immediately.
6948   for (InputInfoList::const_iterator
6949        it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6950     if (it->isFilename())
6951       CmdArgs.push_back(it->getFilename());
6952     else
6953       it->getInputArg().renderAsInput(Args, CmdArgs);
6954   }
6955 
6956   const char *Exec =
6957     Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
6958   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6959 }
6960 
6961 void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
6962                                          const InputInfo &Output,
6963                                          const InputInfoList &Inputs,
6964                                          const ArgList &Args,
6965                                          const char *LinkingOutput) const {
6966   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
6967 }
6968 
6969 // Try to find FallbackName on PATH that is not identical to ClangProgramPath.
6970 // If one cannot be found, return FallbackName.
6971 // We do this special search to prevent clang-cl from falling back onto itself
6972 // if it's available as cl.exe on the path.
6973 static std::string FindFallback(const char *FallbackName,
6974                                 const char *ClangProgramPath) {
6975   llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
6976   if (!OptPath.hasValue())
6977     return FallbackName;
6978 
6979 #ifdef LLVM_ON_WIN32
6980   const StringRef PathSeparators = ";";
6981 #else
6982   const StringRef PathSeparators = ":";
6983 #endif
6984 
6985   SmallVector<StringRef, 8> PathSegments;
6986   llvm::SplitString(OptPath.getValue(), PathSegments, PathSeparators);
6987 
6988   for (size_t i = 0, e = PathSegments.size(); i != e; ++i) {
6989     const StringRef &PathSegment = PathSegments[i];
6990     if (PathSegment.empty())
6991       continue;
6992 
6993     SmallString<128> FilePath(PathSegment);
6994     llvm::sys::path::append(FilePath, FallbackName);
6995     if (llvm::sys::fs::can_execute(Twine(FilePath)) &&
6996         !llvm::sys::fs::equivalent(Twine(FilePath), ClangProgramPath))
6997       return FilePath.str();
6998   }
6999 
7000   return FallbackName;
7001 }
7002 
7003 Command *visualstudio::Compile::GetCommand(Compilation &C, const JobAction &JA,
7004                                            const InputInfo &Output,
7005                                            const InputInfoList &Inputs,
7006                                            const ArgList &Args,
7007                                            const char *LinkingOutput) const {
7008   ArgStringList CmdArgs;
7009   CmdArgs.push_back("/nologo");
7010   CmdArgs.push_back("/c"); // Compile only.
7011   CmdArgs.push_back("/W0"); // No warnings.
7012 
7013   // The goal is to be able to invoke this tool correctly based on
7014   // any flag accepted by clang-cl.
7015 
7016   // These are spelled the same way in clang and cl.exe,.
7017   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
7018   Args.AddAllArgs(CmdArgs, options::OPT_I);
7019 
7020   // Optimization level.
7021   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
7022     if (A->getOption().getID() == options::OPT_O0) {
7023       CmdArgs.push_back("/Od");
7024     } else {
7025       StringRef OptLevel = A->getValue();
7026       if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
7027         A->render(Args, CmdArgs);
7028       else if (OptLevel == "3")
7029         CmdArgs.push_back("/Ox");
7030     }
7031   }
7032 
7033   // Flags for which clang-cl have an alias.
7034   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
7035 
7036   if (Arg *A = Args.getLastArg(options::OPT_frtti, options::OPT_fno_rtti))
7037     CmdArgs.push_back(A->getOption().getID() == options::OPT_frtti ? "/GR"
7038                                                                    : "/GR-");
7039   if (Args.hasArg(options::OPT_fsyntax_only))
7040     CmdArgs.push_back("/Zs");
7041 
7042   std::vector<std::string> Includes = Args.getAllArgValues(options::OPT_include);
7043   for (size_t I = 0, E = Includes.size(); I != E; ++I)
7044     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Includes[I]));
7045 
7046   // Flags that can simply be passed through.
7047   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
7048   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
7049 
7050   // The order of these flags is relevant, so pick the last one.
7051   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
7052                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
7053     A->render(Args, CmdArgs);
7054 
7055 
7056   // Input filename.
7057   assert(Inputs.size() == 1);
7058   const InputInfo &II = Inputs[0];
7059   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
7060   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
7061   if (II.isFilename())
7062     CmdArgs.push_back(II.getFilename());
7063   else
7064     II.getInputArg().renderAsInput(Args, CmdArgs);
7065 
7066   // Output filename.
7067   assert(Output.getType() == types::TY_Object);
7068   const char *Fo = Args.MakeArgString(std::string("/Fo") +
7069                                       Output.getFilename());
7070   CmdArgs.push_back(Fo);
7071 
7072   const Driver &D = getToolChain().getDriver();
7073   std::string Exec = FindFallback("cl.exe", D.getClangProgramPath());
7074 
7075   return new Command(JA, *this, Args.MakeArgString(Exec), CmdArgs);
7076 }
7077 
7078 
7079 /// XCore Tools
7080 // We pass assemble and link construction to the xcc tool.
7081 
7082 void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7083                                        const InputInfo &Output,
7084                                        const InputInfoList &Inputs,
7085                                        const ArgList &Args,
7086                                        const char *LinkingOutput) const {
7087   ArgStringList CmdArgs;
7088 
7089   CmdArgs.push_back("-o");
7090   CmdArgs.push_back(Output.getFilename());
7091 
7092   CmdArgs.push_back("-c");
7093 
7094   if (Args.hasArg(options::OPT_g_Group)) {
7095     CmdArgs.push_back("-g");
7096   }
7097 
7098   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7099                        options::OPT_Xassembler);
7100 
7101   for (InputInfoList::const_iterator
7102        it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
7103     const InputInfo &II = *it;
7104     CmdArgs.push_back(II.getFilename());
7105   }
7106 
7107   const char *Exec =
7108     Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
7109   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7110 }
7111 
7112 void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
7113                                    const InputInfo &Output,
7114                                    const InputInfoList &Inputs,
7115                                    const ArgList &Args,
7116                                    const char *LinkingOutput) const {
7117   ArgStringList CmdArgs;
7118 
7119   if (Output.isFilename()) {
7120     CmdArgs.push_back("-o");
7121     CmdArgs.push_back(Output.getFilename());
7122   } else {
7123     assert(Output.isNothing() && "Invalid output.");
7124   }
7125 
7126   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7127 
7128   const char *Exec =
7129     Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
7130   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7131 }
7132