]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Merge ^/head r305361 through r305389.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / Tools.cpp
1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
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/CodeGen.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 #include "llvm/Support/TargetParser.h"
45
46 #ifdef LLVM_ON_UNIX
47 #include <unistd.h> // For getuid().
48 #endif
49
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
54
55 static void handleTargetFeaturesGroup(const ArgList &Args,
56                                       std::vector<const char *> &Features,
57                                       OptSpecifier Group) {
58   for (const Arg *A : Args.filtered(Group)) {
59     StringRef Name = A->getOption().getName();
60     A->claim();
61
62     // Skip over "-m".
63     assert(Name.startswith("m") && "Invalid feature name.");
64     Name = Name.substr(1);
65
66     bool IsNegative = Name.startswith("no-");
67     if (IsNegative)
68       Name = Name.substr(3);
69     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
70   }
71 }
72
73 static const char *getSparcAsmModeForCPU(StringRef Name,
74                                          const llvm::Triple &Triple) {
75   if (Triple.getArch() == llvm::Triple::sparcv9) {
76     return llvm::StringSwitch<const char *>(Name)
77           .Case("niagara", "-Av9b")
78           .Case("niagara2", "-Av9b")
79           .Case("niagara3", "-Av9d")
80           .Case("niagara4", "-Av9d")
81           .Default("-Av9");
82   } else {
83     return llvm::StringSwitch<const char *>(Name)
84           .Case("v8", "-Av8")
85           .Case("supersparc", "-Av8")
86           .Case("sparclite", "-Asparclite")
87           .Case("f934", "-Asparclite")
88           .Case("hypersparc", "-Av8")
89           .Case("sparclite86x", "-Asparclite")
90           .Case("sparclet", "-Asparclet")
91           .Case("tsc701", "-Asparclet")
92           .Case("v9", "-Av8plus")
93           .Case("ultrasparc", "-Av8plus")
94           .Case("ultrasparc3", "-Av8plus")
95           .Case("niagara", "-Av8plusb")
96           .Case("niagara2", "-Av8plusb")
97           .Case("niagara3", "-Av8plusd")
98           .Case("niagara4", "-Av8plusd")
99           .Case("leon2", "-Av8")
100           .Case("at697e", "-Av8")
101           .Case("at697f", "-Av8")
102           .Case("leon3", "-Av8")
103           .Case("ut699", "-Av8")
104           .Case("gr712rc", "-Av8")
105           .Case("leon4", "-Av8")
106           .Case("gr740", "-Av8")
107           .Default("-Av8");
108   }
109 }
110
111 /// CheckPreprocessingOptions - Perform some validation of preprocessing
112 /// arguments that is shared with gcc.
113 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
114   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
115     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
116         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
117       D.Diag(diag::err_drv_argument_only_allowed_with)
118           << A->getBaseArg().getAsString(Args)
119           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
120     }
121   }
122 }
123
124 /// CheckCodeGenerationOptions - Perform some validation of code generation
125 /// arguments that is shared with gcc.
126 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
127   // In gcc, only ARM checks this, but it seems reasonable to check universally.
128   if (Args.hasArg(options::OPT_static))
129     if (const Arg *A =
130             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
131       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
132                                                       << "-static";
133 }
134
135 // Add backslashes to escape spaces and other backslashes.
136 // This is used for the space-separated argument list specified with
137 // the -dwarf-debug-flags option.
138 static void EscapeSpacesAndBackslashes(const char *Arg,
139                                        SmallVectorImpl<char> &Res) {
140   for (; *Arg; ++Arg) {
141     switch (*Arg) {
142     default:
143       break;
144     case ' ':
145     case '\\':
146       Res.push_back('\\');
147       break;
148     }
149     Res.push_back(*Arg);
150   }
151 }
152
153 // Quote target names for inclusion in GNU Make dependency files.
154 // Only the characters '$', '#', ' ', '\t' are quoted.
155 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
156   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
157     switch (Target[i]) {
158     case ' ':
159     case '\t':
160       // Escape the preceding backslashes
161       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
162         Res.push_back('\\');
163
164       // Escape the space/tab
165       Res.push_back('\\');
166       break;
167     case '$':
168       Res.push_back('$');
169       break;
170     case '#':
171       Res.push_back('\\');
172       break;
173     default:
174       break;
175     }
176
177     Res.push_back(Target[i]);
178   }
179 }
180
181 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
182                              const char *ArgName, const char *EnvVar) {
183   const char *DirList = ::getenv(EnvVar);
184   bool CombinedArg = false;
185
186   if (!DirList)
187     return; // Nothing to do.
188
189   StringRef Name(ArgName);
190   if (Name.equals("-I") || Name.equals("-L"))
191     CombinedArg = true;
192
193   StringRef Dirs(DirList);
194   if (Dirs.empty()) // Empty string should not add '.'.
195     return;
196
197   StringRef::size_type Delim;
198   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
199     if (Delim == 0) { // Leading colon.
200       if (CombinedArg) {
201         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
202       } else {
203         CmdArgs.push_back(ArgName);
204         CmdArgs.push_back(".");
205       }
206     } else {
207       if (CombinedArg) {
208         CmdArgs.push_back(
209             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
210       } else {
211         CmdArgs.push_back(ArgName);
212         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
213       }
214     }
215     Dirs = Dirs.substr(Delim + 1);
216   }
217
218   if (Dirs.empty()) { // Trailing colon.
219     if (CombinedArg) {
220       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
221     } else {
222       CmdArgs.push_back(ArgName);
223       CmdArgs.push_back(".");
224     }
225   } else { // Add the last path.
226     if (CombinedArg) {
227       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
228     } else {
229       CmdArgs.push_back(ArgName);
230       CmdArgs.push_back(Args.MakeArgString(Dirs));
231     }
232   }
233 }
234
235 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
236                             const ArgList &Args, ArgStringList &CmdArgs) {
237   const Driver &D = TC.getDriver();
238
239   // Add extra linker input arguments which are not treated as inputs
240   // (constructed via -Xarch_).
241   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
242
243   for (const auto &II : Inputs) {
244     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
245       // Don't try to pass LLVM inputs unless we have native support.
246       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
247
248     // Add filenames immediately.
249     if (II.isFilename()) {
250       CmdArgs.push_back(II.getFilename());
251       continue;
252     }
253
254     // Otherwise, this is a linker input argument.
255     const Arg &A = II.getInputArg();
256
257     // Handle reserved library options.
258     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
259       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
260     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
261       TC.AddCCKextLibArgs(Args, CmdArgs);
262     else if (A.getOption().matches(options::OPT_z)) {
263       // Pass -z prefix for gcc linker compatibility.
264       A.claim();
265       A.render(Args, CmdArgs);
266     } else {
267       A.renderAsInput(Args, CmdArgs);
268     }
269   }
270
271   // LIBRARY_PATH - included following the user specified library paths.
272   //                and only supported on native toolchains.
273   if (!TC.isCrossCompiling())
274     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
275 }
276
277 /// \brief Determine whether Objective-C automated reference counting is
278 /// enabled.
279 static bool isObjCAutoRefCount(const ArgList &Args) {
280   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
281 }
282
283 /// \brief Determine whether we are linking the ObjC runtime.
284 static bool isObjCRuntimeLinked(const ArgList &Args) {
285   if (isObjCAutoRefCount(Args)) {
286     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
287     return true;
288   }
289   return Args.hasArg(options::OPT_fobjc_link_runtime);
290 }
291
292 static bool forwardToGCC(const Option &O) {
293   // Don't forward inputs from the original command line.  They are added from
294   // InputInfoList.
295   return O.getKind() != Option::InputClass &&
296          !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
297 }
298
299 /// Add the C++ include args of other offloading toolchains. If this is a host
300 /// job, the device toolchains are added. If this is a device job, the host
301 /// toolchains will be added.
302 static void addExtraOffloadCXXStdlibIncludeArgs(Compilation &C,
303                                                 const JobAction &JA,
304                                                 const ArgList &Args,
305                                                 ArgStringList &CmdArgs) {
306
307   if (JA.isHostOffloading(Action::OFK_Cuda))
308     C.getSingleOffloadToolChain<Action::OFK_Cuda>()
309         ->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
310   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
311     C.getSingleOffloadToolChain<Action::OFK_Host>()
312         ->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
313
314   // TODO: Add support for other programming models here.
315 }
316
317 /// Add the include args that are specific of each offloading programming model.
318 static void addExtraOffloadSpecificIncludeArgs(Compilation &C,
319                                                const JobAction &JA,
320                                                const ArgList &Args,
321                                                ArgStringList &CmdArgs) {
322
323   if (JA.isHostOffloading(Action::OFK_Cuda))
324     C.getSingleOffloadToolChain<Action::OFK_Host>()->AddCudaIncludeArgs(
325         Args, CmdArgs);
326   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
327     C.getSingleOffloadToolChain<Action::OFK_Cuda>()->AddCudaIncludeArgs(
328         Args, CmdArgs);
329
330   // TODO: Add support for other programming models here.
331 }
332
333 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
334                                     const Driver &D, const ArgList &Args,
335                                     ArgStringList &CmdArgs,
336                                     const InputInfo &Output,
337                                     const InputInfoList &Inputs) const {
338   Arg *A;
339   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
340
341   CheckPreprocessingOptions(D, Args);
342
343   Args.AddLastArg(CmdArgs, options::OPT_C);
344   Args.AddLastArg(CmdArgs, options::OPT_CC);
345
346   // Handle dependency file generation.
347   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
348       (A = Args.getLastArg(options::OPT_MD)) ||
349       (A = Args.getLastArg(options::OPT_MMD))) {
350     // Determine the output location.
351     const char *DepFile;
352     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
353       DepFile = MF->getValue();
354       C.addFailureResultFile(DepFile, &JA);
355     } else if (Output.getType() == types::TY_Dependencies) {
356       DepFile = Output.getFilename();
357     } else if (A->getOption().matches(options::OPT_M) ||
358                A->getOption().matches(options::OPT_MM)) {
359       DepFile = "-";
360     } else {
361       DepFile = getDependencyFileName(Args, Inputs);
362       C.addFailureResultFile(DepFile, &JA);
363     }
364     CmdArgs.push_back("-dependency-file");
365     CmdArgs.push_back(DepFile);
366
367     // Add a default target if one wasn't specified.
368     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
369       const char *DepTarget;
370
371       // If user provided -o, that is the dependency target, except
372       // when we are only generating a dependency file.
373       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
374       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
375         DepTarget = OutputOpt->getValue();
376       } else {
377         // Otherwise derive from the base input.
378         //
379         // FIXME: This should use the computed output file location.
380         SmallString<128> P(Inputs[0].getBaseInput());
381         llvm::sys::path::replace_extension(P, "o");
382         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
383       }
384
385       CmdArgs.push_back("-MT");
386       SmallString<128> Quoted;
387       QuoteTarget(DepTarget, Quoted);
388       CmdArgs.push_back(Args.MakeArgString(Quoted));
389     }
390
391     if (A->getOption().matches(options::OPT_M) ||
392         A->getOption().matches(options::OPT_MD))
393       CmdArgs.push_back("-sys-header-deps");
394     if ((isa<PrecompileJobAction>(JA) &&
395          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
396         Args.hasArg(options::OPT_fmodule_file_deps))
397       CmdArgs.push_back("-module-file-deps");
398   }
399
400   if (Args.hasArg(options::OPT_MG)) {
401     if (!A || A->getOption().matches(options::OPT_MD) ||
402         A->getOption().matches(options::OPT_MMD))
403       D.Diag(diag::err_drv_mg_requires_m_or_mm);
404     CmdArgs.push_back("-MG");
405   }
406
407   Args.AddLastArg(CmdArgs, options::OPT_MP);
408   Args.AddLastArg(CmdArgs, options::OPT_MV);
409
410   // Convert all -MQ <target> args to -MT <quoted target>
411   for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
412     A->claim();
413
414     if (A->getOption().matches(options::OPT_MQ)) {
415       CmdArgs.push_back("-MT");
416       SmallString<128> Quoted;
417       QuoteTarget(A->getValue(), Quoted);
418       CmdArgs.push_back(Args.MakeArgString(Quoted));
419
420       // -MT flag - no change
421     } else {
422       A->render(Args, CmdArgs);
423     }
424   }
425
426   // Add -i* options, and automatically translate to
427   // -include-pch/-include-pth for transparent PCH support. It's
428   // wonky, but we include looking for .gch so we can support seamless
429   // replacement into a build system already set up to be generating
430   // .gch files.
431   int YcIndex = -1, YuIndex = -1;
432   {
433     int AI = -1;
434     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
435     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
436     for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
437       // Walk the whole i_Group and skip non "-include" flags so that the index
438       // here matches the index in the next loop below.
439       ++AI;
440       if (!A->getOption().matches(options::OPT_include))
441         continue;
442       if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
443         YcIndex = AI;
444       if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
445         YuIndex = AI;
446     }
447   }
448   if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
449     Driver::InputList Inputs;
450     D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
451     assert(Inputs.size() == 1 && "Need one input when building pch");
452     CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
453                                          Inputs[0].second->getValue()));
454   }
455
456   bool RenderedImplicitInclude = false;
457   int AI = -1;
458   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
459     ++AI;
460
461     if (getToolChain().getDriver().IsCLMode() &&
462         A->getOption().matches(options::OPT_include)) {
463       // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
464       // include is compiled into foo.h, and everything after goes into
465       // the .obj file. /Yufoo.h means that all includes prior to and including
466       // foo.h are completely skipped and replaced with a use of the pch file
467       // for foo.h.  (Each flag can have at most one value, multiple /Yc flags
468       // just mean that the last one wins.)  If /Yc and /Yu are both present
469       // and refer to the same file, /Yc wins.
470       // Note that OPT__SLASH_FI gets mapped to OPT_include.
471       // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
472       // cl.exe seems to support both flags with different values, but that
473       // seems strange (which flag does /Fp now refer to?), so don't implement
474       // that until someone needs it.
475       int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
476       if (PchIndex != -1) {
477         if (isa<PrecompileJobAction>(JA)) {
478           // When building the pch, skip all includes after the pch.
479           assert(YcIndex != -1 && PchIndex == YcIndex);
480           if (AI >= YcIndex)
481             continue;
482         } else {
483           // When using the pch, skip all includes prior to the pch.
484           if (AI < PchIndex) {
485             A->claim();
486             continue;
487           }
488           if (AI == PchIndex) {
489             A->claim();
490             CmdArgs.push_back("-include-pch");
491             CmdArgs.push_back(
492                 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
493             continue;
494           }
495         }
496       }
497     } else if (A->getOption().matches(options::OPT_include)) {
498       // Handling of gcc-style gch precompiled headers.
499       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
500       RenderedImplicitInclude = true;
501
502       // Use PCH if the user requested it.
503       bool UsePCH = D.CCCUsePCH;
504
505       bool FoundPTH = false;
506       bool FoundPCH = false;
507       SmallString<128> P(A->getValue());
508       // We want the files to have a name like foo.h.pch. Add a dummy extension
509       // so that replace_extension does the right thing.
510       P += ".dummy";
511       if (UsePCH) {
512         llvm::sys::path::replace_extension(P, "pch");
513         if (llvm::sys::fs::exists(P))
514           FoundPCH = true;
515       }
516
517       if (!FoundPCH) {
518         llvm::sys::path::replace_extension(P, "pth");
519         if (llvm::sys::fs::exists(P))
520           FoundPTH = true;
521       }
522
523       if (!FoundPCH && !FoundPTH) {
524         llvm::sys::path::replace_extension(P, "gch");
525         if (llvm::sys::fs::exists(P)) {
526           FoundPCH = UsePCH;
527           FoundPTH = !UsePCH;
528         }
529       }
530
531       if (FoundPCH || FoundPTH) {
532         if (IsFirstImplicitInclude) {
533           A->claim();
534           if (UsePCH)
535             CmdArgs.push_back("-include-pch");
536           else
537             CmdArgs.push_back("-include-pth");
538           CmdArgs.push_back(Args.MakeArgString(P));
539           continue;
540         } else {
541           // Ignore the PCH if not first on command line and emit warning.
542           D.Diag(diag::warn_drv_pch_not_first_include) << P
543                                                        << A->getAsString(Args);
544         }
545       }
546     } else if (A->getOption().matches(options::OPT_isystem_after)) {
547       // Handling of paths which must come late.  These entries are handled by
548       // the toolchain itself after the resource dir is inserted in the right
549       // search order.
550       // Do not claim the argument so that the use of the argument does not
551       // silently go unnoticed on toolchains which do not honour the option.
552       continue;
553     }
554
555     // Not translated, render as usual.
556     A->claim();
557     A->render(Args, CmdArgs);
558   }
559
560   Args.AddAllArgs(CmdArgs,
561                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
562                    options::OPT_F, options::OPT_index_header_map});
563
564   // Add -Wp, and -Xpreprocessor if using the preprocessor.
565
566   // FIXME: There is a very unfortunate problem here, some troubled
567   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
568   // really support that we would have to parse and then translate
569   // those options. :(
570   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
571                        options::OPT_Xpreprocessor);
572
573   // -I- is a deprecated GCC feature, reject it.
574   if (Arg *A = Args.getLastArg(options::OPT_I_))
575     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
576
577   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
578   // -isysroot to the CC1 invocation.
579   StringRef sysroot = C.getSysRoot();
580   if (sysroot != "") {
581     if (!Args.hasArg(options::OPT_isysroot)) {
582       CmdArgs.push_back("-isysroot");
583       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
584     }
585   }
586
587   // Parse additional include paths from environment variables.
588   // FIXME: We should probably sink the logic for handling these from the
589   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
590   // CPATH - included following the user specified includes (but prior to
591   // builtin and standard includes).
592   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
593   // C_INCLUDE_PATH - system includes enabled when compiling C.
594   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
595   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
596   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
597   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
598   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
599   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
600   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
601
602   // While adding the include arguments, we also attempt to retrieve the
603   // arguments of related offloading toolchains or arguments that are specific
604   // of an offloading programming model.
605
606   // Add C++ include arguments, if needed.
607   if (types::isCXX(Inputs[0].getType())) {
608     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
609     addExtraOffloadCXXStdlibIncludeArgs(C, JA, Args, CmdArgs);
610   }
611
612   // Add system include arguments for all targets but IAMCU.
613   if (!IsIAMCU) {
614     getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
615     addExtraOffloadCXXStdlibIncludeArgs(C, JA, Args, CmdArgs);
616   } else {
617     // For IAMCU add special include arguments.
618     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
619   }
620
621   // Add offload include arguments, if needed.
622   addExtraOffloadSpecificIncludeArgs(C, JA, Args, CmdArgs);
623 }
624
625 // FIXME: Move to target hook.
626 static bool isSignedCharDefault(const llvm::Triple &Triple) {
627   switch (Triple.getArch()) {
628   default:
629     return true;
630
631   case llvm::Triple::aarch64:
632   case llvm::Triple::aarch64_be:
633   case llvm::Triple::arm:
634   case llvm::Triple::armeb:
635   case llvm::Triple::thumb:
636   case llvm::Triple::thumbeb:
637     if (Triple.isOSDarwin() || Triple.isOSWindows())
638       return true;
639     return false;
640
641   case llvm::Triple::ppc:
642   case llvm::Triple::ppc64:
643     if (Triple.isOSDarwin())
644       return true;
645     return false;
646
647   case llvm::Triple::hexagon:
648   case llvm::Triple::ppc64le:
649   case llvm::Triple::systemz:
650   case llvm::Triple::xcore:
651     return false;
652   }
653 }
654
655 static bool isNoCommonDefault(const llvm::Triple &Triple) {
656   switch (Triple.getArch()) {
657   default:
658     return false;
659
660   case llvm::Triple::xcore:
661   case llvm::Triple::wasm32:
662   case llvm::Triple::wasm64:
663     return true;
664   }
665 }
666
667 // ARM tools start.
668
669 // Get SubArch (vN).
670 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
671   llvm::StringRef Arch = Triple.getArchName();
672   return llvm::ARM::parseArchVersion(Arch);
673 }
674
675 // True if M-profile.
676 static bool isARMMProfile(const llvm::Triple &Triple) {
677   llvm::StringRef Arch = Triple.getArchName();
678   unsigned Profile = llvm::ARM::parseArchProfile(Arch);
679   return Profile == llvm::ARM::PK_M;
680 }
681
682 // Get Arch/CPU from args.
683 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
684                                   llvm::StringRef &CPU, bool FromAs = false) {
685   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
686     CPU = A->getValue();
687   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
688     Arch = A->getValue();
689   if (!FromAs)
690     return;
691
692   for (const Arg *A :
693        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
694     StringRef Value = A->getValue();
695     if (Value.startswith("-mcpu="))
696       CPU = Value.substr(6);
697     if (Value.startswith("-march="))
698       Arch = Value.substr(7);
699   }
700 }
701
702 // Handle -mhwdiv=.
703 // FIXME: Use ARMTargetParser.
704 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
705                                 const ArgList &Args, StringRef HWDiv,
706                                 std::vector<const char *> &Features) {
707   unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
708   if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
709     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
710 }
711
712 // Handle -mfpu=.
713 static void getARMFPUFeatures(const Driver &D, const Arg *A,
714                               const ArgList &Args, StringRef FPU,
715                               std::vector<const char *> &Features) {
716   unsigned FPUID = llvm::ARM::parseFPU(FPU);
717   if (!llvm::ARM::getFPUFeatures(FPUID, Features))
718     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
719 }
720
721 // Decode ARM features from string like +[no]featureA+[no]featureB+...
722 static bool DecodeARMFeatures(const Driver &D, StringRef text,
723                               std::vector<const char *> &Features) {
724   SmallVector<StringRef, 8> Split;
725   text.split(Split, StringRef("+"), -1, false);
726
727   for (StringRef Feature : Split) {
728     const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
729     if (FeatureName)
730       Features.push_back(FeatureName);
731     else
732       return false;
733   }
734   return true;
735 }
736
737 // Check if -march is valid by checking if it can be canonicalised and parsed.
738 // getARMArch is used here instead of just checking the -march value in order
739 // to handle -march=native correctly.
740 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
741                              llvm::StringRef ArchName,
742                              std::vector<const char *> &Features,
743                              const llvm::Triple &Triple) {
744   std::pair<StringRef, StringRef> Split = ArchName.split("+");
745
746   std::string MArch = arm::getARMArch(ArchName, Triple);
747   if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
748       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
749     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
750 }
751
752 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
753 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
754                             llvm::StringRef CPUName, llvm::StringRef ArchName,
755                             std::vector<const char *> &Features,
756                             const llvm::Triple &Triple) {
757   std::pair<StringRef, StringRef> Split = CPUName.split("+");
758
759   std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
760   if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
761       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
762     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
763 }
764
765 static bool useAAPCSForMachO(const llvm::Triple &T) {
766   // The backend is hardwired to assume AAPCS for M-class processors, ensure
767   // the frontend matches that.
768   return T.getEnvironment() == llvm::Triple::EABI ||
769          T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
770 }
771
772 // Select the float ABI as determined by -msoft-float, -mhard-float, and
773 // -mfloat-abi=.
774 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
775   const Driver &D = TC.getDriver();
776   const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
777   auto SubArch = getARMSubArchVersionNumber(Triple);
778   arm::FloatABI ABI = FloatABI::Invalid;
779   if (Arg *A =
780           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
781                           options::OPT_mfloat_abi_EQ)) {
782     if (A->getOption().matches(options::OPT_msoft_float)) {
783       ABI = FloatABI::Soft;
784     } else if (A->getOption().matches(options::OPT_mhard_float)) {
785       ABI = FloatABI::Hard;
786     } else {
787       ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
788                 .Case("soft", FloatABI::Soft)
789                 .Case("softfp", FloatABI::SoftFP)
790                 .Case("hard", FloatABI::Hard)
791                 .Default(FloatABI::Invalid);
792       if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
793         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
794         ABI = FloatABI::Soft;
795       }
796     }
797
798     // It is incorrect to select hard float ABI on MachO platforms if the ABI is
799     // "apcs-gnu".
800     if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
801         ABI == FloatABI::Hard) {
802       D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
803                                                        << Triple.getArchName();
804     }
805   }
806
807   // If unspecified, choose the default based on the platform.
808   if (ABI == FloatABI::Invalid) {
809     switch (Triple.getOS()) {
810     case llvm::Triple::Darwin:
811     case llvm::Triple::MacOSX:
812     case llvm::Triple::IOS:
813     case llvm::Triple::TvOS: {
814       // Darwin defaults to "softfp" for v6 and v7.
815       ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
816       ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
817       break;
818     }
819     case llvm::Triple::WatchOS:
820       ABI = FloatABI::Hard;
821       break;
822
823     // FIXME: this is invalid for WindowsCE
824     case llvm::Triple::Win32:
825       ABI = FloatABI::Hard;
826       break;
827
828     case llvm::Triple::FreeBSD:
829       switch (Triple.getEnvironment()) {
830       case llvm::Triple::GNUEABIHF:
831         ABI = FloatABI::Hard;
832         break;
833       default:
834         // FreeBSD defaults to soft float
835         ABI = FloatABI::Soft;
836         break;
837       }
838       break;
839
840     default:
841       switch (Triple.getEnvironment()) {
842       case llvm::Triple::GNUEABIHF:
843       case llvm::Triple::MuslEABIHF:
844       case llvm::Triple::EABIHF:
845         ABI = FloatABI::Hard;
846         break;
847       case llvm::Triple::GNUEABI:
848       case llvm::Triple::MuslEABI:
849       case llvm::Triple::EABI:
850         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
851         ABI = FloatABI::SoftFP;
852         break;
853       case llvm::Triple::Android:
854         ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
855         break;
856       default:
857         // Assume "soft", but warn the user we are guessing.
858         if (Triple.isOSBinFormatMachO() &&
859             Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
860           ABI = FloatABI::Hard;
861         else
862           ABI = FloatABI::Soft;
863
864         if (Triple.getOS() != llvm::Triple::UnknownOS ||
865             !Triple.isOSBinFormatMachO())
866           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
867         break;
868       }
869     }
870   }
871
872   assert(ABI != FloatABI::Invalid && "must select an ABI");
873   return ABI;
874 }
875
876 static void getARMTargetFeatures(const ToolChain &TC,
877                                  const llvm::Triple &Triple,
878                                  const ArgList &Args,
879                                  std::vector<const char *> &Features,
880                                  bool ForAS) {
881   const Driver &D = TC.getDriver();
882
883   bool KernelOrKext =
884       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
885   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
886   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
887   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
888
889   if (!ForAS) {
890     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
891     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
892     // stripped out by the ARM target. We should probably pass this a new
893     // -target-option, which is handled by the -cc1/-cc1as invocation.
894     //
895     // FIXME2:  For consistency, it would be ideal if we set up the target
896     // machine state the same when using the frontend or the assembler. We don't
897     // currently do that for the assembler, we pass the options directly to the
898     // backend and never even instantiate the frontend TargetInfo. If we did,
899     // and used its handleTargetFeatures hook, then we could ensure the
900     // assembler and the frontend behave the same.
901
902     // Use software floating point operations?
903     if (ABI == arm::FloatABI::Soft)
904       Features.push_back("+soft-float");
905
906     // Use software floating point argument passing?
907     if (ABI != arm::FloatABI::Hard)
908       Features.push_back("+soft-float-abi");
909   } else {
910     // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
911     // to the assembler correctly.
912     for (const Arg *A :
913          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
914       StringRef Value = A->getValue();
915       if (Value.startswith("-mfpu=")) {
916         WaFPU = A;
917       } else if (Value.startswith("-mcpu=")) {
918         WaCPU = A;
919       } else if (Value.startswith("-mhwdiv=")) {
920         WaHDiv = A;
921       } else if (Value.startswith("-march=")) {
922         WaArch = A;
923       }
924     }
925   }
926
927   // Check -march. ClangAs gives preference to -Wa,-march=.
928   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
929   StringRef ArchName;
930   if (WaArch) {
931     if (ArchArg)
932       D.Diag(clang::diag::warn_drv_unused_argument)
933           << ArchArg->getAsString(Args);
934     ArchName = StringRef(WaArch->getValue()).substr(7);
935     checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
936     // FIXME: Set Arch.
937     D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
938   } else if (ArchArg) {
939     ArchName = ArchArg->getValue();
940     checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
941   }
942
943   // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
944   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
945   StringRef CPUName;
946   if (WaCPU) {
947     if (CPUArg)
948       D.Diag(clang::diag::warn_drv_unused_argument)
949           << CPUArg->getAsString(Args);
950     CPUName = StringRef(WaCPU->getValue()).substr(6);
951     checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
952   } else if (CPUArg) {
953     CPUName = CPUArg->getValue();
954     checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
955   }
956
957   // Add CPU features for generic CPUs
958   if (CPUName == "native") {
959     llvm::StringMap<bool> HostFeatures;
960     if (llvm::sys::getHostCPUFeatures(HostFeatures))
961       for (auto &F : HostFeatures)
962         Features.push_back(
963             Args.MakeArgString((F.second ? "+" : "-") + F.first()));
964   }
965
966   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
967   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
968   if (WaFPU) {
969     if (FPUArg)
970       D.Diag(clang::diag::warn_drv_unused_argument)
971           << FPUArg->getAsString(Args);
972     getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
973                       Features);
974   } else if (FPUArg) {
975     getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
976   }
977
978   // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
979   const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
980   if (WaHDiv) {
981     if (HDivArg)
982       D.Diag(clang::diag::warn_drv_unused_argument)
983           << HDivArg->getAsString(Args);
984     getARMHWDivFeatures(D, WaHDiv, Args,
985                         StringRef(WaHDiv->getValue()).substr(8), Features);
986   } else if (HDivArg)
987     getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
988
989   // Setting -msoft-float effectively disables NEON because of the GCC
990   // implementation, although the same isn't true of VFP or VFP3.
991   if (ABI == arm::FloatABI::Soft) {
992     Features.push_back("-neon");
993     // Also need to explicitly disable features which imply NEON.
994     Features.push_back("-crypto");
995   }
996
997   // En/disable crc code generation.
998   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
999     if (A->getOption().matches(options::OPT_mcrc))
1000       Features.push_back("+crc");
1001     else
1002       Features.push_back("-crc");
1003   }
1004
1005   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
1006   // neither options are specified, see if we are compiling for kernel/kext and
1007   // decide whether to pass "+long-calls" based on the OS and its version.
1008   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
1009                                options::OPT_mno_long_calls)) {
1010     if (A->getOption().matches(options::OPT_mlong_calls))
1011       Features.push_back("+long-calls");
1012   } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
1013              !Triple.isWatchOS()) {
1014       Features.push_back("+long-calls");
1015   }
1016
1017   // Kernel code has more strict alignment requirements.
1018   if (KernelOrKext)
1019     Features.push_back("+strict-align");
1020   else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
1021                                     options::OPT_munaligned_access)) {
1022     if (A->getOption().matches(options::OPT_munaligned_access)) {
1023       // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
1024       if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1025         D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
1026       // v8M Baseline follows on from v6M, so doesn't support unaligned memory
1027       // access either.
1028       else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
1029         D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
1030     } else
1031       Features.push_back("+strict-align");
1032   } else {
1033     // Assume pre-ARMv6 doesn't support unaligned accesses.
1034     //
1035     // ARMv6 may or may not support unaligned accesses depending on the
1036     // SCTLR.U bit, which is architecture-specific. We assume ARMv6
1037     // Darwin and NetBSD targets support unaligned accesses, and others don't.
1038     //
1039     // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
1040     // which raises an alignment fault on unaligned accesses. Linux
1041     // defaults this bit to 0 and handles it as a system-wide (not
1042     // per-process) setting. It is therefore safe to assume that ARMv7+
1043     // Linux targets support unaligned accesses. The same goes for NaCl.
1044     //
1045     // The above behavior is consistent with GCC.
1046     int VersionNum = getARMSubArchVersionNumber(Triple);
1047     if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
1048       if (VersionNum < 6 ||
1049           Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1050         Features.push_back("+strict-align");
1051     } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
1052       if (VersionNum < 7)
1053         Features.push_back("+strict-align");
1054     } else
1055       Features.push_back("+strict-align");
1056   }
1057
1058   // llvm does not support reserving registers in general. There is support
1059   // for reserving r9 on ARM though (defined as a platform-specific register
1060   // in ARM EABI).
1061   if (Args.hasArg(options::OPT_ffixed_r9))
1062     Features.push_back("+reserve-r9");
1063
1064   // The kext linker doesn't know how to deal with movw/movt.
1065   if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
1066     Features.push_back("+no-movt");
1067 }
1068
1069 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1070                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1071   // Select the ABI to use.
1072   // FIXME: Support -meabi.
1073   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1074   const char *ABIName = nullptr;
1075   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1076     ABIName = A->getValue();
1077   } else if (Triple.isOSBinFormatMachO()) {
1078     if (useAAPCSForMachO(Triple)) {
1079       ABIName = "aapcs";
1080     } else if (Triple.isWatchABI()) {
1081       ABIName = "aapcs16";
1082     } else {
1083       ABIName = "apcs-gnu";
1084     }
1085   } else if (Triple.isOSWindows()) {
1086     // FIXME: this is invalid for WindowsCE
1087     ABIName = "aapcs";
1088   } else {
1089     // Select the default based on the platform.
1090     switch (Triple.getEnvironment()) {
1091     case llvm::Triple::Android:
1092     case llvm::Triple::GNUEABI:
1093     case llvm::Triple::GNUEABIHF:
1094     case llvm::Triple::MuslEABI:
1095     case llvm::Triple::MuslEABIHF:
1096       ABIName = "aapcs-linux";
1097       break;
1098     case llvm::Triple::EABIHF:
1099     case llvm::Triple::EABI:
1100       ABIName = "aapcs";
1101       break;
1102     default:
1103       if (Triple.getOS() == llvm::Triple::NetBSD)
1104         ABIName = "apcs-gnu";
1105       else
1106         ABIName = "aapcs";
1107       break;
1108     }
1109   }
1110   CmdArgs.push_back("-target-abi");
1111   CmdArgs.push_back(ABIName);
1112
1113   // Determine floating point ABI from the options & target defaults.
1114   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1115   if (ABI == arm::FloatABI::Soft) {
1116     // Floating point operations and argument passing are soft.
1117     // FIXME: This changes CPP defines, we need -target-soft-float.
1118     CmdArgs.push_back("-msoft-float");
1119     CmdArgs.push_back("-mfloat-abi");
1120     CmdArgs.push_back("soft");
1121   } else if (ABI == arm::FloatABI::SoftFP) {
1122     // Floating point operations are hard, but argument passing is soft.
1123     CmdArgs.push_back("-mfloat-abi");
1124     CmdArgs.push_back("soft");
1125   } else {
1126     // Floating point operations and argument passing are hard.
1127     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1128     CmdArgs.push_back("-mfloat-abi");
1129     CmdArgs.push_back("hard");
1130   }
1131
1132   // Forward the -mglobal-merge option for explicit control over the pass.
1133   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1134                                options::OPT_mno_global_merge)) {
1135     CmdArgs.push_back("-backend-option");
1136     if (A->getOption().matches(options::OPT_mno_global_merge))
1137       CmdArgs.push_back("-arm-global-merge=false");
1138     else
1139       CmdArgs.push_back("-arm-global-merge=true");
1140   }
1141
1142   if (!Args.hasFlag(options::OPT_mimplicit_float,
1143                     options::OPT_mno_implicit_float, true))
1144     CmdArgs.push_back("-no-implicit-float");
1145 }
1146 // ARM tools end.
1147
1148 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1149 /// targeting.
1150 static std::string getAArch64TargetCPU(const ArgList &Args) {
1151   Arg *A;
1152   std::string CPU;
1153   // If we have -mtune or -mcpu, use that.
1154   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1155     CPU = StringRef(A->getValue()).lower();
1156   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1157     StringRef Mcpu = A->getValue();
1158     CPU = Mcpu.split("+").first.lower();
1159   }
1160
1161   // Handle CPU name is 'native'.
1162   if (CPU == "native")
1163     return llvm::sys::getHostCPUName();
1164   else if (CPU.size())
1165     return CPU;
1166
1167   // Make sure we pick "cyclone" if -arch is used.
1168   // FIXME: Should this be picked by checking the target triple instead?
1169   if (Args.getLastArg(options::OPT_arch))
1170     return "cyclone";
1171
1172   return "generic";
1173 }
1174
1175 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1176                                  ArgStringList &CmdArgs) const {
1177   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1178   llvm::Triple Triple(TripleStr);
1179
1180   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1181       Args.hasArg(options::OPT_mkernel) ||
1182       Args.hasArg(options::OPT_fapple_kext))
1183     CmdArgs.push_back("-disable-red-zone");
1184
1185   if (!Args.hasFlag(options::OPT_mimplicit_float,
1186                     options::OPT_mno_implicit_float, true))
1187     CmdArgs.push_back("-no-implicit-float");
1188
1189   const char *ABIName = nullptr;
1190   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1191     ABIName = A->getValue();
1192   else if (Triple.isOSDarwin())
1193     ABIName = "darwinpcs";
1194   else
1195     ABIName = "aapcs";
1196
1197   CmdArgs.push_back("-target-abi");
1198   CmdArgs.push_back(ABIName);
1199
1200   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1201                                options::OPT_mno_fix_cortex_a53_835769)) {
1202     CmdArgs.push_back("-backend-option");
1203     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1204       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1205     else
1206       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1207   } else if (Triple.isAndroid()) {
1208     // Enabled A53 errata (835769) workaround by default on android
1209     CmdArgs.push_back("-backend-option");
1210     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1211   }
1212
1213   // Forward the -mglobal-merge option for explicit control over the pass.
1214   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1215                                options::OPT_mno_global_merge)) {
1216     CmdArgs.push_back("-backend-option");
1217     if (A->getOption().matches(options::OPT_mno_global_merge))
1218       CmdArgs.push_back("-aarch64-global-merge=false");
1219     else
1220       CmdArgs.push_back("-aarch64-global-merge=true");
1221   }
1222 }
1223
1224 // Get CPU and ABI names. They are not independent
1225 // so we have to calculate them together.
1226 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1227                             StringRef &CPUName, StringRef &ABIName) {
1228   const char *DefMips32CPU = "mips32r2";
1229   const char *DefMips64CPU = "mips64r2";
1230
1231   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1232   // default for mips64(el)?-img-linux-gnu.
1233   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1234       Triple.getEnvironment() == llvm::Triple::GNU) {
1235     DefMips32CPU = "mips32r6";
1236     DefMips64CPU = "mips64r6";
1237   }
1238
1239   // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1240   if (Triple.isAndroid()) {
1241     DefMips32CPU = "mips32";
1242     DefMips64CPU = "mips64r6";
1243   }
1244
1245   // MIPS3 is the default for mips64*-unknown-openbsd.
1246   if (Triple.getOS() == llvm::Triple::OpenBSD)
1247     DefMips64CPU = "mips3";
1248
1249   if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1250     CPUName = A->getValue();
1251
1252   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1253     ABIName = A->getValue();
1254     // Convert a GNU style Mips ABI name to the name
1255     // accepted by LLVM Mips backend.
1256     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1257                   .Case("32", "o32")
1258                   .Case("64", "n64")
1259                   .Default(ABIName);
1260   }
1261
1262   // Setup default CPU and ABI names.
1263   if (CPUName.empty() && ABIName.empty()) {
1264     switch (Triple.getArch()) {
1265     default:
1266       llvm_unreachable("Unexpected triple arch name");
1267     case llvm::Triple::mips:
1268     case llvm::Triple::mipsel:
1269       CPUName = DefMips32CPU;
1270       break;
1271     case llvm::Triple::mips64:
1272     case llvm::Triple::mips64el:
1273       CPUName = DefMips64CPU;
1274       break;
1275     }
1276   }
1277
1278   if (ABIName.empty() &&
1279       (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
1280        Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
1281     ABIName = llvm::StringSwitch<const char *>(CPUName)
1282                   .Case("mips1", "o32")
1283                   .Case("mips2", "o32")
1284                   .Case("mips3", "n64")
1285                   .Case("mips4", "n64")
1286                   .Case("mips5", "n64")
1287                   .Case("mips32", "o32")
1288                   .Case("mips32r2", "o32")
1289                   .Case("mips32r3", "o32")
1290                   .Case("mips32r5", "o32")
1291                   .Case("mips32r6", "o32")
1292                   .Case("mips64", "n64")
1293                   .Case("mips64r2", "n64")
1294                   .Case("mips64r3", "n64")
1295                   .Case("mips64r5", "n64")
1296                   .Case("mips64r6", "n64")
1297                   .Case("octeon", "n64")
1298                   .Case("p5600", "o32")
1299                   .Default("");
1300   }
1301
1302   if (ABIName.empty()) {
1303     // Deduce ABI name from the target triple.
1304     if (Triple.getArch() == llvm::Triple::mips ||
1305         Triple.getArch() == llvm::Triple::mipsel)
1306       ABIName = "o32";
1307     else
1308       ABIName = "n64";
1309   }
1310
1311   if (CPUName.empty()) {
1312     // Deduce CPU name from ABI name.
1313     CPUName = llvm::StringSwitch<const char *>(ABIName)
1314                   .Case("o32", DefMips32CPU)
1315                   .Cases("n32", "n64", DefMips64CPU)
1316                   .Default("");
1317   }
1318
1319   // FIXME: Warn on inconsistent use of -march and -mabi.
1320 }
1321
1322 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1323                                       const llvm::Triple &Triple) {
1324   StringRef CPUName, ABIName;
1325   tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1326   return llvm::StringSwitch<std::string>(ABIName)
1327       .Case("o32", "")
1328       .Case("n32", "32")
1329       .Case("n64", "64");
1330 }
1331
1332 // Convert ABI name to the GNU tools acceptable variant.
1333 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1334   return llvm::StringSwitch<llvm::StringRef>(ABI)
1335       .Case("o32", "32")
1336       .Case("n64", "64")
1337       .Default(ABI);
1338 }
1339
1340 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1341 // and -mfloat-abi=.
1342 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1343   mips::FloatABI ABI = mips::FloatABI::Invalid;
1344   if (Arg *A =
1345           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1346                           options::OPT_mfloat_abi_EQ)) {
1347     if (A->getOption().matches(options::OPT_msoft_float))
1348       ABI = mips::FloatABI::Soft;
1349     else if (A->getOption().matches(options::OPT_mhard_float))
1350       ABI = mips::FloatABI::Hard;
1351     else {
1352       ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1353                 .Case("soft", mips::FloatABI::Soft)
1354                 .Case("hard", mips::FloatABI::Hard)
1355                 .Default(mips::FloatABI::Invalid);
1356       if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1357         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1358         ABI = mips::FloatABI::Hard;
1359       }
1360     }
1361   }
1362
1363   // If unspecified, choose the default based on the platform.
1364   if (ABI == mips::FloatABI::Invalid) {
1365     // Assume "hard", because it's a default value used by gcc.
1366     // When we start to recognize specific target MIPS processors,
1367     // we will be able to select the default more correctly.
1368     ABI = mips::FloatABI::Hard;
1369   }
1370
1371   assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1372   return ABI;
1373 }
1374
1375 static void AddTargetFeature(const ArgList &Args,
1376                              std::vector<const char *> &Features,
1377                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1378                              StringRef FeatureName) {
1379   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1380     if (A->getOption().matches(OnOpt))
1381       Features.push_back(Args.MakeArgString("+" + FeatureName));
1382     else
1383       Features.push_back(Args.MakeArgString("-" + FeatureName));
1384   }
1385 }
1386
1387 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1388                                   const ArgList &Args,
1389                                   std::vector<const char *> &Features) {
1390   StringRef CPUName;
1391   StringRef ABIName;
1392   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1393   ABIName = getGnuCompatibleMipsABIName(ABIName);
1394
1395   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1396                    options::OPT_mabicalls, "noabicalls");
1397
1398   mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1399   if (FloatABI == mips::FloatABI::Soft) {
1400     // FIXME: Note, this is a hack. We need to pass the selected float
1401     // mode to the MipsTargetInfoBase to define appropriate macros there.
1402     // Now it is the only method.
1403     Features.push_back("+soft-float");
1404   }
1405
1406   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1407     StringRef Val = StringRef(A->getValue());
1408     if (Val == "2008") {
1409       if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1410         Features.push_back("+nan2008");
1411       else {
1412         Features.push_back("-nan2008");
1413         D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1414       }
1415     } else if (Val == "legacy") {
1416       if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1417         Features.push_back("-nan2008");
1418       else {
1419         Features.push_back("+nan2008");
1420         D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1421       }
1422     } else
1423       D.Diag(diag::err_drv_unsupported_option_argument)
1424           << A->getOption().getName() << Val;
1425   }
1426
1427   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1428                    options::OPT_mdouble_float, "single-float");
1429   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1430                    "mips16");
1431   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1432                    options::OPT_mno_micromips, "micromips");
1433   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1434                    "dsp");
1435   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1436                    "dspr2");
1437   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1438                    "msa");
1439
1440   // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
1441   // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
1442   // nooddspreg.
1443   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1444                                options::OPT_mfp64)) {
1445     if (A->getOption().matches(options::OPT_mfp32))
1446       Features.push_back(Args.MakeArgString("-fp64"));
1447     else if (A->getOption().matches(options::OPT_mfpxx)) {
1448       Features.push_back(Args.MakeArgString("+fpxx"));
1449       Features.push_back(Args.MakeArgString("+nooddspreg"));
1450     } else
1451       Features.push_back(Args.MakeArgString("+fp64"));
1452   } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1453     Features.push_back(Args.MakeArgString("+fpxx"));
1454     Features.push_back(Args.MakeArgString("+nooddspreg"));
1455   } else if (mips::isFP64ADefault(Triple, CPUName)) {
1456     Features.push_back(Args.MakeArgString("+fp64"));
1457     Features.push_back(Args.MakeArgString("+nooddspreg"));
1458   }
1459
1460   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1461                    options::OPT_modd_spreg, "nooddspreg");
1462 }
1463
1464 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1465                               ArgStringList &CmdArgs) const {
1466   const Driver &D = getToolChain().getDriver();
1467   StringRef CPUName;
1468   StringRef ABIName;
1469   const llvm::Triple &Triple = getToolChain().getTriple();
1470   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1471
1472   CmdArgs.push_back("-target-abi");
1473   CmdArgs.push_back(ABIName.data());
1474
1475   mips::FloatABI ABI = getMipsFloatABI(D, Args);
1476   if (ABI == mips::FloatABI::Soft) {
1477     // Floating point operations and argument passing are soft.
1478     CmdArgs.push_back("-msoft-float");
1479     CmdArgs.push_back("-mfloat-abi");
1480     CmdArgs.push_back("soft");
1481   } else {
1482     // Floating point operations and argument passing are hard.
1483     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1484     CmdArgs.push_back("-mfloat-abi");
1485     CmdArgs.push_back("hard");
1486   }
1487
1488   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1489     if (A->getOption().matches(options::OPT_mxgot)) {
1490       CmdArgs.push_back("-mllvm");
1491       CmdArgs.push_back("-mxgot");
1492     }
1493   }
1494
1495   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1496                                options::OPT_mno_ldc1_sdc1)) {
1497     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1498       CmdArgs.push_back("-mllvm");
1499       CmdArgs.push_back("-mno-ldc1-sdc1");
1500     }
1501   }
1502
1503   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1504                                options::OPT_mno_check_zero_division)) {
1505     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1506       CmdArgs.push_back("-mllvm");
1507       CmdArgs.push_back("-mno-check-zero-division");
1508     }
1509   }
1510
1511   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1512     StringRef v = A->getValue();
1513     CmdArgs.push_back("-mllvm");
1514     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1515     A->claim();
1516   }
1517
1518   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1519     StringRef Val = StringRef(A->getValue());
1520     if (mips::hasCompactBranches(CPUName)) {
1521       if (Val == "never" || Val == "always" || Val == "optimal") {
1522         CmdArgs.push_back("-mllvm");
1523         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1524       } else
1525         D.Diag(diag::err_drv_unsupported_option_argument)
1526             << A->getOption().getName() << Val;
1527     } else
1528       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1529   }
1530 }
1531
1532 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1533 static std::string getPPCTargetCPU(const ArgList &Args) {
1534   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1535     StringRef CPUName = A->getValue();
1536
1537     if (CPUName == "native") {
1538       std::string CPU = llvm::sys::getHostCPUName();
1539       if (!CPU.empty() && CPU != "generic")
1540         return CPU;
1541       else
1542         return "";
1543     }
1544
1545     return llvm::StringSwitch<const char *>(CPUName)
1546         .Case("common", "generic")
1547         .Case("440", "440")
1548         .Case("440fp", "440")
1549         .Case("450", "450")
1550         .Case("601", "601")
1551         .Case("602", "602")
1552         .Case("603", "603")
1553         .Case("603e", "603e")
1554         .Case("603ev", "603ev")
1555         .Case("604", "604")
1556         .Case("604e", "604e")
1557         .Case("620", "620")
1558         .Case("630", "pwr3")
1559         .Case("G3", "g3")
1560         .Case("7400", "7400")
1561         .Case("G4", "g4")
1562         .Case("7450", "7450")
1563         .Case("G4+", "g4+")
1564         .Case("750", "750")
1565         .Case("970", "970")
1566         .Case("G5", "g5")
1567         .Case("a2", "a2")
1568         .Case("a2q", "a2q")
1569         .Case("e500mc", "e500mc")
1570         .Case("e5500", "e5500")
1571         .Case("power3", "pwr3")
1572         .Case("power4", "pwr4")
1573         .Case("power5", "pwr5")
1574         .Case("power5x", "pwr5x")
1575         .Case("power6", "pwr6")
1576         .Case("power6x", "pwr6x")
1577         .Case("power7", "pwr7")
1578         .Case("power8", "pwr8")
1579         .Case("power9", "pwr9")
1580         .Case("pwr3", "pwr3")
1581         .Case("pwr4", "pwr4")
1582         .Case("pwr5", "pwr5")
1583         .Case("pwr5x", "pwr5x")
1584         .Case("pwr6", "pwr6")
1585         .Case("pwr6x", "pwr6x")
1586         .Case("pwr7", "pwr7")
1587         .Case("pwr8", "pwr8")
1588         .Case("pwr9", "pwr9")
1589         .Case("powerpc", "ppc")
1590         .Case("powerpc64", "ppc64")
1591         .Case("powerpc64le", "ppc64le")
1592         .Default("");
1593   }
1594
1595   return "";
1596 }
1597
1598 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1599                                  const ArgList &Args,
1600                                  std::vector<const char *> &Features) {
1601   handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1602
1603   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1604   if (FloatABI == ppc::FloatABI::Soft &&
1605       !(Triple.getArch() == llvm::Triple::ppc64 ||
1606         Triple.getArch() == llvm::Triple::ppc64le))
1607     Features.push_back("+soft-float");
1608   else if (FloatABI == ppc::FloatABI::Soft &&
1609            (Triple.getArch() == llvm::Triple::ppc64 ||
1610             Triple.getArch() == llvm::Triple::ppc64le))
1611     D.Diag(diag::err_drv_invalid_mfloat_abi)
1612         << "soft float is not supported for ppc64";
1613
1614   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1615   AddTargetFeature(Args, Features, options::OPT_faltivec,
1616                    options::OPT_fno_altivec, "altivec");
1617 }
1618
1619 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1620   ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1621   if (Arg *A =
1622           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1623                           options::OPT_mfloat_abi_EQ)) {
1624     if (A->getOption().matches(options::OPT_msoft_float))
1625       ABI = ppc::FloatABI::Soft;
1626     else if (A->getOption().matches(options::OPT_mhard_float))
1627       ABI = ppc::FloatABI::Hard;
1628     else {
1629       ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1630                 .Case("soft", ppc::FloatABI::Soft)
1631                 .Case("hard", ppc::FloatABI::Hard)
1632                 .Default(ppc::FloatABI::Invalid);
1633       if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1634         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1635         ABI = ppc::FloatABI::Hard;
1636       }
1637     }
1638   }
1639
1640   // If unspecified, choose the default based on the platform.
1641   if (ABI == ppc::FloatABI::Invalid) {
1642     ABI = ppc::FloatABI::Hard;
1643   }
1644
1645   return ABI;
1646 }
1647
1648 void Clang::AddPPCTargetArgs(const ArgList &Args,
1649                              ArgStringList &CmdArgs) const {
1650   // Select the ABI to use.
1651   const char *ABIName = nullptr;
1652   if (getToolChain().getTriple().isOSLinux())
1653     switch (getToolChain().getArch()) {
1654     case llvm::Triple::ppc64: {
1655       // When targeting a processor that supports QPX, or if QPX is
1656       // specifically enabled, default to using the ABI that supports QPX (so
1657       // long as it is not specifically disabled).
1658       bool HasQPX = false;
1659       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1660         HasQPX = A->getValue() == StringRef("a2q");
1661       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1662       if (HasQPX) {
1663         ABIName = "elfv1-qpx";
1664         break;
1665       }
1666
1667       ABIName = "elfv1";
1668       break;
1669     }
1670     case llvm::Triple::ppc64le:
1671       ABIName = "elfv2";
1672       break;
1673     default:
1674       break;
1675     }
1676
1677   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1678     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1679     // the option if given as we don't have backend support for any targets
1680     // that don't use the altivec abi.
1681     if (StringRef(A->getValue()) != "altivec")
1682       ABIName = A->getValue();
1683
1684   ppc::FloatABI FloatABI =
1685       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1686
1687   if (FloatABI == ppc::FloatABI::Soft) {
1688     // Floating point operations and argument passing are soft.
1689     CmdArgs.push_back("-msoft-float");
1690     CmdArgs.push_back("-mfloat-abi");
1691     CmdArgs.push_back("soft");
1692   } else {
1693     // Floating point operations and argument passing are hard.
1694     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1695     CmdArgs.push_back("-mfloat-abi");
1696     CmdArgs.push_back("hard");
1697   }
1698
1699   if (ABIName) {
1700     CmdArgs.push_back("-target-abi");
1701     CmdArgs.push_back(ABIName);
1702   }
1703 }
1704
1705 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1706   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1707   return A && (A->getValue() == StringRef(Value));
1708 }
1709
1710 /// Get the (LLVM) name of the R600 gpu we are targeting.
1711 static std::string getR600TargetGPU(const ArgList &Args) {
1712   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1713     const char *GPUName = A->getValue();
1714     return llvm::StringSwitch<const char *>(GPUName)
1715         .Cases("rv630", "rv635", "r600")
1716         .Cases("rv610", "rv620", "rs780", "rs880")
1717         .Case("rv740", "rv770")
1718         .Case("palm", "cedar")
1719         .Cases("sumo", "sumo2", "sumo")
1720         .Case("hemlock", "cypress")
1721         .Case("aruba", "cayman")
1722         .Default(GPUName);
1723   }
1724   return "";
1725 }
1726
1727 static std::string getLanaiTargetCPU(const ArgList &Args) {
1728   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1729     return A->getValue();
1730   }
1731   return "";
1732 }
1733
1734 sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
1735                                         const ArgList &Args) {
1736   sparc::FloatABI ABI = sparc::FloatABI::Invalid;
1737   if (Arg *A =
1738           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1739                           options::OPT_mfloat_abi_EQ)) {
1740     if (A->getOption().matches(options::OPT_msoft_float))
1741       ABI = sparc::FloatABI::Soft;
1742     else if (A->getOption().matches(options::OPT_mhard_float))
1743       ABI = sparc::FloatABI::Hard;
1744     else {
1745       ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
1746                 .Case("soft", sparc::FloatABI::Soft)
1747                 .Case("hard", sparc::FloatABI::Hard)
1748                 .Default(sparc::FloatABI::Invalid);
1749       if (ABI == sparc::FloatABI::Invalid &&
1750           !StringRef(A->getValue()).empty()) {
1751         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1752         ABI = sparc::FloatABI::Hard;
1753       }
1754     }
1755   }
1756
1757   // If unspecified, choose the default based on the platform.
1758   // Only the hard-float ABI on Sparc is standardized, and it is the
1759   // default. GCC also supports a nonstandard soft-float ABI mode, also
1760   // implemented in LLVM. However as this is not standard we set the default
1761   // to be hard-float.
1762   if (ABI == sparc::FloatABI::Invalid) {
1763     ABI = sparc::FloatABI::Hard;
1764   }
1765
1766   return ABI;
1767 }
1768
1769 static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
1770                                  std::vector<const char *> &Features) {
1771   sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
1772   if (FloatABI == sparc::FloatABI::Soft)
1773     Features.push_back("+soft-float");
1774 }
1775
1776 void Clang::AddSparcTargetArgs(const ArgList &Args,
1777                                ArgStringList &CmdArgs) const {
1778   sparc::FloatABI FloatABI =
1779       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1780
1781   if (FloatABI == sparc::FloatABI::Soft) {
1782     // Floating point operations and argument passing are soft.
1783     CmdArgs.push_back("-msoft-float");
1784     CmdArgs.push_back("-mfloat-abi");
1785     CmdArgs.push_back("soft");
1786   } else {
1787     // Floating point operations and argument passing are hard.
1788     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1789     CmdArgs.push_back("-mfloat-abi");
1790     CmdArgs.push_back("hard");
1791   }
1792 }
1793
1794 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1795                                  ArgStringList &CmdArgs) const {
1796   if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1797     CmdArgs.push_back("-mbackchain");
1798 }
1799
1800 static const char *getSystemZTargetCPU(const ArgList &Args) {
1801   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1802     return A->getValue();
1803   return "z10";
1804 }
1805
1806 static void getSystemZTargetFeatures(const ArgList &Args,
1807                                      std::vector<const char *> &Features) {
1808   // -m(no-)htm overrides use of the transactional-execution facility.
1809   if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1810     if (A->getOption().matches(options::OPT_mhtm))
1811       Features.push_back("+transactional-execution");
1812     else
1813       Features.push_back("-transactional-execution");
1814   }
1815   // -m(no-)vx overrides use of the vector facility.
1816   if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1817     if (A->getOption().matches(options::OPT_mvx))
1818       Features.push_back("+vector");
1819     else
1820       Features.push_back("-vector");
1821   }
1822 }
1823
1824 static const char *getX86TargetCPU(const ArgList &Args,
1825                                    const llvm::Triple &Triple) {
1826   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1827     if (StringRef(A->getValue()) != "native") {
1828       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1829         return "core-avx2";
1830
1831       return A->getValue();
1832     }
1833
1834     // FIXME: Reject attempts to use -march=native unless the target matches
1835     // the host.
1836     //
1837     // FIXME: We should also incorporate the detected target features for use
1838     // with -native.
1839     std::string CPU = llvm::sys::getHostCPUName();
1840     if (!CPU.empty() && CPU != "generic")
1841       return Args.MakeArgString(CPU);
1842   }
1843
1844   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1845     // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1846     StringRef Arch = A->getValue();
1847     const char *CPU;
1848     if (Triple.getArch() == llvm::Triple::x86) {
1849       CPU = llvm::StringSwitch<const char *>(Arch)
1850                 .Case("IA32", "i386")
1851                 .Case("SSE", "pentium3")
1852                 .Case("SSE2", "pentium4")
1853                 .Case("AVX", "sandybridge")
1854                 .Case("AVX2", "haswell")
1855                 .Default(nullptr);
1856     } else {
1857       CPU = llvm::StringSwitch<const char *>(Arch)
1858                 .Case("AVX", "sandybridge")
1859                 .Case("AVX2", "haswell")
1860                 .Default(nullptr);
1861     }
1862     if (CPU)
1863       return CPU;
1864   }
1865
1866   // Select the default CPU if none was given (or detection failed).
1867
1868   if (Triple.getArch() != llvm::Triple::x86_64 &&
1869       Triple.getArch() != llvm::Triple::x86)
1870     return nullptr; // This routine is only handling x86 targets.
1871
1872   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1873
1874   // FIXME: Need target hooks.
1875   if (Triple.isOSDarwin()) {
1876     if (Triple.getArchName() == "x86_64h")
1877       return "core-avx2";
1878     return Is64Bit ? "core2" : "yonah";
1879   }
1880
1881   // Set up default CPU name for PS4 compilers.
1882   if (Triple.isPS4CPU())
1883     return "btver2";
1884
1885   // On Android use targets compatible with gcc
1886   if (Triple.isAndroid())
1887     return Is64Bit ? "x86-64" : "i686";
1888
1889   // Everything else goes to x86-64 in 64-bit mode.
1890   if (Is64Bit)
1891     return "x86-64";
1892
1893   switch (Triple.getOS()) {
1894   case llvm::Triple::FreeBSD:
1895   case llvm::Triple::NetBSD:
1896   case llvm::Triple::OpenBSD:
1897     return "i486";
1898   case llvm::Triple::Haiku:
1899     return "i586";
1900   case llvm::Triple::Bitrig:
1901     return "i686";
1902   default:
1903     // Fallback to p4.
1904     return "pentium4";
1905   }
1906 }
1907
1908 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1909 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1910   // If we have -mcpu=, use that.
1911   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1912     StringRef CPU = A->getValue();
1913
1914 #ifdef __wasm__
1915     // Handle "native" by examining the host. "native" isn't meaningful when
1916     // cross compiling, so only support this when the host is also WebAssembly.
1917     if (CPU == "native")
1918       return llvm::sys::getHostCPUName();
1919 #endif
1920
1921     return CPU;
1922   }
1923
1924   return "generic";
1925 }
1926
1927 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1928                               bool FromAs = false) {
1929   switch (T.getArch()) {
1930   default:
1931     return "";
1932
1933   case llvm::Triple::aarch64:
1934   case llvm::Triple::aarch64_be:
1935     return getAArch64TargetCPU(Args);
1936
1937   case llvm::Triple::arm:
1938   case llvm::Triple::armeb:
1939   case llvm::Triple::thumb:
1940   case llvm::Triple::thumbeb: {
1941     StringRef MArch, MCPU;
1942     getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1943     return arm::getARMTargetCPU(MCPU, MArch, T);
1944   }
1945   case llvm::Triple::mips:
1946   case llvm::Triple::mipsel:
1947   case llvm::Triple::mips64:
1948   case llvm::Triple::mips64el: {
1949     StringRef CPUName;
1950     StringRef ABIName;
1951     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1952     return CPUName;
1953   }
1954
1955   case llvm::Triple::nvptx:
1956   case llvm::Triple::nvptx64:
1957     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1958       return A->getValue();
1959     return "";
1960
1961   case llvm::Triple::ppc:
1962   case llvm::Triple::ppc64:
1963   case llvm::Triple::ppc64le: {
1964     std::string TargetCPUName = getPPCTargetCPU(Args);
1965     // LLVM may default to generating code for the native CPU,
1966     // but, like gcc, we default to a more generic option for
1967     // each architecture. (except on Darwin)
1968     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1969       if (T.getArch() == llvm::Triple::ppc64)
1970         TargetCPUName = "ppc64";
1971       else if (T.getArch() == llvm::Triple::ppc64le)
1972         TargetCPUName = "ppc64le";
1973       else
1974         TargetCPUName = "ppc";
1975     }
1976     return TargetCPUName;
1977   }
1978
1979   case llvm::Triple::sparc:
1980   case llvm::Triple::sparcel:
1981   case llvm::Triple::sparcv9:
1982     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1983       return A->getValue();
1984     return "";
1985
1986   case llvm::Triple::x86:
1987   case llvm::Triple::x86_64:
1988     return getX86TargetCPU(Args, T);
1989
1990   case llvm::Triple::hexagon:
1991     return "hexagon" +
1992            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1993
1994   case llvm::Triple::lanai:
1995     return getLanaiTargetCPU(Args);
1996
1997   case llvm::Triple::systemz:
1998     return getSystemZTargetCPU(Args);
1999
2000   case llvm::Triple::r600:
2001   case llvm::Triple::amdgcn:
2002     return getR600TargetGPU(Args);
2003
2004   case llvm::Triple::wasm32:
2005   case llvm::Triple::wasm64:
2006     return getWebAssemblyTargetCPU(Args);
2007   }
2008 }
2009
2010 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
2011                           ArgStringList &CmdArgs, bool IsThinLTO) {
2012   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
2013   // as gold requires -plugin to come before any -plugin-opt that -Wl might
2014   // forward.
2015   CmdArgs.push_back("-plugin");
2016   std::string Plugin =
2017       ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
2018   CmdArgs.push_back(Args.MakeArgString(Plugin));
2019
2020   // Try to pass driver level flags relevant to LTO code generation down to
2021   // the plugin.
2022
2023   // Handle flags for selecting CPU variants.
2024   std::string CPU = getCPUName(Args, ToolChain.getTriple());
2025   if (!CPU.empty())
2026     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
2027
2028   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2029     StringRef OOpt;
2030     if (A->getOption().matches(options::OPT_O4) ||
2031         A->getOption().matches(options::OPT_Ofast))
2032       OOpt = "3";
2033     else if (A->getOption().matches(options::OPT_O))
2034       OOpt = A->getValue();
2035     else if (A->getOption().matches(options::OPT_O0))
2036       OOpt = "0";
2037     if (!OOpt.empty())
2038       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
2039   }
2040
2041   if (IsThinLTO)
2042     CmdArgs.push_back("-plugin-opt=thinlto");
2043
2044   // If an explicit debugger tuning argument appeared, pass it along.
2045   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2046                                options::OPT_ggdbN_Group)) {
2047     if (A->getOption().matches(options::OPT_glldb))
2048       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
2049     else if (A->getOption().matches(options::OPT_gsce))
2050       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
2051     else
2052       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
2053   }
2054 }
2055
2056 /// This is a helper function for validating the optional refinement step
2057 /// parameter in reciprocal argument strings. Return false if there is an error
2058 /// parsing the refinement step. Otherwise, return true and set the Position
2059 /// of the refinement step in the input string.
2060 static bool getRefinementStep(StringRef In, const Driver &D,
2061                               const Arg &A, size_t &Position) {
2062   const char RefinementStepToken = ':';
2063   Position = In.find(RefinementStepToken);
2064   if (Position != StringRef::npos) {
2065     StringRef Option = A.getOption().getName();
2066     StringRef RefStep = In.substr(Position + 1);
2067     // Allow exactly one numeric character for the additional refinement
2068     // step parameter. This is reasonable for all currently-supported
2069     // operations and architectures because we would expect that a larger value
2070     // of refinement steps would cause the estimate "optimization" to
2071     // under-perform the native operation. Also, if the estimate does not
2072     // converge quickly, it probably will not ever converge, so further
2073     // refinement steps will not produce a better answer.
2074     if (RefStep.size() != 1) {
2075       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2076       return false;
2077     }
2078     char RefStepChar = RefStep[0];
2079     if (RefStepChar < '0' || RefStepChar > '9') {
2080       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2081       return false;
2082     }
2083   }
2084   return true;
2085 }
2086
2087 /// The -mrecip flag requires processing of many optional parameters.
2088 static void ParseMRecip(const Driver &D, const ArgList &Args,
2089                         ArgStringList &OutStrings) {
2090   StringRef DisabledPrefixIn = "!";
2091   StringRef DisabledPrefixOut = "!";
2092   StringRef EnabledPrefixOut = "";
2093   StringRef Out = "-mrecip=";
2094
2095   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
2096   if (!A)
2097     return;
2098
2099   unsigned NumOptions = A->getNumValues();
2100   if (NumOptions == 0) {
2101     // No option is the same as "all".
2102     OutStrings.push_back(Args.MakeArgString(Out + "all"));
2103     return;
2104   }
2105
2106   // Pass through "all", "none", or "default" with an optional refinement step.
2107   if (NumOptions == 1) {
2108     StringRef Val = A->getValue(0);
2109     size_t RefStepLoc;
2110     if (!getRefinementStep(Val, D, *A, RefStepLoc))
2111       return;
2112     StringRef ValBase = Val.slice(0, RefStepLoc);
2113     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2114       OutStrings.push_back(Args.MakeArgString(Out + Val));
2115       return;
2116     }
2117   }
2118
2119   // Each reciprocal type may be enabled or disabled individually.
2120   // Check each input value for validity, concatenate them all back together,
2121   // and pass through.
2122
2123   llvm::StringMap<bool> OptionStrings;
2124   OptionStrings.insert(std::make_pair("divd", false));
2125   OptionStrings.insert(std::make_pair("divf", false));
2126   OptionStrings.insert(std::make_pair("vec-divd", false));
2127   OptionStrings.insert(std::make_pair("vec-divf", false));
2128   OptionStrings.insert(std::make_pair("sqrtd", false));
2129   OptionStrings.insert(std::make_pair("sqrtf", false));
2130   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2131   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
2132
2133   for (unsigned i = 0; i != NumOptions; ++i) {
2134     StringRef Val = A->getValue(i);
2135
2136     bool IsDisabled = Val.startswith(DisabledPrefixIn);
2137     // Ignore the disablement token for string matching.
2138     if (IsDisabled)
2139       Val = Val.substr(1);
2140
2141     size_t RefStep;
2142     if (!getRefinementStep(Val, D, *A, RefStep))
2143       return;
2144
2145     StringRef ValBase = Val.slice(0, RefStep);
2146     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2147     if (OptionIter == OptionStrings.end()) {
2148       // Try again specifying float suffix.
2149       OptionIter = OptionStrings.find(ValBase.str() + 'f');
2150       if (OptionIter == OptionStrings.end()) {
2151         // The input name did not match any known option string.
2152         D.Diag(diag::err_drv_unknown_argument) << Val;
2153         return;
2154       }
2155       // The option was specified without a float or double suffix.
2156       // Make sure that the double entry was not already specified.
2157       // The float entry will be checked below.
2158       if (OptionStrings[ValBase.str() + 'd']) {
2159         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2160         return;
2161       }
2162     }
2163
2164     if (OptionIter->second == true) {
2165       // Duplicate option specified.
2166       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2167       return;
2168     }
2169
2170     // Mark the matched option as found. Do not allow duplicate specifiers.
2171     OptionIter->second = true;
2172
2173     // If the precision was not specified, also mark the double entry as found.
2174     if (ValBase.back() != 'f' && ValBase.back() != 'd')
2175       OptionStrings[ValBase.str() + 'd'] = true;
2176
2177     // Build the output string.
2178     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2179     Out = Args.MakeArgString(Out + Prefix + Val);
2180     if (i != NumOptions - 1)
2181       Out = Args.MakeArgString(Out + ",");
2182   }
2183
2184   OutStrings.push_back(Args.MakeArgString(Out));
2185 }
2186
2187 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
2188                                  const ArgList &Args,
2189                                  std::vector<const char *> &Features) {
2190   // If -march=native, autodetect the feature list.
2191   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
2192     if (StringRef(A->getValue()) == "native") {
2193       llvm::StringMap<bool> HostFeatures;
2194       if (llvm::sys::getHostCPUFeatures(HostFeatures))
2195         for (auto &F : HostFeatures)
2196           Features.push_back(
2197               Args.MakeArgString((F.second ? "+" : "-") + F.first()));
2198     }
2199   }
2200
2201   if (Triple.getArchName() == "x86_64h") {
2202     // x86_64h implies quite a few of the more modern subtarget features
2203     // for Haswell class CPUs, but not all of them. Opt-out of a few.
2204     Features.push_back("-rdrnd");
2205     Features.push_back("-aes");
2206     Features.push_back("-pclmul");
2207     Features.push_back("-rtm");
2208     Features.push_back("-hle");
2209     Features.push_back("-fsgsbase");
2210   }
2211
2212   const llvm::Triple::ArchType ArchType = Triple.getArch();
2213   // Add features to be compatible with gcc for Android.
2214   if (Triple.isAndroid()) {
2215     if (ArchType == llvm::Triple::x86_64) {
2216       Features.push_back("+sse4.2");
2217       Features.push_back("+popcnt");
2218     } else
2219       Features.push_back("+ssse3");
2220   }
2221
2222   // Set features according to the -arch flag on MSVC.
2223   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
2224     StringRef Arch = A->getValue();
2225     bool ArchUsed = false;
2226     // First, look for flags that are shared in x86 and x86-64.
2227     if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
2228       if (Arch == "AVX" || Arch == "AVX2") {
2229         ArchUsed = true;
2230         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2231       }
2232     }
2233     // Then, look for x86-specific flags.
2234     if (ArchType == llvm::Triple::x86) {
2235       if (Arch == "IA32") {
2236         ArchUsed = true;
2237       } else if (Arch == "SSE" || Arch == "SSE2") {
2238         ArchUsed = true;
2239         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2240       }
2241     }
2242     if (!ArchUsed)
2243       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2244   }
2245
2246   // Now add any that the user explicitly requested on the command line,
2247   // which may override the defaults.
2248   handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2249 }
2250
2251 void Clang::AddX86TargetArgs(const ArgList &Args,
2252                              ArgStringList &CmdArgs) const {
2253   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2254       Args.hasArg(options::OPT_mkernel) ||
2255       Args.hasArg(options::OPT_fapple_kext))
2256     CmdArgs.push_back("-disable-red-zone");
2257
2258   // Default to avoid implicit floating-point for kernel/kext code, but allow
2259   // that to be overridden with -mno-soft-float.
2260   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2261                           Args.hasArg(options::OPT_fapple_kext));
2262   if (Arg *A = Args.getLastArg(
2263           options::OPT_msoft_float, options::OPT_mno_soft_float,
2264           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2265     const Option &O = A->getOption();
2266     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2267                        O.matches(options::OPT_msoft_float));
2268   }
2269   if (NoImplicitFloat)
2270     CmdArgs.push_back("-no-implicit-float");
2271
2272   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2273     StringRef Value = A->getValue();
2274     if (Value == "intel" || Value == "att") {
2275       CmdArgs.push_back("-mllvm");
2276       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2277     } else {
2278       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2279           << A->getOption().getName() << Value;
2280     }
2281   }
2282
2283   // Set flags to support MCU ABI.
2284   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2285     CmdArgs.push_back("-mfloat-abi");
2286     CmdArgs.push_back("soft");
2287     CmdArgs.push_back("-mstack-alignment=4");
2288   }
2289 }
2290
2291 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2292                                  ArgStringList &CmdArgs) const {
2293   CmdArgs.push_back("-mqdsp6-compat");
2294   CmdArgs.push_back("-Wreturn-type");
2295
2296   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2297     std::string N = llvm::utostr(G.getValue());
2298     std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2299     CmdArgs.push_back("-mllvm");
2300     CmdArgs.push_back(Args.MakeArgString(Opt));
2301   }
2302
2303   if (!Args.hasArg(options::OPT_fno_short_enums))
2304     CmdArgs.push_back("-fshort-enums");
2305   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2306     CmdArgs.push_back("-mllvm");
2307     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2308   }
2309   CmdArgs.push_back("-mllvm");
2310   CmdArgs.push_back("-machine-sink-split=0");
2311 }
2312
2313 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2314                                ArgStringList &CmdArgs) const {
2315   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2316     StringRef CPUName = A->getValue();
2317
2318     CmdArgs.push_back("-target-cpu");
2319     CmdArgs.push_back(Args.MakeArgString(CPUName));
2320   }
2321   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2322     StringRef Value = A->getValue();
2323     // Only support mregparm=4 to support old usage. Report error for all other
2324     // cases.
2325     int Mregparm;
2326     if (Value.getAsInteger(10, Mregparm)) {
2327       if (Mregparm != 4) {
2328         getToolChain().getDriver().Diag(
2329             diag::err_drv_unsupported_option_argument)
2330             << A->getOption().getName() << Value;
2331       }
2332     }
2333   }
2334 }
2335
2336 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2337                                      ArgStringList &CmdArgs) const {
2338   // Default to "hidden" visibility.
2339   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2340                    options::OPT_fvisibility_ms_compat)) {
2341     CmdArgs.push_back("-fvisibility");
2342     CmdArgs.push_back("hidden");
2343   }
2344 }
2345
2346 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2347 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2348                                   std::vector<const char *> &Features) {
2349   SmallVector<StringRef, 8> Split;
2350   text.split(Split, StringRef("+"), -1, false);
2351
2352   for (StringRef Feature : Split) {
2353     const char *result = llvm::StringSwitch<const char *>(Feature)
2354                              .Case("fp", "+fp-armv8")
2355                              .Case("simd", "+neon")
2356                              .Case("crc", "+crc")
2357                              .Case("crypto", "+crypto")
2358                              .Case("fp16", "+fullfp16")
2359                              .Case("profile", "+spe")
2360                              .Case("ras", "+ras")
2361                              .Case("nofp", "-fp-armv8")
2362                              .Case("nosimd", "-neon")
2363                              .Case("nocrc", "-crc")
2364                              .Case("nocrypto", "-crypto")
2365                              .Case("nofp16", "-fullfp16")
2366                              .Case("noprofile", "-spe")
2367                              .Case("noras", "-ras")
2368                              .Default(nullptr);
2369     if (result)
2370       Features.push_back(result);
2371     else if (Feature == "neon" || Feature == "noneon")
2372       D.Diag(diag::err_drv_no_neon_modifier);
2373     else
2374       return false;
2375   }
2376   return true;
2377 }
2378
2379 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2380 // decode CPU and feature.
2381 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2382                               std::vector<const char *> &Features) {
2383   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2384   CPU = Split.first;
2385   if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
2386       CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
2387       CPU == "kryo"       || CPU == "cortex-a73" || CPU == "vulcan") {
2388     Features.push_back("+neon");
2389     Features.push_back("+crc");
2390     Features.push_back("+crypto");
2391   } else if (CPU == "cyclone") {
2392     Features.push_back("+neon");
2393     Features.push_back("+crypto");
2394   } else if (CPU == "generic") {
2395     Features.push_back("+neon");
2396   } else {
2397     return false;
2398   }
2399
2400   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2401     return false;
2402
2403   return true;
2404 }
2405
2406 static bool
2407 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2408                                 const ArgList &Args,
2409                                 std::vector<const char *> &Features) {
2410   std::string MarchLowerCase = March.lower();
2411   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2412
2413   if (Split.first == "armv8-a" || Split.first == "armv8a") {
2414     // ok, no additional features.
2415   } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2416     Features.push_back("+v8.1a");
2417   } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2418     Features.push_back("+v8.2a");
2419   } else {
2420     return false;
2421   }
2422
2423   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2424     return false;
2425
2426   return true;
2427 }
2428
2429 static bool
2430 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2431                                const ArgList &Args,
2432                                std::vector<const char *> &Features) {
2433   StringRef CPU;
2434   std::string McpuLowerCase = Mcpu.lower();
2435   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2436     return false;
2437
2438   return true;
2439 }
2440
2441 static bool
2442 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2443                                      const ArgList &Args,
2444                                      std::vector<const char *> &Features) {
2445   std::string MtuneLowerCase = Mtune.lower();
2446   // Handle CPU name is 'native'.
2447   if (MtuneLowerCase == "native")
2448     MtuneLowerCase = llvm::sys::getHostCPUName();
2449   if (MtuneLowerCase == "cyclone") {
2450     Features.push_back("+zcm");
2451     Features.push_back("+zcz");
2452   }
2453   return true;
2454 }
2455
2456 static bool
2457 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2458                                     const ArgList &Args,
2459                                     std::vector<const char *> &Features) {
2460   StringRef CPU;
2461   std::vector<const char *> DecodedFeature;
2462   std::string McpuLowerCase = Mcpu.lower();
2463   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2464     return false;
2465
2466   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2467 }
2468
2469 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2470                                      std::vector<const char *> &Features) {
2471   Arg *A;
2472   bool success = true;
2473   // Enable NEON by default.
2474   Features.push_back("+neon");
2475   if ((A = Args.getLastArg(options::OPT_march_EQ)))
2476     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2477   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2478     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2479   else if (Args.hasArg(options::OPT_arch))
2480     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2481                                              Features);
2482
2483   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2484     success =
2485         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2486   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2487     success =
2488         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2489   else if (Args.hasArg(options::OPT_arch))
2490     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2491                                                   Args, Features);
2492
2493   if (!success)
2494     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2495
2496   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2497     Features.push_back("-fp-armv8");
2498     Features.push_back("-crypto");
2499     Features.push_back("-neon");
2500   }
2501
2502   // En/disable crc
2503   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2504     if (A->getOption().matches(options::OPT_mcrc))
2505       Features.push_back("+crc");
2506     else
2507       Features.push_back("-crc");
2508   }
2509
2510   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2511                                options::OPT_munaligned_access))
2512     if (A->getOption().matches(options::OPT_mno_unaligned_access))
2513       Features.push_back("+strict-align");
2514
2515   if (Args.hasArg(options::OPT_ffixed_x18))
2516     Features.push_back("+reserve-x18");
2517 }
2518
2519 static void getHexagonTargetFeatures(const ArgList &Args,
2520                                      std::vector<const char *> &Features) {
2521   bool HasHVX = false, HasHVXD = false;
2522
2523   // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2524   // doing dependent option handling here rather than in initFeatureMap or a
2525   // similar handler.
2526   for (auto &A : Args) {
2527     auto &Opt = A->getOption();
2528     if (Opt.matches(options::OPT_mhexagon_hvx))
2529       HasHVX = true;
2530     else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2531       HasHVXD = HasHVX = false;
2532     else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2533       HasHVXD = HasHVX = true;
2534     else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2535       HasHVXD = false;
2536     else
2537       continue;
2538     A->claim();
2539   }
2540
2541   Features.push_back(HasHVX  ? "+hvx" : "-hvx");
2542   Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2543 }
2544
2545 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2546                                          std::vector<const char *> &Features) {
2547   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2548 }
2549
2550 static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
2551                                     std::vector<const char *> &Features) {
2552   if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
2553     StringRef value = dAbi->getValue();
2554     if (value == "1.0") {
2555       Features.push_back("+amdgpu-debugger-insert-nops");
2556       Features.push_back("+amdgpu-debugger-reserve-regs");
2557       Features.push_back("+amdgpu-debugger-emit-prologue");
2558     } else {
2559       D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
2560     }
2561   }
2562
2563   handleTargetFeaturesGroup(
2564     Args, Features, options::OPT_m_amdgpu_Features_Group);
2565 }
2566
2567 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2568                               const ArgList &Args, ArgStringList &CmdArgs,
2569                               bool ForAS) {
2570   const Driver &D = TC.getDriver();
2571   std::vector<const char *> Features;
2572   switch (Triple.getArch()) {
2573   default:
2574     break;
2575   case llvm::Triple::mips:
2576   case llvm::Triple::mipsel:
2577   case llvm::Triple::mips64:
2578   case llvm::Triple::mips64el:
2579     getMIPSTargetFeatures(D, Triple, Args, Features);
2580     break;
2581
2582   case llvm::Triple::arm:
2583   case llvm::Triple::armeb:
2584   case llvm::Triple::thumb:
2585   case llvm::Triple::thumbeb:
2586     getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2587     break;
2588
2589   case llvm::Triple::ppc:
2590   case llvm::Triple::ppc64:
2591   case llvm::Triple::ppc64le:
2592     getPPCTargetFeatures(D, Triple, Args, Features);
2593     break;
2594   case llvm::Triple::systemz:
2595     getSystemZTargetFeatures(Args, Features);
2596     break;
2597   case llvm::Triple::aarch64:
2598   case llvm::Triple::aarch64_be:
2599     getAArch64TargetFeatures(D, Args, Features);
2600     break;
2601   case llvm::Triple::x86:
2602   case llvm::Triple::x86_64:
2603     getX86TargetFeatures(D, Triple, Args, Features);
2604     break;
2605   case llvm::Triple::hexagon:
2606     getHexagonTargetFeatures(Args, Features);
2607     break;
2608   case llvm::Triple::wasm32:
2609   case llvm::Triple::wasm64:
2610     getWebAssemblyTargetFeatures(Args, Features);
2611     break; 
2612   case llvm::Triple::sparc:
2613   case llvm::Triple::sparcel:
2614   case llvm::Triple::sparcv9:
2615     getSparcTargetFeatures(D, Args, Features);
2616     break;
2617   case llvm::Triple::r600:
2618   case llvm::Triple::amdgcn:
2619     getAMDGPUTargetFeatures(D, Args, Features);
2620     break;
2621   }
2622
2623   // Find the last of each feature.
2624   llvm::StringMap<unsigned> LastOpt;
2625   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2626     const char *Name = Features[I];
2627     assert(Name[0] == '-' || Name[0] == '+');
2628     LastOpt[Name + 1] = I;
2629   }
2630
2631   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2632     // If this feature was overridden, ignore it.
2633     const char *Name = Features[I];
2634     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2635     assert(LastI != LastOpt.end());
2636     unsigned Last = LastI->second;
2637     if (Last != I)
2638       continue;
2639
2640     CmdArgs.push_back("-target-feature");
2641     CmdArgs.push_back(Name);
2642   }
2643 }
2644
2645 static bool
2646 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2647                                           const llvm::Triple &Triple) {
2648   // We use the zero-cost exception tables for Objective-C if the non-fragile
2649   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2650   // later.
2651   if (runtime.isNonFragile())
2652     return true;
2653
2654   if (!Triple.isMacOSX())
2655     return false;
2656
2657   return (!Triple.isMacOSXVersionLT(10, 5) &&
2658           (Triple.getArch() == llvm::Triple::x86_64 ||
2659            Triple.getArch() == llvm::Triple::arm));
2660 }
2661
2662 /// Adds exception related arguments to the driver command arguments. There's a
2663 /// master flag, -fexceptions and also language specific flags to enable/disable
2664 /// C++ and Objective-C exceptions. This makes it possible to for example
2665 /// disable C++ exceptions but enable Objective-C exceptions.
2666 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2667                              const ToolChain &TC, bool KernelOrKext,
2668                              const ObjCRuntime &objcRuntime,
2669                              ArgStringList &CmdArgs) {
2670   const Driver &D = TC.getDriver();
2671   const llvm::Triple &Triple = TC.getTriple();
2672
2673   if (KernelOrKext) {
2674     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2675     // arguments now to avoid warnings about unused arguments.
2676     Args.ClaimAllArgs(options::OPT_fexceptions);
2677     Args.ClaimAllArgs(options::OPT_fno_exceptions);
2678     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2679     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2680     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2681     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2682     return;
2683   }
2684
2685   // See if the user explicitly enabled exceptions.
2686   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2687                          false);
2688
2689   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2690   // is not necessarily sensible, but follows GCC.
2691   if (types::isObjC(InputType) &&
2692       Args.hasFlag(options::OPT_fobjc_exceptions,
2693                    options::OPT_fno_objc_exceptions, true)) {
2694     CmdArgs.push_back("-fobjc-exceptions");
2695
2696     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2697   }
2698
2699   if (types::isCXX(InputType)) {
2700     // Disable C++ EH by default on XCore and PS4.
2701     bool CXXExceptionsEnabled =
2702         Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2703     Arg *ExceptionArg = Args.getLastArg(
2704         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2705         options::OPT_fexceptions, options::OPT_fno_exceptions);
2706     if (ExceptionArg)
2707       CXXExceptionsEnabled =
2708           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2709           ExceptionArg->getOption().matches(options::OPT_fexceptions);
2710
2711     if (CXXExceptionsEnabled) {
2712       if (Triple.isPS4CPU()) {
2713         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2714         assert(ExceptionArg &&
2715                "On the PS4 exceptions should only be enabled if passing "
2716                "an argument");
2717         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2718           const Arg *RTTIArg = TC.getRTTIArg();
2719           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2720           D.Diag(diag::err_drv_argument_not_allowed_with)
2721               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2722         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2723           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2724       } else
2725         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2726
2727       CmdArgs.push_back("-fcxx-exceptions");
2728
2729       EH = true;
2730     }
2731   }
2732
2733   if (EH)
2734     CmdArgs.push_back("-fexceptions");
2735 }
2736
2737 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2738   bool Default = true;
2739   if (TC.getTriple().isOSDarwin()) {
2740     // The native darwin assembler doesn't support the linker_option directives,
2741     // so we disable them if we think the .s file will be passed to it.
2742     Default = TC.useIntegratedAs();
2743   }
2744   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2745                        Default);
2746 }
2747
2748 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2749                                         const ToolChain &TC) {
2750   bool UseDwarfDirectory =
2751       Args.hasFlag(options::OPT_fdwarf_directory_asm,
2752                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2753   return !UseDwarfDirectory;
2754 }
2755
2756 /// \brief Check whether the given input tree contains any compilation actions.
2757 static bool ContainsCompileAction(const Action *A) {
2758   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2759     return true;
2760
2761   for (const auto &AI : A->inputs())
2762     if (ContainsCompileAction(AI))
2763       return true;
2764
2765   return false;
2766 }
2767
2768 /// \brief Check if -relax-all should be passed to the internal assembler.
2769 /// This is done by default when compiling non-assembler source with -O0.
2770 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2771   bool RelaxDefault = true;
2772
2773   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2774     RelaxDefault = A->getOption().matches(options::OPT_O0);
2775
2776   if (RelaxDefault) {
2777     RelaxDefault = false;
2778     for (const auto &Act : C.getActions()) {
2779       if (ContainsCompileAction(Act)) {
2780         RelaxDefault = true;
2781         break;
2782       }
2783     }
2784   }
2785
2786   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2787                       RelaxDefault);
2788 }
2789
2790 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2791 // to the corresponding DebugInfoKind.
2792 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2793   assert(A.getOption().matches(options::OPT_gN_Group) &&
2794          "Not a -g option that specifies a debug-info level");
2795   if (A.getOption().matches(options::OPT_g0) ||
2796       A.getOption().matches(options::OPT_ggdb0))
2797     return codegenoptions::NoDebugInfo;
2798   if (A.getOption().matches(options::OPT_gline_tables_only) ||
2799       A.getOption().matches(options::OPT_ggdb1))
2800     return codegenoptions::DebugLineTablesOnly;
2801   return codegenoptions::LimitedDebugInfo;
2802 }
2803
2804 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2805 // on mismatch. The StringRef input (rather than an Arg) allows
2806 // for use by the "-Xassembler" option parser.
2807 static unsigned DwarfVersionNum(StringRef ArgValue) {
2808   return llvm::StringSwitch<unsigned>(ArgValue)
2809       .Case("-gdwarf-2", 2)
2810       .Case("-gdwarf-3", 3)
2811       .Case("-gdwarf-4", 4)
2812       .Case("-gdwarf-5", 5)
2813       .Default(0);
2814 }
2815
2816 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2817                                     codegenoptions::DebugInfoKind DebugInfoKind,
2818                                     unsigned DwarfVersion,
2819                                     llvm::DebuggerKind DebuggerTuning) {
2820   switch (DebugInfoKind) {
2821   case codegenoptions::DebugLineTablesOnly:
2822     CmdArgs.push_back("-debug-info-kind=line-tables-only");
2823     break;
2824   case codegenoptions::LimitedDebugInfo:
2825     CmdArgs.push_back("-debug-info-kind=limited");
2826     break;
2827   case codegenoptions::FullDebugInfo:
2828     CmdArgs.push_back("-debug-info-kind=standalone");
2829     break;
2830   default:
2831     break;
2832   }
2833   if (DwarfVersion > 0)
2834     CmdArgs.push_back(
2835         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2836   switch (DebuggerTuning) {
2837   case llvm::DebuggerKind::GDB:
2838     CmdArgs.push_back("-debugger-tuning=gdb");
2839     break;
2840   case llvm::DebuggerKind::LLDB:
2841     CmdArgs.push_back("-debugger-tuning=lldb");
2842     break;
2843   case llvm::DebuggerKind::SCE:
2844     CmdArgs.push_back("-debugger-tuning=sce");
2845     break;
2846   default:
2847     break;
2848   }
2849 }
2850
2851 static void CollectArgsForIntegratedAssembler(Compilation &C,
2852                                               const ArgList &Args,
2853                                               ArgStringList &CmdArgs,
2854                                               const Driver &D) {
2855   if (UseRelaxAll(C, Args))
2856     CmdArgs.push_back("-mrelax-all");
2857
2858   // Only default to -mincremental-linker-compatible if we think we are
2859   // targeting the MSVC linker.
2860   bool DefaultIncrementalLinkerCompatible =
2861       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2862   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2863                    options::OPT_mno_incremental_linker_compatible,
2864                    DefaultIncrementalLinkerCompatible))
2865     CmdArgs.push_back("-mincremental-linker-compatible");
2866
2867   // When passing -I arguments to the assembler we sometimes need to
2868   // unconditionally take the next argument.  For example, when parsing
2869   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2870   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2871   // arg after parsing the '-I' arg.
2872   bool TakeNextArg = false;
2873
2874   // When using an integrated assembler, translate -Wa, and -Xassembler
2875   // options.
2876   bool CompressDebugSections = false;
2877
2878   bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
2879   const char *MipsTargetFeature = nullptr;
2880   for (const Arg *A :
2881        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2882     A->claim();
2883
2884     for (StringRef Value : A->getValues()) {
2885       if (TakeNextArg) {
2886         CmdArgs.push_back(Value.data());
2887         TakeNextArg = false;
2888         continue;
2889       }
2890
2891       switch (C.getDefaultToolChain().getArch()) {
2892       default:
2893         break;
2894       case llvm::Triple::mips:
2895       case llvm::Triple::mipsel:
2896       case llvm::Triple::mips64:
2897       case llvm::Triple::mips64el:
2898         if (Value == "--trap") {
2899           CmdArgs.push_back("-target-feature");
2900           CmdArgs.push_back("+use-tcc-in-div");
2901           continue;
2902         }
2903         if (Value == "--break") {
2904           CmdArgs.push_back("-target-feature");
2905           CmdArgs.push_back("-use-tcc-in-div");
2906           continue;
2907         }
2908         if (Value.startswith("-msoft-float")) {
2909           CmdArgs.push_back("-target-feature");
2910           CmdArgs.push_back("+soft-float");
2911           continue;
2912         }
2913         if (Value.startswith("-mhard-float")) {
2914           CmdArgs.push_back("-target-feature");
2915           CmdArgs.push_back("-soft-float");
2916           continue;
2917         }
2918
2919         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2920                                 .Case("-mips1", "+mips1")
2921                                 .Case("-mips2", "+mips2")
2922                                 .Case("-mips3", "+mips3")
2923                                 .Case("-mips4", "+mips4")
2924                                 .Case("-mips5", "+mips5")
2925                                 .Case("-mips32", "+mips32")
2926                                 .Case("-mips32r2", "+mips32r2")
2927                                 .Case("-mips32r3", "+mips32r3")
2928                                 .Case("-mips32r5", "+mips32r5")
2929                                 .Case("-mips32r6", "+mips32r6")
2930                                 .Case("-mips64", "+mips64")
2931                                 .Case("-mips64r2", "+mips64r2")
2932                                 .Case("-mips64r3", "+mips64r3")
2933                                 .Case("-mips64r5", "+mips64r5")
2934                                 .Case("-mips64r6", "+mips64r6")
2935                                 .Default(nullptr);
2936         if (MipsTargetFeature)
2937           continue;
2938       }
2939
2940       if (Value == "-force_cpusubtype_ALL") {
2941         // Do nothing, this is the default and we don't support anything else.
2942       } else if (Value == "-L") {
2943         CmdArgs.push_back("-msave-temp-labels");
2944       } else if (Value == "--fatal-warnings") {
2945         CmdArgs.push_back("-massembler-fatal-warnings");
2946       } else if (Value == "--noexecstack") {
2947         CmdArgs.push_back("-mnoexecstack");
2948       } else if (Value == "-compress-debug-sections" ||
2949                  Value == "--compress-debug-sections") {
2950         CompressDebugSections = true;
2951       } else if (Value == "-nocompress-debug-sections" ||
2952                  Value == "--nocompress-debug-sections") {
2953         CompressDebugSections = false;
2954       } else if (Value == "-mrelax-relocations=yes" ||
2955                  Value == "--mrelax-relocations=yes") {
2956         UseRelaxRelocations = true;
2957       } else if (Value == "-mrelax-relocations=no" ||
2958                  Value == "--mrelax-relocations=no") {
2959         UseRelaxRelocations = false;
2960       } else if (Value.startswith("-I")) {
2961         CmdArgs.push_back(Value.data());
2962         // We need to consume the next argument if the current arg is a plain
2963         // -I. The next arg will be the include directory.
2964         if (Value == "-I")
2965           TakeNextArg = true;
2966       } else if (Value.startswith("-gdwarf-")) {
2967         // "-gdwarf-N" options are not cc1as options.
2968         unsigned DwarfVersion = DwarfVersionNum(Value);
2969         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2970           CmdArgs.push_back(Value.data());
2971         } else {
2972           RenderDebugEnablingArgs(Args, CmdArgs,
2973                                   codegenoptions::LimitedDebugInfo,
2974                                   DwarfVersion, llvm::DebuggerKind::Default);
2975         }
2976       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2977                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2978         // Do nothing, we'll validate it later.
2979       } else {
2980         D.Diag(diag::err_drv_unsupported_option_argument)
2981             << A->getOption().getName() << Value;
2982       }
2983     }
2984   }
2985   if (CompressDebugSections) {
2986     if (llvm::zlib::isAvailable())
2987       CmdArgs.push_back("-compress-debug-sections");
2988     else
2989       D.Diag(diag::warn_debug_compression_unavailable);
2990   }
2991   if (UseRelaxRelocations)
2992     CmdArgs.push_back("--mrelax-relocations");
2993   if (MipsTargetFeature != nullptr) {
2994     CmdArgs.push_back("-target-feature");
2995     CmdArgs.push_back(MipsTargetFeature);
2996   }
2997 }
2998
2999 // This adds the static libclang_rt.builtins-arch.a directly to the command line
3000 // FIXME: Make sure we can also emit shared objects if they're requested
3001 // and available, check for possible errors, etc.
3002 static void addClangRT(const ToolChain &TC, const ArgList &Args,
3003                        ArgStringList &CmdArgs) {
3004   CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
3005 }
3006
3007 namespace {
3008 enum OpenMPRuntimeKind {
3009   /// An unknown OpenMP runtime. We can't generate effective OpenMP code
3010   /// without knowing what runtime to target.
3011   OMPRT_Unknown,
3012
3013   /// The LLVM OpenMP runtime. When completed and integrated, this will become
3014   /// the default for Clang.
3015   OMPRT_OMP,
3016
3017   /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
3018   /// this runtime but can swallow the pragmas, and find and link against the
3019   /// runtime library itself.
3020   OMPRT_GOMP,
3021
3022   /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
3023   /// OpenMP runtime. We support this mode for users with existing dependencies
3024   /// on this runtime library name.
3025   OMPRT_IOMP5
3026 };
3027 }
3028
3029 /// Compute the desired OpenMP runtime from the flag provided.
3030 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
3031                                           const ArgList &Args) {
3032   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
3033
3034   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
3035   if (A)
3036     RuntimeName = A->getValue();
3037
3038   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
3039                 .Case("libomp", OMPRT_OMP)
3040                 .Case("libgomp", OMPRT_GOMP)
3041                 .Case("libiomp5", OMPRT_IOMP5)
3042                 .Default(OMPRT_Unknown);
3043
3044   if (RT == OMPRT_Unknown) {
3045     if (A)
3046       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
3047           << A->getOption().getName() << A->getValue();
3048     else
3049       // FIXME: We could use a nicer diagnostic here.
3050       TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
3051   }
3052
3053   return RT;
3054 }
3055
3056 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
3057                               const ArgList &Args) {
3058   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3059                     options::OPT_fno_openmp, false))
3060     return;
3061
3062   switch (getOpenMPRuntime(TC, Args)) {
3063   case OMPRT_OMP:
3064     CmdArgs.push_back("-lomp");
3065     break;
3066   case OMPRT_GOMP:
3067     CmdArgs.push_back("-lgomp");
3068     break;
3069   case OMPRT_IOMP5:
3070     CmdArgs.push_back("-liomp5");
3071     break;
3072   case OMPRT_Unknown:
3073     // Already diagnosed.
3074     break;
3075   }
3076 }
3077
3078 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
3079                                 ArgStringList &CmdArgs, StringRef Sanitizer,
3080                                 bool IsShared, bool IsWhole) {
3081   // Wrap any static runtimes that must be forced into executable in
3082   // whole-archive.
3083   if (IsWhole) CmdArgs.push_back("-whole-archive");
3084   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
3085   if (IsWhole) CmdArgs.push_back("-no-whole-archive");
3086 }
3087
3088 // Tries to use a file with the list of dynamic symbols that need to be exported
3089 // from the runtime library. Returns true if the file was found.
3090 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
3091                                     ArgStringList &CmdArgs,
3092                                     StringRef Sanitizer) {
3093   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
3094   if (llvm::sys::fs::exists(SanRT + ".syms")) {
3095     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
3096     return true;
3097   }
3098   return false;
3099 }
3100
3101 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
3102                                      ArgStringList &CmdArgs) {
3103   // Force linking against the system libraries sanitizers depends on
3104   // (see PR15823 why this is necessary).
3105   CmdArgs.push_back("--no-as-needed");
3106   CmdArgs.push_back("-lpthread");
3107   CmdArgs.push_back("-lrt");
3108   CmdArgs.push_back("-lm");
3109   // There's no libdl on FreeBSD.
3110   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3111     CmdArgs.push_back("-ldl");
3112 }
3113
3114 static void
3115 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3116                          SmallVectorImpl<StringRef> &SharedRuntimes,
3117                          SmallVectorImpl<StringRef> &StaticRuntimes,
3118                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
3119                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
3120                          SmallVectorImpl<StringRef> &RequiredSymbols) {
3121   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
3122   // Collect shared runtimes.
3123   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
3124     SharedRuntimes.push_back("asan");
3125   }
3126   // The stats_client library is also statically linked into DSOs.
3127   if (SanArgs.needsStatsRt())
3128     StaticRuntimes.push_back("stats_client");
3129
3130   // Collect static runtimes.
3131   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
3132     // Don't link static runtimes into DSOs or if compiling for Android.
3133     return;
3134   }
3135   if (SanArgs.needsAsanRt()) {
3136     if (SanArgs.needsSharedAsanRt()) {
3137       HelperStaticRuntimes.push_back("asan-preinit");
3138     } else {
3139       StaticRuntimes.push_back("asan");
3140       if (SanArgs.linkCXXRuntimes())
3141         StaticRuntimes.push_back("asan_cxx");
3142     }
3143   }
3144   if (SanArgs.needsDfsanRt())
3145     StaticRuntimes.push_back("dfsan");
3146   if (SanArgs.needsLsanRt())
3147     StaticRuntimes.push_back("lsan");
3148   if (SanArgs.needsMsanRt()) {
3149     StaticRuntimes.push_back("msan");
3150     if (SanArgs.linkCXXRuntimes())
3151       StaticRuntimes.push_back("msan_cxx");
3152   }
3153   if (SanArgs.needsTsanRt()) {
3154     StaticRuntimes.push_back("tsan");
3155     if (SanArgs.linkCXXRuntimes())
3156       StaticRuntimes.push_back("tsan_cxx");
3157   }
3158   if (SanArgs.needsUbsanRt()) {
3159     StaticRuntimes.push_back("ubsan_standalone");
3160     if (SanArgs.linkCXXRuntimes())
3161       StaticRuntimes.push_back("ubsan_standalone_cxx");
3162   }
3163   if (SanArgs.needsSafeStackRt())
3164     StaticRuntimes.push_back("safestack");
3165   if (SanArgs.needsCfiRt())
3166     StaticRuntimes.push_back("cfi");
3167   if (SanArgs.needsCfiDiagRt()) {
3168     StaticRuntimes.push_back("cfi_diag");
3169     if (SanArgs.linkCXXRuntimes())
3170       StaticRuntimes.push_back("ubsan_standalone_cxx");
3171   }
3172   if (SanArgs.needsStatsRt()) {
3173     NonWholeStaticRuntimes.push_back("stats");
3174     RequiredSymbols.push_back("__sanitizer_stats_register");
3175   }
3176   if (SanArgs.needsEsanRt())
3177     StaticRuntimes.push_back("esan");
3178 }
3179
3180 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
3181 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
3182 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3183                                  ArgStringList &CmdArgs) {
3184   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
3185       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
3186   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
3187                            NonWholeStaticRuntimes, HelperStaticRuntimes,
3188                            RequiredSymbols);
3189   for (auto RT : SharedRuntimes)
3190     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
3191   for (auto RT : HelperStaticRuntimes)
3192     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3193   bool AddExportDynamic = false;
3194   for (auto RT : StaticRuntimes) {
3195     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3196     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3197   }
3198   for (auto RT : NonWholeStaticRuntimes) {
3199     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
3200     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3201   }
3202   for (auto S : RequiredSymbols) {
3203     CmdArgs.push_back("-u");
3204     CmdArgs.push_back(Args.MakeArgString(S));
3205   }
3206   // If there is a static runtime with no dynamic list, force all the symbols
3207   // to be dynamic to be sure we export sanitizer interface functions.
3208   if (AddExportDynamic)
3209     CmdArgs.push_back("-export-dynamic");
3210   return !StaticRuntimes.empty();
3211 }
3212
3213 static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
3214                            ArgStringList &CmdArgs) {
3215   if (Args.hasFlag(options::OPT_fxray_instrument,
3216                    options::OPT_fnoxray_instrument, false)) {
3217     CmdArgs.push_back("-whole-archive");
3218     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
3219     CmdArgs.push_back("-no-whole-archive");
3220     return true;
3221   }
3222   return false;
3223 }
3224
3225 static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
3226                                 ArgStringList &CmdArgs) {
3227   CmdArgs.push_back("--no-as-needed");
3228   CmdArgs.push_back("-lpthread");
3229   CmdArgs.push_back("-lrt");
3230   CmdArgs.push_back("-lm");
3231   CmdArgs.push_back("-latomic");
3232   if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3233     CmdArgs.push_back("-lc++");
3234   else
3235     CmdArgs.push_back("-lstdc++");
3236   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3237     CmdArgs.push_back("-ldl");
3238 }
3239
3240 static bool areOptimizationsEnabled(const ArgList &Args) {
3241   // Find the last -O arg and see if it is non-zero.
3242   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
3243     return !A->getOption().matches(options::OPT_O0);
3244   // Defaults to -O0.
3245   return false;
3246 }
3247
3248 static bool shouldUseFramePointerForTarget(const ArgList &Args,
3249                                            const llvm::Triple &Triple) {
3250   switch (Triple.getArch()) {
3251   case llvm::Triple::xcore:
3252   case llvm::Triple::wasm32:
3253   case llvm::Triple::wasm64:
3254     // XCore never wants frame pointers, regardless of OS.
3255     // WebAssembly never wants frame pointers.
3256     return false;
3257   default:
3258     break;
3259   }
3260
3261   if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
3262     switch (Triple.getArch()) {
3263     // Don't use a frame pointer on linux if optimizing for certain targets.
3264     case llvm::Triple::mips64:
3265     case llvm::Triple::mips64el:
3266     case llvm::Triple::mips:
3267     case llvm::Triple::mipsel:
3268     case llvm::Triple::systemz:
3269     case llvm::Triple::x86:
3270     case llvm::Triple::x86_64:
3271       return !areOptimizationsEnabled(Args);
3272     default:
3273       return true;
3274     }
3275   }
3276
3277   if (Triple.isOSWindows()) {
3278     switch (Triple.getArch()) {
3279     case llvm::Triple::x86:
3280       return !areOptimizationsEnabled(Args);
3281     case llvm::Triple::x86_64:
3282       return Triple.isOSBinFormatMachO();
3283     case llvm::Triple::arm:
3284     case llvm::Triple::thumb:
3285       // Windows on ARM builds with FPO disabled to aid fast stack walking
3286       return true;
3287     default:
3288       // All other supported Windows ISAs use xdata unwind information, so frame
3289       // pointers are not generally useful.
3290       return false;
3291     }
3292   }
3293
3294   return true;
3295 }
3296
3297 static bool shouldUseFramePointer(const ArgList &Args,
3298                                   const llvm::Triple &Triple) {
3299   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
3300                                options::OPT_fomit_frame_pointer))
3301     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
3302   if (Args.hasArg(options::OPT_pg))
3303     return true;
3304
3305   return shouldUseFramePointerForTarget(Args, Triple);
3306 }
3307
3308 static bool shouldUseLeafFramePointer(const ArgList &Args,
3309                                       const llvm::Triple &Triple) {
3310   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
3311                                options::OPT_momit_leaf_frame_pointer))
3312     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
3313   if (Args.hasArg(options::OPT_pg))
3314     return true;
3315
3316   if (Triple.isPS4CPU())
3317     return false;
3318
3319   return shouldUseFramePointerForTarget(Args, Triple);
3320 }
3321
3322 /// Add a CC1 option to specify the debug compilation directory.
3323 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
3324   SmallString<128> cwd;
3325   if (!llvm::sys::fs::current_path(cwd)) {
3326     CmdArgs.push_back("-fdebug-compilation-dir");
3327     CmdArgs.push_back(Args.MakeArgString(cwd));
3328   }
3329 }
3330
3331 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
3332   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3333   if (FinalOutput && Args.hasArg(options::OPT_c)) {
3334     SmallString<128> T(FinalOutput->getValue());
3335     llvm::sys::path::replace_extension(T, "dwo");
3336     return Args.MakeArgString(T);
3337   } else {
3338     // Use the compilation dir.
3339     SmallString<128> T(
3340         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
3341     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
3342     llvm::sys::path::replace_extension(F, "dwo");
3343     T += F;
3344     return Args.MakeArgString(F);
3345   }
3346 }
3347
3348 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
3349                            const JobAction &JA, const ArgList &Args,
3350                            const InputInfo &Output, const char *OutFile) {
3351   ArgStringList ExtractArgs;
3352   ExtractArgs.push_back("--extract-dwo");
3353
3354   ArgStringList StripArgs;
3355   StripArgs.push_back("--strip-dwo");
3356
3357   // Grabbing the output of the earlier compile step.
3358   StripArgs.push_back(Output.getFilename());
3359   ExtractArgs.push_back(Output.getFilename());
3360   ExtractArgs.push_back(OutFile);
3361
3362   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
3363   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
3364
3365   // First extract the dwo sections.
3366   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
3367
3368   // Then remove them from the original .o file.
3369   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
3370 }
3371
3372 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
3373 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
3374 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3375   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3376     if (A->getOption().matches(options::OPT_O4) ||
3377         A->getOption().matches(options::OPT_Ofast))
3378       return true;
3379
3380     if (A->getOption().matches(options::OPT_O0))
3381       return false;
3382
3383     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3384
3385     // Vectorize -Os.
3386     StringRef S(A->getValue());
3387     if (S == "s")
3388       return true;
3389
3390     // Don't vectorize -Oz, unless it's the slp vectorizer.
3391     if (S == "z")
3392       return isSlpVec;
3393
3394     unsigned OptLevel = 0;
3395     if (S.getAsInteger(10, OptLevel))
3396       return false;
3397
3398     return OptLevel > 1;
3399   }
3400
3401   return false;
3402 }
3403
3404 /// Add -x lang to \p CmdArgs for \p Input.
3405 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3406                              ArgStringList &CmdArgs) {
3407   // When using -verify-pch, we don't want to provide the type
3408   // 'precompiled-header' if it was inferred from the file extension
3409   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3410     return;
3411
3412   CmdArgs.push_back("-x");
3413   if (Args.hasArg(options::OPT_rewrite_objc))
3414     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3415   else
3416     CmdArgs.push_back(types::getTypeName(Input.getType()));
3417 }
3418
3419 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3420   if (Version < 100)
3421     return VersionTuple(Version);
3422
3423   if (Version < 10000)
3424     return VersionTuple(Version / 100, Version % 100);
3425
3426   unsigned Build = 0, Factor = 1;
3427   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3428     Build = Build + (Version % 10) * Factor;
3429   return VersionTuple(Version / 100, Version % 100, Build);
3430 }
3431
3432 // Claim options we don't want to warn if they are unused. We do this for
3433 // options that build systems might add but are unused when assembling or only
3434 // running the preprocessor for example.
3435 static void claimNoWarnArgs(const ArgList &Args) {
3436   // Don't warn about unused -f(no-)?lto.  This can happen when we're
3437   // preprocessing, precompiling or assembling.
3438   Args.ClaimAllArgs(options::OPT_flto_EQ);
3439   Args.ClaimAllArgs(options::OPT_flto);
3440   Args.ClaimAllArgs(options::OPT_fno_lto);
3441 }
3442
3443 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3444 #ifdef LLVM_ON_UNIX
3445   const char *Username = getenv("LOGNAME");
3446 #else
3447   const char *Username = getenv("USERNAME");
3448 #endif
3449   if (Username) {
3450     // Validate that LoginName can be used in a path, and get its length.
3451     size_t Len = 0;
3452     for (const char *P = Username; *P; ++P, ++Len) {
3453       if (!isAlphanumeric(*P) && *P != '_') {
3454         Username = nullptr;
3455         break;
3456       }
3457     }
3458
3459     if (Username && Len > 0) {
3460       Result.append(Username, Username + Len);
3461       return;
3462     }
3463   }
3464
3465 // Fallback to user id.
3466 #ifdef LLVM_ON_UNIX
3467   std::string UID = llvm::utostr(getuid());
3468 #else
3469   // FIXME: Windows seems to have an 'SID' that might work.
3470   std::string UID = "9999";
3471 #endif
3472   Result.append(UID.begin(), UID.end());
3473 }
3474
3475 VersionTuple visualstudio::getMSVCVersion(const Driver *D, const ToolChain &TC,
3476                                           const llvm::Triple &Triple,
3477                                           const llvm::opt::ArgList &Args,
3478                                           bool IsWindowsMSVC) {
3479   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3480                    IsWindowsMSVC) ||
3481       Args.hasArg(options::OPT_fmsc_version) ||
3482       Args.hasArg(options::OPT_fms_compatibility_version)) {
3483     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3484     const Arg *MSCompatibilityVersion =
3485         Args.getLastArg(options::OPT_fms_compatibility_version);
3486
3487     if (MSCVersion && MSCompatibilityVersion) {
3488       if (D)
3489         D->Diag(diag::err_drv_argument_not_allowed_with)
3490             << MSCVersion->getAsString(Args)
3491             << MSCompatibilityVersion->getAsString(Args);
3492       return VersionTuple();
3493     }
3494
3495     if (MSCompatibilityVersion) {
3496       VersionTuple MSVT;
3497       if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3498         D->Diag(diag::err_drv_invalid_value)
3499             << MSCompatibilityVersion->getAsString(Args)
3500             << MSCompatibilityVersion->getValue();
3501       return MSVT;
3502     }
3503
3504     if (MSCVersion) {
3505       unsigned Version = 0;
3506       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3507         D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3508                                              << MSCVersion->getValue();
3509       return getMSCompatibilityVersion(Version);
3510     }
3511
3512     unsigned Major, Minor, Micro;
3513     Triple.getEnvironmentVersion(Major, Minor, Micro);
3514     if (Major || Minor || Micro)
3515       return VersionTuple(Major, Minor, Micro);
3516
3517     if (IsWindowsMSVC) {
3518       VersionTuple MSVT = TC.getMSVCVersionFromExe();
3519       if (!MSVT.empty())
3520         return MSVT;
3521
3522       // FIXME: Consider bumping this to 19 (MSVC2015) soon.
3523       return VersionTuple(18);
3524     }
3525   }
3526   return VersionTuple();
3527 }
3528
3529 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3530                                    const InputInfo &Output, const ArgList &Args,
3531                                    ArgStringList &CmdArgs) {
3532
3533   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
3534                                          options::OPT_fprofile_generate_EQ,
3535                                          options::OPT_fno_profile_generate);
3536   if (PGOGenerateArg &&
3537       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
3538     PGOGenerateArg = nullptr;
3539
3540   auto *ProfileGenerateArg = Args.getLastArg(
3541       options::OPT_fprofile_instr_generate,
3542       options::OPT_fprofile_instr_generate_EQ,
3543       options::OPT_fno_profile_instr_generate);
3544   if (ProfileGenerateArg &&
3545       ProfileGenerateArg->getOption().matches(
3546           options::OPT_fno_profile_instr_generate))
3547     ProfileGenerateArg = nullptr;
3548
3549   if (PGOGenerateArg && ProfileGenerateArg)
3550     D.Diag(diag::err_drv_argument_not_allowed_with)
3551         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
3552
3553   auto *ProfileUseArg = Args.getLastArg(
3554       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3555       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3556       options::OPT_fno_profile_instr_use);
3557   if (ProfileUseArg &&
3558       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3559     ProfileUseArg = nullptr;
3560
3561   if (PGOGenerateArg && ProfileUseArg)
3562     D.Diag(diag::err_drv_argument_not_allowed_with)
3563         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
3564
3565   if (ProfileGenerateArg && ProfileUseArg)
3566     D.Diag(diag::err_drv_argument_not_allowed_with)
3567         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3568
3569   if (ProfileGenerateArg) {
3570     if (ProfileGenerateArg->getOption().matches(
3571             options::OPT_fprofile_instr_generate_EQ))
3572       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
3573                                            ProfileGenerateArg->getValue()));
3574     // The default is to use Clang Instrumentation.
3575     CmdArgs.push_back("-fprofile-instrument=clang");
3576   }
3577
3578   if (PGOGenerateArg) {
3579     CmdArgs.push_back("-fprofile-instrument=llvm");
3580     if (PGOGenerateArg->getOption().matches(
3581             options::OPT_fprofile_generate_EQ)) {
3582       SmallString<128> Path(PGOGenerateArg->getValue());
3583       llvm::sys::path::append(Path, "default.profraw");
3584       CmdArgs.push_back(
3585           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
3586     }
3587   }
3588
3589   if (ProfileUseArg) {
3590     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3591       CmdArgs.push_back(Args.MakeArgString(
3592           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
3593     else if ((ProfileUseArg->getOption().matches(
3594                   options::OPT_fprofile_use_EQ) ||
3595               ProfileUseArg->getOption().matches(
3596                   options::OPT_fprofile_instr_use))) {
3597       SmallString<128> Path(
3598           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3599       if (Path.empty() || llvm::sys::fs::is_directory(Path))
3600         llvm::sys::path::append(Path, "default.profdata");
3601       CmdArgs.push_back(
3602           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
3603     }
3604   }
3605
3606   if (Args.hasArg(options::OPT_ftest_coverage) ||
3607       Args.hasArg(options::OPT_coverage))
3608     CmdArgs.push_back("-femit-coverage-notes");
3609   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3610                    false) ||
3611       Args.hasArg(options::OPT_coverage))
3612     CmdArgs.push_back("-femit-coverage-data");
3613
3614   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3615                    options::OPT_fno_coverage_mapping, false) &&
3616       !ProfileGenerateArg)
3617     D.Diag(diag::err_drv_argument_only_allowed_with)
3618         << "-fcoverage-mapping"
3619         << "-fprofile-instr-generate";
3620
3621   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3622                    options::OPT_fno_coverage_mapping, false))
3623     CmdArgs.push_back("-fcoverage-mapping");
3624
3625   if (C.getArgs().hasArg(options::OPT_c) ||
3626       C.getArgs().hasArg(options::OPT_S)) {
3627     if (Output.isFilename()) {
3628       CmdArgs.push_back("-coverage-file");
3629       SmallString<128> CoverageFilename;
3630       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3631         CoverageFilename = FinalOutput->getValue();
3632       } else {
3633         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3634       }
3635       if (llvm::sys::path::is_relative(CoverageFilename)) {
3636         SmallString<128> Pwd;
3637         if (!llvm::sys::fs::current_path(Pwd)) {
3638           llvm::sys::path::append(Pwd, CoverageFilename);
3639           CoverageFilename.swap(Pwd);
3640         }
3641       }
3642       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3643     }
3644   }
3645 }
3646
3647 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3648                                 ArgStringList &CmdArgs) {
3649   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3650                     false) ||
3651        Args.hasFlag(options::OPT_fprofile_generate,
3652                     options::OPT_fno_profile_instr_generate, false) ||
3653        Args.hasFlag(options::OPT_fprofile_generate_EQ,
3654                     options::OPT_fno_profile_instr_generate, false) ||
3655        Args.hasFlag(options::OPT_fprofile_instr_generate,
3656                     options::OPT_fno_profile_instr_generate, false) ||
3657        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3658                     options::OPT_fno_profile_instr_generate, false) ||
3659        Args.hasArg(options::OPT_fcreate_profile) ||
3660        Args.hasArg(options::OPT_coverage)))
3661     CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3662 }
3663
3664 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
3665 /// smooshes them together with platform defaults, to decide whether
3666 /// this compile should be using PIC mode or not. Returns a tuple of
3667 /// (RelocationModel, PICLevel, IsPIE).
3668 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3669 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3670              const ArgList &Args) {
3671   // FIXME: why does this code...and so much everywhere else, use both
3672   // ToolChain.getTriple() and Triple?
3673   bool PIE = ToolChain.isPIEDefault();
3674   bool PIC = PIE || ToolChain.isPICDefault();
3675   // The Darwin/MachO default to use PIC does not apply when using -static.
3676   if (ToolChain.getTriple().isOSBinFormatMachO() &&
3677       Args.hasArg(options::OPT_static))
3678     PIE = PIC = false;
3679   bool IsPICLevelTwo = PIC;
3680
3681   bool KernelOrKext =
3682       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3683
3684   // Android-specific defaults for PIC/PIE
3685   if (ToolChain.getTriple().isAndroid()) {
3686     switch (ToolChain.getArch()) {
3687     case llvm::Triple::arm:
3688     case llvm::Triple::armeb:
3689     case llvm::Triple::thumb:
3690     case llvm::Triple::thumbeb:
3691     case llvm::Triple::aarch64:
3692     case llvm::Triple::mips:
3693     case llvm::Triple::mipsel:
3694     case llvm::Triple::mips64:
3695     case llvm::Triple::mips64el:
3696       PIC = true; // "-fpic"
3697       break;
3698
3699     case llvm::Triple::x86:
3700     case llvm::Triple::x86_64:
3701       PIC = true; // "-fPIC"
3702       IsPICLevelTwo = true;
3703       break;
3704
3705     default:
3706       break;
3707     }
3708   }
3709
3710   // OpenBSD-specific defaults for PIE
3711   if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3712     switch (ToolChain.getArch()) {
3713     case llvm::Triple::mips64:
3714     case llvm::Triple::mips64el:
3715     case llvm::Triple::sparcel:
3716     case llvm::Triple::x86:
3717     case llvm::Triple::x86_64:
3718       IsPICLevelTwo = false; // "-fpie"
3719       break;
3720
3721     case llvm::Triple::ppc:
3722     case llvm::Triple::sparc:
3723     case llvm::Triple::sparcv9:
3724       IsPICLevelTwo = true; // "-fPIE"
3725       break;
3726
3727     default:
3728       break;
3729     }
3730   }
3731
3732   // The last argument relating to either PIC or PIE wins, and no
3733   // other argument is used. If the last argument is any flavor of the
3734   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3735   // option implicitly enables PIC at the same level.
3736   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3737                                     options::OPT_fpic, options::OPT_fno_pic,
3738                                     options::OPT_fPIE, options::OPT_fno_PIE,
3739                                     options::OPT_fpie, options::OPT_fno_pie);
3740   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3741   // is forced, then neither PIC nor PIE flags will have no effect.
3742   if (!ToolChain.isPICDefaultForced()) {
3743     if (LastPICArg) {
3744       Option O = LastPICArg->getOption();
3745       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3746           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3747         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3748         PIC =
3749             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3750         IsPICLevelTwo =
3751             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3752       } else {
3753         PIE = PIC = false;
3754         if (Triple.isPS4CPU()) {
3755           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3756           StringRef Model = ModelArg ? ModelArg->getValue() : "";
3757           if (Model != "kernel") {
3758             PIC = true;
3759             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3760                 << LastPICArg->getSpelling();
3761           }
3762         }
3763       }
3764     }
3765   }
3766
3767   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3768   // PIC level would've been set to level 1, force it back to level 2 PIC
3769   // instead.
3770   if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3771     IsPICLevelTwo |= ToolChain.isPICDefault();
3772
3773   // This kernel flags are a trump-card: they will disable PIC/PIE
3774   // generation, independent of the argument order.
3775   if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3776                        !Triple.isWatchOS()))
3777     PIC = PIE = false;
3778
3779   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3780     // This is a very special mode. It trumps the other modes, almost no one
3781     // uses it, and it isn't even valid on any OS but Darwin.
3782     if (!ToolChain.getTriple().isOSDarwin())
3783       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3784           << A->getSpelling() << ToolChain.getTriple().str();
3785
3786     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3787
3788     // Only a forced PIC mode can cause the actual compile to have PIC defines
3789     // etc., no flags are sufficient. This behavior was selected to closely
3790     // match that of llvm-gcc and Apple GCC before that.
3791     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3792
3793     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3794   }
3795
3796   if (PIC)
3797     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3798
3799   return std::make_tuple(llvm::Reloc::Static, 0, false);
3800 }
3801
3802 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3803   switch (Model) {
3804   case llvm::Reloc::Static:
3805     return "static";
3806   case llvm::Reloc::PIC_:
3807     return "pic";
3808   case llvm::Reloc::DynamicNoPIC:
3809     return "dynamic-no-pic";
3810   }
3811   llvm_unreachable("Unknown Reloc::Model kind");
3812 }
3813
3814 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3815                              ArgStringList &CmdArgs) {
3816   llvm::Reloc::Model RelocationModel;
3817   unsigned PICLevel;
3818   bool IsPIE;
3819   std::tie(RelocationModel, PICLevel, IsPIE) =
3820       ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3821
3822   if (RelocationModel != llvm::Reloc::Static)
3823     CmdArgs.push_back("-KPIC");
3824 }
3825
3826 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3827                          const InputInfo &Output, const InputInfoList &Inputs,
3828                          const ArgList &Args, const char *LinkingOutput) const {
3829   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3830   const llvm::Triple Triple(TripleStr);
3831
3832   bool KernelOrKext =
3833       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3834   const Driver &D = getToolChain().getDriver();
3835   ArgStringList CmdArgs;
3836
3837   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3838   bool IsWindowsCygnus =
3839       getToolChain().getTriple().isWindowsCygwinEnvironment();
3840   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3841   bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3842   bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
3843
3844   // Check number of inputs for sanity. We need at least one input.
3845   assert(Inputs.size() >= 1 && "Must have at least one input.");
3846   const InputInfo &Input = Inputs[0];
3847   // CUDA compilation may have multiple inputs (source file + results of
3848   // device-side compilations). All other jobs are expected to have exactly one
3849   // input.
3850   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3851   assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3852
3853   // C++ is not supported for IAMCU.
3854   if (IsIAMCU && types::isCXX(Input.getType()))
3855     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3856
3857   // Invoke ourselves in -cc1 mode.
3858   //
3859   // FIXME: Implement custom jobs for internal actions.
3860   CmdArgs.push_back("-cc1");
3861
3862   // Add the "effective" target triple.
3863   CmdArgs.push_back("-triple");
3864   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3865
3866   if (IsCuda) {
3867     // We have to pass the triple of the host if compiling for a CUDA device and
3868     // vice-versa.
3869     std::string NormalizedTriple;
3870     if (JA.isDeviceOffloading(Action::OFK_Cuda))
3871       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3872                              ->getTriple()
3873                              .normalize();
3874     else
3875       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3876                              ->getTriple()
3877                              .normalize();
3878
3879     CmdArgs.push_back("-aux-triple");
3880     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3881   }
3882
3883   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3884                                Triple.getArch() == llvm::Triple::thumb)) {
3885     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3886     unsigned Version;
3887     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3888     if (Version < 7)
3889       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3890                                                 << TripleStr;
3891   }
3892
3893   // Push all default warning arguments that are specific to
3894   // the given target.  These come before user provided warning options
3895   // are provided.
3896   getToolChain().addClangWarningOptions(CmdArgs);
3897
3898   // Select the appropriate action.
3899   RewriteKind rewriteKind = RK_None;
3900
3901   if (isa<AnalyzeJobAction>(JA)) {
3902     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3903     CmdArgs.push_back("-analyze");
3904   } else if (isa<MigrateJobAction>(JA)) {
3905     CmdArgs.push_back("-migrate");
3906   } else if (isa<PreprocessJobAction>(JA)) {
3907     if (Output.getType() == types::TY_Dependencies)
3908       CmdArgs.push_back("-Eonly");
3909     else {
3910       CmdArgs.push_back("-E");
3911       if (Args.hasArg(options::OPT_rewrite_objc) &&
3912           !Args.hasArg(options::OPT_g_Group))
3913         CmdArgs.push_back("-P");
3914     }
3915   } else if (isa<AssembleJobAction>(JA)) {
3916     CmdArgs.push_back("-emit-obj");
3917
3918     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3919
3920     // Also ignore explicit -force_cpusubtype_ALL option.
3921     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3922   } else if (isa<PrecompileJobAction>(JA)) {
3923     // Use PCH if the user requested it.
3924     bool UsePCH = D.CCCUsePCH;
3925
3926     if (JA.getType() == types::TY_Nothing)
3927       CmdArgs.push_back("-fsyntax-only");
3928     else if (UsePCH)
3929       CmdArgs.push_back("-emit-pch");
3930     else
3931       CmdArgs.push_back("-emit-pth");
3932   } else if (isa<VerifyPCHJobAction>(JA)) {
3933     CmdArgs.push_back("-verify-pch");
3934   } else {
3935     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3936            "Invalid action for clang tool.");
3937     if (JA.getType() == types::TY_Nothing) {
3938       CmdArgs.push_back("-fsyntax-only");
3939     } else if (JA.getType() == types::TY_LLVM_IR ||
3940                JA.getType() == types::TY_LTO_IR) {
3941       CmdArgs.push_back("-emit-llvm");
3942     } else if (JA.getType() == types::TY_LLVM_BC ||
3943                JA.getType() == types::TY_LTO_BC) {
3944       CmdArgs.push_back("-emit-llvm-bc");
3945     } else if (JA.getType() == types::TY_PP_Asm) {
3946       CmdArgs.push_back("-S");
3947     } else if (JA.getType() == types::TY_AST) {
3948       CmdArgs.push_back("-emit-pch");
3949     } else if (JA.getType() == types::TY_ModuleFile) {
3950       CmdArgs.push_back("-module-file-info");
3951     } else if (JA.getType() == types::TY_RewrittenObjC) {
3952       CmdArgs.push_back("-rewrite-objc");
3953       rewriteKind = RK_NonFragile;
3954     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3955       CmdArgs.push_back("-rewrite-objc");
3956       rewriteKind = RK_Fragile;
3957     } else {
3958       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3959     }
3960
3961     // Preserve use-list order by default when emitting bitcode, so that
3962     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3963     // same result as running passes here.  For LTO, we don't need to preserve
3964     // the use-list order, since serialization to bitcode is part of the flow.
3965     if (JA.getType() == types::TY_LLVM_BC)
3966       CmdArgs.push_back("-emit-llvm-uselists");
3967
3968     if (D.isUsingLTO())
3969       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3970   }
3971
3972   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3973     if (!types::isLLVMIR(Input.getType()))
3974       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3975                                                        << "-x ir";
3976     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3977   }
3978
3979   // Embed-bitcode option.
3980   if (C.getDriver().embedBitcodeEnabled() &&
3981       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3982     // Add flags implied by -fembed-bitcode.
3983     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3984     // Disable all llvm IR level optimizations.
3985     CmdArgs.push_back("-disable-llvm-optzns");
3986   }
3987   if (C.getDriver().embedBitcodeMarkerOnly())
3988     CmdArgs.push_back("-fembed-bitcode=marker");
3989
3990   // We normally speed up the clang process a bit by skipping destructors at
3991   // exit, but when we're generating diagnostics we can rely on some of the
3992   // cleanup.
3993   if (!C.isForDiagnostics())
3994     CmdArgs.push_back("-disable-free");
3995
3996 // Disable the verification pass in -asserts builds.
3997 #ifdef NDEBUG
3998   CmdArgs.push_back("-disable-llvm-verifier");
3999   // Discard LLVM value names in -asserts builds.
4000   CmdArgs.push_back("-discard-value-names");
4001 #endif
4002
4003   // Set the main file name, so that debug info works even with
4004   // -save-temps.
4005   CmdArgs.push_back("-main-file-name");
4006   CmdArgs.push_back(getBaseInputName(Args, Input));
4007
4008   // Some flags which affect the language (via preprocessor
4009   // defines).
4010   if (Args.hasArg(options::OPT_static))
4011     CmdArgs.push_back("-static-define");
4012
4013   if (isa<AnalyzeJobAction>(JA)) {
4014     // Enable region store model by default.
4015     CmdArgs.push_back("-analyzer-store=region");
4016
4017     // Treat blocks as analysis entry points.
4018     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
4019
4020     CmdArgs.push_back("-analyzer-eagerly-assume");
4021
4022     // Add default argument set.
4023     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
4024       CmdArgs.push_back("-analyzer-checker=core");
4025
4026     if (!IsWindowsMSVC) {
4027       CmdArgs.push_back("-analyzer-checker=unix");
4028     } else {
4029       // Enable "unix" checkers that also work on Windows.
4030       CmdArgs.push_back("-analyzer-checker=unix.API");
4031       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
4032       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
4033       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
4034       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
4035       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
4036     }
4037
4038       // Disable some unix checkers for PS4.
4039       if (IsPS4CPU) {
4040         CmdArgs.push_back("-analyzer-disable-checker=unix.API");
4041         CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
4042       }
4043
4044       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
4045         CmdArgs.push_back("-analyzer-checker=osx");
4046
4047       CmdArgs.push_back("-analyzer-checker=deadcode");
4048
4049       if (types::isCXX(Input.getType()))
4050         CmdArgs.push_back("-analyzer-checker=cplusplus");
4051
4052       if (!IsPS4CPU) {
4053         CmdArgs.push_back(
4054             "-analyzer-checker=security.insecureAPI.UncheckedReturn");
4055         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
4056         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
4057         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
4058         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
4059         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
4060       }
4061
4062       // Default nullability checks.
4063       CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
4064       CmdArgs.push_back(
4065           "-analyzer-checker=nullability.NullReturnedFromNonnull");
4066     }
4067
4068     // Set the output format. The default is plist, for (lame) historical
4069     // reasons.
4070     CmdArgs.push_back("-analyzer-output");
4071     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
4072       CmdArgs.push_back(A->getValue());
4073     else
4074       CmdArgs.push_back("plist");
4075
4076     // Disable the presentation of standard compiler warnings when
4077     // using --analyze.  We only want to show static analyzer diagnostics
4078     // or frontend errors.
4079     CmdArgs.push_back("-w");
4080
4081     // Add -Xanalyzer arguments when running as analyzer.
4082     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
4083   }
4084
4085   CheckCodeGenerationOptions(D, Args);
4086
4087   llvm::Reloc::Model RelocationModel;
4088   unsigned PICLevel;
4089   bool IsPIE;
4090   std::tie(RelocationModel, PICLevel, IsPIE) =
4091       ParsePICArgs(getToolChain(), Triple, Args);
4092
4093   const char *RMName = RelocationModelName(RelocationModel);
4094   if (RMName) {
4095     CmdArgs.push_back("-mrelocation-model");
4096     CmdArgs.push_back(RMName);
4097   }
4098   if (PICLevel > 0) {
4099     CmdArgs.push_back("-pic-level");
4100     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4101     if (IsPIE)
4102       CmdArgs.push_back("-pic-is-pie");
4103   }
4104
4105   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4106     CmdArgs.push_back("-meabi");
4107     CmdArgs.push_back(A->getValue());
4108   }
4109
4110   CmdArgs.push_back("-mthread-model");
4111   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
4112     CmdArgs.push_back(A->getValue());
4113   else
4114     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
4115
4116   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4117
4118   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
4119                     options::OPT_fno_merge_all_constants))
4120     CmdArgs.push_back("-fno-merge-all-constants");
4121
4122   // LLVM Code Generator Options.
4123
4124   if (Args.hasArg(options::OPT_frewrite_map_file) ||
4125       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
4126     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
4127                                       options::OPT_frewrite_map_file_EQ)) {
4128       CmdArgs.push_back("-frewrite-map-file");
4129       CmdArgs.push_back(A->getValue());
4130       A->claim();
4131     }
4132   }
4133
4134   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4135     StringRef v = A->getValue();
4136     CmdArgs.push_back("-mllvm");
4137     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4138     A->claim();
4139   }
4140
4141   if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4142                     true))
4143     CmdArgs.push_back("-fno-jump-tables");
4144
4145   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4146     CmdArgs.push_back("-mregparm");
4147     CmdArgs.push_back(A->getValue());
4148   }
4149
4150   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4151                                options::OPT_freg_struct_return)) {
4152     if (getToolChain().getArch() != llvm::Triple::x86) {
4153       D.Diag(diag::err_drv_unsupported_opt_for_target)
4154           << A->getSpelling() << getToolChain().getTriple().str();
4155     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4156       CmdArgs.push_back("-fpcc-struct-return");
4157     } else {
4158       assert(A->getOption().matches(options::OPT_freg_struct_return));
4159       CmdArgs.push_back("-freg-struct-return");
4160     }
4161   }
4162
4163   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4164     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4165
4166   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
4167     CmdArgs.push_back("-mdisable-fp-elim");
4168   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4169                     options::OPT_fno_zero_initialized_in_bss))
4170     CmdArgs.push_back("-mno-zero-initialized-in-bss");
4171
4172   bool OFastEnabled = isOptimizationLevelFast(Args);
4173   // If -Ofast is the optimization level, then -fstrict-aliasing should be
4174   // enabled.  This alias option is being used to simplify the hasFlag logic.
4175   OptSpecifier StrictAliasingAliasOption =
4176       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4177   // We turn strict aliasing off by default if we're in CL mode, since MSVC
4178   // doesn't do any TBAA.
4179   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
4180   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4181                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4182     CmdArgs.push_back("-relaxed-aliasing");
4183   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4184                     options::OPT_fno_struct_path_tbaa))
4185     CmdArgs.push_back("-no-struct-path-tbaa");
4186   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4187                    false))
4188     CmdArgs.push_back("-fstrict-enums");
4189   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4190                    options::OPT_fno_strict_vtable_pointers,
4191                    false))
4192     CmdArgs.push_back("-fstrict-vtable-pointers");
4193   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4194                     options::OPT_fno_optimize_sibling_calls))
4195     CmdArgs.push_back("-mdisable-tail-calls");
4196
4197   // Handle segmented stacks.
4198   if (Args.hasArg(options::OPT_fsplit_stack))
4199     CmdArgs.push_back("-split-stacks");
4200
4201   // If -Ofast is the optimization level, then -ffast-math should be enabled.
4202   // This alias option is being used to simplify the getLastArg logic.
4203   OptSpecifier FastMathAliasOption =
4204       OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
4205
4206   // Handle various floating point optimization flags, mapping them to the
4207   // appropriate LLVM code generation flags. The pattern for all of these is to
4208   // default off the codegen optimizations, and if any flag enables them and no
4209   // flag disables them after the flag enabling them, enable the codegen
4210   // optimization. This is complicated by several "umbrella" flags.
4211   if (Arg *A = Args.getLastArg(
4212           options::OPT_ffast_math, FastMathAliasOption,
4213           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4214           options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
4215           options::OPT_fno_honor_infinities))
4216     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4217         A->getOption().getID() != options::OPT_fno_finite_math_only &&
4218         A->getOption().getID() != options::OPT_fhonor_infinities)
4219       CmdArgs.push_back("-menable-no-infs");
4220   if (Arg *A = Args.getLastArg(
4221           options::OPT_ffast_math, FastMathAliasOption,
4222           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4223           options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
4224           options::OPT_fno_honor_nans))
4225     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4226         A->getOption().getID() != options::OPT_fno_finite_math_only &&
4227         A->getOption().getID() != options::OPT_fhonor_nans)
4228       CmdArgs.push_back("-menable-no-nans");
4229
4230   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
4231   bool MathErrno = getToolChain().IsMathErrnoDefault();
4232   if (Arg *A =
4233           Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4234                           options::OPT_fno_fast_math, options::OPT_fmath_errno,
4235                           options::OPT_fno_math_errno)) {
4236     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
4237     // However, turning *off* -ffast_math merely restores the toolchain default
4238     // (which may be false).
4239     if (A->getOption().getID() == options::OPT_fno_math_errno ||
4240         A->getOption().getID() == options::OPT_ffast_math ||
4241         A->getOption().getID() == options::OPT_Ofast)
4242       MathErrno = false;
4243     else if (A->getOption().getID() == options::OPT_fmath_errno)
4244       MathErrno = true;
4245   }
4246   if (MathErrno)
4247     CmdArgs.push_back("-fmath-errno");
4248
4249   // There are several flags which require disabling very specific
4250   // optimizations. Any of these being disabled forces us to turn off the
4251   // entire set of LLVM optimizations, so collect them through all the flag
4252   // madness.
4253   bool AssociativeMath = false;
4254   if (Arg *A = Args.getLastArg(
4255           options::OPT_ffast_math, FastMathAliasOption,
4256           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4257           options::OPT_fno_unsafe_math_optimizations,
4258           options::OPT_fassociative_math, options::OPT_fno_associative_math))
4259     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4260         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4261         A->getOption().getID() != options::OPT_fno_associative_math)
4262       AssociativeMath = true;
4263   bool ReciprocalMath = false;
4264   if (Arg *A = Args.getLastArg(
4265           options::OPT_ffast_math, FastMathAliasOption,
4266           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4267           options::OPT_fno_unsafe_math_optimizations,
4268           options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
4269     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4270         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4271         A->getOption().getID() != options::OPT_fno_reciprocal_math)
4272       ReciprocalMath = true;
4273   bool SignedZeros = true;
4274   if (Arg *A = Args.getLastArg(
4275           options::OPT_ffast_math, FastMathAliasOption,
4276           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4277           options::OPT_fno_unsafe_math_optimizations,
4278           options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
4279     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4280         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4281         A->getOption().getID() != options::OPT_fsigned_zeros)
4282       SignedZeros = false;
4283   bool TrappingMath = true;
4284   if (Arg *A = Args.getLastArg(
4285           options::OPT_ffast_math, FastMathAliasOption,
4286           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4287           options::OPT_fno_unsafe_math_optimizations,
4288           options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
4289     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4290         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4291         A->getOption().getID() != options::OPT_ftrapping_math)
4292       TrappingMath = false;
4293   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
4294       !TrappingMath)
4295     CmdArgs.push_back("-menable-unsafe-fp-math");
4296
4297   if (!SignedZeros)
4298     CmdArgs.push_back("-fno-signed-zeros");
4299
4300   if (ReciprocalMath)
4301     CmdArgs.push_back("-freciprocal-math");
4302
4303   // Validate and pass through -fp-contract option.
4304   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4305                                options::OPT_fno_fast_math,
4306                                options::OPT_ffp_contract)) {
4307     if (A->getOption().getID() == options::OPT_ffp_contract) {
4308       StringRef Val = A->getValue();
4309       if (Val == "fast" || Val == "on" || Val == "off") {
4310         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
4311       } else {
4312         D.Diag(diag::err_drv_unsupported_option_argument)
4313             << A->getOption().getName() << Val;
4314       }
4315     } else if (A->getOption().matches(options::OPT_ffast_math) ||
4316                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
4317       // If fast-math is set then set the fp-contract mode to fast.
4318       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
4319     }
4320   }
4321
4322   ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
4323
4324   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
4325   // and if we find them, tell the frontend to provide the appropriate
4326   // preprocessor macros. This is distinct from enabling any optimizations as
4327   // these options induce language changes which must survive serialization
4328   // and deserialization, etc.
4329   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4330                                options::OPT_fno_fast_math))
4331     if (!A->getOption().matches(options::OPT_fno_fast_math))
4332       CmdArgs.push_back("-ffast-math");
4333   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
4334                                options::OPT_fno_fast_math))
4335     if (A->getOption().matches(options::OPT_ffinite_math_only))
4336       CmdArgs.push_back("-ffinite-math-only");
4337
4338   // Decide whether to use verbose asm. Verbose assembly is the default on
4339   // toolchains which have the integrated assembler on by default.
4340   bool IsIntegratedAssemblerDefault =
4341       getToolChain().IsIntegratedAssemblerDefault();
4342   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4343                    IsIntegratedAssemblerDefault) ||
4344       Args.hasArg(options::OPT_dA))
4345     CmdArgs.push_back("-masm-verbose");
4346
4347   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
4348                     IsIntegratedAssemblerDefault))
4349     CmdArgs.push_back("-no-integrated-as");
4350
4351   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4352     CmdArgs.push_back("-mdebug-pass");
4353     CmdArgs.push_back("Structure");
4354   }
4355   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4356     CmdArgs.push_back("-mdebug-pass");
4357     CmdArgs.push_back("Arguments");
4358   }
4359
4360   // Enable -mconstructor-aliases except on darwin, where we have to work around
4361   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4362   // aliases aren't supported.
4363   if (!getToolChain().getTriple().isOSDarwin() &&
4364       !getToolChain().getTriple().isNVPTX())
4365     CmdArgs.push_back("-mconstructor-aliases");
4366
4367   // Darwin's kernel doesn't support guard variables; just die if we
4368   // try to use them.
4369   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
4370     CmdArgs.push_back("-fforbid-guard-variables");
4371
4372   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4373                    false)) {
4374     CmdArgs.push_back("-mms-bitfields");
4375   }
4376
4377   // This is a coarse approximation of what llvm-gcc actually does, both
4378   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4379   // complicated ways.
4380   bool AsynchronousUnwindTables =
4381       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4382                    options::OPT_fno_asynchronous_unwind_tables,
4383                    (getToolChain().IsUnwindTablesDefault() ||
4384                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
4385                        !KernelOrKext);
4386   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4387                    AsynchronousUnwindTables))
4388     CmdArgs.push_back("-munwind-tables");
4389
4390   getToolChain().addClangTargetOptions(Args, CmdArgs);
4391
4392   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
4393     CmdArgs.push_back("-mlimit-float-precision");
4394     CmdArgs.push_back(A->getValue());
4395   }
4396
4397   // FIXME: Handle -mtune=.
4398   (void)Args.hasArg(options::OPT_mtune_EQ);
4399
4400   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4401     CmdArgs.push_back("-mcode-model");
4402     CmdArgs.push_back(A->getValue());
4403   }
4404
4405   // Add the target cpu
4406   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4407   if (!CPU.empty()) {
4408     CmdArgs.push_back("-target-cpu");
4409     CmdArgs.push_back(Args.MakeArgString(CPU));
4410   }
4411
4412   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
4413     CmdArgs.push_back("-mfpmath");
4414     CmdArgs.push_back(A->getValue());
4415   }
4416
4417   // Add the target features
4418   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
4419
4420   // Add target specific flags.
4421   switch (getToolChain().getArch()) {
4422   default:
4423     break;
4424
4425   case llvm::Triple::arm:
4426   case llvm::Triple::armeb:
4427   case llvm::Triple::thumb:
4428   case llvm::Triple::thumbeb:
4429     // Use the effective triple, which takes into account the deployment target.
4430     AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
4431     break;
4432
4433   case llvm::Triple::aarch64:
4434   case llvm::Triple::aarch64_be:
4435     AddAArch64TargetArgs(Args, CmdArgs);
4436     break;
4437
4438   case llvm::Triple::mips:
4439   case llvm::Triple::mipsel:
4440   case llvm::Triple::mips64:
4441   case llvm::Triple::mips64el:
4442     AddMIPSTargetArgs(Args, CmdArgs);
4443     break;
4444
4445   case llvm::Triple::ppc:
4446   case llvm::Triple::ppc64:
4447   case llvm::Triple::ppc64le:
4448     AddPPCTargetArgs(Args, CmdArgs);
4449     break;
4450
4451   case llvm::Triple::sparc:
4452   case llvm::Triple::sparcel:
4453   case llvm::Triple::sparcv9:
4454     AddSparcTargetArgs(Args, CmdArgs);
4455     break;
4456
4457   case llvm::Triple::systemz:
4458     AddSystemZTargetArgs(Args, CmdArgs);
4459     break;
4460
4461   case llvm::Triple::x86:
4462   case llvm::Triple::x86_64:
4463     AddX86TargetArgs(Args, CmdArgs);
4464     break;
4465
4466   case llvm::Triple::lanai:
4467     AddLanaiTargetArgs(Args, CmdArgs);
4468     break;
4469
4470   case llvm::Triple::hexagon:
4471     AddHexagonTargetArgs(Args, CmdArgs);
4472     break;
4473
4474   case llvm::Triple::wasm32:
4475   case llvm::Triple::wasm64:
4476     AddWebAssemblyTargetArgs(Args, CmdArgs);
4477     break;
4478   }
4479
4480   // The 'g' groups options involve a somewhat intricate sequence of decisions
4481   // about what to pass from the driver to the frontend, but by the time they
4482   // reach cc1 they've been factored into three well-defined orthogonal choices:
4483   //  * what level of debug info to generate
4484   //  * what dwarf version to write
4485   //  * what debugger tuning to use
4486   // This avoids having to monkey around further in cc1 other than to disable
4487   // codeview if not running in a Windows environment. Perhaps even that
4488   // decision should be made in the driver as well though.
4489   unsigned DwarfVersion = 0;
4490   llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4491   // These two are potentially updated by AddClangCLArgs.
4492   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4493   bool EmitCodeView = false;
4494
4495   // Add clang-cl arguments.
4496   types::ID InputType = Input.getType();
4497   if (getToolChain().getDriver().IsCLMode())
4498     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4499
4500   // Pass the linker version in use.
4501   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4502     CmdArgs.push_back("-target-linker-version");
4503     CmdArgs.push_back(A->getValue());
4504   }
4505
4506   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4507     CmdArgs.push_back("-momit-leaf-frame-pointer");
4508
4509   // Explicitly error on some things we know we don't support and can't just
4510   // ignore.
4511   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4512     Arg *Unsupported;
4513     if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4514         getToolChain().getArch() == llvm::Triple::x86) {
4515       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4516           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4517         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4518             << Unsupported->getOption().getName();
4519     }
4520   }
4521
4522   Args.AddAllArgs(CmdArgs, options::OPT_v);
4523   Args.AddLastArg(CmdArgs, options::OPT_H);
4524   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4525     CmdArgs.push_back("-header-include-file");
4526     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4527                                                : "-");
4528   }
4529   Args.AddLastArg(CmdArgs, options::OPT_P);
4530   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4531
4532   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4533     CmdArgs.push_back("-diagnostic-log-file");
4534     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4535                                                  : "-");
4536   }
4537
4538   Args.ClaimAllArgs(options::OPT_g_Group);
4539   Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4540   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4541     // If the last option explicitly specified a debug-info level, use it.
4542     if (A->getOption().matches(options::OPT_gN_Group)) {
4543       DebugInfoKind = DebugLevelToInfoKind(*A);
4544       // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4545       // But -gsplit-dwarf is not a g_group option, hence we have to check the
4546       // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4547       if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
4548           A->getIndex() > SplitDwarfArg->getIndex())
4549         SplitDwarfArg = nullptr;
4550     } else
4551       // For any other 'g' option, use Limited.
4552       DebugInfoKind = codegenoptions::LimitedDebugInfo;
4553   }
4554
4555   // If a debugger tuning argument appeared, remember it.
4556   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4557                                options::OPT_ggdbN_Group)) {
4558     if (A->getOption().matches(options::OPT_glldb))
4559       DebuggerTuning = llvm::DebuggerKind::LLDB;
4560     else if (A->getOption().matches(options::OPT_gsce))
4561       DebuggerTuning = llvm::DebuggerKind::SCE;
4562     else
4563       DebuggerTuning = llvm::DebuggerKind::GDB;
4564   }
4565
4566   // If a -gdwarf argument appeared, remember it.
4567   if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4568                                options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4569     DwarfVersion = DwarfVersionNum(A->getSpelling());
4570
4571   // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
4572   // argument parsing.
4573   if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4574     // DwarfVersion remains at 0 if no explicit choice was made.
4575     CmdArgs.push_back("-gcodeview");
4576   } else if (DwarfVersion == 0 &&
4577              DebugInfoKind != codegenoptions::NoDebugInfo) {
4578     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4579   }
4580
4581   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4582   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4583
4584   // PS4 defaults to no column info
4585   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4586                    /*Default=*/ !IsPS4CPU))
4587     CmdArgs.push_back("-dwarf-column-info");
4588
4589   // FIXME: Move backend command line options to the module.
4590   if (Args.hasArg(options::OPT_gmodules)) {
4591     DebugInfoKind = codegenoptions::LimitedDebugInfo;
4592     CmdArgs.push_back("-dwarf-ext-refs");
4593     CmdArgs.push_back("-fmodule-format=obj");
4594   }
4595
4596   // -gsplit-dwarf should turn on -g and enable the backend dwarf
4597   // splitting and extraction.
4598   // FIXME: Currently only works on Linux.
4599   if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4600     DebugInfoKind = codegenoptions::LimitedDebugInfo;
4601     CmdArgs.push_back("-backend-option");
4602     CmdArgs.push_back("-split-dwarf=Enable");
4603   }
4604
4605   // After we've dealt with all combinations of things that could
4606   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4607   // figure out if we need to "upgrade" it to standalone debug info.
4608   // We parse these two '-f' options whether or not they will be used,
4609   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4610   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4611                                     options::OPT_fno_standalone_debug,
4612                                     getToolChain().GetDefaultStandaloneDebug());
4613   if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
4614     DebugInfoKind = codegenoptions::FullDebugInfo;
4615   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4616                           DebuggerTuning);
4617
4618   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4619   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4620     CmdArgs.push_back("-backend-option");
4621     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4622   }
4623
4624   // -gdwarf-aranges turns on the emission of the aranges section in the
4625   // backend.
4626   // Always enabled on the PS4.
4627   if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4628     CmdArgs.push_back("-backend-option");
4629     CmdArgs.push_back("-generate-arange-section");
4630   }
4631
4632   if (Args.hasFlag(options::OPT_fdebug_types_section,
4633                    options::OPT_fno_debug_types_section, false)) {
4634     CmdArgs.push_back("-backend-option");
4635     CmdArgs.push_back("-generate-type-units");
4636   }
4637
4638   // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4639   // default.
4640   bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4641                              Triple.getArch() == llvm::Triple::wasm32 ||
4642                              Triple.getArch() == llvm::Triple::wasm64;
4643
4644   if (Args.hasFlag(options::OPT_ffunction_sections,
4645                    options::OPT_fno_function_sections, UseSeparateSections)) {
4646     CmdArgs.push_back("-ffunction-sections");
4647   }
4648
4649   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4650                    UseSeparateSections)) {
4651     CmdArgs.push_back("-fdata-sections");
4652   }
4653
4654   if (!Args.hasFlag(options::OPT_funique_section_names,
4655                     options::OPT_fno_unique_section_names, true))
4656     CmdArgs.push_back("-fno-unique-section-names");
4657
4658   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4659
4660   if (Args.hasFlag(options::OPT_fxray_instrument,
4661                    options::OPT_fnoxray_instrument, false)) {
4662     CmdArgs.push_back("-fxray-instrument");
4663     if (const Arg *A =
4664             Args.getLastArg(options::OPT_fxray_instruction_threshold_,
4665                             options::OPT_fxray_instruction_threshold_EQ)) {
4666       CmdArgs.push_back("-fxray-instruction-threshold");
4667       CmdArgs.push_back(A->getValue());
4668     }
4669   }
4670
4671   addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4672
4673   // Add runtime flag for PS4 when PGO or Coverage are enabled.
4674   if (getToolChain().getTriple().isPS4CPU())
4675     addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4676
4677   // Pass options for controlling the default header search paths.
4678   if (Args.hasArg(options::OPT_nostdinc)) {
4679     CmdArgs.push_back("-nostdsysteminc");
4680     CmdArgs.push_back("-nobuiltininc");
4681   } else {
4682     if (Args.hasArg(options::OPT_nostdlibinc))
4683       CmdArgs.push_back("-nostdsysteminc");
4684     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4685     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4686   }
4687
4688   // Pass the path to compiler resource files.
4689   CmdArgs.push_back("-resource-dir");
4690   CmdArgs.push_back(D.ResourceDir.c_str());
4691
4692   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4693
4694   bool ARCMTEnabled = false;
4695   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4696     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4697                                        options::OPT_ccc_arcmt_modify,
4698                                        options::OPT_ccc_arcmt_migrate)) {
4699       ARCMTEnabled = true;
4700       switch (A->getOption().getID()) {
4701       default:
4702         llvm_unreachable("missed a case");
4703       case options::OPT_ccc_arcmt_check:
4704         CmdArgs.push_back("-arcmt-check");
4705         break;
4706       case options::OPT_ccc_arcmt_modify:
4707         CmdArgs.push_back("-arcmt-modify");
4708         break;
4709       case options::OPT_ccc_arcmt_migrate:
4710         CmdArgs.push_back("-arcmt-migrate");
4711         CmdArgs.push_back("-mt-migrate-directory");
4712         CmdArgs.push_back(A->getValue());
4713
4714         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4715         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4716         break;
4717       }
4718     }
4719   } else {
4720     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4721     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4722     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4723   }
4724
4725   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4726     if (ARCMTEnabled) {
4727       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4728                                                       << "-ccc-arcmt-migrate";
4729     }
4730     CmdArgs.push_back("-mt-migrate-directory");
4731     CmdArgs.push_back(A->getValue());
4732
4733     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4734                      options::OPT_objcmt_migrate_subscripting,
4735                      options::OPT_objcmt_migrate_property)) {
4736       // None specified, means enable them all.
4737       CmdArgs.push_back("-objcmt-migrate-literals");
4738       CmdArgs.push_back("-objcmt-migrate-subscripting");
4739       CmdArgs.push_back("-objcmt-migrate-property");
4740     } else {
4741       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4742       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4743       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4744     }
4745   } else {
4746     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4747     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4748     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4749     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4750     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4751     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4752     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4753     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4754     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4755     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4756     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4757     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4758     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4759     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4760     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4761     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4762   }
4763
4764   // Add preprocessing options like -I, -D, etc. if we are using the
4765   // preprocessor.
4766   //
4767   // FIXME: Support -fpreprocessed
4768   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4769     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4770
4771   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4772   // that "The compiler can only warn and ignore the option if not recognized".
4773   // When building with ccache, it will pass -D options to clang even on
4774   // preprocessed inputs and configure concludes that -fPIC is not supported.
4775   Args.ClaimAllArgs(options::OPT_D);
4776
4777   // Manually translate -O4 to -O3; let clang reject others.
4778   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4779     if (A->getOption().matches(options::OPT_O4)) {
4780       CmdArgs.push_back("-O3");
4781       D.Diag(diag::warn_O4_is_O3);
4782     } else {
4783       A->render(Args, CmdArgs);
4784     }
4785   }
4786
4787   // Warn about ignored options to clang.
4788   for (const Arg *A :
4789        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4790     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4791     A->claim();
4792   }
4793
4794   claimNoWarnArgs(Args);
4795
4796   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4797   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4798   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4799     CmdArgs.push_back("-pedantic");
4800   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4801   Args.AddLastArg(CmdArgs, options::OPT_w);
4802
4803   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4804   // (-ansi is equivalent to -std=c89 or -std=c++98).
4805   //
4806   // If a std is supplied, only add -trigraphs if it follows the
4807   // option.
4808   bool ImplyVCPPCXXVer = false;
4809   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4810     if (Std->getOption().matches(options::OPT_ansi))
4811       if (types::isCXX(InputType))
4812         CmdArgs.push_back("-std=c++98");
4813       else
4814         CmdArgs.push_back("-std=c89");
4815     else
4816       Std->render(Args, CmdArgs);
4817
4818     // If -f(no-)trigraphs appears after the language standard flag, honor it.
4819     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4820                                  options::OPT_ftrigraphs,
4821                                  options::OPT_fno_trigraphs))
4822       if (A != Std)
4823         A->render(Args, CmdArgs);
4824   } else {
4825     // Honor -std-default.
4826     //
4827     // FIXME: Clang doesn't correctly handle -std= when the input language
4828     // doesn't match. For the time being just ignore this for C++ inputs;
4829     // eventually we want to do all the standard defaulting here instead of
4830     // splitting it between the driver and clang -cc1.
4831     if (!types::isCXX(InputType))
4832       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4833                                 /*Joined=*/true);
4834     else if (IsWindowsMSVC)
4835       ImplyVCPPCXXVer = true;
4836
4837     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4838                     options::OPT_fno_trigraphs);
4839   }
4840
4841   // GCC's behavior for -Wwrite-strings is a bit strange:
4842   //  * In C, this "warning flag" changes the types of string literals from
4843   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4844   //    for the discarded qualifier.
4845   //  * In C++, this is just a normal warning flag.
4846   //
4847   // Implementing this warning correctly in C is hard, so we follow GCC's
4848   // behavior for now. FIXME: Directly diagnose uses of a string literal as
4849   // a non-const char* in C, rather than using this crude hack.
4850   if (!types::isCXX(InputType)) {
4851     // FIXME: This should behave just like a warning flag, and thus should also
4852     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4853     Arg *WriteStrings =
4854         Args.getLastArg(options::OPT_Wwrite_strings,
4855                         options::OPT_Wno_write_strings, options::OPT_w);
4856     if (WriteStrings &&
4857         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4858       CmdArgs.push_back("-fconst-strings");
4859   }
4860
4861   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4862   // during C++ compilation, which it is by default. GCC keeps this define even
4863   // in the presence of '-w', match this behavior bug-for-bug.
4864   if (types::isCXX(InputType) &&
4865       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4866                    true)) {
4867     CmdArgs.push_back("-fdeprecated-macro");
4868   }
4869
4870   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4871   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4872     if (Asm->getOption().matches(options::OPT_fasm))
4873       CmdArgs.push_back("-fgnu-keywords");
4874     else
4875       CmdArgs.push_back("-fno-gnu-keywords");
4876   }
4877
4878   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4879     CmdArgs.push_back("-fno-dwarf-directory-asm");
4880
4881   if (ShouldDisableAutolink(Args, getToolChain()))
4882     CmdArgs.push_back("-fno-autolink");
4883
4884   // Add in -fdebug-compilation-dir if necessary.
4885   addDebugCompDirArg(Args, CmdArgs);
4886
4887   for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4888     StringRef Map = A->getValue();
4889     if (Map.find('=') == StringRef::npos)
4890       D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4891     else
4892       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4893     A->claim();
4894   }
4895
4896   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4897                                options::OPT_ftemplate_depth_EQ)) {
4898     CmdArgs.push_back("-ftemplate-depth");
4899     CmdArgs.push_back(A->getValue());
4900   }
4901
4902   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4903     CmdArgs.push_back("-foperator-arrow-depth");
4904     CmdArgs.push_back(A->getValue());
4905   }
4906
4907   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4908     CmdArgs.push_back("-fconstexpr-depth");
4909     CmdArgs.push_back(A->getValue());
4910   }
4911
4912   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4913     CmdArgs.push_back("-fconstexpr-steps");
4914     CmdArgs.push_back(A->getValue());
4915   }
4916
4917   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4918     CmdArgs.push_back("-fbracket-depth");
4919     CmdArgs.push_back(A->getValue());
4920   }
4921
4922   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4923                                options::OPT_Wlarge_by_value_copy_def)) {
4924     if (A->getNumValues()) {
4925       StringRef bytes = A->getValue();
4926       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4927     } else
4928       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4929   }
4930
4931   if (Args.hasArg(options::OPT_relocatable_pch))
4932     CmdArgs.push_back("-relocatable-pch");
4933
4934   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4935     CmdArgs.push_back("-fconstant-string-class");
4936     CmdArgs.push_back(A->getValue());
4937   }
4938
4939   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4940     CmdArgs.push_back("-ftabstop");
4941     CmdArgs.push_back(A->getValue());
4942   }
4943
4944   CmdArgs.push_back("-ferror-limit");
4945   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4946     CmdArgs.push_back(A->getValue());
4947   else
4948     CmdArgs.push_back("19");
4949
4950   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4951     CmdArgs.push_back("-fmacro-backtrace-limit");
4952     CmdArgs.push_back(A->getValue());
4953   }
4954
4955   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4956     CmdArgs.push_back("-ftemplate-backtrace-limit");
4957     CmdArgs.push_back(A->getValue());
4958   }
4959
4960   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4961     CmdArgs.push_back("-fconstexpr-backtrace-limit");
4962     CmdArgs.push_back(A->getValue());
4963   }
4964
4965   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4966     CmdArgs.push_back("-fspell-checking-limit");
4967     CmdArgs.push_back(A->getValue());
4968   }
4969
4970   // Pass -fmessage-length=.
4971   CmdArgs.push_back("-fmessage-length");
4972   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4973     CmdArgs.push_back(A->getValue());
4974   } else {
4975     // If -fmessage-length=N was not specified, determine whether this is a
4976     // terminal and, if so, implicitly define -fmessage-length appropriately.
4977     unsigned N = llvm::sys::Process::StandardErrColumns();
4978     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4979   }
4980
4981   // -fvisibility= and -fvisibility-ms-compat are of a piece.
4982   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4983                                      options::OPT_fvisibility_ms_compat)) {
4984     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4985       CmdArgs.push_back("-fvisibility");
4986       CmdArgs.push_back(A->getValue());
4987     } else {
4988       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4989       CmdArgs.push_back("-fvisibility");
4990       CmdArgs.push_back("hidden");
4991       CmdArgs.push_back("-ftype-visibility");
4992       CmdArgs.push_back("default");
4993     }
4994   }
4995
4996   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4997
4998   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4999
5000   // -fhosted is default.
5001   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5002       KernelOrKext)
5003     CmdArgs.push_back("-ffreestanding");
5004
5005   // Forward -f (flag) options which we can pass directly.
5006   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5007   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5008   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
5009   // Emulated TLS is enabled by default on Android, and can be enabled manually
5010   // with -femulated-tls.
5011   bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
5012   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
5013                    EmulatedTLSDefault))
5014     CmdArgs.push_back("-femulated-tls");
5015   // AltiVec-like language extensions aren't relevant for assembling.
5016   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
5017     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
5018     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5019   }
5020   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5021   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5022
5023   // Forward flags for OpenMP. We don't do this if the current action is an
5024   // device offloading action.
5025   //
5026   // TODO: Allow OpenMP offload actions when they become available.
5027   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5028                    options::OPT_fno_openmp, false) &&
5029       JA.isDeviceOffloading(Action::OFK_None)) {
5030     switch (getOpenMPRuntime(getToolChain(), Args)) {
5031     case OMPRT_OMP:
5032     case OMPRT_IOMP5:
5033       // Clang can generate useful OpenMP code for these two runtime libraries.
5034       CmdArgs.push_back("-fopenmp");
5035
5036       // If no option regarding the use of TLS in OpenMP codegeneration is
5037       // given, decide a default based on the target. Otherwise rely on the
5038       // options and pass the right information to the frontend.
5039       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5040                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5041         CmdArgs.push_back("-fnoopenmp-use-tls");
5042       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5043       break;
5044     default:
5045       // By default, if Clang doesn't know how to generate useful OpenMP code
5046       // for a specific runtime library, we just don't pass the '-fopenmp' flag
5047       // down to the actual compilation.
5048       // FIXME: It would be better to have a mode which *only* omits IR
5049       // generation based on the OpenMP support so that we get consistent
5050       // semantic analysis, etc.
5051       break;
5052     }
5053   }
5054
5055   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
5056   Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
5057
5058   // Report an error for -faltivec on anything other than PowerPC.
5059   if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
5060     const llvm::Triple::ArchType Arch = getToolChain().getArch();
5061     if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
5062           Arch == llvm::Triple::ppc64le))
5063       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
5064                                                        << "ppc/ppc64/ppc64le";
5065   }
5066
5067   // -fzvector is incompatible with -faltivec.
5068   if (Arg *A = Args.getLastArg(options::OPT_fzvector))
5069     if (Args.hasArg(options::OPT_faltivec))
5070       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5071                                                       << "-faltivec";
5072
5073   if (getToolChain().SupportsProfiling())
5074     Args.AddLastArg(CmdArgs, options::OPT_pg);
5075
5076   // -flax-vector-conversions is default.
5077   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
5078                     options::OPT_fno_lax_vector_conversions))
5079     CmdArgs.push_back("-fno-lax-vector-conversions");
5080
5081   if (Args.getLastArg(options::OPT_fapple_kext) ||
5082       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5083     CmdArgs.push_back("-fapple-kext");
5084
5085   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5086   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5087   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5088   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5089   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5090
5091   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5092     CmdArgs.push_back("-ftrapv-handler");
5093     CmdArgs.push_back(A->getValue());
5094   }
5095
5096   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5097
5098   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5099   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5100   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5101     if (A->getOption().matches(options::OPT_fwrapv))
5102       CmdArgs.push_back("-fwrapv");
5103   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5104                                       options::OPT_fno_strict_overflow)) {
5105     if (A->getOption().matches(options::OPT_fno_strict_overflow))
5106       CmdArgs.push_back("-fwrapv");
5107   }
5108
5109   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5110                                options::OPT_fno_reroll_loops))
5111     if (A->getOption().matches(options::OPT_freroll_loops))
5112       CmdArgs.push_back("-freroll-loops");
5113
5114   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5115   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5116                   options::OPT_fno_unroll_loops);
5117
5118   Args.AddLastArg(CmdArgs, options::OPT_pthread);
5119
5120   // -stack-protector=0 is default.
5121   unsigned StackProtectorLevel = 0;
5122   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
5123                                options::OPT_fstack_protector_all,
5124                                options::OPT_fstack_protector_strong,
5125                                options::OPT_fstack_protector)) {
5126     if (A->getOption().matches(options::OPT_fstack_protector)) {
5127       StackProtectorLevel = std::max<unsigned>(
5128           LangOptions::SSPOn,
5129           getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
5130     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
5131       StackProtectorLevel = LangOptions::SSPStrong;
5132     else if (A->getOption().matches(options::OPT_fstack_protector_all))
5133       StackProtectorLevel = LangOptions::SSPReq;
5134   } else {
5135     StackProtectorLevel =
5136         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
5137   }
5138   if (StackProtectorLevel) {
5139     CmdArgs.push_back("-stack-protector");
5140     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
5141   }
5142
5143   // --param ssp-buffer-size=
5144   for (const Arg *A : Args.filtered(options::OPT__param)) {
5145     StringRef Str(A->getValue());
5146     if (Str.startswith("ssp-buffer-size=")) {
5147       if (StackProtectorLevel) {
5148         CmdArgs.push_back("-stack-protector-buffer-size");
5149         // FIXME: Verify the argument is a valid integer.
5150         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
5151       }
5152       A->claim();
5153     }
5154   }
5155
5156   // Translate -mstackrealign
5157   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5158                    false))
5159     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5160
5161   if (Args.hasArg(options::OPT_mstack_alignment)) {
5162     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5163     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5164   }
5165
5166   if (Args.hasArg(options::OPT_mstack_probe_size)) {
5167     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5168
5169     if (!Size.empty())
5170       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5171     else
5172       CmdArgs.push_back("-mstack-probe-size=0");
5173   }
5174
5175   switch (getToolChain().getArch()) {
5176   case llvm::Triple::aarch64:
5177   case llvm::Triple::aarch64_be:
5178   case llvm::Triple::arm:
5179   case llvm::Triple::armeb:
5180   case llvm::Triple::thumb:
5181   case llvm::Triple::thumbeb:
5182     CmdArgs.push_back("-fallow-half-arguments-and-returns");
5183     break;
5184
5185   default:
5186     break;
5187   }
5188
5189   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5190                                options::OPT_mno_restrict_it)) {
5191     if (A->getOption().matches(options::OPT_mrestrict_it)) {
5192       CmdArgs.push_back("-backend-option");
5193       CmdArgs.push_back("-arm-restrict-it");
5194     } else {
5195       CmdArgs.push_back("-backend-option");
5196       CmdArgs.push_back("-arm-no-restrict-it");
5197     }
5198   } else if (Triple.isOSWindows() &&
5199              (Triple.getArch() == llvm::Triple::arm ||
5200               Triple.getArch() == llvm::Triple::thumb)) {
5201     // Windows on ARM expects restricted IT blocks
5202     CmdArgs.push_back("-backend-option");
5203     CmdArgs.push_back("-arm-restrict-it");
5204   }
5205
5206   // Forward -cl options to -cc1
5207   if (Args.getLastArg(options::OPT_cl_opt_disable)) {
5208     CmdArgs.push_back("-cl-opt-disable");
5209   }
5210   if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
5211     CmdArgs.push_back("-cl-strict-aliasing");
5212   }
5213   if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
5214     CmdArgs.push_back("-cl-single-precision-constant");
5215   }
5216   if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
5217     CmdArgs.push_back("-cl-finite-math-only");
5218   }
5219   if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
5220     CmdArgs.push_back("-cl-kernel-arg-info");
5221   }
5222   if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
5223     CmdArgs.push_back("-cl-unsafe-math-optimizations");
5224   }
5225   if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
5226     CmdArgs.push_back("-cl-fast-relaxed-math");
5227   }
5228   if (Args.getLastArg(options::OPT_cl_mad_enable)) {
5229     CmdArgs.push_back("-cl-mad-enable");
5230   }
5231   if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
5232     CmdArgs.push_back("-cl-no-signed-zeros");
5233   }
5234   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
5235     std::string CLStdStr = "-cl-std=";
5236     CLStdStr += A->getValue();
5237     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
5238   }
5239   if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
5240     CmdArgs.push_back("-cl-denorms-are-zero");
5241   }
5242
5243   // Forward -f options with positive and negative forms; we translate
5244   // these by hand.
5245   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
5246     StringRef fname = A->getValue();
5247     if (!llvm::sys::fs::exists(fname))
5248       D.Diag(diag::err_drv_no_such_file) << fname;
5249     else
5250       A->render(Args, CmdArgs);
5251   }
5252
5253   // -fbuiltin is default unless -mkernel is used.
5254   bool UseBuiltins =
5255       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
5256                    !Args.hasArg(options::OPT_mkernel));
5257   if (!UseBuiltins)
5258     CmdArgs.push_back("-fno-builtin");
5259
5260   // -ffreestanding implies -fno-builtin.
5261   if (Args.hasArg(options::OPT_ffreestanding))
5262     UseBuiltins = false;
5263
5264   // Process the -fno-builtin-* options.
5265   for (const auto &Arg : Args) {
5266     const Option &O = Arg->getOption();
5267     if (!O.matches(options::OPT_fno_builtin_))
5268       continue;
5269
5270     Arg->claim();
5271     // If -fno-builtin is specified, then there's no need to pass the option to
5272     // the frontend.
5273     if (!UseBuiltins)
5274       continue;
5275
5276     StringRef FuncName = Arg->getValue();
5277     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
5278   }
5279
5280   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5281                     options::OPT_fno_assume_sane_operator_new))
5282     CmdArgs.push_back("-fno-assume-sane-operator-new");
5283
5284   // -fblocks=0 is default.
5285   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5286                    getToolChain().IsBlocksDefault()) ||
5287       (Args.hasArg(options::OPT_fgnu_runtime) &&
5288        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5289        !Args.hasArg(options::OPT_fno_blocks))) {
5290     CmdArgs.push_back("-fblocks");
5291
5292     if (!Args.hasArg(options::OPT_fgnu_runtime) &&
5293         !getToolChain().hasBlocksRuntime())
5294       CmdArgs.push_back("-fblocks-runtime-optional");
5295   }
5296
5297   // -fmodules enables the use of precompiled modules (off by default).
5298   // Users can pass -fno-cxx-modules to turn off modules support for
5299   // C++/Objective-C++ programs.
5300   bool HaveModules = false;
5301   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
5302     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
5303                                      options::OPT_fno_cxx_modules, true);
5304     if (AllowedInCXX || !types::isCXX(InputType)) {
5305       CmdArgs.push_back("-fmodules");
5306       HaveModules = true;
5307     }
5308   }
5309
5310   // -fmodule-maps enables implicit reading of module map files. By default,
5311   // this is enabled if we are using precompiled modules.
5312   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
5313                    options::OPT_fno_implicit_module_maps, HaveModules)) {
5314     CmdArgs.push_back("-fimplicit-module-maps");
5315   }
5316
5317   // -fmodules-decluse checks that modules used are declared so (off by
5318   // default).
5319   if (Args.hasFlag(options::OPT_fmodules_decluse,
5320                    options::OPT_fno_modules_decluse, false)) {
5321     CmdArgs.push_back("-fmodules-decluse");
5322   }
5323
5324   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
5325   // all #included headers are part of modules.
5326   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
5327                    options::OPT_fno_modules_strict_decluse, false)) {
5328     CmdArgs.push_back("-fmodules-strict-decluse");
5329   }
5330
5331   // -fno-implicit-modules turns off implicitly compiling modules on demand.
5332   if (!Args.hasFlag(options::OPT_fimplicit_modules,
5333                     options::OPT_fno_implicit_modules)) {
5334     CmdArgs.push_back("-fno-implicit-modules");
5335   } else if (HaveModules) {
5336     // -fmodule-cache-path specifies where our implicitly-built module files
5337     // should be written.
5338     SmallString<128> Path;
5339     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
5340       Path = A->getValue();
5341     if (C.isForDiagnostics()) {
5342       // When generating crash reports, we want to emit the modules along with
5343       // the reproduction sources, so we ignore any provided module path.
5344       Path = Output.getFilename();
5345       llvm::sys::path::replace_extension(Path, ".cache");
5346       llvm::sys::path::append(Path, "modules");
5347     } else if (Path.empty()) {
5348       // No module path was provided: use the default.
5349       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
5350       llvm::sys::path::append(Path, "org.llvm.clang.");
5351       appendUserToPath(Path);
5352       llvm::sys::path::append(Path, "ModuleCache");
5353     }
5354     const char Arg[] = "-fmodules-cache-path=";
5355     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
5356     CmdArgs.push_back(Args.MakeArgString(Path));
5357   }
5358
5359   // -fmodule-name specifies the module that is currently being built (or
5360   // used for header checking by -fmodule-maps).
5361   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
5362
5363   // -fmodule-map-file can be used to specify files containing module
5364   // definitions.
5365   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
5366
5367   // -fmodule-file can be used to specify files containing precompiled modules.
5368   if (HaveModules)
5369     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
5370   else
5371     Args.ClaimAllArgs(options::OPT_fmodule_file);
5372
5373   // When building modules and generating crashdumps, we need to dump a module
5374   // dependency VFS alongside the output.
5375   if (HaveModules && C.isForDiagnostics()) {
5376     SmallString<128> VFSDir(Output.getFilename());
5377     llvm::sys::path::replace_extension(VFSDir, ".cache");
5378     // Add the cache directory as a temp so the crash diagnostics pick it up.
5379     C.addTempFile(Args.MakeArgString(VFSDir));
5380
5381     llvm::sys::path::append(VFSDir, "vfs");
5382     CmdArgs.push_back("-module-dependency-dir");
5383     CmdArgs.push_back(Args.MakeArgString(VFSDir));
5384   }
5385
5386   if (HaveModules)
5387     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
5388
5389   // Pass through all -fmodules-ignore-macro arguments.
5390   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
5391   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
5392   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
5393
5394   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
5395
5396   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
5397     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
5398       D.Diag(diag::err_drv_argument_not_allowed_with)
5399           << A->getAsString(Args) << "-fbuild-session-timestamp";
5400
5401     llvm::sys::fs::file_status Status;
5402     if (llvm::sys::fs::status(A->getValue(), Status))
5403       D.Diag(diag::err_drv_no_such_file) << A->getValue();
5404     CmdArgs.push_back(Args.MakeArgString(
5405         "-fbuild-session-timestamp=" +
5406         Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
5407   }
5408
5409   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
5410     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
5411                          options::OPT_fbuild_session_file))
5412       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
5413
5414     Args.AddLastArg(CmdArgs,
5415                     options::OPT_fmodules_validate_once_per_build_session);
5416   }
5417
5418   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
5419
5420   // -faccess-control is default.
5421   if (Args.hasFlag(options::OPT_fno_access_control,
5422                    options::OPT_faccess_control, false))
5423     CmdArgs.push_back("-fno-access-control");
5424
5425   // -felide-constructors is the default.
5426   if (Args.hasFlag(options::OPT_fno_elide_constructors,
5427                    options::OPT_felide_constructors, false))
5428     CmdArgs.push_back("-fno-elide-constructors");
5429
5430   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5431
5432   if (KernelOrKext || (types::isCXX(InputType) &&
5433                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5434                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
5435     CmdArgs.push_back("-fno-rtti");
5436
5437   // -fshort-enums=0 is default for all architectures except Hexagon.
5438   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5439                    getToolChain().getArch() == llvm::Triple::hexagon))
5440     CmdArgs.push_back("-fshort-enums");
5441
5442   // -fsigned-char is default.
5443   if (Arg *A = Args.getLastArg(
5444           options::OPT_fsigned_char, options::OPT_fno_signed_char,
5445           options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5446     if (A->getOption().matches(options::OPT_funsigned_char) ||
5447         A->getOption().matches(options::OPT_fno_signed_char)) {
5448       CmdArgs.push_back("-fno-signed-char");
5449     }
5450   } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5451     CmdArgs.push_back("-fno-signed-char");
5452   }
5453
5454   // -fuse-cxa-atexit is default.
5455   if (!Args.hasFlag(
5456           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5457           !IsWindowsCygnus && !IsWindowsGNU &&
5458               getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5459               getToolChain().getArch() != llvm::Triple::hexagon &&
5460               getToolChain().getArch() != llvm::Triple::xcore &&
5461               ((getToolChain().getTriple().getVendor() !=
5462                 llvm::Triple::MipsTechnologies) ||
5463                getToolChain().getTriple().hasEnvironment())) ||
5464       KernelOrKext)
5465     CmdArgs.push_back("-fno-use-cxa-atexit");
5466
5467   // -fms-extensions=0 is default.
5468   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5469                    IsWindowsMSVC))
5470     CmdArgs.push_back("-fms-extensions");
5471
5472   // -fno-use-line-directives is default.
5473   if (Args.hasFlag(options::OPT_fuse_line_directives,
5474                    options::OPT_fno_use_line_directives, false))
5475     CmdArgs.push_back("-fuse-line-directives");
5476
5477   // -fms-compatibility=0 is default.
5478   if (Args.hasFlag(options::OPT_fms_compatibility,
5479                    options::OPT_fno_ms_compatibility,
5480                    (IsWindowsMSVC &&
5481                     Args.hasFlag(options::OPT_fms_extensions,
5482                                  options::OPT_fno_ms_extensions, true))))
5483     CmdArgs.push_back("-fms-compatibility");
5484
5485   // -fms-compatibility-version=18.00 is default.
5486   VersionTuple MSVT = visualstudio::getMSVCVersion(
5487       &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
5488   if (!MSVT.empty())
5489     CmdArgs.push_back(
5490         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5491
5492   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5493   if (ImplyVCPPCXXVer) {
5494     StringRef LanguageStandard;
5495     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
5496       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
5497                              .Case("c++14", "-std=c++14")
5498                              .Case("c++latest", "-std=c++1z")
5499                              .Default("");
5500       if (LanguageStandard.empty())
5501         D.Diag(clang::diag::warn_drv_unused_argument)
5502             << StdArg->getAsString(Args);
5503     }
5504
5505     if (LanguageStandard.empty()) {
5506       if (IsMSVC2015Compatible)
5507         LanguageStandard = "-std=c++14";
5508       else
5509         LanguageStandard = "-std=c++11";
5510     }
5511
5512     CmdArgs.push_back(LanguageStandard.data());
5513   }
5514
5515   // -fno-borland-extensions is default.
5516   if (Args.hasFlag(options::OPT_fborland_extensions,
5517                    options::OPT_fno_borland_extensions, false))
5518     CmdArgs.push_back("-fborland-extensions");
5519
5520   // -fno-declspec is default, except for PS4.
5521   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5522                    getToolChain().getTriple().isPS4()))
5523     CmdArgs.push_back("-fdeclspec");
5524   else if (Args.hasArg(options::OPT_fno_declspec))
5525     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5526
5527   // -fthreadsafe-static is default, except for MSVC compatibility versions less
5528   // than 19.
5529   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5530                     options::OPT_fno_threadsafe_statics,
5531                     !IsWindowsMSVC || IsMSVC2015Compatible))
5532     CmdArgs.push_back("-fno-threadsafe-statics");
5533
5534   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5535   // needs it.
5536   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5537                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5538     CmdArgs.push_back("-fdelayed-template-parsing");
5539
5540   // -fgnu-keywords default varies depending on language; only pass if
5541   // specified.
5542   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5543                                options::OPT_fno_gnu_keywords))
5544     A->render(Args, CmdArgs);
5545
5546   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5547                    false))
5548     CmdArgs.push_back("-fgnu89-inline");
5549
5550   if (Args.hasArg(options::OPT_fno_inline))
5551     CmdArgs.push_back("-fno-inline");
5552
5553   if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
5554                                        options::OPT_finline_hint_functions,
5555                                        options::OPT_fno_inline_functions))
5556     InlineArg->render(Args, CmdArgs);
5557
5558   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5559
5560   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5561   // legacy is the default. Except for deployment taget of 10.5,
5562   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5563   // gets ignored silently.
5564   if (objcRuntime.isNonFragile()) {
5565     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5566                       options::OPT_fno_objc_legacy_dispatch,
5567                       objcRuntime.isLegacyDispatchDefaultForArch(
5568                           getToolChain().getArch()))) {
5569       if (getToolChain().UseObjCMixedDispatch())
5570         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5571       else
5572         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5573     }
5574   }
5575
5576   // When ObjectiveC legacy runtime is in effect on MacOSX,
5577   // turn on the option to do Array/Dictionary subscripting
5578   // by default.
5579   if (getToolChain().getArch() == llvm::Triple::x86 &&
5580       getToolChain().getTriple().isMacOSX() &&
5581       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5582       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5583       objcRuntime.isNeXTFamily())
5584     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5585
5586   // -fencode-extended-block-signature=1 is default.
5587   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5588     CmdArgs.push_back("-fencode-extended-block-signature");
5589   }
5590
5591   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5592   // NOTE: This logic is duplicated in ToolChains.cpp.
5593   bool ARC = isObjCAutoRefCount(Args);
5594   if (ARC) {
5595     getToolChain().CheckObjCARC();
5596
5597     CmdArgs.push_back("-fobjc-arc");
5598
5599     // FIXME: It seems like this entire block, and several around it should be
5600     // wrapped in isObjC, but for now we just use it here as this is where it
5601     // was being used previously.
5602     if (types::isCXX(InputType) && types::isObjC(InputType)) {
5603       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5604         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5605       else
5606         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5607     }
5608
5609     // Allow the user to enable full exceptions code emission.
5610     // We define off for Objective-CC, on for Objective-C++.
5611     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5612                      options::OPT_fno_objc_arc_exceptions,
5613                      /*default*/ types::isCXX(InputType)))
5614       CmdArgs.push_back("-fobjc-arc-exceptions");
5615
5616   }
5617
5618   // -fobjc-infer-related-result-type is the default, except in the Objective-C
5619   // rewriter.
5620   if (rewriteKind != RK_None)
5621     CmdArgs.push_back("-fno-objc-infer-related-result-type");
5622
5623   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5624   // takes precedence.
5625   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5626   if (!GCArg)
5627     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5628   if (GCArg) {
5629     if (ARC) {
5630       D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5631     } else if (getToolChain().SupportsObjCGC()) {
5632       GCArg->render(Args, CmdArgs);
5633     } else {
5634       // FIXME: We should move this to a hard error.
5635       D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5636     }
5637   }
5638
5639   // Pass down -fobjc-weak or -fno-objc-weak if present.
5640   if (types::isObjC(InputType)) {
5641     auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5642                                    options::OPT_fno_objc_weak);
5643     if (!WeakArg) {
5644       // nothing to do
5645     } else if (GCArg) {
5646       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5647         D.Diag(diag::err_objc_weak_with_gc);
5648     } else if (!objcRuntime.allowsWeak()) {
5649       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5650         D.Diag(diag::err_objc_weak_unsupported);
5651     } else {
5652       WeakArg->render(Args, CmdArgs);
5653     }
5654   }
5655
5656   if (Args.hasFlag(options::OPT_fapplication_extension,
5657                    options::OPT_fno_application_extension, false))
5658     CmdArgs.push_back("-fapplication-extension");
5659
5660   // Handle GCC-style exception args.
5661   if (!C.getDriver().IsCLMode())
5662     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5663                      CmdArgs);
5664
5665   if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
5666       getToolChain().UseSjLjExceptions(Args))
5667     CmdArgs.push_back("-fsjlj-exceptions");
5668
5669   // C++ "sane" operator new.
5670   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5671                     options::OPT_fno_assume_sane_operator_new))
5672     CmdArgs.push_back("-fno-assume-sane-operator-new");
5673
5674   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5675   // most platforms.
5676   if (Args.hasFlag(options::OPT_fsized_deallocation,
5677                    options::OPT_fno_sized_deallocation, false))
5678     CmdArgs.push_back("-fsized-deallocation");
5679
5680   // -fconstant-cfstrings is default, and may be subject to argument translation
5681   // on Darwin.
5682   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5683                     options::OPT_fno_constant_cfstrings) ||
5684       !Args.hasFlag(options::OPT_mconstant_cfstrings,
5685                     options::OPT_mno_constant_cfstrings))
5686     CmdArgs.push_back("-fno-constant-cfstrings");
5687
5688   // -fshort-wchar default varies depending on platform; only
5689   // pass if specified.
5690   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5691                                options::OPT_fno_short_wchar))
5692     A->render(Args, CmdArgs);
5693
5694   // -fno-pascal-strings is default, only pass non-default.
5695   if (Args.hasFlag(options::OPT_fpascal_strings,
5696                    options::OPT_fno_pascal_strings, false))
5697     CmdArgs.push_back("-fpascal-strings");
5698
5699   // Honor -fpack-struct= and -fpack-struct, if given. Note that
5700   // -fno-pack-struct doesn't apply to -fpack-struct=.
5701   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5702     std::string PackStructStr = "-fpack-struct=";
5703     PackStructStr += A->getValue();
5704     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5705   } else if (Args.hasFlag(options::OPT_fpack_struct,
5706                           options::OPT_fno_pack_struct, false)) {
5707     CmdArgs.push_back("-fpack-struct=1");
5708   }
5709
5710   // Handle -fmax-type-align=N and -fno-type-align
5711   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5712   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5713     if (!SkipMaxTypeAlign) {
5714       std::string MaxTypeAlignStr = "-fmax-type-align=";
5715       MaxTypeAlignStr += A->getValue();
5716       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5717     }
5718   } else if (getToolChain().getTriple().isOSDarwin()) {
5719     if (!SkipMaxTypeAlign) {
5720       std::string MaxTypeAlignStr = "-fmax-type-align=16";
5721       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5722     }
5723   }
5724
5725   // -fcommon is the default unless compiling kernel code or the target says so
5726   bool NoCommonDefault =
5727       KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5728   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5729                     !NoCommonDefault))
5730     CmdArgs.push_back("-fno-common");
5731
5732   // -fsigned-bitfields is default, and clang doesn't yet support
5733   // -funsigned-bitfields.
5734   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5735                     options::OPT_funsigned_bitfields))
5736     D.Diag(diag::warn_drv_clang_unsupported)
5737         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5738
5739   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5740   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5741     D.Diag(diag::err_drv_clang_unsupported)
5742         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5743
5744   // -finput_charset=UTF-8 is default. Reject others
5745   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5746     StringRef value = inputCharset->getValue();
5747     if (value != "UTF-8")
5748       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5749                                           << value;
5750   }
5751
5752   // -fexec_charset=UTF-8 is default. Reject others
5753   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5754     StringRef value = execCharset->getValue();
5755     if (value != "UTF-8")
5756       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5757                                           << value;
5758   }
5759
5760   // -fcaret-diagnostics is default.
5761   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5762                     options::OPT_fno_caret_diagnostics, true))
5763     CmdArgs.push_back("-fno-caret-diagnostics");
5764
5765   // -fdiagnostics-fixit-info is default, only pass non-default.
5766   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5767                     options::OPT_fno_diagnostics_fixit_info))
5768     CmdArgs.push_back("-fno-diagnostics-fixit-info");
5769
5770   // Enable -fdiagnostics-show-option by default.
5771   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5772                    options::OPT_fno_diagnostics_show_option))
5773     CmdArgs.push_back("-fdiagnostics-show-option");
5774
5775   if (const Arg *A =
5776           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5777     CmdArgs.push_back("-fdiagnostics-show-category");
5778     CmdArgs.push_back(A->getValue());
5779   }
5780
5781   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5782     CmdArgs.push_back("-fdiagnostics-format");
5783     CmdArgs.push_back(A->getValue());
5784   }
5785
5786   if (Arg *A = Args.getLastArg(
5787           options::OPT_fdiagnostics_show_note_include_stack,
5788           options::OPT_fno_diagnostics_show_note_include_stack)) {
5789     if (A->getOption().matches(
5790             options::OPT_fdiagnostics_show_note_include_stack))
5791       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5792     else
5793       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5794   }
5795
5796   // Color diagnostics are parsed by the driver directly from argv
5797   // and later re-parsed to construct this job; claim any possible
5798   // color diagnostic here to avoid warn_drv_unused_argument and
5799   // diagnose bad OPT_fdiagnostics_color_EQ values.
5800   for (Arg *A : Args) {
5801     const Option &O = A->getOption();
5802     if (!O.matches(options::OPT_fcolor_diagnostics) &&
5803         !O.matches(options::OPT_fdiagnostics_color) &&
5804         !O.matches(options::OPT_fno_color_diagnostics) &&
5805         !O.matches(options::OPT_fno_diagnostics_color) &&
5806         !O.matches(options::OPT_fdiagnostics_color_EQ))
5807       continue;
5808     if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
5809       StringRef Value(A->getValue());
5810       if (Value != "always" && Value != "never" && Value != "auto")
5811         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5812               << ("-fdiagnostics-color=" + Value).str();
5813     }
5814     A->claim();
5815   }
5816   if (D.getDiags().getDiagnosticOptions().ShowColors)
5817     CmdArgs.push_back("-fcolor-diagnostics");
5818
5819   if (Args.hasArg(options::OPT_fansi_escape_codes))
5820     CmdArgs.push_back("-fansi-escape-codes");
5821
5822   if (!Args.hasFlag(options::OPT_fshow_source_location,
5823                     options::OPT_fno_show_source_location))
5824     CmdArgs.push_back("-fno-show-source-location");
5825
5826   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5827                     true))
5828     CmdArgs.push_back("-fno-show-column");
5829
5830   if (!Args.hasFlag(options::OPT_fspell_checking,
5831                     options::OPT_fno_spell_checking))
5832     CmdArgs.push_back("-fno-spell-checking");
5833
5834   // -fno-asm-blocks is default.
5835   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5836                    false))
5837     CmdArgs.push_back("-fasm-blocks");
5838
5839   // -fgnu-inline-asm is default.
5840   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5841                     options::OPT_fno_gnu_inline_asm, true))
5842     CmdArgs.push_back("-fno-gnu-inline-asm");
5843
5844   // Enable vectorization per default according to the optimization level
5845   // selected. For optimization levels that want vectorization we use the alias
5846   // option to simplify the hasFlag logic.
5847   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5848   OptSpecifier VectorizeAliasOption =
5849       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5850   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5851                    options::OPT_fno_vectorize, EnableVec))
5852     CmdArgs.push_back("-vectorize-loops");
5853
5854   // -fslp-vectorize is enabled based on the optimization level selected.
5855   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5856   OptSpecifier SLPVectAliasOption =
5857       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5858   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5859                    options::OPT_fno_slp_vectorize, EnableSLPVec))
5860     CmdArgs.push_back("-vectorize-slp");
5861
5862   // -fno-slp-vectorize-aggressive is default.
5863   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5864                    options::OPT_fno_slp_vectorize_aggressive, false))
5865     CmdArgs.push_back("-vectorize-slp-aggressive");
5866
5867   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5868     A->render(Args, CmdArgs);
5869
5870   if (Arg *A = Args.getLastArg(
5871           options::OPT_fsanitize_undefined_strip_path_components_EQ))
5872     A->render(Args, CmdArgs);
5873
5874   // -fdollars-in-identifiers default varies depending on platform and
5875   // language; only pass if specified.
5876   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5877                                options::OPT_fno_dollars_in_identifiers)) {
5878     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5879       CmdArgs.push_back("-fdollars-in-identifiers");
5880     else
5881       CmdArgs.push_back("-fno-dollars-in-identifiers");
5882   }
5883
5884   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5885   // practical purposes.
5886   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5887                                options::OPT_fno_unit_at_a_time)) {
5888     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5889       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5890   }
5891
5892   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5893                    options::OPT_fno_apple_pragma_pack, false))
5894     CmdArgs.push_back("-fapple-pragma-pack");
5895
5896   // le32-specific flags:
5897   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
5898   //                     by default.
5899   if (getToolChain().getArch() == llvm::Triple::le32) {
5900     CmdArgs.push_back("-fno-math-builtin");
5901   }
5902
5903 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5904 //
5905 // FIXME: Now that PR4941 has been fixed this can be enabled.
5906 #if 0
5907   if (getToolChain().getTriple().isOSDarwin() &&
5908       (getToolChain().getArch() == llvm::Triple::arm ||
5909        getToolChain().getArch() == llvm::Triple::thumb)) {
5910     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5911       CmdArgs.push_back("-fno-builtin-strcat");
5912     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5913       CmdArgs.push_back("-fno-builtin-strcpy");
5914   }
5915 #endif
5916
5917   // Enable rewrite includes if the user's asked for it or if we're generating
5918   // diagnostics.
5919   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5920   // nice to enable this when doing a crashdump for modules as well.
5921   if (Args.hasFlag(options::OPT_frewrite_includes,
5922                    options::OPT_fno_rewrite_includes, false) ||
5923       (C.isForDiagnostics() && !HaveModules))
5924     CmdArgs.push_back("-frewrite-includes");
5925
5926   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5927   if (Arg *A = Args.getLastArg(options::OPT_traditional,
5928                                options::OPT_traditional_cpp)) {
5929     if (isa<PreprocessJobAction>(JA))
5930       CmdArgs.push_back("-traditional-cpp");
5931     else
5932       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5933   }
5934
5935   Args.AddLastArg(CmdArgs, options::OPT_dM);
5936   Args.AddLastArg(CmdArgs, options::OPT_dD);
5937
5938   // Handle serialized diagnostics.
5939   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5940     CmdArgs.push_back("-serialize-diagnostic-file");
5941     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5942   }
5943
5944   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5945     CmdArgs.push_back("-fretain-comments-from-system-headers");
5946
5947   // Forward -fcomment-block-commands to -cc1.
5948   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5949   // Forward -fparse-all-comments to -cc1.
5950   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5951
5952   // Turn -fplugin=name.so into -load name.so
5953   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5954     CmdArgs.push_back("-load");
5955     CmdArgs.push_back(A->getValue());
5956     A->claim();
5957   }
5958
5959   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5960   // parser.
5961   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5962   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5963     A->claim();
5964
5965     // We translate this by hand to the -cc1 argument, since nightly test uses
5966     // it and developers have been trained to spell it with -mllvm.
5967     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5968       CmdArgs.push_back("-disable-llvm-optzns");
5969     } else
5970       A->render(Args, CmdArgs);
5971   }
5972
5973   // With -save-temps, we want to save the unoptimized bitcode output from the
5974   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5975   // by the frontend.
5976   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5977   // has slightly different breakdown between stages.
5978   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5979   // pristine IR generated by the frontend. Ideally, a new compile action should
5980   // be added so both IR can be captured.
5981   if (C.getDriver().isSaveTempsEnabled() &&
5982       !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
5983     CmdArgs.push_back("-disable-llvm-passes");
5984
5985   if (Output.getType() == types::TY_Dependencies) {
5986     // Handled with other dependency code.
5987   } else if (Output.isFilename()) {
5988     CmdArgs.push_back("-o");
5989     CmdArgs.push_back(Output.getFilename());
5990   } else {
5991     assert(Output.isNothing() && "Invalid output.");
5992   }
5993
5994   addDashXForInput(Args, Input, CmdArgs);
5995
5996   if (Input.isFilename())
5997     CmdArgs.push_back(Input.getFilename());
5998   else
5999     Input.getInputArg().renderAsInput(Args, CmdArgs);
6000
6001   Args.AddAllArgs(CmdArgs, options::OPT_undef);
6002
6003   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6004
6005   // Optionally embed the -cc1 level arguments into the debug info, for build
6006   // analysis.
6007   if (getToolChain().UseDwarfDebugFlags()) {
6008     ArgStringList OriginalArgs;
6009     for (const auto &Arg : Args)
6010       Arg->render(Args, OriginalArgs);
6011
6012     SmallString<256> Flags;
6013     Flags += Exec;
6014     for (const char *OriginalArg : OriginalArgs) {
6015       SmallString<128> EscapedArg;
6016       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6017       Flags += " ";
6018       Flags += EscapedArg;
6019     }
6020     CmdArgs.push_back("-dwarf-debug-flags");
6021     CmdArgs.push_back(Args.MakeArgString(Flags));
6022   }
6023
6024   // Add the split debug info name to the command lines here so we
6025   // can propagate it to the backend.
6026   bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
6027                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6028                      isa<BackendJobAction>(JA));
6029   const char *SplitDwarfOut;
6030   if (SplitDwarf) {
6031     CmdArgs.push_back("-split-dwarf-file");
6032     SplitDwarfOut = SplitDebugName(Args, Input);
6033     CmdArgs.push_back(SplitDwarfOut);
6034   }
6035
6036   // Host-side cuda compilation receives device-side outputs as Inputs[1...].
6037   // Include them with -fcuda-include-gpubinary.
6038   if (IsCuda && Inputs.size() > 1)
6039     for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
6040       CmdArgs.push_back("-fcuda-include-gpubinary");
6041       CmdArgs.push_back(I->getFilename());
6042     }
6043
6044   bool WholeProgramVTables =
6045       Args.hasFlag(options::OPT_fwhole_program_vtables,
6046                    options::OPT_fno_whole_program_vtables, false);
6047   if (WholeProgramVTables) {
6048     if (!D.isUsingLTO())
6049       D.Diag(diag::err_drv_argument_only_allowed_with)
6050           << "-fwhole-program-vtables"
6051           << "-flto";
6052     CmdArgs.push_back("-fwhole-program-vtables");
6053   }
6054
6055   // Finally add the compile command to the compilation.
6056   if (Args.hasArg(options::OPT__SLASH_fallback) &&
6057       Output.getType() == types::TY_Object &&
6058       (InputType == types::TY_C || InputType == types::TY_CXX)) {
6059     auto CLCommand =
6060         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
6061     C.addCommand(llvm::make_unique<FallbackCommand>(
6062         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
6063   } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
6064              isa<PrecompileJobAction>(JA)) {
6065     // In /fallback builds, run the main compilation even if the pch generation
6066     // fails, so that the main compilation's fallback to cl.exe runs.
6067     C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
6068                                                         CmdArgs, Inputs));
6069   } else {
6070     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6071   }
6072
6073   // Handle the debug info splitting at object creation time if we're
6074   // creating an object.
6075   // TODO: Currently only works on linux with newer objcopy.
6076   if (SplitDwarf && Output.getType() == types::TY_Object)
6077     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
6078
6079   if (Arg *A = Args.getLastArg(options::OPT_pg))
6080     if (Args.hasArg(options::OPT_fomit_frame_pointer))
6081       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6082                                                       << A->getAsString(Args);
6083
6084   // Claim some arguments which clang supports automatically.
6085
6086   // -fpch-preprocess is used with gcc to add a special marker in the output to
6087   // include the PCH file. Clang's PTH solution is completely transparent, so we
6088   // do not need to deal with it at all.
6089   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6090
6091   // Claim some arguments which clang doesn't support, but we don't
6092   // care to warn the user about.
6093   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6094   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6095
6096   // Disable warnings for clang -E -emit-llvm foo.c
6097   Args.ClaimAllArgs(options::OPT_emit_llvm);
6098 }
6099
6100 /// Add options related to the Objective-C runtime/ABI.
6101 ///
6102 /// Returns true if the runtime is non-fragile.
6103 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6104                                       ArgStringList &cmdArgs,
6105                                       RewriteKind rewriteKind) const {
6106   // Look for the controlling runtime option.
6107   Arg *runtimeArg =
6108       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6109                       options::OPT_fobjc_runtime_EQ);
6110
6111   // Just forward -fobjc-runtime= to the frontend.  This supercedes
6112   // options about fragility.
6113   if (runtimeArg &&
6114       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6115     ObjCRuntime runtime;
6116     StringRef value = runtimeArg->getValue();
6117     if (runtime.tryParse(value)) {
6118       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6119           << value;
6120     }
6121
6122     runtimeArg->render(args, cmdArgs);
6123     return runtime;
6124   }
6125
6126   // Otherwise, we'll need the ABI "version".  Version numbers are
6127   // slightly confusing for historical reasons:
6128   //   1 - Traditional "fragile" ABI
6129   //   2 - Non-fragile ABI, version 1
6130   //   3 - Non-fragile ABI, version 2
6131   unsigned objcABIVersion = 1;
6132   // If -fobjc-abi-version= is present, use that to set the version.
6133   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6134     StringRef value = abiArg->getValue();
6135     if (value == "1")
6136       objcABIVersion = 1;
6137     else if (value == "2")
6138       objcABIVersion = 2;
6139     else if (value == "3")
6140       objcABIVersion = 3;
6141     else
6142       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6143   } else {
6144     // Otherwise, determine if we are using the non-fragile ABI.
6145     bool nonFragileABIIsDefault =
6146         (rewriteKind == RK_NonFragile ||
6147          (rewriteKind == RK_None &&
6148           getToolChain().IsObjCNonFragileABIDefault()));
6149     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6150                      options::OPT_fno_objc_nonfragile_abi,
6151                      nonFragileABIIsDefault)) {
6152 // Determine the non-fragile ABI version to use.
6153 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6154       unsigned nonFragileABIVersion = 1;
6155 #else
6156       unsigned nonFragileABIVersion = 2;
6157 #endif
6158
6159       if (Arg *abiArg =
6160               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6161         StringRef value = abiArg->getValue();
6162         if (value == "1")
6163           nonFragileABIVersion = 1;
6164         else if (value == "2")
6165           nonFragileABIVersion = 2;
6166         else
6167           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6168               << value;
6169       }
6170
6171       objcABIVersion = 1 + nonFragileABIVersion;
6172     } else {
6173       objcABIVersion = 1;
6174     }
6175   }
6176
6177   // We don't actually care about the ABI version other than whether
6178   // it's non-fragile.
6179   bool isNonFragile = objcABIVersion != 1;
6180
6181   // If we have no runtime argument, ask the toolchain for its default runtime.
6182   // However, the rewriter only really supports the Mac runtime, so assume that.
6183   ObjCRuntime runtime;
6184   if (!runtimeArg) {
6185     switch (rewriteKind) {
6186     case RK_None:
6187       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6188       break;
6189     case RK_Fragile:
6190       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6191       break;
6192     case RK_NonFragile:
6193       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6194       break;
6195     }
6196
6197     // -fnext-runtime
6198   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6199     // On Darwin, make this use the default behavior for the toolchain.
6200     if (getToolChain().getTriple().isOSDarwin()) {
6201       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6202
6203       // Otherwise, build for a generic macosx port.
6204     } else {
6205       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6206     }
6207
6208     // -fgnu-runtime
6209   } else {
6210     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6211     // Legacy behaviour is to target the gnustep runtime if we are in
6212     // non-fragile mode or the GCC runtime in fragile mode.
6213     if (isNonFragile)
6214       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
6215     else
6216       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6217   }
6218
6219   cmdArgs.push_back(
6220       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6221   return runtime;
6222 }
6223
6224 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6225   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6226   I += HaveDash;
6227   return !HaveDash;
6228 }
6229
6230 namespace {
6231 struct EHFlags {
6232   bool Synch = false;
6233   bool Asynch = false;
6234   bool NoUnwindC = false;
6235 };
6236 } // end anonymous namespace
6237
6238 /// /EH controls whether to run destructor cleanups when exceptions are
6239 /// thrown.  There are three modifiers:
6240 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
6241 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
6242 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
6243 /// - c: Assume that extern "C" functions are implicitly nounwind.
6244 /// The default is /EHs-c-, meaning cleanups are disabled.
6245 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
6246   EHFlags EH;
6247
6248   std::vector<std::string> EHArgs =
6249       Args.getAllArgValues(options::OPT__SLASH_EH);
6250   for (auto EHVal : EHArgs) {
6251     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
6252       switch (EHVal[I]) {
6253       case 'a':
6254         EH.Asynch = maybeConsumeDash(EHVal, I);
6255         if (EH.Asynch)
6256           EH.Synch = false;
6257         continue;
6258       case 'c':
6259         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
6260         continue;
6261       case 's':
6262         EH.Synch = maybeConsumeDash(EHVal, I);
6263         if (EH.Synch)
6264           EH.Asynch = false;
6265         continue;
6266       default:
6267         break;
6268       }
6269       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
6270       break;
6271     }
6272   }
6273   // The /GX, /GX- flags are only processed if there are not /EH flags.
6274   // The default is that /GX is not specified.
6275   if (EHArgs.empty() &&
6276       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
6277                    /*default=*/false)) {
6278     EH.Synch = true;
6279     EH.NoUnwindC = true;
6280   }
6281
6282   return EH;
6283 }
6284
6285 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
6286                            ArgStringList &CmdArgs,
6287                            codegenoptions::DebugInfoKind *DebugInfoKind,
6288                            bool *EmitCodeView) const {
6289   unsigned RTOptionID = options::OPT__SLASH_MT;
6290
6291   if (Args.hasArg(options::OPT__SLASH_LDd))
6292     // The /LDd option implies /MTd. The dependent lib part can be overridden,
6293     // but defining _DEBUG is sticky.
6294     RTOptionID = options::OPT__SLASH_MTd;
6295
6296   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
6297     RTOptionID = A->getOption().getID();
6298
6299   StringRef FlagForCRT;
6300   switch (RTOptionID) {
6301   case options::OPT__SLASH_MD:
6302     if (Args.hasArg(options::OPT__SLASH_LDd))
6303       CmdArgs.push_back("-D_DEBUG");
6304     CmdArgs.push_back("-D_MT");
6305     CmdArgs.push_back("-D_DLL");
6306     FlagForCRT = "--dependent-lib=msvcrt";
6307     break;
6308   case options::OPT__SLASH_MDd:
6309     CmdArgs.push_back("-D_DEBUG");
6310     CmdArgs.push_back("-D_MT");
6311     CmdArgs.push_back("-D_DLL");
6312     FlagForCRT = "--dependent-lib=msvcrtd";
6313     break;
6314   case options::OPT__SLASH_MT:
6315     if (Args.hasArg(options::OPT__SLASH_LDd))
6316       CmdArgs.push_back("-D_DEBUG");
6317     CmdArgs.push_back("-D_MT");
6318     CmdArgs.push_back("-flto-visibility-public-std");
6319     FlagForCRT = "--dependent-lib=libcmt";
6320     break;
6321   case options::OPT__SLASH_MTd:
6322     CmdArgs.push_back("-D_DEBUG");
6323     CmdArgs.push_back("-D_MT");
6324     CmdArgs.push_back("-flto-visibility-public-std");
6325     FlagForCRT = "--dependent-lib=libcmtd";
6326     break;
6327   default:
6328     llvm_unreachable("Unexpected option ID.");
6329   }
6330
6331   if (Args.hasArg(options::OPT__SLASH_Zl)) {
6332     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
6333   } else {
6334     CmdArgs.push_back(FlagForCRT.data());
6335
6336     // This provides POSIX compatibility (maps 'open' to '_open'), which most
6337     // users want.  The /Za flag to cl.exe turns this off, but it's not
6338     // implemented in clang.
6339     CmdArgs.push_back("--dependent-lib=oldnames");
6340   }
6341
6342   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
6343   // would produce interleaved output, so ignore /showIncludes in such cases.
6344   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
6345     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
6346       A->render(Args, CmdArgs);
6347
6348   // This controls whether or not we emit RTTI data for polymorphic types.
6349   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
6350                    /*default=*/false))
6351     CmdArgs.push_back("-fno-rtti-data");
6352
6353   // This controls whether or not we emit stack-protector instrumentation.
6354   // In MSVC, Buffer Security Check (/GS) is on by default.
6355   if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
6356                    /*default=*/true)) {
6357     CmdArgs.push_back("-stack-protector");
6358     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
6359   }
6360
6361   // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
6362   if (Arg *DebugInfoArg =
6363           Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
6364                           options::OPT_gline_tables_only)) {
6365     *EmitCodeView = true;
6366     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
6367       *DebugInfoKind = codegenoptions::LimitedDebugInfo;
6368     else
6369       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
6370     CmdArgs.push_back("-gcodeview");
6371   } else {
6372     *EmitCodeView = false;
6373   }
6374
6375   const Driver &D = getToolChain().getDriver();
6376   EHFlags EH = parseClangCLEHFlags(D, Args);
6377   if (EH.Synch || EH.Asynch) {
6378     if (types::isCXX(InputType))
6379       CmdArgs.push_back("-fcxx-exceptions");
6380     CmdArgs.push_back("-fexceptions");
6381   }
6382   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
6383     CmdArgs.push_back("-fexternc-nounwind");
6384
6385   // /EP should expand to -E -P.
6386   if (Args.hasArg(options::OPT__SLASH_EP)) {
6387     CmdArgs.push_back("-E");
6388     CmdArgs.push_back("-P");
6389   }
6390
6391   unsigned VolatileOptionID;
6392   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
6393       getToolChain().getArch() == llvm::Triple::x86)
6394     VolatileOptionID = options::OPT__SLASH_volatile_ms;
6395   else
6396     VolatileOptionID = options::OPT__SLASH_volatile_iso;
6397
6398   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
6399     VolatileOptionID = A->getOption().getID();
6400
6401   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
6402     CmdArgs.push_back("-fms-volatile");
6403
6404   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
6405   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
6406   if (MostGeneralArg && BestCaseArg)
6407     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6408         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
6409
6410   if (MostGeneralArg) {
6411     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
6412     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
6413     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
6414
6415     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
6416     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
6417     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
6418       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6419           << FirstConflict->getAsString(Args)
6420           << SecondConflict->getAsString(Args);
6421
6422     if (SingleArg)
6423       CmdArgs.push_back("-fms-memptr-rep=single");
6424     else if (MultipleArg)
6425       CmdArgs.push_back("-fms-memptr-rep=multiple");
6426     else
6427       CmdArgs.push_back("-fms-memptr-rep=virtual");
6428   }
6429
6430   if (Args.getLastArg(options::OPT__SLASH_Gd))
6431      CmdArgs.push_back("-fdefault-calling-conv=cdecl");
6432   else if (Args.getLastArg(options::OPT__SLASH_Gr))
6433      CmdArgs.push_back("-fdefault-calling-conv=fastcall");
6434   else if (Args.getLastArg(options::OPT__SLASH_Gz))
6435      CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6436   else if (Args.getLastArg(options::OPT__SLASH_Gv))
6437      CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
6438
6439   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
6440     A->render(Args, CmdArgs);
6441
6442   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6443     CmdArgs.push_back("-fdiagnostics-format");
6444     if (Args.hasArg(options::OPT__SLASH_fallback))
6445       CmdArgs.push_back("msvc-fallback");
6446     else
6447       CmdArgs.push_back("msvc");
6448   }
6449 }
6450
6451 visualstudio::Compiler *Clang::getCLFallback() const {
6452   if (!CLFallback)
6453     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6454   return CLFallback.get();
6455 }
6456
6457 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6458                                 ArgStringList &CmdArgs) const {
6459   StringRef CPUName;
6460   StringRef ABIName;
6461   const llvm::Triple &Triple = getToolChain().getTriple();
6462   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6463
6464   CmdArgs.push_back("-target-abi");
6465   CmdArgs.push_back(ABIName.data());
6466 }
6467
6468 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6469                            const InputInfo &Output, const InputInfoList &Inputs,
6470                            const ArgList &Args,
6471                            const char *LinkingOutput) const {
6472   ArgStringList CmdArgs;
6473
6474   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6475   const InputInfo &Input = Inputs[0];
6476
6477   std::string TripleStr =
6478       getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
6479   const llvm::Triple Triple(TripleStr);
6480
6481   // Don't warn about "clang -w -c foo.s"
6482   Args.ClaimAllArgs(options::OPT_w);
6483   // and "clang -emit-llvm -c foo.s"
6484   Args.ClaimAllArgs(options::OPT_emit_llvm);
6485
6486   claimNoWarnArgs(Args);
6487
6488   // Invoke ourselves in -cc1as mode.
6489   //
6490   // FIXME: Implement custom jobs for internal actions.
6491   CmdArgs.push_back("-cc1as");
6492
6493   // Add the "effective" target triple.
6494   CmdArgs.push_back("-triple");
6495   CmdArgs.push_back(Args.MakeArgString(TripleStr));
6496
6497   // Set the output mode, we currently only expect to be used as a real
6498   // assembler.
6499   CmdArgs.push_back("-filetype");
6500   CmdArgs.push_back("obj");
6501
6502   // Set the main file name, so that debug info works even with
6503   // -save-temps or preprocessed assembly.
6504   CmdArgs.push_back("-main-file-name");
6505   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6506
6507   // Add the target cpu
6508   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6509   if (!CPU.empty()) {
6510     CmdArgs.push_back("-target-cpu");
6511     CmdArgs.push_back(Args.MakeArgString(CPU));
6512   }
6513
6514   // Add the target features
6515   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6516
6517   // Ignore explicit -force_cpusubtype_ALL option.
6518   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6519
6520   // Pass along any -I options so we get proper .include search paths.
6521   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6522
6523   // Determine the original source input.
6524   const Action *SourceAction = &JA;
6525   while (SourceAction->getKind() != Action::InputClass) {
6526     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6527     SourceAction = SourceAction->getInputs()[0];
6528   }
6529
6530   // Forward -g and handle debug info related flags, assuming we are dealing
6531   // with an actual assembly file.
6532   bool WantDebug = false;
6533   unsigned DwarfVersion = 0;
6534   Args.ClaimAllArgs(options::OPT_g_Group);
6535   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6536     WantDebug = !A->getOption().matches(options::OPT_g0) &&
6537                 !A->getOption().matches(options::OPT_ggdb0);
6538     if (WantDebug)
6539       DwarfVersion = DwarfVersionNum(A->getSpelling());
6540   }
6541   if (DwarfVersion == 0)
6542     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6543
6544   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6545
6546   if (SourceAction->getType() == types::TY_Asm ||
6547       SourceAction->getType() == types::TY_PP_Asm) {
6548     // You might think that it would be ok to set DebugInfoKind outside of
6549     // the guard for source type, however there is a test which asserts
6550     // that some assembler invocation receives no -debug-info-kind,
6551     // and it's not clear whether that test is just overly restrictive.
6552     DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6553                                : codegenoptions::NoDebugInfo);
6554     // Add the -fdebug-compilation-dir flag if needed.
6555     addDebugCompDirArg(Args, CmdArgs);
6556
6557     // Set the AT_producer to the clang version when using the integrated
6558     // assembler on assembly source files.
6559     CmdArgs.push_back("-dwarf-debug-producer");
6560     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6561
6562     // And pass along -I options
6563     Args.AddAllArgs(CmdArgs, options::OPT_I);
6564   }
6565   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6566                           llvm::DebuggerKind::Default);
6567
6568   // Handle -fPIC et al -- the relocation-model affects the assembler
6569   // for some targets.
6570   llvm::Reloc::Model RelocationModel;
6571   unsigned PICLevel;
6572   bool IsPIE;
6573   std::tie(RelocationModel, PICLevel, IsPIE) =
6574       ParsePICArgs(getToolChain(), Triple, Args);
6575
6576   const char *RMName = RelocationModelName(RelocationModel);
6577   if (RMName) {
6578     CmdArgs.push_back("-mrelocation-model");
6579     CmdArgs.push_back(RMName);
6580   }
6581
6582   // Optionally embed the -cc1as level arguments into the debug info, for build
6583   // analysis.
6584   if (getToolChain().UseDwarfDebugFlags()) {
6585     ArgStringList OriginalArgs;
6586     for (const auto &Arg : Args)
6587       Arg->render(Args, OriginalArgs);
6588
6589     SmallString<256> Flags;
6590     const char *Exec = getToolChain().getDriver().getClangProgramPath();
6591     Flags += Exec;
6592     for (const char *OriginalArg : OriginalArgs) {
6593       SmallString<128> EscapedArg;
6594       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6595       Flags += " ";
6596       Flags += EscapedArg;
6597     }
6598     CmdArgs.push_back("-dwarf-debug-flags");
6599     CmdArgs.push_back(Args.MakeArgString(Flags));
6600   }
6601
6602   // FIXME: Add -static support, once we have it.
6603
6604   // Add target specific flags.
6605   switch (getToolChain().getArch()) {
6606   default:
6607     break;
6608
6609   case llvm::Triple::mips:
6610   case llvm::Triple::mipsel:
6611   case llvm::Triple::mips64:
6612   case llvm::Triple::mips64el:
6613     AddMIPSTargetArgs(Args, CmdArgs);
6614     break;
6615   }
6616
6617   // Consume all the warning flags. Usually this would be handled more
6618   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6619   // doesn't handle that so rather than warning about unused flags that are
6620   // actually used, we'll lie by omission instead.
6621   // FIXME: Stop lying and consume only the appropriate driver flags
6622   Args.ClaimAllArgs(options::OPT_W_Group);
6623
6624   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6625                                     getToolChain().getDriver());
6626
6627   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6628
6629   assert(Output.isFilename() && "Unexpected lipo output.");
6630   CmdArgs.push_back("-o");
6631   CmdArgs.push_back(Output.getFilename());
6632
6633   assert(Input.isFilename() && "Invalid input.");
6634   CmdArgs.push_back(Input.getFilename());
6635
6636   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6637   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6638
6639   // Handle the debug info splitting at object creation time if we're
6640   // creating an object.
6641   // TODO: Currently only works on linux with newer objcopy.
6642   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6643       getToolChain().getTriple().isOSLinux())
6644     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6645                    SplitDebugName(Args, Input));
6646 }
6647
6648 void GnuTool::anchor() {}
6649
6650 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6651                                const InputInfo &Output,
6652                                const InputInfoList &Inputs, const ArgList &Args,
6653                                const char *LinkingOutput) const {
6654   const Driver &D = getToolChain().getDriver();
6655   ArgStringList CmdArgs;
6656
6657   for (const auto &A : Args) {
6658     if (forwardToGCC(A->getOption())) {
6659       // It is unfortunate that we have to claim here, as this means
6660       // we will basically never report anything interesting for
6661       // platforms using a generic gcc, even if we are just using gcc
6662       // to get to the assembler.
6663       A->claim();
6664
6665       // Don't forward any -g arguments to assembly steps.
6666       if (isa<AssembleJobAction>(JA) &&
6667           A->getOption().matches(options::OPT_g_Group))
6668         continue;
6669
6670       // Don't forward any -W arguments to assembly and link steps.
6671       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6672           A->getOption().matches(options::OPT_W_Group))
6673         continue;
6674
6675       A->render(Args, CmdArgs);
6676     }
6677   }
6678
6679   RenderExtraToolArgs(JA, CmdArgs);
6680
6681   // If using a driver driver, force the arch.
6682   if (getToolChain().getTriple().isOSDarwin()) {
6683     CmdArgs.push_back("-arch");
6684     CmdArgs.push_back(
6685         Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6686   }
6687
6688   // Try to force gcc to match the tool chain we want, if we recognize
6689   // the arch.
6690   //
6691   // FIXME: The triple class should directly provide the information we want
6692   // here.
6693   switch (getToolChain().getArch()) {
6694   default:
6695     break;
6696   case llvm::Triple::x86:
6697   case llvm::Triple::ppc:
6698     CmdArgs.push_back("-m32");
6699     break;
6700   case llvm::Triple::x86_64:
6701   case llvm::Triple::ppc64:
6702   case llvm::Triple::ppc64le:
6703     CmdArgs.push_back("-m64");
6704     break;
6705   case llvm::Triple::sparcel:
6706     CmdArgs.push_back("-EL");
6707     break;
6708   }
6709
6710   if (Output.isFilename()) {
6711     CmdArgs.push_back("-o");
6712     CmdArgs.push_back(Output.getFilename());
6713   } else {
6714     assert(Output.isNothing() && "Unexpected output");
6715     CmdArgs.push_back("-fsyntax-only");
6716   }
6717
6718   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6719
6720   // Only pass -x if gcc will understand it; otherwise hope gcc
6721   // understands the suffix correctly. The main use case this would go
6722   // wrong in is for linker inputs if they happened to have an odd
6723   // suffix; really the only way to get this to happen is a command
6724   // like '-x foobar a.c' which will treat a.c like a linker input.
6725   //
6726   // FIXME: For the linker case specifically, can we safely convert
6727   // inputs into '-Wl,' options?
6728   for (const auto &II : Inputs) {
6729     // Don't try to pass LLVM or AST inputs to a generic gcc.
6730     if (types::isLLVMIR(II.getType()))
6731       D.Diag(diag::err_drv_no_linker_llvm_support)
6732           << getToolChain().getTripleString();
6733     else if (II.getType() == types::TY_AST)
6734       D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6735     else if (II.getType() == types::TY_ModuleFile)
6736       D.Diag(diag::err_drv_no_module_support)
6737           << getToolChain().getTripleString();
6738
6739     if (types::canTypeBeUserSpecified(II.getType())) {
6740       CmdArgs.push_back("-x");
6741       CmdArgs.push_back(types::getTypeName(II.getType()));
6742     }
6743
6744     if (II.isFilename())
6745       CmdArgs.push_back(II.getFilename());
6746     else {
6747       const Arg &A = II.getInputArg();
6748
6749       // Reverse translate some rewritten options.
6750       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6751         CmdArgs.push_back("-lstdc++");
6752         continue;
6753       }
6754
6755       // Don't render as input, we need gcc to do the translations.
6756       A.render(Args, CmdArgs);
6757     }
6758   }
6759
6760   const std::string &customGCCName = D.getCCCGenericGCCName();
6761   const char *GCCName;
6762   if (!customGCCName.empty())
6763     GCCName = customGCCName.c_str();
6764   else if (D.CCCIsCXX()) {
6765     GCCName = "g++";
6766   } else
6767     GCCName = "gcc";
6768
6769   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6770   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6771 }
6772
6773 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6774                                             ArgStringList &CmdArgs) const {
6775   CmdArgs.push_back("-E");
6776 }
6777
6778 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6779                                         ArgStringList &CmdArgs) const {
6780   const Driver &D = getToolChain().getDriver();
6781
6782   switch (JA.getType()) {
6783   // If -flto, etc. are present then make sure not to force assembly output.
6784   case types::TY_LLVM_IR:
6785   case types::TY_LTO_IR:
6786   case types::TY_LLVM_BC:
6787   case types::TY_LTO_BC:
6788     CmdArgs.push_back("-c");
6789     break;
6790   // We assume we've got an "integrated" assembler in that gcc will produce an
6791   // object file itself.
6792   case types::TY_Object:
6793     CmdArgs.push_back("-c");
6794     break;
6795   case types::TY_PP_Asm:
6796     CmdArgs.push_back("-S");
6797     break;
6798   case types::TY_Nothing:
6799     CmdArgs.push_back("-fsyntax-only");
6800     break;
6801   default:
6802     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6803   }
6804 }
6805
6806 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6807                                       ArgStringList &CmdArgs) const {
6808   // The types are (hopefully) good enough.
6809 }
6810
6811 // Hexagon tools start.
6812 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6813                                              ArgStringList &CmdArgs) const {
6814 }
6815
6816 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6817                                       const InputInfo &Output,
6818                                       const InputInfoList &Inputs,
6819                                       const ArgList &Args,
6820                                       const char *LinkingOutput) const {
6821   claimNoWarnArgs(Args);
6822
6823   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6824   const Driver &D = HTC.getDriver();
6825   ArgStringList CmdArgs;
6826
6827   std::string MArchString = "-march=hexagon";
6828   CmdArgs.push_back(Args.MakeArgString(MArchString));
6829
6830   RenderExtraToolArgs(JA, CmdArgs);
6831
6832   std::string AsName = "hexagon-llvm-mc";
6833   std::string MCpuString = "-mcpu=hexagon" +
6834         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6835   CmdArgs.push_back("-filetype=obj");
6836   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6837
6838   if (Output.isFilename()) {
6839     CmdArgs.push_back("-o");
6840     CmdArgs.push_back(Output.getFilename());
6841   } else {
6842     assert(Output.isNothing() && "Unexpected output");
6843     CmdArgs.push_back("-fsyntax-only");
6844   }
6845
6846   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6847     std::string N = llvm::utostr(G.getValue());
6848     CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6849   }
6850
6851   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6852
6853   // Only pass -x if gcc will understand it; otherwise hope gcc
6854   // understands the suffix correctly. The main use case this would go
6855   // wrong in is for linker inputs if they happened to have an odd
6856   // suffix; really the only way to get this to happen is a command
6857   // like '-x foobar a.c' which will treat a.c like a linker input.
6858   //
6859   // FIXME: For the linker case specifically, can we safely convert
6860   // inputs into '-Wl,' options?
6861   for (const auto &II : Inputs) {
6862     // Don't try to pass LLVM or AST inputs to a generic gcc.
6863     if (types::isLLVMIR(II.getType()))
6864       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6865           << HTC.getTripleString();
6866     else if (II.getType() == types::TY_AST)
6867       D.Diag(clang::diag::err_drv_no_ast_support)
6868           << HTC.getTripleString();
6869     else if (II.getType() == types::TY_ModuleFile)
6870       D.Diag(diag::err_drv_no_module_support)
6871           << HTC.getTripleString();
6872
6873     if (II.isFilename())
6874       CmdArgs.push_back(II.getFilename());
6875     else
6876       // Don't render as input, we need gcc to do the translations.
6877       // FIXME: What is this?
6878       II.getInputArg().render(Args, CmdArgs);
6879   }
6880
6881   auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6882   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6883 }
6884
6885 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6886                                           ArgStringList &CmdArgs) const {
6887 }
6888
6889 static void
6890 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6891                          const toolchains::HexagonToolChain &HTC,
6892                          const InputInfo &Output, const InputInfoList &Inputs,
6893                          const ArgList &Args, ArgStringList &CmdArgs,
6894                          const char *LinkingOutput) {
6895
6896   const Driver &D = HTC.getDriver();
6897
6898   //----------------------------------------------------------------------------
6899   //
6900   //----------------------------------------------------------------------------
6901   bool IsStatic = Args.hasArg(options::OPT_static);
6902   bool IsShared = Args.hasArg(options::OPT_shared);
6903   bool IsPIE = Args.hasArg(options::OPT_pie);
6904   bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6905   bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6906   bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6907   bool UseG0 = false;
6908   bool UseShared = IsShared && !IsStatic;
6909
6910   //----------------------------------------------------------------------------
6911   // Silence warnings for various options
6912   //----------------------------------------------------------------------------
6913   Args.ClaimAllArgs(options::OPT_g_Group);
6914   Args.ClaimAllArgs(options::OPT_emit_llvm);
6915   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6916                                      // handled somewhere else.
6917   Args.ClaimAllArgs(options::OPT_static_libgcc);
6918
6919   //----------------------------------------------------------------------------
6920   //
6921   //----------------------------------------------------------------------------
6922   if (Args.hasArg(options::OPT_s))
6923     CmdArgs.push_back("-s");
6924
6925   if (Args.hasArg(options::OPT_r))
6926     CmdArgs.push_back("-r");
6927
6928   for (const auto &Opt : HTC.ExtraOpts)
6929     CmdArgs.push_back(Opt.c_str());
6930
6931   CmdArgs.push_back("-march=hexagon");
6932   std::string CpuVer =
6933         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6934   std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6935   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6936
6937   if (IsShared) {
6938     CmdArgs.push_back("-shared");
6939     // The following should be the default, but doing as hexagon-gcc does.
6940     CmdArgs.push_back("-call_shared");
6941   }
6942
6943   if (IsStatic)
6944     CmdArgs.push_back("-static");
6945
6946   if (IsPIE && !IsShared)
6947     CmdArgs.push_back("-pie");
6948
6949   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6950     std::string N = llvm::utostr(G.getValue());
6951     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6952     UseG0 = G.getValue() == 0;
6953   }
6954
6955   //----------------------------------------------------------------------------
6956   //
6957   //----------------------------------------------------------------------------
6958   CmdArgs.push_back("-o");
6959   CmdArgs.push_back(Output.getFilename());
6960
6961   //----------------------------------------------------------------------------
6962   // moslib
6963   //----------------------------------------------------------------------------
6964   std::vector<std::string> OsLibs;
6965   bool HasStandalone = false;
6966
6967   for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6968     A->claim();
6969     OsLibs.emplace_back(A->getValue());
6970     HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6971   }
6972   if (OsLibs.empty()) {
6973     OsLibs.push_back("standalone");
6974     HasStandalone = true;
6975   }
6976
6977   //----------------------------------------------------------------------------
6978   // Start Files
6979   //----------------------------------------------------------------------------
6980   const std::string MCpuSuffix = "/" + CpuVer;
6981   const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6982   const std::string RootDir =
6983       HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6984   const std::string StartSubDir =
6985       "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6986
6987   auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6988                       const char *Name) -> std::string {
6989     std::string RelName = SubDir + Name;
6990     std::string P = HTC.GetFilePath(RelName.c_str());
6991     if (llvm::sys::fs::exists(P))
6992       return P;
6993     return RootDir + RelName;
6994   };
6995
6996   if (IncStdLib && IncStartFiles) {
6997     if (!IsShared) {
6998       if (HasStandalone) {
6999         std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
7000         CmdArgs.push_back(Args.MakeArgString(Crt0SA));
7001       }
7002       std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
7003       CmdArgs.push_back(Args.MakeArgString(Crt0));
7004     }
7005     std::string Init = UseShared
7006           ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
7007           : Find(RootDir, StartSubDir, "/init.o");
7008     CmdArgs.push_back(Args.MakeArgString(Init));
7009   }
7010
7011   //----------------------------------------------------------------------------
7012   // Library Search Paths
7013   //----------------------------------------------------------------------------
7014   const ToolChain::path_list &LibPaths = HTC.getFilePaths();
7015   for (const auto &LibPath : LibPaths)
7016     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
7017
7018   //----------------------------------------------------------------------------
7019   //
7020   //----------------------------------------------------------------------------
7021   Args.AddAllArgs(CmdArgs,
7022                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7023                    options::OPT_t, options::OPT_u_Group});
7024
7025   AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
7026
7027   //----------------------------------------------------------------------------
7028   // Libraries
7029   //----------------------------------------------------------------------------
7030   if (IncStdLib && IncDefLibs) {
7031     if (D.CCCIsCXX()) {
7032       HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
7033       CmdArgs.push_back("-lm");
7034     }
7035
7036     CmdArgs.push_back("--start-group");
7037
7038     if (!IsShared) {
7039       for (const std::string &Lib : OsLibs)
7040         CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
7041       CmdArgs.push_back("-lc");
7042     }
7043     CmdArgs.push_back("-lgcc");
7044
7045     CmdArgs.push_back("--end-group");
7046   }
7047
7048   //----------------------------------------------------------------------------
7049   // End files
7050   //----------------------------------------------------------------------------
7051   if (IncStdLib && IncStartFiles) {
7052     std::string Fini = UseShared
7053           ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
7054           : Find(RootDir, StartSubDir, "/fini.o");
7055     CmdArgs.push_back(Args.MakeArgString(Fini));
7056   }
7057 }
7058
7059 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7060                                    const InputInfo &Output,
7061                                    const InputInfoList &Inputs,
7062                                    const ArgList &Args,
7063                                    const char *LinkingOutput) const {
7064   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7065
7066   ArgStringList CmdArgs;
7067   constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
7068                            LinkingOutput);
7069
7070   std::string Linker = HTC.GetProgramPath("hexagon-link");
7071   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7072                                           CmdArgs, Inputs));
7073 }
7074 // Hexagon tools end.
7075
7076 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7077                                   const InputInfo &Output,
7078                                   const InputInfoList &Inputs,
7079                                   const ArgList &Args,
7080                                   const char *LinkingOutput) const {
7081
7082   std::string Linker = getToolChain().GetProgramPath(getShortName());
7083   ArgStringList CmdArgs;
7084   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7085   CmdArgs.push_back("-shared");
7086   CmdArgs.push_back("-o");
7087   CmdArgs.push_back(Output.getFilename());
7088   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7089                                           CmdArgs, Inputs));
7090 }
7091 // AMDGPU tools end.
7092
7093 wasm::Linker::Linker(const ToolChain &TC)
7094   : GnuTool("wasm::Linker", "lld", TC) {}
7095
7096 bool wasm::Linker::isLinkJob() const {
7097   return true;
7098 }
7099
7100 bool wasm::Linker::hasIntegratedCPP() const {
7101   return false;
7102 }
7103
7104 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7105                                 const InputInfo &Output,
7106                                 const InputInfoList &Inputs,
7107                                 const ArgList &Args,
7108                                 const char *LinkingOutput) const {
7109
7110   const ToolChain &ToolChain = getToolChain();
7111   const Driver &D = ToolChain.getDriver();
7112   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
7113   ArgStringList CmdArgs;
7114   CmdArgs.push_back("-flavor");
7115   CmdArgs.push_back("ld");
7116
7117   // Enable garbage collection of unused input sections by default, since code
7118   // size is of particular importance. This is significantly facilitated by
7119   // the enabling of -ffunction-sections and -fdata-sections in
7120   // Clang::ConstructJob.
7121   if (areOptimizationsEnabled(Args))
7122     CmdArgs.push_back("--gc-sections");
7123
7124   if (Args.hasArg(options::OPT_rdynamic))
7125     CmdArgs.push_back("-export-dynamic");
7126   if (Args.hasArg(options::OPT_s))
7127     CmdArgs.push_back("--strip-all");
7128   if (Args.hasArg(options::OPT_shared))
7129     CmdArgs.push_back("-shared");
7130   if (Args.hasArg(options::OPT_static))
7131     CmdArgs.push_back("-Bstatic");
7132
7133   Args.AddAllArgs(CmdArgs, options::OPT_L);
7134   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7135
7136   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7137     if (Args.hasArg(options::OPT_shared))
7138       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
7139     else if (Args.hasArg(options::OPT_pie))
7140       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
7141     else
7142       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
7143
7144     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7145   }
7146
7147   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7148
7149   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7150     if (D.CCCIsCXX())
7151       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7152
7153     if (Args.hasArg(options::OPT_pthread))
7154       CmdArgs.push_back("-lpthread");
7155
7156     CmdArgs.push_back("-lc");
7157     CmdArgs.push_back("-lcompiler_rt");
7158   }
7159
7160   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7161     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7162
7163   CmdArgs.push_back("-o");
7164   CmdArgs.push_back(Output.getFilename());
7165
7166   C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
7167 }
7168
7169 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
7170   std::string MArch;
7171   if (!Arch.empty())
7172     MArch = Arch;
7173   else
7174     MArch = Triple.getArchName();
7175   MArch = StringRef(MArch).split("+").first.lower();
7176
7177   // Handle -march=native.
7178   if (MArch == "native") {
7179     std::string CPU = llvm::sys::getHostCPUName();
7180     if (CPU != "generic") {
7181       // Translate the native cpu into the architecture suffix for that CPU.
7182       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
7183       // If there is no valid architecture suffix for this CPU we don't know how
7184       // to handle it, so return no architecture.
7185       if (Suffix.empty())
7186         MArch = "";
7187       else
7188         MArch = std::string("arm") + Suffix.str();
7189     }
7190   }
7191
7192   return MArch;
7193 }
7194
7195 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
7196 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
7197   std::string MArch = getARMArch(Arch, Triple);
7198   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
7199   // here means an -march=native that we can't handle, so instead return no CPU.
7200   if (MArch.empty())
7201     return StringRef();
7202
7203   // We need to return an empty string here on invalid MArch values as the
7204   // various places that call this function can't cope with a null result.
7205   return Triple.getARMCPUForArch(MArch);
7206 }
7207
7208 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
7209 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
7210                                  const llvm::Triple &Triple) {
7211   // FIXME: Warn on inconsistent use of -mcpu and -march.
7212   // If we have -mcpu=, use that.
7213   if (!CPU.empty()) {
7214     std::string MCPU = StringRef(CPU).split("+").first.lower();
7215     // Handle -mcpu=native.
7216     if (MCPU == "native")
7217       return llvm::sys::getHostCPUName();
7218     else
7219       return MCPU;
7220   }
7221
7222   return getARMCPUForMArch(Arch, Triple);
7223 }
7224
7225 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
7226 /// CPU  (or Arch, if CPU is generic).
7227 // FIXME: This is redundant with -mcpu, why does LLVM use this.
7228 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
7229                                        const llvm::Triple &Triple) {
7230   unsigned ArchKind;
7231   if (CPU == "generic") {
7232     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
7233     ArchKind = llvm::ARM::parseArch(ARMArch);
7234     if (ArchKind == llvm::ARM::AK_INVALID)
7235       // In case of generic Arch, i.e. "arm",
7236       // extract arch from default cpu of the Triple
7237       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
7238   } else {
7239     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
7240     // armv7k triple if it's actually been specified via "-arch armv7k".
7241     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
7242                           ? (unsigned)llvm::ARM::AK_ARMV7K
7243                           : llvm::ARM::parseCPUArch(CPU);
7244   }
7245   if (ArchKind == llvm::ARM::AK_INVALID)
7246     return "";
7247   return llvm::ARM::getSubArch(ArchKind);
7248 }
7249
7250 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
7251                             const llvm::Triple &Triple) {
7252   if (Args.hasArg(options::OPT_r))
7253     return;
7254
7255   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
7256   // to generate BE-8 executables.
7257   if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
7258     CmdArgs.push_back("--be8");
7259 }
7260
7261 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
7262   // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
7263   // was first introduced in Release 3. However, other compilers have
7264   // traditionally allowed it for Release 2 so we should do the same.
7265   return (NanEncoding)llvm::StringSwitch<int>(CPU)
7266       .Case("mips1", NanLegacy)
7267       .Case("mips2", NanLegacy)
7268       .Case("mips3", NanLegacy)
7269       .Case("mips4", NanLegacy)
7270       .Case("mips5", NanLegacy)
7271       .Case("mips32", NanLegacy)
7272       .Case("mips32r2", NanLegacy | Nan2008)
7273       .Case("mips32r3", NanLegacy | Nan2008)
7274       .Case("mips32r5", NanLegacy | Nan2008)
7275       .Case("mips32r6", Nan2008)
7276       .Case("mips64", NanLegacy)
7277       .Case("mips64r2", NanLegacy | Nan2008)
7278       .Case("mips64r3", NanLegacy | Nan2008)
7279       .Case("mips64r5", NanLegacy | Nan2008)
7280       .Case("mips64r6", Nan2008)
7281       .Default(NanLegacy);
7282 }
7283
7284 bool mips::hasCompactBranches(StringRef &CPU) {
7285   // mips32r6 and mips64r6 have compact branches.
7286   return llvm::StringSwitch<bool>(CPU)
7287       .Case("mips32r6", true)
7288       .Case("mips64r6", true)
7289       .Default(false);
7290 }
7291
7292 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
7293   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
7294   return A && (A->getValue() == StringRef(Value));
7295 }
7296
7297 bool mips::isUCLibc(const ArgList &Args) {
7298   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
7299   return A && A->getOption().matches(options::OPT_muclibc);
7300 }
7301
7302 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
7303   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
7304     return llvm::StringSwitch<bool>(NaNArg->getValue())
7305         .Case("2008", true)
7306         .Case("legacy", false)
7307         .Default(false);
7308
7309   // NaN2008 is the default for MIPS32r6/MIPS64r6.
7310   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
7311       .Cases("mips32r6", "mips64r6", true)
7312       .Default(false);
7313
7314   return false;
7315 }
7316
7317 bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
7318   if (!Triple.isAndroid())
7319     return false;
7320
7321   // Android MIPS32R6 defaults to FP64A.
7322   return llvm::StringSwitch<bool>(CPUName)
7323       .Case("mips32r6", true)
7324       .Default(false);
7325 }
7326
7327 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
7328                          StringRef ABIName, mips::FloatABI FloatABI) {
7329   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
7330       Triple.getVendor() != llvm::Triple::MipsTechnologies &&
7331       !Triple.isAndroid())
7332     return false;
7333
7334   if (ABIName != "32")
7335     return false;
7336
7337   // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
7338   // present.
7339   if (FloatABI == mips::FloatABI::Soft)
7340     return false;
7341
7342   return llvm::StringSwitch<bool>(CPUName)
7343       .Cases("mips2", "mips3", "mips4", "mips5", true)
7344       .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
7345       .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
7346       .Default(false);
7347 }
7348
7349 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
7350                          StringRef CPUName, StringRef ABIName,
7351                          mips::FloatABI FloatABI) {
7352   bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
7353
7354   // FPXX shouldn't be used if -msingle-float is present.
7355   if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
7356                                options::OPT_mdouble_float))
7357     if (A->getOption().matches(options::OPT_msingle_float))
7358       UseFPXX = false;
7359
7360   return UseFPXX;
7361 }
7362
7363 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
7364   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
7365   // archs which Darwin doesn't use.
7366
7367   // The matching this routine does is fairly pointless, since it is neither the
7368   // complete architecture list, nor a reasonable subset. The problem is that
7369   // historically the driver driver accepts this and also ties its -march=
7370   // handling to the architecture name, so we need to be careful before removing
7371   // support for it.
7372
7373   // This code must be kept in sync with Clang's Darwin specific argument
7374   // translation.
7375
7376   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
7377       .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
7378       .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
7379       .Case("ppc64", llvm::Triple::ppc64)
7380       .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
7381       .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
7382              llvm::Triple::x86)
7383       .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
7384       // This is derived from the driver driver.
7385       .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
7386       .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
7387       .Cases("armv7s", "xscale", llvm::Triple::arm)
7388       .Case("arm64", llvm::Triple::aarch64)
7389       .Case("r600", llvm::Triple::r600)
7390       .Case("amdgcn", llvm::Triple::amdgcn)
7391       .Case("nvptx", llvm::Triple::nvptx)
7392       .Case("nvptx64", llvm::Triple::nvptx64)
7393       .Case("amdil", llvm::Triple::amdil)
7394       .Case("spir", llvm::Triple::spir)
7395       .Default(llvm::Triple::UnknownArch);
7396 }
7397
7398 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
7399   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
7400   T.setArch(Arch);
7401
7402   if (Str == "x86_64h")
7403     T.setArchName(Str);
7404   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
7405     T.setOS(llvm::Triple::UnknownOS);
7406     T.setObjectFormat(llvm::Triple::MachO);
7407   }
7408 }
7409
7410 const char *Clang::getBaseInputName(const ArgList &Args,
7411                                     const InputInfo &Input) {
7412   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7413 }
7414
7415 const char *Clang::getBaseInputStem(const ArgList &Args,
7416                                     const InputInfoList &Inputs) {
7417   const char *Str = getBaseInputName(Args, Inputs[0]);
7418
7419   if (const char *End = strrchr(Str, '.'))
7420     return Args.MakeArgString(std::string(Str, End));
7421
7422   return Str;
7423 }
7424
7425 const char *Clang::getDependencyFileName(const ArgList &Args,
7426                                          const InputInfoList &Inputs) {
7427   // FIXME: Think about this more.
7428   std::string Res;
7429
7430   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7431     std::string Str(OutputOpt->getValue());
7432     Res = Str.substr(0, Str.rfind('.'));
7433   } else {
7434     Res = getBaseInputStem(Args, Inputs);
7435   }
7436   return Args.MakeArgString(Res + ".d");
7437 }
7438
7439 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7440                                     const InputInfo &Output,
7441                                     const InputInfoList &Inputs,
7442                                     const ArgList &Args,
7443                                     const char *LinkingOutput) const {
7444   const ToolChain &ToolChain = getToolChain();
7445   const Driver &D = ToolChain.getDriver();
7446   ArgStringList CmdArgs;
7447
7448   // Silence warning for "clang -g foo.o -o foo"
7449   Args.ClaimAllArgs(options::OPT_g_Group);
7450   // and "clang -emit-llvm foo.o -o foo"
7451   Args.ClaimAllArgs(options::OPT_emit_llvm);
7452   // and for "clang -w foo.o -o foo". Other warning options are already
7453   // handled somewhere else.
7454   Args.ClaimAllArgs(options::OPT_w);
7455
7456   if (!D.SysRoot.empty())
7457     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7458
7459   // CloudABI only supports static linkage.
7460   CmdArgs.push_back("-Bstatic");
7461   CmdArgs.push_back("--no-dynamic-linker");
7462
7463   // Provide PIE linker flags in case PIE is default for the architecture.
7464   if (ToolChain.isPIEDefault()) {
7465     CmdArgs.push_back("-pie");
7466     CmdArgs.push_back("-zrelro");
7467   }
7468
7469   CmdArgs.push_back("--eh-frame-hdr");
7470   CmdArgs.push_back("--gc-sections");
7471
7472   if (Output.isFilename()) {
7473     CmdArgs.push_back("-o");
7474     CmdArgs.push_back(Output.getFilename());
7475   } else {
7476     assert(Output.isNothing() && "Invalid output.");
7477   }
7478
7479   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7480     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
7481     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
7482   }
7483
7484   Args.AddAllArgs(CmdArgs, options::OPT_L);
7485   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7486   Args.AddAllArgs(CmdArgs,
7487                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7488                    options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
7489
7490   if (D.isUsingLTO())
7491     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7492
7493   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7494
7495   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7496     if (D.CCCIsCXX())
7497       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7498     CmdArgs.push_back("-lc");
7499     CmdArgs.push_back("-lcompiler_rt");
7500   }
7501
7502   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7503     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7504
7505   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
7506   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7507 }
7508
7509 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7510                                      const InputInfo &Output,
7511                                      const InputInfoList &Inputs,
7512                                      const ArgList &Args,
7513                                      const char *LinkingOutput) const {
7514   ArgStringList CmdArgs;
7515
7516   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7517   const InputInfo &Input = Inputs[0];
7518
7519   // Determine the original source input.
7520   const Action *SourceAction = &JA;
7521   while (SourceAction->getKind() != Action::InputClass) {
7522     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7523     SourceAction = SourceAction->getInputs()[0];
7524   }
7525
7526   // If -fno-integrated-as is used add -Q to the darwin assember driver to make
7527   // sure it runs its system assembler not clang's integrated assembler.
7528   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
7529   // FIXME: at run-time detect assembler capabilities or rely on version
7530   // information forwarded by -target-assembler-version.
7531   if (Args.hasArg(options::OPT_fno_integrated_as)) {
7532     const llvm::Triple &T(getToolChain().getTriple());
7533     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
7534       CmdArgs.push_back("-Q");
7535   }
7536
7537   // Forward -g, assuming we are dealing with an actual assembly file.
7538   if (SourceAction->getType() == types::TY_Asm ||
7539       SourceAction->getType() == types::TY_PP_Asm) {
7540     if (Args.hasArg(options::OPT_gstabs))
7541       CmdArgs.push_back("--gstabs");
7542     else if (Args.hasArg(options::OPT_g_Group))
7543       CmdArgs.push_back("-g");
7544   }
7545
7546   // Derived from asm spec.
7547   AddMachOArch(Args, CmdArgs);
7548
7549   // Use -force_cpusubtype_ALL on x86 by default.
7550   if (getToolChain().getArch() == llvm::Triple::x86 ||
7551       getToolChain().getArch() == llvm::Triple::x86_64 ||
7552       Args.hasArg(options::OPT_force__cpusubtype__ALL))
7553     CmdArgs.push_back("-force_cpusubtype_ALL");
7554
7555   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
7556       (((Args.hasArg(options::OPT_mkernel) ||
7557          Args.hasArg(options::OPT_fapple_kext)) &&
7558         getMachOToolChain().isKernelStatic()) ||
7559        Args.hasArg(options::OPT_static)))
7560     CmdArgs.push_back("-static");
7561
7562   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7563
7564   assert(Output.isFilename() && "Unexpected lipo output.");
7565   CmdArgs.push_back("-o");
7566   CmdArgs.push_back(Output.getFilename());
7567
7568   assert(Input.isFilename() && "Invalid input.");
7569   CmdArgs.push_back(Input.getFilename());
7570
7571   // asm_final spec is empty.
7572
7573   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7574   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7575 }
7576
7577 void darwin::MachOTool::anchor() {}
7578
7579 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
7580                                      ArgStringList &CmdArgs) const {
7581   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
7582
7583   // Derived from darwin_arch spec.
7584   CmdArgs.push_back("-arch");
7585   CmdArgs.push_back(Args.MakeArgString(ArchName));
7586
7587   // FIXME: Is this needed anymore?
7588   if (ArchName == "arm")
7589     CmdArgs.push_back("-force_cpusubtype_ALL");
7590 }
7591
7592 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
7593   // We only need to generate a temp path for LTO if we aren't compiling object
7594   // files. When compiling source files, we run 'dsymutil' after linking. We
7595   // don't run 'dsymutil' when compiling object files.
7596   for (const auto &Input : Inputs)
7597     if (Input.getType() != types::TY_Object)
7598       return true;
7599
7600   return false;
7601 }
7602
7603 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
7604                                  ArgStringList &CmdArgs,
7605                                  const InputInfoList &Inputs) const {
7606   const Driver &D = getToolChain().getDriver();
7607   const toolchains::MachO &MachOTC = getMachOToolChain();
7608
7609   unsigned Version[5] = {0, 0, 0, 0, 0};
7610   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
7611     if (!Driver::GetReleaseVersion(A->getValue(), Version))
7612       D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
7613   }
7614
7615   // Newer linkers support -demangle. Pass it if supported and not disabled by
7616   // the user.
7617   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7618     CmdArgs.push_back("-demangle");
7619
7620   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7621     CmdArgs.push_back("-export_dynamic");
7622
7623   // If we are using App Extension restrictions, pass a flag to the linker
7624   // telling it that the compiled code has been audited.
7625   if (Args.hasFlag(options::OPT_fapplication_extension,
7626                    options::OPT_fno_application_extension, false))
7627     CmdArgs.push_back("-application_extension");
7628
7629   if (D.isUsingLTO()) {
7630     // If we are using LTO, then automatically create a temporary file path for
7631     // the linker to use, so that it's lifetime will extend past a possible
7632     // dsymutil step.
7633     if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7634       const char *TmpPath = C.getArgs().MakeArgString(
7635           D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7636       C.addTempFile(TmpPath);
7637       CmdArgs.push_back("-object_path_lto");
7638       CmdArgs.push_back(TmpPath);
7639     }
7640
7641     // Use -lto_library option to specify the libLTO.dylib path. Try to find
7642     // it in clang installed libraries. If not found, the option is not used
7643     // and 'ld' will use its default mechanism to search for libLTO.dylib.
7644     if (Version[0] >= 133) {
7645       // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7646       StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7647       SmallString<128> LibLTOPath(P);
7648       llvm::sys::path::append(LibLTOPath, "lib");
7649       llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7650       if (llvm::sys::fs::exists(LibLTOPath)) {
7651         CmdArgs.push_back("-lto_library");
7652         CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7653       } else {
7654         D.Diag(diag::warn_drv_lto_libpath);
7655       }
7656     }
7657   }
7658
7659   // Derived from the "link" spec.
7660   Args.AddAllArgs(CmdArgs, options::OPT_static);
7661   if (!Args.hasArg(options::OPT_static))
7662     CmdArgs.push_back("-dynamic");
7663   if (Args.hasArg(options::OPT_fgnu_runtime)) {
7664     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7665     // here. How do we wish to handle such things?
7666   }
7667
7668   if (!Args.hasArg(options::OPT_dynamiclib)) {
7669     AddMachOArch(Args, CmdArgs);
7670     // FIXME: Why do this only on this path?
7671     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7672
7673     Args.AddLastArg(CmdArgs, options::OPT_bundle);
7674     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7675     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7676
7677     Arg *A;
7678     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7679         (A = Args.getLastArg(options::OPT_current__version)) ||
7680         (A = Args.getLastArg(options::OPT_install__name)))
7681       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7682                                                        << "-dynamiclib";
7683
7684     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7685     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7686     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7687   } else {
7688     CmdArgs.push_back("-dylib");
7689
7690     Arg *A;
7691     if ((A = Args.getLastArg(options::OPT_bundle)) ||
7692         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7693         (A = Args.getLastArg(options::OPT_client__name)) ||
7694         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7695         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7696         (A = Args.getLastArg(options::OPT_private__bundle)))
7697       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7698                                                       << "-dynamiclib";
7699
7700     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7701                               "-dylib_compatibility_version");
7702     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7703                               "-dylib_current_version");
7704
7705     AddMachOArch(Args, CmdArgs);
7706
7707     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7708                               "-dylib_install_name");
7709   }
7710
7711   Args.AddLastArg(CmdArgs, options::OPT_all__load);
7712   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7713   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7714   if (MachOTC.isTargetIOSBased())
7715     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7716   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7717   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7718   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7719   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7720   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7721   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7722   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7723   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7724   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7725   Args.AddAllArgs(CmdArgs, options::OPT_init);
7726
7727   // Add the deployment target.
7728   MachOTC.addMinVersionArgs(Args, CmdArgs);
7729
7730   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7731   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7732   Args.AddLastArg(CmdArgs, options::OPT_single__module);
7733   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7734   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7735
7736   if (const Arg *A =
7737           Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7738                           options::OPT_fno_pie, options::OPT_fno_PIE)) {
7739     if (A->getOption().matches(options::OPT_fpie) ||
7740         A->getOption().matches(options::OPT_fPIE))
7741       CmdArgs.push_back("-pie");
7742     else
7743       CmdArgs.push_back("-no_pie");
7744   }
7745   // for embed-bitcode, use -bitcode_bundle in linker command
7746   if (C.getDriver().embedBitcodeEnabled() ||
7747       C.getDriver().embedBitcodeMarkerOnly()) {
7748     // Check if the toolchain supports bitcode build flow.
7749     if (MachOTC.SupportsEmbeddedBitcode())
7750       CmdArgs.push_back("-bitcode_bundle");
7751     else
7752       D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
7753   }
7754
7755   Args.AddLastArg(CmdArgs, options::OPT_prebind);
7756   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7757   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7758   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7759   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7760   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7761   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7762   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7763   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7764   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7765   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7766   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7767   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7768   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7769   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7770   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7771
7772   // Give --sysroot= preference, over the Apple specific behavior to also use
7773   // --isysroot as the syslibroot.
7774   StringRef sysroot = C.getSysRoot();
7775   if (sysroot != "") {
7776     CmdArgs.push_back("-syslibroot");
7777     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7778   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7779     CmdArgs.push_back("-syslibroot");
7780     CmdArgs.push_back(A->getValue());
7781   }
7782
7783   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7784   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7785   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7786   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7787   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7788   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7789   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7790   Args.AddAllArgs(CmdArgs, options::OPT_y);
7791   Args.AddLastArg(CmdArgs, options::OPT_w);
7792   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7793   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7794   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7795   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7796   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7797   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7798   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7799   Args.AddLastArg(CmdArgs, options::OPT_whyload);
7800   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7801   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7802   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7803   Args.AddLastArg(CmdArgs, options::OPT_Mach);
7804 }
7805
7806 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7807                                   const InputInfo &Output,
7808                                   const InputInfoList &Inputs,
7809                                   const ArgList &Args,
7810                                   const char *LinkingOutput) const {
7811   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7812
7813   // If the number of arguments surpasses the system limits, we will encode the
7814   // input files in a separate file, shortening the command line. To this end,
7815   // build a list of input file names that can be passed via a file with the
7816   // -filelist linker option.
7817   llvm::opt::ArgStringList InputFileList;
7818
7819   // The logic here is derived from gcc's behavior; most of which
7820   // comes from specs (starting with link_command). Consult gcc for
7821   // more information.
7822   ArgStringList CmdArgs;
7823
7824   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7825   if (Args.hasArg(options::OPT_ccc_arcmt_check,
7826                   options::OPT_ccc_arcmt_migrate)) {
7827     for (const auto &Arg : Args)
7828       Arg->claim();
7829     const char *Exec =
7830         Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7831     CmdArgs.push_back(Output.getFilename());
7832     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7833     return;
7834   }
7835
7836   // I'm not sure why this particular decomposition exists in gcc, but
7837   // we follow suite for ease of comparison.
7838   AddLinkArgs(C, Args, CmdArgs, Inputs);
7839
7840   // It seems that the 'e' option is completely ignored for dynamic executables
7841   // (the default), and with static executables, the last one wins, as expected.
7842   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7843                             options::OPT_Z_Flag, options::OPT_u_Group,
7844                             options::OPT_e, options::OPT_r});
7845
7846   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7847   // members of static archive libraries which implement Objective-C classes or
7848   // categories.
7849   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7850     CmdArgs.push_back("-ObjC");
7851
7852   CmdArgs.push_back("-o");
7853   CmdArgs.push_back(Output.getFilename());
7854
7855   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7856     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7857
7858   // SafeStack requires its own runtime libraries
7859   // These libraries should be linked first, to make sure the
7860   // __safestack_init constructor executes before everything else
7861   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7862     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7863                                           "libclang_rt.safestack_osx.a",
7864                                           /*AlwaysLink=*/true);
7865   }
7866
7867   Args.AddAllArgs(CmdArgs, options::OPT_L);
7868
7869   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7870   // Build the input file for -filelist (list of linker input files) in case we
7871   // need it later
7872   for (const auto &II : Inputs) {
7873     if (!II.isFilename()) {
7874       // This is a linker input argument.
7875       // We cannot mix input arguments and file names in a -filelist input, thus
7876       // we prematurely stop our list (remaining files shall be passed as
7877       // arguments).
7878       if (InputFileList.size() > 0)
7879         break;
7880
7881       continue;
7882     }
7883
7884     InputFileList.push_back(II.getFilename());
7885   }
7886
7887   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7888     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7889
7890   if (isObjCRuntimeLinked(Args) &&
7891       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7892     // We use arclite library for both ARC and subscripting support.
7893     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7894
7895     CmdArgs.push_back("-framework");
7896     CmdArgs.push_back("Foundation");
7897     // Link libobj.
7898     CmdArgs.push_back("-lobjc");
7899   }
7900
7901   if (LinkingOutput) {
7902     CmdArgs.push_back("-arch_multiple");
7903     CmdArgs.push_back("-final_output");
7904     CmdArgs.push_back(LinkingOutput);
7905   }
7906
7907   if (Args.hasArg(options::OPT_fnested_functions))
7908     CmdArgs.push_back("-allow_stack_execute");
7909
7910   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7911
7912   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7913     if (getToolChain().getDriver().CCCIsCXX())
7914       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7915
7916     // link_ssp spec is empty.
7917
7918     // Let the tool chain choose which runtime library to link.
7919     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7920   }
7921
7922   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7923     // endfile_spec is empty.
7924   }
7925
7926   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7927   Args.AddAllArgs(CmdArgs, options::OPT_F);
7928
7929   // -iframework should be forwarded as -F.
7930   for (const Arg *A : Args.filtered(options::OPT_iframework))
7931     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7932
7933   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7934     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7935       if (A->getValue() == StringRef("Accelerate")) {
7936         CmdArgs.push_back("-framework");
7937         CmdArgs.push_back("Accelerate");
7938       }
7939     }
7940   }
7941
7942   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7943   std::unique_ptr<Command> Cmd =
7944       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7945   Cmd->setInputFileList(std::move(InputFileList));
7946   C.addCommand(std::move(Cmd));
7947 }
7948
7949 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7950                                 const InputInfo &Output,
7951                                 const InputInfoList &Inputs,
7952                                 const ArgList &Args,
7953                                 const char *LinkingOutput) const {
7954   ArgStringList CmdArgs;
7955
7956   CmdArgs.push_back("-create");
7957   assert(Output.isFilename() && "Unexpected lipo output.");
7958
7959   CmdArgs.push_back("-output");
7960   CmdArgs.push_back(Output.getFilename());
7961
7962   for (const auto &II : Inputs) {
7963     assert(II.isFilename() && "Unexpected lipo input.");
7964     CmdArgs.push_back(II.getFilename());
7965   }
7966
7967   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7968   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7969 }
7970
7971 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7972                                     const InputInfo &Output,
7973                                     const InputInfoList &Inputs,
7974                                     const ArgList &Args,
7975                                     const char *LinkingOutput) const {
7976   ArgStringList CmdArgs;
7977
7978   CmdArgs.push_back("-o");
7979   CmdArgs.push_back(Output.getFilename());
7980
7981   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7982   const InputInfo &Input = Inputs[0];
7983   assert(Input.isFilename() && "Unexpected dsymutil input.");
7984   CmdArgs.push_back(Input.getFilename());
7985
7986   const char *Exec =
7987       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7988   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7989 }
7990
7991 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7992                                        const InputInfo &Output,
7993                                        const InputInfoList &Inputs,
7994                                        const ArgList &Args,
7995                                        const char *LinkingOutput) const {
7996   ArgStringList CmdArgs;
7997   CmdArgs.push_back("--verify");
7998   CmdArgs.push_back("--debug-info");
7999   CmdArgs.push_back("--eh-frame");
8000   CmdArgs.push_back("--quiet");
8001
8002   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
8003   const InputInfo &Input = Inputs[0];
8004   assert(Input.isFilename() && "Unexpected verify input");
8005
8006   // Grabbing the output of the earlier dsymutil run.
8007   CmdArgs.push_back(Input.getFilename());
8008
8009   const char *Exec =
8010       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
8011   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8012 }
8013
8014 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8015                                       const InputInfo &Output,
8016                                       const InputInfoList &Inputs,
8017                                       const ArgList &Args,
8018                                       const char *LinkingOutput) const {
8019   claimNoWarnArgs(Args);
8020   ArgStringList CmdArgs;
8021
8022   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8023
8024   CmdArgs.push_back("-o");
8025   CmdArgs.push_back(Output.getFilename());
8026
8027   for (const auto &II : Inputs)
8028     CmdArgs.push_back(II.getFilename());
8029
8030   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8031   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8032 }
8033
8034 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8035                                    const InputInfo &Output,
8036                                    const InputInfoList &Inputs,
8037                                    const ArgList &Args,
8038                                    const char *LinkingOutput) const {
8039   ArgStringList CmdArgs;
8040
8041   // Demangle C++ names in errors
8042   CmdArgs.push_back("-C");
8043
8044   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8045     CmdArgs.push_back("-e");
8046     CmdArgs.push_back("_start");
8047   }
8048
8049   if (Args.hasArg(options::OPT_static)) {
8050     CmdArgs.push_back("-Bstatic");
8051     CmdArgs.push_back("-dn");
8052   } else {
8053     CmdArgs.push_back("-Bdynamic");
8054     if (Args.hasArg(options::OPT_shared)) {
8055       CmdArgs.push_back("-shared");
8056     } else {
8057       CmdArgs.push_back("--dynamic-linker");
8058       CmdArgs.push_back(
8059           Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
8060     }
8061   }
8062
8063   if (Output.isFilename()) {
8064     CmdArgs.push_back("-o");
8065     CmdArgs.push_back(Output.getFilename());
8066   } else {
8067     assert(Output.isNothing() && "Invalid output.");
8068   }
8069
8070   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8071     if (!Args.hasArg(options::OPT_shared))
8072       CmdArgs.push_back(
8073           Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8074
8075     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8076     CmdArgs.push_back(
8077         Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
8078     CmdArgs.push_back(
8079         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8080   }
8081
8082   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
8083
8084   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8085                             options::OPT_e, options::OPT_r});
8086
8087   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8088
8089   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8090     if (getToolChain().getDriver().CCCIsCXX())
8091       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8092     CmdArgs.push_back("-lgcc_s");
8093     CmdArgs.push_back("-lc");
8094     if (!Args.hasArg(options::OPT_shared)) {
8095       CmdArgs.push_back("-lgcc");
8096       CmdArgs.push_back("-lm");
8097     }
8098   }
8099
8100   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8101     CmdArgs.push_back(
8102         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8103   }
8104   CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8105
8106   getToolChain().addProfileRTLibs(Args, CmdArgs);
8107
8108   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8109   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8110 }
8111
8112 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8113                                       const InputInfo &Output,
8114                                       const InputInfoList &Inputs,
8115                                       const ArgList &Args,
8116                                       const char *LinkingOutput) const {
8117   claimNoWarnArgs(Args);
8118   ArgStringList CmdArgs;
8119
8120   switch (getToolChain().getArch()) {
8121   case llvm::Triple::x86:
8122     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
8123     // instruct as in the base system to assemble 32-bit code.
8124     CmdArgs.push_back("--32");
8125     break;
8126
8127   case llvm::Triple::ppc:
8128     CmdArgs.push_back("-mppc");
8129     CmdArgs.push_back("-many");
8130     break;
8131
8132   case llvm::Triple::sparc:
8133   case llvm::Triple::sparcel: {
8134     CmdArgs.push_back("-32");
8135     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8136     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8137     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8138     break;
8139   }
8140
8141   case llvm::Triple::sparcv9: {
8142     CmdArgs.push_back("-64");
8143     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8144     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8145     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8146     break;
8147   }
8148
8149   case llvm::Triple::mips64:
8150   case llvm::Triple::mips64el: {
8151     StringRef CPUName;
8152     StringRef ABIName;
8153     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8154
8155     CmdArgs.push_back("-mabi");
8156     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8157
8158     if (getToolChain().getArch() == llvm::Triple::mips64)
8159       CmdArgs.push_back("-EB");
8160     else
8161       CmdArgs.push_back("-EL");
8162
8163     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8164     break;
8165   }
8166
8167   default:
8168     break;
8169   }
8170
8171   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8172
8173   CmdArgs.push_back("-o");
8174   CmdArgs.push_back(Output.getFilename());
8175
8176   for (const auto &II : Inputs)
8177     CmdArgs.push_back(II.getFilename());
8178
8179   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8180   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8181 }
8182
8183 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8184                                    const InputInfo &Output,
8185                                    const InputInfoList &Inputs,
8186                                    const ArgList &Args,
8187                                    const char *LinkingOutput) const {
8188   const Driver &D = getToolChain().getDriver();
8189   ArgStringList CmdArgs;
8190
8191   // Silence warning for "clang -g foo.o -o foo"
8192   Args.ClaimAllArgs(options::OPT_g_Group);
8193   // and "clang -emit-llvm foo.o -o foo"
8194   Args.ClaimAllArgs(options::OPT_emit_llvm);
8195   // and for "clang -w foo.o -o foo". Other warning options are already
8196   // handled somewhere else.
8197   Args.ClaimAllArgs(options::OPT_w);
8198
8199   if (getToolChain().getArch() == llvm::Triple::mips64)
8200     CmdArgs.push_back("-EB");
8201   else if (getToolChain().getArch() == llvm::Triple::mips64el)
8202     CmdArgs.push_back("-EL");
8203
8204   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8205     CmdArgs.push_back("-e");
8206     CmdArgs.push_back("__start");
8207   }
8208
8209   if (Args.hasArg(options::OPT_static)) {
8210     CmdArgs.push_back("-Bstatic");
8211   } else {
8212     if (Args.hasArg(options::OPT_rdynamic))
8213       CmdArgs.push_back("-export-dynamic");
8214     CmdArgs.push_back("--eh-frame-hdr");
8215     CmdArgs.push_back("-Bdynamic");
8216     if (Args.hasArg(options::OPT_shared)) {
8217       CmdArgs.push_back("-shared");
8218     } else {
8219       CmdArgs.push_back("-dynamic-linker");
8220       CmdArgs.push_back("/usr/libexec/ld.so");
8221     }
8222   }
8223
8224   if (Args.hasArg(options::OPT_nopie))
8225     CmdArgs.push_back("-nopie");
8226
8227   if (Output.isFilename()) {
8228     CmdArgs.push_back("-o");
8229     CmdArgs.push_back(Output.getFilename());
8230   } else {
8231     assert(Output.isNothing() && "Invalid output.");
8232   }
8233
8234   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8235     if (!Args.hasArg(options::OPT_shared)) {
8236       if (Args.hasArg(options::OPT_pg))
8237         CmdArgs.push_back(
8238             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8239       else
8240         CmdArgs.push_back(
8241             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8242       CmdArgs.push_back(
8243           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8244     } else {
8245       CmdArgs.push_back(
8246           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8247     }
8248   }
8249
8250   std::string Triple = getToolChain().getTripleString();
8251   if (Triple.substr(0, 6) == "x86_64")
8252     Triple.replace(0, 6, "amd64");
8253   CmdArgs.push_back(
8254       Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
8255
8256   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8257                             options::OPT_e, options::OPT_s, options::OPT_t,
8258                             options::OPT_Z_Flag, options::OPT_r});
8259
8260   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8261
8262   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8263     if (D.CCCIsCXX()) {
8264       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8265       if (Args.hasArg(options::OPT_pg))
8266         CmdArgs.push_back("-lm_p");
8267       else
8268         CmdArgs.push_back("-lm");
8269     }
8270
8271     // FIXME: For some reason GCC passes -lgcc before adding
8272     // the default system libraries. Just mimic this for now.
8273     CmdArgs.push_back("-lgcc");
8274
8275     if (Args.hasArg(options::OPT_pthread)) {
8276       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8277         CmdArgs.push_back("-lpthread_p");
8278       else
8279         CmdArgs.push_back("-lpthread");
8280     }
8281
8282     if (!Args.hasArg(options::OPT_shared)) {
8283       if (Args.hasArg(options::OPT_pg))
8284         CmdArgs.push_back("-lc_p");
8285       else
8286         CmdArgs.push_back("-lc");
8287     }
8288
8289     CmdArgs.push_back("-lgcc");
8290   }
8291
8292   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8293     if (!Args.hasArg(options::OPT_shared))
8294       CmdArgs.push_back(
8295           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8296     else
8297       CmdArgs.push_back(
8298           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8299   }
8300
8301   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8302   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8303 }
8304
8305 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8306                                      const InputInfo &Output,
8307                                      const InputInfoList &Inputs,
8308                                      const ArgList &Args,
8309                                      const char *LinkingOutput) const {
8310   claimNoWarnArgs(Args);
8311   ArgStringList CmdArgs;
8312
8313   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8314
8315   CmdArgs.push_back("-o");
8316   CmdArgs.push_back(Output.getFilename());
8317
8318   for (const auto &II : Inputs)
8319     CmdArgs.push_back(II.getFilename());
8320
8321   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8322   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8323 }
8324
8325 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8326                                   const InputInfo &Output,
8327                                   const InputInfoList &Inputs,
8328                                   const ArgList &Args,
8329                                   const char *LinkingOutput) const {
8330   const Driver &D = getToolChain().getDriver();
8331   ArgStringList CmdArgs;
8332
8333   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8334     CmdArgs.push_back("-e");
8335     CmdArgs.push_back("__start");
8336   }
8337
8338   if (Args.hasArg(options::OPT_static)) {
8339     CmdArgs.push_back("-Bstatic");
8340   } else {
8341     if (Args.hasArg(options::OPT_rdynamic))
8342       CmdArgs.push_back("-export-dynamic");
8343     CmdArgs.push_back("--eh-frame-hdr");
8344     CmdArgs.push_back("-Bdynamic");
8345     if (Args.hasArg(options::OPT_shared)) {
8346       CmdArgs.push_back("-shared");
8347     } else {
8348       CmdArgs.push_back("-dynamic-linker");
8349       CmdArgs.push_back("/usr/libexec/ld.so");
8350     }
8351   }
8352
8353   if (Output.isFilename()) {
8354     CmdArgs.push_back("-o");
8355     CmdArgs.push_back(Output.getFilename());
8356   } else {
8357     assert(Output.isNothing() && "Invalid output.");
8358   }
8359
8360   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8361     if (!Args.hasArg(options::OPT_shared)) {
8362       if (Args.hasArg(options::OPT_pg))
8363         CmdArgs.push_back(
8364             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8365       else
8366         CmdArgs.push_back(
8367             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8368       CmdArgs.push_back(
8369           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8370     } else {
8371       CmdArgs.push_back(
8372           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8373     }
8374   }
8375
8376   Args.AddAllArgs(CmdArgs,
8377                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
8378
8379   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8380
8381   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8382     if (D.CCCIsCXX()) {
8383       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8384       if (Args.hasArg(options::OPT_pg))
8385         CmdArgs.push_back("-lm_p");
8386       else
8387         CmdArgs.push_back("-lm");
8388     }
8389
8390     if (Args.hasArg(options::OPT_pthread)) {
8391       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8392         CmdArgs.push_back("-lpthread_p");
8393       else
8394         CmdArgs.push_back("-lpthread");
8395     }
8396
8397     if (!Args.hasArg(options::OPT_shared)) {
8398       if (Args.hasArg(options::OPT_pg))
8399         CmdArgs.push_back("-lc_p");
8400       else
8401         CmdArgs.push_back("-lc");
8402     }
8403
8404     StringRef MyArch;
8405     switch (getToolChain().getArch()) {
8406     case llvm::Triple::arm:
8407       MyArch = "arm";
8408       break;
8409     case llvm::Triple::x86:
8410       MyArch = "i386";
8411       break;
8412     case llvm::Triple::x86_64:
8413       MyArch = "amd64";
8414       break;
8415     default:
8416       llvm_unreachable("Unsupported architecture");
8417     }
8418     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
8419   }
8420
8421   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8422     if (!Args.hasArg(options::OPT_shared))
8423       CmdArgs.push_back(
8424           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8425     else
8426       CmdArgs.push_back(
8427           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8428   }
8429
8430   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8431   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8432 }
8433
8434 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8435                                       const InputInfo &Output,
8436                                       const InputInfoList &Inputs,
8437                                       const ArgList &Args,
8438                                       const char *LinkingOutput) const {
8439   claimNoWarnArgs(Args);
8440   ArgStringList CmdArgs;
8441
8442   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8443   // instruct as in the base system to assemble 32-bit code.
8444   switch (getToolChain().getArch()) {
8445   default:
8446     break;
8447   case llvm::Triple::x86:
8448     CmdArgs.push_back("--32");
8449     break;
8450   case llvm::Triple::ppc:
8451     CmdArgs.push_back("-a32");
8452     break;
8453   case llvm::Triple::mips:
8454   case llvm::Triple::mipsel:
8455   case llvm::Triple::mips64:
8456   case llvm::Triple::mips64el: {
8457     StringRef CPUName;
8458     StringRef ABIName;
8459     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8460
8461     CmdArgs.push_back("-march");
8462     CmdArgs.push_back(CPUName.data());
8463
8464     CmdArgs.push_back("-mabi");
8465     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8466
8467     if (getToolChain().getArch() == llvm::Triple::mips ||
8468         getToolChain().getArch() == llvm::Triple::mips64)
8469       CmdArgs.push_back("-EB");
8470     else
8471       CmdArgs.push_back("-EL");
8472
8473     if (Arg *A = Args.getLastArg(options::OPT_G)) {
8474       StringRef v = A->getValue();
8475       CmdArgs.push_back(Args.MakeArgString("-G" + v));
8476       A->claim();
8477     }
8478
8479     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8480     break;
8481   }
8482   case llvm::Triple::arm:
8483   case llvm::Triple::armeb:
8484   case llvm::Triple::thumb:
8485   case llvm::Triple::thumbeb: {
8486     arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
8487
8488     if (ABI == arm::FloatABI::Hard)
8489       CmdArgs.push_back("-mfpu=vfp");
8490     else
8491       CmdArgs.push_back("-mfpu=softvfp");
8492
8493     switch (getToolChain().getTriple().getEnvironment()) {
8494     case llvm::Triple::GNUEABIHF:
8495     case llvm::Triple::GNUEABI:
8496     case llvm::Triple::EABI:
8497       CmdArgs.push_back("-meabi=5");
8498       break;
8499
8500     default:
8501       CmdArgs.push_back("-matpcs");
8502     }
8503     break;
8504   }
8505   case llvm::Triple::sparc:
8506   case llvm::Triple::sparcel:
8507   case llvm::Triple::sparcv9: {
8508     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8509     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8510     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8511     break;
8512   }
8513   }
8514
8515   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8516
8517   CmdArgs.push_back("-o");
8518   CmdArgs.push_back(Output.getFilename());
8519
8520   for (const auto &II : Inputs)
8521     CmdArgs.push_back(II.getFilename());
8522
8523   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8524   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8525 }
8526
8527 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8528                                    const InputInfo &Output,
8529                                    const InputInfoList &Inputs,
8530                                    const ArgList &Args,
8531                                    const char *LinkingOutput) const {
8532   const toolchains::FreeBSD &ToolChain =
8533       static_cast<const toolchains::FreeBSD &>(getToolChain());
8534   const Driver &D = ToolChain.getDriver();
8535   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8536   const bool IsPIE =
8537       !Args.hasArg(options::OPT_shared) &&
8538       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8539   ArgStringList CmdArgs;
8540
8541   // Silence warning for "clang -g foo.o -o foo"
8542   Args.ClaimAllArgs(options::OPT_g_Group);
8543   // and "clang -emit-llvm foo.o -o foo"
8544   Args.ClaimAllArgs(options::OPT_emit_llvm);
8545   // and for "clang -w foo.o -o foo". Other warning options are already
8546   // handled somewhere else.
8547   Args.ClaimAllArgs(options::OPT_w);
8548
8549   if (!D.SysRoot.empty())
8550     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8551
8552   if (IsPIE)
8553     CmdArgs.push_back("-pie");
8554
8555   CmdArgs.push_back("--eh-frame-hdr");
8556   if (Args.hasArg(options::OPT_static)) {
8557     CmdArgs.push_back("-Bstatic");
8558   } else {
8559     if (Args.hasArg(options::OPT_rdynamic))
8560       CmdArgs.push_back("-export-dynamic");
8561     if (Args.hasArg(options::OPT_shared)) {
8562       CmdArgs.push_back("-Bshareable");
8563     } else {
8564       CmdArgs.push_back("-dynamic-linker");
8565       CmdArgs.push_back("/libexec/ld-elf.so.1");
8566     }
8567     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
8568       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
8569           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
8570         CmdArgs.push_back("--hash-style=both");
8571       }
8572     }
8573     CmdArgs.push_back("--enable-new-dtags");
8574   }
8575
8576   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8577   // instruct ld in the base system to link 32-bit code.
8578   if (Arch == llvm::Triple::x86) {
8579     CmdArgs.push_back("-m");
8580     CmdArgs.push_back("elf_i386_fbsd");
8581   }
8582
8583   if (Arch == llvm::Triple::ppc) {
8584     CmdArgs.push_back("-m");
8585     CmdArgs.push_back("elf32ppc_fbsd");
8586   }
8587
8588   if (Arg *A = Args.getLastArg(options::OPT_G)) {
8589     if (ToolChain.getArch() == llvm::Triple::mips ||
8590       ToolChain.getArch() == llvm::Triple::mipsel ||
8591       ToolChain.getArch() == llvm::Triple::mips64 ||
8592       ToolChain.getArch() == llvm::Triple::mips64el) {
8593       StringRef v = A->getValue();
8594       CmdArgs.push_back(Args.MakeArgString("-G" + v));
8595       A->claim();
8596     }
8597   }
8598
8599   if (Output.isFilename()) {
8600     CmdArgs.push_back("-o");
8601     CmdArgs.push_back(Output.getFilename());
8602   } else {
8603     assert(Output.isNothing() && "Invalid output.");
8604   }
8605
8606   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8607     const char *crt1 = nullptr;
8608     if (!Args.hasArg(options::OPT_shared)) {
8609       if (Args.hasArg(options::OPT_pg))
8610         crt1 = "gcrt1.o";
8611       else if (IsPIE)
8612         crt1 = "Scrt1.o";
8613       else
8614         crt1 = "crt1.o";
8615     }
8616     if (crt1)
8617       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8618
8619     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8620
8621     const char *crtbegin = nullptr;
8622     if (Args.hasArg(options::OPT_static))
8623       crtbegin = "crtbeginT.o";
8624     else if (Args.hasArg(options::OPT_shared) || IsPIE)
8625       crtbegin = "crtbeginS.o";
8626     else
8627       crtbegin = "crtbegin.o";
8628
8629     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8630   }
8631
8632   Args.AddAllArgs(CmdArgs, options::OPT_L);
8633   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8634   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8635   Args.AddAllArgs(CmdArgs, options::OPT_e);
8636   Args.AddAllArgs(CmdArgs, options::OPT_s);
8637   Args.AddAllArgs(CmdArgs, options::OPT_t);
8638   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8639   Args.AddAllArgs(CmdArgs, options::OPT_r);
8640
8641   if (D.isUsingLTO())
8642     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8643
8644   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8645   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8646
8647   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8648     addOpenMPRuntime(CmdArgs, ToolChain, Args);
8649     if (D.CCCIsCXX()) {
8650       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8651       if (Args.hasArg(options::OPT_pg))
8652         CmdArgs.push_back("-lm_p");
8653       else
8654         CmdArgs.push_back("-lm");
8655     }
8656     if (NeedsSanitizerDeps)
8657       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8658     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8659     // the default system libraries. Just mimic this for now.
8660     if (Args.hasArg(options::OPT_pg))
8661       CmdArgs.push_back("-lgcc_p");
8662     else
8663       CmdArgs.push_back("-lgcc");
8664     if (Args.hasArg(options::OPT_static)) {
8665       CmdArgs.push_back("-lgcc_eh");
8666     } else if (Args.hasArg(options::OPT_pg)) {
8667       CmdArgs.push_back("-lgcc_eh_p");
8668     } else {
8669       CmdArgs.push_back("--as-needed");
8670       CmdArgs.push_back("-lgcc_s");
8671       CmdArgs.push_back("--no-as-needed");
8672     }
8673
8674     if (Args.hasArg(options::OPT_pthread)) {
8675       if (Args.hasArg(options::OPT_pg))
8676         CmdArgs.push_back("-lpthread_p");
8677       else
8678         CmdArgs.push_back("-lpthread");
8679     }
8680
8681     if (Args.hasArg(options::OPT_pg)) {
8682       if (Args.hasArg(options::OPT_shared))
8683         CmdArgs.push_back("-lc");
8684       else
8685         CmdArgs.push_back("-lc_p");
8686       CmdArgs.push_back("-lgcc_p");
8687     } else {
8688       CmdArgs.push_back("-lc");
8689       CmdArgs.push_back("-lgcc");
8690     }
8691
8692     if (Args.hasArg(options::OPT_static)) {
8693       CmdArgs.push_back("-lgcc_eh");
8694     } else if (Args.hasArg(options::OPT_pg)) {
8695       CmdArgs.push_back("-lgcc_eh_p");
8696     } else {
8697       CmdArgs.push_back("--as-needed");
8698       CmdArgs.push_back("-lgcc_s");
8699       CmdArgs.push_back("--no-as-needed");
8700     }
8701   }
8702
8703   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8704     if (Args.hasArg(options::OPT_shared) || IsPIE)
8705       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8706     else
8707       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8708     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8709   }
8710
8711   ToolChain.addProfileRTLibs(Args, CmdArgs);
8712
8713   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8714   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8715 }
8716
8717 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8718                                      const InputInfo &Output,
8719                                      const InputInfoList &Inputs,
8720                                      const ArgList &Args,
8721                                      const char *LinkingOutput) const {
8722   claimNoWarnArgs(Args);
8723   ArgStringList CmdArgs;
8724
8725   // GNU as needs different flags for creating the correct output format
8726   // on architectures with different ABIs or optional feature sets.
8727   switch (getToolChain().getArch()) {
8728   case llvm::Triple::x86:
8729     CmdArgs.push_back("--32");
8730     break;
8731   case llvm::Triple::arm:
8732   case llvm::Triple::armeb:
8733   case llvm::Triple::thumb:
8734   case llvm::Triple::thumbeb: {
8735     StringRef MArch, MCPU;
8736     getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8737     std::string Arch =
8738         arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8739     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8740     break;
8741   }
8742
8743   case llvm::Triple::mips:
8744   case llvm::Triple::mipsel:
8745   case llvm::Triple::mips64:
8746   case llvm::Triple::mips64el: {
8747     StringRef CPUName;
8748     StringRef ABIName;
8749     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8750
8751     CmdArgs.push_back("-march");
8752     CmdArgs.push_back(CPUName.data());
8753
8754     CmdArgs.push_back("-mabi");
8755     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8756
8757     if (getToolChain().getArch() == llvm::Triple::mips ||
8758         getToolChain().getArch() == llvm::Triple::mips64)
8759       CmdArgs.push_back("-EB");
8760     else
8761       CmdArgs.push_back("-EL");
8762
8763     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8764     break;
8765   }
8766
8767   case llvm::Triple::sparc:
8768   case llvm::Triple::sparcel: {
8769     CmdArgs.push_back("-32");
8770     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8771     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8772     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8773     break;
8774   }
8775
8776   case llvm::Triple::sparcv9: {
8777     CmdArgs.push_back("-64");
8778     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8779     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8780     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8781     break;
8782   }
8783
8784   default:
8785     break;
8786   }
8787
8788   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8789
8790   CmdArgs.push_back("-o");
8791   CmdArgs.push_back(Output.getFilename());
8792
8793   for (const auto &II : Inputs)
8794     CmdArgs.push_back(II.getFilename());
8795
8796   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8797   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8798 }
8799
8800 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8801                                   const InputInfo &Output,
8802                                   const InputInfoList &Inputs,
8803                                   const ArgList &Args,
8804                                   const char *LinkingOutput) const {
8805   const Driver &D = getToolChain().getDriver();
8806   ArgStringList CmdArgs;
8807
8808   if (!D.SysRoot.empty())
8809     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8810
8811   CmdArgs.push_back("--eh-frame-hdr");
8812   if (Args.hasArg(options::OPT_static)) {
8813     CmdArgs.push_back("-Bstatic");
8814   } else {
8815     if (Args.hasArg(options::OPT_rdynamic))
8816       CmdArgs.push_back("-export-dynamic");
8817     if (Args.hasArg(options::OPT_shared)) {
8818       CmdArgs.push_back("-Bshareable");
8819     } else {
8820       Args.AddAllArgs(CmdArgs, options::OPT_pie);
8821       CmdArgs.push_back("-dynamic-linker");
8822       CmdArgs.push_back("/libexec/ld.elf_so");
8823     }
8824   }
8825
8826   // Many NetBSD architectures support more than one ABI.
8827   // Determine the correct emulation for ld.
8828   switch (getToolChain().getArch()) {
8829   case llvm::Triple::x86:
8830     CmdArgs.push_back("-m");
8831     CmdArgs.push_back("elf_i386");
8832     break;
8833   case llvm::Triple::arm:
8834   case llvm::Triple::thumb:
8835     CmdArgs.push_back("-m");
8836     switch (getToolChain().getTriple().getEnvironment()) {
8837     case llvm::Triple::EABI:
8838     case llvm::Triple::GNUEABI:
8839       CmdArgs.push_back("armelf_nbsd_eabi");
8840       break;
8841     case llvm::Triple::EABIHF:
8842     case llvm::Triple::GNUEABIHF:
8843       CmdArgs.push_back("armelf_nbsd_eabihf");
8844       break;
8845     default:
8846       CmdArgs.push_back("armelf_nbsd");
8847       break;
8848     }
8849     break;
8850   case llvm::Triple::armeb:
8851   case llvm::Triple::thumbeb:
8852     arm::appendEBLinkFlags(
8853         Args, CmdArgs,
8854         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8855     CmdArgs.push_back("-m");
8856     switch (getToolChain().getTriple().getEnvironment()) {
8857     case llvm::Triple::EABI:
8858     case llvm::Triple::GNUEABI:
8859       CmdArgs.push_back("armelfb_nbsd_eabi");
8860       break;
8861     case llvm::Triple::EABIHF:
8862     case llvm::Triple::GNUEABIHF:
8863       CmdArgs.push_back("armelfb_nbsd_eabihf");
8864       break;
8865     default:
8866       CmdArgs.push_back("armelfb_nbsd");
8867       break;
8868     }
8869     break;
8870   case llvm::Triple::mips64:
8871   case llvm::Triple::mips64el:
8872     if (mips::hasMipsAbiArg(Args, "32")) {
8873       CmdArgs.push_back("-m");
8874       if (getToolChain().getArch() == llvm::Triple::mips64)
8875         CmdArgs.push_back("elf32btsmip");
8876       else
8877         CmdArgs.push_back("elf32ltsmip");
8878     } else if (mips::hasMipsAbiArg(Args, "64")) {
8879       CmdArgs.push_back("-m");
8880       if (getToolChain().getArch() == llvm::Triple::mips64)
8881         CmdArgs.push_back("elf64btsmip");
8882       else
8883         CmdArgs.push_back("elf64ltsmip");
8884     }
8885     break;
8886   case llvm::Triple::ppc:
8887     CmdArgs.push_back("-m");
8888     CmdArgs.push_back("elf32ppc_nbsd");
8889     break;
8890
8891   case llvm::Triple::ppc64:
8892   case llvm::Triple::ppc64le:
8893     CmdArgs.push_back("-m");
8894     CmdArgs.push_back("elf64ppc");
8895     break;
8896
8897   case llvm::Triple::sparc:
8898     CmdArgs.push_back("-m");
8899     CmdArgs.push_back("elf32_sparc");
8900     break;
8901
8902   case llvm::Triple::sparcv9:
8903     CmdArgs.push_back("-m");
8904     CmdArgs.push_back("elf64_sparc");
8905     break;
8906
8907   default:
8908     break;
8909   }
8910
8911   if (Output.isFilename()) {
8912     CmdArgs.push_back("-o");
8913     CmdArgs.push_back(Output.getFilename());
8914   } else {
8915     assert(Output.isNothing() && "Invalid output.");
8916   }
8917
8918   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8919     if (!Args.hasArg(options::OPT_shared)) {
8920       CmdArgs.push_back(
8921           Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8922     }
8923     CmdArgs.push_back(
8924         Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8925     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
8926       CmdArgs.push_back(
8927           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8928     } else {
8929       CmdArgs.push_back(
8930           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8931     }
8932   }
8933
8934   Args.AddAllArgs(CmdArgs, options::OPT_L);
8935   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8936   Args.AddAllArgs(CmdArgs, options::OPT_e);
8937   Args.AddAllArgs(CmdArgs, options::OPT_s);
8938   Args.AddAllArgs(CmdArgs, options::OPT_t);
8939   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8940   Args.AddAllArgs(CmdArgs, options::OPT_r);
8941
8942   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8943
8944   unsigned Major, Minor, Micro;
8945   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8946   bool useLibgcc = true;
8947   if (Major >= 7 || Major == 0) {
8948     switch (getToolChain().getArch()) {
8949     case llvm::Triple::aarch64:
8950     case llvm::Triple::arm:
8951     case llvm::Triple::armeb:
8952     case llvm::Triple::thumb:
8953     case llvm::Triple::thumbeb:
8954     case llvm::Triple::ppc:
8955     case llvm::Triple::ppc64:
8956     case llvm::Triple::ppc64le:
8957     case llvm::Triple::sparc:
8958     case llvm::Triple::sparcv9:
8959     case llvm::Triple::x86:
8960     case llvm::Triple::x86_64:
8961       useLibgcc = false;
8962       break;
8963     default:
8964       break;
8965     }
8966   }
8967
8968   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8969     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8970     if (D.CCCIsCXX()) {
8971       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8972       CmdArgs.push_back("-lm");
8973     }
8974     if (Args.hasArg(options::OPT_pthread))
8975       CmdArgs.push_back("-lpthread");
8976     CmdArgs.push_back("-lc");
8977
8978     if (useLibgcc) {
8979       if (Args.hasArg(options::OPT_static)) {
8980         // libgcc_eh depends on libc, so resolve as much as possible,
8981         // pull in any new requirements from libc and then get the rest
8982         // of libgcc.
8983         CmdArgs.push_back("-lgcc_eh");
8984         CmdArgs.push_back("-lc");
8985         CmdArgs.push_back("-lgcc");
8986       } else {
8987         CmdArgs.push_back("-lgcc");
8988         CmdArgs.push_back("--as-needed");
8989         CmdArgs.push_back("-lgcc_s");
8990         CmdArgs.push_back("--no-as-needed");
8991       }
8992     }
8993   }
8994
8995   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8996     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8997       CmdArgs.push_back(
8998           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8999     else
9000       CmdArgs.push_back(
9001           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9002     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9003   }
9004
9005   getToolChain().addProfileRTLibs(Args, CmdArgs);
9006
9007   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9008   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9009 }
9010
9011 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9012                                        const InputInfo &Output,
9013                                        const InputInfoList &Inputs,
9014                                        const ArgList &Args,
9015                                        const char *LinkingOutput) const {
9016   claimNoWarnArgs(Args);
9017
9018   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9019   llvm::Triple Triple = llvm::Triple(TripleStr);
9020
9021   ArgStringList CmdArgs;
9022
9023   llvm::Reloc::Model RelocationModel;
9024   unsigned PICLevel;
9025   bool IsPIE;
9026   std::tie(RelocationModel, PICLevel, IsPIE) =
9027       ParsePICArgs(getToolChain(), Triple, Args);
9028
9029   switch (getToolChain().getArch()) {
9030   default:
9031     break;
9032   // Add --32/--64 to make sure we get the format we want.
9033   // This is incomplete
9034   case llvm::Triple::x86:
9035     CmdArgs.push_back("--32");
9036     break;
9037   case llvm::Triple::x86_64:
9038     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
9039       CmdArgs.push_back("--x32");
9040     else
9041       CmdArgs.push_back("--64");
9042     break;
9043   case llvm::Triple::ppc:
9044     CmdArgs.push_back("-a32");
9045     CmdArgs.push_back("-mppc");
9046     CmdArgs.push_back("-many");
9047     break;
9048   case llvm::Triple::ppc64:
9049     CmdArgs.push_back("-a64");
9050     CmdArgs.push_back("-mppc64");
9051     CmdArgs.push_back("-many");
9052     break;
9053   case llvm::Triple::ppc64le:
9054     CmdArgs.push_back("-a64");
9055     CmdArgs.push_back("-mppc64");
9056     CmdArgs.push_back("-many");
9057     CmdArgs.push_back("-mlittle-endian");
9058     break;
9059   case llvm::Triple::sparc:
9060   case llvm::Triple::sparcel: {
9061     CmdArgs.push_back("-32");
9062     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9063     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9064     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9065     break;
9066   }
9067   case llvm::Triple::sparcv9: {
9068     CmdArgs.push_back("-64");
9069     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9070     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9071     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9072     break;
9073   }
9074   case llvm::Triple::arm:
9075   case llvm::Triple::armeb:
9076   case llvm::Triple::thumb:
9077   case llvm::Triple::thumbeb: {
9078     const llvm::Triple &Triple2 = getToolChain().getTriple();
9079     switch (Triple2.getSubArch()) {
9080     case llvm::Triple::ARMSubArch_v7:
9081       CmdArgs.push_back("-mfpu=neon");
9082       break;
9083     case llvm::Triple::ARMSubArch_v8:
9084       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
9085       break;
9086     default:
9087       break;
9088     }
9089
9090     switch (arm::getARMFloatABI(getToolChain(), Args)) {
9091     case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
9092     case arm::FloatABI::Soft:
9093       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
9094       break;
9095     case arm::FloatABI::SoftFP:
9096       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
9097       break;
9098     case arm::FloatABI::Hard:
9099       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
9100       break;
9101     }
9102
9103     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
9104
9105     // FIXME: remove krait check when GNU tools support krait cpu
9106     // for now replace it with -mcpu=cortex-a15 to avoid a lower
9107     // march from being picked in the absence of a cpu flag.
9108     Arg *A;
9109     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
9110         StringRef(A->getValue()).lower() == "krait")
9111       CmdArgs.push_back("-mcpu=cortex-a15");
9112     else
9113       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
9114     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
9115     break;
9116   }
9117   case llvm::Triple::mips:
9118   case llvm::Triple::mipsel:
9119   case llvm::Triple::mips64:
9120   case llvm::Triple::mips64el: {
9121     StringRef CPUName;
9122     StringRef ABIName;
9123     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9124     ABIName = getGnuCompatibleMipsABIName(ABIName);
9125
9126     CmdArgs.push_back("-march");
9127     CmdArgs.push_back(CPUName.data());
9128
9129     CmdArgs.push_back("-mabi");
9130     CmdArgs.push_back(ABIName.data());
9131
9132     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
9133     // or -mshared (not implemented) is in effect.
9134     if (RelocationModel == llvm::Reloc::Static)
9135       CmdArgs.push_back("-mno-shared");
9136
9137     // LLVM doesn't support -mplt yet and acts as if it is always given.
9138     // However, -mplt has no effect with the N64 ABI.
9139     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
9140
9141     if (getToolChain().getArch() == llvm::Triple::mips ||
9142         getToolChain().getArch() == llvm::Triple::mips64)
9143       CmdArgs.push_back("-EB");
9144     else
9145       CmdArgs.push_back("-EL");
9146
9147     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
9148       if (StringRef(A->getValue()) == "2008")
9149         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
9150     }
9151
9152     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
9153     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
9154                                  options::OPT_mfp64)) {
9155       A->claim();
9156       A->render(Args, CmdArgs);
9157     } else if (mips::shouldUseFPXX(
9158                    Args, getToolChain().getTriple(), CPUName, ABIName,
9159                    getMipsFloatABI(getToolChain().getDriver(), Args)))
9160       CmdArgs.push_back("-mfpxx");
9161
9162     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
9163     // -mno-mips16 is actually -no-mips16.
9164     if (Arg *A =
9165             Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
9166       if (A->getOption().matches(options::OPT_mips16)) {
9167         A->claim();
9168         A->render(Args, CmdArgs);
9169       } else {
9170         A->claim();
9171         CmdArgs.push_back("-no-mips16");
9172       }
9173     }
9174
9175     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
9176                     options::OPT_mno_micromips);
9177     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
9178     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
9179
9180     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
9181       // Do not use AddLastArg because not all versions of MIPS assembler
9182       // support -mmsa / -mno-msa options.
9183       if (A->getOption().matches(options::OPT_mmsa))
9184         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
9185     }
9186
9187     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
9188                     options::OPT_msoft_float);
9189
9190     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
9191                     options::OPT_msingle_float);
9192
9193     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
9194                     options::OPT_mno_odd_spreg);
9195
9196     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9197     break;
9198   }
9199   case llvm::Triple::systemz: {
9200     // Always pass an -march option, since our default of z10 is later
9201     // than the GNU assembler's default.
9202     StringRef CPUName = getSystemZTargetCPU(Args);
9203     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
9204     break;
9205   }
9206   }
9207
9208   Args.AddAllArgs(CmdArgs, options::OPT_I);
9209   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9210
9211   CmdArgs.push_back("-o");
9212   CmdArgs.push_back(Output.getFilename());
9213
9214   for (const auto &II : Inputs)
9215     CmdArgs.push_back(II.getFilename());
9216
9217   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9218   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9219
9220   // Handle the debug info splitting at object creation time if we're
9221   // creating an object.
9222   // TODO: Currently only works on linux with newer objcopy.
9223   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
9224       getToolChain().getTriple().isOSLinux())
9225     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9226                    SplitDebugName(Args, Inputs[0]));
9227 }
9228
9229 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
9230                       ArgStringList &CmdArgs, const ArgList &Args) {
9231   bool isAndroid = Triple.isAndroid();
9232   bool isCygMing = Triple.isOSCygMing();
9233   bool IsIAMCU = Triple.isOSIAMCU();
9234   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
9235                       Args.hasArg(options::OPT_static);
9236   if (!D.CCCIsCXX())
9237     CmdArgs.push_back("-lgcc");
9238
9239   if (StaticLibgcc || isAndroid) {
9240     if (D.CCCIsCXX())
9241       CmdArgs.push_back("-lgcc");
9242   } else {
9243     if (!D.CCCIsCXX() && !isCygMing)
9244       CmdArgs.push_back("--as-needed");
9245     CmdArgs.push_back("-lgcc_s");
9246     if (!D.CCCIsCXX() && !isCygMing)
9247       CmdArgs.push_back("--no-as-needed");
9248   }
9249
9250   if (StaticLibgcc && !isAndroid && !IsIAMCU)
9251     CmdArgs.push_back("-lgcc_eh");
9252   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
9253     CmdArgs.push_back("-lgcc");
9254
9255   // According to Android ABI, we have to link with libdl if we are
9256   // linking with non-static libgcc.
9257   //
9258   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
9259   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
9260   if (isAndroid && !StaticLibgcc)
9261     CmdArgs.push_back("-ldl");
9262 }
9263
9264 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
9265                            ArgStringList &CmdArgs, const ArgList &Args) {
9266   // Make use of compiler-rt if --rtlib option is used
9267   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
9268
9269   switch (RLT) {
9270   case ToolChain::RLT_CompilerRT:
9271     switch (TC.getTriple().getOS()) {
9272     default:
9273       llvm_unreachable("unsupported OS");
9274     case llvm::Triple::Win32:
9275     case llvm::Triple::Linux:
9276       addClangRT(TC, Args, CmdArgs);
9277       break;
9278     }
9279     break;
9280   case ToolChain::RLT_Libgcc:
9281     // Make sure libgcc is not used under MSVC environment by default
9282     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
9283       // Issue error diagnostic if libgcc is explicitly specified
9284       // through command line as --rtlib option argument.
9285       if (Args.hasArg(options::OPT_rtlib_EQ)) {
9286         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
9287             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
9288       }
9289     } else
9290       AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
9291     break;
9292   }
9293 }
9294
9295 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
9296   switch (T.getArch()) {
9297   case llvm::Triple::x86:
9298     if (T.isOSIAMCU())
9299       return "elf_iamcu";
9300     return "elf_i386";
9301   case llvm::Triple::aarch64:
9302     return "aarch64linux";
9303   case llvm::Triple::aarch64_be:
9304     return "aarch64_be_linux";
9305   case llvm::Triple::arm:
9306   case llvm::Triple::thumb:
9307     return "armelf_linux_eabi";
9308   case llvm::Triple::armeb:
9309   case llvm::Triple::thumbeb:
9310     return "armelfb_linux_eabi";
9311   case llvm::Triple::ppc:
9312     return "elf32ppclinux";
9313   case llvm::Triple::ppc64:
9314     return "elf64ppc";
9315   case llvm::Triple::ppc64le:
9316     return "elf64lppc";
9317   case llvm::Triple::sparc:
9318   case llvm::Triple::sparcel:
9319     return "elf32_sparc";
9320   case llvm::Triple::sparcv9:
9321     return "elf64_sparc";
9322   case llvm::Triple::mips:
9323     return "elf32btsmip";
9324   case llvm::Triple::mipsel:
9325     return "elf32ltsmip";
9326   case llvm::Triple::mips64:
9327     if (mips::hasMipsAbiArg(Args, "n32"))
9328       return "elf32btsmipn32";
9329     return "elf64btsmip";
9330   case llvm::Triple::mips64el:
9331     if (mips::hasMipsAbiArg(Args, "n32"))
9332       return "elf32ltsmipn32";
9333     return "elf64ltsmip";
9334   case llvm::Triple::systemz:
9335     return "elf64_s390";
9336   case llvm::Triple::x86_64:
9337     if (T.getEnvironment() == llvm::Triple::GNUX32)
9338       return "elf32_x86_64";
9339     return "elf_x86_64";
9340   default:
9341     llvm_unreachable("Unexpected arch");
9342   }
9343 }
9344
9345 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9346                                     const InputInfo &Output,
9347                                     const InputInfoList &Inputs,
9348                                     const ArgList &Args,
9349                                     const char *LinkingOutput) const {
9350   const toolchains::Linux &ToolChain =
9351       static_cast<const toolchains::Linux &>(getToolChain());
9352   const Driver &D = ToolChain.getDriver();
9353
9354   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9355   llvm::Triple Triple = llvm::Triple(TripleStr);
9356
9357   const llvm::Triple::ArchType Arch = ToolChain.getArch();
9358   const bool isAndroid = ToolChain.getTriple().isAndroid();
9359   const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
9360   const bool IsPIE =
9361       !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
9362       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
9363   const bool HasCRTBeginEndFiles =
9364       ToolChain.getTriple().hasEnvironment() ||
9365       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
9366
9367   ArgStringList CmdArgs;
9368
9369   // Silence warning for "clang -g foo.o -o foo"
9370   Args.ClaimAllArgs(options::OPT_g_Group);
9371   // and "clang -emit-llvm foo.o -o foo"
9372   Args.ClaimAllArgs(options::OPT_emit_llvm);
9373   // and for "clang -w foo.o -o foo". Other warning options are already
9374   // handled somewhere else.
9375   Args.ClaimAllArgs(options::OPT_w);
9376
9377   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9378   if (llvm::sys::path::filename(Exec) == "lld") {
9379     CmdArgs.push_back("-flavor");
9380     CmdArgs.push_back("old-gnu");
9381     CmdArgs.push_back("-target");
9382     CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
9383   }
9384
9385   if (!D.SysRoot.empty())
9386     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9387
9388   if (IsPIE)
9389     CmdArgs.push_back("-pie");
9390
9391   if (Args.hasArg(options::OPT_rdynamic))
9392     CmdArgs.push_back("-export-dynamic");
9393
9394   if (Args.hasArg(options::OPT_s))
9395     CmdArgs.push_back("-s");
9396
9397   if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
9398     arm::appendEBLinkFlags(Args, CmdArgs, Triple);
9399
9400   for (const auto &Opt : ToolChain.ExtraOpts)
9401     CmdArgs.push_back(Opt.c_str());
9402
9403   if (!Args.hasArg(options::OPT_static)) {
9404     CmdArgs.push_back("--eh-frame-hdr");
9405   }
9406
9407   CmdArgs.push_back("-m");
9408   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
9409
9410   if (Args.hasArg(options::OPT_static)) {
9411     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
9412         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
9413       CmdArgs.push_back("-Bstatic");
9414     else
9415       CmdArgs.push_back("-static");
9416   } else if (Args.hasArg(options::OPT_shared)) {
9417     CmdArgs.push_back("-shared");
9418   }
9419
9420   if (!Args.hasArg(options::OPT_static)) {
9421     if (Args.hasArg(options::OPT_rdynamic))
9422       CmdArgs.push_back("-export-dynamic");
9423
9424     if (!Args.hasArg(options::OPT_shared)) {
9425       const std::string Loader =
9426           D.DyldPrefix + ToolChain.getDynamicLinker(Args);
9427       CmdArgs.push_back("-dynamic-linker");
9428       CmdArgs.push_back(Args.MakeArgString(Loader));
9429     }
9430   }
9431
9432   CmdArgs.push_back("-o");
9433   CmdArgs.push_back(Output.getFilename());
9434
9435   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9436     if (!isAndroid && !IsIAMCU) {
9437       const char *crt1 = nullptr;
9438       if (!Args.hasArg(options::OPT_shared)) {
9439         if (Args.hasArg(options::OPT_pg))
9440           crt1 = "gcrt1.o";
9441         else if (IsPIE)
9442           crt1 = "Scrt1.o";
9443         else
9444           crt1 = "crt1.o";
9445       }
9446       if (crt1)
9447         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
9448
9449       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9450     }
9451
9452     if (IsIAMCU)
9453       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
9454     else {
9455       const char *crtbegin;
9456       if (Args.hasArg(options::OPT_static))
9457         crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
9458       else if (Args.hasArg(options::OPT_shared))
9459         crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
9460       else if (IsPIE)
9461         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
9462       else
9463         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
9464
9465       if (HasCRTBeginEndFiles)
9466         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9467     }
9468
9469     // Add crtfastmath.o if available and fast math is enabled.
9470     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9471   }
9472
9473   Args.AddAllArgs(CmdArgs, options::OPT_L);
9474   Args.AddAllArgs(CmdArgs, options::OPT_u);
9475
9476   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9477
9478   if (D.isUsingLTO())
9479     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
9480
9481   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9482     CmdArgs.push_back("--no-demangle");
9483
9484   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
9485   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
9486   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9487   // The profile runtime also needs access to system libraries.
9488   getToolChain().addProfileRTLibs(Args, CmdArgs);
9489
9490   if (D.CCCIsCXX() &&
9491       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9492     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9493                                !Args.hasArg(options::OPT_static);
9494     if (OnlyLibstdcxxStatic)
9495       CmdArgs.push_back("-Bstatic");
9496     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9497     if (OnlyLibstdcxxStatic)
9498       CmdArgs.push_back("-Bdynamic");
9499     CmdArgs.push_back("-lm");
9500   }
9501   // Silence warnings when linking C code with a C++ '-stdlib' argument.
9502   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
9503
9504   if (!Args.hasArg(options::OPT_nostdlib)) {
9505     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9506       if (Args.hasArg(options::OPT_static))
9507         CmdArgs.push_back("--start-group");
9508
9509       if (NeedsSanitizerDeps)
9510         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
9511
9512       if (NeedsXRayDeps)
9513         linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
9514
9515       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
9516                          Args.hasArg(options::OPT_pthreads);
9517
9518       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9519                        options::OPT_fno_openmp, false)) {
9520         // OpenMP runtimes implies pthreads when using the GNU toolchain.
9521         // FIXME: Does this really make sense for all GNU toolchains?
9522         WantPthread = true;
9523
9524         // Also link the particular OpenMP runtimes.
9525         switch (getOpenMPRuntime(ToolChain, Args)) {
9526         case OMPRT_OMP:
9527           CmdArgs.push_back("-lomp");
9528           break;
9529         case OMPRT_GOMP:
9530           CmdArgs.push_back("-lgomp");
9531
9532           // FIXME: Exclude this for platforms with libgomp that don't require
9533           // librt. Most modern Linux platforms require it, but some may not.
9534           CmdArgs.push_back("-lrt");
9535           break;
9536         case OMPRT_IOMP5:
9537           CmdArgs.push_back("-liomp5");
9538           break;
9539         case OMPRT_Unknown:
9540           // Already diagnosed.
9541           break;
9542         }
9543       }
9544
9545       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9546
9547       if (WantPthread && !isAndroid)
9548         CmdArgs.push_back("-lpthread");
9549
9550       if (Args.hasArg(options::OPT_fsplit_stack))
9551         CmdArgs.push_back("--wrap=pthread_create");
9552
9553       CmdArgs.push_back("-lc");
9554
9555       // Add IAMCU specific libs, if needed.
9556       if (IsIAMCU)
9557         CmdArgs.push_back("-lgloss");
9558
9559       if (Args.hasArg(options::OPT_static))
9560         CmdArgs.push_back("--end-group");
9561       else
9562         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9563
9564       // Add IAMCU specific libs (outside the group), if needed.
9565       if (IsIAMCU) {
9566         CmdArgs.push_back("--as-needed");
9567         CmdArgs.push_back("-lsoftfp");
9568         CmdArgs.push_back("--no-as-needed");
9569       }
9570     }
9571
9572     if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
9573       const char *crtend;
9574       if (Args.hasArg(options::OPT_shared))
9575         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
9576       else if (IsPIE)
9577         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
9578       else
9579         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
9580
9581       if (HasCRTBeginEndFiles)
9582         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9583       if (!isAndroid)
9584         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9585     }
9586   }
9587
9588   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9589 }
9590
9591 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
9592 // for the various SFI requirements like register masking. The assembly tool
9593 // inserts the file containing the macros as an input into all the assembly
9594 // jobs.
9595 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
9596                                            const InputInfo &Output,
9597                                            const InputInfoList &Inputs,
9598                                            const ArgList &Args,
9599                                            const char *LinkingOutput) const {
9600   const toolchains::NaClToolChain &ToolChain =
9601       static_cast<const toolchains::NaClToolChain &>(getToolChain());
9602   InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9603                        "nacl-arm-macros.s");
9604   InputInfoList NewInputs;
9605   NewInputs.push_back(NaClMacros);
9606   NewInputs.append(Inputs.begin(), Inputs.end());
9607   gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9608                                     LinkingOutput);
9609 }
9610
9611 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9612 // we use static by default, do not yet support sanitizers or LTO, and a few
9613 // others. Eventually we can support more of that and hopefully migrate back
9614 // to gnutools::Linker.
9615 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9616                                      const InputInfo &Output,
9617                                      const InputInfoList &Inputs,
9618                                      const ArgList &Args,
9619                                      const char *LinkingOutput) const {
9620
9621   const toolchains::NaClToolChain &ToolChain =
9622       static_cast<const toolchains::NaClToolChain &>(getToolChain());
9623   const Driver &D = ToolChain.getDriver();
9624   const llvm::Triple::ArchType Arch = ToolChain.getArch();
9625   const bool IsStatic =
9626       !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9627
9628   ArgStringList CmdArgs;
9629
9630   // Silence warning for "clang -g foo.o -o foo"
9631   Args.ClaimAllArgs(options::OPT_g_Group);
9632   // and "clang -emit-llvm foo.o -o foo"
9633   Args.ClaimAllArgs(options::OPT_emit_llvm);
9634   // and for "clang -w foo.o -o foo". Other warning options are already
9635   // handled somewhere else.
9636   Args.ClaimAllArgs(options::OPT_w);
9637
9638   if (!D.SysRoot.empty())
9639     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9640
9641   if (Args.hasArg(options::OPT_rdynamic))
9642     CmdArgs.push_back("-export-dynamic");
9643
9644   if (Args.hasArg(options::OPT_s))
9645     CmdArgs.push_back("-s");
9646
9647   // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9648   // from there is --build-id, which we do want.
9649   CmdArgs.push_back("--build-id");
9650
9651   if (!IsStatic)
9652     CmdArgs.push_back("--eh-frame-hdr");
9653
9654   CmdArgs.push_back("-m");
9655   if (Arch == llvm::Triple::x86)
9656     CmdArgs.push_back("elf_i386_nacl");
9657   else if (Arch == llvm::Triple::arm)
9658     CmdArgs.push_back("armelf_nacl");
9659   else if (Arch == llvm::Triple::x86_64)
9660     CmdArgs.push_back("elf_x86_64_nacl");
9661   else if (Arch == llvm::Triple::mipsel)
9662     CmdArgs.push_back("mipselelf_nacl");
9663   else
9664     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9665                                               << "Native Client";
9666
9667   if (IsStatic)
9668     CmdArgs.push_back("-static");
9669   else if (Args.hasArg(options::OPT_shared))
9670     CmdArgs.push_back("-shared");
9671
9672   CmdArgs.push_back("-o");
9673   CmdArgs.push_back(Output.getFilename());
9674   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9675     if (!Args.hasArg(options::OPT_shared))
9676       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9677     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9678
9679     const char *crtbegin;
9680     if (IsStatic)
9681       crtbegin = "crtbeginT.o";
9682     else if (Args.hasArg(options::OPT_shared))
9683       crtbegin = "crtbeginS.o";
9684     else
9685       crtbegin = "crtbegin.o";
9686     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9687   }
9688
9689   Args.AddAllArgs(CmdArgs, options::OPT_L);
9690   Args.AddAllArgs(CmdArgs, options::OPT_u);
9691
9692   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9693
9694   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9695     CmdArgs.push_back("--no-demangle");
9696
9697   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9698
9699   if (D.CCCIsCXX() &&
9700       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9701     bool OnlyLibstdcxxStatic =
9702         Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9703     if (OnlyLibstdcxxStatic)
9704       CmdArgs.push_back("-Bstatic");
9705     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9706     if (OnlyLibstdcxxStatic)
9707       CmdArgs.push_back("-Bdynamic");
9708     CmdArgs.push_back("-lm");
9709   }
9710
9711   if (!Args.hasArg(options::OPT_nostdlib)) {
9712     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9713       // Always use groups, since it has no effect on dynamic libraries.
9714       CmdArgs.push_back("--start-group");
9715       CmdArgs.push_back("-lc");
9716       // NaCl's libc++ currently requires libpthread, so just always include it
9717       // in the group for C++.
9718       if (Args.hasArg(options::OPT_pthread) ||
9719           Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9720         // Gold, used by Mips, handles nested groups differently than ld, and
9721         // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9722         // which is not a desired behaviour here.
9723         // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9724         if (getToolChain().getArch() == llvm::Triple::mipsel)
9725           CmdArgs.push_back("-lnacl");
9726
9727         CmdArgs.push_back("-lpthread");
9728       }
9729
9730       CmdArgs.push_back("-lgcc");
9731       CmdArgs.push_back("--as-needed");
9732       if (IsStatic)
9733         CmdArgs.push_back("-lgcc_eh");
9734       else
9735         CmdArgs.push_back("-lgcc_s");
9736       CmdArgs.push_back("--no-as-needed");
9737
9738       // Mips needs to create and use pnacl_legacy library that contains
9739       // definitions from bitcode/pnaclmm.c and definitions for
9740       // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9741       if (getToolChain().getArch() == llvm::Triple::mipsel)
9742         CmdArgs.push_back("-lpnacl_legacy");
9743
9744       CmdArgs.push_back("--end-group");
9745     }
9746
9747     if (!Args.hasArg(options::OPT_nostartfiles)) {
9748       const char *crtend;
9749       if (Args.hasArg(options::OPT_shared))
9750         crtend = "crtendS.o";
9751       else
9752         crtend = "crtend.o";
9753
9754       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9755       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9756     }
9757   }
9758
9759   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9760   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9761 }
9762
9763 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9764                                     const InputInfo &Output,
9765                                     const InputInfoList &Inputs,
9766                                     const ArgList &Args,
9767                                     const char *LinkingOutput) const {
9768   claimNoWarnArgs(Args);
9769   ArgStringList CmdArgs;
9770
9771   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9772
9773   CmdArgs.push_back("-o");
9774   CmdArgs.push_back(Output.getFilename());
9775
9776   for (const auto &II : Inputs)
9777     CmdArgs.push_back(II.getFilename());
9778
9779   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9780   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9781 }
9782
9783 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9784                                  const InputInfo &Output,
9785                                  const InputInfoList &Inputs,
9786                                  const ArgList &Args,
9787                                  const char *LinkingOutput) const {
9788   const Driver &D = getToolChain().getDriver();
9789   ArgStringList CmdArgs;
9790
9791   if (Output.isFilename()) {
9792     CmdArgs.push_back("-o");
9793     CmdArgs.push_back(Output.getFilename());
9794   } else {
9795     assert(Output.isNothing() && "Invalid output.");
9796   }
9797
9798   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9799     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9800     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9801     CmdArgs.push_back(
9802         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9803     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9804   }
9805
9806   Args.AddAllArgs(CmdArgs,
9807                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9808
9809   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9810
9811   getToolChain().addProfileRTLibs(Args, CmdArgs);
9812
9813   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9814     if (D.CCCIsCXX()) {
9815       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9816       CmdArgs.push_back("-lm");
9817     }
9818   }
9819
9820   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9821     if (Args.hasArg(options::OPT_pthread))
9822       CmdArgs.push_back("-lpthread");
9823     CmdArgs.push_back("-lc");
9824     CmdArgs.push_back("-lCompilerRT-Generic");
9825     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9826     CmdArgs.push_back(
9827         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9828   }
9829
9830   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9831   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9832 }
9833
9834 /// DragonFly Tools
9835
9836 // For now, DragonFly Assemble does just about the same as for
9837 // FreeBSD, but this may change soon.
9838 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9839                                         const InputInfo &Output,
9840                                         const InputInfoList &Inputs,
9841                                         const ArgList &Args,
9842                                         const char *LinkingOutput) const {
9843   claimNoWarnArgs(Args);
9844   ArgStringList CmdArgs;
9845
9846   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9847   // instruct as in the base system to assemble 32-bit code.
9848   if (getToolChain().getArch() == llvm::Triple::x86)
9849     CmdArgs.push_back("--32");
9850
9851   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9852
9853   CmdArgs.push_back("-o");
9854   CmdArgs.push_back(Output.getFilename());
9855
9856   for (const auto &II : Inputs)
9857     CmdArgs.push_back(II.getFilename());
9858
9859   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9860   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9861 }
9862
9863 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9864                                      const InputInfo &Output,
9865                                      const InputInfoList &Inputs,
9866                                      const ArgList &Args,
9867                                      const char *LinkingOutput) const {
9868   const Driver &D = getToolChain().getDriver();
9869   ArgStringList CmdArgs;
9870
9871   if (!D.SysRoot.empty())
9872     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9873
9874   CmdArgs.push_back("--eh-frame-hdr");
9875   if (Args.hasArg(options::OPT_static)) {
9876     CmdArgs.push_back("-Bstatic");
9877   } else {
9878     if (Args.hasArg(options::OPT_rdynamic))
9879       CmdArgs.push_back("-export-dynamic");
9880     if (Args.hasArg(options::OPT_shared))
9881       CmdArgs.push_back("-Bshareable");
9882     else {
9883       CmdArgs.push_back("-dynamic-linker");
9884       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9885     }
9886     CmdArgs.push_back("--hash-style=gnu");
9887     CmdArgs.push_back("--enable-new-dtags");
9888   }
9889
9890   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9891   // instruct ld in the base system to link 32-bit code.
9892   if (getToolChain().getArch() == llvm::Triple::x86) {
9893     CmdArgs.push_back("-m");
9894     CmdArgs.push_back("elf_i386");
9895   }
9896
9897   if (Output.isFilename()) {
9898     CmdArgs.push_back("-o");
9899     CmdArgs.push_back(Output.getFilename());
9900   } else {
9901     assert(Output.isNothing() && "Invalid output.");
9902   }
9903
9904   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9905     if (!Args.hasArg(options::OPT_shared)) {
9906       if (Args.hasArg(options::OPT_pg))
9907         CmdArgs.push_back(
9908             Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9909       else {
9910         if (Args.hasArg(options::OPT_pie))
9911           CmdArgs.push_back(
9912               Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9913         else
9914           CmdArgs.push_back(
9915               Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9916       }
9917     }
9918     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9919     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9920       CmdArgs.push_back(
9921           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9922     else
9923       CmdArgs.push_back(
9924           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9925   }
9926
9927   Args.AddAllArgs(CmdArgs,
9928                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9929
9930   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9931
9932   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9933     CmdArgs.push_back("-L/usr/lib/gcc50");
9934
9935     if (!Args.hasArg(options::OPT_static)) {
9936       CmdArgs.push_back("-rpath");
9937       CmdArgs.push_back("/usr/lib/gcc50");
9938     }
9939
9940     if (D.CCCIsCXX()) {
9941       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9942       CmdArgs.push_back("-lm");
9943     }
9944
9945     if (Args.hasArg(options::OPT_pthread))
9946       CmdArgs.push_back("-lpthread");
9947
9948     if (!Args.hasArg(options::OPT_nolibc)) {
9949       CmdArgs.push_back("-lc");
9950     }
9951
9952     if (Args.hasArg(options::OPT_static) ||
9953         Args.hasArg(options::OPT_static_libgcc)) {
9954         CmdArgs.push_back("-lgcc");
9955         CmdArgs.push_back("-lgcc_eh");
9956     } else {
9957       if (Args.hasArg(options::OPT_shared_libgcc)) {
9958           CmdArgs.push_back("-lgcc_pic");
9959           if (!Args.hasArg(options::OPT_shared))
9960             CmdArgs.push_back("-lgcc");
9961       } else {
9962           CmdArgs.push_back("-lgcc");
9963           CmdArgs.push_back("--as-needed");
9964           CmdArgs.push_back("-lgcc_pic");
9965           CmdArgs.push_back("--no-as-needed");
9966       }
9967     }
9968   }
9969
9970   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9971     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9972       CmdArgs.push_back(
9973           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9974     else
9975       CmdArgs.push_back(
9976           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9977     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9978   }
9979
9980   getToolChain().addProfileRTLibs(Args, CmdArgs);
9981
9982   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9983   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9984 }
9985
9986 // Try to find Exe from a Visual Studio distribution.  This first tries to find
9987 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9988 // making sure that whatever executable that's found is not a same-named exe
9989 // from clang itself to prevent clang from falling back to itself.
9990 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9991                                               const char *Exe,
9992                                               const char *ClangProgramPath) {
9993   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9994   std::string visualStudioBinDir;
9995   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9996                                          visualStudioBinDir)) {
9997     SmallString<128> FilePath(visualStudioBinDir);
9998     llvm::sys::path::append(FilePath, Exe);
9999     if (llvm::sys::fs::can_execute(FilePath.c_str()))
10000       return FilePath.str();
10001   }
10002
10003   return Exe;
10004 }
10005
10006 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10007                                         const InputInfo &Output,
10008                                         const InputInfoList &Inputs,
10009                                         const ArgList &Args,
10010                                         const char *LinkingOutput) const {
10011   ArgStringList CmdArgs;
10012   const ToolChain &TC = getToolChain();
10013
10014   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
10015   if (Output.isFilename())
10016     CmdArgs.push_back(
10017         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
10018
10019   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
10020       !C.getDriver().IsCLMode())
10021     CmdArgs.push_back("-defaultlib:libcmt");
10022
10023   if (!llvm::sys::Process::GetEnv("LIB")) {
10024     // If the VC environment hasn't been configured (perhaps because the user
10025     // did not run vcvarsall), try to build a consistent link environment.  If
10026     // the environment variable is set however, assume the user knows what
10027     // they're doing.
10028     std::string VisualStudioDir;
10029     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
10030     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
10031       SmallString<128> LibDir(VisualStudioDir);
10032       llvm::sys::path::append(LibDir, "VC", "lib");
10033       switch (MSVC.getArch()) {
10034       case llvm::Triple::x86:
10035         // x86 just puts the libraries directly in lib
10036         break;
10037       case llvm::Triple::x86_64:
10038         llvm::sys::path::append(LibDir, "amd64");
10039         break;
10040       case llvm::Triple::arm:
10041         llvm::sys::path::append(LibDir, "arm");
10042         break;
10043       default:
10044         break;
10045       }
10046       CmdArgs.push_back(
10047           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
10048
10049       if (MSVC.useUniversalCRT(VisualStudioDir)) {
10050         std::string UniversalCRTLibPath;
10051         if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
10052           CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10053                                                UniversalCRTLibPath.c_str()));
10054       }
10055     }
10056
10057     std::string WindowsSdkLibPath;
10058     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
10059       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10060                                            WindowsSdkLibPath.c_str()));
10061   }
10062
10063   if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
10064     for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
10065       CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
10066
10067   CmdArgs.push_back("-nologo");
10068
10069   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
10070                   options::OPT__SLASH_Zd))
10071     CmdArgs.push_back("-debug");
10072
10073   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
10074                          options::OPT_shared);
10075   if (DLL) {
10076     CmdArgs.push_back(Args.MakeArgString("-dll"));
10077
10078     SmallString<128> ImplibName(Output.getFilename());
10079     llvm::sys::path::replace_extension(ImplibName, "lib");
10080     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
10081   }
10082
10083   if (TC.getSanitizerArgs().needsAsanRt()) {
10084     CmdArgs.push_back(Args.MakeArgString("-debug"));
10085     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
10086     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
10087       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10088         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10089       // Make sure the dynamic runtime thunk is not optimized out at link time
10090       // to ensure proper SEH handling.
10091       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
10092     } else if (DLL) {
10093       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10094     } else {
10095       for (const auto &Lib : {"asan", "asan_cxx"})
10096         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10097     }
10098   }
10099
10100   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
10101
10102   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10103                    options::OPT_fno_openmp, false)) {
10104     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
10105     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
10106     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10107                                          TC.getDriver().Dir + "/../lib"));
10108     switch (getOpenMPRuntime(getToolChain(), Args)) {
10109     case OMPRT_OMP:
10110       CmdArgs.push_back("-defaultlib:libomp.lib");
10111       break;
10112     case OMPRT_IOMP5:
10113       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
10114       break;
10115     case OMPRT_GOMP:
10116       break;
10117     case OMPRT_Unknown:
10118       // Already diagnosed.
10119       break;
10120     }
10121   }
10122
10123   // Add compiler-rt lib in case if it was explicitly
10124   // specified as an argument for --rtlib option.
10125   if (!Args.hasArg(options::OPT_nostdlib)) {
10126     AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
10127   }
10128
10129   // Add filenames, libraries, and other linker inputs.
10130   for (const auto &Input : Inputs) {
10131     if (Input.isFilename()) {
10132       CmdArgs.push_back(Input.getFilename());
10133       continue;
10134     }
10135
10136     const Arg &A = Input.getInputArg();
10137
10138     // Render -l options differently for the MSVC linker.
10139     if (A.getOption().matches(options::OPT_l)) {
10140       StringRef Lib = A.getValue();
10141       const char *LinkLibArg;
10142       if (Lib.endswith(".lib"))
10143         LinkLibArg = Args.MakeArgString(Lib);
10144       else
10145         LinkLibArg = Args.MakeArgString(Lib + ".lib");
10146       CmdArgs.push_back(LinkLibArg);
10147       continue;
10148     }
10149
10150     // Otherwise, this is some other kind of linker input option like -Wl, -z,
10151     // or -L. Render it, even if MSVC doesn't understand it.
10152     A.renderAsInput(Args, CmdArgs);
10153   }
10154
10155   TC.addProfileRTLibs(Args, CmdArgs);
10156
10157   // We need to special case some linker paths.  In the case of lld, we need to
10158   // translate 'lld' into 'lld-link', and in the case of the regular msvc
10159   // linker, we need to use a special search algorithm.
10160   llvm::SmallString<128> linkPath;
10161   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
10162   if (Linker.equals_lower("lld"))
10163     Linker = "lld-link";
10164
10165   if (Linker.equals_lower("link")) {
10166     // If we're using the MSVC linker, it's not sufficient to just use link
10167     // from the program PATH, because other environments like GnuWin32 install
10168     // their own link.exe which may come first.
10169     linkPath = FindVisualStudioExecutable(TC, "link.exe",
10170                                           C.getDriver().getClangProgramPath());
10171   } else {
10172     linkPath = Linker;
10173     llvm::sys::path::replace_extension(linkPath, "exe");
10174     linkPath = TC.GetProgramPath(linkPath.c_str());
10175   }
10176
10177   const char *Exec = Args.MakeArgString(linkPath);
10178   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10179 }
10180
10181 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10182                                           const InputInfo &Output,
10183                                           const InputInfoList &Inputs,
10184                                           const ArgList &Args,
10185                                           const char *LinkingOutput) const {
10186   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
10187 }
10188
10189 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
10190     Compilation &C, const JobAction &JA, const InputInfo &Output,
10191     const InputInfoList &Inputs, const ArgList &Args,
10192     const char *LinkingOutput) const {
10193   ArgStringList CmdArgs;
10194   CmdArgs.push_back("/nologo");
10195   CmdArgs.push_back("/c");  // Compile only.
10196   CmdArgs.push_back("/W0"); // No warnings.
10197
10198   // The goal is to be able to invoke this tool correctly based on
10199   // any flag accepted by clang-cl.
10200
10201   // These are spelled the same way in clang and cl.exe,.
10202   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
10203
10204   // Optimization level.
10205   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
10206     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
10207                                                                       : "/Oi-");
10208   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
10209     if (A->getOption().getID() == options::OPT_O0) {
10210       CmdArgs.push_back("/Od");
10211     } else {
10212       CmdArgs.push_back("/Og");
10213
10214       StringRef OptLevel = A->getValue();
10215       if (OptLevel == "s" || OptLevel == "z")
10216         CmdArgs.push_back("/Os");
10217       else
10218         CmdArgs.push_back("/Ot");
10219
10220       CmdArgs.push_back("/Ob2");
10221     }
10222   }
10223   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
10224                                options::OPT_fno_omit_frame_pointer))
10225     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
10226                           ? "/Oy"
10227                           : "/Oy-");
10228   if (!Args.hasArg(options::OPT_fwritable_strings))
10229     CmdArgs.push_back("/GF");
10230
10231   // Flags for which clang-cl has an alias.
10232   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
10233
10234   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
10235                    /*default=*/false))
10236     CmdArgs.push_back("/GR-");
10237
10238   if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
10239                    /*default=*/false))
10240     CmdArgs.push_back("/GS-");
10241
10242   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
10243                                options::OPT_fno_function_sections))
10244     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
10245                           ? "/Gy"
10246                           : "/Gy-");
10247   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
10248                                options::OPT_fno_data_sections))
10249     CmdArgs.push_back(
10250         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
10251   if (Args.hasArg(options::OPT_fsyntax_only))
10252     CmdArgs.push_back("/Zs");
10253   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
10254                   options::OPT__SLASH_Z7))
10255     CmdArgs.push_back("/Z7");
10256
10257   std::vector<std::string> Includes =
10258       Args.getAllArgValues(options::OPT_include);
10259   for (const auto &Include : Includes)
10260     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
10261
10262   // Flags that can simply be passed through.
10263   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
10264   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
10265   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
10266   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
10267   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
10268   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
10269
10270   // The order of these flags is relevant, so pick the last one.
10271   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
10272                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
10273     A->render(Args, CmdArgs);
10274
10275   // Pass through all unknown arguments so that the fallback command can see
10276   // them too.
10277   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
10278
10279   // Input filename.
10280   assert(Inputs.size() == 1);
10281   const InputInfo &II = Inputs[0];
10282   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
10283   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
10284   if (II.isFilename())
10285     CmdArgs.push_back(II.getFilename());
10286   else
10287     II.getInputArg().renderAsInput(Args, CmdArgs);
10288
10289   // Output filename.
10290   assert(Output.getType() == types::TY_Object);
10291   const char *Fo =
10292       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
10293   CmdArgs.push_back(Fo);
10294
10295   const Driver &D = getToolChain().getDriver();
10296   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
10297                                                 D.getClangProgramPath());
10298   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10299                                     CmdArgs, Inputs);
10300 }
10301
10302 /// MinGW Tools
10303 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10304                                     const InputInfo &Output,
10305                                     const InputInfoList &Inputs,
10306                                     const ArgList &Args,
10307                                     const char *LinkingOutput) const {
10308   claimNoWarnArgs(Args);
10309   ArgStringList CmdArgs;
10310
10311   if (getToolChain().getArch() == llvm::Triple::x86) {
10312     CmdArgs.push_back("--32");
10313   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
10314     CmdArgs.push_back("--64");
10315   }
10316
10317   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10318
10319   CmdArgs.push_back("-o");
10320   CmdArgs.push_back(Output.getFilename());
10321
10322   for (const auto &II : Inputs)
10323     CmdArgs.push_back(II.getFilename());
10324
10325   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10326   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10327
10328   if (Args.hasArg(options::OPT_gsplit_dwarf))
10329     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
10330                    SplitDebugName(Args, Inputs[0]));
10331 }
10332
10333 void MinGW::Linker::AddLibGCC(const ArgList &Args,
10334                               ArgStringList &CmdArgs) const {
10335   if (Args.hasArg(options::OPT_mthreads))
10336     CmdArgs.push_back("-lmingwthrd");
10337   CmdArgs.push_back("-lmingw32");
10338
10339   // Make use of compiler-rt if --rtlib option is used
10340   ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
10341   if (RLT == ToolChain::RLT_Libgcc) {
10342     bool Static = Args.hasArg(options::OPT_static_libgcc) ||
10343                   Args.hasArg(options::OPT_static);
10344     bool Shared = Args.hasArg(options::OPT_shared);
10345     bool CXX = getToolChain().getDriver().CCCIsCXX();
10346
10347     if (Static || (!CXX && !Shared)) {
10348       CmdArgs.push_back("-lgcc");
10349       CmdArgs.push_back("-lgcc_eh");
10350     } else {
10351       CmdArgs.push_back("-lgcc_s");
10352       CmdArgs.push_back("-lgcc");
10353     }
10354   } else {
10355     AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
10356   }
10357
10358   CmdArgs.push_back("-lmoldname");
10359   CmdArgs.push_back("-lmingwex");
10360   CmdArgs.push_back("-lmsvcrt");
10361 }
10362
10363 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10364                                  const InputInfo &Output,
10365                                  const InputInfoList &Inputs,
10366                                  const ArgList &Args,
10367                                  const char *LinkingOutput) const {
10368   const ToolChain &TC = getToolChain();
10369   const Driver &D = TC.getDriver();
10370   // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
10371
10372   ArgStringList CmdArgs;
10373
10374   // Silence warning for "clang -g foo.o -o foo"
10375   Args.ClaimAllArgs(options::OPT_g_Group);
10376   // and "clang -emit-llvm foo.o -o foo"
10377   Args.ClaimAllArgs(options::OPT_emit_llvm);
10378   // and for "clang -w foo.o -o foo". Other warning options are already
10379   // handled somewhere else.
10380   Args.ClaimAllArgs(options::OPT_w);
10381
10382   StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
10383   if (LinkerName.equals_lower("lld")) {
10384     CmdArgs.push_back("-flavor");
10385     CmdArgs.push_back("gnu");
10386   } else if (!LinkerName.equals_lower("ld")) {
10387     D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
10388   }
10389
10390   if (!D.SysRoot.empty())
10391     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10392
10393   if (Args.hasArg(options::OPT_s))
10394     CmdArgs.push_back("-s");
10395
10396   CmdArgs.push_back("-m");
10397   if (TC.getArch() == llvm::Triple::x86)
10398     CmdArgs.push_back("i386pe");
10399   if (TC.getArch() == llvm::Triple::x86_64)
10400     CmdArgs.push_back("i386pep");
10401   if (TC.getArch() == llvm::Triple::arm)
10402     CmdArgs.push_back("thumb2pe");
10403
10404   if (Args.hasArg(options::OPT_mwindows)) {
10405     CmdArgs.push_back("--subsystem");
10406     CmdArgs.push_back("windows");
10407   } else if (Args.hasArg(options::OPT_mconsole)) {
10408     CmdArgs.push_back("--subsystem");
10409     CmdArgs.push_back("console");
10410   }
10411
10412   if (Args.hasArg(options::OPT_static))
10413     CmdArgs.push_back("-Bstatic");
10414   else {
10415     if (Args.hasArg(options::OPT_mdll))
10416       CmdArgs.push_back("--dll");
10417     else if (Args.hasArg(options::OPT_shared))
10418       CmdArgs.push_back("--shared");
10419     CmdArgs.push_back("-Bdynamic");
10420     if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
10421       CmdArgs.push_back("-e");
10422       if (TC.getArch() == llvm::Triple::x86)
10423         CmdArgs.push_back("_DllMainCRTStartup@12");
10424       else
10425         CmdArgs.push_back("DllMainCRTStartup");
10426       CmdArgs.push_back("--enable-auto-image-base");
10427     }
10428   }
10429
10430   CmdArgs.push_back("-o");
10431   CmdArgs.push_back(Output.getFilename());
10432
10433   Args.AddAllArgs(CmdArgs, options::OPT_e);
10434   // FIXME: add -N, -n flags
10435   Args.AddLastArg(CmdArgs, options::OPT_r);
10436   Args.AddLastArg(CmdArgs, options::OPT_s);
10437   Args.AddLastArg(CmdArgs, options::OPT_t);
10438   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
10439   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
10440
10441   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10442     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
10443       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
10444     } else {
10445       if (Args.hasArg(options::OPT_municode))
10446         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
10447       else
10448         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
10449     }
10450     if (Args.hasArg(options::OPT_pg))
10451       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
10452     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10453   }
10454
10455   Args.AddAllArgs(CmdArgs, options::OPT_L);
10456   TC.AddFilePathLibArgs(Args, CmdArgs);
10457   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10458
10459   // TODO: Add ASan stuff here
10460
10461   // TODO: Add profile stuff here
10462
10463   if (D.CCCIsCXX() &&
10464       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10465     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10466                                !Args.hasArg(options::OPT_static);
10467     if (OnlyLibstdcxxStatic)
10468       CmdArgs.push_back("-Bstatic");
10469     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10470     if (OnlyLibstdcxxStatic)
10471       CmdArgs.push_back("-Bdynamic");
10472   }
10473
10474   if (!Args.hasArg(options::OPT_nostdlib)) {
10475     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10476       if (Args.hasArg(options::OPT_static))
10477         CmdArgs.push_back("--start-group");
10478
10479       if (Args.hasArg(options::OPT_fstack_protector) ||
10480           Args.hasArg(options::OPT_fstack_protector_strong) ||
10481           Args.hasArg(options::OPT_fstack_protector_all)) {
10482         CmdArgs.push_back("-lssp_nonshared");
10483         CmdArgs.push_back("-lssp");
10484       }
10485       if (Args.hasArg(options::OPT_fopenmp))
10486         CmdArgs.push_back("-lgomp");
10487
10488       AddLibGCC(Args, CmdArgs);
10489
10490       if (Args.hasArg(options::OPT_pg))
10491         CmdArgs.push_back("-lgmon");
10492
10493       if (Args.hasArg(options::OPT_pthread))
10494         CmdArgs.push_back("-lpthread");
10495
10496       // add system libraries
10497       if (Args.hasArg(options::OPT_mwindows)) {
10498         CmdArgs.push_back("-lgdi32");
10499         CmdArgs.push_back("-lcomdlg32");
10500       }
10501       CmdArgs.push_back("-ladvapi32");
10502       CmdArgs.push_back("-lshell32");
10503       CmdArgs.push_back("-luser32");
10504       CmdArgs.push_back("-lkernel32");
10505
10506       if (Args.hasArg(options::OPT_static))
10507         CmdArgs.push_back("--end-group");
10508       else if (!LinkerName.equals_lower("lld"))
10509         AddLibGCC(Args, CmdArgs);
10510     }
10511
10512     if (!Args.hasArg(options::OPT_nostartfiles)) {
10513       // Add crtfastmath.o if available and fast math is enabled.
10514       TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
10515
10516       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10517     }
10518   }
10519   const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
10520   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10521 }
10522
10523 /// XCore Tools
10524 // We pass assemble and link construction to the xcc tool.
10525
10526 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10527                                     const InputInfo &Output,
10528                                     const InputInfoList &Inputs,
10529                                     const ArgList &Args,
10530                                     const char *LinkingOutput) const {
10531   claimNoWarnArgs(Args);
10532   ArgStringList CmdArgs;
10533
10534   CmdArgs.push_back("-o");
10535   CmdArgs.push_back(Output.getFilename());
10536
10537   CmdArgs.push_back("-c");
10538
10539   if (Args.hasArg(options::OPT_v))
10540     CmdArgs.push_back("-v");
10541
10542   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
10543     if (!A->getOption().matches(options::OPT_g0))
10544       CmdArgs.push_back("-g");
10545
10546   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
10547                    false))
10548     CmdArgs.push_back("-fverbose-asm");
10549
10550   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10551
10552   for (const auto &II : Inputs)
10553     CmdArgs.push_back(II.getFilename());
10554
10555   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10556   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10557 }
10558
10559 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10560                                  const InputInfo &Output,
10561                                  const InputInfoList &Inputs,
10562                                  const ArgList &Args,
10563                                  const char *LinkingOutput) const {
10564   ArgStringList CmdArgs;
10565
10566   if (Output.isFilename()) {
10567     CmdArgs.push_back("-o");
10568     CmdArgs.push_back(Output.getFilename());
10569   } else {
10570     assert(Output.isNothing() && "Invalid output.");
10571   }
10572
10573   if (Args.hasArg(options::OPT_v))
10574     CmdArgs.push_back("-v");
10575
10576   // Pass -fexceptions through to the linker if it was present.
10577   if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
10578                    false))
10579     CmdArgs.push_back("-fexceptions");
10580
10581   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10582
10583   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10584   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10585 }
10586
10587 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10588                                            const InputInfo &Output,
10589                                            const InputInfoList &Inputs,
10590                                            const ArgList &Args,
10591                                            const char *LinkingOutput) const {
10592   claimNoWarnArgs(Args);
10593   const auto &TC =
10594       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10595   ArgStringList CmdArgs;
10596   const char *Exec;
10597
10598   switch (TC.getArch()) {
10599   default:
10600     llvm_unreachable("unsupported architecture");
10601   case llvm::Triple::arm:
10602   case llvm::Triple::thumb:
10603     break;
10604   case llvm::Triple::x86:
10605     CmdArgs.push_back("--32");
10606     break;
10607   case llvm::Triple::x86_64:
10608     CmdArgs.push_back("--64");
10609     break;
10610   }
10611
10612   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10613
10614   CmdArgs.push_back("-o");
10615   CmdArgs.push_back(Output.getFilename());
10616
10617   for (const auto &Input : Inputs)
10618     CmdArgs.push_back(Input.getFilename());
10619
10620   const std::string Assembler = TC.GetProgramPath("as");
10621   Exec = Args.MakeArgString(Assembler);
10622
10623   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10624 }
10625
10626 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10627                                         const InputInfo &Output,
10628                                         const InputInfoList &Inputs,
10629                                         const ArgList &Args,
10630                                         const char *LinkingOutput) const {
10631   const auto &TC =
10632       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10633   const llvm::Triple &T = TC.getTriple();
10634   const Driver &D = TC.getDriver();
10635   SmallString<128> EntryPoint;
10636   ArgStringList CmdArgs;
10637   const char *Exec;
10638
10639   // Silence warning for "clang -g foo.o -o foo"
10640   Args.ClaimAllArgs(options::OPT_g_Group);
10641   // and "clang -emit-llvm foo.o -o foo"
10642   Args.ClaimAllArgs(options::OPT_emit_llvm);
10643   // and for "clang -w foo.o -o foo"
10644   Args.ClaimAllArgs(options::OPT_w);
10645   // Other warning options are already handled somewhere else.
10646
10647   if (!D.SysRoot.empty())
10648     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10649
10650   if (Args.hasArg(options::OPT_pie))
10651     CmdArgs.push_back("-pie");
10652   if (Args.hasArg(options::OPT_rdynamic))
10653     CmdArgs.push_back("-export-dynamic");
10654   if (Args.hasArg(options::OPT_s))
10655     CmdArgs.push_back("--strip-all");
10656
10657   CmdArgs.push_back("-m");
10658   switch (TC.getArch()) {
10659   default:
10660     llvm_unreachable("unsupported architecture");
10661   case llvm::Triple::arm:
10662   case llvm::Triple::thumb:
10663     // FIXME: this is incorrect for WinCE
10664     CmdArgs.push_back("thumb2pe");
10665     break;
10666   case llvm::Triple::x86:
10667     CmdArgs.push_back("i386pe");
10668     EntryPoint.append("_");
10669     break;
10670   case llvm::Triple::x86_64:
10671     CmdArgs.push_back("i386pep");
10672     break;
10673   }
10674
10675   if (Args.hasArg(options::OPT_shared)) {
10676     switch (T.getArch()) {
10677     default:
10678       llvm_unreachable("unsupported architecture");
10679     case llvm::Triple::arm:
10680     case llvm::Triple::thumb:
10681     case llvm::Triple::x86_64:
10682       EntryPoint.append("_DllMainCRTStartup");
10683       break;
10684     case llvm::Triple::x86:
10685       EntryPoint.append("_DllMainCRTStartup@12");
10686       break;
10687     }
10688
10689     CmdArgs.push_back("-shared");
10690     CmdArgs.push_back("-Bdynamic");
10691
10692     CmdArgs.push_back("--enable-auto-image-base");
10693
10694     CmdArgs.push_back("--entry");
10695     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10696   } else {
10697     EntryPoint.append("mainCRTStartup");
10698
10699     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10700                                                        : "-Bdynamic");
10701
10702     if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10703       CmdArgs.push_back("--entry");
10704       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10705     }
10706
10707     // FIXME: handle subsystem
10708   }
10709
10710   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10711   CmdArgs.push_back("--allow-multiple-definition");
10712
10713   CmdArgs.push_back("-o");
10714   CmdArgs.push_back(Output.getFilename());
10715
10716   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10717     SmallString<261> ImpLib(Output.getFilename());
10718     llvm::sys::path::replace_extension(ImpLib, ".lib");
10719
10720     CmdArgs.push_back("--out-implib");
10721     CmdArgs.push_back(Args.MakeArgString(ImpLib));
10722   }
10723
10724   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10725     const std::string CRTPath(D.SysRoot + "/usr/lib/");
10726     const char *CRTBegin;
10727
10728     CRTBegin =
10729         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10730     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10731   }
10732
10733   Args.AddAllArgs(CmdArgs, options::OPT_L);
10734   TC.AddFilePathLibArgs(Args, CmdArgs);
10735   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10736
10737   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10738       !Args.hasArg(options::OPT_nodefaultlibs)) {
10739     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10740                      !Args.hasArg(options::OPT_static);
10741     if (StaticCXX)
10742       CmdArgs.push_back("-Bstatic");
10743     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10744     if (StaticCXX)
10745       CmdArgs.push_back("-Bdynamic");
10746   }
10747
10748   if (!Args.hasArg(options::OPT_nostdlib)) {
10749     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10750       // TODO handle /MT[d] /MD[d]
10751       CmdArgs.push_back("-lmsvcrt");
10752       AddRunTimeLibs(TC, D, CmdArgs, Args);
10753     }
10754   }
10755
10756   if (TC.getSanitizerArgs().needsAsanRt()) {
10757     // TODO handle /MT[d] /MD[d]
10758     if (Args.hasArg(options::OPT_shared)) {
10759       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10760     } else {
10761       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10762         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10763       // Make sure the dynamic runtime thunk is not optimized out at link time
10764       // to ensure proper SEH handling.
10765       CmdArgs.push_back(Args.MakeArgString("--undefined"));
10766       CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10767                                                ? "___asan_seh_interceptor"
10768                                                : "__asan_seh_interceptor"));
10769     }
10770   }
10771
10772   Exec = Args.MakeArgString(TC.GetLinkerPath());
10773
10774   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10775 }
10776
10777 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10778                                           const InputInfo &Output,
10779                                           const InputInfoList &Inputs,
10780                                           const ArgList &Args,
10781                                           const char *LinkingOutput) const {
10782   ArgStringList CmdArgs;
10783   assert(Inputs.size() == 1);
10784   const InputInfo &II = Inputs[0];
10785   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10786          II.getType() == types::TY_PP_CXX);
10787
10788   if (JA.getKind() == Action::PreprocessJobClass) {
10789     Args.ClaimAllArgs();
10790     CmdArgs.push_back("-E");
10791   } else {
10792     assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10793     CmdArgs.push_back("-S");
10794     CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10795   }
10796   CmdArgs.push_back("-DMYRIAD2");
10797
10798   // Append all -I, -iquote, -isystem paths, defines/undefines,
10799   // 'f' flags, optimize flags, and warning options.
10800   // These are spelled the same way in clang and moviCompile.
10801   Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10802                             options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10803                             options::OPT_f_Group, options::OPT_f_clang_Group,
10804                             options::OPT_g_Group, options::OPT_M_Group,
10805                             options::OPT_O_Group, options::OPT_W_Group,
10806                             options::OPT_mcpu_EQ});
10807
10808   // If we're producing a dependency file, and assembly is the final action,
10809   // then the name of the target in the dependency file should be the '.o'
10810   // file, not the '.s' file produced by this step. For example, instead of
10811   //  /tmp/mumble.s: mumble.c .../someheader.h
10812   // the filename on the lefthand side should be "mumble.o"
10813   if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10814       C.getActions().size() == 1 &&
10815       C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10816     Arg *A = Args.getLastArg(options::OPT_o);
10817     if (A) {
10818       CmdArgs.push_back("-MT");
10819       CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10820     }
10821   }
10822
10823   CmdArgs.push_back(II.getFilename());
10824   CmdArgs.push_back("-o");
10825   CmdArgs.push_back(Output.getFilename());
10826
10827   std::string Exec =
10828       Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10829   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10830                                           CmdArgs, Inputs));
10831 }
10832
10833 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10834                                            const InputInfo &Output,
10835                                            const InputInfoList &Inputs,
10836                                            const ArgList &Args,
10837                                            const char *LinkingOutput) const {
10838   ArgStringList CmdArgs;
10839
10840   assert(Inputs.size() == 1);
10841   const InputInfo &II = Inputs[0];
10842   assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10843   assert(Output.getType() == types::TY_Object);
10844
10845   CmdArgs.push_back("-no6thSlotCompression");
10846   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
10847   if (CPUArg)
10848     CmdArgs.push_back(
10849         Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
10850   CmdArgs.push_back("-noSPrefixing");
10851   CmdArgs.push_back("-a"); // Mystery option.
10852   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10853   for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10854     A->claim();
10855     CmdArgs.push_back(
10856         Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10857   }
10858   CmdArgs.push_back("-elf"); // Output format.
10859   CmdArgs.push_back(II.getFilename());
10860   CmdArgs.push_back(
10861       Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10862
10863   std::string Exec =
10864       Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10865   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10866                                           CmdArgs, Inputs));
10867 }
10868
10869 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10870                                          const InputInfo &Output,
10871                                          const InputInfoList &Inputs,
10872                                          const ArgList &Args,
10873                                          const char *LinkingOutput) const {
10874   const auto &TC =
10875       static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10876   const llvm::Triple &T = TC.getTriple();
10877   ArgStringList CmdArgs;
10878   bool UseStartfiles =
10879       !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10880   bool UseDefaultLibs =
10881       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10882
10883   if (T.getArch() == llvm::Triple::sparc)
10884     CmdArgs.push_back("-EB");
10885   else // SHAVE assumes little-endian, and sparcel is expressly so.
10886     CmdArgs.push_back("-EL");
10887
10888   // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10889   // but we never pass through a --sysroot option and various other bits.
10890   // For example, there are no sanitizers (yet) nor gold linker.
10891
10892   // Eat some arguments that may be present but have no effect.
10893   Args.ClaimAllArgs(options::OPT_g_Group);
10894   Args.ClaimAllArgs(options::OPT_w);
10895   Args.ClaimAllArgs(options::OPT_static_libgcc);
10896
10897   if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10898     CmdArgs.push_back("-s");
10899
10900   CmdArgs.push_back("-o");
10901   CmdArgs.push_back(Output.getFilename());
10902
10903   if (UseStartfiles) {
10904     // If you want startfiles, it means you want the builtin crti and crtbegin,
10905     // but not crt0. Myriad link commands provide their own crt0.o as needed.
10906     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10907     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10908   }
10909
10910   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10911                             options::OPT_e, options::OPT_s, options::OPT_t,
10912                             options::OPT_Z_Flag, options::OPT_r});
10913
10914   TC.AddFilePathLibArgs(Args, CmdArgs);
10915
10916   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10917
10918   if (UseDefaultLibs) {
10919     if (C.getDriver().CCCIsCXX())
10920       CmdArgs.push_back("-lstdc++");
10921     if (T.getOS() == llvm::Triple::RTEMS) {
10922       CmdArgs.push_back("--start-group");
10923       CmdArgs.push_back("-lc");
10924       // You must provide your own "-L" option to enable finding these.
10925       CmdArgs.push_back("-lrtemscpu");
10926       CmdArgs.push_back("-lrtemsbsp");
10927       CmdArgs.push_back("--end-group");
10928     } else {
10929       CmdArgs.push_back("-lc");
10930     }
10931     CmdArgs.push_back("-lgcc");
10932   }
10933   if (UseStartfiles) {
10934     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10935     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10936   }
10937
10938   std::string Exec =
10939       Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10940   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10941                                           CmdArgs, Inputs));
10942 }
10943
10944 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10945                                     const InputInfo &Output,
10946                                     const InputInfoList &Inputs,
10947                                     const ArgList &Args,
10948                                     const char *LinkingOutput) const {
10949   claimNoWarnArgs(Args);
10950   ArgStringList CmdArgs;
10951
10952   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10953
10954   CmdArgs.push_back("-o");
10955   CmdArgs.push_back(Output.getFilename());
10956
10957   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10958   const InputInfo &Input = Inputs[0];
10959   assert(Input.isFilename() && "Invalid input.");
10960   CmdArgs.push_back(Input.getFilename());
10961
10962   const char *Exec =
10963       Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
10964   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10965 }
10966
10967 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10968   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10969   if (SanArgs.needsUbsanRt()) {
10970     CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10971   }
10972   if (SanArgs.needsAsanRt()) {
10973     CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10974   }
10975 }
10976
10977 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10978                                 const JobAction &JA, const InputInfo &Output,
10979                                 const InputInfoList &Inputs,
10980                                 const ArgList &Args,
10981                                 const char *LinkingOutput) {
10982   const toolchains::FreeBSD &ToolChain =
10983       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10984   const Driver &D = ToolChain.getDriver();
10985   ArgStringList CmdArgs;
10986
10987   // Silence warning for "clang -g foo.o -o foo"
10988   Args.ClaimAllArgs(options::OPT_g_Group);
10989   // and "clang -emit-llvm foo.o -o foo"
10990   Args.ClaimAllArgs(options::OPT_emit_llvm);
10991   // and for "clang -w foo.o -o foo". Other warning options are already
10992   // handled somewhere else.
10993   Args.ClaimAllArgs(options::OPT_w);
10994
10995   if (!D.SysRoot.empty())
10996     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10997
10998   if (Args.hasArg(options::OPT_pie))
10999     CmdArgs.push_back("-pie");
11000
11001   if (Args.hasArg(options::OPT_rdynamic))
11002     CmdArgs.push_back("-export-dynamic");
11003   if (Args.hasArg(options::OPT_shared))
11004     CmdArgs.push_back("--oformat=so");
11005
11006   if (Output.isFilename()) {
11007     CmdArgs.push_back("-o");
11008     CmdArgs.push_back(Output.getFilename());
11009   } else {
11010     assert(Output.isNothing() && "Invalid output.");
11011   }
11012
11013   AddPS4SanitizerArgs(ToolChain, CmdArgs);
11014
11015   Args.AddAllArgs(CmdArgs, options::OPT_L);
11016   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11017   Args.AddAllArgs(CmdArgs, options::OPT_e);
11018   Args.AddAllArgs(CmdArgs, options::OPT_s);
11019   Args.AddAllArgs(CmdArgs, options::OPT_t);
11020   Args.AddAllArgs(CmdArgs, options::OPT_r);
11021
11022   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11023     CmdArgs.push_back("--no-demangle");
11024
11025   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11026
11027   if (Args.hasArg(options::OPT_pthread)) {
11028     CmdArgs.push_back("-lpthread");
11029   }
11030
11031   const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11032
11033   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11034 }
11035
11036 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
11037                                  const JobAction &JA, const InputInfo &Output,
11038                                  const InputInfoList &Inputs,
11039                                  const ArgList &Args,
11040                                  const char *LinkingOutput) {
11041   const toolchains::FreeBSD &ToolChain =
11042       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
11043   const Driver &D = ToolChain.getDriver();
11044   ArgStringList CmdArgs;
11045
11046   // Silence warning for "clang -g foo.o -o foo"
11047   Args.ClaimAllArgs(options::OPT_g_Group);
11048   // and "clang -emit-llvm foo.o -o foo"
11049   Args.ClaimAllArgs(options::OPT_emit_llvm);
11050   // and for "clang -w foo.o -o foo". Other warning options are already
11051   // handled somewhere else.
11052   Args.ClaimAllArgs(options::OPT_w);
11053
11054   if (!D.SysRoot.empty())
11055     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11056
11057   if (Args.hasArg(options::OPT_pie))
11058     CmdArgs.push_back("-pie");
11059
11060   if (Args.hasArg(options::OPT_static)) {
11061     CmdArgs.push_back("-Bstatic");
11062   } else {
11063     if (Args.hasArg(options::OPT_rdynamic))
11064       CmdArgs.push_back("-export-dynamic");
11065     CmdArgs.push_back("--eh-frame-hdr");
11066     if (Args.hasArg(options::OPT_shared)) {
11067       CmdArgs.push_back("-Bshareable");
11068     } else {
11069       CmdArgs.push_back("-dynamic-linker");
11070       CmdArgs.push_back("/libexec/ld-elf.so.1");
11071     }
11072     CmdArgs.push_back("--enable-new-dtags");
11073   }
11074
11075   if (Output.isFilename()) {
11076     CmdArgs.push_back("-o");
11077     CmdArgs.push_back(Output.getFilename());
11078   } else {
11079     assert(Output.isNothing() && "Invalid output.");
11080   }
11081
11082   AddPS4SanitizerArgs(ToolChain, CmdArgs);
11083
11084   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11085     const char *crt1 = nullptr;
11086     if (!Args.hasArg(options::OPT_shared)) {
11087       if (Args.hasArg(options::OPT_pg))
11088         crt1 = "gcrt1.o";
11089       else if (Args.hasArg(options::OPT_pie))
11090         crt1 = "Scrt1.o";
11091       else
11092         crt1 = "crt1.o";
11093     }
11094     if (crt1)
11095       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
11096
11097     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
11098
11099     const char *crtbegin = nullptr;
11100     if (Args.hasArg(options::OPT_static))
11101       crtbegin = "crtbeginT.o";
11102     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11103       crtbegin = "crtbeginS.o";
11104     else
11105       crtbegin = "crtbegin.o";
11106
11107     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
11108   }
11109
11110   Args.AddAllArgs(CmdArgs, options::OPT_L);
11111   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
11112   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11113   Args.AddAllArgs(CmdArgs, options::OPT_e);
11114   Args.AddAllArgs(CmdArgs, options::OPT_s);
11115   Args.AddAllArgs(CmdArgs, options::OPT_t);
11116   Args.AddAllArgs(CmdArgs, options::OPT_r);
11117
11118   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11119     CmdArgs.push_back("--no-demangle");
11120
11121   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11122
11123   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11124     // For PS4, we always want to pass libm, libstdc++ and libkernel
11125     // libraries for both C and C++ compilations.
11126     CmdArgs.push_back("-lkernel");
11127     if (D.CCCIsCXX()) {
11128       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
11129       if (Args.hasArg(options::OPT_pg))
11130         CmdArgs.push_back("-lm_p");
11131       else
11132         CmdArgs.push_back("-lm");
11133     }
11134     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
11135     // the default system libraries. Just mimic this for now.
11136     if (Args.hasArg(options::OPT_pg))
11137       CmdArgs.push_back("-lgcc_p");
11138     else
11139       CmdArgs.push_back("-lcompiler_rt");
11140     if (Args.hasArg(options::OPT_static)) {
11141       CmdArgs.push_back("-lstdc++");
11142     } else if (Args.hasArg(options::OPT_pg)) {
11143       CmdArgs.push_back("-lgcc_eh_p");
11144     } else {
11145       CmdArgs.push_back("--as-needed");
11146       CmdArgs.push_back("-lstdc++");
11147       CmdArgs.push_back("--no-as-needed");
11148     }
11149
11150     if (Args.hasArg(options::OPT_pthread)) {
11151       if (Args.hasArg(options::OPT_pg))
11152         CmdArgs.push_back("-lpthread_p");
11153       else
11154         CmdArgs.push_back("-lpthread");
11155     }
11156
11157     if (Args.hasArg(options::OPT_pg)) {
11158       if (Args.hasArg(options::OPT_shared))
11159         CmdArgs.push_back("-lc");
11160       else {
11161         if (Args.hasArg(options::OPT_static)) {
11162           CmdArgs.push_back("--start-group");
11163           CmdArgs.push_back("-lc_p");
11164           CmdArgs.push_back("-lpthread_p");
11165           CmdArgs.push_back("--end-group");
11166         } else {
11167           CmdArgs.push_back("-lc_p");
11168         }
11169       }
11170       CmdArgs.push_back("-lgcc_p");
11171     } else {
11172       if (Args.hasArg(options::OPT_static)) {
11173         CmdArgs.push_back("--start-group");
11174         CmdArgs.push_back("-lc");
11175         CmdArgs.push_back("-lpthread");
11176         CmdArgs.push_back("--end-group");
11177       } else {
11178         CmdArgs.push_back("-lc");
11179       }
11180       CmdArgs.push_back("-lcompiler_rt");
11181     }
11182
11183     if (Args.hasArg(options::OPT_static)) {
11184       CmdArgs.push_back("-lstdc++");
11185     } else if (Args.hasArg(options::OPT_pg)) {
11186       CmdArgs.push_back("-lgcc_eh_p");
11187     } else {
11188       CmdArgs.push_back("--as-needed");
11189       CmdArgs.push_back("-lstdc++");
11190       CmdArgs.push_back("--no-as-needed");
11191     }
11192   }
11193
11194   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11195     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11196       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
11197     else
11198       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
11199     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
11200   }
11201
11202   const char *Exec =
11203 #ifdef LLVM_ON_WIN32
11204       Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
11205 #else
11206       Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11207 #endif
11208
11209   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11210 }
11211
11212 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
11213                                 const InputInfo &Output,
11214                                 const InputInfoList &Inputs,
11215                                 const ArgList &Args,
11216                                 const char *LinkingOutput) const {
11217   const toolchains::FreeBSD &ToolChain =
11218       static_cast<const toolchains::FreeBSD &>(getToolChain());
11219   const Driver &D = ToolChain.getDriver();
11220   bool PS4Linker;
11221   StringRef LinkerOptName;
11222   if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
11223     LinkerOptName = A->getValue();
11224     if (LinkerOptName != "ps4" && LinkerOptName != "gold")
11225       D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
11226   }
11227
11228   if (LinkerOptName == "gold")
11229     PS4Linker = false;
11230   else if (LinkerOptName == "ps4")
11231     PS4Linker = true;
11232   else
11233     PS4Linker = !Args.hasArg(options::OPT_shared);
11234
11235   if (PS4Linker)
11236     ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11237   else
11238     ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11239 }
11240
11241 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11242                                     const InputInfo &Output,
11243                                     const InputInfoList &Inputs,
11244                                     const ArgList &Args,
11245                                     const char *LinkingOutput) const {
11246   const auto &TC =
11247       static_cast<const toolchains::CudaToolChain &>(getToolChain());
11248   assert(TC.getTriple().isNVPTX() && "Wrong platform");
11249
11250   // Obtain architecture from the action.
11251   CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
11252   assert(gpu_arch != CudaArch::UNKNOWN &&
11253          "Device action expected to have an architecture.");
11254
11255   // Check that our installation's ptxas supports gpu_arch.
11256   if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
11257     TC.cudaInstallation().CheckCudaVersionSupportsArch(gpu_arch);
11258   }
11259
11260   ArgStringList CmdArgs;
11261   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
11262   if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
11263                    options::OPT_no_cuda_noopt_device_debug, false)) {
11264     // ptxas does not accept -g option if optimization is enabled, so
11265     // we ignore the compiler's -O* options if we want debug info.
11266     CmdArgs.push_back("-g");
11267     CmdArgs.push_back("--dont-merge-basicblocks");
11268     CmdArgs.push_back("--return-at-end");
11269   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
11270     // Map the -O we received to -O{0,1,2,3}.
11271     //
11272     // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
11273     // default, so it may correspond more closely to the spirit of clang -O2.
11274
11275     // -O3 seems like the least-bad option when -Osomething is specified to
11276     // clang but it isn't handled below.
11277     StringRef OOpt = "3";
11278     if (A->getOption().matches(options::OPT_O4) ||
11279         A->getOption().matches(options::OPT_Ofast))
11280       OOpt = "3";
11281     else if (A->getOption().matches(options::OPT_O0))
11282       OOpt = "0";
11283     else if (A->getOption().matches(options::OPT_O)) {
11284       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
11285       OOpt = llvm::StringSwitch<const char *>(A->getValue())
11286                  .Case("1", "1")
11287                  .Case("2", "2")
11288                  .Case("3", "3")
11289                  .Case("s", "2")
11290                  .Case("z", "2")
11291                  .Default("2");
11292     }
11293     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
11294   } else {
11295     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
11296     // to no optimizations, but ptxas's default is -O3.
11297     CmdArgs.push_back("-O0");
11298   }
11299
11300   CmdArgs.push_back("--gpu-name");
11301   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
11302   CmdArgs.push_back("--output-file");
11303   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11304   for (const auto& II : Inputs)
11305     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
11306
11307   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
11308     CmdArgs.push_back(Args.MakeArgString(A));
11309
11310   const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
11311   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11312 }
11313
11314 // All inputs to this linker must be from CudaDeviceActions, as we need to look
11315 // at the Inputs' Actions in order to figure out which GPU architecture they
11316 // correspond to.
11317 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11318                                  const InputInfo &Output,
11319                                  const InputInfoList &Inputs,
11320                                  const ArgList &Args,
11321                                  const char *LinkingOutput) const {
11322   const auto &TC =
11323       static_cast<const toolchains::CudaToolChain &>(getToolChain());
11324   assert(TC.getTriple().isNVPTX() && "Wrong platform");
11325
11326   ArgStringList CmdArgs;
11327   CmdArgs.push_back("--cuda");
11328   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
11329   CmdArgs.push_back(Args.MakeArgString("--create"));
11330   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11331
11332   for (const auto& II : Inputs) {
11333     auto *A = II.getAction();
11334     assert(A->getInputs().size() == 1 &&
11335            "Device offload action is expected to have a single input");
11336     const char *gpu_arch_str = A->getOffloadingArch();
11337     assert(gpu_arch_str &&
11338            "Device action expected to have associated a GPU architecture!");
11339     CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
11340
11341     // We need to pass an Arch of the form "sm_XX" for cubin files and
11342     // "compute_XX" for ptx.
11343     const char *Arch =
11344         (II.getType() == types::TY_PP_Asm)
11345             ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
11346             : gpu_arch_str;
11347     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
11348                                          Arch + ",file=" + II.getFilename()));
11349   }
11350
11351   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
11352     CmdArgs.push_back(Args.MakeArgString(A));
11353
11354   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
11355   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11356 }