]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Merge ^/head r284644 through r284736.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / Tools.cpp
1 //===--- Tools.cpp - Tools Implementations --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Tools.h"
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/TargetParser.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44
45 #ifdef LLVM_ON_UNIX
46 #include <unistd.h> // For getuid().
47 #endif
48
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
53
54 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
55   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
56                                     options::OPT_fpic, options::OPT_fno_pic,
57                                     options::OPT_fPIE, options::OPT_fno_PIE,
58                                     options::OPT_fpie, options::OPT_fno_pie);
59   if (!LastPICArg)
60     return;
61   if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
62       LastPICArg->getOption().matches(options::OPT_fpic) ||
63       LastPICArg->getOption().matches(options::OPT_fPIE) ||
64       LastPICArg->getOption().matches(options::OPT_fpie)) {
65     CmdArgs.push_back("-KPIC");
66   }
67 }
68
69 /// CheckPreprocessingOptions - Perform some validation of preprocessing
70 /// arguments that is shared with gcc.
71 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
73     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
74         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
75       D.Diag(diag::err_drv_argument_only_allowed_with)
76           << A->getBaseArg().getAsString(Args)
77           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
78     }
79   }
80 }
81
82 /// CheckCodeGenerationOptions - Perform some validation of code generation
83 /// arguments that is shared with gcc.
84 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
85   // In gcc, only ARM checks this, but it seems reasonable to check universally.
86   if (Args.hasArg(options::OPT_static))
87     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
88                                        options::OPT_mdynamic_no_pic))
89       D.Diag(diag::err_drv_argument_not_allowed_with)
90         << A->getAsString(Args) << "-static";
91 }
92
93 // Add backslashes to escape spaces and other backslashes.
94 // This is used for the space-separated argument list specified with
95 // the -dwarf-debug-flags option.
96 static void EscapeSpacesAndBackslashes(const char *Arg,
97                                        SmallVectorImpl<char> &Res) {
98   for ( ; *Arg; ++Arg) {
99     switch (*Arg) {
100     default: break;
101     case ' ':
102     case '\\':
103       Res.push_back('\\');
104       break;
105     }
106     Res.push_back(*Arg);
107   }
108 }
109
110 // Quote target names for inclusion in GNU Make dependency files.
111 // Only the characters '$', '#', ' ', '\t' are quoted.
112 static void QuoteTarget(StringRef Target,
113                         SmallVectorImpl<char> &Res) {
114   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
115     switch (Target[i]) {
116     case ' ':
117     case '\t':
118       // Escape the preceding backslashes
119       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
120         Res.push_back('\\');
121
122       // Escape the space/tab
123       Res.push_back('\\');
124       break;
125     case '$':
126       Res.push_back('$');
127       break;
128     case '#':
129       Res.push_back('\\');
130       break;
131     default:
132       break;
133     }
134
135     Res.push_back(Target[i]);
136   }
137 }
138
139 static void addDirectoryList(const ArgList &Args,
140                              ArgStringList &CmdArgs,
141                              const char *ArgName,
142                              const char *EnvVar) {
143   const char *DirList = ::getenv(EnvVar);
144   bool CombinedArg = false;
145
146   if (!DirList)
147     return; // Nothing to do.
148
149   StringRef Name(ArgName);
150   if (Name.equals("-I") || Name.equals("-L"))
151     CombinedArg = true;
152
153   StringRef Dirs(DirList);
154   if (Dirs.empty()) // Empty string should not add '.'.
155     return;
156
157   StringRef::size_type Delim;
158   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
159     if (Delim == 0) { // Leading colon.
160       if (CombinedArg) {
161         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
162       } else {
163         CmdArgs.push_back(ArgName);
164         CmdArgs.push_back(".");
165       }
166     } else {
167       if (CombinedArg) {
168         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
169       } else {
170         CmdArgs.push_back(ArgName);
171         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
172       }
173     }
174     Dirs = Dirs.substr(Delim + 1);
175   }
176
177   if (Dirs.empty()) { // Trailing colon.
178     if (CombinedArg) {
179       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
180     } else {
181       CmdArgs.push_back(ArgName);
182       CmdArgs.push_back(".");
183     }
184   } else { // Add the last path.
185     if (CombinedArg) {
186       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
187     } else {
188       CmdArgs.push_back(ArgName);
189       CmdArgs.push_back(Args.MakeArgString(Dirs));
190     }
191   }
192 }
193
194 static void AddLinkerInputs(const ToolChain &TC,
195                             const InputInfoList &Inputs, const ArgList &Args,
196                             ArgStringList &CmdArgs) {
197   const Driver &D = TC.getDriver();
198
199   // Add extra linker input arguments which are not treated as inputs
200   // (constructed via -Xarch_).
201   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
202
203   for (const auto &II : Inputs) {
204     if (!TC.HasNativeLLVMSupport()) {
205       // Don't try to pass LLVM inputs unless we have native support.
206       if (II.getType() == types::TY_LLVM_IR ||
207           II.getType() == types::TY_LTO_IR ||
208           II.getType() == types::TY_LLVM_BC ||
209           II.getType() == types::TY_LTO_BC)
210         D.Diag(diag::err_drv_no_linker_llvm_support)
211           << TC.getTripleString();
212     }
213
214     // Add filenames immediately.
215     if (II.isFilename()) {
216       CmdArgs.push_back(II.getFilename());
217       continue;
218     }
219
220     // Otherwise, this is a linker input argument.
221     const Arg &A = II.getInputArg();
222
223     // Handle reserved library options.
224     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
225       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
226     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
227       TC.AddCCKextLibArgs(Args, CmdArgs);
228     else if (A.getOption().matches(options::OPT_z)) {
229       // Pass -z prefix for gcc linker compatibility.
230       A.claim();
231       A.render(Args, CmdArgs);
232     } else {
233        A.renderAsInput(Args, CmdArgs);
234     }
235   }
236
237   // LIBRARY_PATH - included following the user specified library paths.
238   //                and only supported on native toolchains.
239   if (!TC.isCrossCompiling())
240     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
241 }
242
243 /// \brief Determine whether Objective-C automated reference counting is
244 /// enabled.
245 static bool isObjCAutoRefCount(const ArgList &Args) {
246   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
247 }
248
249 /// \brief Determine whether we are linking the ObjC runtime.
250 static bool isObjCRuntimeLinked(const ArgList &Args) {
251   if (isObjCAutoRefCount(Args)) {
252     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
253     return true;
254   }
255   return Args.hasArg(options::OPT_fobjc_link_runtime);
256 }
257
258 static bool forwardToGCC(const Option &O) {
259   // Don't forward inputs from the original command line.  They are added from
260   // InputInfoList.
261   return O.getKind() != Option::InputClass &&
262          !O.hasFlag(options::DriverOption) &&
263          !O.hasFlag(options::LinkerInput);
264 }
265
266 void Clang::AddPreprocessingOptions(Compilation &C,
267                                     const JobAction &JA,
268                                     const Driver &D,
269                                     const ArgList &Args,
270                                     ArgStringList &CmdArgs,
271                                     const InputInfo &Output,
272                                     const InputInfoList &Inputs) const {
273   Arg *A;
274
275   CheckPreprocessingOptions(D, Args);
276
277   Args.AddLastArg(CmdArgs, options::OPT_C);
278   Args.AddLastArg(CmdArgs, options::OPT_CC);
279
280   // Handle dependency file generation.
281   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
282       (A = Args.getLastArg(options::OPT_MD)) ||
283       (A = Args.getLastArg(options::OPT_MMD))) {
284     // Determine the output location.
285     const char *DepFile;
286     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
287       DepFile = MF->getValue();
288       C.addFailureResultFile(DepFile, &JA);
289     } else if (Output.getType() == types::TY_Dependencies) {
290       DepFile = Output.getFilename();
291     } else if (A->getOption().matches(options::OPT_M) ||
292                A->getOption().matches(options::OPT_MM)) {
293       DepFile = "-";
294     } else {
295       DepFile = getDependencyFileName(Args, Inputs);
296       C.addFailureResultFile(DepFile, &JA);
297     }
298     CmdArgs.push_back("-dependency-file");
299     CmdArgs.push_back(DepFile);
300
301     // Add a default target if one wasn't specified.
302     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
303       const char *DepTarget;
304
305       // If user provided -o, that is the dependency target, except
306       // when we are only generating a dependency file.
307       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
308       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
309         DepTarget = OutputOpt->getValue();
310       } else {
311         // Otherwise derive from the base input.
312         //
313         // FIXME: This should use the computed output file location.
314         SmallString<128> P(Inputs[0].getBaseInput());
315         llvm::sys::path::replace_extension(P, "o");
316         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
317       }
318
319       CmdArgs.push_back("-MT");
320       SmallString<128> Quoted;
321       QuoteTarget(DepTarget, Quoted);
322       CmdArgs.push_back(Args.MakeArgString(Quoted));
323     }
324
325     if (A->getOption().matches(options::OPT_M) ||
326         A->getOption().matches(options::OPT_MD))
327       CmdArgs.push_back("-sys-header-deps");
328     if ((isa<PrecompileJobAction>(JA) &&
329          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
330         Args.hasArg(options::OPT_fmodule_file_deps))
331       CmdArgs.push_back("-module-file-deps");
332   }
333
334   if (Args.hasArg(options::OPT_MG)) {
335     if (!A || A->getOption().matches(options::OPT_MD) ||
336               A->getOption().matches(options::OPT_MMD))
337       D.Diag(diag::err_drv_mg_requires_m_or_mm);
338     CmdArgs.push_back("-MG");
339   }
340
341   Args.AddLastArg(CmdArgs, options::OPT_MP);
342   Args.AddLastArg(CmdArgs, options::OPT_MV);
343
344   // Convert all -MQ <target> args to -MT <quoted target>
345   for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
346     A->claim();
347
348     if (A->getOption().matches(options::OPT_MQ)) {
349       CmdArgs.push_back("-MT");
350       SmallString<128> Quoted;
351       QuoteTarget(A->getValue(), Quoted);
352       CmdArgs.push_back(Args.MakeArgString(Quoted));
353
354     // -MT flag - no change
355     } else {
356       A->render(Args, CmdArgs);
357     }
358   }
359
360   // Add -i* options, and automatically translate to
361   // -include-pch/-include-pth for transparent PCH support. It's
362   // wonky, but we include looking for .gch so we can support seamless
363   // replacement into a build system already set up to be generating
364   // .gch files.
365   bool RenderedImplicitInclude = false;
366   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
367     if (A->getOption().matches(options::OPT_include)) {
368       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
369       RenderedImplicitInclude = true;
370
371       // Use PCH if the user requested it.
372       bool UsePCH = D.CCCUsePCH;
373
374       bool FoundPTH = false;
375       bool FoundPCH = false;
376       SmallString<128> P(A->getValue());
377       // We want the files to have a name like foo.h.pch. Add a dummy extension
378       // so that replace_extension does the right thing.
379       P += ".dummy";
380       if (UsePCH) {
381         llvm::sys::path::replace_extension(P, "pch");
382         if (llvm::sys::fs::exists(P))
383           FoundPCH = true;
384       }
385
386       if (!FoundPCH) {
387         llvm::sys::path::replace_extension(P, "pth");
388         if (llvm::sys::fs::exists(P))
389           FoundPTH = true;
390       }
391
392       if (!FoundPCH && !FoundPTH) {
393         llvm::sys::path::replace_extension(P, "gch");
394         if (llvm::sys::fs::exists(P)) {
395           FoundPCH = UsePCH;
396           FoundPTH = !UsePCH;
397         }
398       }
399
400       if (FoundPCH || FoundPTH) {
401         if (IsFirstImplicitInclude) {
402           A->claim();
403           if (UsePCH)
404             CmdArgs.push_back("-include-pch");
405           else
406             CmdArgs.push_back("-include-pth");
407           CmdArgs.push_back(Args.MakeArgString(P));
408           continue;
409         } else {
410           // Ignore the PCH if not first on command line and emit warning.
411           D.Diag(diag::warn_drv_pch_not_first_include)
412               << P << A->getAsString(Args);
413         }
414       }
415     }
416
417     // Not translated, render as usual.
418     A->claim();
419     A->render(Args, CmdArgs);
420   }
421
422   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
423   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
424                   options::OPT_index_header_map);
425
426   // Add -Wp, and -Xassembler if using the preprocessor.
427
428   // FIXME: There is a very unfortunate problem here, some troubled
429   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
430   // really support that we would have to parse and then translate
431   // those options. :(
432   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
433                        options::OPT_Xpreprocessor);
434
435   // -I- is a deprecated GCC feature, reject it.
436   if (Arg *A = Args.getLastArg(options::OPT_I_))
437     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
438
439   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
440   // -isysroot to the CC1 invocation.
441   StringRef sysroot = C.getSysRoot();
442   if (sysroot != "") {
443     if (!Args.hasArg(options::OPT_isysroot)) {
444       CmdArgs.push_back("-isysroot");
445       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
446     }
447   }
448
449   // Parse additional include paths from environment variables.
450   // FIXME: We should probably sink the logic for handling these from the
451   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
452   // CPATH - included following the user specified includes (but prior to
453   // builtin and standard includes).
454   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
455   // C_INCLUDE_PATH - system includes enabled when compiling C.
456   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
457   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
458   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
459   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
460   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
461   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
462   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
463
464   // Add C++ include arguments, if needed.
465   if (types::isCXX(Inputs[0].getType()))
466     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
467
468   // Add system include arguments.
469   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
470 }
471
472 // FIXME: Move to target hook.
473 static bool isSignedCharDefault(const llvm::Triple &Triple) {
474   switch (Triple.getArch()) {
475   default:
476     return true;
477
478   case llvm::Triple::aarch64:
479   case llvm::Triple::aarch64_be:
480   case llvm::Triple::arm:
481   case llvm::Triple::armeb:
482   case llvm::Triple::thumb:
483   case llvm::Triple::thumbeb:
484     if (Triple.isOSDarwin() || Triple.isOSWindows())
485       return true;
486     return false;
487
488   case llvm::Triple::ppc:
489   case llvm::Triple::ppc64:
490     if (Triple.isOSDarwin())
491       return true;
492     return false;
493
494   case llvm::Triple::hexagon:
495   case llvm::Triple::ppc64le:
496   case llvm::Triple::systemz:
497   case llvm::Triple::xcore:
498     return false;
499   }
500 }
501
502 static bool isNoCommonDefault(const llvm::Triple &Triple) {
503   switch (Triple.getArch()) {
504   default:
505     return false;
506
507   case llvm::Triple::xcore:
508     return true;
509   }
510 }
511
512 // Handle -mhwdiv=.
513 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
514                               const ArgList &Args,
515                               std::vector<const char *> &Features) {
516   StringRef HWDiv = A->getValue();
517   if (HWDiv == "arm") {
518     Features.push_back("+hwdiv-arm");
519     Features.push_back("-hwdiv");
520   } else if (HWDiv == "thumb") {
521     Features.push_back("-hwdiv-arm");
522     Features.push_back("+hwdiv");
523   } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
524     Features.push_back("+hwdiv-arm");
525     Features.push_back("+hwdiv");
526   } else if (HWDiv == "none") {
527     Features.push_back("-hwdiv-arm");
528     Features.push_back("-hwdiv");
529   } else
530     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
531 }
532
533 // Handle -mfpu=.
534 static void getARMFPUFeatures(const Driver &D, const Arg *A,
535                               const ArgList &Args,
536                               std::vector<const char *> &Features) {
537   StringRef FPU = A->getValue();
538   unsigned FPUID = llvm::ARMTargetParser::parseFPU(FPU);
539   if (!llvm::ARMTargetParser::getFPUFeatures(FPUID, Features))
540     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
541 }
542
543 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
544   llvm::StringRef Arch = Triple.getArchName();
545   return llvm::ARMTargetParser::parseArchVersion(Arch);
546 }
547
548 static bool isARMMProfile(const llvm::Triple &Triple) {
549   llvm::StringRef Arch = Triple.getArchName();
550   unsigned Profile = llvm::ARMTargetParser::parseArchProfile(Arch);
551   return Profile == llvm::ARM::PK_M;
552 }
553
554 // Select the float ABI as determined by -msoft-float, -mhard-float, and
555 // -mfloat-abi=.
556 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
557                                      const llvm::Triple &Triple) {
558   StringRef FloatABI;
559   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
560                                options::OPT_mhard_float,
561                                options::OPT_mfloat_abi_EQ)) {
562     if (A->getOption().matches(options::OPT_msoft_float))
563       FloatABI = "soft";
564     else if (A->getOption().matches(options::OPT_mhard_float))
565       FloatABI = "hard";
566     else {
567       FloatABI = A->getValue();
568       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
569         D.Diag(diag::err_drv_invalid_mfloat_abi)
570           << A->getAsString(Args);
571         FloatABI = "soft";
572       }
573     }
574   }
575
576   // If unspecified, choose the default based on the platform.
577   if (FloatABI.empty()) {
578     switch (Triple.getOS()) {
579     case llvm::Triple::Darwin:
580     case llvm::Triple::MacOSX:
581     case llvm::Triple::IOS: {
582       // Darwin defaults to "softfp" for v6 and v7.
583       //
584       if (getARMSubArchVersionNumber(Triple) == 6 ||
585           getARMSubArchVersionNumber(Triple) == 7)
586         FloatABI = "softfp";
587       else
588         FloatABI = "soft";
589       break;
590     }
591
592     // FIXME: this is invalid for WindowsCE
593     case llvm::Triple::Win32:
594       FloatABI = "hard";
595       break;
596
597     case llvm::Triple::FreeBSD:
598       switch(Triple.getEnvironment()) {
599       case llvm::Triple::GNUEABIHF:
600         FloatABI = "hard";
601         break;
602       default:
603         // FreeBSD defaults to soft float
604         FloatABI = "soft";
605         break;
606       }
607       break;
608
609     default:
610       switch(Triple.getEnvironment()) {
611       case llvm::Triple::GNUEABIHF:
612         FloatABI = "hard";
613         break;
614       case llvm::Triple::GNUEABI:
615         FloatABI = "softfp";
616         break;
617       case llvm::Triple::EABIHF:
618         FloatABI = "hard";
619         break;
620       case llvm::Triple::EABI:
621         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
622         FloatABI = "softfp";
623         break;
624       case llvm::Triple::Android: {
625         if (getARMSubArchVersionNumber(Triple) == 7)
626           FloatABI = "softfp";
627         else
628           FloatABI = "soft";
629         break;
630       }
631       default:
632         // Assume "soft", but warn the user we are guessing.
633         FloatABI = "soft";
634         if (Triple.getOS() != llvm::Triple::UnknownOS ||
635             !Triple.isOSBinFormatMachO())
636           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
637         break;
638       }
639     }
640   }
641
642   return FloatABI;
643 }
644
645 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
646                                  const ArgList &Args,
647                                  std::vector<const char *> &Features,
648                                  bool ForAS) {
649   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
650   if (!ForAS) {
651     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
652     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
653     // stripped out by the ARM target. We should probably pass this a new
654     // -target-option, which is handled by the -cc1/-cc1as invocation.
655     //
656     // FIXME2:  For consistency, it would be ideal if we set up the target
657     // machine state the same when using the frontend or the assembler. We don't
658     // currently do that for the assembler, we pass the options directly to the
659     // backend and never even instantiate the frontend TargetInfo. If we did,
660     // and used its handleTargetFeatures hook, then we could ensure the
661     // assembler and the frontend behave the same.
662
663     // Use software floating point operations?
664     if (FloatABI == "soft")
665       Features.push_back("+soft-float");
666
667     // Use software floating point argument passing?
668     if (FloatABI != "hard")
669       Features.push_back("+soft-float-abi");
670   }
671
672   // Honor -mfpu=.
673   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
674     getARMFPUFeatures(D, A, Args, Features);
675   if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
676     getARMHWDivFeatures(D, A, Args, Features);
677
678   // Check if -march is valid by checking if it can be canonicalised and parsed.
679   // getARMArch is used here instead of just checking the -march value in order
680   // to handle -march=native correctly.
681   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
682     std::string Arch = arm::getARMArch(Args, Triple);
683     if (llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_INVALID)
684       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
685   }
686
687   // We do a similar thing with -mcpu, but here things are complicated because
688   // the only function we have to check if a cpu is valid is
689   // getLLVMArchSuffixForARM which also needs an architecture.
690   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
691     std::string CPU = arm::getARMTargetCPU(Args, Triple);
692     std::string Arch = arm::getARMArch(Args, Triple);
693     if (strcmp(arm::getLLVMArchSuffixForARM(CPU, Arch), "") == 0)
694       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
695   }
696
697   // Setting -msoft-float effectively disables NEON because of the GCC
698   // implementation, although the same isn't true of VFP or VFP3.
699   if (FloatABI == "soft") {
700     Features.push_back("-neon");
701     // Also need to explicitly disable features which imply NEON.
702     Features.push_back("-crypto");
703   }
704
705   // En/disable crc code generation.
706   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
707     if (A->getOption().matches(options::OPT_mcrc))
708       Features.push_back("+crc");
709     else
710       Features.push_back("-crc");
711   }
712
713   if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
714     Features.insert(Features.begin(), "+v8.1a");
715   }
716 }
717
718 void Clang::AddARMTargetArgs(const ArgList &Args,
719                              ArgStringList &CmdArgs,
720                              bool KernelOrKext) const {
721   const Driver &D = getToolChain().getDriver();
722   // Get the effective triple, which takes into account the deployment target.
723   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
724   llvm::Triple Triple(TripleStr);
725
726   // Select the ABI to use.
727   //
728   // FIXME: Support -meabi.
729   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
730   const char *ABIName = nullptr;
731   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
732     ABIName = A->getValue();
733   } else if (Triple.isOSBinFormatMachO()) {
734     // The backend is hardwired to assume AAPCS for M-class processors, ensure
735     // the frontend matches that.
736     if (Triple.getEnvironment() == llvm::Triple::EABI ||
737         Triple.getOS() == llvm::Triple::UnknownOS ||
738         isARMMProfile(Triple)) {
739       ABIName = "aapcs";
740     } else {
741       ABIName = "apcs-gnu";
742     }
743   } else if (Triple.isOSWindows()) {
744     // FIXME: this is invalid for WindowsCE
745     ABIName = "aapcs";
746   } else {
747     // Select the default based on the platform.
748     switch(Triple.getEnvironment()) {
749     case llvm::Triple::Android:
750     case llvm::Triple::GNUEABI:
751     case llvm::Triple::GNUEABIHF:
752       ABIName = "aapcs-linux";
753       break;
754     case llvm::Triple::EABIHF:
755     case llvm::Triple::EABI:
756       ABIName = "aapcs";
757       break;
758     default:
759       if (Triple.getOS() == llvm::Triple::NetBSD)
760         ABIName = "apcs-gnu";
761       else
762         ABIName = "aapcs";
763       break;
764     }
765   }
766   CmdArgs.push_back("-target-abi");
767   CmdArgs.push_back(ABIName);
768
769   // Determine floating point ABI from the options & target defaults.
770   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
771   if (FloatABI == "soft") {
772     // Floating point operations and argument passing are soft.
773     //
774     // FIXME: This changes CPP defines, we need -target-soft-float.
775     CmdArgs.push_back("-msoft-float");
776     CmdArgs.push_back("-mfloat-abi");
777     CmdArgs.push_back("soft");
778   } else if (FloatABI == "softfp") {
779     // Floating point operations are hard, but argument passing is soft.
780     CmdArgs.push_back("-mfloat-abi");
781     CmdArgs.push_back("soft");
782   } else {
783     // Floating point operations and argument passing are hard.
784     assert(FloatABI == "hard" && "Invalid float abi!");
785     CmdArgs.push_back("-mfloat-abi");
786     CmdArgs.push_back("hard");
787   }
788
789   // Kernel code has more strict alignment requirements.
790   if (KernelOrKext) {
791     if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
792       CmdArgs.push_back("-backend-option");
793       CmdArgs.push_back("-arm-long-calls");
794     }
795
796     CmdArgs.push_back("-backend-option");
797     CmdArgs.push_back("-arm-strict-align");
798
799     // The kext linker doesn't know how to deal with movw/movt.
800     CmdArgs.push_back("-backend-option");
801     CmdArgs.push_back("-arm-use-movt=0");
802   }
803
804   // -mkernel implies -mstrict-align; don't add the redundant option.
805   if (!KernelOrKext) {
806     if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
807                                  options::OPT_munaligned_access)) {
808       CmdArgs.push_back("-backend-option");
809       if (A->getOption().matches(options::OPT_mno_unaligned_access))
810         CmdArgs.push_back("-arm-strict-align");
811       else {
812         if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
813           D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
814         CmdArgs.push_back("-arm-no-strict-align");
815       }
816     }
817   }
818
819   // Forward the -mglobal-merge option for explicit control over the pass.
820   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
821                                options::OPT_mno_global_merge)) {
822     CmdArgs.push_back("-backend-option");
823     if (A->getOption().matches(options::OPT_mno_global_merge))
824       CmdArgs.push_back("-arm-global-merge=false");
825     else
826       CmdArgs.push_back("-arm-global-merge=true");
827   }
828
829   if (!Args.hasFlag(options::OPT_mimplicit_float,
830                     options::OPT_mno_implicit_float,
831                     true))
832     CmdArgs.push_back("-no-implicit-float");
833
834   // llvm does not support reserving registers in general. There is support
835   // for reserving r9 on ARM though (defined as a platform-specific register
836   // in ARM EABI).
837   if (Args.hasArg(options::OPT_ffixed_r9)) {
838     CmdArgs.push_back("-backend-option");
839     CmdArgs.push_back("-arm-reserve-r9");
840   }
841 }
842
843 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
844 /// targeting.
845 static std::string getAArch64TargetCPU(const ArgList &Args) {
846   Arg *A;
847   std::string CPU;
848   // If we have -mtune or -mcpu, use that.
849   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
850     CPU = A->getValue();
851   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
852     StringRef Mcpu = A->getValue();
853     CPU = Mcpu.split("+").first.lower();
854   }
855
856   // Handle CPU name is 'native'.
857   if (CPU == "native")
858     return llvm::sys::getHostCPUName();
859   else if (CPU.size())
860     return CPU;
861
862   // Make sure we pick "cyclone" if -arch is used.
863   // FIXME: Should this be picked by checking the target triple instead?
864   if (Args.getLastArg(options::OPT_arch))
865     return "cyclone";
866
867   return "generic";
868 }
869
870 void Clang::AddAArch64TargetArgs(const ArgList &Args,
871                                  ArgStringList &CmdArgs) const {
872   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
873   llvm::Triple Triple(TripleStr);
874
875   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
876       Args.hasArg(options::OPT_mkernel) ||
877       Args.hasArg(options::OPT_fapple_kext))
878     CmdArgs.push_back("-disable-red-zone");
879
880   if (!Args.hasFlag(options::OPT_mimplicit_float,
881                     options::OPT_mno_implicit_float, true))
882     CmdArgs.push_back("-no-implicit-float");
883
884   const char *ABIName = nullptr;
885   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
886     ABIName = A->getValue();
887   else if (Triple.isOSDarwin())
888     ABIName = "darwinpcs";
889   else
890     ABIName = "aapcs";
891
892   CmdArgs.push_back("-target-abi");
893   CmdArgs.push_back(ABIName);
894
895   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
896                                options::OPT_munaligned_access)) {
897     CmdArgs.push_back("-backend-option");
898     if (A->getOption().matches(options::OPT_mno_unaligned_access))
899       CmdArgs.push_back("-aarch64-strict-align");
900     else
901       CmdArgs.push_back("-aarch64-no-strict-align");
902   }
903
904   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
905                                options::OPT_mno_fix_cortex_a53_835769)) {
906     CmdArgs.push_back("-backend-option");
907     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
908       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
909     else
910       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
911   } else if (Triple.getEnvironment() == llvm::Triple::Android) {
912     // Enabled A53 errata (835769) workaround by default on android
913     CmdArgs.push_back("-backend-option");
914     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
915   }
916
917   // Forward the -mglobal-merge option for explicit control over the pass.
918   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
919                                options::OPT_mno_global_merge)) {
920     CmdArgs.push_back("-backend-option");
921     if (A->getOption().matches(options::OPT_mno_global_merge))
922       CmdArgs.push_back("-aarch64-global-merge=false");
923     else
924       CmdArgs.push_back("-aarch64-global-merge=true");
925   }
926
927   if (Args.hasArg(options::OPT_ffixed_x18)) {
928     CmdArgs.push_back("-backend-option");
929     CmdArgs.push_back("-aarch64-reserve-x18");
930   }
931 }
932
933 // Get CPU and ABI names. They are not independent
934 // so we have to calculate them together.
935 void mips::getMipsCPUAndABI(const ArgList &Args,
936                             const llvm::Triple &Triple,
937                             StringRef &CPUName,
938                             StringRef &ABIName) {
939   const char *DefMips32CPU = "mips32r2";
940   const char *DefMips64CPU = "mips64r2";
941
942   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
943   // default for mips64(el)?-img-linux-gnu.
944   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
945       Triple.getEnvironment() == llvm::Triple::GNU) {
946     DefMips32CPU = "mips32r6";
947     DefMips64CPU = "mips64r6";
948   }
949
950   // MIPS3 is the default for mips64*-unknown-openbsd.
951   if (Triple.getOS() == llvm::Triple::OpenBSD)
952     DefMips64CPU = "mips3";
953
954   if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
955                                options::OPT_mcpu_EQ))
956     CPUName = A->getValue();
957
958   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
959     ABIName = A->getValue();
960     // Convert a GNU style Mips ABI name to the name
961     // accepted by LLVM Mips backend.
962     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
963       .Case("32", "o32")
964       .Case("64", "n64")
965       .Default(ABIName);
966   }
967
968   // Setup default CPU and ABI names.
969   if (CPUName.empty() && ABIName.empty()) {
970     switch (Triple.getArch()) {
971     default:
972       llvm_unreachable("Unexpected triple arch name");
973     case llvm::Triple::mips:
974     case llvm::Triple::mipsel:
975       CPUName = DefMips32CPU;
976       break;
977     case llvm::Triple::mips64:
978     case llvm::Triple::mips64el:
979       CPUName = DefMips64CPU;
980       break;
981     }
982   }
983
984   if (ABIName.empty()) {
985     // Deduce ABI name from the target triple.
986     if (Triple.getArch() == llvm::Triple::mips ||
987         Triple.getArch() == llvm::Triple::mipsel)
988       ABIName = "o32";
989     else
990       ABIName = "n64";
991   }
992
993   if (CPUName.empty()) {
994     // Deduce CPU name from ABI name.
995     CPUName = llvm::StringSwitch<const char *>(ABIName)
996       .Cases("o32", "eabi", DefMips32CPU)
997       .Cases("n32", "n64", DefMips64CPU)
998       .Default("");
999   }
1000
1001   // FIXME: Warn on inconsistent use of -march and -mabi.
1002 }
1003
1004 // Convert ABI name to the GNU tools acceptable variant.
1005 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1006   return llvm::StringSwitch<llvm::StringRef>(ABI)
1007     .Case("o32", "32")
1008     .Case("n64", "64")
1009     .Default(ABI);
1010 }
1011
1012 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1013 // and -mfloat-abi=.
1014 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
1015   StringRef FloatABI;
1016   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1017                                options::OPT_mhard_float,
1018                                options::OPT_mfloat_abi_EQ)) {
1019     if (A->getOption().matches(options::OPT_msoft_float))
1020       FloatABI = "soft";
1021     else if (A->getOption().matches(options::OPT_mhard_float))
1022       FloatABI = "hard";
1023     else {
1024       FloatABI = A->getValue();
1025       if (FloatABI != "soft" && FloatABI != "hard") {
1026         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1027         FloatABI = "hard";
1028       }
1029     }
1030   }
1031
1032   // If unspecified, choose the default based on the platform.
1033   if (FloatABI.empty()) {
1034     // Assume "hard", because it's a default value used by gcc.
1035     // When we start to recognize specific target MIPS processors,
1036     // we will be able to select the default more correctly.
1037     FloatABI = "hard";
1038   }
1039
1040   return FloatABI;
1041 }
1042
1043 static void AddTargetFeature(const ArgList &Args,
1044                              std::vector<const char *> &Features,
1045                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1046                              StringRef FeatureName) {
1047   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1048     if (A->getOption().matches(OnOpt))
1049       Features.push_back(Args.MakeArgString("+" + FeatureName));
1050     else
1051       Features.push_back(Args.MakeArgString("-" + FeatureName));
1052   }
1053 }
1054
1055 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1056                                   const ArgList &Args,
1057                                   std::vector<const char *> &Features) {
1058   StringRef CPUName;
1059   StringRef ABIName;
1060   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1061   ABIName = getGnuCompatibleMipsABIName(ABIName);
1062
1063   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1064                    options::OPT_mabicalls, "noabicalls");
1065
1066   StringRef FloatABI = getMipsFloatABI(D, Args);
1067   if (FloatABI == "soft") {
1068     // FIXME: Note, this is a hack. We need to pass the selected float
1069     // mode to the MipsTargetInfoBase to define appropriate macros there.
1070     // Now it is the only method.
1071     Features.push_back("+soft-float");
1072   }
1073
1074   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1075     StringRef Val = StringRef(A->getValue());
1076     if (Val == "2008") {
1077       if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1078         Features.push_back("+nan2008");
1079       else {
1080         Features.push_back("-nan2008");
1081         D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1082       }
1083     } else if (Val == "legacy") {
1084       if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1085         Features.push_back("-nan2008");
1086       else {
1087         Features.push_back("+nan2008");
1088         D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1089       }
1090     } else
1091       D.Diag(diag::err_drv_unsupported_option_argument)
1092           << A->getOption().getName() << Val;
1093   }
1094
1095   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1096                    options::OPT_mdouble_float, "single-float");
1097   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1098                    "mips16");
1099   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1100                    options::OPT_mno_micromips, "micromips");
1101   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1102                    "dsp");
1103   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1104                    "dspr2");
1105   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1106                    "msa");
1107
1108   // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1109   // pass -mfpxx
1110   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1111                                options::OPT_mfp64)) {
1112     if (A->getOption().matches(options::OPT_mfp32))
1113       Features.push_back(Args.MakeArgString("-fp64"));
1114     else if (A->getOption().matches(options::OPT_mfpxx)) {
1115       Features.push_back(Args.MakeArgString("+fpxx"));
1116       Features.push_back(Args.MakeArgString("+nooddspreg"));
1117     } else
1118       Features.push_back(Args.MakeArgString("+fp64"));
1119   } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1120     Features.push_back(Args.MakeArgString("+fpxx"));
1121     Features.push_back(Args.MakeArgString("+nooddspreg"));
1122   }
1123
1124   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1125                    options::OPT_modd_spreg, "nooddspreg");
1126 }
1127
1128 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1129                               ArgStringList &CmdArgs) const {
1130   const Driver &D = getToolChain().getDriver();
1131   StringRef CPUName;
1132   StringRef ABIName;
1133   const llvm::Triple &Triple = getToolChain().getTriple();
1134   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1135
1136   CmdArgs.push_back("-target-abi");
1137   CmdArgs.push_back(ABIName.data());
1138
1139   StringRef FloatABI = getMipsFloatABI(D, Args);
1140
1141   if (FloatABI == "soft") {
1142     // Floating point operations and argument passing are soft.
1143     CmdArgs.push_back("-msoft-float");
1144     CmdArgs.push_back("-mfloat-abi");
1145     CmdArgs.push_back("soft");
1146   }
1147   else {
1148     // Floating point operations and argument passing are hard.
1149     assert(FloatABI == "hard" && "Invalid float abi!");
1150     CmdArgs.push_back("-mfloat-abi");
1151     CmdArgs.push_back("hard");
1152   }
1153
1154   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1155     if (A->getOption().matches(options::OPT_mxgot)) {
1156       CmdArgs.push_back("-mllvm");
1157       CmdArgs.push_back("-mxgot");
1158     }
1159   }
1160
1161   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1162                                options::OPT_mno_ldc1_sdc1)) {
1163     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1164       CmdArgs.push_back("-mllvm");
1165       CmdArgs.push_back("-mno-ldc1-sdc1");
1166     }
1167   }
1168
1169   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1170                                options::OPT_mno_check_zero_division)) {
1171     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1172       CmdArgs.push_back("-mllvm");
1173       CmdArgs.push_back("-mno-check-zero-division");
1174     }
1175   }
1176
1177   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1178     StringRef v = A->getValue();
1179     CmdArgs.push_back("-mllvm");
1180     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1181     A->claim();
1182   }
1183 }
1184
1185 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1186 static std::string getPPCTargetCPU(const ArgList &Args) {
1187   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1188     StringRef CPUName = A->getValue();
1189
1190     if (CPUName == "native") {
1191       std::string CPU = llvm::sys::getHostCPUName();
1192       if (!CPU.empty() && CPU != "generic")
1193         return CPU;
1194       else
1195         return "";
1196     }
1197
1198     return llvm::StringSwitch<const char *>(CPUName)
1199       .Case("common", "generic")
1200       .Case("440", "440")
1201       .Case("440fp", "440")
1202       .Case("450", "450")
1203       .Case("601", "601")
1204       .Case("602", "602")
1205       .Case("603", "603")
1206       .Case("603e", "603e")
1207       .Case("603ev", "603ev")
1208       .Case("604", "604")
1209       .Case("604e", "604e")
1210       .Case("620", "620")
1211       .Case("630", "pwr3")
1212       .Case("G3", "g3")
1213       .Case("7400", "7400")
1214       .Case("G4", "g4")
1215       .Case("7450", "7450")
1216       .Case("G4+", "g4+")
1217       .Case("750", "750")
1218       .Case("970", "970")
1219       .Case("G5", "g5")
1220       .Case("a2", "a2")
1221       .Case("a2q", "a2q")
1222       .Case("e500mc", "e500mc")
1223       .Case("e5500", "e5500")
1224       .Case("power3", "pwr3")
1225       .Case("power4", "pwr4")
1226       .Case("power5", "pwr5")
1227       .Case("power5x", "pwr5x")
1228       .Case("power6", "pwr6")
1229       .Case("power6x", "pwr6x")
1230       .Case("power7", "pwr7")
1231       .Case("power8", "pwr8")
1232       .Case("pwr3", "pwr3")
1233       .Case("pwr4", "pwr4")
1234       .Case("pwr5", "pwr5")
1235       .Case("pwr5x", "pwr5x")
1236       .Case("pwr6", "pwr6")
1237       .Case("pwr6x", "pwr6x")
1238       .Case("pwr7", "pwr7")
1239       .Case("pwr8", "pwr8")
1240       .Case("powerpc", "ppc")
1241       .Case("powerpc64", "ppc64")
1242       .Case("powerpc64le", "ppc64le")
1243       .Default("");
1244   }
1245
1246   return "";
1247 }
1248
1249 static void getPPCTargetFeatures(const ArgList &Args,
1250                                  std::vector<const char *> &Features) {
1251   for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
1252     StringRef Name = A->getOption().getName();
1253     A->claim();
1254
1255     // Skip over "-m".
1256     assert(Name.startswith("m") && "Invalid feature name.");
1257     Name = Name.substr(1);
1258
1259     bool IsNegative = Name.startswith("no-");
1260     if (IsNegative)
1261       Name = Name.substr(3);
1262
1263     // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1264     // pass the correct option to the backend while calling the frontend
1265     // option the same.
1266     // TODO: Change the LLVM backend option maybe?
1267     if (Name == "mfcrf")
1268       Name = "mfocrf";
1269
1270     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1271   }
1272
1273   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1274   AddTargetFeature(Args, Features, options::OPT_faltivec,
1275                    options::OPT_fno_altivec, "altivec");
1276 }
1277
1278 void Clang::AddPPCTargetArgs(const ArgList &Args,
1279                              ArgStringList &CmdArgs) const {
1280   // Select the ABI to use.
1281   const char *ABIName = nullptr;
1282   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1283     ABIName = A->getValue();
1284   } else if (getToolChain().getTriple().isOSLinux())
1285     switch(getToolChain().getArch()) {
1286     case llvm::Triple::ppc64: {
1287       // When targeting a processor that supports QPX, or if QPX is
1288       // specifically enabled, default to using the ABI that supports QPX (so
1289       // long as it is not specifically disabled).
1290       bool HasQPX = false;
1291       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1292         HasQPX = A->getValue() == StringRef("a2q");
1293       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1294       if (HasQPX) {
1295         ABIName = "elfv1-qpx";
1296         break;
1297       }
1298
1299       ABIName = "elfv1";
1300       break;
1301     }
1302     case llvm::Triple::ppc64le:
1303       ABIName = "elfv2";
1304       break;
1305     default:
1306       break;
1307   }
1308
1309   if (ABIName) {
1310     CmdArgs.push_back("-target-abi");
1311     CmdArgs.push_back(ABIName);
1312   }
1313 }
1314
1315 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1316   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1317   return A && (A->getValue() == StringRef(Value));
1318 }
1319
1320 /// Get the (LLVM) name of the R600 gpu we are targeting.
1321 static std::string getR600TargetGPU(const ArgList &Args) {
1322   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1323     const char *GPUName = A->getValue();
1324     return llvm::StringSwitch<const char *>(GPUName)
1325       .Cases("rv630", "rv635", "r600")
1326       .Cases("rv610", "rv620", "rs780", "rs880")
1327       .Case("rv740", "rv770")
1328       .Case("palm", "cedar")
1329       .Cases("sumo", "sumo2", "sumo")
1330       .Case("hemlock", "cypress")
1331       .Case("aruba", "cayman")
1332       .Default(GPUName);
1333   }
1334   return "";
1335 }
1336
1337 void Clang::AddSparcTargetArgs(const ArgList &Args,
1338                              ArgStringList &CmdArgs) const {
1339   const Driver &D = getToolChain().getDriver();
1340   std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1341
1342   bool SoftFloatABI = false;
1343   if (Arg *A =
1344           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1345     if (A->getOption().matches(options::OPT_msoft_float))
1346       SoftFloatABI = true;
1347   }
1348
1349   // Only the hard-float ABI on Sparc is standardized, and it is the
1350   // default. GCC also supports a nonstandard soft-float ABI mode, and
1351   // perhaps LLVM should implement that, too. However, since llvm
1352   // currently does not support Sparc soft-float, at all, display an
1353   // error if it's requested.
1354   if (SoftFloatABI) {
1355     D.Diag(diag::err_drv_unsupported_opt_for_target)
1356         << "-msoft-float" << Triple;
1357   }
1358 }
1359
1360 static const char *getSystemZTargetCPU(const ArgList &Args) {
1361   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1362     return A->getValue();
1363   return "z10";
1364 }
1365
1366 static void getSystemZTargetFeatures(const ArgList &Args,
1367                                      std::vector<const char *> &Features) {
1368   // -m(no-)htm overrides use of the transactional-execution facility.
1369   if (Arg *A = Args.getLastArg(options::OPT_mhtm,
1370                                options::OPT_mno_htm)) {
1371     if (A->getOption().matches(options::OPT_mhtm))
1372       Features.push_back("+transactional-execution");
1373     else
1374       Features.push_back("-transactional-execution");
1375   }
1376   // -m(no-)vx overrides use of the vector facility.
1377   if (Arg *A = Args.getLastArg(options::OPT_mvx,
1378                                options::OPT_mno_vx)) {
1379     if (A->getOption().matches(options::OPT_mvx))
1380       Features.push_back("+vector");
1381     else
1382       Features.push_back("-vector");
1383   }
1384 }
1385
1386 static const char *getX86TargetCPU(const ArgList &Args,
1387                                    const llvm::Triple &Triple) {
1388   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1389     if (StringRef(A->getValue()) != "native") {
1390       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1391         return "core-avx2";
1392
1393       return A->getValue();
1394     }
1395
1396     // FIXME: Reject attempts to use -march=native unless the target matches
1397     // the host.
1398     //
1399     // FIXME: We should also incorporate the detected target features for use
1400     // with -native.
1401     std::string CPU = llvm::sys::getHostCPUName();
1402     if (!CPU.empty() && CPU != "generic")
1403       return Args.MakeArgString(CPU);
1404   }
1405
1406   // Select the default CPU if none was given (or detection failed).
1407
1408   if (Triple.getArch() != llvm::Triple::x86_64 &&
1409       Triple.getArch() != llvm::Triple::x86)
1410     return nullptr; // This routine is only handling x86 targets.
1411
1412   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1413
1414   // FIXME: Need target hooks.
1415   if (Triple.isOSDarwin()) {
1416     if (Triple.getArchName() == "x86_64h")
1417       return "core-avx2";
1418     return Is64Bit ? "core2" : "yonah";
1419   }
1420
1421   // Set up default CPU name for PS4 compilers.
1422   if (Triple.isPS4CPU())
1423     return "btver2";
1424
1425   // On Android use targets compatible with gcc
1426   if (Triple.getEnvironment() == llvm::Triple::Android)
1427     return Is64Bit ? "x86-64" : "i686";
1428
1429   // Everything else goes to x86-64 in 64-bit mode.
1430   if (Is64Bit)
1431     return "x86-64";
1432
1433   switch (Triple.getOS()) {
1434   case llvm::Triple::FreeBSD:
1435   case llvm::Triple::NetBSD:
1436   case llvm::Triple::OpenBSD:
1437     return "i486";
1438   case llvm::Triple::Haiku:
1439     return "i586";
1440   case llvm::Triple::Bitrig:
1441     return "i686";
1442   default:
1443     // Fallback to p4.
1444     return "pentium4";
1445   }
1446 }
1447
1448 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1449   switch(T.getArch()) {
1450   default:
1451     return "";
1452
1453   case llvm::Triple::aarch64:
1454   case llvm::Triple::aarch64_be:
1455     return getAArch64TargetCPU(Args);
1456
1457   case llvm::Triple::arm:
1458   case llvm::Triple::armeb:
1459   case llvm::Triple::thumb:
1460   case llvm::Triple::thumbeb:
1461     return arm::getARMTargetCPU(Args, T);
1462
1463   case llvm::Triple::mips:
1464   case llvm::Triple::mipsel:
1465   case llvm::Triple::mips64:
1466   case llvm::Triple::mips64el: {
1467     StringRef CPUName;
1468     StringRef ABIName;
1469     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1470     return CPUName;
1471   }
1472
1473   case llvm::Triple::ppc:
1474   case llvm::Triple::ppc64:
1475   case llvm::Triple::ppc64le: {
1476     std::string TargetCPUName = getPPCTargetCPU(Args);
1477     // LLVM may default to generating code for the native CPU,
1478     // but, like gcc, we default to a more generic option for
1479     // each architecture. (except on Darwin)
1480     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1481       if (T.getArch() == llvm::Triple::ppc64)
1482         TargetCPUName = "ppc64";
1483       else if (T.getArch() == llvm::Triple::ppc64le)
1484         TargetCPUName = "ppc64le";
1485       else
1486         TargetCPUName = "ppc";
1487     }
1488     return TargetCPUName;
1489   }
1490
1491   case llvm::Triple::sparc:
1492   case llvm::Triple::sparcel:
1493   case llvm::Triple::sparcv9:
1494     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1495       return A->getValue();
1496     return "";
1497
1498   case llvm::Triple::x86:
1499   case llvm::Triple::x86_64:
1500     return getX86TargetCPU(Args, T);
1501
1502   case llvm::Triple::hexagon:
1503     return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1504
1505   case llvm::Triple::systemz:
1506     return getSystemZTargetCPU(Args);
1507
1508   case llvm::Triple::r600:
1509   case llvm::Triple::amdgcn:
1510     return getR600TargetGPU(Args);
1511   }
1512 }
1513
1514 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1515                           ArgStringList &CmdArgs) {
1516   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1517   // as gold requires -plugin to come before any -plugin-opt that -Wl might
1518   // forward.
1519   CmdArgs.push_back("-plugin");
1520   std::string Plugin = ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1521   CmdArgs.push_back(Args.MakeArgString(Plugin));
1522
1523   // Try to pass driver level flags relevant to LTO code generation down to
1524   // the plugin.
1525
1526   // Handle flags for selecting CPU variants.
1527   std::string CPU = getCPUName(Args, ToolChain.getTriple());
1528   if (!CPU.empty())
1529     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1530 }
1531
1532 /// This is a helper function for validating the optional refinement step
1533 /// parameter in reciprocal argument strings. Return false if there is an error
1534 /// parsing the refinement step. Otherwise, return true and set the Position
1535 /// of the refinement step in the input string.
1536 static bool getRefinementStep(const StringRef &In, const Driver &D,
1537                                 const Arg &A, size_t &Position) {
1538   const char RefinementStepToken = ':';
1539   Position = In.find(RefinementStepToken);
1540   if (Position != StringRef::npos) {
1541     StringRef Option = A.getOption().getName();
1542     StringRef RefStep = In.substr(Position + 1);
1543     // Allow exactly one numeric character for the additional refinement
1544     // step parameter. This is reasonable for all currently-supported
1545     // operations and architectures because we would expect that a larger value
1546     // of refinement steps would cause the estimate "optimization" to
1547     // under-perform the native operation. Also, if the estimate does not
1548     // converge quickly, it probably will not ever converge, so further
1549     // refinement steps will not produce a better answer.
1550     if (RefStep.size() != 1) {
1551       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1552       return false;
1553     }
1554     char RefStepChar = RefStep[0];
1555     if (RefStepChar < '0' || RefStepChar > '9') {
1556       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1557       return false;
1558     }
1559   }
1560   return true;
1561 }
1562
1563 /// The -mrecip flag requires processing of many optional parameters.
1564 static void ParseMRecip(const Driver &D, const ArgList &Args,
1565                         ArgStringList &OutStrings) {
1566   StringRef DisabledPrefixIn = "!";
1567   StringRef DisabledPrefixOut = "!";
1568   StringRef EnabledPrefixOut = "";
1569   StringRef Out = "-mrecip=";
1570
1571   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1572   if (!A)
1573     return;
1574
1575   unsigned NumOptions = A->getNumValues();
1576   if (NumOptions == 0) {
1577     // No option is the same as "all".
1578     OutStrings.push_back(Args.MakeArgString(Out + "all"));
1579     return;
1580   }
1581
1582   // Pass through "all", "none", or "default" with an optional refinement step.
1583   if (NumOptions == 1) {
1584     StringRef Val = A->getValue(0);
1585     size_t RefStepLoc;
1586     if (!getRefinementStep(Val, D, *A, RefStepLoc))
1587       return;
1588     StringRef ValBase = Val.slice(0, RefStepLoc);
1589     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1590       OutStrings.push_back(Args.MakeArgString(Out + Val));
1591       return;
1592     }
1593   }
1594
1595   // Each reciprocal type may be enabled or disabled individually.
1596   // Check each input value for validity, concatenate them all back together,
1597   // and pass through.
1598
1599   llvm::StringMap<bool> OptionStrings;
1600   OptionStrings.insert(std::make_pair("divd",       false));
1601   OptionStrings.insert(std::make_pair("divf",       false));
1602   OptionStrings.insert(std::make_pair("vec-divd",   false));
1603   OptionStrings.insert(std::make_pair("vec-divf",   false));
1604   OptionStrings.insert(std::make_pair("sqrtd",      false));
1605   OptionStrings.insert(std::make_pair("sqrtf",      false));
1606   OptionStrings.insert(std::make_pair("vec-sqrtd",  false));
1607   OptionStrings.insert(std::make_pair("vec-sqrtf",  false));
1608
1609   for (unsigned i = 0; i != NumOptions; ++i) {
1610     StringRef Val = A->getValue(i);
1611
1612     bool IsDisabled = Val.startswith(DisabledPrefixIn);
1613     // Ignore the disablement token for string matching.
1614     if (IsDisabled)
1615       Val = Val.substr(1);
1616
1617     size_t RefStep;
1618     if (!getRefinementStep(Val, D, *A, RefStep))
1619       return;
1620
1621     StringRef ValBase = Val.slice(0, RefStep);
1622     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1623     if (OptionIter == OptionStrings.end()) {
1624       // Try again specifying float suffix.
1625       OptionIter = OptionStrings.find(ValBase.str() + 'f');
1626       if (OptionIter == OptionStrings.end()) {
1627         // The input name did not match any known option string.
1628         D.Diag(diag::err_drv_unknown_argument) << Val;
1629         return;
1630       }
1631       // The option was specified without a float or double suffix.
1632       // Make sure that the double entry was not already specified.
1633       // The float entry will be checked below.
1634       if (OptionStrings[ValBase.str() + 'd']) {
1635         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1636         return;
1637       }
1638     }
1639     
1640     if (OptionIter->second == true) {
1641       // Duplicate option specified.
1642       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1643       return;
1644     }
1645
1646     // Mark the matched option as found. Do not allow duplicate specifiers.
1647     OptionIter->second = true;
1648
1649     // If the precision was not specified, also mark the double entry as found.
1650     if (ValBase.back() != 'f' && ValBase.back() != 'd')
1651       OptionStrings[ValBase.str() + 'd'] = true;
1652
1653     // Build the output string.
1654     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1655     Out = Args.MakeArgString(Out + Prefix + Val);
1656     if (i != NumOptions - 1)
1657       Out = Args.MakeArgString(Out + ",");
1658   }
1659
1660   OutStrings.push_back(Args.MakeArgString(Out));
1661 }
1662
1663 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1664                                  const ArgList &Args,
1665                                  std::vector<const char *> &Features) {
1666   // If -march=native, autodetect the feature list.
1667   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1668     if (StringRef(A->getValue()) == "native") {
1669       llvm::StringMap<bool> HostFeatures;
1670       if (llvm::sys::getHostCPUFeatures(HostFeatures))
1671         for (auto &F : HostFeatures)
1672           Features.push_back(Args.MakeArgString((F.second ? "+" : "-") +
1673                                                 F.first()));
1674     }
1675   }
1676
1677   if (Triple.getArchName() == "x86_64h") {
1678     // x86_64h implies quite a few of the more modern subtarget features
1679     // for Haswell class CPUs, but not all of them. Opt-out of a few.
1680     Features.push_back("-rdrnd");
1681     Features.push_back("-aes");
1682     Features.push_back("-pclmul");
1683     Features.push_back("-rtm");
1684     Features.push_back("-hle");
1685     Features.push_back("-fsgsbase");
1686   }
1687
1688   const llvm::Triple::ArchType ArchType = Triple.getArch();
1689   // Add features to be compatible with gcc for Android.
1690   if (Triple.getEnvironment() == llvm::Triple::Android) {
1691     if (ArchType == llvm::Triple::x86_64) {
1692       Features.push_back("+sse4.2");
1693       Features.push_back("+popcnt");
1694     } else
1695       Features.push_back("+ssse3");
1696   }
1697
1698   // Set features according to the -arch flag on MSVC.
1699   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1700     StringRef Arch = A->getValue();
1701     bool ArchUsed = false;
1702     // First, look for flags that are shared in x86 and x86-64.
1703     if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1704       if (Arch == "AVX" || Arch == "AVX2") {
1705         ArchUsed = true;
1706         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1707       }
1708     }
1709     // Then, look for x86-specific flags.
1710     if (ArchType == llvm::Triple::x86) {
1711       if (Arch == "IA32") {
1712         ArchUsed = true;
1713       } else if (Arch == "SSE" || Arch == "SSE2") {
1714         ArchUsed = true;
1715         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1716       }
1717     }
1718     if (!ArchUsed)
1719       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1720   }
1721
1722   // Now add any that the user explicitly requested on the command line,
1723   // which may override the defaults.
1724   for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
1725     StringRef Name = A->getOption().getName();
1726     A->claim();
1727
1728     // Skip over "-m".
1729     assert(Name.startswith("m") && "Invalid feature name.");
1730     Name = Name.substr(1);
1731
1732     bool IsNegative = Name.startswith("no-");
1733     if (IsNegative)
1734       Name = Name.substr(3);
1735
1736     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1737   }
1738 }
1739
1740 void Clang::AddX86TargetArgs(const ArgList &Args,
1741                              ArgStringList &CmdArgs) const {
1742   if (!Args.hasFlag(options::OPT_mred_zone,
1743                     options::OPT_mno_red_zone,
1744                     true) ||
1745       Args.hasArg(options::OPT_mkernel) ||
1746       Args.hasArg(options::OPT_fapple_kext))
1747     CmdArgs.push_back("-disable-red-zone");
1748
1749   // Default to avoid implicit floating-point for kernel/kext code, but allow
1750   // that to be overridden with -mno-soft-float.
1751   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1752                           Args.hasArg(options::OPT_fapple_kext));
1753   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1754                                options::OPT_mno_soft_float,
1755                                options::OPT_mimplicit_float,
1756                                options::OPT_mno_implicit_float)) {
1757     const Option &O = A->getOption();
1758     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1759                        O.matches(options::OPT_msoft_float));
1760   }
1761   if (NoImplicitFloat)
1762     CmdArgs.push_back("-no-implicit-float");
1763
1764   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1765     StringRef Value = A->getValue();
1766     if (Value == "intel" || Value == "att") {
1767       CmdArgs.push_back("-mllvm");
1768       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1769     } else {
1770       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1771           << A->getOption().getName() << Value;
1772     }
1773   }
1774 }
1775
1776 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1777                                  ArgStringList &CmdArgs) const {
1778   CmdArgs.push_back("-mqdsp6-compat");
1779   CmdArgs.push_back("-Wreturn-type");
1780
1781   if (const char* v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
1782     std::string SmallDataThreshold="-hexagon-small-data-threshold=";
1783     SmallDataThreshold += v;
1784     CmdArgs.push_back ("-mllvm");
1785     CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
1786   }
1787
1788   if (!Args.hasArg(options::OPT_fno_short_enums))
1789     CmdArgs.push_back("-fshort-enums");
1790   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1791     CmdArgs.push_back ("-mllvm");
1792     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
1793   }
1794   CmdArgs.push_back ("-mllvm");
1795   CmdArgs.push_back ("-machine-sink-split=0");
1796 }
1797
1798 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
1799 static bool DecodeAArch64Features(const Driver &D, StringRef text,
1800                                   std::vector<const char *> &Features) {
1801   SmallVector<StringRef, 8> Split;
1802   text.split(Split, StringRef("+"), -1, false);
1803
1804   for (unsigned I = 0, E = Split.size(); I != E; ++I) {
1805     const char *result = llvm::StringSwitch<const char *>(Split[I])
1806                              .Case("fp", "+fp-armv8")
1807                              .Case("simd", "+neon")
1808                              .Case("crc", "+crc")
1809                              .Case("crypto", "+crypto")
1810                              .Case("nofp", "-fp-armv8")
1811                              .Case("nosimd", "-neon")
1812                              .Case("nocrc", "-crc")
1813                              .Case("nocrypto", "-crypto")
1814                              .Default(nullptr);
1815     if (result)
1816       Features.push_back(result);
1817     else if (Split[I] == "neon" || Split[I] == "noneon")
1818       D.Diag(diag::err_drv_no_neon_modifier);
1819     else
1820       return false;
1821   }
1822   return true;
1823 }
1824
1825 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1826 // decode CPU and feature.
1827 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1828                               std::vector<const char *> &Features) {
1829   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1830   CPU = Split.first;
1831   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" || CPU == "cortex-a72") {
1832     Features.push_back("+neon");
1833     Features.push_back("+crc");
1834     Features.push_back("+crypto");
1835   } else if (CPU == "generic") {
1836     Features.push_back("+neon");
1837   } else {
1838     return false;
1839   }
1840
1841   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1842     return false;
1843
1844   return true;
1845 }
1846
1847 static bool
1848 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1849                                 const ArgList &Args,
1850                                 std::vector<const char *> &Features) {
1851   std::string MarchLowerCase = March.lower();
1852   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
1853
1854   if (Split.first == "armv8-a" ||
1855       Split.first == "armv8a") {
1856     // ok, no additional features.
1857   } else if (
1858       Split.first == "armv8.1-a" ||
1859       Split.first == "armv8.1a" ) {
1860     Features.push_back("+v8.1a");
1861   } else {
1862     return false;
1863   }
1864
1865   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1866     return false;
1867
1868   return true;
1869 }
1870
1871 static bool
1872 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1873                                const ArgList &Args,
1874                                std::vector<const char *> &Features) {
1875   StringRef CPU;
1876   std::string McpuLowerCase = Mcpu.lower();
1877   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
1878     return false;
1879
1880   return true;
1881 }
1882
1883 static bool
1884 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
1885                                      const ArgList &Args,
1886                                      std::vector<const char *> &Features) {
1887   // Handle CPU name is 'native'.
1888   if (Mtune == "native")
1889     Mtune = llvm::sys::getHostCPUName();
1890   if (Mtune == "cyclone") {
1891     Features.push_back("+zcm");
1892     Features.push_back("+zcz");
1893   }
1894   return true;
1895 }
1896
1897 static bool
1898 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1899                                     const ArgList &Args,
1900                                     std::vector<const char *> &Features) {
1901   StringRef CPU;
1902   std::vector<const char *> DecodedFeature;
1903   std::string McpuLowerCase = Mcpu.lower();
1904   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
1905     return false;
1906
1907   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
1908 }
1909
1910 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1911                                      std::vector<const char *> &Features) {
1912   Arg *A;
1913   bool success = true;
1914   // Enable NEON by default.
1915   Features.push_back("+neon");
1916   if ((A = Args.getLastArg(options::OPT_march_EQ)))
1917     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
1918   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
1919     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1920   else if (Args.hasArg(options::OPT_arch))
1921     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
1922                                              Features);
1923
1924   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
1925     success =
1926         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
1927   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
1928     success =
1929         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1930   else if (Args.hasArg(options::OPT_arch))
1931     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
1932                                                   Args, Features);
1933
1934   if (!success)
1935     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
1936
1937   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
1938     Features.push_back("-fp-armv8");
1939     Features.push_back("-crypto");
1940     Features.push_back("-neon");
1941   }
1942
1943   // En/disable crc
1944   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
1945                                options::OPT_mnocrc)) {
1946     if (A->getOption().matches(options::OPT_mcrc))
1947       Features.push_back("+crc");
1948     else
1949       Features.push_back("-crc");
1950   }
1951 }
1952
1953 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1954                               const ArgList &Args, ArgStringList &CmdArgs,
1955                               bool ForAS) {
1956   std::vector<const char *> Features;
1957   switch (Triple.getArch()) {
1958   default:
1959     break;
1960   case llvm::Triple::mips:
1961   case llvm::Triple::mipsel:
1962   case llvm::Triple::mips64:
1963   case llvm::Triple::mips64el:
1964     getMIPSTargetFeatures(D, Triple, Args, Features);
1965     break;
1966
1967   case llvm::Triple::arm:
1968   case llvm::Triple::armeb:
1969   case llvm::Triple::thumb:
1970   case llvm::Triple::thumbeb:
1971     getARMTargetFeatures(D, Triple, Args, Features, ForAS);
1972     break;
1973
1974   case llvm::Triple::ppc:
1975   case llvm::Triple::ppc64:
1976   case llvm::Triple::ppc64le:
1977     getPPCTargetFeatures(Args, Features);
1978     break;
1979   case llvm::Triple::systemz:
1980     getSystemZTargetFeatures(Args, Features);
1981     break;
1982   case llvm::Triple::aarch64:
1983   case llvm::Triple::aarch64_be:
1984     getAArch64TargetFeatures(D, Args, Features);
1985     break;
1986   case llvm::Triple::x86:
1987   case llvm::Triple::x86_64:
1988     getX86TargetFeatures(D, Triple, Args, Features);
1989     break;
1990   }
1991
1992   // Find the last of each feature.
1993   llvm::StringMap<unsigned> LastOpt;
1994   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1995     const char *Name = Features[I];
1996     assert(Name[0] == '-' || Name[0] == '+');
1997     LastOpt[Name + 1] = I;
1998   }
1999
2000   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2001     // If this feature was overridden, ignore it.
2002     const char *Name = Features[I];
2003     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2004     assert(LastI != LastOpt.end());
2005     unsigned Last = LastI->second;
2006     if (Last != I)
2007       continue;
2008
2009     CmdArgs.push_back("-target-feature");
2010     CmdArgs.push_back(Name);
2011   }
2012 }
2013
2014 static bool
2015 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2016                                           const llvm::Triple &Triple) {
2017   // We use the zero-cost exception tables for Objective-C if the non-fragile
2018   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2019   // later.
2020   if (runtime.isNonFragile())
2021     return true;
2022
2023   if (!Triple.isMacOSX())
2024     return false;
2025
2026   return (!Triple.isMacOSXVersionLT(10,5) &&
2027           (Triple.getArch() == llvm::Triple::x86_64 ||
2028            Triple.getArch() == llvm::Triple::arm));
2029 }
2030
2031 // exceptionSettings() exists to share the logic between -cc1 and linker
2032 // invocations.
2033 static bool exceptionSettings(const ArgList &Args, const llvm::Triple &Triple) {
2034   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
2035                                options::OPT_fno_exceptions))
2036     if (A->getOption().matches(options::OPT_fexceptions))
2037       return true;
2038
2039   return false;
2040 }
2041
2042 /// Adds exception related arguments to the driver command arguments. There's a
2043 /// master flag, -fexceptions and also language specific flags to enable/disable
2044 /// C++ and Objective-C exceptions. This makes it possible to for example
2045 /// disable C++ exceptions but enable Objective-C exceptions.
2046 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2047                              const ToolChain &TC, bool KernelOrKext,
2048                              const ObjCRuntime &objcRuntime,
2049                              ArgStringList &CmdArgs) {
2050   const Driver &D = TC.getDriver();
2051   const llvm::Triple &Triple = TC.getTriple();
2052
2053   if (KernelOrKext) {
2054     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2055     // arguments now to avoid warnings about unused arguments.
2056     Args.ClaimAllArgs(options::OPT_fexceptions);
2057     Args.ClaimAllArgs(options::OPT_fno_exceptions);
2058     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2059     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2060     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2061     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2062     return;
2063   }
2064
2065   // Gather the exception settings from the command line arguments.
2066   bool EH = exceptionSettings(Args, Triple);
2067
2068   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2069   // is not necessarily sensible, but follows GCC.
2070   if (types::isObjC(InputType) &&
2071       Args.hasFlag(options::OPT_fobjc_exceptions,
2072                    options::OPT_fno_objc_exceptions,
2073                    true)) {
2074     CmdArgs.push_back("-fobjc-exceptions");
2075
2076     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2077   }
2078
2079   if (types::isCXX(InputType)) {
2080     bool CXXExceptionsEnabled =
2081         Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2082     Arg *ExceptionArg = Args.getLastArg(
2083         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2084         options::OPT_fexceptions, options::OPT_fno_exceptions);
2085     if (ExceptionArg)
2086       CXXExceptionsEnabled =
2087           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2088           ExceptionArg->getOption().matches(options::OPT_fexceptions);
2089
2090     if (CXXExceptionsEnabled) {
2091       if (Triple.isPS4CPU()) {
2092         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2093         assert(ExceptionArg &&
2094                "On the PS4 exceptions should only be enabled if passing "
2095                "an argument");
2096         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2097           const Arg *RTTIArg = TC.getRTTIArg();
2098           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2099           D.Diag(diag::err_drv_argument_not_allowed_with)
2100               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2101         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2102           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2103       } else
2104         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2105
2106       CmdArgs.push_back("-fcxx-exceptions");
2107
2108       EH = true;
2109     }
2110   }
2111
2112   if (EH)
2113     CmdArgs.push_back("-fexceptions");
2114 }
2115
2116 static bool ShouldDisableAutolink(const ArgList &Args,
2117                              const ToolChain &TC) {
2118   bool Default = true;
2119   if (TC.getTriple().isOSDarwin()) {
2120     // The native darwin assembler doesn't support the linker_option directives,
2121     // so we disable them if we think the .s file will be passed to it.
2122     Default = TC.useIntegratedAs();
2123   }
2124   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2125                        Default);
2126 }
2127
2128 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2129                                         const ToolChain &TC) {
2130   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
2131                                         options::OPT_fno_dwarf_directory_asm,
2132                                         TC.useIntegratedAs());
2133   return !UseDwarfDirectory;
2134 }
2135
2136 /// \brief Check whether the given input tree contains any compilation actions.
2137 static bool ContainsCompileAction(const Action *A) {
2138   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2139     return true;
2140
2141   for (const auto &Act : *A)
2142     if (ContainsCompileAction(Act))
2143       return true;
2144
2145   return false;
2146 }
2147
2148 /// \brief Check if -relax-all should be passed to the internal assembler.
2149 /// This is done by default when compiling non-assembler source with -O0.
2150 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2151   bool RelaxDefault = true;
2152
2153   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2154     RelaxDefault = A->getOption().matches(options::OPT_O0);
2155
2156   if (RelaxDefault) {
2157     RelaxDefault = false;
2158     for (const auto &Act : C.getActions()) {
2159       if (ContainsCompileAction(Act)) {
2160         RelaxDefault = true;
2161         break;
2162       }
2163     }
2164   }
2165
2166   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2167     RelaxDefault);
2168 }
2169
2170 static void CollectArgsForIntegratedAssembler(Compilation &C,
2171                                               const ArgList &Args,
2172                                               ArgStringList &CmdArgs,
2173                                               const Driver &D) {
2174     if (UseRelaxAll(C, Args))
2175       CmdArgs.push_back("-mrelax-all");
2176
2177     // When passing -I arguments to the assembler we sometimes need to
2178     // unconditionally take the next argument.  For example, when parsing
2179     // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2180     // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2181     // arg after parsing the '-I' arg.
2182     bool TakeNextArg = false;
2183
2184     // When using an integrated assembler, translate -Wa, and -Xassembler
2185     // options.
2186     bool CompressDebugSections = false;
2187     for (const Arg *A :
2188          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2189       A->claim();
2190
2191       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
2192         StringRef Value = A->getValue(i);
2193         if (TakeNextArg) {
2194           CmdArgs.push_back(Value.data());
2195           TakeNextArg = false;
2196           continue;
2197         }
2198
2199         if (Value == "-force_cpusubtype_ALL") {
2200           // Do nothing, this is the default and we don't support anything else.
2201         } else if (Value == "-L") {
2202           CmdArgs.push_back("-msave-temp-labels");
2203         } else if (Value == "--fatal-warnings") {
2204           CmdArgs.push_back("-massembler-fatal-warnings");
2205         } else if (Value == "--noexecstack") {
2206           CmdArgs.push_back("-mnoexecstack");
2207         } else if (Value == "-compress-debug-sections" ||
2208                    Value == "--compress-debug-sections") {
2209           CompressDebugSections = true;
2210         } else if (Value == "-nocompress-debug-sections" ||
2211                    Value == "--nocompress-debug-sections") {
2212           CompressDebugSections = false;
2213         } else if (Value.startswith("-I")) {
2214           CmdArgs.push_back(Value.data());
2215           // We need to consume the next argument if the current arg is a plain
2216           // -I. The next arg will be the include directory.
2217           if (Value == "-I")
2218             TakeNextArg = true;
2219         } else if (Value.startswith("-gdwarf-")) {
2220           CmdArgs.push_back(Value.data());
2221         } else {
2222           D.Diag(diag::err_drv_unsupported_option_argument)
2223             << A->getOption().getName() << Value;
2224         }
2225       }
2226     }
2227     if (CompressDebugSections) {
2228       if (llvm::zlib::isAvailable())
2229         CmdArgs.push_back("-compress-debug-sections");
2230       else
2231         D.Diag(diag::warn_debug_compression_unavailable);
2232     }
2233 }
2234
2235 // Until ARM libraries are build separately, we have them all in one library
2236 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2237   // FIXME: handle 64-bit
2238   if (TC.getTriple().isOSWindows() &&
2239       !TC.getTriple().isWindowsItaniumEnvironment())
2240     return "i386";
2241   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
2242     return "arm";
2243   return TC.getArchName();
2244 }
2245
2246 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2247   // The runtimes are located in the OS-specific resource directory.
2248   SmallString<128> Res(TC.getDriver().ResourceDir);
2249   const llvm::Triple &Triple = TC.getTriple();
2250   // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2251   StringRef OSLibName =
2252       (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
2253   llvm::sys::path::append(Res, "lib", OSLibName);
2254   return Res;
2255 }
2256
2257 static SmallString<128> getCompilerRT(const ToolChain &TC, StringRef Component,
2258                                       bool Shared = false) {
2259   const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
2260                         ? "-android"
2261                         : "";
2262
2263   bool IsOSWindows = TC.getTriple().isOSWindows();
2264   StringRef Arch = getArchNameForCompilerRTLib(TC);
2265   const char *Prefix = IsOSWindows ? "" : "lib";
2266   const char *Suffix =
2267       Shared ? (IsOSWindows ? ".dll" : ".so") : (IsOSWindows ? ".lib" : ".a");
2268
2269   SmallString<128> Path = getCompilerRTLibDir(TC);
2270   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
2271                                     Arch + Env + Suffix);
2272
2273   return Path;
2274 }
2275
2276 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2277 // FIXME: Make sure we can also emit shared objects if they're requested
2278 // and available, check for possible errors, etc.
2279 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2280                        ArgStringList &CmdArgs) {
2281   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
2282
2283   if (!TC.getTriple().isOSWindows()) {
2284     // FIXME: why do we link against gcc when we are using compiler-rt?
2285     CmdArgs.push_back("-lgcc_s");
2286     if (TC.getDriver().CCCIsCXX())
2287       CmdArgs.push_back("-lgcc_eh");
2288   }
2289 }
2290
2291 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
2292                          ArgStringList &CmdArgs) {
2293   if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2294                      false) ||
2295         Args.hasArg(options::OPT_fprofile_generate) ||
2296         Args.hasArg(options::OPT_fprofile_instr_generate) ||
2297         Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
2298         Args.hasArg(options::OPT_fcreate_profile) ||
2299         Args.hasArg(options::OPT_coverage)))
2300     return;
2301
2302   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
2303 }
2304
2305 namespace {
2306 enum OpenMPRuntimeKind {
2307   /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2308   /// without knowing what runtime to target.
2309   OMPRT_Unknown,
2310
2311   /// The LLVM OpenMP runtime. When completed and integrated, this will become
2312   /// the default for Clang.
2313   OMPRT_OMP,
2314
2315   /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2316   /// this runtime but can swallow the pragmas, and find and link against the
2317   /// runtime library itself.
2318   OMPRT_GOMP,
2319
2320   /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2321   /// OpenMP runtime. We support this mode for users with existing dependencies
2322   /// on this runtime library name.
2323   OMPRT_IOMP5
2324 };
2325 }
2326
2327 /// Compute the desired OpenMP runtime from the flag provided.
2328 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2329                                           const ArgList &Args) {
2330   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2331
2332   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2333   if (A)
2334     RuntimeName = A->getValue();
2335
2336   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2337       .Case("libomp", OMPRT_OMP)
2338       .Case("libgomp", OMPRT_GOMP)
2339       .Case("libiomp5", OMPRT_IOMP5)
2340       .Default(OMPRT_Unknown);
2341
2342   if (RT == OMPRT_Unknown) {
2343     if (A)
2344       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2345         << A->getOption().getName() << A->getValue();
2346     else
2347       // FIXME: We could use a nicer diagnostic here.
2348       TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2349   }
2350
2351   return RT;
2352 }
2353
2354 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2355                                 ArgStringList &CmdArgs, StringRef Sanitizer,
2356                                 bool IsShared) {
2357   // Static runtimes must be forced into executable, so we wrap them in
2358   // whole-archive.
2359   if (!IsShared)
2360     CmdArgs.push_back("-whole-archive");
2361   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
2362   if (!IsShared)
2363     CmdArgs.push_back("-no-whole-archive");
2364 }
2365
2366 // Tries to use a file with the list of dynamic symbols that need to be exported
2367 // from the runtime library. Returns true if the file was found.
2368 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2369                                     ArgStringList &CmdArgs,
2370                                     StringRef Sanitizer) {
2371   SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
2372   if (llvm::sys::fs::exists(SanRT + ".syms")) {
2373     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2374     return true;
2375   }
2376   return false;
2377 }
2378
2379 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2380                                      ArgStringList &CmdArgs) {
2381   // Force linking against the system libraries sanitizers depends on
2382   // (see PR15823 why this is necessary).
2383   CmdArgs.push_back("--no-as-needed");
2384   CmdArgs.push_back("-lpthread");
2385   CmdArgs.push_back("-lrt");
2386   CmdArgs.push_back("-lm");
2387   // There's no libdl on FreeBSD.
2388   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2389     CmdArgs.push_back("-ldl");
2390 }
2391
2392 static void
2393 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2394                          SmallVectorImpl<StringRef> &SharedRuntimes,
2395                          SmallVectorImpl<StringRef> &StaticRuntimes,
2396                          SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2397   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2398   // Collect shared runtimes.
2399   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2400     SharedRuntimes.push_back("asan");
2401   }
2402
2403   // Collect static runtimes.
2404   if (Args.hasArg(options::OPT_shared) ||
2405       (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
2406     // Don't link static runtimes into DSOs or if compiling for Android.
2407     return;
2408   }
2409   if (SanArgs.needsAsanRt()) {
2410     if (SanArgs.needsSharedAsanRt()) {
2411       HelperStaticRuntimes.push_back("asan-preinit");
2412     } else {
2413       StaticRuntimes.push_back("asan");
2414       if (SanArgs.linkCXXRuntimes())
2415         StaticRuntimes.push_back("asan_cxx");
2416     }
2417   }
2418   if (SanArgs.needsDfsanRt())
2419     StaticRuntimes.push_back("dfsan");
2420   if (SanArgs.needsLsanRt())
2421     StaticRuntimes.push_back("lsan");
2422   if (SanArgs.needsMsanRt()) {
2423     StaticRuntimes.push_back("msan");
2424     if (SanArgs.linkCXXRuntimes())
2425       StaticRuntimes.push_back("msan_cxx");
2426   }
2427   if (SanArgs.needsTsanRt()) {
2428     StaticRuntimes.push_back("tsan");
2429     if (SanArgs.linkCXXRuntimes())
2430       StaticRuntimes.push_back("tsan_cxx");
2431   }
2432   if (SanArgs.needsUbsanRt()) {
2433     StaticRuntimes.push_back("ubsan_standalone");
2434     if (SanArgs.linkCXXRuntimes())
2435       StaticRuntimes.push_back("ubsan_standalone_cxx");
2436   }
2437   if (SanArgs.needsSafeStackRt())
2438     StaticRuntimes.push_back("safestack");
2439 }
2440
2441 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2442 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2443 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2444                                  ArgStringList &CmdArgs) {
2445   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2446       HelperStaticRuntimes;
2447   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2448                            HelperStaticRuntimes);
2449   for (auto RT : SharedRuntimes)
2450     addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2451   for (auto RT : HelperStaticRuntimes)
2452     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2453   bool AddExportDynamic = false;
2454   for (auto RT : StaticRuntimes) {
2455     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2456     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2457   }
2458   // If there is a static runtime with no dynamic list, force all the symbols
2459   // to be dynamic to be sure we export sanitizer interface functions.
2460   if (AddExportDynamic)
2461     CmdArgs.push_back("-export-dynamic");
2462   return !StaticRuntimes.empty();
2463 }
2464
2465 static bool areOptimizationsEnabled(const ArgList &Args) {
2466   // Find the last -O arg and see if it is non-zero.
2467   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2468     return !A->getOption().matches(options::OPT_O0);
2469   // Defaults to -O0.
2470   return false;
2471 }
2472
2473 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2474                                            const llvm::Triple &Triple) {
2475   // XCore never wants frame pointers, regardless of OS.
2476   if (Triple.getArch() == llvm::Triple::xcore) {
2477     return false;
2478   }
2479
2480   if (Triple.isOSLinux()) {
2481     switch (Triple.getArch()) {
2482     // Don't use a frame pointer on linux if optimizing for certain targets.
2483     case llvm::Triple::mips64:
2484     case llvm::Triple::mips64el:
2485     case llvm::Triple::mips:
2486     case llvm::Triple::mipsel:
2487     case llvm::Triple::systemz:
2488     case llvm::Triple::x86:
2489     case llvm::Triple::x86_64:
2490       return !areOptimizationsEnabled(Args);
2491     default:
2492       return true;
2493     }
2494   }
2495
2496   if (Triple.isOSWindows()) {
2497     switch (Triple.getArch()) {
2498     case llvm::Triple::x86:
2499       return !areOptimizationsEnabled(Args);
2500     default:
2501       // All other supported Windows ISAs use xdata unwind information, so frame
2502       // pointers are not generally useful.
2503       return false;
2504     }
2505   }
2506
2507   return true;
2508 }
2509
2510 static bool shouldUseFramePointer(const ArgList &Args,
2511                                   const llvm::Triple &Triple) {
2512   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2513                                options::OPT_fomit_frame_pointer))
2514     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2515
2516   return shouldUseFramePointerForTarget(Args, Triple);
2517 }
2518
2519 static bool shouldUseLeafFramePointer(const ArgList &Args,
2520                                       const llvm::Triple &Triple) {
2521   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2522                                options::OPT_momit_leaf_frame_pointer))
2523     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2524
2525   if (Triple.isPS4CPU())
2526     return false;
2527
2528   return shouldUseFramePointerForTarget(Args, Triple);
2529 }
2530
2531 /// Add a CC1 option to specify the debug compilation directory.
2532 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2533   SmallString<128> cwd;
2534   if (!llvm::sys::fs::current_path(cwd)) {
2535     CmdArgs.push_back("-fdebug-compilation-dir");
2536     CmdArgs.push_back(Args.MakeArgString(cwd));
2537   }
2538 }
2539
2540 static const char *SplitDebugName(const ArgList &Args,
2541                                   const InputInfo &Input) {
2542   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2543   if (FinalOutput && Args.hasArg(options::OPT_c)) {
2544     SmallString<128> T(FinalOutput->getValue());
2545     llvm::sys::path::replace_extension(T, "dwo");
2546     return Args.MakeArgString(T);
2547   } else {
2548     // Use the compilation dir.
2549     SmallString<128> T(
2550         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2551     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2552     llvm::sys::path::replace_extension(F, "dwo");
2553     T += F;
2554     return Args.MakeArgString(F);
2555   }
2556 }
2557
2558 static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
2559                            const Tool &T, const JobAction &JA,
2560                            const ArgList &Args, const InputInfo &Output,
2561                            const char *OutFile) {
2562   ArgStringList ExtractArgs;
2563   ExtractArgs.push_back("--extract-dwo");
2564
2565   ArgStringList StripArgs;
2566   StripArgs.push_back("--strip-dwo");
2567
2568   // Grabbing the output of the earlier compile step.
2569   StripArgs.push_back(Output.getFilename());
2570   ExtractArgs.push_back(Output.getFilename());
2571   ExtractArgs.push_back(OutFile);
2572
2573   const char *Exec =
2574     Args.MakeArgString(TC.GetProgramPath("objcopy"));
2575
2576   // First extract the dwo sections.
2577   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
2578
2579   // Then remove them from the original .o file.
2580   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
2581 }
2582
2583 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2584 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2585 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2586   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2587     if (A->getOption().matches(options::OPT_O4) ||
2588         A->getOption().matches(options::OPT_Ofast))
2589       return true;
2590
2591     if (A->getOption().matches(options::OPT_O0))
2592       return false;
2593
2594     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2595
2596     // Vectorize -Os.
2597     StringRef S(A->getValue());
2598     if (S == "s")
2599       return true;
2600
2601     // Don't vectorize -Oz, unless it's the slp vectorizer.
2602     if (S == "z")
2603       return isSlpVec;
2604
2605     unsigned OptLevel = 0;
2606     if (S.getAsInteger(10, OptLevel))
2607       return false;
2608
2609     return OptLevel > 1;
2610   }
2611
2612   return false;
2613 }
2614
2615 /// Add -x lang to \p CmdArgs for \p Input.
2616 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2617                              ArgStringList &CmdArgs) {
2618   // When using -verify-pch, we don't want to provide the type
2619   // 'precompiled-header' if it was inferred from the file extension
2620   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2621     return;
2622
2623   CmdArgs.push_back("-x");
2624   if (Args.hasArg(options::OPT_rewrite_objc))
2625     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2626   else
2627     CmdArgs.push_back(types::getTypeName(Input.getType()));
2628 }
2629
2630 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
2631   if (Version < 100)
2632     return VersionTuple(Version);
2633
2634   if (Version < 10000)
2635     return VersionTuple(Version / 100, Version % 100);
2636
2637   unsigned Build = 0, Factor = 1;
2638   for ( ; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2639     Build = Build + (Version % 10) * Factor;
2640   return VersionTuple(Version / 100, Version % 100, Build);
2641 }
2642
2643 // Claim options we don't want to warn if they are unused. We do this for
2644 // options that build systems might add but are unused when assembling or only
2645 // running the preprocessor for example.
2646 static void claimNoWarnArgs(const ArgList &Args) {
2647   // Don't warn about unused -f(no-)?lto.  This can happen when we're
2648   // preprocessing, precompiling or assembling.
2649   Args.ClaimAllArgs(options::OPT_flto);
2650   Args.ClaimAllArgs(options::OPT_fno_lto);
2651 }
2652
2653 static void appendUserToPath(SmallVectorImpl<char> &Result) {
2654 #ifdef LLVM_ON_UNIX
2655   const char *Username = getenv("LOGNAME");
2656 #else
2657   const char *Username = getenv("USERNAME");
2658 #endif
2659   if (Username) {
2660     // Validate that LoginName can be used in a path, and get its length.
2661     size_t Len = 0;
2662     for (const char *P = Username; *P; ++P, ++Len) {
2663       if (!isAlphanumeric(*P) && *P != '_') {
2664         Username = nullptr;
2665         break;
2666       }
2667     }
2668
2669     if (Username && Len > 0) {
2670       Result.append(Username, Username + Len);
2671       return;
2672     }
2673   }
2674
2675   // Fallback to user id.
2676 #ifdef LLVM_ON_UNIX
2677   std::string UID = llvm::utostr(getuid());
2678 #else
2679   // FIXME: Windows seems to have an 'SID' that might work.
2680   std::string UID = "9999";
2681 #endif
2682   Result.append(UID.begin(), UID.end());
2683 }
2684
2685 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
2686                                           const llvm::Triple &Triple,
2687                                           const llvm::opt::ArgList &Args,
2688                                           bool IsWindowsMSVC) {
2689   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2690                    IsWindowsMSVC) ||
2691       Args.hasArg(options::OPT_fmsc_version) ||
2692       Args.hasArg(options::OPT_fms_compatibility_version)) {
2693     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
2694     const Arg *MSCompatibilityVersion =
2695       Args.getLastArg(options::OPT_fms_compatibility_version);
2696
2697     if (MSCVersion && MSCompatibilityVersion) {
2698       if (D)
2699         D->Diag(diag::err_drv_argument_not_allowed_with)
2700             << MSCVersion->getAsString(Args)
2701             << MSCompatibilityVersion->getAsString(Args);
2702       return VersionTuple();
2703     }
2704
2705     if (MSCompatibilityVersion) {
2706       VersionTuple MSVT;
2707       if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
2708         D->Diag(diag::err_drv_invalid_value)
2709             << MSCompatibilityVersion->getAsString(Args)
2710             << MSCompatibilityVersion->getValue();
2711       return MSVT;
2712     }
2713
2714     if (MSCVersion) {
2715       unsigned Version = 0;
2716       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
2717         D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
2718                                              << MSCVersion->getValue();
2719       return getMSCompatibilityVersion(Version);
2720     }
2721
2722     unsigned Major, Minor, Micro;
2723     Triple.getEnvironmentVersion(Major, Minor, Micro);
2724     if (Major || Minor || Micro)
2725       return VersionTuple(Major, Minor, Micro);
2726
2727     return VersionTuple(18);
2728   }
2729   return VersionTuple();
2730 }
2731
2732 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2733                          const InputInfo &Output,
2734                          const InputInfoList &Inputs,
2735                          const ArgList &Args,
2736                          const char *LinkingOutput) const {
2737   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
2738                                   options::OPT_fapple_kext);
2739   const Driver &D = getToolChain().getDriver();
2740   ArgStringList CmdArgs;
2741
2742   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2743   bool IsWindowsCygnus =
2744       getToolChain().getTriple().isWindowsCygwinEnvironment();
2745   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2746
2747   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2748   const InputInfo &Input = Inputs[0];
2749
2750   // Invoke ourselves in -cc1 mode.
2751   //
2752   // FIXME: Implement custom jobs for internal actions.
2753   CmdArgs.push_back("-cc1");
2754
2755   // Add the "effective" target triple.
2756   CmdArgs.push_back("-triple");
2757   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2758   CmdArgs.push_back(Args.MakeArgString(TripleStr));
2759
2760   const llvm::Triple TT(TripleStr);
2761   if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2762                            TT.getArch() == llvm::Triple::thumb)) {
2763     unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2764     unsigned Version;
2765     TT.getArchName().substr(Offset).getAsInteger(10, Version);
2766     if (Version < 7)
2767       D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2768                                                 << TripleStr;
2769   }
2770
2771   // Push all default warning arguments that are specific to
2772   // the given target.  These come before user provided warning options
2773   // are provided.
2774   getToolChain().addClangWarningOptions(CmdArgs);
2775
2776   // Select the appropriate action.
2777   RewriteKind rewriteKind = RK_None;
2778   
2779   if (isa<AnalyzeJobAction>(JA)) {
2780     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2781     CmdArgs.push_back("-analyze");
2782   } else if (isa<MigrateJobAction>(JA)) {
2783     CmdArgs.push_back("-migrate");
2784   } else if (isa<PreprocessJobAction>(JA)) {
2785     if (Output.getType() == types::TY_Dependencies)
2786       CmdArgs.push_back("-Eonly");
2787     else {
2788       CmdArgs.push_back("-E");
2789       if (Args.hasArg(options::OPT_rewrite_objc) &&
2790           !Args.hasArg(options::OPT_g_Group))
2791         CmdArgs.push_back("-P");
2792     }
2793   } else if (isa<AssembleJobAction>(JA)) {
2794     CmdArgs.push_back("-emit-obj");
2795
2796     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2797
2798     // Also ignore explicit -force_cpusubtype_ALL option.
2799     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
2800   } else if (isa<PrecompileJobAction>(JA)) {
2801     // Use PCH if the user requested it.
2802     bool UsePCH = D.CCCUsePCH;
2803
2804     if (JA.getType() == types::TY_Nothing)
2805       CmdArgs.push_back("-fsyntax-only");
2806     else if (UsePCH)
2807       CmdArgs.push_back("-emit-pch");
2808     else
2809       CmdArgs.push_back("-emit-pth");
2810   } else if (isa<VerifyPCHJobAction>(JA)) {
2811     CmdArgs.push_back("-verify-pch");
2812   } else {
2813     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
2814            "Invalid action for clang tool.");
2815
2816     if (JA.getType() == types::TY_Nothing) {
2817       CmdArgs.push_back("-fsyntax-only");
2818     } else if (JA.getType() == types::TY_LLVM_IR ||
2819                JA.getType() == types::TY_LTO_IR) {
2820       CmdArgs.push_back("-emit-llvm");
2821     } else if (JA.getType() == types::TY_LLVM_BC ||
2822                JA.getType() == types::TY_LTO_BC) {
2823       CmdArgs.push_back("-emit-llvm-bc");
2824     } else if (JA.getType() == types::TY_PP_Asm) {
2825       CmdArgs.push_back("-S");
2826     } else if (JA.getType() == types::TY_AST) {
2827       CmdArgs.push_back("-emit-pch");
2828     } else if (JA.getType() == types::TY_ModuleFile) {
2829       CmdArgs.push_back("-module-file-info");
2830     } else if (JA.getType() == types::TY_RewrittenObjC) {
2831       CmdArgs.push_back("-rewrite-objc");
2832       rewriteKind = RK_NonFragile;
2833     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2834       CmdArgs.push_back("-rewrite-objc");
2835       rewriteKind = RK_Fragile;
2836     } else {
2837       assert(JA.getType() == types::TY_PP_Asm &&
2838              "Unexpected output type!");
2839     }
2840
2841     // Preserve use-list order by default when emitting bitcode, so that
2842     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
2843     // same result as running passes here.  For LTO, we don't need to preserve
2844     // the use-list order, since serialization to bitcode is part of the flow.
2845     if (JA.getType() == types::TY_LLVM_BC)
2846       CmdArgs.push_back("-emit-llvm-uselists");
2847   }
2848
2849   // We normally speed up the clang process a bit by skipping destructors at
2850   // exit, but when we're generating diagnostics we can rely on some of the
2851   // cleanup.
2852   if (!C.isForDiagnostics())
2853     CmdArgs.push_back("-disable-free");
2854
2855   // Disable the verification pass in -asserts builds.
2856 #ifdef NDEBUG
2857   CmdArgs.push_back("-disable-llvm-verifier");
2858 #endif
2859
2860   // Set the main file name, so that debug info works even with
2861   // -save-temps.
2862   CmdArgs.push_back("-main-file-name");
2863   CmdArgs.push_back(getBaseInputName(Args, Input));
2864
2865   // Some flags which affect the language (via preprocessor
2866   // defines).
2867   if (Args.hasArg(options::OPT_static))
2868     CmdArgs.push_back("-static-define");
2869
2870   if (isa<AnalyzeJobAction>(JA)) {
2871     // Enable region store model by default.
2872     CmdArgs.push_back("-analyzer-store=region");
2873
2874     // Treat blocks as analysis entry points.
2875     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2876
2877     CmdArgs.push_back("-analyzer-eagerly-assume");
2878
2879     // Add default argument set.
2880     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2881       CmdArgs.push_back("-analyzer-checker=core");
2882
2883       if (!IsWindowsMSVC)
2884         CmdArgs.push_back("-analyzer-checker=unix");
2885
2886       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2887         CmdArgs.push_back("-analyzer-checker=osx");
2888       
2889       CmdArgs.push_back("-analyzer-checker=deadcode");
2890       
2891       if (types::isCXX(Input.getType()))
2892         CmdArgs.push_back("-analyzer-checker=cplusplus");
2893
2894       // Enable the following experimental checkers for testing.
2895       CmdArgs.push_back(
2896           "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2897       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2898       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2899       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");      
2900       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2901       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2902     }
2903
2904     // Set the output format. The default is plist, for (lame) historical
2905     // reasons.
2906     CmdArgs.push_back("-analyzer-output");
2907     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2908       CmdArgs.push_back(A->getValue());
2909     else
2910       CmdArgs.push_back("plist");
2911
2912     // Disable the presentation of standard compiler warnings when
2913     // using --analyze.  We only want to show static analyzer diagnostics
2914     // or frontend errors.
2915     CmdArgs.push_back("-w");
2916
2917     // Add -Xanalyzer arguments when running as analyzer.
2918     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2919   }
2920
2921   CheckCodeGenerationOptions(D, Args);
2922
2923   bool PIE = getToolChain().isPIEDefault();
2924   bool PIC = PIE || getToolChain().isPICDefault();
2925   bool IsPICLevelTwo = PIC;
2926
2927   // Android-specific defaults for PIC/PIE
2928   if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
2929     switch (getToolChain().getArch()) {
2930     case llvm::Triple::arm:
2931     case llvm::Triple::armeb:
2932     case llvm::Triple::thumb:
2933     case llvm::Triple::thumbeb:
2934     case llvm::Triple::aarch64:
2935     case llvm::Triple::mips:
2936     case llvm::Triple::mipsel:
2937     case llvm::Triple::mips64:
2938     case llvm::Triple::mips64el:
2939       PIC = true; // "-fpic"
2940       break;
2941
2942     case llvm::Triple::x86:
2943     case llvm::Triple::x86_64:
2944       PIC = true; // "-fPIC"
2945       IsPICLevelTwo = true;
2946       break;
2947
2948     default:
2949       break;
2950     }
2951   }
2952
2953   // OpenBSD-specific defaults for PIE
2954   if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
2955     switch (getToolChain().getArch()) {
2956     case llvm::Triple::mips64:
2957     case llvm::Triple::mips64el:
2958     case llvm::Triple::sparcel:
2959     case llvm::Triple::x86:
2960     case llvm::Triple::x86_64:
2961       IsPICLevelTwo = false; // "-fpie"
2962       break;
2963
2964     case llvm::Triple::ppc:
2965     case llvm::Triple::sparc:
2966     case llvm::Triple::sparcv9:
2967       IsPICLevelTwo = true; // "-fPIE"
2968       break;
2969
2970     default:
2971       break;
2972     }
2973   }
2974
2975   // For the PIC and PIE flag options, this logic is different from the
2976   // legacy logic in very old versions of GCC, as that logic was just
2977   // a bug no one had ever fixed. This logic is both more rational and
2978   // consistent with GCC's new logic now that the bugs are fixed. The last
2979   // argument relating to either PIC or PIE wins, and no other argument is
2980   // used. If the last argument is any flavor of the '-fno-...' arguments,
2981   // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
2982   // at the same level.
2983   Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
2984                                  options::OPT_fpic, options::OPT_fno_pic,
2985                                  options::OPT_fPIE, options::OPT_fno_PIE,
2986                                  options::OPT_fpie, options::OPT_fno_pie);
2987   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2988   // is forced, then neither PIC nor PIE flags will have no effect.
2989   if (!getToolChain().isPICDefaultForced()) {
2990     if (LastPICArg) {
2991       Option O = LastPICArg->getOption();
2992       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
2993           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
2994         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
2995         PIC = PIE || O.matches(options::OPT_fPIC) ||
2996               O.matches(options::OPT_fpic);
2997         IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
2998                         O.matches(options::OPT_fPIC);
2999       } else {
3000         PIE = PIC = false;
3001       }
3002     }
3003   }
3004
3005   // Introduce a Darwin-specific hack. If the default is PIC but the flags
3006   // specified while enabling PIC enabled level 1 PIC, just force it back to
3007   // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
3008   // informal testing).
3009   if (PIC && getToolChain().getTriple().isOSDarwin())
3010     IsPICLevelTwo |= getToolChain().isPICDefault();
3011
3012   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
3013   // PIC or PIE options above, if these show up, PIC is disabled.
3014   llvm::Triple Triple(TripleStr);
3015   if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
3016     PIC = PIE = false;
3017   if (Args.hasArg(options::OPT_static))
3018     PIC = PIE = false;
3019
3020   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3021     // This is a very special mode. It trumps the other modes, almost no one
3022     // uses it, and it isn't even valid on any OS but Darwin.
3023     if (!getToolChain().getTriple().isOSDarwin())
3024       D.Diag(diag::err_drv_unsupported_opt_for_target)
3025         << A->getSpelling() << getToolChain().getTriple().str();
3026
3027     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3028
3029     CmdArgs.push_back("-mrelocation-model");
3030     CmdArgs.push_back("dynamic-no-pic");
3031
3032     // Only a forced PIC mode can cause the actual compile to have PIC defines
3033     // etc., no flags are sufficient. This behavior was selected to closely
3034     // match that of llvm-gcc and Apple GCC before that.
3035     if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
3036       CmdArgs.push_back("-pic-level");
3037       CmdArgs.push_back("2");
3038     }
3039   } else {
3040     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
3041     // handled in Clang's IRGen by the -pie-level flag.
3042     CmdArgs.push_back("-mrelocation-model");
3043     CmdArgs.push_back(PIC ? "pic" : "static");
3044
3045     if (PIC) {
3046       CmdArgs.push_back("-pic-level");
3047       CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3048       if (PIE) {
3049         CmdArgs.push_back("-pie-level");
3050         CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3051       }
3052     }
3053   }
3054
3055   CmdArgs.push_back("-mthread-model");
3056   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3057     CmdArgs.push_back(A->getValue());
3058   else
3059     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3060
3061   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3062
3063   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3064                     options::OPT_fno_merge_all_constants))
3065     CmdArgs.push_back("-fno-merge-all-constants");
3066
3067   // LLVM Code Generator Options.
3068
3069   if (Args.hasArg(options::OPT_frewrite_map_file) ||
3070       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3071     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3072                                       options::OPT_frewrite_map_file_EQ)) {
3073       CmdArgs.push_back("-frewrite-map-file");
3074       CmdArgs.push_back(A->getValue());
3075       A->claim();
3076     }
3077   }
3078
3079   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3080     StringRef v = A->getValue();
3081     CmdArgs.push_back("-mllvm");
3082     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3083     A->claim();
3084   }
3085
3086   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3087     CmdArgs.push_back("-mregparm");
3088     CmdArgs.push_back(A->getValue());
3089   }
3090
3091   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3092                                options::OPT_freg_struct_return)) {
3093     if (getToolChain().getArch() != llvm::Triple::x86) {
3094       D.Diag(diag::err_drv_unsupported_opt_for_target)
3095         << A->getSpelling() << getToolChain().getTriple().str();
3096     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3097       CmdArgs.push_back("-fpcc-struct-return");
3098     } else {
3099       assert(A->getOption().matches(options::OPT_freg_struct_return));
3100       CmdArgs.push_back("-freg-struct-return");
3101     }
3102   }
3103
3104   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3105     CmdArgs.push_back("-mrtd");
3106
3107   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3108     CmdArgs.push_back("-mdisable-fp-elim");
3109   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3110                     options::OPT_fno_zero_initialized_in_bss))
3111     CmdArgs.push_back("-mno-zero-initialized-in-bss");
3112
3113   bool OFastEnabled = isOptimizationLevelFast(Args);
3114   // If -Ofast is the optimization level, then -fstrict-aliasing should be
3115   // enabled.  This alias option is being used to simplify the hasFlag logic.
3116   OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
3117     options::OPT_fstrict_aliasing;
3118   // We turn strict aliasing off by default if we're in CL mode, since MSVC
3119   // doesn't do any TBAA.
3120   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3121   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3122                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3123     CmdArgs.push_back("-relaxed-aliasing");
3124   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3125                     options::OPT_fno_struct_path_tbaa))
3126     CmdArgs.push_back("-no-struct-path-tbaa");
3127   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3128                    false))
3129     CmdArgs.push_back("-fstrict-enums");
3130   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3131                     options::OPT_fno_optimize_sibling_calls))
3132     CmdArgs.push_back("-mdisable-tail-calls");
3133
3134   // Handle segmented stacks.
3135   if (Args.hasArg(options::OPT_fsplit_stack))
3136     CmdArgs.push_back("-split-stacks");
3137
3138   // If -Ofast is the optimization level, then -ffast-math should be enabled.
3139   // This alias option is being used to simplify the getLastArg logic.
3140   OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
3141     options::OPT_ffast_math;
3142   
3143   // Handle various floating point optimization flags, mapping them to the
3144   // appropriate LLVM code generation flags. The pattern for all of these is to
3145   // default off the codegen optimizations, and if any flag enables them and no
3146   // flag disables them after the flag enabling them, enable the codegen
3147   // optimization. This is complicated by several "umbrella" flags.
3148   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3149                                options::OPT_fno_fast_math,
3150                                options::OPT_ffinite_math_only,
3151                                options::OPT_fno_finite_math_only,
3152                                options::OPT_fhonor_infinities,
3153                                options::OPT_fno_honor_infinities))
3154     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3155         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3156         A->getOption().getID() != options::OPT_fhonor_infinities)
3157       CmdArgs.push_back("-menable-no-infs");
3158   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3159                                options::OPT_fno_fast_math,
3160                                options::OPT_ffinite_math_only,
3161                                options::OPT_fno_finite_math_only,
3162                                options::OPT_fhonor_nans,
3163                                options::OPT_fno_honor_nans))
3164     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3165         A->getOption().getID() != options::OPT_fno_finite_math_only &&
3166         A->getOption().getID() != options::OPT_fhonor_nans)
3167       CmdArgs.push_back("-menable-no-nans");
3168
3169   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3170   bool MathErrno = getToolChain().IsMathErrnoDefault();
3171   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3172                                options::OPT_fno_fast_math,
3173                                options::OPT_fmath_errno,
3174                                options::OPT_fno_math_errno)) {
3175     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3176     // However, turning *off* -ffast_math merely restores the toolchain default
3177     // (which may be false).
3178     if (A->getOption().getID() == options::OPT_fno_math_errno ||
3179         A->getOption().getID() == options::OPT_ffast_math ||
3180         A->getOption().getID() == options::OPT_Ofast)
3181       MathErrno = false;
3182     else if (A->getOption().getID() == options::OPT_fmath_errno)
3183       MathErrno = true;
3184   }
3185   if (MathErrno)
3186     CmdArgs.push_back("-fmath-errno");
3187
3188   // There are several flags which require disabling very specific
3189   // optimizations. Any of these being disabled forces us to turn off the
3190   // entire set of LLVM optimizations, so collect them through all the flag
3191   // madness.
3192   bool AssociativeMath = false;
3193   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3194                                options::OPT_fno_fast_math,
3195                                options::OPT_funsafe_math_optimizations,
3196                                options::OPT_fno_unsafe_math_optimizations,
3197                                options::OPT_fassociative_math,
3198                                options::OPT_fno_associative_math))
3199     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3200         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3201         A->getOption().getID() != options::OPT_fno_associative_math)
3202       AssociativeMath = true;
3203   bool ReciprocalMath = false;
3204   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3205                                options::OPT_fno_fast_math,
3206                                options::OPT_funsafe_math_optimizations,
3207                                options::OPT_fno_unsafe_math_optimizations,
3208                                options::OPT_freciprocal_math,
3209                                options::OPT_fno_reciprocal_math))
3210     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3211         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3212         A->getOption().getID() != options::OPT_fno_reciprocal_math)
3213       ReciprocalMath = true;
3214   bool SignedZeros = true;
3215   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3216                                options::OPT_fno_fast_math,
3217                                options::OPT_funsafe_math_optimizations,
3218                                options::OPT_fno_unsafe_math_optimizations,
3219                                options::OPT_fsigned_zeros,
3220                                options::OPT_fno_signed_zeros))
3221     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3222         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3223         A->getOption().getID() != options::OPT_fsigned_zeros)
3224       SignedZeros = false;
3225   bool TrappingMath = true;
3226   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3227                                options::OPT_fno_fast_math,
3228                                options::OPT_funsafe_math_optimizations,
3229                                options::OPT_fno_unsafe_math_optimizations,
3230                                options::OPT_ftrapping_math,
3231                                options::OPT_fno_trapping_math))
3232     if (A->getOption().getID() != options::OPT_fno_fast_math &&
3233         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3234         A->getOption().getID() != options::OPT_ftrapping_math)
3235       TrappingMath = false;
3236   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3237       !TrappingMath)
3238     CmdArgs.push_back("-menable-unsafe-fp-math");
3239
3240   if (!SignedZeros)
3241     CmdArgs.push_back("-fno-signed-zeros");
3242
3243   if (ReciprocalMath)
3244     CmdArgs.push_back("-freciprocal-math");
3245
3246   // Validate and pass through -fp-contract option. 
3247   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3248                                options::OPT_fno_fast_math,
3249                                options::OPT_ffp_contract)) {
3250     if (A->getOption().getID() == options::OPT_ffp_contract) {
3251       StringRef Val = A->getValue();
3252       if (Val == "fast" || Val == "on" || Val == "off") {
3253         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3254       } else {
3255         D.Diag(diag::err_drv_unsupported_option_argument)
3256           << A->getOption().getName() << Val;
3257       }
3258     } else if (A->getOption().matches(options::OPT_ffast_math) ||
3259                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3260       // If fast-math is set then set the fp-contract mode to fast.
3261       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3262     }
3263   }
3264   
3265   ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3266
3267   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3268   // and if we find them, tell the frontend to provide the appropriate
3269   // preprocessor macros. This is distinct from enabling any optimizations as
3270   // these options induce language changes which must survive serialization
3271   // and deserialization, etc.
3272   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3273                                options::OPT_fno_fast_math))
3274       if (!A->getOption().matches(options::OPT_fno_fast_math))
3275         CmdArgs.push_back("-ffast-math");
3276   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3277                                options::OPT_fno_fast_math))
3278     if (A->getOption().matches(options::OPT_ffinite_math_only))
3279       CmdArgs.push_back("-ffinite-math-only");
3280
3281   // Decide whether to use verbose asm. Verbose assembly is the default on
3282   // toolchains which have the integrated assembler on by default.
3283   bool IsIntegratedAssemblerDefault =
3284       getToolChain().IsIntegratedAssemblerDefault();
3285   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3286                    IsIntegratedAssemblerDefault) ||
3287       Args.hasArg(options::OPT_dA))
3288     CmdArgs.push_back("-masm-verbose");
3289
3290   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3291                     IsIntegratedAssemblerDefault))
3292     CmdArgs.push_back("-no-integrated-as");
3293
3294   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3295     CmdArgs.push_back("-mdebug-pass");
3296     CmdArgs.push_back("Structure");
3297   }
3298   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3299     CmdArgs.push_back("-mdebug-pass");
3300     CmdArgs.push_back("Arguments");
3301   }
3302
3303   // Enable -mconstructor-aliases except on darwin, where we have to
3304   // work around a linker bug;  see <rdar://problem/7651567>.
3305   if (!getToolChain().getTriple().isOSDarwin())
3306     CmdArgs.push_back("-mconstructor-aliases");
3307
3308   // Darwin's kernel doesn't support guard variables; just die if we
3309   // try to use them.
3310   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3311     CmdArgs.push_back("-fforbid-guard-variables");
3312
3313   if (Args.hasArg(options::OPT_mms_bitfields)) {
3314     CmdArgs.push_back("-mms-bitfields");
3315   }
3316
3317   // This is a coarse approximation of what llvm-gcc actually does, both
3318   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3319   // complicated ways.
3320   bool AsynchronousUnwindTables =
3321       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3322                    options::OPT_fno_asynchronous_unwind_tables,
3323                    (getToolChain().IsUnwindTablesDefault() ||
3324                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3325                        !KernelOrKext);
3326   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3327                    AsynchronousUnwindTables))
3328     CmdArgs.push_back("-munwind-tables");
3329
3330   getToolChain().addClangTargetOptions(Args, CmdArgs);
3331
3332   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3333     CmdArgs.push_back("-mlimit-float-precision");
3334     CmdArgs.push_back(A->getValue());
3335   }
3336
3337   // FIXME: Handle -mtune=.
3338   (void) Args.hasArg(options::OPT_mtune_EQ);
3339
3340   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3341     CmdArgs.push_back("-mcode-model");
3342     CmdArgs.push_back(A->getValue());
3343   }
3344
3345   // Add the target cpu
3346   std::string CPU = getCPUName(Args, Triple);
3347   if (!CPU.empty()) {
3348     CmdArgs.push_back("-target-cpu");
3349     CmdArgs.push_back(Args.MakeArgString(CPU));
3350   }
3351
3352   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3353     CmdArgs.push_back("-mfpmath");
3354     CmdArgs.push_back(A->getValue());
3355   }
3356
3357   // Add the target features
3358   getTargetFeatures(D, Triple, Args, CmdArgs, false);
3359
3360   // Add target specific flags.
3361   switch(getToolChain().getArch()) {
3362   default:
3363     break;
3364
3365   case llvm::Triple::arm:
3366   case llvm::Triple::armeb:
3367   case llvm::Triple::thumb:
3368   case llvm::Triple::thumbeb:
3369     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3370     break;
3371
3372   case llvm::Triple::aarch64:
3373   case llvm::Triple::aarch64_be:
3374     AddAArch64TargetArgs(Args, CmdArgs);
3375     break;
3376
3377   case llvm::Triple::mips:
3378   case llvm::Triple::mipsel:
3379   case llvm::Triple::mips64:
3380   case llvm::Triple::mips64el:
3381     AddMIPSTargetArgs(Args, CmdArgs);
3382     break;
3383
3384   case llvm::Triple::ppc:
3385   case llvm::Triple::ppc64:
3386   case llvm::Triple::ppc64le:
3387     AddPPCTargetArgs(Args, CmdArgs);
3388     break;
3389
3390   case llvm::Triple::sparc:
3391   case llvm::Triple::sparcel:
3392   case llvm::Triple::sparcv9:
3393     AddSparcTargetArgs(Args, CmdArgs);
3394     break;
3395
3396   case llvm::Triple::x86:
3397   case llvm::Triple::x86_64:
3398     AddX86TargetArgs(Args, CmdArgs);
3399     break;
3400
3401   case llvm::Triple::hexagon:
3402     AddHexagonTargetArgs(Args, CmdArgs);
3403     break;
3404   }
3405
3406   // Add clang-cl arguments.
3407   if (getToolChain().getDriver().IsCLMode())
3408     AddClangCLArgs(Args, CmdArgs);
3409
3410   // Pass the linker version in use.
3411   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3412     CmdArgs.push_back("-target-linker-version");
3413     CmdArgs.push_back(A->getValue());
3414   }
3415
3416   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3417     CmdArgs.push_back("-momit-leaf-frame-pointer");
3418
3419   // Explicitly error on some things we know we don't support and can't just
3420   // ignore.
3421   types::ID InputType = Input.getType();
3422   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3423     Arg *Unsupported;
3424     if (types::isCXX(InputType) &&
3425         getToolChain().getTriple().isOSDarwin() &&
3426         getToolChain().getArch() == llvm::Triple::x86) {
3427       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3428           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3429         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3430           << Unsupported->getOption().getName();
3431     }
3432   }
3433
3434   Args.AddAllArgs(CmdArgs, options::OPT_v);
3435   Args.AddLastArg(CmdArgs, options::OPT_H);
3436   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3437     CmdArgs.push_back("-header-include-file");
3438     CmdArgs.push_back(D.CCPrintHeadersFilename ?
3439                       D.CCPrintHeadersFilename : "-");
3440   }
3441   Args.AddLastArg(CmdArgs, options::OPT_P);
3442   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3443
3444   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3445     CmdArgs.push_back("-diagnostic-log-file");
3446     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
3447                       D.CCLogDiagnosticsFilename : "-");
3448   }
3449
3450   // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3451   // are preserved, all other debug options are substituted with "-g".
3452   Args.ClaimAllArgs(options::OPT_g_Group);
3453   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3454     if (A->getOption().matches(options::OPT_gline_tables_only) ||
3455         A->getOption().matches(options::OPT_g1)) {
3456       // FIXME: we should support specifying dwarf version with
3457       // -gline-tables-only.
3458       CmdArgs.push_back("-gline-tables-only");
3459       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3460       const llvm::Triple &Triple = getToolChain().getTriple();
3461       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3462           Triple.getOS() == llvm::Triple::FreeBSD ||
3463           Triple.getOS() == llvm::Triple::Solaris)
3464         CmdArgs.push_back("-gdwarf-2");
3465     } else if (A->getOption().matches(options::OPT_gdwarf_2))
3466       CmdArgs.push_back("-gdwarf-2");
3467     else if (A->getOption().matches(options::OPT_gdwarf_3))
3468       CmdArgs.push_back("-gdwarf-3");
3469     else if (A->getOption().matches(options::OPT_gdwarf_4))
3470       CmdArgs.push_back("-gdwarf-4");
3471     else if (!A->getOption().matches(options::OPT_g0) &&
3472              !A->getOption().matches(options::OPT_ggdb0)) {
3473       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3474       const llvm::Triple &Triple = getToolChain().getTriple();
3475       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3476           Triple.getOS() == llvm::Triple::FreeBSD ||
3477           Triple.getOS() == llvm::Triple::Solaris)
3478         CmdArgs.push_back("-gdwarf-2");
3479       else
3480         CmdArgs.push_back("-g");
3481     }
3482   }
3483
3484   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3485   Args.ClaimAllArgs(options::OPT_g_flags_Group);
3486   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3487                    /*Default*/ true))
3488     CmdArgs.push_back("-dwarf-column-info");
3489
3490   // FIXME: Move backend command line options to the module.
3491   // -gsplit-dwarf should turn on -g and enable the backend dwarf
3492   // splitting and extraction.
3493   // FIXME: Currently only works on Linux.
3494   if (getToolChain().getTriple().isOSLinux() &&
3495       Args.hasArg(options::OPT_gsplit_dwarf)) {
3496     CmdArgs.push_back("-g");
3497     CmdArgs.push_back("-backend-option");
3498     CmdArgs.push_back("-split-dwarf=Enable");
3499   }
3500
3501   // -ggnu-pubnames turns on gnu style pubnames in the backend.
3502   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3503     CmdArgs.push_back("-backend-option");
3504     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3505   }
3506
3507   // -gdwarf-aranges turns on the emission of the aranges section in the
3508   // backend.
3509   if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3510     CmdArgs.push_back("-backend-option");
3511     CmdArgs.push_back("-generate-arange-section");
3512   }
3513
3514   if (Args.hasFlag(options::OPT_fdebug_types_section,
3515                    options::OPT_fno_debug_types_section, false)) {
3516     CmdArgs.push_back("-backend-option");
3517     CmdArgs.push_back("-generate-type-units");
3518   }
3519
3520   // CloudABI uses -ffunction-sections and -fdata-sections by default.
3521   bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
3522
3523   if (Args.hasFlag(options::OPT_ffunction_sections,
3524                    options::OPT_fno_function_sections, UseSeparateSections)) {
3525     CmdArgs.push_back("-ffunction-sections");
3526   }
3527
3528   if (Args.hasFlag(options::OPT_fdata_sections,
3529                    options::OPT_fno_data_sections, UseSeparateSections)) {
3530     CmdArgs.push_back("-fdata-sections");
3531   }
3532
3533   if (!Args.hasFlag(options::OPT_funique_section_names,
3534                     options::OPT_fno_unique_section_names, true))
3535     CmdArgs.push_back("-fno-unique-section-names");
3536
3537   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3538
3539   if ((Args.hasArg(options::OPT_fprofile_instr_generate) ||
3540        Args.hasArg(options::OPT_fprofile_instr_generate_EQ)) &&
3541       (Args.hasArg(options::OPT_fprofile_instr_use) ||
3542        Args.hasArg(options::OPT_fprofile_instr_use_EQ)))
3543     D.Diag(diag::err_drv_argument_not_allowed_with)
3544       << "-fprofile-instr-generate" << "-fprofile-instr-use";
3545
3546   if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_generate_EQ))
3547     A->render(Args, CmdArgs);
3548   else
3549     Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3550
3551   if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_use_EQ))
3552     A->render(Args, CmdArgs);
3553   else if (Args.hasArg(options::OPT_fprofile_instr_use))
3554     CmdArgs.push_back("-fprofile-instr-use=pgo-data");
3555
3556   if (Args.hasArg(options::OPT_ftest_coverage) ||
3557       Args.hasArg(options::OPT_coverage))
3558     CmdArgs.push_back("-femit-coverage-notes");
3559   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3560                    false) ||
3561       Args.hasArg(options::OPT_coverage))
3562     CmdArgs.push_back("-femit-coverage-data");
3563
3564   if (Args.hasArg(options::OPT_fcoverage_mapping) &&
3565       !(Args.hasArg(options::OPT_fprofile_instr_generate) ||
3566         Args.hasArg(options::OPT_fprofile_instr_generate_EQ)))
3567     D.Diag(diag::err_drv_argument_only_allowed_with)
3568       << "-fcoverage-mapping" << "-fprofile-instr-generate";
3569
3570   if (Args.hasArg(options::OPT_fcoverage_mapping))
3571     CmdArgs.push_back("-fcoverage-mapping");
3572
3573   if (C.getArgs().hasArg(options::OPT_c) ||
3574       C.getArgs().hasArg(options::OPT_S)) {
3575     if (Output.isFilename()) {
3576       CmdArgs.push_back("-coverage-file");
3577       SmallString<128> CoverageFilename;
3578       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3579         CoverageFilename = FinalOutput->getValue();
3580       } else {
3581         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3582       }
3583       if (llvm::sys::path::is_relative(CoverageFilename)) {
3584         SmallString<128> Pwd;
3585         if (!llvm::sys::fs::current_path(Pwd)) {
3586           llvm::sys::path::append(Pwd, CoverageFilename);
3587           CoverageFilename.swap(Pwd);
3588         }
3589       }
3590       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3591     }
3592   }
3593
3594   // Pass options for controlling the default header search paths.
3595   if (Args.hasArg(options::OPT_nostdinc)) {
3596     CmdArgs.push_back("-nostdsysteminc");
3597     CmdArgs.push_back("-nobuiltininc");
3598   } else {
3599     if (Args.hasArg(options::OPT_nostdlibinc))
3600         CmdArgs.push_back("-nostdsysteminc");
3601     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3602     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3603   }
3604
3605   // Pass the path to compiler resource files.
3606   CmdArgs.push_back("-resource-dir");
3607   CmdArgs.push_back(D.ResourceDir.c_str());
3608
3609   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3610
3611   bool ARCMTEnabled = false;
3612   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3613     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3614                                        options::OPT_ccc_arcmt_modify,
3615                                        options::OPT_ccc_arcmt_migrate)) {
3616       ARCMTEnabled = true;
3617       switch (A->getOption().getID()) {
3618       default:
3619         llvm_unreachable("missed a case");
3620       case options::OPT_ccc_arcmt_check:
3621         CmdArgs.push_back("-arcmt-check");
3622         break;
3623       case options::OPT_ccc_arcmt_modify:
3624         CmdArgs.push_back("-arcmt-modify");
3625         break;
3626       case options::OPT_ccc_arcmt_migrate:
3627         CmdArgs.push_back("-arcmt-migrate");
3628         CmdArgs.push_back("-mt-migrate-directory");
3629         CmdArgs.push_back(A->getValue());
3630
3631         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3632         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3633         break;
3634       }
3635     }
3636   } else {
3637     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3638     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3639     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3640   }
3641
3642   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3643     if (ARCMTEnabled) {
3644       D.Diag(diag::err_drv_argument_not_allowed_with)
3645         << A->getAsString(Args) << "-ccc-arcmt-migrate";
3646     }
3647     CmdArgs.push_back("-mt-migrate-directory");
3648     CmdArgs.push_back(A->getValue());
3649
3650     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3651                      options::OPT_objcmt_migrate_subscripting,
3652                      options::OPT_objcmt_migrate_property)) {
3653       // None specified, means enable them all.
3654       CmdArgs.push_back("-objcmt-migrate-literals");
3655       CmdArgs.push_back("-objcmt-migrate-subscripting");
3656       CmdArgs.push_back("-objcmt-migrate-property");
3657     } else {
3658       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3659       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3660       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3661     }
3662   } else {
3663     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3664     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3665     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3666     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3667     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3668     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3669     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3670     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3671     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3672     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3673     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3674     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3675     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3676     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3677     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3678     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3679   }
3680
3681   // Add preprocessing options like -I, -D, etc. if we are using the
3682   // preprocessor.
3683   //
3684   // FIXME: Support -fpreprocessed
3685   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3686     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3687
3688   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3689   // that "The compiler can only warn and ignore the option if not recognized".
3690   // When building with ccache, it will pass -D options to clang even on
3691   // preprocessed inputs and configure concludes that -fPIC is not supported.
3692   Args.ClaimAllArgs(options::OPT_D);
3693
3694   // Manually translate -O4 to -O3; let clang reject others.
3695   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3696     if (A->getOption().matches(options::OPT_O4)) {
3697       CmdArgs.push_back("-O3");
3698       D.Diag(diag::warn_O4_is_O3);
3699     } else {
3700       A->render(Args, CmdArgs);
3701     }
3702   }
3703
3704   // Warn about ignored options to clang.
3705   for (const Arg *A :
3706        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3707     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3708   }
3709
3710   claimNoWarnArgs(Args);
3711
3712   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3713   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3714   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3715     CmdArgs.push_back("-pedantic");
3716   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3717   Args.AddLastArg(CmdArgs, options::OPT_w);
3718
3719   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3720   // (-ansi is equivalent to -std=c89 or -std=c++98).
3721   //
3722   // If a std is supplied, only add -trigraphs if it follows the
3723   // option.
3724   bool ImplyVCPPCXXVer = false;
3725   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3726     if (Std->getOption().matches(options::OPT_ansi))
3727       if (types::isCXX(InputType))
3728         CmdArgs.push_back("-std=c++98");
3729       else
3730         CmdArgs.push_back("-std=c89");
3731     else
3732       Std->render(Args, CmdArgs);
3733
3734     // If -f(no-)trigraphs appears after the language standard flag, honor it.
3735     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3736                                  options::OPT_ftrigraphs,
3737                                  options::OPT_fno_trigraphs))
3738       if (A != Std)
3739         A->render(Args, CmdArgs);
3740   } else {
3741     // Honor -std-default.
3742     //
3743     // FIXME: Clang doesn't correctly handle -std= when the input language
3744     // doesn't match. For the time being just ignore this for C++ inputs;
3745     // eventually we want to do all the standard defaulting here instead of
3746     // splitting it between the driver and clang -cc1.
3747     if (!types::isCXX(InputType))
3748       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3749                                 "-std=", /*Joined=*/true);
3750     else if (IsWindowsMSVC)
3751       ImplyVCPPCXXVer = true;
3752
3753     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3754                     options::OPT_fno_trigraphs);
3755   }
3756
3757   // GCC's behavior for -Wwrite-strings is a bit strange:
3758   //  * In C, this "warning flag" changes the types of string literals from
3759   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3760   //    for the discarded qualifier.
3761   //  * In C++, this is just a normal warning flag.
3762   //
3763   // Implementing this warning correctly in C is hard, so we follow GCC's
3764   // behavior for now. FIXME: Directly diagnose uses of a string literal as
3765   // a non-const char* in C, rather than using this crude hack.
3766   if (!types::isCXX(InputType)) {
3767     // FIXME: This should behave just like a warning flag, and thus should also
3768     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3769     Arg *WriteStrings =
3770         Args.getLastArg(options::OPT_Wwrite_strings,
3771                         options::OPT_Wno_write_strings, options::OPT_w);
3772     if (WriteStrings &&
3773         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3774       CmdArgs.push_back("-fconst-strings");
3775   }
3776
3777   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3778   // during C++ compilation, which it is by default. GCC keeps this define even
3779   // in the presence of '-w', match this behavior bug-for-bug.
3780   if (types::isCXX(InputType) &&
3781       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3782                    true)) {
3783     CmdArgs.push_back("-fdeprecated-macro");
3784   }
3785
3786   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3787   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3788     if (Asm->getOption().matches(options::OPT_fasm))
3789       CmdArgs.push_back("-fgnu-keywords");
3790     else
3791       CmdArgs.push_back("-fno-gnu-keywords");
3792   }
3793
3794   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3795     CmdArgs.push_back("-fno-dwarf-directory-asm");
3796
3797   if (ShouldDisableAutolink(Args, getToolChain()))
3798     CmdArgs.push_back("-fno-autolink");
3799
3800   // Add in -fdebug-compilation-dir if necessary.
3801   addDebugCompDirArg(Args, CmdArgs);
3802
3803   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3804                                options::OPT_ftemplate_depth_EQ)) {
3805     CmdArgs.push_back("-ftemplate-depth");
3806     CmdArgs.push_back(A->getValue());
3807   }
3808
3809   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3810     CmdArgs.push_back("-foperator-arrow-depth");
3811     CmdArgs.push_back(A->getValue());
3812   }
3813
3814   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3815     CmdArgs.push_back("-fconstexpr-depth");
3816     CmdArgs.push_back(A->getValue());
3817   }
3818
3819   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3820     CmdArgs.push_back("-fconstexpr-steps");
3821     CmdArgs.push_back(A->getValue());
3822   }
3823
3824   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3825     CmdArgs.push_back("-fbracket-depth");
3826     CmdArgs.push_back(A->getValue());
3827   }
3828
3829   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3830                                options::OPT_Wlarge_by_value_copy_def)) {
3831     if (A->getNumValues()) {
3832       StringRef bytes = A->getValue();
3833       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3834     } else
3835       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3836   }
3837
3838
3839   if (Args.hasArg(options::OPT_relocatable_pch))
3840     CmdArgs.push_back("-relocatable-pch");
3841
3842   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3843     CmdArgs.push_back("-fconstant-string-class");
3844     CmdArgs.push_back(A->getValue());
3845   }
3846
3847   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3848     CmdArgs.push_back("-ftabstop");
3849     CmdArgs.push_back(A->getValue());
3850   }
3851
3852   CmdArgs.push_back("-ferror-limit");
3853   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3854     CmdArgs.push_back(A->getValue());
3855   else
3856     CmdArgs.push_back("19");
3857
3858   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3859     CmdArgs.push_back("-fmacro-backtrace-limit");
3860     CmdArgs.push_back(A->getValue());
3861   }
3862
3863   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3864     CmdArgs.push_back("-ftemplate-backtrace-limit");
3865     CmdArgs.push_back(A->getValue());
3866   }
3867
3868   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3869     CmdArgs.push_back("-fconstexpr-backtrace-limit");
3870     CmdArgs.push_back(A->getValue());
3871   }
3872
3873   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3874     CmdArgs.push_back("-fspell-checking-limit");
3875     CmdArgs.push_back(A->getValue());
3876   }
3877
3878   // Pass -fmessage-length=.
3879   CmdArgs.push_back("-fmessage-length");
3880   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3881     CmdArgs.push_back(A->getValue());
3882   } else {
3883     // If -fmessage-length=N was not specified, determine whether this is a
3884     // terminal and, if so, implicitly define -fmessage-length appropriately.
3885     unsigned N = llvm::sys::Process::StandardErrColumns();
3886     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3887   }
3888
3889   // -fvisibility= and -fvisibility-ms-compat are of a piece.
3890   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3891                                      options::OPT_fvisibility_ms_compat)) {
3892     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3893       CmdArgs.push_back("-fvisibility");
3894       CmdArgs.push_back(A->getValue());
3895     } else {
3896       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3897       CmdArgs.push_back("-fvisibility");
3898       CmdArgs.push_back("hidden");
3899       CmdArgs.push_back("-ftype-visibility");
3900       CmdArgs.push_back("default");
3901     }
3902   }
3903
3904   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3905
3906   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3907
3908   // -fhosted is default.
3909   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3910       KernelOrKext)
3911     CmdArgs.push_back("-ffreestanding");
3912
3913   // Forward -f (flag) options which we can pass directly.
3914   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3915   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3916   Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
3917   Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
3918   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3919   // AltiVec language extensions aren't relevant for assembling.
3920   if (!isa<PreprocessJobAction>(JA) || 
3921       Output.getType() != types::TY_PP_Asm)
3922     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
3923   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3924   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3925
3926   // Forward flags for OpenMP
3927   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3928                    options::OPT_fno_openmp, false))
3929     switch (getOpenMPRuntime(getToolChain(), Args)) {
3930     case OMPRT_OMP:
3931     case OMPRT_IOMP5:
3932       // Clang can generate useful OpenMP code for these two runtime libraries.
3933       CmdArgs.push_back("-fopenmp");
3934       break;
3935     default:
3936       // By default, if Clang doesn't know how to generate useful OpenMP code
3937       // for a specific runtime library, we just don't pass the '-fopenmp' flag
3938       // down to the actual compilation.
3939       // FIXME: It would be better to have a mode which *only* omits IR
3940       // generation based on the OpenMP support so that we get consistent
3941       // semantic analysis, etc.
3942       break;
3943     }
3944
3945   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3946   Sanitize.addArgs(Args, CmdArgs);
3947
3948   // Report an error for -faltivec on anything other than PowerPC.
3949   if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
3950     const llvm::Triple::ArchType Arch = getToolChain().getArch();
3951     if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
3952           Arch == llvm::Triple::ppc64le))
3953       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3954                                                        << "ppc/ppc64/ppc64le";
3955   }
3956
3957   if (getToolChain().SupportsProfiling())
3958     Args.AddLastArg(CmdArgs, options::OPT_pg);
3959
3960   // -flax-vector-conversions is default.
3961   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3962                     options::OPT_fno_lax_vector_conversions))
3963     CmdArgs.push_back("-fno-lax-vector-conversions");
3964
3965   if (Args.getLastArg(options::OPT_fapple_kext))
3966     CmdArgs.push_back("-fapple-kext");
3967
3968   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3969   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3970   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3971   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3972   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3973
3974   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3975     CmdArgs.push_back("-ftrapv-handler");
3976     CmdArgs.push_back(A->getValue());
3977   }
3978
3979   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3980
3981   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3982   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3983   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
3984                                options::OPT_fno_wrapv)) {
3985     if (A->getOption().matches(options::OPT_fwrapv))
3986       CmdArgs.push_back("-fwrapv");
3987   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3988                                       options::OPT_fno_strict_overflow)) {
3989     if (A->getOption().matches(options::OPT_fno_strict_overflow))
3990       CmdArgs.push_back("-fwrapv");
3991   }
3992
3993   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3994                                options::OPT_fno_reroll_loops))
3995     if (A->getOption().matches(options::OPT_freroll_loops))
3996       CmdArgs.push_back("-freroll-loops");
3997
3998   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3999   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4000                   options::OPT_fno_unroll_loops);
4001
4002   Args.AddLastArg(CmdArgs, options::OPT_pthread);
4003
4004
4005   // -stack-protector=0 is default.
4006   unsigned StackProtectorLevel = 0;
4007   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4008     Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4009     Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4010     Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4011     Args.ClaimAllArgs(options::OPT_fstack_protector);
4012   } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4013                                options::OPT_fstack_protector_all,
4014                                options::OPT_fstack_protector_strong,
4015                                options::OPT_fstack_protector)) {
4016     if (A->getOption().matches(options::OPT_fstack_protector)) {
4017       StackProtectorLevel = std::max<unsigned>(LangOptions::SSPOn,
4018         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4019     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4020       StackProtectorLevel = LangOptions::SSPStrong;
4021     else if (A->getOption().matches(options::OPT_fstack_protector_all))
4022       StackProtectorLevel = LangOptions::SSPReq;
4023   } else {
4024     StackProtectorLevel =
4025       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4026   }
4027   if (StackProtectorLevel) {
4028     CmdArgs.push_back("-stack-protector");
4029     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4030   }
4031
4032   // --param ssp-buffer-size=
4033   for (const Arg *A : Args.filtered(options::OPT__param)) {
4034     StringRef Str(A->getValue());
4035     if (Str.startswith("ssp-buffer-size=")) {
4036       if (StackProtectorLevel) {
4037         CmdArgs.push_back("-stack-protector-buffer-size");
4038         // FIXME: Verify the argument is a valid integer.
4039         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4040       }
4041       A->claim();
4042     }
4043   }
4044
4045   // Translate -mstackrealign
4046   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4047                    false)) {
4048     CmdArgs.push_back("-backend-option");
4049     CmdArgs.push_back("-force-align-stack");
4050   }
4051   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
4052                    false)) {
4053     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4054   }
4055
4056   if (Args.hasArg(options::OPT_mstack_alignment)) {
4057     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4058     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4059   }
4060
4061   if (Args.hasArg(options::OPT_mstack_probe_size)) {
4062     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4063
4064     if (!Size.empty())
4065       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4066     else
4067       CmdArgs.push_back("-mstack-probe-size=0");
4068   }
4069
4070   if (getToolChain().getArch() == llvm::Triple::aarch64 ||
4071       getToolChain().getArch() == llvm::Triple::aarch64_be)
4072     CmdArgs.push_back("-fallow-half-arguments-and-returns");
4073
4074   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4075                                options::OPT_mno_restrict_it)) {
4076     if (A->getOption().matches(options::OPT_mrestrict_it)) {
4077       CmdArgs.push_back("-backend-option");
4078       CmdArgs.push_back("-arm-restrict-it");
4079     } else {
4080       CmdArgs.push_back("-backend-option");
4081       CmdArgs.push_back("-arm-no-restrict-it");
4082     }
4083   } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
4084                                   TT.getArch() == llvm::Triple::thumb)) {
4085     // Windows on ARM expects restricted IT blocks
4086     CmdArgs.push_back("-backend-option");
4087     CmdArgs.push_back("-arm-restrict-it");
4088   }
4089
4090   if (TT.getArch() == llvm::Triple::arm ||
4091       TT.getArch() == llvm::Triple::thumb) {
4092     if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
4093                                  options::OPT_mno_long_calls)) {
4094       if (A->getOption().matches(options::OPT_mlong_calls)) {
4095         CmdArgs.push_back("-backend-option");
4096         CmdArgs.push_back("-arm-long-calls");
4097       }
4098     }
4099   }
4100
4101   // Forward -f options with positive and negative forms; we translate
4102   // these by hand.
4103   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4104     StringRef fname = A->getValue();
4105     if (!llvm::sys::fs::exists(fname))
4106       D.Diag(diag::err_drv_no_such_file) << fname;
4107     else
4108       A->render(Args, CmdArgs);
4109   }
4110
4111   if (Args.hasArg(options::OPT_mkernel)) {
4112     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
4113       CmdArgs.push_back("-fapple-kext");
4114     if (!Args.hasArg(options::OPT_fbuiltin))
4115       CmdArgs.push_back("-fno-builtin");
4116     Args.ClaimAllArgs(options::OPT_fno_builtin);
4117   }
4118   // -fbuiltin is default.
4119   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
4120     CmdArgs.push_back("-fno-builtin");
4121
4122   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4123                     options::OPT_fno_assume_sane_operator_new))
4124     CmdArgs.push_back("-fno-assume-sane-operator-new");
4125
4126   // -fblocks=0 is default.
4127   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4128                    getToolChain().IsBlocksDefault()) ||
4129         (Args.hasArg(options::OPT_fgnu_runtime) &&
4130          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4131          !Args.hasArg(options::OPT_fno_blocks))) {
4132     CmdArgs.push_back("-fblocks");
4133
4134     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
4135         !getToolChain().hasBlocksRuntime())
4136       CmdArgs.push_back("-fblocks-runtime-optional");
4137   }
4138
4139   // -fmodules enables the use of precompiled modules (off by default).
4140   // Users can pass -fno-cxx-modules to turn off modules support for
4141   // C++/Objective-C++ programs.
4142   bool HaveModules = false;
4143   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4144     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
4145                                      options::OPT_fno_cxx_modules, 
4146                                      true);
4147     if (AllowedInCXX || !types::isCXX(InputType)) {
4148       CmdArgs.push_back("-fmodules");
4149       HaveModules = true;
4150     }
4151   }
4152
4153   // -fmodule-maps enables implicit reading of module map files. By default,
4154   // this is enabled if we are using precompiled modules.
4155   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4156                    options::OPT_fno_implicit_module_maps, HaveModules)) {
4157     CmdArgs.push_back("-fimplicit-module-maps");
4158   }
4159
4160   // -fmodules-decluse checks that modules used are declared so (off by
4161   // default).
4162   if (Args.hasFlag(options::OPT_fmodules_decluse,
4163                    options::OPT_fno_modules_decluse,
4164                    false)) {
4165     CmdArgs.push_back("-fmodules-decluse");
4166   }
4167
4168   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4169   // all #included headers are part of modules.
4170   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4171                    options::OPT_fno_modules_strict_decluse,
4172                    false)) {
4173     CmdArgs.push_back("-fmodules-strict-decluse");
4174   }
4175
4176   // -fno-implicit-modules turns off implicitly compiling modules on demand.
4177   if (!Args.hasFlag(options::OPT_fimplicit_modules,
4178                     options::OPT_fno_implicit_modules)) {
4179     CmdArgs.push_back("-fno-implicit-modules");
4180   }
4181
4182   // -fmodule-name specifies the module that is currently being built (or
4183   // used for header checking by -fmodule-maps).
4184   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4185
4186   // -fmodule-map-file can be used to specify files containing module
4187   // definitions.
4188   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4189
4190   // -fmodule-file can be used to specify files containing precompiled modules.
4191   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4192
4193   // -fmodule-cache-path specifies where our implicitly-built module files
4194   // should be written.
4195   SmallString<128> ModuleCachePath;
4196   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4197     ModuleCachePath = A->getValue();
4198   if (HaveModules) {
4199     if (C.isForDiagnostics()) {
4200       // When generating crash reports, we want to emit the modules along with
4201       // the reproduction sources, so we ignore any provided module path.
4202       ModuleCachePath = Output.getFilename();
4203       llvm::sys::path::replace_extension(ModuleCachePath, ".cache");
4204       llvm::sys::path::append(ModuleCachePath, "modules");
4205     } else if (ModuleCachePath.empty()) {
4206       // No module path was provided: use the default.
4207       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
4208                                              ModuleCachePath);
4209       llvm::sys::path::append(ModuleCachePath, "org.llvm.clang.");
4210       appendUserToPath(ModuleCachePath);
4211       llvm::sys::path::append(ModuleCachePath, "ModuleCache");
4212     }
4213     const char Arg[] = "-fmodules-cache-path=";
4214     ModuleCachePath.insert(ModuleCachePath.begin(), Arg, Arg + strlen(Arg));
4215     CmdArgs.push_back(Args.MakeArgString(ModuleCachePath));
4216   }
4217
4218   // When building modules and generating crashdumps, we need to dump a module
4219   // dependency VFS alongside the output.
4220   if (HaveModules && C.isForDiagnostics()) {
4221     SmallString<128> VFSDir(Output.getFilename());
4222     llvm::sys::path::replace_extension(VFSDir, ".cache");
4223     // Add the cache directory as a temp so the crash diagnostics pick it up.
4224     C.addTempFile(Args.MakeArgString(VFSDir));
4225
4226     llvm::sys::path::append(VFSDir, "vfs");
4227     CmdArgs.push_back("-module-dependency-dir");
4228     CmdArgs.push_back(Args.MakeArgString(VFSDir));
4229   }
4230
4231   if (HaveModules)
4232     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4233
4234   // Pass through all -fmodules-ignore-macro arguments.
4235   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4236   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4237   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4238
4239   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4240
4241   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4242     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4243       D.Diag(diag::err_drv_argument_not_allowed_with)
4244           << A->getAsString(Args) << "-fbuild-session-timestamp";
4245
4246     llvm::sys::fs::file_status Status;
4247     if (llvm::sys::fs::status(A->getValue(), Status))
4248       D.Diag(diag::err_drv_no_such_file) << A->getValue();
4249     CmdArgs.push_back(Args.MakeArgString(
4250         "-fbuild-session-timestamp=" +
4251         Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4252   }
4253
4254   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4255     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4256                          options::OPT_fbuild_session_file))
4257       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4258
4259     Args.AddLastArg(CmdArgs,
4260                     options::OPT_fmodules_validate_once_per_build_session);
4261   }
4262
4263   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4264
4265   // -faccess-control is default.
4266   if (Args.hasFlag(options::OPT_fno_access_control,
4267                    options::OPT_faccess_control,
4268                    false))
4269     CmdArgs.push_back("-fno-access-control");
4270
4271   // -felide-constructors is the default.
4272   if (Args.hasFlag(options::OPT_fno_elide_constructors,
4273                    options::OPT_felide_constructors,
4274                    false))
4275     CmdArgs.push_back("-fno-elide-constructors");
4276
4277   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4278
4279   if (KernelOrKext || (types::isCXX(InputType) &&
4280                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4281                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
4282     CmdArgs.push_back("-fno-rtti");
4283
4284   // -fshort-enums=0 is default for all architectures except Hexagon.
4285   if (Args.hasFlag(options::OPT_fshort_enums,
4286                    options::OPT_fno_short_enums,
4287                    getToolChain().getArch() ==
4288                    llvm::Triple::hexagon))
4289     CmdArgs.push_back("-fshort-enums");
4290
4291   // -fsigned-char is default.
4292   if (Arg *A = Args.getLastArg(
4293           options::OPT_fsigned_char, options::OPT_fno_signed_char,
4294           options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4295     if (A->getOption().matches(options::OPT_funsigned_char) ||
4296         A->getOption().matches(options::OPT_fno_signed_char)) {
4297       CmdArgs.push_back("-fno-signed-char");
4298     }
4299   } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4300     CmdArgs.push_back("-fno-signed-char");
4301   }
4302
4303   // -fuse-cxa-atexit is default.
4304   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
4305                     options::OPT_fno_use_cxa_atexit,
4306                     !IsWindowsCygnus && !IsWindowsGNU &&
4307                     getToolChain().getArch() != llvm::Triple::hexagon &&
4308                     getToolChain().getArch() != llvm::Triple::xcore) ||
4309       KernelOrKext)
4310     CmdArgs.push_back("-fno-use-cxa-atexit");
4311
4312   // -fms-extensions=0 is default.
4313   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4314                    IsWindowsMSVC))
4315     CmdArgs.push_back("-fms-extensions");
4316
4317   // -fno-use-line-directives is default.
4318   if (Args.hasFlag(options::OPT_fuse_line_directives,
4319                    options::OPT_fno_use_line_directives, false))
4320     CmdArgs.push_back("-fuse-line-directives");
4321
4322   // -fms-compatibility=0 is default.
4323   if (Args.hasFlag(options::OPT_fms_compatibility, 
4324                    options::OPT_fno_ms_compatibility,
4325                    (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
4326                                                   options::OPT_fno_ms_extensions,
4327                                                   true))))
4328     CmdArgs.push_back("-fms-compatibility");
4329
4330   // -fms-compatibility-version=18.00 is default.
4331   VersionTuple MSVT = visualstudio::getMSVCVersion(
4332       &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4333   if (!MSVT.empty())
4334     CmdArgs.push_back(
4335         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4336
4337   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4338   if (ImplyVCPPCXXVer) {
4339     if (IsMSVC2015Compatible)
4340       CmdArgs.push_back("-std=c++14");
4341     else
4342       CmdArgs.push_back("-std=c++11");
4343   }
4344
4345   // -fno-borland-extensions is default.
4346   if (Args.hasFlag(options::OPT_fborland_extensions,
4347                    options::OPT_fno_borland_extensions, false))
4348     CmdArgs.push_back("-fborland-extensions");
4349
4350   // -fthreadsafe-static is default, except for MSVC compatibility versions less
4351   // than 19.
4352   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4353                     options::OPT_fno_threadsafe_statics,
4354                     !IsWindowsMSVC || IsMSVC2015Compatible))
4355     CmdArgs.push_back("-fno-threadsafe-statics");
4356
4357   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4358   // needs it.
4359   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4360                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4361     CmdArgs.push_back("-fdelayed-template-parsing");
4362
4363   // -fgnu-keywords default varies depending on language; only pass if
4364   // specified.
4365   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4366                                options::OPT_fno_gnu_keywords))
4367     A->render(Args, CmdArgs);
4368
4369   if (Args.hasFlag(options::OPT_fgnu89_inline,
4370                    options::OPT_fno_gnu89_inline,
4371                    false))
4372     CmdArgs.push_back("-fgnu89-inline");
4373
4374   if (Args.hasArg(options::OPT_fno_inline))
4375     CmdArgs.push_back("-fno-inline");
4376
4377   if (Args.hasArg(options::OPT_fno_inline_functions))
4378     CmdArgs.push_back("-fno-inline-functions");
4379
4380   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4381
4382   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
4383   // legacy is the default. Except for deployment taget of 10.5,
4384   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
4385   // gets ignored silently.
4386   if (objcRuntime.isNonFragile()) {
4387     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4388                       options::OPT_fno_objc_legacy_dispatch,
4389                       objcRuntime.isLegacyDispatchDefaultForArch(
4390                         getToolChain().getArch()))) {
4391       if (getToolChain().UseObjCMixedDispatch())
4392         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4393       else
4394         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4395     }
4396   }
4397
4398   // When ObjectiveC legacy runtime is in effect on MacOSX,
4399   // turn on the option to do Array/Dictionary subscripting
4400   // by default.
4401   if (getToolChain().getArch() == llvm::Triple::x86 &&
4402       getToolChain().getTriple().isMacOSX() &&
4403       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
4404       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
4405       objcRuntime.isNeXTFamily())
4406     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4407   
4408   // -fencode-extended-block-signature=1 is default.
4409   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
4410     CmdArgs.push_back("-fencode-extended-block-signature");
4411   }
4412   
4413   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4414   // NOTE: This logic is duplicated in ToolChains.cpp.
4415   bool ARC = isObjCAutoRefCount(Args);
4416   if (ARC) {
4417     getToolChain().CheckObjCARC();
4418
4419     CmdArgs.push_back("-fobjc-arc");
4420
4421     // FIXME: It seems like this entire block, and several around it should be
4422     // wrapped in isObjC, but for now we just use it here as this is where it
4423     // was being used previously.
4424     if (types::isCXX(InputType) && types::isObjC(InputType)) {
4425       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4426         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4427       else
4428         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4429     }
4430
4431     // Allow the user to enable full exceptions code emission.
4432     // We define off for Objective-CC, on for Objective-C++.
4433     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4434                      options::OPT_fno_objc_arc_exceptions,
4435                      /*default*/ types::isCXX(InputType)))
4436       CmdArgs.push_back("-fobjc-arc-exceptions");
4437   }
4438
4439   // -fobjc-infer-related-result-type is the default, except in the Objective-C
4440   // rewriter.
4441   if (rewriteKind != RK_None)
4442     CmdArgs.push_back("-fno-objc-infer-related-result-type");
4443
4444   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4445   // takes precedence.
4446   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4447   if (!GCArg)
4448     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4449   if (GCArg) {
4450     if (ARC) {
4451       D.Diag(diag::err_drv_objc_gc_arr)
4452         << GCArg->getAsString(Args);
4453     } else if (getToolChain().SupportsObjCGC()) {
4454       GCArg->render(Args, CmdArgs);
4455     } else {
4456       // FIXME: We should move this to a hard error.
4457       D.Diag(diag::warn_drv_objc_gc_unsupported)
4458         << GCArg->getAsString(Args);
4459     }
4460   }
4461
4462   if (Args.hasFlag(options::OPT_fapplication_extension,
4463                    options::OPT_fno_application_extension, false))
4464     CmdArgs.push_back("-fapplication-extension");
4465
4466   // Handle GCC-style exception args.
4467   if (!C.getDriver().IsCLMode())
4468     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext,
4469                      objcRuntime, CmdArgs);
4470
4471   if (getToolChain().UseSjLjExceptions())
4472     CmdArgs.push_back("-fsjlj-exceptions");
4473
4474   // C++ "sane" operator new.
4475   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4476                     options::OPT_fno_assume_sane_operator_new))
4477     CmdArgs.push_back("-fno-assume-sane-operator-new");
4478
4479   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4480   // most platforms.
4481   if (Args.hasFlag(options::OPT_fsized_deallocation,
4482                    options::OPT_fno_sized_deallocation, false))
4483     CmdArgs.push_back("-fsized-deallocation");
4484
4485   // -fconstant-cfstrings is default, and may be subject to argument translation
4486   // on Darwin.
4487   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4488                     options::OPT_fno_constant_cfstrings) ||
4489       !Args.hasFlag(options::OPT_mconstant_cfstrings,
4490                     options::OPT_mno_constant_cfstrings))
4491     CmdArgs.push_back("-fno-constant-cfstrings");
4492
4493   // -fshort-wchar default varies depending on platform; only
4494   // pass if specified.
4495   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4496                                options::OPT_fno_short_wchar))
4497     A->render(Args, CmdArgs);
4498
4499   // -fno-pascal-strings is default, only pass non-default.
4500   if (Args.hasFlag(options::OPT_fpascal_strings,
4501                    options::OPT_fno_pascal_strings,
4502                    false))
4503     CmdArgs.push_back("-fpascal-strings");
4504
4505   // Honor -fpack-struct= and -fpack-struct, if given. Note that
4506   // -fno-pack-struct doesn't apply to -fpack-struct=.
4507   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4508     std::string PackStructStr = "-fpack-struct=";
4509     PackStructStr += A->getValue();
4510     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4511   } else if (Args.hasFlag(options::OPT_fpack_struct,
4512                           options::OPT_fno_pack_struct, false)) {
4513     CmdArgs.push_back("-fpack-struct=1");
4514   }
4515
4516   // Handle -fmax-type-align=N and -fno-type-align
4517   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4518   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4519     if (!SkipMaxTypeAlign) {
4520       std::string MaxTypeAlignStr = "-fmax-type-align=";
4521       MaxTypeAlignStr += A->getValue();
4522       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4523     }
4524   } else if (getToolChain().getTriple().isOSDarwin()) {
4525     if (!SkipMaxTypeAlign) {
4526       std::string MaxTypeAlignStr = "-fmax-type-align=16";
4527       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4528     }
4529   }
4530
4531   if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4532     if (!Args.hasArg(options::OPT_fcommon))
4533       CmdArgs.push_back("-fno-common");
4534     Args.ClaimAllArgs(options::OPT_fno_common);
4535   }
4536
4537   // -fcommon is default, only pass non-default.
4538   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4539     CmdArgs.push_back("-fno-common");
4540
4541   // -fsigned-bitfields is default, and clang doesn't yet support
4542   // -funsigned-bitfields.
4543   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4544                     options::OPT_funsigned_bitfields))
4545     D.Diag(diag::warn_drv_clang_unsupported)
4546       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4547
4548   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4549   if (!Args.hasFlag(options::OPT_ffor_scope,
4550                     options::OPT_fno_for_scope))
4551     D.Diag(diag::err_drv_clang_unsupported)
4552       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4553
4554   // -finput_charset=UTF-8 is default. Reject others
4555   if (Arg *inputCharset = Args.getLastArg(
4556           options::OPT_finput_charset_EQ)) {
4557       StringRef value = inputCharset->getValue();
4558       if (value != "UTF-8")
4559           D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) << value;
4560   }
4561
4562   // -fexec_charset=UTF-8 is default. Reject others
4563   if (Arg *execCharset = Args.getLastArg(
4564           options::OPT_fexec_charset_EQ)) {
4565       StringRef value = execCharset->getValue();
4566       if (value != "UTF-8")
4567           D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) << value;
4568   }
4569
4570   // -fcaret-diagnostics is default.
4571   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4572                     options::OPT_fno_caret_diagnostics, true))
4573     CmdArgs.push_back("-fno-caret-diagnostics");
4574
4575   // -fdiagnostics-fixit-info is default, only pass non-default.
4576   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4577                     options::OPT_fno_diagnostics_fixit_info))
4578     CmdArgs.push_back("-fno-diagnostics-fixit-info");
4579
4580   // Enable -fdiagnostics-show-option by default.
4581   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4582                    options::OPT_fno_diagnostics_show_option))
4583     CmdArgs.push_back("-fdiagnostics-show-option");
4584
4585   if (const Arg *A =
4586         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4587     CmdArgs.push_back("-fdiagnostics-show-category");
4588     CmdArgs.push_back(A->getValue());
4589   }
4590
4591   if (const Arg *A =
4592         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4593     CmdArgs.push_back("-fdiagnostics-format");
4594     CmdArgs.push_back(A->getValue());
4595   }
4596
4597   if (Arg *A = Args.getLastArg(
4598       options::OPT_fdiagnostics_show_note_include_stack,
4599       options::OPT_fno_diagnostics_show_note_include_stack)) {
4600     if (A->getOption().matches(
4601         options::OPT_fdiagnostics_show_note_include_stack))
4602       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4603     else
4604       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4605   }
4606
4607   // Color diagnostics are the default, unless the terminal doesn't support
4608   // them.
4609   // Support both clang's -f[no-]color-diagnostics and gcc's
4610   // -f[no-]diagnostics-colors[=never|always|auto].
4611   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4612   for (const auto &Arg : Args) {
4613     const Option &O = Arg->getOption();
4614     if (!O.matches(options::OPT_fcolor_diagnostics) &&
4615         !O.matches(options::OPT_fdiagnostics_color) &&
4616         !O.matches(options::OPT_fno_color_diagnostics) &&
4617         !O.matches(options::OPT_fno_diagnostics_color) &&
4618         !O.matches(options::OPT_fdiagnostics_color_EQ))
4619       continue;
4620
4621     Arg->claim();
4622     if (O.matches(options::OPT_fcolor_diagnostics) ||
4623         O.matches(options::OPT_fdiagnostics_color)) {
4624       ShowColors = Colors_On;
4625     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4626                O.matches(options::OPT_fno_diagnostics_color)) {
4627       ShowColors = Colors_Off;
4628     } else {
4629       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4630       StringRef value(Arg->getValue());
4631       if (value == "always")
4632         ShowColors = Colors_On;
4633       else if (value == "never")
4634         ShowColors = Colors_Off;
4635       else if (value == "auto")
4636         ShowColors = Colors_Auto;
4637       else
4638         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4639           << ("-fdiagnostics-color=" + value).str();
4640     }
4641   }
4642   if (ShowColors == Colors_On ||
4643       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4644     CmdArgs.push_back("-fcolor-diagnostics");
4645
4646   if (Args.hasArg(options::OPT_fansi_escape_codes))
4647     CmdArgs.push_back("-fansi-escape-codes");
4648
4649   if (!Args.hasFlag(options::OPT_fshow_source_location,
4650                     options::OPT_fno_show_source_location))
4651     CmdArgs.push_back("-fno-show-source-location");
4652
4653   if (!Args.hasFlag(options::OPT_fshow_column,
4654                     options::OPT_fno_show_column,
4655                     true))
4656     CmdArgs.push_back("-fno-show-column");
4657
4658   if (!Args.hasFlag(options::OPT_fspell_checking,
4659                     options::OPT_fno_spell_checking))
4660     CmdArgs.push_back("-fno-spell-checking");
4661
4662
4663   // -fno-asm-blocks is default.
4664   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4665                    false))
4666     CmdArgs.push_back("-fasm-blocks");
4667
4668   // -fgnu-inline-asm is default.
4669   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4670                     options::OPT_fno_gnu_inline_asm, true))
4671     CmdArgs.push_back("-fno-gnu-inline-asm");
4672
4673   // Enable vectorization per default according to the optimization level
4674   // selected. For optimization levels that want vectorization we use the alias
4675   // option to simplify the hasFlag logic.
4676   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4677   OptSpecifier VectorizeAliasOption = EnableVec ? options::OPT_O_Group :
4678     options::OPT_fvectorize;
4679   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4680                    options::OPT_fno_vectorize, EnableVec))
4681     CmdArgs.push_back("-vectorize-loops");
4682
4683   // -fslp-vectorize is enabled based on the optimization level selected.
4684   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4685   OptSpecifier SLPVectAliasOption = EnableSLPVec ? options::OPT_O_Group :
4686     options::OPT_fslp_vectorize;
4687   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4688                    options::OPT_fno_slp_vectorize, EnableSLPVec))
4689     CmdArgs.push_back("-vectorize-slp");
4690
4691   // -fno-slp-vectorize-aggressive is default.
4692   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4693                    options::OPT_fno_slp_vectorize_aggressive, false))
4694     CmdArgs.push_back("-vectorize-slp-aggressive");
4695
4696   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4697     A->render(Args, CmdArgs);
4698
4699   // -fdollars-in-identifiers default varies depending on platform and
4700   // language; only pass if specified.
4701   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4702                                options::OPT_fno_dollars_in_identifiers)) {
4703     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4704       CmdArgs.push_back("-fdollars-in-identifiers");
4705     else
4706       CmdArgs.push_back("-fno-dollars-in-identifiers");
4707   }
4708
4709   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4710   // practical purposes.
4711   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4712                                options::OPT_fno_unit_at_a_time)) {
4713     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4714       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4715   }
4716
4717   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4718                    options::OPT_fno_apple_pragma_pack, false))
4719     CmdArgs.push_back("-fapple-pragma-pack");
4720
4721   // le32-specific flags: 
4722   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
4723   //                     by default.
4724   if (getToolChain().getArch() == llvm::Triple::le32) {
4725     CmdArgs.push_back("-fno-math-builtin");
4726   }
4727
4728   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4729   //
4730   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4731 #if 0
4732   if (getToolChain().getTriple().isOSDarwin() &&
4733       (getToolChain().getArch() == llvm::Triple::arm ||
4734        getToolChain().getArch() == llvm::Triple::thumb)) {
4735     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4736       CmdArgs.push_back("-fno-builtin-strcat");
4737     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4738       CmdArgs.push_back("-fno-builtin-strcpy");
4739   }
4740 #endif
4741
4742   // Enable rewrite includes if the user's asked for it or if we're generating
4743   // diagnostics.
4744   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4745   // nice to enable this when doing a crashdump for modules as well.
4746   if (Args.hasFlag(options::OPT_frewrite_includes,
4747                    options::OPT_fno_rewrite_includes, false) ||
4748       (C.isForDiagnostics() && !HaveModules))
4749     CmdArgs.push_back("-frewrite-includes");
4750
4751   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4752   if (Arg *A = Args.getLastArg(options::OPT_traditional,
4753                                options::OPT_traditional_cpp)) {
4754     if (isa<PreprocessJobAction>(JA))
4755       CmdArgs.push_back("-traditional-cpp");
4756     else
4757       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4758   }
4759
4760   Args.AddLastArg(CmdArgs, options::OPT_dM);
4761   Args.AddLastArg(CmdArgs, options::OPT_dD);
4762   
4763   // Handle serialized diagnostics.
4764   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4765     CmdArgs.push_back("-serialize-diagnostic-file");
4766     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4767   }
4768
4769   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4770     CmdArgs.push_back("-fretain-comments-from-system-headers");
4771
4772   // Forward -fcomment-block-commands to -cc1.
4773   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4774   // Forward -fparse-all-comments to -cc1.
4775   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4776
4777   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4778   // parser.
4779   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4780   bool OptDisabled = false;
4781   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4782     A->claim();
4783
4784     // We translate this by hand to the -cc1 argument, since nightly test uses
4785     // it and developers have been trained to spell it with -mllvm.
4786     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4787       CmdArgs.push_back("-disable-llvm-optzns");
4788       OptDisabled = true;
4789     } else
4790       A->render(Args, CmdArgs);
4791   }
4792
4793   // With -save-temps, we want to save the unoptimized bitcode output from the
4794   // CompileJobAction, so disable optimizations if they are not already
4795   // disabled.
4796   if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
4797       isa<CompileJobAction>(JA))
4798     CmdArgs.push_back("-disable-llvm-optzns");
4799
4800   if (Output.getType() == types::TY_Dependencies) {
4801     // Handled with other dependency code.
4802   } else if (Output.isFilename()) {
4803     CmdArgs.push_back("-o");
4804     CmdArgs.push_back(Output.getFilename());
4805   } else {
4806     assert(Output.isNothing() && "Invalid output.");
4807   }
4808
4809   for (const auto &II : Inputs) {
4810     addDashXForInput(Args, II, CmdArgs);
4811
4812     if (II.isFilename())
4813       CmdArgs.push_back(II.getFilename());
4814     else
4815       II.getInputArg().renderAsInput(Args, CmdArgs);
4816   }
4817
4818   Args.AddAllArgs(CmdArgs, options::OPT_undef);
4819
4820   const char *Exec = getToolChain().getDriver().getClangProgramPath();
4821
4822   // Optionally embed the -cc1 level arguments into the debug info, for build
4823   // analysis.
4824   if (getToolChain().UseDwarfDebugFlags()) {
4825     ArgStringList OriginalArgs;
4826     for (const auto &Arg : Args)
4827       Arg->render(Args, OriginalArgs);
4828
4829     SmallString<256> Flags;
4830     Flags += Exec;
4831     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
4832       SmallString<128> EscapedArg;
4833       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
4834       Flags += " ";
4835       Flags += EscapedArg;
4836     }
4837     CmdArgs.push_back("-dwarf-debug-flags");
4838     CmdArgs.push_back(Args.MakeArgString(Flags));
4839   }
4840
4841   // Add the split debug info name to the command lines here so we
4842   // can propagate it to the backend.
4843   bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4844     getToolChain().getTriple().isOSLinux() &&
4845     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4846      isa<BackendJobAction>(JA));
4847   const char *SplitDwarfOut;
4848   if (SplitDwarf) {
4849     CmdArgs.push_back("-split-dwarf-file");
4850     SplitDwarfOut = SplitDebugName(Args, Input);
4851     CmdArgs.push_back(SplitDwarfOut);
4852   }
4853
4854   // Finally add the compile command to the compilation.
4855   if (Args.hasArg(options::OPT__SLASH_fallback) &&
4856       Output.getType() == types::TY_Object &&
4857       (InputType == types::TY_C || InputType == types::TY_CXX)) {
4858     auto CLCommand =
4859         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4860     C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
4861                                                     std::move(CLCommand)));
4862   } else {
4863     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
4864   }
4865
4866
4867   // Handle the debug info splitting at object creation time if we're
4868   // creating an object.
4869   // TODO: Currently only works on linux with newer objcopy.
4870   if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4871     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4872
4873   if (Arg *A = Args.getLastArg(options::OPT_pg))
4874     if (Args.hasArg(options::OPT_fomit_frame_pointer))
4875       D.Diag(diag::err_drv_argument_not_allowed_with)
4876         << "-fomit-frame-pointer" << A->getAsString(Args);
4877
4878   // Claim some arguments which clang supports automatically.
4879
4880   // -fpch-preprocess is used with gcc to add a special marker in the output to
4881   // include the PCH file. Clang's PTH solution is completely transparent, so we
4882   // do not need to deal with it at all.
4883   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4884
4885   // Claim some arguments which clang doesn't support, but we don't
4886   // care to warn the user about.
4887   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4888   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4889
4890   // Disable warnings for clang -E -emit-llvm foo.c
4891   Args.ClaimAllArgs(options::OPT_emit_llvm);
4892 }
4893
4894 /// Add options related to the Objective-C runtime/ABI.
4895 ///
4896 /// Returns true if the runtime is non-fragile.
4897 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4898                                       ArgStringList &cmdArgs,
4899                                       RewriteKind rewriteKind) const {
4900   // Look for the controlling runtime option.
4901   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
4902                                     options::OPT_fgnu_runtime,
4903                                     options::OPT_fobjc_runtime_EQ);
4904
4905   // Just forward -fobjc-runtime= to the frontend.  This supercedes
4906   // options about fragility.
4907   if (runtimeArg &&
4908       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4909     ObjCRuntime runtime;
4910     StringRef value = runtimeArg->getValue();
4911     if (runtime.tryParse(value)) {
4912       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4913         << value;
4914     }
4915
4916     runtimeArg->render(args, cmdArgs);
4917     return runtime;
4918   }
4919
4920   // Otherwise, we'll need the ABI "version".  Version numbers are
4921   // slightly confusing for historical reasons:
4922   //   1 - Traditional "fragile" ABI
4923   //   2 - Non-fragile ABI, version 1
4924   //   3 - Non-fragile ABI, version 2
4925   unsigned objcABIVersion = 1;
4926   // If -fobjc-abi-version= is present, use that to set the version.
4927   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4928     StringRef value = abiArg->getValue();
4929     if (value == "1")
4930       objcABIVersion = 1;
4931     else if (value == "2")
4932       objcABIVersion = 2;
4933     else if (value == "3")
4934       objcABIVersion = 3;
4935     else
4936       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4937         << value;
4938   } else {
4939     // Otherwise, determine if we are using the non-fragile ABI.
4940     bool nonFragileABIIsDefault = 
4941       (rewriteKind == RK_NonFragile || 
4942        (rewriteKind == RK_None &&
4943         getToolChain().IsObjCNonFragileABIDefault()));
4944     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4945                      options::OPT_fno_objc_nonfragile_abi,
4946                      nonFragileABIIsDefault)) {
4947       // Determine the non-fragile ABI version to use.
4948 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4949       unsigned nonFragileABIVersion = 1;
4950 #else
4951       unsigned nonFragileABIVersion = 2;
4952 #endif
4953
4954       if (Arg *abiArg = args.getLastArg(
4955             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4956         StringRef value = abiArg->getValue();
4957         if (value == "1")
4958           nonFragileABIVersion = 1;
4959         else if (value == "2")
4960           nonFragileABIVersion = 2;
4961         else
4962           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4963             << value;
4964       }
4965
4966       objcABIVersion = 1 + nonFragileABIVersion;
4967     } else {
4968       objcABIVersion = 1;
4969     }
4970   }
4971
4972   // We don't actually care about the ABI version other than whether
4973   // it's non-fragile.
4974   bool isNonFragile = objcABIVersion != 1;
4975
4976   // If we have no runtime argument, ask the toolchain for its default runtime.
4977   // However, the rewriter only really supports the Mac runtime, so assume that.
4978   ObjCRuntime runtime;
4979   if (!runtimeArg) {
4980     switch (rewriteKind) {
4981     case RK_None:
4982       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4983       break;
4984     case RK_Fragile:
4985       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4986       break;
4987     case RK_NonFragile:
4988       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4989       break;
4990     }
4991
4992   // -fnext-runtime
4993   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4994     // On Darwin, make this use the default behavior for the toolchain.
4995     if (getToolChain().getTriple().isOSDarwin()) {
4996       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4997
4998     // Otherwise, build for a generic macosx port.
4999     } else {
5000       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5001     }
5002
5003   // -fgnu-runtime
5004   } else {
5005     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5006     // Legacy behaviour is to target the gnustep runtime if we are i
5007     // non-fragile mode or the GCC runtime in fragile mode.
5008     if (isNonFragile)
5009       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
5010     else
5011       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5012   }
5013
5014   cmdArgs.push_back(args.MakeArgString(
5015                                  "-fobjc-runtime=" + runtime.getAsString()));
5016   return runtime;
5017 }
5018
5019 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5020   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5021   I += HaveDash;
5022   return !HaveDash;
5023 }
5024
5025 struct EHFlags {
5026   EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5027   bool Synch;
5028   bool Asynch;
5029   bool NoExceptC;
5030 };
5031
5032 /// /EH controls whether to run destructor cleanups when exceptions are
5033 /// thrown.  There are three modifiers:
5034 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5035 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5036 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5037 /// - c: Assume that extern "C" functions are implicitly noexcept.  This
5038 ///      modifier is an optimization, so we ignore it for now.
5039 /// The default is /EHs-c-, meaning cleanups are disabled.
5040 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5041   EHFlags EH;
5042   std::vector<std::string> EHArgs = Args.getAllArgValues(options::OPT__SLASH_EH);
5043   for (auto EHVal : EHArgs) {
5044     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5045       switch (EHVal[I]) {
5046       case 'a': EH.Asynch = maybeConsumeDash(EHVal, I); continue;
5047       case 'c': EH.NoExceptC = maybeConsumeDash(EHVal, I); continue;
5048       case 's': EH.Synch = maybeConsumeDash(EHVal, I); continue;
5049       default: break;
5050       }
5051       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5052       break;
5053     }
5054   }
5055   return EH;
5056 }
5057
5058 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
5059   unsigned RTOptionID = options::OPT__SLASH_MT;
5060
5061   if (Args.hasArg(options::OPT__SLASH_LDd))
5062     // The /LDd option implies /MTd. The dependent lib part can be overridden,
5063     // but defining _DEBUG is sticky.
5064     RTOptionID = options::OPT__SLASH_MTd;
5065
5066   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5067     RTOptionID = A->getOption().getID();
5068
5069   switch(RTOptionID) {
5070     case options::OPT__SLASH_MD:
5071       if (Args.hasArg(options::OPT__SLASH_LDd))
5072         CmdArgs.push_back("-D_DEBUG");
5073       CmdArgs.push_back("-D_MT");
5074       CmdArgs.push_back("-D_DLL");
5075       CmdArgs.push_back("--dependent-lib=msvcrt");
5076       break;
5077     case options::OPT__SLASH_MDd:
5078       CmdArgs.push_back("-D_DEBUG");
5079       CmdArgs.push_back("-D_MT");
5080       CmdArgs.push_back("-D_DLL");
5081       CmdArgs.push_back("--dependent-lib=msvcrtd");
5082       break;
5083     case options::OPT__SLASH_MT:
5084       if (Args.hasArg(options::OPT__SLASH_LDd))
5085         CmdArgs.push_back("-D_DEBUG");
5086       CmdArgs.push_back("-D_MT");
5087       CmdArgs.push_back("--dependent-lib=libcmt");
5088       break;
5089     case options::OPT__SLASH_MTd:
5090       CmdArgs.push_back("-D_DEBUG");
5091       CmdArgs.push_back("-D_MT");
5092       CmdArgs.push_back("--dependent-lib=libcmtd");
5093       break;
5094     default:
5095       llvm_unreachable("Unexpected option ID.");
5096   }
5097
5098   // This provides POSIX compatibility (maps 'open' to '_open'), which most
5099   // users want.  The /Za flag to cl.exe turns this off, but it's not
5100   // implemented in clang.
5101   CmdArgs.push_back("--dependent-lib=oldnames");
5102
5103   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5104   // would produce interleaved output, so ignore /showIncludes in such cases.
5105   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5106     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5107       A->render(Args, CmdArgs);
5108
5109   // This controls whether or not we emit RTTI data for polymorphic types.
5110   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5111                    /*default=*/false))
5112     CmdArgs.push_back("-fno-rtti-data");
5113
5114   const Driver &D = getToolChain().getDriver();
5115   EHFlags EH = parseClangCLEHFlags(D, Args);
5116   // FIXME: Do something with NoExceptC.
5117   if (EH.Synch || EH.Asynch) {
5118     CmdArgs.push_back("-fcxx-exceptions");
5119     CmdArgs.push_back("-fexceptions");
5120   }
5121
5122   // /EP should expand to -E -P.
5123   if (Args.hasArg(options::OPT__SLASH_EP)) {
5124     CmdArgs.push_back("-E");
5125     CmdArgs.push_back("-P");
5126   }
5127
5128   unsigned VolatileOptionID;
5129   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5130       getToolChain().getArch() == llvm::Triple::x86)
5131     VolatileOptionID = options::OPT__SLASH_volatile_ms;
5132   else
5133     VolatileOptionID = options::OPT__SLASH_volatile_iso;
5134
5135   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5136     VolatileOptionID = A->getOption().getID();
5137
5138   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5139     CmdArgs.push_back("-fms-volatile");
5140
5141   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5142   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5143   if (MostGeneralArg && BestCaseArg)
5144     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5145         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5146
5147   if (MostGeneralArg) {
5148     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5149     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5150     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5151
5152     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5153     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5154     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5155       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5156           << FirstConflict->getAsString(Args)
5157           << SecondConflict->getAsString(Args);
5158
5159     if (SingleArg)
5160       CmdArgs.push_back("-fms-memptr-rep=single");
5161     else if (MultipleArg)
5162       CmdArgs.push_back("-fms-memptr-rep=multiple");
5163     else
5164       CmdArgs.push_back("-fms-memptr-rep=virtual");
5165   }
5166
5167   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5168     A->render(Args, CmdArgs);
5169
5170   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5171     CmdArgs.push_back("-fdiagnostics-format");
5172     if (Args.hasArg(options::OPT__SLASH_fallback))
5173       CmdArgs.push_back("msvc-fallback");
5174     else
5175       CmdArgs.push_back("msvc");
5176   }
5177 }
5178
5179 visualstudio::Compile *Clang::getCLFallback() const {
5180   if (!CLFallback)
5181     CLFallback.reset(new visualstudio::Compile(getToolChain()));
5182   return CLFallback.get();
5183 }
5184
5185 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5186                                 ArgStringList &CmdArgs) const {
5187   StringRef CPUName;
5188   StringRef ABIName;
5189   const llvm::Triple &Triple = getToolChain().getTriple();
5190   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5191
5192   CmdArgs.push_back("-target-abi");
5193   CmdArgs.push_back(ABIName.data());
5194 }
5195
5196 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5197                            const InputInfo &Output,
5198                            const InputInfoList &Inputs,
5199                            const ArgList &Args,
5200                            const char *LinkingOutput) const {
5201   ArgStringList CmdArgs;
5202
5203   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5204   const InputInfo &Input = Inputs[0];
5205
5206   // Don't warn about "clang -w -c foo.s"
5207   Args.ClaimAllArgs(options::OPT_w);
5208   // and "clang -emit-llvm -c foo.s"
5209   Args.ClaimAllArgs(options::OPT_emit_llvm);
5210
5211   claimNoWarnArgs(Args);
5212
5213   // Invoke ourselves in -cc1as mode.
5214   //
5215   // FIXME: Implement custom jobs for internal actions.
5216   CmdArgs.push_back("-cc1as");
5217
5218   // Add the "effective" target triple.
5219   CmdArgs.push_back("-triple");
5220   std::string TripleStr = 
5221     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5222   CmdArgs.push_back(Args.MakeArgString(TripleStr));
5223
5224   // Set the output mode, we currently only expect to be used as a real
5225   // assembler.
5226   CmdArgs.push_back("-filetype");
5227   CmdArgs.push_back("obj");
5228
5229   // Set the main file name, so that debug info works even with
5230   // -save-temps or preprocessed assembly.
5231   CmdArgs.push_back("-main-file-name");
5232   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5233
5234   // Add the target cpu
5235   const llvm::Triple Triple(TripleStr);
5236   std::string CPU = getCPUName(Args, Triple);
5237   if (!CPU.empty()) {
5238     CmdArgs.push_back("-target-cpu");
5239     CmdArgs.push_back(Args.MakeArgString(CPU));
5240   }
5241
5242   // Add the target features
5243   const Driver &D = getToolChain().getDriver();
5244   getTargetFeatures(D, Triple, Args, CmdArgs, true);
5245
5246   // Ignore explicit -force_cpusubtype_ALL option.
5247   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
5248
5249   // Determine the original source input.
5250   const Action *SourceAction = &JA;
5251   while (SourceAction->getKind() != Action::InputClass) {
5252     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5253     SourceAction = SourceAction->getInputs()[0];
5254   }
5255
5256   // Forward -g and handle debug info related flags, assuming we are dealing
5257   // with an actual assembly file.
5258   if (SourceAction->getType() == types::TY_Asm ||
5259       SourceAction->getType() == types::TY_PP_Asm) {
5260     Args.ClaimAllArgs(options::OPT_g_Group);
5261     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
5262       if (!A->getOption().matches(options::OPT_g0))
5263         CmdArgs.push_back("-g");
5264
5265     if (Args.hasArg(options::OPT_gdwarf_2))
5266       CmdArgs.push_back("-gdwarf-2");
5267     if (Args.hasArg(options::OPT_gdwarf_3))
5268       CmdArgs.push_back("-gdwarf-3");
5269     if (Args.hasArg(options::OPT_gdwarf_4))
5270       CmdArgs.push_back("-gdwarf-4");
5271
5272     // Add the -fdebug-compilation-dir flag if needed.
5273     addDebugCompDirArg(Args, CmdArgs);
5274
5275     // Set the AT_producer to the clang version when using the integrated
5276     // assembler on assembly source files.
5277     CmdArgs.push_back("-dwarf-debug-producer");
5278     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5279   }
5280
5281   // Optionally embed the -cc1as level arguments into the debug info, for build
5282   // analysis.
5283   if (getToolChain().UseDwarfDebugFlags()) {
5284     ArgStringList OriginalArgs;
5285     for (const auto &Arg : Args)
5286       Arg->render(Args, OriginalArgs);
5287
5288     SmallString<256> Flags;
5289     const char *Exec = getToolChain().getDriver().getClangProgramPath();
5290     Flags += Exec;
5291     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
5292       SmallString<128> EscapedArg;
5293       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
5294       Flags += " ";
5295       Flags += EscapedArg;
5296     }
5297     CmdArgs.push_back("-dwarf-debug-flags");
5298     CmdArgs.push_back(Args.MakeArgString(Flags));
5299   }
5300
5301   // FIXME: Add -static support, once we have it.
5302
5303   // Add target specific flags.
5304   switch(getToolChain().getArch()) {
5305   default:
5306     break;
5307
5308   case llvm::Triple::mips:
5309   case llvm::Triple::mipsel:
5310   case llvm::Triple::mips64:
5311   case llvm::Triple::mips64el:
5312     AddMIPSTargetArgs(Args, CmdArgs);
5313     break;
5314   }
5315
5316   // Consume all the warning flags. Usually this would be handled more
5317   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5318   // doesn't handle that so rather than warning about unused flags that are
5319   // actually used, we'll lie by omission instead.
5320   // FIXME: Stop lying and consume only the appropriate driver flags
5321   for (const Arg *A : Args.filtered(options::OPT_W_Group))
5322     A->claim();
5323
5324   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5325                                     getToolChain().getDriver());
5326
5327   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5328
5329   assert(Output.isFilename() && "Unexpected lipo output.");
5330   CmdArgs.push_back("-o");
5331   CmdArgs.push_back(Output.getFilename());
5332
5333   assert(Input.isFilename() && "Invalid input.");
5334   CmdArgs.push_back(Input.getFilename());
5335
5336   const char *Exec = getToolChain().getDriver().getClangProgramPath();
5337   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5338
5339   // Handle the debug info splitting at object creation time if we're
5340   // creating an object.
5341   // TODO: Currently only works on linux with newer objcopy.
5342   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5343       getToolChain().getTriple().isOSLinux())
5344     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5345                    SplitDebugName(Args, Input));
5346 }
5347
5348 void GnuTool::anchor() {}
5349
5350 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
5351                                const InputInfo &Output,
5352                                const InputInfoList &Inputs,
5353                                const ArgList &Args,
5354                                const char *LinkingOutput) const {
5355   const Driver &D = getToolChain().getDriver();
5356   ArgStringList CmdArgs;
5357
5358   for (const auto &A : Args) {
5359     if (forwardToGCC(A->getOption())) {
5360       // Don't forward any -g arguments to assembly steps.
5361       if (isa<AssembleJobAction>(JA) &&
5362           A->getOption().matches(options::OPT_g_Group))
5363         continue;
5364
5365       // Don't forward any -W arguments to assembly and link steps.
5366       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
5367           A->getOption().matches(options::OPT_W_Group))
5368         continue;
5369
5370       // It is unfortunate that we have to claim here, as this means
5371       // we will basically never report anything interesting for
5372       // platforms using a generic gcc, even if we are just using gcc
5373       // to get to the assembler.
5374       A->claim();
5375       A->render(Args, CmdArgs);
5376     }
5377   }
5378
5379   RenderExtraToolArgs(JA, CmdArgs);
5380
5381   // If using a driver driver, force the arch.
5382   if (getToolChain().getTriple().isOSDarwin()) {
5383     CmdArgs.push_back("-arch");
5384     CmdArgs.push_back(
5385       Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
5386   }
5387
5388   // Try to force gcc to match the tool chain we want, if we recognize
5389   // the arch.
5390   //
5391   // FIXME: The triple class should directly provide the information we want
5392   // here.
5393   const llvm::Triple::ArchType Arch = getToolChain().getArch();
5394   if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
5395     CmdArgs.push_back("-m32");
5396   else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
5397            Arch == llvm::Triple::ppc64le)
5398     CmdArgs.push_back("-m64");
5399
5400   if (Output.isFilename()) {
5401     CmdArgs.push_back("-o");
5402     CmdArgs.push_back(Output.getFilename());
5403   } else {
5404     assert(Output.isNothing() && "Unexpected output");
5405     CmdArgs.push_back("-fsyntax-only");
5406   }
5407
5408   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5409                        options::OPT_Xassembler);
5410
5411   // Only pass -x if gcc will understand it; otherwise hope gcc
5412   // understands the suffix correctly. The main use case this would go
5413   // wrong in is for linker inputs if they happened to have an odd
5414   // suffix; really the only way to get this to happen is a command
5415   // like '-x foobar a.c' which will treat a.c like a linker input.
5416   //
5417   // FIXME: For the linker case specifically, can we safely convert
5418   // inputs into '-Wl,' options?
5419   for (const auto &II : Inputs) {
5420     // Don't try to pass LLVM or AST inputs to a generic gcc.
5421     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5422         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5423       D.Diag(diag::err_drv_no_linker_llvm_support)
5424         << getToolChain().getTripleString();
5425     else if (II.getType() == types::TY_AST)
5426       D.Diag(diag::err_drv_no_ast_support)
5427         << getToolChain().getTripleString();
5428     else if (II.getType() == types::TY_ModuleFile)
5429       D.Diag(diag::err_drv_no_module_support)
5430         << getToolChain().getTripleString();
5431
5432     if (types::canTypeBeUserSpecified(II.getType())) {
5433       CmdArgs.push_back("-x");
5434       CmdArgs.push_back(types::getTypeName(II.getType()));
5435     }
5436
5437     if (II.isFilename())
5438       CmdArgs.push_back(II.getFilename());
5439     else {
5440       const Arg &A = II.getInputArg();
5441
5442       // Reverse translate some rewritten options.
5443       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
5444         CmdArgs.push_back("-lstdc++");
5445         continue;
5446       }
5447
5448       // Don't render as input, we need gcc to do the translations.
5449       A.render(Args, CmdArgs);
5450     }
5451   }
5452
5453   const std::string customGCCName = D.getCCCGenericGCCName();
5454   const char *GCCName;
5455   if (!customGCCName.empty())
5456     GCCName = customGCCName.c_str();
5457   else if (D.CCCIsCXX()) {
5458     GCCName = "g++";
5459   } else
5460     GCCName = "gcc";
5461
5462   const char *Exec =
5463     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5464   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5465 }
5466
5467 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
5468                                           ArgStringList &CmdArgs) const {
5469   CmdArgs.push_back("-E");
5470 }
5471
5472 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
5473                                        ArgStringList &CmdArgs) const {
5474   const Driver &D = getToolChain().getDriver();
5475
5476   switch (JA.getType()) {
5477   // If -flto, etc. are present then make sure not to force assembly output.
5478   case types::TY_LLVM_IR:
5479   case types::TY_LTO_IR:
5480   case types::TY_LLVM_BC:
5481   case types::TY_LTO_BC:
5482     CmdArgs.push_back("-c");
5483     break;
5484   case types::TY_PP_Asm:
5485     CmdArgs.push_back("-S");
5486     break;
5487   case types::TY_Nothing:
5488     CmdArgs.push_back("-fsyntax-only");
5489     break;
5490   default:
5491     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
5492   }
5493 }
5494
5495 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
5496                                     ArgStringList &CmdArgs) const {
5497   // The types are (hopefully) good enough.
5498 }
5499
5500 // Hexagon tools start.
5501 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
5502                                         ArgStringList &CmdArgs) const {
5503
5504 }
5505 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5506                                const InputInfo &Output,
5507                                const InputInfoList &Inputs,
5508                                const ArgList &Args,
5509                                const char *LinkingOutput) const {
5510   claimNoWarnArgs(Args);
5511
5512   const Driver &D = getToolChain().getDriver();
5513   ArgStringList CmdArgs;
5514
5515   std::string MarchString = "-march=";
5516   MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5517   CmdArgs.push_back(Args.MakeArgString(MarchString));
5518
5519   RenderExtraToolArgs(JA, CmdArgs);
5520
5521   if (Output.isFilename()) {
5522     CmdArgs.push_back("-o");
5523     CmdArgs.push_back(Output.getFilename());
5524   } else {
5525     assert(Output.isNothing() && "Unexpected output");
5526     CmdArgs.push_back("-fsyntax-only");
5527   }
5528
5529   if (const char* v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args))
5530     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5531
5532   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5533                        options::OPT_Xassembler);
5534
5535   // Only pass -x if gcc will understand it; otherwise hope gcc
5536   // understands the suffix correctly. The main use case this would go
5537   // wrong in is for linker inputs if they happened to have an odd
5538   // suffix; really the only way to get this to happen is a command
5539   // like '-x foobar a.c' which will treat a.c like a linker input.
5540   //
5541   // FIXME: For the linker case specifically, can we safely convert
5542   // inputs into '-Wl,' options?
5543   for (const auto &II : Inputs) {
5544     // Don't try to pass LLVM or AST inputs to a generic gcc.
5545     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5546         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5547       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5548         << getToolChain().getTripleString();
5549     else if (II.getType() == types::TY_AST)
5550       D.Diag(clang::diag::err_drv_no_ast_support)
5551         << getToolChain().getTripleString();
5552     else if (II.getType() == types::TY_ModuleFile)
5553       D.Diag(diag::err_drv_no_module_support)
5554       << getToolChain().getTripleString();
5555
5556     if (II.isFilename())
5557       CmdArgs.push_back(II.getFilename());
5558     else
5559       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
5560       II.getInputArg().render(Args, CmdArgs);
5561   }
5562
5563   const char *GCCName = "hexagon-as";
5564   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5565   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5566 }
5567
5568 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
5569                                     ArgStringList &CmdArgs) const {
5570   // The types are (hopefully) good enough.
5571 }
5572
5573 static void constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
5574                               const toolchains::Hexagon_TC& ToolChain,
5575                               const InputInfo &Output,
5576                               const InputInfoList &Inputs,
5577                               const ArgList &Args,
5578                               ArgStringList &CmdArgs,
5579                               const char *LinkingOutput) {
5580
5581   const Driver &D = ToolChain.getDriver();
5582
5583
5584   //----------------------------------------------------------------------------
5585   //
5586   //----------------------------------------------------------------------------
5587   bool hasStaticArg = Args.hasArg(options::OPT_static);
5588   bool buildingLib = Args.hasArg(options::OPT_shared);
5589   bool buildPIE = Args.hasArg(options::OPT_pie);
5590   bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5591   bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5592   bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5593   bool useG0 = false;
5594   bool useShared = buildingLib && !hasStaticArg;
5595
5596   //----------------------------------------------------------------------------
5597   // Silence warnings for various options
5598   //----------------------------------------------------------------------------
5599
5600   Args.ClaimAllArgs(options::OPT_g_Group);
5601   Args.ClaimAllArgs(options::OPT_emit_llvm);
5602   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5603                                      // handled somewhere else.
5604   Args.ClaimAllArgs(options::OPT_static_libgcc);
5605
5606   //----------------------------------------------------------------------------
5607   //
5608   //----------------------------------------------------------------------------
5609   for (const auto &Opt : ToolChain.ExtraOpts)
5610     CmdArgs.push_back(Opt.c_str());
5611
5612   std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5613   CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5614
5615   if (buildingLib) {
5616     CmdArgs.push_back("-shared");
5617     CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5618                                        // hexagon-gcc does
5619   }
5620
5621   if (hasStaticArg)
5622     CmdArgs.push_back("-static");
5623
5624   if (buildPIE && !buildingLib)
5625     CmdArgs.push_back("-pie");
5626
5627   if (const char* v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
5628     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5629     useG0 = toolchains::Hexagon_TC::UsesG0(v);
5630   }
5631
5632   //----------------------------------------------------------------------------
5633   //
5634   //----------------------------------------------------------------------------
5635   CmdArgs.push_back("-o");
5636   CmdArgs.push_back(Output.getFilename());
5637
5638   const std::string MarchSuffix = "/" + MarchString;
5639   const std::string G0Suffix = "/G0";
5640   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5641   const std::string RootDir =
5642       toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
5643   const std::string StartFilesDir = RootDir
5644                                     + "hexagon/lib"
5645                                     + (useG0 ? MarchG0Suffix : MarchSuffix);
5646
5647   //----------------------------------------------------------------------------
5648   // moslib
5649   //----------------------------------------------------------------------------
5650   std::vector<std::string> oslibs;
5651   bool hasStandalone= false;
5652
5653   for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
5654     A->claim();
5655     oslibs.emplace_back(A->getValue());
5656     hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5657   }
5658   if (oslibs.empty()) {
5659     oslibs.push_back("standalone");
5660     hasStandalone = true;
5661   }
5662
5663   //----------------------------------------------------------------------------
5664   // Start Files
5665   //----------------------------------------------------------------------------
5666   if (incStdLib && incStartFiles) {
5667
5668     if (!buildingLib) {
5669       if (hasStandalone) {
5670         CmdArgs.push_back(
5671           Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5672       }
5673       CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5674     }
5675     std::string initObj = useShared ? "/initS.o" : "/init.o";
5676     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5677   }
5678
5679   //----------------------------------------------------------------------------
5680   // Library Search Paths
5681   //----------------------------------------------------------------------------
5682   const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5683   for (const auto &LibPath : LibPaths)
5684     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5685
5686   //----------------------------------------------------------------------------
5687   //
5688   //----------------------------------------------------------------------------
5689   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5690   Args.AddAllArgs(CmdArgs, options::OPT_e);
5691   Args.AddAllArgs(CmdArgs, options::OPT_s);
5692   Args.AddAllArgs(CmdArgs, options::OPT_t);
5693   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5694
5695   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5696
5697   //----------------------------------------------------------------------------
5698   // Libraries
5699   //----------------------------------------------------------------------------
5700   if (incStdLib && incDefLibs) {
5701     if (D.CCCIsCXX()) {
5702       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5703       CmdArgs.push_back("-lm");
5704     }
5705
5706     CmdArgs.push_back("--start-group");
5707
5708     if (!buildingLib) {
5709       for(std::vector<std::string>::iterator i = oslibs.begin(),
5710             e = oslibs.end(); i != e; ++i)
5711         CmdArgs.push_back(Args.MakeArgString("-l" + *i));
5712       CmdArgs.push_back("-lc");
5713     }
5714     CmdArgs.push_back("-lgcc");
5715
5716     CmdArgs.push_back("--end-group");
5717   }
5718
5719   //----------------------------------------------------------------------------
5720   // End files
5721   //----------------------------------------------------------------------------
5722   if (incStdLib && incStartFiles) {
5723     std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5724     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5725   }
5726 }
5727
5728 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
5729                                const InputInfo &Output,
5730                                const InputInfoList &Inputs,
5731                                const ArgList &Args,
5732                                const char *LinkingOutput) const {
5733
5734   const toolchains::Hexagon_TC& ToolChain =
5735     static_cast<const toolchains::Hexagon_TC&>(getToolChain());
5736
5737   ArgStringList CmdArgs;
5738   constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
5739                            LinkingOutput);
5740
5741   std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5742   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
5743                                           CmdArgs));
5744 }
5745 // Hexagon tools end.
5746
5747 const std::string arm::getARMArch(const ArgList &Args,
5748                                   const llvm::Triple &Triple) {
5749   std::string MArch;
5750   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
5751     // Otherwise, if we have -march= choose the base CPU for that arch.
5752     MArch = A->getValue();
5753   } else {
5754     // Otherwise, use the Arch from the triple.
5755     MArch = Triple.getArchName();
5756   }
5757   MArch = StringRef(MArch).lower();
5758
5759   // Handle -march=native.
5760   if (MArch == "native") {
5761     std::string CPU = llvm::sys::getHostCPUName();
5762     if (CPU != "generic") {
5763       // Translate the native cpu into the architecture suffix for that CPU.
5764       const char *Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch);
5765       // If there is no valid architecture suffix for this CPU we don't know how
5766       // to handle it, so return no architecture.
5767       if (strcmp(Suffix,"") == 0)
5768         MArch = "";
5769       else
5770         MArch = std::string("arm") + Suffix;
5771     }
5772   }
5773
5774   return MArch;
5775 }
5776 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
5777 const char *arm::getARMCPUForMArch(const ArgList &Args,
5778                                    const llvm::Triple &Triple) {
5779   std::string MArch = getARMArch(Args, Triple);
5780   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
5781   // here means an -march=native that we can't handle, so instead return no CPU.
5782   if (MArch.empty())
5783     return "";
5784
5785   // We need to return an empty string here on invalid MArch values as the
5786   // various places that call this function can't cope with a null result.
5787   const char *result = Triple.getARMCPUForArch(MArch);
5788   if (result)
5789     return result;
5790   else
5791     return "";
5792 }
5793
5794 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
5795 std::string arm::getARMTargetCPU(const ArgList &Args,
5796                                const llvm::Triple &Triple) {
5797   // FIXME: Warn on inconsistent use of -mcpu and -march.
5798   // If we have -mcpu=, use that.
5799   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
5800     std::string MCPU = StringRef(A->getValue()).lower();
5801     // Handle -mcpu=native.
5802     if (MCPU == "native")
5803       return llvm::sys::getHostCPUName();
5804     else
5805       return MCPU;
5806   }
5807
5808   return getARMCPUForMArch(Args, Triple);
5809 }
5810
5811 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5812 /// CPU  (or Arch, if CPU is generic).
5813 // FIXME: This is redundant with -mcpu, why does LLVM use this.
5814 const char *arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch) {
5815   if (CPU == "generic" &&
5816       llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_ARMV8_1A)
5817     return "v8.1a";
5818
5819   unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
5820   if (ArchKind == llvm::ARM::AK_INVALID)
5821     return "";
5822   return llvm::ARMTargetParser::getSubArch(ArchKind);
5823 }
5824
5825 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs, 
5826                             const llvm::Triple &Triple) {
5827   if (Args.hasArg(options::OPT_r))
5828     return;
5829
5830   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
5831   // to generate BE-8 executables.
5832   if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
5833     CmdArgs.push_back("--be8");
5834 }
5835
5836 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
5837   return (NanEncoding)llvm::StringSwitch<int>(CPU)
5838       .Case("mips1", NanLegacy)
5839       .Case("mips2", NanLegacy)
5840       .Case("mips3", NanLegacy)
5841       .Case("mips4", NanLegacy)
5842       .Case("mips5", NanLegacy)
5843       .Case("mips32", NanLegacy)
5844       .Case("mips32r2", NanLegacy)
5845       .Case("mips32r3", NanLegacy | Nan2008)
5846       .Case("mips32r5", NanLegacy | Nan2008)
5847       .Case("mips32r6", Nan2008)
5848       .Case("mips64", NanLegacy)
5849       .Case("mips64r2", NanLegacy)
5850       .Case("mips64r3", NanLegacy | Nan2008)
5851       .Case("mips64r5", NanLegacy | Nan2008)
5852       .Case("mips64r6", Nan2008)
5853       .Default(NanLegacy);
5854 }
5855
5856 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
5857   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5858   return A && (A->getValue() == StringRef(Value));
5859 }
5860
5861 bool mips::isUCLibc(const ArgList &Args) {
5862   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
5863   return A && A->getOption().matches(options::OPT_muclibc);
5864 }
5865
5866 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
5867   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
5868     return llvm::StringSwitch<bool>(NaNArg->getValue())
5869                .Case("2008", true)
5870                .Case("legacy", false)
5871                .Default(false);
5872
5873   // NaN2008 is the default for MIPS32r6/MIPS64r6.
5874   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
5875              .Cases("mips32r6", "mips64r6", true)
5876              .Default(false);
5877
5878   return false;
5879 }
5880
5881 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
5882                          StringRef ABIName, StringRef FloatABI) {
5883   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
5884       Triple.getVendor() != llvm::Triple::MipsTechnologies)
5885     return false;
5886
5887   if (ABIName != "32")
5888     return false;
5889
5890   // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
5891   // present.
5892   if (FloatABI == "soft")
5893     return false;
5894
5895   return llvm::StringSwitch<bool>(CPUName)
5896              .Cases("mips2", "mips3", "mips4", "mips5", true)
5897              .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
5898              .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
5899              .Default(false);
5900 }
5901
5902 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
5903                          StringRef CPUName, StringRef ABIName,
5904                          StringRef FloatABI) {
5905   bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
5906
5907   // FPXX shouldn't be used if -msingle-float is present.
5908   if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
5909                                options::OPT_mdouble_float))
5910     if (A->getOption().matches(options::OPT_msingle_float))
5911       UseFPXX = false;
5912
5913   return UseFPXX;
5914 }
5915
5916 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
5917   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
5918   // archs which Darwin doesn't use.
5919
5920   // The matching this routine does is fairly pointless, since it is neither the
5921   // complete architecture list, nor a reasonable subset. The problem is that
5922   // historically the driver driver accepts this and also ties its -march=
5923   // handling to the architecture name, so we need to be careful before removing
5924   // support for it.
5925
5926   // This code must be kept in sync with Clang's Darwin specific argument
5927   // translation.
5928
5929   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
5930     .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
5931     .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
5932     .Case("ppc64", llvm::Triple::ppc64)
5933     .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
5934     .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
5935            llvm::Triple::x86)
5936     .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
5937     // This is derived from the driver driver.
5938     .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
5939     .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
5940     .Cases("armv7s", "xscale", llvm::Triple::arm)
5941     .Case("arm64", llvm::Triple::aarch64)
5942     .Case("r600", llvm::Triple::r600)
5943     .Case("amdgcn", llvm::Triple::amdgcn)
5944     .Case("nvptx", llvm::Triple::nvptx)
5945     .Case("nvptx64", llvm::Triple::nvptx64)
5946     .Case("amdil", llvm::Triple::amdil)
5947     .Case("spir", llvm::Triple::spir)
5948     .Default(llvm::Triple::UnknownArch);
5949 }
5950
5951 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
5952   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
5953   T.setArch(Arch);
5954
5955   if (Str == "x86_64h")
5956     T.setArchName(Str);
5957   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
5958     T.setOS(llvm::Triple::UnknownOS);
5959     T.setObjectFormat(llvm::Triple::MachO);
5960   }
5961 }
5962
5963 const char *Clang::getBaseInputName(const ArgList &Args,
5964                                     const InputInfo &Input) {
5965   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5966 }
5967
5968 const char *Clang::getBaseInputStem(const ArgList &Args,
5969                                     const InputInfoList &Inputs) {
5970   const char *Str = getBaseInputName(Args, Inputs[0]);
5971
5972   if (const char *End = strrchr(Str, '.'))
5973     return Args.MakeArgString(std::string(Str, End));
5974
5975   return Str;
5976 }
5977
5978 const char *Clang::getDependencyFileName(const ArgList &Args,
5979                                          const InputInfoList &Inputs) {
5980   // FIXME: Think about this more.
5981   std::string Res;
5982
5983   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5984     std::string Str(OutputOpt->getValue());
5985     Res = Str.substr(0, Str.rfind('.'));
5986   } else {
5987     Res = getBaseInputStem(Args, Inputs);
5988   }
5989   return Args.MakeArgString(Res + ".d");
5990 }
5991
5992 void cloudabi::Link::ConstructJob(Compilation &C, const JobAction &JA,
5993                                   const InputInfo &Output,
5994                                   const InputInfoList &Inputs,
5995                                   const ArgList &Args,
5996                                   const char *LinkingOutput) const {
5997   const ToolChain &ToolChain = getToolChain();
5998   const Driver &D = ToolChain.getDriver();
5999   ArgStringList CmdArgs;
6000
6001   // Silence warning for "clang -g foo.o -o foo"
6002   Args.ClaimAllArgs(options::OPT_g_Group);
6003   // and "clang -emit-llvm foo.o -o foo"
6004   Args.ClaimAllArgs(options::OPT_emit_llvm);
6005   // and for "clang -w foo.o -o foo". Other warning options are already
6006   // handled somewhere else.
6007   Args.ClaimAllArgs(options::OPT_w);
6008
6009   if (!D.SysRoot.empty())
6010     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6011
6012   // CloudABI only supports static linkage.
6013   CmdArgs.push_back("-Bstatic");
6014   CmdArgs.push_back("--eh-frame-hdr");
6015   CmdArgs.push_back("--gc-sections");
6016
6017   if (Output.isFilename()) {
6018     CmdArgs.push_back("-o");
6019     CmdArgs.push_back(Output.getFilename());
6020   } else {
6021     assert(Output.isNothing() && "Invalid output.");
6022   }
6023
6024   if (!Args.hasArg(options::OPT_nostdlib) &&
6025       !Args.hasArg(options::OPT_nostartfiles)) {
6026     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6027     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6028   }
6029
6030   Args.AddAllArgs(CmdArgs, options::OPT_L);
6031   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
6032   for (const auto &Path : Paths)
6033     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6034   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6035   Args.AddAllArgs(CmdArgs, options::OPT_e);
6036   Args.AddAllArgs(CmdArgs, options::OPT_s);
6037   Args.AddAllArgs(CmdArgs, options::OPT_t);
6038   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6039   Args.AddAllArgs(CmdArgs, options::OPT_r);
6040
6041   if (D.IsUsingLTO(Args))
6042     AddGoldPlugin(ToolChain, Args, CmdArgs);
6043
6044   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6045
6046   if (!Args.hasArg(options::OPT_nostdlib) &&
6047       !Args.hasArg(options::OPT_nodefaultlibs)) {
6048     if (D.CCCIsCXX())
6049       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6050     CmdArgs.push_back("-lc");
6051     CmdArgs.push_back("-lcompiler_rt");
6052   }
6053
6054   if (!Args.hasArg(options::OPT_nostdlib) &&
6055       !Args.hasArg(options::OPT_nostartfiles))
6056     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6057
6058   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6059   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6060 }
6061
6062 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6063                                     const InputInfo &Output,
6064                                     const InputInfoList &Inputs,
6065                                     const ArgList &Args,
6066                                     const char *LinkingOutput) const {
6067   ArgStringList CmdArgs;
6068
6069   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6070   const InputInfo &Input = Inputs[0];
6071
6072   // Determine the original source input.
6073   const Action *SourceAction = &JA;
6074   while (SourceAction->getKind() != Action::InputClass) {
6075     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6076     SourceAction = SourceAction->getInputs()[0];
6077   }
6078
6079   // If -fno_integrated_as is used add -Q to the darwin assember driver to make
6080   // sure it runs its system assembler not clang's integrated assembler.
6081   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
6082   // FIXME: at run-time detect assembler capabilities or rely on version
6083   // information forwarded by -target-assembler-version (future)
6084   if (Args.hasArg(options::OPT_fno_integrated_as)) {
6085     const llvm::Triple &T(getToolChain().getTriple());
6086     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6087       CmdArgs.push_back("-Q");
6088   }
6089
6090   // Forward -g, assuming we are dealing with an actual assembly file.
6091   if (SourceAction->getType() == types::TY_Asm ||
6092       SourceAction->getType() == types::TY_PP_Asm) {
6093     if (Args.hasArg(options::OPT_gstabs))
6094       CmdArgs.push_back("--gstabs");
6095     else if (Args.hasArg(options::OPT_g_Group))
6096       CmdArgs.push_back("-g");
6097   }
6098
6099   // Derived from asm spec.
6100   AddMachOArch(Args, CmdArgs);
6101
6102   // Use -force_cpusubtype_ALL on x86 by default.
6103   if (getToolChain().getArch() == llvm::Triple::x86 ||
6104       getToolChain().getArch() == llvm::Triple::x86_64 ||
6105       Args.hasArg(options::OPT_force__cpusubtype__ALL))
6106     CmdArgs.push_back("-force_cpusubtype_ALL");
6107
6108   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6109       (((Args.hasArg(options::OPT_mkernel) ||
6110          Args.hasArg(options::OPT_fapple_kext)) &&
6111         getMachOToolChain().isKernelStatic()) ||
6112        Args.hasArg(options::OPT_static)))
6113     CmdArgs.push_back("-static");
6114
6115   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6116                        options::OPT_Xassembler);
6117
6118   assert(Output.isFilename() && "Unexpected lipo output.");
6119   CmdArgs.push_back("-o");
6120   CmdArgs.push_back(Output.getFilename());
6121
6122   assert(Input.isFilename() && "Invalid input.");
6123   CmdArgs.push_back(Input.getFilename());
6124
6125   // asm_final spec is empty.
6126
6127   const char *Exec =
6128     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6129   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6130 }
6131
6132 void darwin::MachOTool::anchor() {}
6133
6134 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6135                                      ArgStringList &CmdArgs) const {
6136   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6137
6138   // Derived from darwin_arch spec.
6139   CmdArgs.push_back("-arch");
6140   CmdArgs.push_back(Args.MakeArgString(ArchName));
6141
6142   // FIXME: Is this needed anymore?
6143   if (ArchName == "arm")
6144     CmdArgs.push_back("-force_cpusubtype_ALL");
6145 }
6146
6147 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
6148   // We only need to generate a temp path for LTO if we aren't compiling object
6149   // files. When compiling source files, we run 'dsymutil' after linking. We
6150   // don't run 'dsymutil' when compiling object files.
6151   for (const auto &Input : Inputs)
6152     if (Input.getType() != types::TY_Object)
6153       return true;
6154
6155   return false;
6156 }
6157
6158 void darwin::Link::AddLinkArgs(Compilation &C,
6159                                const ArgList &Args,
6160                                ArgStringList &CmdArgs,
6161                                const InputInfoList &Inputs) const {
6162   const Driver &D = getToolChain().getDriver();
6163   const toolchains::MachO &MachOTC = getMachOToolChain();
6164
6165   unsigned Version[3] = { 0, 0, 0 };
6166   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6167     bool HadExtra;
6168     if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
6169                                    Version[1], Version[2], HadExtra) ||
6170         HadExtra)
6171       D.Diag(diag::err_drv_invalid_version_number)
6172         << A->getAsString(Args);
6173   }
6174
6175   // Newer linkers support -demangle. Pass it if supported and not disabled by
6176   // the user.
6177   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6178     CmdArgs.push_back("-demangle");
6179
6180   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6181     CmdArgs.push_back("-export_dynamic");
6182
6183   // If we are using App Extension restrictions, pass a flag to the linker
6184   // telling it that the compiled code has been audited.
6185   if (Args.hasFlag(options::OPT_fapplication_extension,
6186                    options::OPT_fno_application_extension, false))
6187     CmdArgs.push_back("-application_extension");
6188
6189   // If we are using LTO, then automatically create a temporary file path for
6190   // the linker to use, so that it's lifetime will extend past a possible
6191   // dsymutil step.
6192   if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
6193     const char *TmpPath = C.getArgs().MakeArgString(
6194       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6195     C.addTempFile(TmpPath);
6196     CmdArgs.push_back("-object_path_lto");
6197     CmdArgs.push_back(TmpPath);
6198   }
6199
6200   // Derived from the "link" spec.
6201   Args.AddAllArgs(CmdArgs, options::OPT_static);
6202   if (!Args.hasArg(options::OPT_static))
6203     CmdArgs.push_back("-dynamic");
6204   if (Args.hasArg(options::OPT_fgnu_runtime)) {
6205     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6206     // here. How do we wish to handle such things?
6207   }
6208
6209   if (!Args.hasArg(options::OPT_dynamiclib)) {
6210     AddMachOArch(Args, CmdArgs);
6211     // FIXME: Why do this only on this path?
6212     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6213
6214     Args.AddLastArg(CmdArgs, options::OPT_bundle);
6215     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6216     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6217
6218     Arg *A;
6219     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6220         (A = Args.getLastArg(options::OPT_current__version)) ||
6221         (A = Args.getLastArg(options::OPT_install__name)))
6222       D.Diag(diag::err_drv_argument_only_allowed_with)
6223         << A->getAsString(Args) << "-dynamiclib";
6224
6225     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
6226     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
6227     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
6228   } else {
6229     CmdArgs.push_back("-dylib");
6230
6231     Arg *A;
6232     if ((A = Args.getLastArg(options::OPT_bundle)) ||
6233         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
6234         (A = Args.getLastArg(options::OPT_client__name)) ||
6235         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
6236         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
6237         (A = Args.getLastArg(options::OPT_private__bundle)))
6238       D.Diag(diag::err_drv_argument_not_allowed_with)
6239         << A->getAsString(Args) << "-dynamiclib";
6240
6241     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
6242                               "-dylib_compatibility_version");
6243     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
6244                               "-dylib_current_version");
6245
6246     AddMachOArch(Args, CmdArgs);
6247
6248     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
6249                               "-dylib_install_name");
6250   }
6251
6252   Args.AddLastArg(CmdArgs, options::OPT_all__load);
6253   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
6254   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
6255   if (MachOTC.isTargetIOSBased())
6256     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
6257   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
6258   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
6259   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
6260   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
6261   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
6262   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
6263   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
6264   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
6265   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
6266   Args.AddAllArgs(CmdArgs, options::OPT_init);
6267
6268   // Add the deployment target.
6269   MachOTC.addMinVersionArgs(Args, CmdArgs);
6270
6271   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
6272   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
6273   Args.AddLastArg(CmdArgs, options::OPT_single__module);
6274   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
6275   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
6276
6277   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
6278                                      options::OPT_fno_pie,
6279                                      options::OPT_fno_PIE)) {
6280     if (A->getOption().matches(options::OPT_fpie) ||
6281         A->getOption().matches(options::OPT_fPIE))
6282       CmdArgs.push_back("-pie");
6283     else
6284       CmdArgs.push_back("-no_pie");
6285   }
6286
6287   Args.AddLastArg(CmdArgs, options::OPT_prebind);
6288   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
6289   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
6290   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
6291   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
6292   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
6293   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
6294   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
6295   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
6296   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
6297   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
6298   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
6299   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
6300   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
6301   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
6302   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
6303
6304   // Give --sysroot= preference, over the Apple specific behavior to also use
6305   // --isysroot as the syslibroot.
6306   StringRef sysroot = C.getSysRoot();
6307   if (sysroot != "") {
6308     CmdArgs.push_back("-syslibroot");
6309     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
6310   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
6311     CmdArgs.push_back("-syslibroot");
6312     CmdArgs.push_back(A->getValue());
6313   }
6314
6315   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
6316   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
6317   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
6318   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
6319   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
6320   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
6321   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
6322   Args.AddAllArgs(CmdArgs, options::OPT_y);
6323   Args.AddLastArg(CmdArgs, options::OPT_w);
6324   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
6325   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
6326   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
6327   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
6328   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
6329   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
6330   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
6331   Args.AddLastArg(CmdArgs, options::OPT_whyload);
6332   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
6333   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
6334   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
6335   Args.AddLastArg(CmdArgs, options::OPT_Mach);
6336 }
6337
6338 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
6339                                 const InputInfo &Output,
6340                                 const InputInfoList &Inputs,
6341                                 const ArgList &Args,
6342                                 const char *LinkingOutput) const {
6343   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
6344
6345   // If the number of arguments surpasses the system limits, we will encode the
6346   // input files in a separate file, shortening the command line. To this end,
6347   // build a list of input file names that can be passed via a file with the
6348   // -filelist linker option.
6349   llvm::opt::ArgStringList InputFileList;
6350
6351   // The logic here is derived from gcc's behavior; most of which
6352   // comes from specs (starting with link_command). Consult gcc for
6353   // more information.
6354   ArgStringList CmdArgs;
6355
6356   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
6357   if (Args.hasArg(options::OPT_ccc_arcmt_check,
6358                   options::OPT_ccc_arcmt_migrate)) {
6359     for (const auto &Arg : Args)
6360       Arg->claim();
6361     const char *Exec =
6362       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
6363     CmdArgs.push_back(Output.getFilename());
6364     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6365     return;
6366   }
6367
6368   // I'm not sure why this particular decomposition exists in gcc, but
6369   // we follow suite for ease of comparison.
6370   AddLinkArgs(C, Args, CmdArgs, Inputs);
6371
6372   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
6373   Args.AddAllArgs(CmdArgs, options::OPT_s);
6374   Args.AddAllArgs(CmdArgs, options::OPT_t);
6375   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6376   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
6377   Args.AddLastArg(CmdArgs, options::OPT_e);
6378   Args.AddAllArgs(CmdArgs, options::OPT_r);
6379
6380   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
6381   // members of static archive libraries which implement Objective-C classes or
6382   // categories.
6383   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
6384     CmdArgs.push_back("-ObjC");
6385
6386   CmdArgs.push_back("-o");
6387   CmdArgs.push_back(Output.getFilename());
6388
6389   if (!Args.hasArg(options::OPT_nostdlib) &&
6390       !Args.hasArg(options::OPT_nostartfiles))
6391     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
6392
6393   // SafeStack requires its own runtime libraries
6394   // These libraries should be linked first, to make sure the
6395   // __safestack_init constructor executes before everything else
6396   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
6397     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
6398                                           "libclang_rt.safestack_osx.a",
6399                                           /*AlwaysLink=*/true);
6400   }
6401
6402   Args.AddAllArgs(CmdArgs, options::OPT_L);
6403
6404   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6405                    options::OPT_fno_openmp, false)) {
6406     switch (getOpenMPRuntime(getToolChain(), Args)) {
6407     case OMPRT_OMP:
6408       CmdArgs.push_back("-lomp");
6409       break;
6410     case OMPRT_GOMP:
6411       CmdArgs.push_back("-lgomp");
6412       break;
6413     case OMPRT_IOMP5:
6414       CmdArgs.push_back("-liomp5");
6415       break;
6416     case OMPRT_Unknown:
6417       // Already diagnosed.
6418       break;
6419     }
6420   }
6421
6422   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6423   // Build the input file for -filelist (list of linker input files) in case we
6424   // need it later
6425   for (const auto &II : Inputs) {
6426     if (!II.isFilename()) {
6427       // This is a linker input argument.
6428       // We cannot mix input arguments and file names in a -filelist input, thus
6429       // we prematurely stop our list (remaining files shall be passed as
6430       // arguments).
6431       if (InputFileList.size() > 0)
6432         break;
6433
6434       continue;
6435     }
6436
6437     InputFileList.push_back(II.getFilename());
6438   }
6439
6440   if (isObjCRuntimeLinked(Args) &&
6441       !Args.hasArg(options::OPT_nostdlib) &&
6442       !Args.hasArg(options::OPT_nodefaultlibs)) {
6443     // We use arclite library for both ARC and subscripting support.
6444     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
6445
6446     CmdArgs.push_back("-framework");
6447     CmdArgs.push_back("Foundation");
6448     // Link libobj.
6449     CmdArgs.push_back("-lobjc");
6450   }
6451
6452   if (LinkingOutput) {
6453     CmdArgs.push_back("-arch_multiple");
6454     CmdArgs.push_back("-final_output");
6455     CmdArgs.push_back(LinkingOutput);
6456   }
6457
6458   if (Args.hasArg(options::OPT_fnested_functions))
6459     CmdArgs.push_back("-allow_stack_execute");
6460
6461   // TODO: It would be nice to use addProfileRT() here, but darwin's compiler-rt
6462   // paths are different enough from other toolchains that this needs a fair
6463   // amount of refactoring done first.
6464   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
6465
6466   if (!Args.hasArg(options::OPT_nostdlib) &&
6467       !Args.hasArg(options::OPT_nodefaultlibs)) {
6468     if (getToolChain().getDriver().CCCIsCXX())
6469       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6470
6471     // link_ssp spec is empty.
6472
6473     // Let the tool chain choose which runtime library to link.
6474     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
6475   }
6476
6477   if (!Args.hasArg(options::OPT_nostdlib) &&
6478       !Args.hasArg(options::OPT_nostartfiles)) {
6479     // endfile_spec is empty.
6480   }
6481
6482   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6483   Args.AddAllArgs(CmdArgs, options::OPT_F);
6484
6485   // -iframework should be forwarded as -F.
6486   for (const Arg *A : Args.filtered(options::OPT_iframework))
6487     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
6488
6489   if (!Args.hasArg(options::OPT_nostdlib) &&
6490       !Args.hasArg(options::OPT_nodefaultlibs)) {
6491     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6492       if (A->getValue() == StringRef("Accelerate")) {
6493         CmdArgs.push_back("-framework");
6494         CmdArgs.push_back("Accelerate");
6495       }
6496     }
6497   }
6498
6499   const char *Exec =
6500     Args.MakeArgString(getToolChain().GetLinkerPath());
6501   std::unique_ptr<Command> Cmd =
6502     llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
6503   Cmd->setInputFileList(std::move(InputFileList));
6504   C.addCommand(std::move(Cmd));
6505 }
6506
6507 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
6508                                 const InputInfo &Output,
6509                                 const InputInfoList &Inputs,
6510                                 const ArgList &Args,
6511                                 const char *LinkingOutput) const {
6512   ArgStringList CmdArgs;
6513
6514   CmdArgs.push_back("-create");
6515   assert(Output.isFilename() && "Unexpected lipo output.");
6516
6517   CmdArgs.push_back("-output");
6518   CmdArgs.push_back(Output.getFilename());
6519
6520   for (const auto &II : Inputs) {
6521     assert(II.isFilename() && "Unexpected lipo input.");
6522     CmdArgs.push_back(II.getFilename());
6523   }
6524
6525   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
6526   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6527 }
6528
6529 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
6530                                     const InputInfo &Output,
6531                                     const InputInfoList &Inputs,
6532                                     const ArgList &Args,
6533                                     const char *LinkingOutput) const {
6534   ArgStringList CmdArgs;
6535
6536   CmdArgs.push_back("-o");
6537   CmdArgs.push_back(Output.getFilename());
6538
6539   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6540   const InputInfo &Input = Inputs[0];
6541   assert(Input.isFilename() && "Unexpected dsymutil input.");
6542   CmdArgs.push_back(Input.getFilename());
6543
6544   const char *Exec =
6545     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
6546   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6547 }
6548
6549 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
6550                                        const InputInfo &Output,
6551                                        const InputInfoList &Inputs,
6552                                        const ArgList &Args,
6553                                        const char *LinkingOutput) const {
6554   ArgStringList CmdArgs;
6555   CmdArgs.push_back("--verify");
6556   CmdArgs.push_back("--debug-info");
6557   CmdArgs.push_back("--eh-frame");
6558   CmdArgs.push_back("--quiet");
6559
6560   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6561   const InputInfo &Input = Inputs[0];
6562   assert(Input.isFilename() && "Unexpected verify input");
6563
6564   // Grabbing the output of the earlier dsymutil run.
6565   CmdArgs.push_back(Input.getFilename());
6566
6567   const char *Exec =
6568     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
6569   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6570 }
6571
6572 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6573                                       const InputInfo &Output,
6574                                       const InputInfoList &Inputs,
6575                                       const ArgList &Args,
6576                                       const char *LinkingOutput) const {
6577   claimNoWarnArgs(Args);
6578   ArgStringList CmdArgs;
6579
6580   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6581                        options::OPT_Xassembler);
6582
6583   CmdArgs.push_back("-o");
6584   CmdArgs.push_back(Output.getFilename());
6585
6586   for (const auto &II : Inputs)
6587     CmdArgs.push_back(II.getFilename());
6588
6589   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6590   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6591 }
6592
6593 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
6594                                   const InputInfo &Output,
6595                                   const InputInfoList &Inputs,
6596                                   const ArgList &Args,
6597                                   const char *LinkingOutput) const {
6598   // FIXME: Find a real GCC, don't hard-code versions here
6599   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
6600   const llvm::Triple &T = getToolChain().getTriple();
6601   std::string LibPath = "/usr/lib/";
6602   const llvm::Triple::ArchType Arch = T.getArch();
6603   switch (Arch) {
6604   case llvm::Triple::x86:
6605     GCCLibPath +=
6606         ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
6607     break;
6608   case llvm::Triple::x86_64:
6609     GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
6610     GCCLibPath += "/4.5.2/amd64/";
6611     LibPath += "amd64/";
6612     break;
6613   default:
6614     llvm_unreachable("Unsupported architecture");
6615   }
6616
6617   ArgStringList CmdArgs;
6618
6619   // Demangle C++ names in errors
6620   CmdArgs.push_back("-C");
6621
6622   if ((!Args.hasArg(options::OPT_nostdlib)) &&
6623       (!Args.hasArg(options::OPT_shared))) {
6624     CmdArgs.push_back("-e");
6625     CmdArgs.push_back("_start");
6626   }
6627
6628   if (Args.hasArg(options::OPT_static)) {
6629     CmdArgs.push_back("-Bstatic");
6630     CmdArgs.push_back("-dn");
6631   } else {
6632     CmdArgs.push_back("-Bdynamic");
6633     if (Args.hasArg(options::OPT_shared)) {
6634       CmdArgs.push_back("-shared");
6635     } else {
6636       CmdArgs.push_back("--dynamic-linker");
6637       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
6638     }
6639   }
6640
6641   if (Output.isFilename()) {
6642     CmdArgs.push_back("-o");
6643     CmdArgs.push_back(Output.getFilename());
6644   } else {
6645     assert(Output.isNothing() && "Invalid output.");
6646   }
6647
6648   if (!Args.hasArg(options::OPT_nostdlib) &&
6649       !Args.hasArg(options::OPT_nostartfiles)) {
6650     if (!Args.hasArg(options::OPT_shared)) {
6651       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
6652       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6653       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6654       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6655     } else {
6656       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6657       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6658       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6659     }
6660     if (getToolChain().getDriver().CCCIsCXX())
6661       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
6662   }
6663
6664   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
6665
6666   Args.AddAllArgs(CmdArgs, options::OPT_L);
6667   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6668   Args.AddAllArgs(CmdArgs, options::OPT_e);
6669   Args.AddAllArgs(CmdArgs, options::OPT_r);
6670
6671   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6672
6673   if (!Args.hasArg(options::OPT_nostdlib) &&
6674       !Args.hasArg(options::OPT_nodefaultlibs)) {
6675     if (getToolChain().getDriver().CCCIsCXX())
6676       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6677     CmdArgs.push_back("-lgcc_s");
6678     if (!Args.hasArg(options::OPT_shared)) {
6679       CmdArgs.push_back("-lgcc");
6680       CmdArgs.push_back("-lc");
6681       CmdArgs.push_back("-lm");
6682     }
6683   }
6684
6685   if (!Args.hasArg(options::OPT_nostdlib) &&
6686       !Args.hasArg(options::OPT_nostartfiles)) {
6687     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
6688   }
6689   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
6690
6691   addProfileRT(getToolChain(), Args, CmdArgs);
6692
6693   const char *Exec =
6694     Args.MakeArgString(getToolChain().GetLinkerPath());
6695   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6696 }
6697
6698 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6699                                      const InputInfo &Output,
6700                                      const InputInfoList &Inputs,
6701                                      const ArgList &Args,
6702                                      const char *LinkingOutput) const {
6703   claimNoWarnArgs(Args);
6704   ArgStringList CmdArgs;
6705   bool NeedsKPIC = false;
6706
6707   switch (getToolChain().getArch()) {
6708   case llvm::Triple::x86:
6709     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6710     // instruct as in the base system to assemble 32-bit code.
6711     CmdArgs.push_back("--32");
6712     break;
6713
6714   case llvm::Triple::ppc:
6715     CmdArgs.push_back("-mppc");
6716     CmdArgs.push_back("-many");
6717     break;
6718
6719   case llvm::Triple::sparc:
6720   case llvm::Triple::sparcel:
6721     CmdArgs.push_back("-32");
6722     NeedsKPIC = true;
6723     break;
6724
6725   case llvm::Triple::sparcv9:
6726     CmdArgs.push_back("-64");
6727     CmdArgs.push_back("-Av9a");
6728     NeedsKPIC = true;
6729     break;
6730
6731   case llvm::Triple::mips64:
6732   case llvm::Triple::mips64el: {
6733     StringRef CPUName;
6734     StringRef ABIName;
6735     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6736
6737     CmdArgs.push_back("-mabi");
6738     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6739
6740     if (getToolChain().getArch() == llvm::Triple::mips64)
6741       CmdArgs.push_back("-EB");
6742     else
6743       CmdArgs.push_back("-EL");
6744
6745     NeedsKPIC = true;
6746     break;
6747   }
6748
6749   default:
6750     break;
6751   }
6752
6753   if (NeedsKPIC)
6754     addAssemblerKPIC(Args, CmdArgs);
6755
6756   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6757                        options::OPT_Xassembler);
6758
6759   CmdArgs.push_back("-o");
6760   CmdArgs.push_back(Output.getFilename());
6761
6762   for (const auto &II : Inputs)
6763     CmdArgs.push_back(II.getFilename());
6764
6765   const char *Exec =
6766     Args.MakeArgString(getToolChain().GetProgramPath("as"));
6767   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6768 }
6769
6770 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6771                                  const InputInfo &Output,
6772                                  const InputInfoList &Inputs,
6773                                  const ArgList &Args,
6774                                  const char *LinkingOutput) const {
6775   const Driver &D = getToolChain().getDriver();
6776   ArgStringList CmdArgs;
6777
6778   // Silence warning for "clang -g foo.o -o foo"
6779   Args.ClaimAllArgs(options::OPT_g_Group);
6780   // and "clang -emit-llvm foo.o -o foo"
6781   Args.ClaimAllArgs(options::OPT_emit_llvm);
6782   // and for "clang -w foo.o -o foo". Other warning options are already
6783   // handled somewhere else.
6784   Args.ClaimAllArgs(options::OPT_w);
6785
6786   if (getToolChain().getArch() == llvm::Triple::mips64)
6787     CmdArgs.push_back("-EB");
6788   else if (getToolChain().getArch() == llvm::Triple::mips64el)
6789     CmdArgs.push_back("-EL");
6790
6791   if ((!Args.hasArg(options::OPT_nostdlib)) &&
6792       (!Args.hasArg(options::OPT_shared))) {
6793     CmdArgs.push_back("-e");
6794     CmdArgs.push_back("__start");
6795   }
6796
6797   if (Args.hasArg(options::OPT_static)) {
6798     CmdArgs.push_back("-Bstatic");
6799   } else {
6800     if (Args.hasArg(options::OPT_rdynamic))
6801       CmdArgs.push_back("-export-dynamic");
6802     CmdArgs.push_back("--eh-frame-hdr");
6803     CmdArgs.push_back("-Bdynamic");
6804     if (Args.hasArg(options::OPT_shared)) {
6805       CmdArgs.push_back("-shared");
6806     } else {
6807       CmdArgs.push_back("-dynamic-linker");
6808       CmdArgs.push_back("/usr/libexec/ld.so");
6809     }
6810   }
6811
6812   if (Args.hasArg(options::OPT_nopie))
6813     CmdArgs.push_back("-nopie");
6814
6815   if (Output.isFilename()) {
6816     CmdArgs.push_back("-o");
6817     CmdArgs.push_back(Output.getFilename());
6818   } else {
6819     assert(Output.isNothing() && "Invalid output.");
6820   }
6821
6822   if (!Args.hasArg(options::OPT_nostdlib) &&
6823       !Args.hasArg(options::OPT_nostartfiles)) {
6824     if (!Args.hasArg(options::OPT_shared)) {
6825       if (Args.hasArg(options::OPT_pg))  
6826         CmdArgs.push_back(Args.MakeArgString(
6827                                 getToolChain().GetFilePath("gcrt0.o")));
6828       else
6829         CmdArgs.push_back(Args.MakeArgString(
6830                                 getToolChain().GetFilePath("crt0.o")));
6831       CmdArgs.push_back(Args.MakeArgString(
6832                               getToolChain().GetFilePath("crtbegin.o")));
6833     } else {
6834       CmdArgs.push_back(Args.MakeArgString(
6835                               getToolChain().GetFilePath("crtbeginS.o")));
6836     }
6837   }
6838
6839   std::string Triple = getToolChain().getTripleString();
6840   if (Triple.substr(0, 6) == "x86_64")
6841     Triple.replace(0, 6, "amd64");
6842   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
6843                                        "/4.2.1"));
6844
6845   Args.AddAllArgs(CmdArgs, options::OPT_L);
6846   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6847   Args.AddAllArgs(CmdArgs, options::OPT_e);
6848   Args.AddAllArgs(CmdArgs, options::OPT_s);
6849   Args.AddAllArgs(CmdArgs, options::OPT_t);
6850   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6851   Args.AddAllArgs(CmdArgs, options::OPT_r);
6852
6853   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6854
6855   if (!Args.hasArg(options::OPT_nostdlib) &&
6856       !Args.hasArg(options::OPT_nodefaultlibs)) {
6857     if (D.CCCIsCXX()) {
6858       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6859       if (Args.hasArg(options::OPT_pg)) 
6860         CmdArgs.push_back("-lm_p");
6861       else
6862         CmdArgs.push_back("-lm");
6863     }
6864
6865     // FIXME: For some reason GCC passes -lgcc before adding
6866     // the default system libraries. Just mimic this for now.
6867     CmdArgs.push_back("-lgcc");
6868
6869     if (Args.hasArg(options::OPT_pthread)) {
6870       if (!Args.hasArg(options::OPT_shared) &&
6871           Args.hasArg(options::OPT_pg))
6872          CmdArgs.push_back("-lpthread_p");
6873       else
6874          CmdArgs.push_back("-lpthread");
6875     }
6876
6877     if (!Args.hasArg(options::OPT_shared)) {
6878       if (Args.hasArg(options::OPT_pg))
6879          CmdArgs.push_back("-lc_p");
6880       else
6881          CmdArgs.push_back("-lc");
6882     }
6883
6884     CmdArgs.push_back("-lgcc");
6885   }
6886
6887   if (!Args.hasArg(options::OPT_nostdlib) &&
6888       !Args.hasArg(options::OPT_nostartfiles)) {
6889     if (!Args.hasArg(options::OPT_shared))
6890       CmdArgs.push_back(Args.MakeArgString(
6891                               getToolChain().GetFilePath("crtend.o")));
6892     else
6893       CmdArgs.push_back(Args.MakeArgString(
6894                               getToolChain().GetFilePath("crtendS.o")));
6895   }
6896
6897   const char *Exec =
6898     Args.MakeArgString(getToolChain().GetLinkerPath());
6899   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6900 }
6901
6902 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6903                                     const InputInfo &Output,
6904                                     const InputInfoList &Inputs,
6905                                     const ArgList &Args,
6906                                     const char *LinkingOutput) const {
6907   claimNoWarnArgs(Args);
6908   ArgStringList CmdArgs;
6909
6910   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6911                        options::OPT_Xassembler);
6912
6913   CmdArgs.push_back("-o");
6914   CmdArgs.push_back(Output.getFilename());
6915
6916   for (const auto &II : Inputs)
6917     CmdArgs.push_back(II.getFilename());
6918
6919   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6920   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6921 }
6922
6923 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
6924                                 const InputInfo &Output,
6925                                 const InputInfoList &Inputs,
6926                                 const ArgList &Args,
6927                                 const char *LinkingOutput) const {
6928   const Driver &D = getToolChain().getDriver();
6929   ArgStringList CmdArgs;
6930
6931   if ((!Args.hasArg(options::OPT_nostdlib)) &&
6932       (!Args.hasArg(options::OPT_shared))) {
6933     CmdArgs.push_back("-e");
6934     CmdArgs.push_back("__start");
6935   }
6936
6937   if (Args.hasArg(options::OPT_static)) {
6938     CmdArgs.push_back("-Bstatic");
6939   } else {
6940     if (Args.hasArg(options::OPT_rdynamic))
6941       CmdArgs.push_back("-export-dynamic");
6942     CmdArgs.push_back("--eh-frame-hdr");
6943     CmdArgs.push_back("-Bdynamic");
6944     if (Args.hasArg(options::OPT_shared)) {
6945       CmdArgs.push_back("-shared");
6946     } else {
6947       CmdArgs.push_back("-dynamic-linker");
6948       CmdArgs.push_back("/usr/libexec/ld.so");
6949     }
6950   }
6951
6952   if (Output.isFilename()) {
6953     CmdArgs.push_back("-o");
6954     CmdArgs.push_back(Output.getFilename());
6955   } else {
6956     assert(Output.isNothing() && "Invalid output.");
6957   }
6958
6959   if (!Args.hasArg(options::OPT_nostdlib) &&
6960       !Args.hasArg(options::OPT_nostartfiles)) {
6961     if (!Args.hasArg(options::OPT_shared)) {
6962       if (Args.hasArg(options::OPT_pg))
6963         CmdArgs.push_back(Args.MakeArgString(
6964                                 getToolChain().GetFilePath("gcrt0.o")));
6965       else
6966         CmdArgs.push_back(Args.MakeArgString(
6967                                 getToolChain().GetFilePath("crt0.o")));
6968       CmdArgs.push_back(Args.MakeArgString(
6969                               getToolChain().GetFilePath("crtbegin.o")));
6970     } else {
6971       CmdArgs.push_back(Args.MakeArgString(
6972                               getToolChain().GetFilePath("crtbeginS.o")));
6973     }
6974   }
6975
6976   Args.AddAllArgs(CmdArgs, options::OPT_L);
6977   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6978   Args.AddAllArgs(CmdArgs, options::OPT_e);
6979
6980   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6981
6982   if (!Args.hasArg(options::OPT_nostdlib) &&
6983       !Args.hasArg(options::OPT_nodefaultlibs)) {
6984     if (D.CCCIsCXX()) {
6985       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6986       if (Args.hasArg(options::OPT_pg))
6987         CmdArgs.push_back("-lm_p");
6988       else
6989         CmdArgs.push_back("-lm");
6990     }
6991
6992     if (Args.hasArg(options::OPT_pthread)) {
6993       if (!Args.hasArg(options::OPT_shared) &&
6994           Args.hasArg(options::OPT_pg))
6995         CmdArgs.push_back("-lpthread_p");
6996       else
6997         CmdArgs.push_back("-lpthread");
6998     }
6999
7000     if (!Args.hasArg(options::OPT_shared)) {
7001       if (Args.hasArg(options::OPT_pg))
7002         CmdArgs.push_back("-lc_p");
7003       else
7004         CmdArgs.push_back("-lc");
7005     }
7006
7007     StringRef MyArch;
7008     switch (getToolChain().getArch()) {
7009     case llvm::Triple::arm:
7010       MyArch = "arm";
7011       break;
7012     case llvm::Triple::x86:
7013       MyArch = "i386";
7014       break;
7015     case llvm::Triple::x86_64:
7016       MyArch = "amd64";
7017       break;
7018     default:
7019       llvm_unreachable("Unsupported architecture");
7020     }
7021     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7022   }
7023
7024   if (!Args.hasArg(options::OPT_nostdlib) &&
7025       !Args.hasArg(options::OPT_nostartfiles)) {
7026     if (!Args.hasArg(options::OPT_shared))
7027       CmdArgs.push_back(Args.MakeArgString(
7028                               getToolChain().GetFilePath("crtend.o")));
7029     else
7030       CmdArgs.push_back(Args.MakeArgString(
7031                               getToolChain().GetFilePath("crtendS.o")));
7032   }
7033
7034   const char *Exec =
7035     Args.MakeArgString(getToolChain().GetLinkerPath());
7036   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7037 }
7038
7039 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7040                                      const InputInfo &Output,
7041                                      const InputInfoList &Inputs,
7042                                      const ArgList &Args,
7043                                      const char *LinkingOutput) const {
7044   claimNoWarnArgs(Args);
7045   ArgStringList CmdArgs;
7046
7047   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7048   // instruct as in the base system to assemble 32-bit code.
7049   if (getToolChain().getArch() == llvm::Triple::x86)
7050     CmdArgs.push_back("--32");
7051   else if (getToolChain().getArch() == llvm::Triple::ppc)
7052     CmdArgs.push_back("-a32");
7053   else if (getToolChain().getArch() == llvm::Triple::mips ||
7054            getToolChain().getArch() == llvm::Triple::mipsel ||
7055            getToolChain().getArch() == llvm::Triple::mips64 ||
7056            getToolChain().getArch() == llvm::Triple::mips64el) {
7057     StringRef CPUName;
7058     StringRef ABIName;
7059     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7060
7061     CmdArgs.push_back("-march");
7062     CmdArgs.push_back(CPUName.data());
7063
7064     CmdArgs.push_back("-mabi");
7065     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7066
7067     if (getToolChain().getArch() == llvm::Triple::mips ||
7068         getToolChain().getArch() == llvm::Triple::mips64)
7069       CmdArgs.push_back("-EB");
7070     else
7071       CmdArgs.push_back("-EL");
7072
7073     addAssemblerKPIC(Args, CmdArgs);
7074   } else if (getToolChain().getArch() == llvm::Triple::arm ||
7075              getToolChain().getArch() == llvm::Triple::armeb ||
7076              getToolChain().getArch() == llvm::Triple::thumb ||
7077              getToolChain().getArch() == llvm::Triple::thumbeb) {
7078     const Driver &D = getToolChain().getDriver();
7079     const llvm::Triple &Triple = getToolChain().getTriple();
7080     StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
7081
7082     if (FloatABI == "hard") {
7083       CmdArgs.push_back("-mfpu=vfp");
7084     } else {
7085       CmdArgs.push_back("-mfpu=softvfp");
7086     }
7087
7088     switch(getToolChain().getTriple().getEnvironment()) {
7089     case llvm::Triple::GNUEABIHF:
7090     case llvm::Triple::GNUEABI:
7091     case llvm::Triple::EABI:
7092       CmdArgs.push_back("-meabi=5");
7093       break;
7094
7095     default:
7096       CmdArgs.push_back("-matpcs");
7097     }
7098   } else if (getToolChain().getArch() == llvm::Triple::sparc ||
7099              getToolChain().getArch() == llvm::Triple::sparcel ||
7100              getToolChain().getArch() == llvm::Triple::sparcv9) {
7101     if (getToolChain().getArch() == llvm::Triple::sparc)
7102       CmdArgs.push_back("-Av8plusa");
7103     else
7104       CmdArgs.push_back("-Av9a");
7105
7106     addAssemblerKPIC(Args, CmdArgs);
7107   }
7108
7109   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7110                        options::OPT_Xassembler);
7111
7112   CmdArgs.push_back("-o");
7113   CmdArgs.push_back(Output.getFilename());
7114
7115   for (const auto &II : Inputs)
7116     CmdArgs.push_back(II.getFilename());
7117
7118   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7119   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7120 }
7121
7122 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
7123                                  const InputInfo &Output,
7124                                  const InputInfoList &Inputs,
7125                                  const ArgList &Args,
7126                                  const char *LinkingOutput) const {
7127   const toolchains::FreeBSD &ToolChain =
7128       static_cast<const toolchains::FreeBSD &>(getToolChain());
7129   const Driver &D = ToolChain.getDriver();
7130   const llvm::Triple::ArchType Arch = ToolChain.getArch();
7131   const bool IsPIE =
7132       !Args.hasArg(options::OPT_shared) &&
7133       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7134   ArgStringList CmdArgs;
7135
7136   // Silence warning for "clang -g foo.o -o foo"
7137   Args.ClaimAllArgs(options::OPT_g_Group);
7138   // and "clang -emit-llvm foo.o -o foo"
7139   Args.ClaimAllArgs(options::OPT_emit_llvm);
7140   // and for "clang -w foo.o -o foo". Other warning options are already
7141   // handled somewhere else.
7142   Args.ClaimAllArgs(options::OPT_w);
7143
7144   if (!D.SysRoot.empty())
7145     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7146
7147   if (IsPIE)
7148     CmdArgs.push_back("-pie");
7149
7150   if (Args.hasArg(options::OPT_static)) {
7151     CmdArgs.push_back("-Bstatic");
7152   } else {
7153     if (Args.hasArg(options::OPT_rdynamic))
7154       CmdArgs.push_back("-export-dynamic");
7155     CmdArgs.push_back("--eh-frame-hdr");
7156     if (Args.hasArg(options::OPT_shared)) {
7157       CmdArgs.push_back("-Bshareable");
7158     } else {
7159       CmdArgs.push_back("-dynamic-linker");
7160       CmdArgs.push_back("/libexec/ld-elf.so.1");
7161     }
7162     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7163       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7164           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7165         CmdArgs.push_back("--hash-style=both");
7166       }
7167     }
7168     CmdArgs.push_back("--enable-new-dtags");
7169   }
7170
7171   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7172   // instruct ld in the base system to link 32-bit code.
7173   if (Arch == llvm::Triple::x86) {
7174     CmdArgs.push_back("-m");
7175     CmdArgs.push_back("elf_i386_fbsd");
7176   }
7177
7178   if (Arch == llvm::Triple::ppc) {
7179     CmdArgs.push_back("-m");
7180     CmdArgs.push_back("elf32ppc_fbsd");
7181   }
7182
7183   if (Arg *A = Args.getLastArg(options::OPT_G)) {
7184     if (ToolChain.getArch() == llvm::Triple::mips ||
7185       ToolChain.getArch() == llvm::Triple::mipsel ||
7186       ToolChain.getArch() == llvm::Triple::mips64 ||
7187       ToolChain.getArch() == llvm::Triple::mips64el) {
7188       StringRef v = A->getValue();
7189       CmdArgs.push_back(Args.MakeArgString("-G" + v));
7190       A->claim();
7191     }
7192   }
7193
7194   if (Output.isFilename()) {
7195     CmdArgs.push_back("-o");
7196     CmdArgs.push_back(Output.getFilename());
7197   } else {
7198     assert(Output.isNothing() && "Invalid output.");
7199   }
7200
7201   if (!Args.hasArg(options::OPT_nostdlib) &&
7202       !Args.hasArg(options::OPT_nostartfiles)) {
7203     const char *crt1 = nullptr;
7204     if (!Args.hasArg(options::OPT_shared)) {
7205       if (Args.hasArg(options::OPT_pg))
7206         crt1 = "gcrt1.o";
7207       else if (IsPIE)
7208         crt1 = "Scrt1.o";
7209       else
7210         crt1 = "crt1.o";
7211     }
7212     if (crt1)
7213       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7214
7215     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7216
7217     const char *crtbegin = nullptr;
7218     if (Args.hasArg(options::OPT_static))
7219       crtbegin = "crtbeginT.o";
7220     else if (Args.hasArg(options::OPT_shared) || IsPIE)
7221       crtbegin = "crtbeginS.o";
7222     else
7223       crtbegin = "crtbegin.o";
7224
7225     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7226   }
7227
7228   Args.AddAllArgs(CmdArgs, options::OPT_L);
7229   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
7230   for (const auto &Path : Paths)
7231     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7232   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7233   Args.AddAllArgs(CmdArgs, options::OPT_e);
7234   Args.AddAllArgs(CmdArgs, options::OPT_s);
7235   Args.AddAllArgs(CmdArgs, options::OPT_t);
7236   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7237   Args.AddAllArgs(CmdArgs, options::OPT_r);
7238
7239   if (D.IsUsingLTO(Args))
7240     AddGoldPlugin(ToolChain, Args, CmdArgs);
7241
7242   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7243   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7244
7245   if (!Args.hasArg(options::OPT_nostdlib) &&
7246       !Args.hasArg(options::OPT_nodefaultlibs)) {
7247     if (D.CCCIsCXX()) {
7248       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7249       if (Args.hasArg(options::OPT_pg))
7250         CmdArgs.push_back("-lm_p");
7251       else
7252         CmdArgs.push_back("-lm");
7253     }
7254     if (NeedsSanitizerDeps)
7255       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7256     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7257     // the default system libraries. Just mimic this for now.
7258     if (Args.hasArg(options::OPT_pg))
7259       CmdArgs.push_back("-lgcc_p");
7260     else
7261       CmdArgs.push_back("-lgcc");
7262     if (Args.hasArg(options::OPT_static)) {
7263       CmdArgs.push_back("-lgcc_eh");
7264     } else if (Args.hasArg(options::OPT_pg)) {
7265       CmdArgs.push_back("-lgcc_eh_p");
7266     } else {
7267       CmdArgs.push_back("--as-needed");
7268       CmdArgs.push_back("-lgcc_s");
7269       CmdArgs.push_back("--no-as-needed");
7270     }
7271
7272     if (Args.hasArg(options::OPT_pthread)) {
7273       if (Args.hasArg(options::OPT_pg))
7274         CmdArgs.push_back("-lpthread_p");
7275       else
7276         CmdArgs.push_back("-lpthread");
7277     }
7278
7279     if (Args.hasArg(options::OPT_pg)) {
7280       if (Args.hasArg(options::OPT_shared))
7281         CmdArgs.push_back("-lc");
7282       else
7283         CmdArgs.push_back("-lc_p");
7284       CmdArgs.push_back("-lgcc_p");
7285     } else {
7286       CmdArgs.push_back("-lc");
7287       CmdArgs.push_back("-lgcc");
7288     }
7289
7290     if (Args.hasArg(options::OPT_static)) {
7291       CmdArgs.push_back("-lgcc_eh");
7292     } else if (Args.hasArg(options::OPT_pg)) {
7293       CmdArgs.push_back("-lgcc_eh_p");
7294     } else {
7295       CmdArgs.push_back("--as-needed");
7296       CmdArgs.push_back("-lgcc_s");
7297       CmdArgs.push_back("--no-as-needed");
7298     }
7299   }
7300
7301   if (!Args.hasArg(options::OPT_nostdlib) &&
7302       !Args.hasArg(options::OPT_nostartfiles)) {
7303     if (Args.hasArg(options::OPT_shared) || IsPIE)
7304       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
7305     else
7306       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7307     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7308   }
7309
7310   addProfileRT(ToolChain, Args, CmdArgs);
7311
7312   const char *Exec =
7313     Args.MakeArgString(getToolChain().GetLinkerPath());
7314   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7315 }
7316
7317 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7318                                      const InputInfo &Output,
7319                                      const InputInfoList &Inputs,
7320                                      const ArgList &Args,
7321                                      const char *LinkingOutput) const {
7322   claimNoWarnArgs(Args);
7323   ArgStringList CmdArgs;
7324
7325   // GNU as needs different flags for creating the correct output format
7326   // on architectures with different ABIs or optional feature sets.
7327   switch (getToolChain().getArch()) {
7328   case llvm::Triple::x86:
7329     CmdArgs.push_back("--32");
7330     break;
7331   case llvm::Triple::arm:
7332   case llvm::Triple::armeb:
7333   case llvm::Triple::thumb:
7334   case llvm::Triple::thumbeb: {
7335     std::string MArch = arm::getARMTargetCPU(Args, getToolChain().getTriple());
7336     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
7337     break;
7338   }
7339
7340   case llvm::Triple::mips:
7341   case llvm::Triple::mipsel:
7342   case llvm::Triple::mips64:
7343   case llvm::Triple::mips64el: {
7344     StringRef CPUName;
7345     StringRef ABIName;
7346     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7347
7348     CmdArgs.push_back("-march");
7349     CmdArgs.push_back(CPUName.data());
7350
7351     CmdArgs.push_back("-mabi");
7352     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7353
7354     if (getToolChain().getArch() == llvm::Triple::mips ||
7355         getToolChain().getArch() == llvm::Triple::mips64)
7356       CmdArgs.push_back("-EB");
7357     else
7358       CmdArgs.push_back("-EL");
7359
7360     addAssemblerKPIC(Args, CmdArgs);
7361     break;
7362   }
7363
7364   case llvm::Triple::sparc:
7365   case llvm::Triple::sparcel:
7366     CmdArgs.push_back("-32");
7367     addAssemblerKPIC(Args, CmdArgs);
7368     break;
7369
7370   case llvm::Triple::sparcv9:
7371     CmdArgs.push_back("-64");
7372     CmdArgs.push_back("-Av9");
7373     addAssemblerKPIC(Args, CmdArgs);
7374     break;
7375
7376   default:
7377     break;  
7378   }
7379
7380   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7381                        options::OPT_Xassembler);
7382
7383   CmdArgs.push_back("-o");
7384   CmdArgs.push_back(Output.getFilename());
7385
7386   for (const auto &II : Inputs)
7387     CmdArgs.push_back(II.getFilename());
7388
7389   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
7390   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7391 }
7392
7393 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
7394                                  const InputInfo &Output,
7395                                  const InputInfoList &Inputs,
7396                                  const ArgList &Args,
7397                                  const char *LinkingOutput) const {
7398   const Driver &D = getToolChain().getDriver();
7399   ArgStringList CmdArgs;
7400
7401   if (!D.SysRoot.empty())
7402     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7403
7404   CmdArgs.push_back("--eh-frame-hdr");
7405   if (Args.hasArg(options::OPT_static)) {
7406     CmdArgs.push_back("-Bstatic");
7407   } else {
7408     if (Args.hasArg(options::OPT_rdynamic))
7409       CmdArgs.push_back("-export-dynamic");
7410     if (Args.hasArg(options::OPT_shared)) {
7411       CmdArgs.push_back("-Bshareable");
7412     } else {
7413       CmdArgs.push_back("-dynamic-linker");
7414       CmdArgs.push_back("/libexec/ld.elf_so");
7415     }
7416   }
7417
7418   // Many NetBSD architectures support more than one ABI.
7419   // Determine the correct emulation for ld.
7420   switch (getToolChain().getArch()) {
7421   case llvm::Triple::x86:
7422     CmdArgs.push_back("-m");
7423     CmdArgs.push_back("elf_i386");
7424     break;
7425   case llvm::Triple::arm:
7426   case llvm::Triple::thumb:
7427     CmdArgs.push_back("-m");
7428     switch (getToolChain().getTriple().getEnvironment()) {
7429     case llvm::Triple::EABI:
7430     case llvm::Triple::GNUEABI:
7431       CmdArgs.push_back("armelf_nbsd_eabi");
7432       break;
7433     case llvm::Triple::EABIHF:
7434     case llvm::Triple::GNUEABIHF:
7435       CmdArgs.push_back("armelf_nbsd_eabihf");
7436       break;
7437     default:
7438       CmdArgs.push_back("armelf_nbsd");
7439       break;
7440     }
7441     break;
7442   case llvm::Triple::armeb:
7443   case llvm::Triple::thumbeb:
7444     arm::appendEBLinkFlags(Args, CmdArgs,
7445         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7446     CmdArgs.push_back("-m");
7447     switch (getToolChain().getTriple().getEnvironment()) {
7448     case llvm::Triple::EABI:
7449     case llvm::Triple::GNUEABI:
7450       CmdArgs.push_back("armelfb_nbsd_eabi");
7451       break;
7452     case llvm::Triple::EABIHF:
7453     case llvm::Triple::GNUEABIHF:
7454       CmdArgs.push_back("armelfb_nbsd_eabihf");
7455       break;
7456     default:
7457       CmdArgs.push_back("armelfb_nbsd");
7458       break;
7459     }
7460     break;
7461   case llvm::Triple::mips64:
7462   case llvm::Triple::mips64el:
7463     if (mips::hasMipsAbiArg(Args, "32")) {
7464       CmdArgs.push_back("-m");
7465       if (getToolChain().getArch() == llvm::Triple::mips64)
7466         CmdArgs.push_back("elf32btsmip");
7467       else
7468         CmdArgs.push_back("elf32ltsmip");
7469    } else if (mips::hasMipsAbiArg(Args, "64")) {
7470      CmdArgs.push_back("-m");
7471      if (getToolChain().getArch() == llvm::Triple::mips64)
7472        CmdArgs.push_back("elf64btsmip");
7473      else
7474        CmdArgs.push_back("elf64ltsmip");
7475    }
7476    break;
7477   case llvm::Triple::ppc:
7478     CmdArgs.push_back("-m");
7479     CmdArgs.push_back("elf32ppc_nbsd");
7480     break;
7481
7482   case llvm::Triple::ppc64:
7483   case llvm::Triple::ppc64le:
7484     CmdArgs.push_back("-m");
7485     CmdArgs.push_back("elf64ppc");
7486     break;
7487
7488   case llvm::Triple::sparc:
7489     CmdArgs.push_back("-m");
7490     CmdArgs.push_back("elf32_sparc");
7491     break;
7492
7493   case llvm::Triple::sparcv9:
7494     CmdArgs.push_back("-m");
7495     CmdArgs.push_back("elf64_sparc");
7496     break;
7497
7498   default:
7499     break;
7500   }
7501
7502   if (Output.isFilename()) {
7503     CmdArgs.push_back("-o");
7504     CmdArgs.push_back(Output.getFilename());
7505   } else {
7506     assert(Output.isNothing() && "Invalid output.");
7507   }
7508
7509   if (!Args.hasArg(options::OPT_nostdlib) &&
7510       !Args.hasArg(options::OPT_nostartfiles)) {
7511     if (!Args.hasArg(options::OPT_shared)) {
7512       CmdArgs.push_back(Args.MakeArgString(
7513                               getToolChain().GetFilePath("crt0.o")));
7514       CmdArgs.push_back(Args.MakeArgString(
7515                               getToolChain().GetFilePath("crti.o")));
7516       CmdArgs.push_back(Args.MakeArgString(
7517                               getToolChain().GetFilePath("crtbegin.o")));
7518     } else {
7519       CmdArgs.push_back(Args.MakeArgString(
7520                               getToolChain().GetFilePath("crti.o")));
7521       CmdArgs.push_back(Args.MakeArgString(
7522                               getToolChain().GetFilePath("crtbeginS.o")));
7523     }
7524   }
7525
7526   Args.AddAllArgs(CmdArgs, options::OPT_L);
7527   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7528   Args.AddAllArgs(CmdArgs, options::OPT_e);
7529   Args.AddAllArgs(CmdArgs, options::OPT_s);
7530   Args.AddAllArgs(CmdArgs, options::OPT_t);
7531   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7532   Args.AddAllArgs(CmdArgs, options::OPT_r);
7533
7534   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7535
7536   unsigned Major, Minor, Micro;
7537   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
7538   bool useLibgcc = true;
7539   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
7540     switch(getToolChain().getArch()) {
7541     case llvm::Triple::aarch64:
7542     case llvm::Triple::arm:
7543     case llvm::Triple::armeb:
7544     case llvm::Triple::thumb:
7545     case llvm::Triple::thumbeb:
7546     case llvm::Triple::ppc:
7547     case llvm::Triple::ppc64:
7548     case llvm::Triple::ppc64le:
7549     case llvm::Triple::x86:
7550     case llvm::Triple::x86_64:
7551       useLibgcc = false;
7552       break;
7553     default:
7554       break;
7555     }
7556   }
7557
7558   if (!Args.hasArg(options::OPT_nostdlib) &&
7559       !Args.hasArg(options::OPT_nodefaultlibs)) {
7560     if (D.CCCIsCXX()) {
7561       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7562       CmdArgs.push_back("-lm");
7563     }
7564     if (Args.hasArg(options::OPT_pthread))
7565       CmdArgs.push_back("-lpthread");
7566     CmdArgs.push_back("-lc");
7567
7568     if (useLibgcc) {
7569       if (Args.hasArg(options::OPT_static)) {
7570         // libgcc_eh depends on libc, so resolve as much as possible,
7571         // pull in any new requirements from libc and then get the rest
7572         // of libgcc.
7573         CmdArgs.push_back("-lgcc_eh");
7574         CmdArgs.push_back("-lc");
7575         CmdArgs.push_back("-lgcc");
7576       } else {
7577         CmdArgs.push_back("-lgcc");
7578         CmdArgs.push_back("--as-needed");
7579         CmdArgs.push_back("-lgcc_s");
7580         CmdArgs.push_back("--no-as-needed");
7581       }
7582     }
7583   }
7584
7585   if (!Args.hasArg(options::OPT_nostdlib) &&
7586       !Args.hasArg(options::OPT_nostartfiles)) {
7587     if (!Args.hasArg(options::OPT_shared))
7588       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
7589                                                                   "crtend.o")));
7590     else
7591       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
7592                                                                  "crtendS.o")));
7593     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
7594                                                                     "crtn.o")));
7595   }
7596
7597   addProfileRT(getToolChain(), Args, CmdArgs);
7598
7599   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7600   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7601 }
7602
7603 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7604                                       const InputInfo &Output,
7605                                       const InputInfoList &Inputs,
7606                                       const ArgList &Args,
7607                                       const char *LinkingOutput) const {
7608   claimNoWarnArgs(Args);
7609
7610   ArgStringList CmdArgs;
7611   bool NeedsKPIC = false;
7612
7613   switch (getToolChain().getArch()) {
7614   default:
7615     break;
7616   // Add --32/--64 to make sure we get the format we want.
7617   // This is incomplete
7618   case llvm::Triple::x86:
7619     CmdArgs.push_back("--32");
7620     break;
7621   case llvm::Triple::x86_64:
7622     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
7623       CmdArgs.push_back("--x32");
7624     else
7625       CmdArgs.push_back("--64");
7626     break;
7627   case llvm::Triple::ppc:
7628     CmdArgs.push_back("-a32");
7629     CmdArgs.push_back("-mppc");
7630     CmdArgs.push_back("-many");
7631     break;
7632   case llvm::Triple::ppc64:
7633     CmdArgs.push_back("-a64");
7634     CmdArgs.push_back("-mppc64");
7635     CmdArgs.push_back("-many");
7636     break;
7637   case llvm::Triple::ppc64le:
7638     CmdArgs.push_back("-a64");
7639     CmdArgs.push_back("-mppc64");
7640     CmdArgs.push_back("-many");
7641     CmdArgs.push_back("-mlittle-endian");
7642     break;
7643   case llvm::Triple::sparc:
7644   case llvm::Triple::sparcel:
7645     CmdArgs.push_back("-32");
7646     CmdArgs.push_back("-Av8plusa");
7647     NeedsKPIC = true;
7648     break;
7649   case llvm::Triple::sparcv9:
7650     CmdArgs.push_back("-64");
7651     CmdArgs.push_back("-Av9a");
7652     NeedsKPIC = true;
7653     break;
7654   case llvm::Triple::arm:
7655   case llvm::Triple::armeb:
7656   case llvm::Triple::thumb:
7657   case llvm::Triple::thumbeb: {
7658     const llvm::Triple &Triple = getToolChain().getTriple();
7659     switch (Triple.getSubArch()) {
7660     case llvm::Triple::ARMSubArch_v7:
7661       CmdArgs.push_back("-mfpu=neon");
7662       break;
7663     case llvm::Triple::ARMSubArch_v8:
7664       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7665       break;
7666     default:
7667       break;
7668     }
7669
7670     StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7671         getToolChain().getDriver(), Args,
7672         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7673     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7674
7675     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7676
7677     // FIXME: remove krait check when GNU tools support krait cpu
7678     // for now replace it with -march=armv7-a  to avoid a lower
7679     // march from being picked in the absence of a cpu flag.
7680     Arg *A;
7681     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7682       StringRef(A->getValue()).lower() == "krait")
7683         CmdArgs.push_back("-march=armv7-a");
7684     else
7685       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7686     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7687     break;
7688   }
7689   case llvm::Triple::mips:
7690   case llvm::Triple::mipsel:
7691   case llvm::Triple::mips64:
7692   case llvm::Triple::mips64el: {
7693     StringRef CPUName;
7694     StringRef ABIName;
7695     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7696     ABIName = getGnuCompatibleMipsABIName(ABIName);
7697
7698     CmdArgs.push_back("-march");
7699     CmdArgs.push_back(CPUName.data());
7700
7701     CmdArgs.push_back("-mabi");
7702     CmdArgs.push_back(ABIName.data());
7703
7704     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7705     // or -mshared (not implemented) is in effect.
7706     bool IsPicOrPie = false;
7707     if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7708                                  options::OPT_fpic, options::OPT_fno_pic,
7709                                  options::OPT_fPIE, options::OPT_fno_PIE,
7710                                  options::OPT_fpie, options::OPT_fno_pie)) {
7711       if (A->getOption().matches(options::OPT_fPIC) ||
7712           A->getOption().matches(options::OPT_fpic) ||
7713           A->getOption().matches(options::OPT_fPIE) ||
7714           A->getOption().matches(options::OPT_fpie))
7715         IsPicOrPie = true;
7716     }
7717     if (!IsPicOrPie)
7718       CmdArgs.push_back("-mno-shared");
7719
7720     // LLVM doesn't support -mplt yet and acts as if it is always given.
7721     // However, -mplt has no effect with the N64 ABI.
7722     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7723
7724     if (getToolChain().getArch() == llvm::Triple::mips ||
7725         getToolChain().getArch() == llvm::Triple::mips64)
7726       CmdArgs.push_back("-EB");
7727     else
7728       CmdArgs.push_back("-EL");
7729
7730     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7731       if (StringRef(A->getValue()) == "2008")
7732         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7733     }
7734
7735     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7736     StringRef MIPSFloatABI = getMipsFloatABI(getToolChain().getDriver(), Args);
7737     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7738                                  options::OPT_mfp64)) {
7739       A->claim();
7740       A->render(Args, CmdArgs);
7741     } else if (mips::shouldUseFPXX(Args, getToolChain().getTriple(), CPUName,
7742                                    ABIName, MIPSFloatABI))
7743       CmdArgs.push_back("-mfpxx");
7744
7745     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7746     // -mno-mips16 is actually -no-mips16.
7747     if (Arg *A = Args.getLastArg(options::OPT_mips16,
7748                                  options::OPT_mno_mips16)) {
7749       if (A->getOption().matches(options::OPT_mips16)) {
7750         A->claim();
7751         A->render(Args, CmdArgs);
7752       } else {
7753         A->claim();
7754         CmdArgs.push_back("-no-mips16");
7755       }
7756     }
7757
7758     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7759                     options::OPT_mno_micromips);
7760     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7761     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7762
7763     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7764       // Do not use AddLastArg because not all versions of MIPS assembler
7765       // support -mmsa / -mno-msa options.
7766       if (A->getOption().matches(options::OPT_mmsa))
7767         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7768     }
7769
7770     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7771                     options::OPT_msoft_float);
7772
7773     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
7774                     options::OPT_msingle_float);
7775
7776     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7777                     options::OPT_mno_odd_spreg);
7778
7779     NeedsKPIC = true;
7780     break;
7781   }
7782   case llvm::Triple::systemz: {
7783     // Always pass an -march option, since our default of z10 is later
7784     // than the GNU assembler's default.
7785     StringRef CPUName = getSystemZTargetCPU(Args);
7786     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7787     break;
7788   }
7789   }
7790
7791   if (NeedsKPIC)
7792     addAssemblerKPIC(Args, CmdArgs);
7793
7794   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7795                        options::OPT_Xassembler);
7796
7797   CmdArgs.push_back("-o");
7798   CmdArgs.push_back(Output.getFilename());
7799
7800   for (const auto &II : Inputs)
7801     CmdArgs.push_back(II.getFilename());
7802
7803   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7804   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7805
7806   // Handle the debug info splitting at object creation time if we're
7807   // creating an object.
7808   // TODO: Currently only works on linux with newer objcopy.
7809   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7810       getToolChain().getTriple().isOSLinux())
7811     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7812                    SplitDebugName(Args, Inputs[0]));
7813 }
7814
7815 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7816                       ArgStringList &CmdArgs, const ArgList &Args) {
7817   bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7818   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7819                       Args.hasArg(options::OPT_static);
7820   if (!D.CCCIsCXX())
7821     CmdArgs.push_back("-lgcc");
7822
7823   if (StaticLibgcc || isAndroid) {
7824     if (D.CCCIsCXX())
7825       CmdArgs.push_back("-lgcc");
7826   } else {
7827     if (!D.CCCIsCXX())
7828       CmdArgs.push_back("--as-needed");
7829     CmdArgs.push_back("-lgcc_s");
7830     if (!D.CCCIsCXX())
7831       CmdArgs.push_back("--no-as-needed");
7832   }
7833
7834   if (StaticLibgcc && !isAndroid)
7835     CmdArgs.push_back("-lgcc_eh");
7836   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7837     CmdArgs.push_back("-lgcc");
7838
7839   // According to Android ABI, we have to link with libdl if we are
7840   // linking with non-static libgcc.
7841   //
7842   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
7843   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7844   if (isAndroid && !StaticLibgcc)
7845     CmdArgs.push_back("-ldl");
7846 }
7847
7848 static std::string getLinuxDynamicLinker(const ArgList &Args,
7849                                          const toolchains::Linux &ToolChain) {
7850   const llvm::Triple::ArchType Arch = ToolChain.getArch();
7851
7852   if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7853     if (ToolChain.getTriple().isArch64Bit())
7854       return "/system/bin/linker64";
7855     else
7856       return "/system/bin/linker";
7857   } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
7858              Arch == llvm::Triple::sparcel)
7859     return "/lib/ld-linux.so.2";
7860   else if (Arch == llvm::Triple::aarch64)
7861     return "/lib/ld-linux-aarch64.so.1";
7862   else if (Arch == llvm::Triple::aarch64_be)
7863     return "/lib/ld-linux-aarch64_be.so.1";
7864   else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
7865     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7866       return "/lib/ld-linux-armhf.so.3";
7867     else
7868       return "/lib/ld-linux.so.3";
7869   } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
7870     // TODO: check which dynamic linker name.
7871     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7872       return "/lib/ld-linux-armhf.so.3";
7873     else
7874       return "/lib/ld-linux.so.3";
7875   } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
7876              Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
7877     StringRef CPUName;
7878     StringRef ABIName;
7879     mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
7880     bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
7881
7882     StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
7883                            .Case("o32", "/lib")
7884                            .Case("n32", "/lib32")
7885                            .Case("n64", "/lib64")
7886                            .Default("/lib");
7887     StringRef LibName;
7888     if (mips::isUCLibc(Args))
7889       LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
7890     else
7891       LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
7892
7893     return (LibDir + "/" + LibName).str();
7894   } else if (Arch == llvm::Triple::ppc)
7895     return "/lib/ld.so.1";
7896   else if (Arch == llvm::Triple::ppc64) {
7897     if (ppc::hasPPCAbiArg(Args, "elfv2"))
7898       return "/lib64/ld64.so.2";
7899     return "/lib64/ld64.so.1";
7900   } else if (Arch == llvm::Triple::ppc64le) {
7901     if (ppc::hasPPCAbiArg(Args, "elfv1"))
7902       return "/lib64/ld64.so.1";
7903     return "/lib64/ld64.so.2";
7904   } else if (Arch == llvm::Triple::systemz)
7905     return "/lib64/ld64.so.1";
7906   else if (Arch == llvm::Triple::sparcv9)
7907     return "/lib64/ld-linux.so.2";
7908   else if (Arch == llvm::Triple::x86_64 &&
7909            ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
7910     return "/libx32/ld-linux-x32.so.2";
7911   else
7912     return "/lib64/ld-linux-x86-64.so.2";
7913 }
7914
7915 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
7916                            ArgStringList &CmdArgs, const ArgList &Args) {
7917   // Make use of compiler-rt if --rtlib option is used
7918   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
7919
7920   switch (RLT) {
7921   case ToolChain::RLT_CompilerRT:
7922     switch (TC.getTriple().getOS()) {
7923     default: llvm_unreachable("unsupported OS");
7924     case llvm::Triple::Win32:
7925     case llvm::Triple::Linux:
7926       addClangRT(TC, Args, CmdArgs);
7927       break;
7928     }
7929     break;
7930   case ToolChain::RLT_Libgcc:
7931     AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
7932     break;
7933   }
7934 }
7935
7936 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
7937   switch (T.getArch()) {
7938   case llvm::Triple::x86:
7939     return "elf_i386";
7940   case llvm::Triple::aarch64:
7941     return "aarch64linux";
7942   case llvm::Triple::aarch64_be:
7943     return "aarch64_be_linux";
7944   case llvm::Triple::arm:
7945   case llvm::Triple::thumb:
7946     return "armelf_linux_eabi";
7947   case llvm::Triple::armeb:
7948   case llvm::Triple::thumbeb:
7949     return "armebelf_linux_eabi"; /* TODO: check which NAME.  */
7950   case llvm::Triple::ppc:
7951     return "elf32ppclinux";
7952   case llvm::Triple::ppc64:
7953     return "elf64ppc";
7954   case llvm::Triple::ppc64le:
7955     return "elf64lppc";
7956   case llvm::Triple::sparc:
7957   case llvm::Triple::sparcel:
7958     return "elf32_sparc";
7959   case llvm::Triple::sparcv9:
7960     return "elf64_sparc";
7961   case llvm::Triple::mips:
7962     return "elf32btsmip";
7963   case llvm::Triple::mipsel:
7964     return "elf32ltsmip";
7965   case llvm::Triple::mips64:
7966     if (mips::hasMipsAbiArg(Args, "n32"))
7967       return "elf32btsmipn32";
7968     return "elf64btsmip";
7969   case llvm::Triple::mips64el:
7970     if (mips::hasMipsAbiArg(Args, "n32"))
7971       return "elf32ltsmipn32";
7972     return "elf64ltsmip";
7973   case llvm::Triple::systemz:
7974     return "elf64_s390";
7975   case llvm::Triple::x86_64:
7976     if (T.getEnvironment() == llvm::Triple::GNUX32)
7977       return "elf32_x86_64";
7978     return "elf_x86_64";
7979   default:
7980     llvm_unreachable("Unexpected arch");
7981   }
7982 }
7983
7984 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
7985                                   const InputInfo &Output,
7986                                   const InputInfoList &Inputs,
7987                                   const ArgList &Args,
7988                                   const char *LinkingOutput) const {
7989   const toolchains::Linux &ToolChain =
7990       static_cast<const toolchains::Linux &>(getToolChain());
7991   const Driver &D = ToolChain.getDriver();
7992   const llvm::Triple::ArchType Arch = ToolChain.getArch();
7993   const bool isAndroid =
7994       ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
7995   const bool IsPIE =
7996       !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
7997       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7998
7999   ArgStringList CmdArgs;
8000
8001   // Silence warning for "clang -g foo.o -o foo"
8002   Args.ClaimAllArgs(options::OPT_g_Group);
8003   // and "clang -emit-llvm foo.o -o foo"
8004   Args.ClaimAllArgs(options::OPT_emit_llvm);
8005   // and for "clang -w foo.o -o foo". Other warning options are already
8006   // handled somewhere else.
8007   Args.ClaimAllArgs(options::OPT_w);
8008
8009   if (!D.SysRoot.empty())
8010     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8011
8012   if (IsPIE)
8013     CmdArgs.push_back("-pie");
8014
8015   if (Args.hasArg(options::OPT_rdynamic))
8016     CmdArgs.push_back("-export-dynamic");
8017
8018   if (Args.hasArg(options::OPT_s))
8019     CmdArgs.push_back("-s");
8020
8021   if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8022     arm::appendEBLinkFlags(
8023         Args, CmdArgs,
8024         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8025
8026   for (const auto &Opt : ToolChain.ExtraOpts)
8027     CmdArgs.push_back(Opt.c_str());
8028
8029   if (!Args.hasArg(options::OPT_static)) {
8030     CmdArgs.push_back("--eh-frame-hdr");
8031   }
8032
8033   CmdArgs.push_back("-m");
8034   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8035
8036   if (Args.hasArg(options::OPT_static)) {
8037     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8038         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8039       CmdArgs.push_back("-Bstatic");
8040     else
8041       CmdArgs.push_back("-static");
8042   } else if (Args.hasArg(options::OPT_shared)) {
8043     CmdArgs.push_back("-shared");
8044   }
8045
8046   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8047       Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8048       (!Args.hasArg(options::OPT_static) &&
8049        !Args.hasArg(options::OPT_shared))) {
8050     CmdArgs.push_back("-dynamic-linker");
8051     CmdArgs.push_back(Args.MakeArgString(
8052         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8053   }
8054
8055   CmdArgs.push_back("-o");
8056   CmdArgs.push_back(Output.getFilename());
8057
8058   if (!Args.hasArg(options::OPT_nostdlib) &&
8059       !Args.hasArg(options::OPT_nostartfiles)) {
8060     if (!isAndroid) {
8061       const char *crt1 = nullptr;
8062       if (!Args.hasArg(options::OPT_shared)){
8063         if (Args.hasArg(options::OPT_pg))
8064           crt1 = "gcrt1.o";
8065         else if (IsPIE)
8066           crt1 = "Scrt1.o";
8067         else
8068           crt1 = "crt1.o";
8069       }
8070       if (crt1)
8071         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8072
8073       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8074     }
8075
8076     const char *crtbegin;
8077     if (Args.hasArg(options::OPT_static))
8078       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8079     else if (Args.hasArg(options::OPT_shared))
8080       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8081     else if (IsPIE)
8082       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8083     else
8084       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8085     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8086
8087     // Add crtfastmath.o if available and fast math is enabled.
8088     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8089   }
8090
8091   Args.AddAllArgs(CmdArgs, options::OPT_L);
8092   Args.AddAllArgs(CmdArgs, options::OPT_u);
8093
8094   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8095
8096   for (const auto &Path : Paths)
8097     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8098
8099   if (D.IsUsingLTO(Args))
8100     AddGoldPlugin(ToolChain, Args, CmdArgs);
8101
8102   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8103     CmdArgs.push_back("--no-demangle");
8104
8105   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8106   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8107   // The profile runtime also needs access to system libraries.
8108   addProfileRT(getToolChain(), Args, CmdArgs);
8109
8110   if (D.CCCIsCXX() &&
8111       !Args.hasArg(options::OPT_nostdlib) &&
8112       !Args.hasArg(options::OPT_nodefaultlibs)) {
8113     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8114       !Args.hasArg(options::OPT_static);
8115     if (OnlyLibstdcxxStatic)
8116       CmdArgs.push_back("-Bstatic");
8117     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8118     if (OnlyLibstdcxxStatic)
8119       CmdArgs.push_back("-Bdynamic");
8120     CmdArgs.push_back("-lm");
8121   }
8122   // Silence warnings when linking C code with a C++ '-stdlib' argument.
8123   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8124
8125   if (!Args.hasArg(options::OPT_nostdlib)) {
8126     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8127       if (Args.hasArg(options::OPT_static))
8128         CmdArgs.push_back("--start-group");
8129
8130       if (NeedsSanitizerDeps)
8131         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8132
8133       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8134                          Args.hasArg(options::OPT_pthreads);
8135
8136       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8137                        options::OPT_fno_openmp, false)) {
8138         // OpenMP runtimes implies pthreads when using the GNU toolchain.
8139         // FIXME: Does this really make sense for all GNU toolchains?
8140         WantPthread = true;
8141
8142         // Also link the particular OpenMP runtimes.
8143         switch (getOpenMPRuntime(ToolChain, Args)) {
8144         case OMPRT_OMP:
8145           CmdArgs.push_back("-lomp");
8146           break;
8147         case OMPRT_GOMP:
8148           CmdArgs.push_back("-lgomp");
8149
8150           // FIXME: Exclude this for platforms with libgomp that don't require
8151           // librt. Most modern Linux platforms require it, but some may not.
8152           CmdArgs.push_back("-lrt");
8153           break;
8154         case OMPRT_IOMP5:
8155           CmdArgs.push_back("-liomp5");
8156           break;
8157         case OMPRT_Unknown:
8158           // Already diagnosed.
8159           break;
8160         }
8161       }
8162
8163       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8164
8165       if (WantPthread && !isAndroid)
8166         CmdArgs.push_back("-lpthread");
8167
8168       CmdArgs.push_back("-lc");
8169
8170       if (Args.hasArg(options::OPT_static))
8171         CmdArgs.push_back("--end-group");
8172       else
8173         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8174     }
8175
8176     if (!Args.hasArg(options::OPT_nostartfiles)) {
8177       const char *crtend;
8178       if (Args.hasArg(options::OPT_shared))
8179         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8180       else if (IsPIE)
8181         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8182       else
8183         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8184
8185       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8186       if (!isAndroid)
8187         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8188     }
8189   }
8190
8191   C.addCommand(
8192       llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8193 }
8194
8195
8196 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8197 // for the various SFI requirements like register masking. The assembly tool
8198 // inserts the file containing the macros as an input into all the assembly
8199 // jobs.
8200 void nacltools::AssembleARM::ConstructJob(Compilation &C, const JobAction &JA,
8201                                           const InputInfo &Output,
8202                                           const InputInfoList &Inputs,
8203                                           const ArgList &Args,
8204                                           const char *LinkingOutput) const {
8205   const toolchains::NaCl_TC& ToolChain =
8206     static_cast<const toolchains::NaCl_TC&>(getToolChain());
8207   InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8208                        "nacl-arm-macros.s");
8209   InputInfoList NewInputs;
8210   NewInputs.push_back(NaClMacros);
8211   NewInputs.append(Inputs.begin(), Inputs.end());
8212   gnutools::Assemble::ConstructJob(C, JA, Output, NewInputs, Args,
8213                                    LinkingOutput);
8214 }
8215
8216
8217 // This is quite similar to gnutools::link::ConstructJob with changes that
8218 // we use static by default, do not yet support sanitizers or LTO, and a few
8219 // others. Eventually we can support more of that and hopefully migrate back
8220 // to gnutools::link.
8221 void nacltools::Link::ConstructJob(Compilation &C, const JobAction &JA,
8222                                    const InputInfo &Output,
8223                                    const InputInfoList &Inputs,
8224                                    const ArgList &Args,
8225                                    const char *LinkingOutput) const {
8226
8227   const toolchains::NaCl_TC &ToolChain =
8228       static_cast<const toolchains::NaCl_TC &>(getToolChain());
8229   const Driver &D = ToolChain.getDriver();
8230   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8231   const bool IsStatic =
8232       !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8233
8234   ArgStringList CmdArgs;
8235
8236   // Silence warning for "clang -g foo.o -o foo"
8237   Args.ClaimAllArgs(options::OPT_g_Group);
8238   // and "clang -emit-llvm foo.o -o foo"
8239   Args.ClaimAllArgs(options::OPT_emit_llvm);
8240   // and for "clang -w foo.o -o foo". Other warning options are already
8241   // handled somewhere else.
8242   Args.ClaimAllArgs(options::OPT_w);
8243
8244   if (!D.SysRoot.empty())
8245     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8246
8247   if (Args.hasArg(options::OPT_rdynamic))
8248     CmdArgs.push_back("-export-dynamic");
8249
8250   if (Args.hasArg(options::OPT_s))
8251     CmdArgs.push_back("-s");
8252
8253   // NaCl_TC doesn't have ExtraOpts like Linux; the only relevant flag from
8254   // there is --build-id, which we do want.
8255   CmdArgs.push_back("--build-id");
8256
8257   if (!IsStatic)
8258     CmdArgs.push_back("--eh-frame-hdr");
8259
8260   CmdArgs.push_back("-m");
8261   if (Arch == llvm::Triple::x86)
8262     CmdArgs.push_back("elf_i386_nacl");
8263   else if (Arch == llvm::Triple::arm)
8264     CmdArgs.push_back("armelf_nacl");
8265   else if (Arch == llvm::Triple::x86_64)
8266     CmdArgs.push_back("elf_x86_64_nacl");
8267   else
8268     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8269                                               << "Native Client";
8270
8271   if (IsStatic)
8272     CmdArgs.push_back("-static");
8273   else if (Args.hasArg(options::OPT_shared))
8274     CmdArgs.push_back("-shared");
8275
8276   CmdArgs.push_back("-o");
8277   CmdArgs.push_back(Output.getFilename());
8278   if (!Args.hasArg(options::OPT_nostdlib) &&
8279       !Args.hasArg(options::OPT_nostartfiles)) {
8280     if (!Args.hasArg(options::OPT_shared))
8281       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
8282     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8283
8284     const char *crtbegin;
8285     if (IsStatic)
8286       crtbegin = "crtbeginT.o";
8287     else if (Args.hasArg(options::OPT_shared))
8288       crtbegin = "crtbeginS.o";
8289     else
8290       crtbegin = "crtbegin.o";
8291     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8292   }
8293
8294   Args.AddAllArgs(CmdArgs, options::OPT_L);
8295   Args.AddAllArgs(CmdArgs, options::OPT_u);
8296
8297   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8298
8299   for (const auto &Path : Paths)
8300     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8301
8302   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8303     CmdArgs.push_back("--no-demangle");
8304
8305   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8306
8307   if (D.CCCIsCXX() &&
8308       !Args.hasArg(options::OPT_nostdlib) &&
8309       !Args.hasArg(options::OPT_nodefaultlibs)) {
8310     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8311       !IsStatic;
8312     if (OnlyLibstdcxxStatic)
8313       CmdArgs.push_back("-Bstatic");
8314     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8315     if (OnlyLibstdcxxStatic)
8316       CmdArgs.push_back("-Bdynamic");
8317     CmdArgs.push_back("-lm");
8318   }
8319
8320   if (!Args.hasArg(options::OPT_nostdlib)) {
8321     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8322       // Always use groups, since it has no effect on dynamic libraries.
8323       CmdArgs.push_back("--start-group");
8324       CmdArgs.push_back("-lc");
8325       // NaCl's libc++ currently requires libpthread, so just always include it
8326       // in the group for C++.
8327       if (Args.hasArg(options::OPT_pthread) ||
8328           Args.hasArg(options::OPT_pthreads) ||
8329           D.CCCIsCXX()) {
8330         CmdArgs.push_back("-lpthread");
8331       }
8332
8333       CmdArgs.push_back("-lgcc");
8334       CmdArgs.push_back("--as-needed");
8335       if (IsStatic)
8336         CmdArgs.push_back("-lgcc_eh");
8337       else
8338         CmdArgs.push_back("-lgcc_s");
8339       CmdArgs.push_back("--no-as-needed");
8340       CmdArgs.push_back("--end-group");
8341     }
8342
8343     if (!Args.hasArg(options::OPT_nostartfiles)) {
8344       const char *crtend;
8345       if (Args.hasArg(options::OPT_shared))
8346         crtend = "crtendS.o";
8347       else
8348         crtend = "crtend.o";
8349
8350       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8351       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8352     }
8353   }
8354
8355   C.addCommand(llvm::make_unique<Command>(JA, *this,
8356                                           ToolChain.Linker.c_str(), CmdArgs));
8357 }
8358
8359
8360 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
8361                                    const InputInfo &Output,
8362                                    const InputInfoList &Inputs,
8363                                    const ArgList &Args,
8364                                    const char *LinkingOutput) const {
8365   claimNoWarnArgs(Args);
8366   ArgStringList CmdArgs;
8367
8368   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8369
8370   CmdArgs.push_back("-o");
8371   CmdArgs.push_back(Output.getFilename());
8372
8373   for (const auto &II : Inputs)
8374     CmdArgs.push_back(II.getFilename());
8375
8376   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8377   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8378 }
8379
8380 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
8381                                const InputInfo &Output,
8382                                const InputInfoList &Inputs,
8383                                const ArgList &Args,
8384                                const char *LinkingOutput) const {
8385   const Driver &D = getToolChain().getDriver();
8386   ArgStringList CmdArgs;
8387
8388   if (Output.isFilename()) {
8389     CmdArgs.push_back("-o");
8390     CmdArgs.push_back(Output.getFilename());
8391   } else {
8392     assert(Output.isNothing() && "Invalid output.");
8393   }
8394
8395   if (!Args.hasArg(options::OPT_nostdlib) &&
8396       !Args.hasArg(options::OPT_nostartfiles)) {
8397       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8398       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8399       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8400       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8401   }
8402
8403   Args.AddAllArgs(CmdArgs, options::OPT_L);
8404   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8405   Args.AddAllArgs(CmdArgs, options::OPT_e);
8406
8407   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8408
8409   addProfileRT(getToolChain(), Args, CmdArgs);
8410
8411   if (!Args.hasArg(options::OPT_nostdlib) &&
8412       !Args.hasArg(options::OPT_nodefaultlibs)) {
8413     if (D.CCCIsCXX()) {
8414       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8415       CmdArgs.push_back("-lm");
8416     }
8417   }
8418
8419   if (!Args.hasArg(options::OPT_nostdlib) &&
8420       !Args.hasArg(options::OPT_nostartfiles)) {
8421     if (Args.hasArg(options::OPT_pthread))
8422       CmdArgs.push_back("-lpthread");
8423     CmdArgs.push_back("-lc");
8424     CmdArgs.push_back("-lCompilerRT-Generic");
8425     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
8426     CmdArgs.push_back(
8427          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8428   }
8429
8430   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8431   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8432 }
8433
8434 /// DragonFly Tools
8435
8436 // For now, DragonFly Assemble does just about the same as for
8437 // FreeBSD, but this may change soon.
8438 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
8439                                        const InputInfo &Output,
8440                                        const InputInfoList &Inputs,
8441                                        const ArgList &Args,
8442                                        const char *LinkingOutput) const {
8443   claimNoWarnArgs(Args);
8444   ArgStringList CmdArgs;
8445
8446   // When building 32-bit code on DragonFly/pc64, we have to explicitly
8447   // instruct as in the base system to assemble 32-bit code.
8448   if (getToolChain().getArch() == llvm::Triple::x86)
8449     CmdArgs.push_back("--32");
8450
8451   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8452
8453   CmdArgs.push_back("-o");
8454   CmdArgs.push_back(Output.getFilename());
8455
8456   for (const auto &II : Inputs)
8457     CmdArgs.push_back(II.getFilename());
8458
8459   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8460   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8461 }
8462
8463 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
8464                                    const InputInfo &Output,
8465                                    const InputInfoList &Inputs,
8466                                    const ArgList &Args,
8467                                    const char *LinkingOutput) const {
8468   const Driver &D = getToolChain().getDriver();
8469   ArgStringList CmdArgs;
8470   bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
8471
8472   if (!D.SysRoot.empty())
8473     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8474
8475   CmdArgs.push_back("--eh-frame-hdr");
8476   if (Args.hasArg(options::OPT_static)) {
8477     CmdArgs.push_back("-Bstatic");
8478   } else {
8479     if (Args.hasArg(options::OPT_rdynamic))
8480       CmdArgs.push_back("-export-dynamic");
8481     if (Args.hasArg(options::OPT_shared))
8482       CmdArgs.push_back("-Bshareable");
8483     else {
8484       CmdArgs.push_back("-dynamic-linker");
8485       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
8486     }
8487     CmdArgs.push_back("--hash-style=both");
8488   }
8489
8490   // When building 32-bit code on DragonFly/pc64, we have to explicitly
8491   // instruct ld in the base system to link 32-bit code.
8492   if (getToolChain().getArch() == llvm::Triple::x86) {
8493     CmdArgs.push_back("-m");
8494     CmdArgs.push_back("elf_i386");
8495   }
8496
8497   if (Output.isFilename()) {
8498     CmdArgs.push_back("-o");
8499     CmdArgs.push_back(Output.getFilename());
8500   } else {
8501     assert(Output.isNothing() && "Invalid output.");
8502   }
8503
8504   if (!Args.hasArg(options::OPT_nostdlib) &&
8505       !Args.hasArg(options::OPT_nostartfiles)) {
8506     if (!Args.hasArg(options::OPT_shared)) {
8507       if (Args.hasArg(options::OPT_pg))
8508         CmdArgs.push_back(Args.MakeArgString(
8509                                 getToolChain().GetFilePath("gcrt1.o")));
8510       else {
8511         if (Args.hasArg(options::OPT_pie))
8512           CmdArgs.push_back(Args.MakeArgString(
8513                                   getToolChain().GetFilePath("Scrt1.o")));
8514         else
8515           CmdArgs.push_back(Args.MakeArgString(
8516                                   getToolChain().GetFilePath("crt1.o")));
8517       }
8518     }
8519     CmdArgs.push_back(Args.MakeArgString(
8520                             getToolChain().GetFilePath("crti.o")));
8521     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8522       CmdArgs.push_back(Args.MakeArgString(
8523                               getToolChain().GetFilePath("crtbeginS.o")));
8524     else
8525       CmdArgs.push_back(Args.MakeArgString(
8526                               getToolChain().GetFilePath("crtbegin.o")));
8527   }
8528
8529   Args.AddAllArgs(CmdArgs, options::OPT_L);
8530   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8531   Args.AddAllArgs(CmdArgs, options::OPT_e);
8532
8533   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8534
8535   if (!Args.hasArg(options::OPT_nostdlib) &&
8536       !Args.hasArg(options::OPT_nodefaultlibs)) {
8537     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
8538     //         rpaths
8539     if (UseGCC47)
8540       CmdArgs.push_back("-L/usr/lib/gcc47");
8541     else
8542       CmdArgs.push_back("-L/usr/lib/gcc44");
8543
8544     if (!Args.hasArg(options::OPT_static)) {
8545       if (UseGCC47) {
8546         CmdArgs.push_back("-rpath");
8547         CmdArgs.push_back("/usr/lib/gcc47");
8548       } else {
8549         CmdArgs.push_back("-rpath");
8550         CmdArgs.push_back("/usr/lib/gcc44");
8551       }
8552     }
8553
8554     if (D.CCCIsCXX()) {
8555       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8556       CmdArgs.push_back("-lm");
8557     }
8558
8559     if (Args.hasArg(options::OPT_pthread))
8560       CmdArgs.push_back("-lpthread");
8561
8562     if (!Args.hasArg(options::OPT_nolibc)) {
8563       CmdArgs.push_back("-lc");
8564     }
8565
8566     if (UseGCC47) {
8567       if (Args.hasArg(options::OPT_static) ||
8568           Args.hasArg(options::OPT_static_libgcc)) {
8569         CmdArgs.push_back("-lgcc");
8570         CmdArgs.push_back("-lgcc_eh");
8571       } else {
8572         if (Args.hasArg(options::OPT_shared_libgcc)) {
8573           CmdArgs.push_back("-lgcc_pic");
8574           if (!Args.hasArg(options::OPT_shared))
8575             CmdArgs.push_back("-lgcc");
8576         } else {
8577           CmdArgs.push_back("-lgcc");
8578           CmdArgs.push_back("--as-needed");
8579           CmdArgs.push_back("-lgcc_pic");
8580           CmdArgs.push_back("--no-as-needed");
8581         }
8582       }
8583     } else {
8584       if (Args.hasArg(options::OPT_shared)) {
8585         CmdArgs.push_back("-lgcc_pic");
8586       } else {
8587         CmdArgs.push_back("-lgcc");
8588       }
8589     }
8590   }
8591
8592   if (!Args.hasArg(options::OPT_nostdlib) &&
8593       !Args.hasArg(options::OPT_nostartfiles)) {
8594     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8595       CmdArgs.push_back(Args.MakeArgString(
8596                               getToolChain().GetFilePath("crtendS.o")));
8597     else
8598       CmdArgs.push_back(Args.MakeArgString(
8599                               getToolChain().GetFilePath("crtend.o")));
8600     CmdArgs.push_back(Args.MakeArgString(
8601                             getToolChain().GetFilePath("crtn.o")));
8602   }
8603
8604   addProfileRT(getToolChain(), Args, CmdArgs);
8605
8606   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8607   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8608 }
8609
8610 // Try to find Exe from a Visual Studio distribution.  This first tries to find
8611 // an installed copy of Visual Studio and, failing that, looks in the PATH,
8612 // making sure that whatever executable that's found is not a same-named exe
8613 // from clang itself to prevent clang from falling back to itself.
8614 static std::string FindVisualStudioExecutable(const ToolChain &TC,
8615                                               const char *Exe,
8616                                               const char *ClangProgramPath) {
8617   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8618   std::string visualStudioBinDir;
8619   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
8620                                          visualStudioBinDir)) {
8621     SmallString<128> FilePath(visualStudioBinDir);
8622     llvm::sys::path::append(FilePath, Exe);
8623     if (llvm::sys::fs::can_execute(FilePath.c_str()))
8624       return FilePath.str();
8625   }
8626
8627   return Exe;
8628 }
8629
8630 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
8631                                       const InputInfo &Output,
8632                                       const InputInfoList &Inputs,
8633                                       const ArgList &Args,
8634                                       const char *LinkingOutput) const {
8635   ArgStringList CmdArgs;
8636   const ToolChain &TC = getToolChain();
8637
8638   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
8639   if (Output.isFilename())
8640     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
8641                                          Output.getFilename()));
8642
8643   if (!Args.hasArg(options::OPT_nostdlib) &&
8644       !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
8645     CmdArgs.push_back("-defaultlib:libcmt");
8646
8647   if (!llvm::sys::Process::GetEnv("LIB")) {
8648     // If the VC environment hasn't been configured (perhaps because the user
8649     // did not run vcvarsall), try to build a consistent link environment.  If
8650     // the environment variable is set however, assume the user knows what
8651     // they're doing.
8652     std::string VisualStudioDir;
8653     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8654     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
8655       SmallString<128> LibDir(VisualStudioDir);
8656       llvm::sys::path::append(LibDir, "VC", "lib");
8657       switch (MSVC.getArch()) {
8658       case llvm::Triple::x86:
8659         // x86 just puts the libraries directly in lib
8660         break;
8661       case llvm::Triple::x86_64:
8662         llvm::sys::path::append(LibDir, "amd64");
8663         break;
8664       case llvm::Triple::arm:
8665         llvm::sys::path::append(LibDir, "arm");
8666         break;
8667       default:
8668         break;
8669       }
8670       CmdArgs.push_back(
8671           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
8672     }
8673
8674     std::string WindowsSdkLibPath;
8675     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
8676       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
8677                                            WindowsSdkLibPath.c_str()));
8678   }
8679
8680   CmdArgs.push_back("-nologo");
8681
8682   if (Args.hasArg(options::OPT_g_Group))
8683     CmdArgs.push_back("-debug");
8684
8685   bool DLL = Args.hasArg(options::OPT__SLASH_LD,
8686                          options::OPT__SLASH_LDd,
8687                          options::OPT_shared);
8688   if (DLL) {
8689     CmdArgs.push_back(Args.MakeArgString("-dll"));
8690
8691     SmallString<128> ImplibName(Output.getFilename());
8692     llvm::sys::path::replace_extension(ImplibName, "lib");
8693     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
8694                                          ImplibName));
8695   }
8696
8697   if (TC.getSanitizerArgs().needsAsanRt()) {
8698     CmdArgs.push_back(Args.MakeArgString("-debug"));
8699     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
8700     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
8701       static const char *CompilerRTComponents[] = {
8702         "asan_dynamic",
8703         "asan_dynamic_runtime_thunk",
8704       };
8705       for (const auto &Component : CompilerRTComponents)
8706         CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8707       // Make sure the dynamic runtime thunk is not optimized out at link time
8708       // to ensure proper SEH handling.
8709       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
8710     } else if (DLL) {
8711       CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
8712     } else {
8713       static const char *CompilerRTComponents[] = {
8714         "asan",
8715         "asan_cxx",
8716       };
8717       for (const auto &Component : CompilerRTComponents)
8718         CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8719     }
8720   }
8721
8722   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
8723
8724   // Add filenames, libraries, and other linker inputs.
8725   for (const auto &Input : Inputs) {
8726     if (Input.isFilename()) {
8727       CmdArgs.push_back(Input.getFilename());
8728       continue;
8729     }
8730
8731     const Arg &A = Input.getInputArg();
8732
8733     // Render -l options differently for the MSVC linker.
8734     if (A.getOption().matches(options::OPT_l)) {
8735       StringRef Lib = A.getValue();
8736       const char *LinkLibArg;
8737       if (Lib.endswith(".lib"))
8738         LinkLibArg = Args.MakeArgString(Lib);
8739       else
8740         LinkLibArg = Args.MakeArgString(Lib + ".lib");
8741       CmdArgs.push_back(LinkLibArg);
8742       continue;
8743     }
8744
8745     // Otherwise, this is some other kind of linker input option like -Wl, -z,
8746     // or -L. Render it, even if MSVC doesn't understand it.
8747     A.renderAsInput(Args, CmdArgs);
8748   }
8749
8750   // We need to special case some linker paths.  In the case of lld, we need to
8751   // translate 'lld' into 'lld-link', and in the case of the regular msvc
8752   // linker, we need to use a special search algorithm.
8753   llvm::SmallString<128> linkPath;
8754   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
8755   if (Linker.equals_lower("lld"))
8756     Linker = "lld-link";
8757
8758   if (Linker.equals_lower("link")) {
8759     // If we're using the MSVC linker, it's not sufficient to just use link
8760     // from the program PATH, because other environments like GnuWin32 install
8761     // their own link.exe which may come first.
8762     linkPath = FindVisualStudioExecutable(TC, "link.exe",
8763                                           C.getDriver().getClangProgramPath());
8764   } else {
8765     linkPath = Linker;
8766     llvm::sys::path::replace_extension(linkPath, "exe");
8767     linkPath = TC.GetProgramPath(linkPath.c_str());
8768   }
8769
8770   const char *Exec = Args.MakeArgString(linkPath);
8771   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8772 }
8773
8774 void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
8775                                          const InputInfo &Output,
8776                                          const InputInfoList &Inputs,
8777                                          const ArgList &Args,
8778                                          const char *LinkingOutput) const {
8779   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
8780 }
8781
8782 std::unique_ptr<Command> visualstudio::Compile::GetCommand(
8783     Compilation &C, const JobAction &JA, const InputInfo &Output,
8784     const InputInfoList &Inputs, const ArgList &Args,
8785     const char *LinkingOutput) const {
8786   ArgStringList CmdArgs;
8787   CmdArgs.push_back("/nologo");
8788   CmdArgs.push_back("/c"); // Compile only.
8789   CmdArgs.push_back("/W0"); // No warnings.
8790
8791   // The goal is to be able to invoke this tool correctly based on
8792   // any flag accepted by clang-cl.
8793
8794   // These are spelled the same way in clang and cl.exe,.
8795   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
8796   Args.AddAllArgs(CmdArgs, options::OPT_I);
8797
8798   // Optimization level.
8799   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
8800     if (A->getOption().getID() == options::OPT_O0) {
8801       CmdArgs.push_back("/Od");
8802     } else {
8803       StringRef OptLevel = A->getValue();
8804       if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
8805         A->render(Args, CmdArgs);
8806       else if (OptLevel == "3")
8807         CmdArgs.push_back("/Ox");
8808     }
8809   }
8810
8811   // Flags for which clang-cl has an alias.
8812   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
8813
8814   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8815                    /*default=*/false))
8816     CmdArgs.push_back("/GR-");
8817   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
8818                                options::OPT_fno_function_sections))
8819     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
8820                           ? "/Gy"
8821                           : "/Gy-");
8822   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
8823                                options::OPT_fno_data_sections))
8824     CmdArgs.push_back(
8825         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
8826   if (Args.hasArg(options::OPT_fsyntax_only))
8827     CmdArgs.push_back("/Zs");
8828   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
8829     CmdArgs.push_back("/Z7");
8830
8831   std::vector<std::string> Includes =
8832       Args.getAllArgValues(options::OPT_include);
8833   for (const auto &Include : Includes)
8834     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
8835
8836   // Flags that can simply be passed through.
8837   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
8838   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
8839   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
8840
8841   // The order of these flags is relevant, so pick the last one.
8842   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
8843                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
8844     A->render(Args, CmdArgs);
8845
8846
8847   // Input filename.
8848   assert(Inputs.size() == 1);
8849   const InputInfo &II = Inputs[0];
8850   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
8851   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
8852   if (II.isFilename())
8853     CmdArgs.push_back(II.getFilename());
8854   else
8855     II.getInputArg().renderAsInput(Args, CmdArgs);
8856
8857   // Output filename.
8858   assert(Output.getType() == types::TY_Object);
8859   const char *Fo = Args.MakeArgString(std::string("/Fo") +
8860                                       Output.getFilename());
8861   CmdArgs.push_back(Fo);
8862
8863   const Driver &D = getToolChain().getDriver();
8864   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
8865                                                 D.getClangProgramPath());
8866   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
8867                                     CmdArgs);
8868 }
8869
8870
8871 /// XCore Tools
8872 // We pass assemble and link construction to the xcc tool.
8873
8874 void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
8875                                        const InputInfo &Output,
8876                                        const InputInfoList &Inputs,
8877                                        const ArgList &Args,
8878                                        const char *LinkingOutput) const {
8879   claimNoWarnArgs(Args);
8880   ArgStringList CmdArgs;
8881
8882   CmdArgs.push_back("-o");
8883   CmdArgs.push_back(Output.getFilename());
8884
8885   CmdArgs.push_back("-c");
8886
8887   if (Args.hasArg(options::OPT_v))
8888     CmdArgs.push_back("-v");
8889
8890   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8891     if (!A->getOption().matches(options::OPT_g0))
8892       CmdArgs.push_back("-g");
8893
8894   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
8895                    false))
8896     CmdArgs.push_back("-fverbose-asm");
8897
8898   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
8899                        options::OPT_Xassembler);
8900
8901   for (const auto &II : Inputs)
8902     CmdArgs.push_back(II.getFilename());
8903
8904   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
8905   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8906 }
8907
8908 void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
8909                                    const InputInfo &Output,
8910                                    const InputInfoList &Inputs,
8911                                    const ArgList &Args,
8912                                    const char *LinkingOutput) const {
8913   ArgStringList CmdArgs;
8914
8915   if (Output.isFilename()) {
8916     CmdArgs.push_back("-o");
8917     CmdArgs.push_back(Output.getFilename());
8918   } else {
8919     assert(Output.isNothing() && "Invalid output.");
8920   }
8921
8922   if (Args.hasArg(options::OPT_v))
8923     CmdArgs.push_back("-v");
8924
8925   if (exceptionSettings(Args, getToolChain().getTriple()))
8926     CmdArgs.push_back("-fexceptions");
8927
8928   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8929
8930   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
8931   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8932 }
8933
8934 void CrossWindows::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
8935                                           const InputInfo &Output,
8936                                           const InputInfoList &Inputs,
8937                                           const ArgList &Args,
8938                                           const char *LinkingOutput) const {
8939   claimNoWarnArgs(Args);
8940   const auto &TC =
8941       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
8942   ArgStringList CmdArgs;
8943   const char *Exec;
8944
8945   switch (TC.getArch()) {
8946   default: llvm_unreachable("unsupported architecture");
8947   case llvm::Triple::arm:
8948   case llvm::Triple::thumb:
8949     break;
8950   case llvm::Triple::x86:
8951     CmdArgs.push_back("--32");
8952     break;
8953   case llvm::Triple::x86_64:
8954     CmdArgs.push_back("--64");
8955     break;
8956   }
8957
8958   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8959
8960   CmdArgs.push_back("-o");
8961   CmdArgs.push_back(Output.getFilename());
8962
8963   for (const auto &Input : Inputs)
8964     CmdArgs.push_back(Input.getFilename());
8965
8966   const std::string Assembler = TC.GetProgramPath("as");
8967   Exec = Args.MakeArgString(Assembler);
8968
8969   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8970 }
8971
8972 void CrossWindows::Link::ConstructJob(Compilation &C, const JobAction &JA,
8973                                       const InputInfo &Output,
8974                                       const InputInfoList &Inputs,
8975                                       const ArgList &Args,
8976                                       const char *LinkingOutput) const {
8977   const auto &TC =
8978       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
8979   const llvm::Triple &T = TC.getTriple();
8980   const Driver &D = TC.getDriver();
8981   SmallString<128> EntryPoint;
8982   ArgStringList CmdArgs;
8983   const char *Exec;
8984
8985   // Silence warning for "clang -g foo.o -o foo"
8986   Args.ClaimAllArgs(options::OPT_g_Group);
8987   // and "clang -emit-llvm foo.o -o foo"
8988   Args.ClaimAllArgs(options::OPT_emit_llvm);
8989   // and for "clang -w foo.o -o foo"
8990   Args.ClaimAllArgs(options::OPT_w);
8991   // Other warning options are already handled somewhere else.
8992
8993   if (!D.SysRoot.empty())
8994     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8995
8996   if (Args.hasArg(options::OPT_pie))
8997     CmdArgs.push_back("-pie");
8998   if (Args.hasArg(options::OPT_rdynamic))
8999     CmdArgs.push_back("-export-dynamic");
9000   if (Args.hasArg(options::OPT_s))
9001     CmdArgs.push_back("--strip-all");
9002
9003   CmdArgs.push_back("-m");
9004   switch (TC.getArch()) {
9005   default: llvm_unreachable("unsupported architecture");
9006   case llvm::Triple::arm:
9007   case llvm::Triple::thumb:
9008     // FIXME: this is incorrect for WinCE
9009     CmdArgs.push_back("thumb2pe");
9010     break;
9011   case llvm::Triple::x86:
9012     CmdArgs.push_back("i386pe");
9013     EntryPoint.append("_");
9014     break;
9015   case llvm::Triple::x86_64:
9016     CmdArgs.push_back("i386pep");
9017     break;
9018   }
9019
9020   if (Args.hasArg(options::OPT_shared)) {
9021     switch (T.getArch()) {
9022     default: llvm_unreachable("unsupported architecture");
9023     case llvm::Triple::arm:
9024     case llvm::Triple::thumb:
9025     case llvm::Triple::x86_64:
9026       EntryPoint.append("_DllMainCRTStartup");
9027       break;
9028     case llvm::Triple::x86:
9029       EntryPoint.append("_DllMainCRTStartup@12");
9030       break;
9031     }
9032
9033     CmdArgs.push_back("-shared");
9034     CmdArgs.push_back("-Bdynamic");
9035
9036     CmdArgs.push_back("--enable-auto-image-base");
9037
9038     CmdArgs.push_back("--entry");
9039     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9040   } else {
9041     EntryPoint.append("mainCRTStartup");
9042
9043     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
9044                                                        : "-Bdynamic");
9045
9046     if (!Args.hasArg(options::OPT_nostdlib) &&
9047         !Args.hasArg(options::OPT_nostartfiles)) {
9048       CmdArgs.push_back("--entry");
9049       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9050     }
9051
9052     // FIXME: handle subsystem
9053   }
9054
9055   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
9056   CmdArgs.push_back("--allow-multiple-definition");
9057
9058   CmdArgs.push_back("-o");
9059   CmdArgs.push_back(Output.getFilename());
9060
9061   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
9062     SmallString<261> ImpLib(Output.getFilename());
9063     llvm::sys::path::replace_extension(ImpLib, ".lib");
9064
9065     CmdArgs.push_back("--out-implib");
9066     CmdArgs.push_back(Args.MakeArgString(ImpLib));
9067   }
9068
9069   if (!Args.hasArg(options::OPT_nostdlib) &&
9070       !Args.hasArg(options::OPT_nostartfiles)) {
9071     const std::string CRTPath(D.SysRoot + "/usr/lib/");
9072     const char *CRTBegin;
9073
9074     CRTBegin =
9075         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
9076     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
9077   }
9078
9079   Args.AddAllArgs(CmdArgs, options::OPT_L);
9080
9081   const auto &Paths = TC.getFilePaths();
9082   for (const auto &Path : Paths)
9083     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9084
9085   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9086
9087   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9088       !Args.hasArg(options::OPT_nodefaultlibs)) {
9089     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
9090                      !Args.hasArg(options::OPT_static);
9091     if (StaticCXX)
9092       CmdArgs.push_back("-Bstatic");
9093     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9094     if (StaticCXX)
9095       CmdArgs.push_back("-Bdynamic");
9096   }
9097
9098   if (!Args.hasArg(options::OPT_nostdlib)) {
9099     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9100       // TODO handle /MT[d] /MD[d]
9101       CmdArgs.push_back("-lmsvcrt");
9102       AddRunTimeLibs(TC, D, CmdArgs, Args);
9103     }
9104   }
9105
9106   const std::string Linker = TC.GetProgramPath("ld");
9107   Exec = Args.MakeArgString(Linker);
9108
9109   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9110 }
9111
9112 void tools::SHAVE::Compile::ConstructJob(Compilation &C, const JobAction &JA,
9113                                          const InputInfo &Output,
9114                                          const InputInfoList &Inputs,
9115                                          const ArgList &Args,
9116                                          const char *LinkingOutput) const {
9117
9118   ArgStringList CmdArgs;
9119
9120   assert(Inputs.size() == 1);
9121   const InputInfo &II = Inputs[0];
9122   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9123   assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
9124
9125   // Append all -I, -iquote, -isystem paths.
9126   Args.AddAllArgs(CmdArgs, options::OPT_clang_i_Group);
9127   // These are spelled the same way in clang and moviCompile.
9128   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
9129
9130   CmdArgs.push_back("-DMYRIAD2");
9131   CmdArgs.push_back("-mcpu=myriad2");
9132   CmdArgs.push_back("-S");
9133
9134   // Any -O option passes through without translation. What about -Ofast ?
9135   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
9136     A->render(Args, CmdArgs);
9137
9138   if (Args.hasFlag(options::OPT_ffunction_sections,
9139                    options::OPT_fno_function_sections)) {
9140     CmdArgs.push_back("-ffunction-sections");
9141   }
9142   if (Args.hasArg(options::OPT_fno_inline_functions))
9143     CmdArgs.push_back("-fno-inline-functions");
9144
9145   CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
9146
9147   CmdArgs.push_back(II.getFilename());
9148   CmdArgs.push_back("-o");
9149   CmdArgs.push_back(Output.getFilename());
9150
9151   std::string Exec =
9152       Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
9153   C.addCommand(
9154       llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9155 }
9156
9157 void tools::SHAVE::Assemble::ConstructJob(Compilation &C,
9158                                           const JobAction &JA,
9159                                           const InputInfo &Output,
9160                                           const InputInfoList &Inputs,
9161                                           const ArgList &Args,
9162                                           const char *LinkingOutput) const {
9163   ArgStringList CmdArgs;
9164
9165   assert(Inputs.size() == 1);
9166   const InputInfo &II = Inputs[0];
9167   assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
9168   assert(Output.getType() == types::TY_Object);
9169
9170   CmdArgs.push_back("-no6thSlotCompression");
9171   CmdArgs.push_back("-cv:myriad2"); // Chip Version ?
9172   CmdArgs.push_back("-noSPrefixing");
9173   CmdArgs.push_back("-a"); // Mystery option.
9174   for (auto Arg : Args.filtered(options::OPT_I)) {
9175     Arg->claim();
9176     CmdArgs.push_back(
9177         Args.MakeArgString(std::string("-i:") + Arg->getValue(0)));
9178   }
9179   CmdArgs.push_back("-elf"); // Output format.
9180   CmdArgs.push_back(II.getFilename());
9181   CmdArgs.push_back(
9182       Args.MakeArgString(std::string("-o:") + Output.getFilename()));
9183
9184   std::string Exec =
9185       Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
9186   C.addCommand(
9187       llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9188 }