]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Update llvm, clang, lld and lldb to release_39 branch r287912.
[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     Features.push_back("-hard-float");
1606
1607   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1608   AddTargetFeature(Args, Features, options::OPT_faltivec,
1609                    options::OPT_fno_altivec, "altivec");
1610 }
1611
1612 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1613   ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1614   if (Arg *A =
1615           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1616                           options::OPT_mfloat_abi_EQ)) {
1617     if (A->getOption().matches(options::OPT_msoft_float))
1618       ABI = ppc::FloatABI::Soft;
1619     else if (A->getOption().matches(options::OPT_mhard_float))
1620       ABI = ppc::FloatABI::Hard;
1621     else {
1622       ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1623                 .Case("soft", ppc::FloatABI::Soft)
1624                 .Case("hard", ppc::FloatABI::Hard)
1625                 .Default(ppc::FloatABI::Invalid);
1626       if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1627         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1628         ABI = ppc::FloatABI::Hard;
1629       }
1630     }
1631   }
1632
1633   // If unspecified, choose the default based on the platform.
1634   if (ABI == ppc::FloatABI::Invalid) {
1635     ABI = ppc::FloatABI::Hard;
1636   }
1637
1638   return ABI;
1639 }
1640
1641 void Clang::AddPPCTargetArgs(const ArgList &Args,
1642                              ArgStringList &CmdArgs) const {
1643   // Select the ABI to use.
1644   const char *ABIName = nullptr;
1645   if (getToolChain().getTriple().isOSLinux())
1646     switch (getToolChain().getArch()) {
1647     case llvm::Triple::ppc64: {
1648       // When targeting a processor that supports QPX, or if QPX is
1649       // specifically enabled, default to using the ABI that supports QPX (so
1650       // long as it is not specifically disabled).
1651       bool HasQPX = false;
1652       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1653         HasQPX = A->getValue() == StringRef("a2q");
1654       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1655       if (HasQPX) {
1656         ABIName = "elfv1-qpx";
1657         break;
1658       }
1659
1660       ABIName = "elfv1";
1661       break;
1662     }
1663     case llvm::Triple::ppc64le:
1664       ABIName = "elfv2";
1665       break;
1666     default:
1667       break;
1668     }
1669
1670   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1671     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1672     // the option if given as we don't have backend support for any targets
1673     // that don't use the altivec abi.
1674     if (StringRef(A->getValue()) != "altivec")
1675       ABIName = A->getValue();
1676
1677   ppc::FloatABI FloatABI =
1678       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1679
1680   if (FloatABI == ppc::FloatABI::Soft) {
1681     // Floating point operations and argument passing are soft.
1682     CmdArgs.push_back("-msoft-float");
1683     CmdArgs.push_back("-mfloat-abi");
1684     CmdArgs.push_back("soft");
1685   } else {
1686     // Floating point operations and argument passing are hard.
1687     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1688     CmdArgs.push_back("-mfloat-abi");
1689     CmdArgs.push_back("hard");
1690   }
1691
1692   if (ABIName) {
1693     CmdArgs.push_back("-target-abi");
1694     CmdArgs.push_back(ABIName);
1695   }
1696 }
1697
1698 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1699   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1700   return A && (A->getValue() == StringRef(Value));
1701 }
1702
1703 /// Get the (LLVM) name of the R600 gpu we are targeting.
1704 static std::string getR600TargetGPU(const ArgList &Args) {
1705   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1706     const char *GPUName = A->getValue();
1707     return llvm::StringSwitch<const char *>(GPUName)
1708         .Cases("rv630", "rv635", "r600")
1709         .Cases("rv610", "rv620", "rs780", "rs880")
1710         .Case("rv740", "rv770")
1711         .Case("palm", "cedar")
1712         .Cases("sumo", "sumo2", "sumo")
1713         .Case("hemlock", "cypress")
1714         .Case("aruba", "cayman")
1715         .Default(GPUName);
1716   }
1717   return "";
1718 }
1719
1720 static std::string getLanaiTargetCPU(const ArgList &Args) {
1721   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1722     return A->getValue();
1723   }
1724   return "";
1725 }
1726
1727 sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
1728                                         const ArgList &Args) {
1729   sparc::FloatABI ABI = sparc::FloatABI::Invalid;
1730   if (Arg *A =
1731           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1732                           options::OPT_mfloat_abi_EQ)) {
1733     if (A->getOption().matches(options::OPT_msoft_float))
1734       ABI = sparc::FloatABI::Soft;
1735     else if (A->getOption().matches(options::OPT_mhard_float))
1736       ABI = sparc::FloatABI::Hard;
1737     else {
1738       ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
1739                 .Case("soft", sparc::FloatABI::Soft)
1740                 .Case("hard", sparc::FloatABI::Hard)
1741                 .Default(sparc::FloatABI::Invalid);
1742       if (ABI == sparc::FloatABI::Invalid &&
1743           !StringRef(A->getValue()).empty()) {
1744         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1745         ABI = sparc::FloatABI::Hard;
1746       }
1747     }
1748   }
1749
1750   // If unspecified, choose the default based on the platform.
1751   // Only the hard-float ABI on Sparc is standardized, and it is the
1752   // default. GCC also supports a nonstandard soft-float ABI mode, also
1753   // implemented in LLVM. However as this is not standard we set the default
1754   // to be hard-float.
1755   if (ABI == sparc::FloatABI::Invalid) {
1756     ABI = sparc::FloatABI::Hard;
1757   }
1758
1759   return ABI;
1760 }
1761
1762 static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
1763                                  std::vector<const char *> &Features) {
1764   sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
1765   if (FloatABI == sparc::FloatABI::Soft)
1766     Features.push_back("+soft-float");
1767 }
1768
1769 void Clang::AddSparcTargetArgs(const ArgList &Args,
1770                                ArgStringList &CmdArgs) const {
1771   sparc::FloatABI FloatABI =
1772       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1773
1774   if (FloatABI == sparc::FloatABI::Soft) {
1775     // Floating point operations and argument passing are soft.
1776     CmdArgs.push_back("-msoft-float");
1777     CmdArgs.push_back("-mfloat-abi");
1778     CmdArgs.push_back("soft");
1779   } else {
1780     // Floating point operations and argument passing are hard.
1781     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1782     CmdArgs.push_back("-mfloat-abi");
1783     CmdArgs.push_back("hard");
1784   }
1785 }
1786
1787 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1788                                  ArgStringList &CmdArgs) const {
1789   if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1790     CmdArgs.push_back("-mbackchain");
1791 }
1792
1793 static const char *getSystemZTargetCPU(const ArgList &Args) {
1794   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1795     return A->getValue();
1796   return "z10";
1797 }
1798
1799 static void getSystemZTargetFeatures(const ArgList &Args,
1800                                      std::vector<const char *> &Features) {
1801   // -m(no-)htm overrides use of the transactional-execution facility.
1802   if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1803     if (A->getOption().matches(options::OPT_mhtm))
1804       Features.push_back("+transactional-execution");
1805     else
1806       Features.push_back("-transactional-execution");
1807   }
1808   // -m(no-)vx overrides use of the vector facility.
1809   if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1810     if (A->getOption().matches(options::OPT_mvx))
1811       Features.push_back("+vector");
1812     else
1813       Features.push_back("-vector");
1814   }
1815 }
1816
1817 static const char *getX86TargetCPU(const ArgList &Args,
1818                                    const llvm::Triple &Triple) {
1819   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1820     if (StringRef(A->getValue()) != "native") {
1821       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1822         return "core-avx2";
1823
1824       return A->getValue();
1825     }
1826
1827     // FIXME: Reject attempts to use -march=native unless the target matches
1828     // the host.
1829     //
1830     // FIXME: We should also incorporate the detected target features for use
1831     // with -native.
1832     std::string CPU = llvm::sys::getHostCPUName();
1833     if (!CPU.empty() && CPU != "generic")
1834       return Args.MakeArgString(CPU);
1835   }
1836
1837   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1838     // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1839     StringRef Arch = A->getValue();
1840     const char *CPU;
1841     if (Triple.getArch() == llvm::Triple::x86) {
1842       CPU = llvm::StringSwitch<const char *>(Arch)
1843                 .Case("IA32", "i386")
1844                 .Case("SSE", "pentium3")
1845                 .Case("SSE2", "pentium4")
1846                 .Case("AVX", "sandybridge")
1847                 .Case("AVX2", "haswell")
1848                 .Default(nullptr);
1849     } else {
1850       CPU = llvm::StringSwitch<const char *>(Arch)
1851                 .Case("AVX", "sandybridge")
1852                 .Case("AVX2", "haswell")
1853                 .Default(nullptr);
1854     }
1855     if (CPU)
1856       return CPU;
1857   }
1858
1859   // Select the default CPU if none was given (or detection failed).
1860
1861   if (Triple.getArch() != llvm::Triple::x86_64 &&
1862       Triple.getArch() != llvm::Triple::x86)
1863     return nullptr; // This routine is only handling x86 targets.
1864
1865   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1866
1867   // FIXME: Need target hooks.
1868   if (Triple.isOSDarwin()) {
1869     if (Triple.getArchName() == "x86_64h")
1870       return "core-avx2";
1871     return Is64Bit ? "core2" : "yonah";
1872   }
1873
1874   // Set up default CPU name for PS4 compilers.
1875   if (Triple.isPS4CPU())
1876     return "btver2";
1877
1878   // On Android use targets compatible with gcc
1879   if (Triple.isAndroid())
1880     return Is64Bit ? "x86-64" : "i686";
1881
1882   // Everything else goes to x86-64 in 64-bit mode.
1883   if (Is64Bit)
1884     return "x86-64";
1885
1886   switch (Triple.getOS()) {
1887   case llvm::Triple::FreeBSD:
1888   case llvm::Triple::NetBSD:
1889   case llvm::Triple::OpenBSD:
1890     return "i486";
1891   case llvm::Triple::Haiku:
1892     return "i586";
1893   case llvm::Triple::Bitrig:
1894     return "i686";
1895   default:
1896     // Fallback to p4.
1897     return "pentium4";
1898   }
1899 }
1900
1901 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1902 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1903   // If we have -mcpu=, use that.
1904   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1905     StringRef CPU = A->getValue();
1906
1907 #ifdef __wasm__
1908     // Handle "native" by examining the host. "native" isn't meaningful when
1909     // cross compiling, so only support this when the host is also WebAssembly.
1910     if (CPU == "native")
1911       return llvm::sys::getHostCPUName();
1912 #endif
1913
1914     return CPU;
1915   }
1916
1917   return "generic";
1918 }
1919
1920 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1921                               bool FromAs = false) {
1922   switch (T.getArch()) {
1923   default:
1924     return "";
1925
1926   case llvm::Triple::aarch64:
1927   case llvm::Triple::aarch64_be:
1928     return getAArch64TargetCPU(Args);
1929
1930   case llvm::Triple::arm:
1931   case llvm::Triple::armeb:
1932   case llvm::Triple::thumb:
1933   case llvm::Triple::thumbeb: {
1934     StringRef MArch, MCPU;
1935     getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1936     return arm::getARMTargetCPU(MCPU, MArch, T);
1937   }
1938   case llvm::Triple::mips:
1939   case llvm::Triple::mipsel:
1940   case llvm::Triple::mips64:
1941   case llvm::Triple::mips64el: {
1942     StringRef CPUName;
1943     StringRef ABIName;
1944     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1945     return CPUName;
1946   }
1947
1948   case llvm::Triple::nvptx:
1949   case llvm::Triple::nvptx64:
1950     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1951       return A->getValue();
1952     return "";
1953
1954   case llvm::Triple::ppc:
1955   case llvm::Triple::ppc64:
1956   case llvm::Triple::ppc64le: {
1957     std::string TargetCPUName = getPPCTargetCPU(Args);
1958     // LLVM may default to generating code for the native CPU,
1959     // but, like gcc, we default to a more generic option for
1960     // each architecture. (except on Darwin)
1961     if (TargetCPUName.empty() && !T.isOSDarwin()) {
1962       if (T.getArch() == llvm::Triple::ppc64)
1963         TargetCPUName = "ppc64";
1964       else if (T.getArch() == llvm::Triple::ppc64le)
1965         TargetCPUName = "ppc64le";
1966       else
1967         TargetCPUName = "ppc";
1968     }
1969     return TargetCPUName;
1970   }
1971
1972   case llvm::Triple::sparc:
1973   case llvm::Triple::sparcel:
1974   case llvm::Triple::sparcv9:
1975     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1976       return A->getValue();
1977     return "";
1978
1979   case llvm::Triple::x86:
1980   case llvm::Triple::x86_64:
1981     return getX86TargetCPU(Args, T);
1982
1983   case llvm::Triple::hexagon:
1984     return "hexagon" +
1985            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1986
1987   case llvm::Triple::lanai:
1988     return getLanaiTargetCPU(Args);
1989
1990   case llvm::Triple::systemz:
1991     return getSystemZTargetCPU(Args);
1992
1993   case llvm::Triple::r600:
1994   case llvm::Triple::amdgcn:
1995     return getR600TargetGPU(Args);
1996
1997   case llvm::Triple::wasm32:
1998   case llvm::Triple::wasm64:
1999     return getWebAssemblyTargetCPU(Args);
2000   }
2001 }
2002
2003 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
2004                           ArgStringList &CmdArgs, bool IsThinLTO) {
2005   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
2006   // as gold requires -plugin to come before any -plugin-opt that -Wl might
2007   // forward.
2008   CmdArgs.push_back("-plugin");
2009   std::string Plugin =
2010       ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
2011   CmdArgs.push_back(Args.MakeArgString(Plugin));
2012
2013   // Try to pass driver level flags relevant to LTO code generation down to
2014   // the plugin.
2015
2016   // Handle flags for selecting CPU variants.
2017   std::string CPU = getCPUName(Args, ToolChain.getTriple());
2018   if (!CPU.empty())
2019     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
2020
2021   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2022     StringRef OOpt;
2023     if (A->getOption().matches(options::OPT_O4) ||
2024         A->getOption().matches(options::OPT_Ofast))
2025       OOpt = "3";
2026     else if (A->getOption().matches(options::OPT_O))
2027       OOpt = A->getValue();
2028     else if (A->getOption().matches(options::OPT_O0))
2029       OOpt = "0";
2030     if (!OOpt.empty())
2031       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
2032   }
2033
2034   if (IsThinLTO)
2035     CmdArgs.push_back("-plugin-opt=thinlto");
2036
2037   // If an explicit debugger tuning argument appeared, pass it along.
2038   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2039                                options::OPT_ggdbN_Group)) {
2040     if (A->getOption().matches(options::OPT_glldb))
2041       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
2042     else if (A->getOption().matches(options::OPT_gsce))
2043       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
2044     else
2045       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
2046   }
2047 }
2048
2049 /// This is a helper function for validating the optional refinement step
2050 /// parameter in reciprocal argument strings. Return false if there is an error
2051 /// parsing the refinement step. Otherwise, return true and set the Position
2052 /// of the refinement step in the input string.
2053 static bool getRefinementStep(StringRef In, const Driver &D,
2054                               const Arg &A, size_t &Position) {
2055   const char RefinementStepToken = ':';
2056   Position = In.find(RefinementStepToken);
2057   if (Position != StringRef::npos) {
2058     StringRef Option = A.getOption().getName();
2059     StringRef RefStep = In.substr(Position + 1);
2060     // Allow exactly one numeric character for the additional refinement
2061     // step parameter. This is reasonable for all currently-supported
2062     // operations and architectures because we would expect that a larger value
2063     // of refinement steps would cause the estimate "optimization" to
2064     // under-perform the native operation. Also, if the estimate does not
2065     // converge quickly, it probably will not ever converge, so further
2066     // refinement steps will not produce a better answer.
2067     if (RefStep.size() != 1) {
2068       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2069       return false;
2070     }
2071     char RefStepChar = RefStep[0];
2072     if (RefStepChar < '0' || RefStepChar > '9') {
2073       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2074       return false;
2075     }
2076   }
2077   return true;
2078 }
2079
2080 /// The -mrecip flag requires processing of many optional parameters.
2081 static void ParseMRecip(const Driver &D, const ArgList &Args,
2082                         ArgStringList &OutStrings) {
2083   StringRef DisabledPrefixIn = "!";
2084   StringRef DisabledPrefixOut = "!";
2085   StringRef EnabledPrefixOut = "";
2086   StringRef Out = "-mrecip=";
2087
2088   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
2089   if (!A)
2090     return;
2091
2092   unsigned NumOptions = A->getNumValues();
2093   if (NumOptions == 0) {
2094     // No option is the same as "all".
2095     OutStrings.push_back(Args.MakeArgString(Out + "all"));
2096     return;
2097   }
2098
2099   // Pass through "all", "none", or "default" with an optional refinement step.
2100   if (NumOptions == 1) {
2101     StringRef Val = A->getValue(0);
2102     size_t RefStepLoc;
2103     if (!getRefinementStep(Val, D, *A, RefStepLoc))
2104       return;
2105     StringRef ValBase = Val.slice(0, RefStepLoc);
2106     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2107       OutStrings.push_back(Args.MakeArgString(Out + Val));
2108       return;
2109     }
2110   }
2111
2112   // Each reciprocal type may be enabled or disabled individually.
2113   // Check each input value for validity, concatenate them all back together,
2114   // and pass through.
2115
2116   llvm::StringMap<bool> OptionStrings;
2117   OptionStrings.insert(std::make_pair("divd", false));
2118   OptionStrings.insert(std::make_pair("divf", false));
2119   OptionStrings.insert(std::make_pair("vec-divd", false));
2120   OptionStrings.insert(std::make_pair("vec-divf", false));
2121   OptionStrings.insert(std::make_pair("sqrtd", false));
2122   OptionStrings.insert(std::make_pair("sqrtf", false));
2123   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2124   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
2125
2126   for (unsigned i = 0; i != NumOptions; ++i) {
2127     StringRef Val = A->getValue(i);
2128
2129     bool IsDisabled = Val.startswith(DisabledPrefixIn);
2130     // Ignore the disablement token for string matching.
2131     if (IsDisabled)
2132       Val = Val.substr(1);
2133
2134     size_t RefStep;
2135     if (!getRefinementStep(Val, D, *A, RefStep))
2136       return;
2137
2138     StringRef ValBase = Val.slice(0, RefStep);
2139     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2140     if (OptionIter == OptionStrings.end()) {
2141       // Try again specifying float suffix.
2142       OptionIter = OptionStrings.find(ValBase.str() + 'f');
2143       if (OptionIter == OptionStrings.end()) {
2144         // The input name did not match any known option string.
2145         D.Diag(diag::err_drv_unknown_argument) << Val;
2146         return;
2147       }
2148       // The option was specified without a float or double suffix.
2149       // Make sure that the double entry was not already specified.
2150       // The float entry will be checked below.
2151       if (OptionStrings[ValBase.str() + 'd']) {
2152         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2153         return;
2154       }
2155     }
2156
2157     if (OptionIter->second == true) {
2158       // Duplicate option specified.
2159       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2160       return;
2161     }
2162
2163     // Mark the matched option as found. Do not allow duplicate specifiers.
2164     OptionIter->second = true;
2165
2166     // If the precision was not specified, also mark the double entry as found.
2167     if (ValBase.back() != 'f' && ValBase.back() != 'd')
2168       OptionStrings[ValBase.str() + 'd'] = true;
2169
2170     // Build the output string.
2171     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2172     Out = Args.MakeArgString(Out + Prefix + Val);
2173     if (i != NumOptions - 1)
2174       Out = Args.MakeArgString(Out + ",");
2175   }
2176
2177   OutStrings.push_back(Args.MakeArgString(Out));
2178 }
2179
2180 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
2181                                  const ArgList &Args,
2182                                  std::vector<const char *> &Features) {
2183   // If -march=native, autodetect the feature list.
2184   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
2185     if (StringRef(A->getValue()) == "native") {
2186       llvm::StringMap<bool> HostFeatures;
2187       if (llvm::sys::getHostCPUFeatures(HostFeatures))
2188         for (auto &F : HostFeatures)
2189           Features.push_back(
2190               Args.MakeArgString((F.second ? "+" : "-") + F.first()));
2191     }
2192   }
2193
2194   if (Triple.getArchName() == "x86_64h") {
2195     // x86_64h implies quite a few of the more modern subtarget features
2196     // for Haswell class CPUs, but not all of them. Opt-out of a few.
2197     Features.push_back("-rdrnd");
2198     Features.push_back("-aes");
2199     Features.push_back("-pclmul");
2200     Features.push_back("-rtm");
2201     Features.push_back("-hle");
2202     Features.push_back("-fsgsbase");
2203   }
2204
2205   const llvm::Triple::ArchType ArchType = Triple.getArch();
2206   // Add features to be compatible with gcc for Android.
2207   if (Triple.isAndroid()) {
2208     if (ArchType == llvm::Triple::x86_64) {
2209       Features.push_back("+sse4.2");
2210       Features.push_back("+popcnt");
2211     } else
2212       Features.push_back("+ssse3");
2213   }
2214
2215   // Set features according to the -arch flag on MSVC.
2216   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
2217     StringRef Arch = A->getValue();
2218     bool ArchUsed = false;
2219     // First, look for flags that are shared in x86 and x86-64.
2220     if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
2221       if (Arch == "AVX" || Arch == "AVX2") {
2222         ArchUsed = true;
2223         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2224       }
2225     }
2226     // Then, look for x86-specific flags.
2227     if (ArchType == llvm::Triple::x86) {
2228       if (Arch == "IA32") {
2229         ArchUsed = true;
2230       } else if (Arch == "SSE" || Arch == "SSE2") {
2231         ArchUsed = true;
2232         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2233       }
2234     }
2235     if (!ArchUsed)
2236       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2237   }
2238
2239   // Now add any that the user explicitly requested on the command line,
2240   // which may override the defaults.
2241   handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2242 }
2243
2244 void Clang::AddX86TargetArgs(const ArgList &Args,
2245                              ArgStringList &CmdArgs) const {
2246   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2247       Args.hasArg(options::OPT_mkernel) ||
2248       Args.hasArg(options::OPT_fapple_kext))
2249     CmdArgs.push_back("-disable-red-zone");
2250
2251   // Default to avoid implicit floating-point for kernel/kext code, but allow
2252   // that to be overridden with -mno-soft-float.
2253   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2254                           Args.hasArg(options::OPT_fapple_kext));
2255   if (Arg *A = Args.getLastArg(
2256           options::OPT_msoft_float, options::OPT_mno_soft_float,
2257           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2258     const Option &O = A->getOption();
2259     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2260                        O.matches(options::OPT_msoft_float));
2261   }
2262   if (NoImplicitFloat)
2263     CmdArgs.push_back("-no-implicit-float");
2264
2265   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2266     StringRef Value = A->getValue();
2267     if (Value == "intel" || Value == "att") {
2268       CmdArgs.push_back("-mllvm");
2269       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2270     } else {
2271       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2272           << A->getOption().getName() << Value;
2273     }
2274   }
2275
2276   // Set flags to support MCU ABI.
2277   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2278     CmdArgs.push_back("-mfloat-abi");
2279     CmdArgs.push_back("soft");
2280     CmdArgs.push_back("-mstack-alignment=4");
2281   }
2282 }
2283
2284 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2285                                  ArgStringList &CmdArgs) const {
2286   CmdArgs.push_back("-mqdsp6-compat");
2287   CmdArgs.push_back("-Wreturn-type");
2288
2289   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2290     std::string N = llvm::utostr(G.getValue());
2291     std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2292     CmdArgs.push_back("-mllvm");
2293     CmdArgs.push_back(Args.MakeArgString(Opt));
2294   }
2295
2296   if (!Args.hasArg(options::OPT_fno_short_enums))
2297     CmdArgs.push_back("-fshort-enums");
2298   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2299     CmdArgs.push_back("-mllvm");
2300     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2301   }
2302   CmdArgs.push_back("-mllvm");
2303   CmdArgs.push_back("-machine-sink-split=0");
2304 }
2305
2306 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2307                                ArgStringList &CmdArgs) const {
2308   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2309     StringRef CPUName = A->getValue();
2310
2311     CmdArgs.push_back("-target-cpu");
2312     CmdArgs.push_back(Args.MakeArgString(CPUName));
2313   }
2314   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2315     StringRef Value = A->getValue();
2316     // Only support mregparm=4 to support old usage. Report error for all other
2317     // cases.
2318     int Mregparm;
2319     if (Value.getAsInteger(10, Mregparm)) {
2320       if (Mregparm != 4) {
2321         getToolChain().getDriver().Diag(
2322             diag::err_drv_unsupported_option_argument)
2323             << A->getOption().getName() << Value;
2324       }
2325     }
2326   }
2327 }
2328
2329 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2330                                      ArgStringList &CmdArgs) const {
2331   // Default to "hidden" visibility.
2332   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2333                    options::OPT_fvisibility_ms_compat)) {
2334     CmdArgs.push_back("-fvisibility");
2335     CmdArgs.push_back("hidden");
2336   }
2337 }
2338
2339 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2340 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2341                                   std::vector<const char *> &Features) {
2342   SmallVector<StringRef, 8> Split;
2343   text.split(Split, StringRef("+"), -1, false);
2344
2345   for (StringRef Feature : Split) {
2346     const char *result = llvm::StringSwitch<const char *>(Feature)
2347                              .Case("fp", "+fp-armv8")
2348                              .Case("simd", "+neon")
2349                              .Case("crc", "+crc")
2350                              .Case("crypto", "+crypto")
2351                              .Case("fp16", "+fullfp16")
2352                              .Case("profile", "+spe")
2353                              .Case("ras", "+ras")
2354                              .Case("nofp", "-fp-armv8")
2355                              .Case("nosimd", "-neon")
2356                              .Case("nocrc", "-crc")
2357                              .Case("nocrypto", "-crypto")
2358                              .Case("nofp16", "-fullfp16")
2359                              .Case("noprofile", "-spe")
2360                              .Case("noras", "-ras")
2361                              .Default(nullptr);
2362     if (result)
2363       Features.push_back(result);
2364     else if (Feature == "neon" || Feature == "noneon")
2365       D.Diag(diag::err_drv_no_neon_modifier);
2366     else
2367       return false;
2368   }
2369   return true;
2370 }
2371
2372 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2373 // decode CPU and feature.
2374 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2375                               std::vector<const char *> &Features) {
2376   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2377   CPU = Split.first;
2378   if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
2379       CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
2380       CPU == "kryo"       || CPU == "cortex-a73" || CPU == "vulcan") {
2381     Features.push_back("+neon");
2382     Features.push_back("+crc");
2383     Features.push_back("+crypto");
2384   } else if (CPU == "cyclone") {
2385     Features.push_back("+neon");
2386     Features.push_back("+crypto");
2387   } else if (CPU == "generic") {
2388     Features.push_back("+neon");
2389   } else {
2390     return false;
2391   }
2392
2393   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2394     return false;
2395
2396   return true;
2397 }
2398
2399 static bool
2400 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2401                                 const ArgList &Args,
2402                                 std::vector<const char *> &Features) {
2403   std::string MarchLowerCase = March.lower();
2404   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2405
2406   if (Split.first == "armv8-a" || Split.first == "armv8a") {
2407     // ok, no additional features.
2408   } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2409     Features.push_back("+v8.1a");
2410   } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2411     Features.push_back("+v8.2a");
2412   } else {
2413     return false;
2414   }
2415
2416   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2417     return false;
2418
2419   return true;
2420 }
2421
2422 static bool
2423 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2424                                const ArgList &Args,
2425                                std::vector<const char *> &Features) {
2426   StringRef CPU;
2427   std::string McpuLowerCase = Mcpu.lower();
2428   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2429     return false;
2430
2431   return true;
2432 }
2433
2434 static bool
2435 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2436                                      const ArgList &Args,
2437                                      std::vector<const char *> &Features) {
2438   std::string MtuneLowerCase = Mtune.lower();
2439   // Handle CPU name is 'native'.
2440   if (MtuneLowerCase == "native")
2441     MtuneLowerCase = llvm::sys::getHostCPUName();
2442   if (MtuneLowerCase == "cyclone") {
2443     Features.push_back("+zcm");
2444     Features.push_back("+zcz");
2445   }
2446   return true;
2447 }
2448
2449 static bool
2450 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2451                                     const ArgList &Args,
2452                                     std::vector<const char *> &Features) {
2453   StringRef CPU;
2454   std::vector<const char *> DecodedFeature;
2455   std::string McpuLowerCase = Mcpu.lower();
2456   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2457     return false;
2458
2459   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2460 }
2461
2462 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2463                                      std::vector<const char *> &Features) {
2464   Arg *A;
2465   bool success = true;
2466   // Enable NEON by default.
2467   Features.push_back("+neon");
2468   if ((A = Args.getLastArg(options::OPT_march_EQ)))
2469     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2470   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2471     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2472   else if (Args.hasArg(options::OPT_arch))
2473     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2474                                              Features);
2475
2476   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2477     success =
2478         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2479   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2480     success =
2481         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2482   else if (Args.hasArg(options::OPT_arch))
2483     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2484                                                   Args, Features);
2485
2486   if (!success)
2487     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2488
2489   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2490     Features.push_back("-fp-armv8");
2491     Features.push_back("-crypto");
2492     Features.push_back("-neon");
2493   }
2494
2495   // En/disable crc
2496   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2497     if (A->getOption().matches(options::OPT_mcrc))
2498       Features.push_back("+crc");
2499     else
2500       Features.push_back("-crc");
2501   }
2502
2503   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2504                                options::OPT_munaligned_access))
2505     if (A->getOption().matches(options::OPT_mno_unaligned_access))
2506       Features.push_back("+strict-align");
2507
2508   if (Args.hasArg(options::OPT_ffixed_x18))
2509     Features.push_back("+reserve-x18");
2510 }
2511
2512 static void getHexagonTargetFeatures(const ArgList &Args,
2513                                      std::vector<const char *> &Features) {
2514   bool HasHVX = false, HasHVXD = false;
2515
2516   // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2517   // doing dependent option handling here rather than in initFeatureMap or a
2518   // similar handler.
2519   for (auto &A : Args) {
2520     auto &Opt = A->getOption();
2521     if (Opt.matches(options::OPT_mhexagon_hvx))
2522       HasHVX = true;
2523     else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2524       HasHVXD = HasHVX = false;
2525     else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2526       HasHVXD = HasHVX = true;
2527     else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2528       HasHVXD = false;
2529     else
2530       continue;
2531     A->claim();
2532   }
2533
2534   Features.push_back(HasHVX  ? "+hvx" : "-hvx");
2535   Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2536 }
2537
2538 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2539                                          std::vector<const char *> &Features) {
2540   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2541 }
2542
2543 static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
2544                                     std::vector<const char *> &Features) {
2545   if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
2546     StringRef value = dAbi->getValue();
2547     if (value == "1.0") {
2548       Features.push_back("+amdgpu-debugger-insert-nops");
2549       Features.push_back("+amdgpu-debugger-reserve-regs");
2550       Features.push_back("+amdgpu-debugger-emit-prologue");
2551     } else {
2552       D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
2553     }
2554   }
2555
2556   handleTargetFeaturesGroup(
2557     Args, Features, options::OPT_m_amdgpu_Features_Group);
2558 }
2559
2560 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2561                               const ArgList &Args, ArgStringList &CmdArgs,
2562                               bool ForAS) {
2563   const Driver &D = TC.getDriver();
2564   std::vector<const char *> Features;
2565   switch (Triple.getArch()) {
2566   default:
2567     break;
2568   case llvm::Triple::mips:
2569   case llvm::Triple::mipsel:
2570   case llvm::Triple::mips64:
2571   case llvm::Triple::mips64el:
2572     getMIPSTargetFeatures(D, Triple, Args, Features);
2573     break;
2574
2575   case llvm::Triple::arm:
2576   case llvm::Triple::armeb:
2577   case llvm::Triple::thumb:
2578   case llvm::Triple::thumbeb:
2579     getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2580     break;
2581
2582   case llvm::Triple::ppc:
2583   case llvm::Triple::ppc64:
2584   case llvm::Triple::ppc64le:
2585     getPPCTargetFeatures(D, Triple, Args, Features);
2586     break;
2587   case llvm::Triple::systemz:
2588     getSystemZTargetFeatures(Args, Features);
2589     break;
2590   case llvm::Triple::aarch64:
2591   case llvm::Triple::aarch64_be:
2592     getAArch64TargetFeatures(D, Args, Features);
2593     break;
2594   case llvm::Triple::x86:
2595   case llvm::Triple::x86_64:
2596     getX86TargetFeatures(D, Triple, Args, Features);
2597     break;
2598   case llvm::Triple::hexagon:
2599     getHexagonTargetFeatures(Args, Features);
2600     break;
2601   case llvm::Triple::wasm32:
2602   case llvm::Triple::wasm64:
2603     getWebAssemblyTargetFeatures(Args, Features);
2604     break; 
2605   case llvm::Triple::sparc:
2606   case llvm::Triple::sparcel:
2607   case llvm::Triple::sparcv9:
2608     getSparcTargetFeatures(D, Args, Features);
2609     break;
2610   case llvm::Triple::r600:
2611   case llvm::Triple::amdgcn:
2612     getAMDGPUTargetFeatures(D, Args, Features);
2613     break;
2614   }
2615
2616   // Find the last of each feature.
2617   llvm::StringMap<unsigned> LastOpt;
2618   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2619     const char *Name = Features[I];
2620     assert(Name[0] == '-' || Name[0] == '+');
2621     LastOpt[Name + 1] = I;
2622   }
2623
2624   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2625     // If this feature was overridden, ignore it.
2626     const char *Name = Features[I];
2627     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2628     assert(LastI != LastOpt.end());
2629     unsigned Last = LastI->second;
2630     if (Last != I)
2631       continue;
2632
2633     CmdArgs.push_back("-target-feature");
2634     CmdArgs.push_back(Name);
2635   }
2636 }
2637
2638 static bool
2639 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2640                                           const llvm::Triple &Triple) {
2641   // We use the zero-cost exception tables for Objective-C if the non-fragile
2642   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2643   // later.
2644   if (runtime.isNonFragile())
2645     return true;
2646
2647   if (!Triple.isMacOSX())
2648     return false;
2649
2650   return (!Triple.isMacOSXVersionLT(10, 5) &&
2651           (Triple.getArch() == llvm::Triple::x86_64 ||
2652            Triple.getArch() == llvm::Triple::arm));
2653 }
2654
2655 /// Adds exception related arguments to the driver command arguments. There's a
2656 /// master flag, -fexceptions and also language specific flags to enable/disable
2657 /// C++ and Objective-C exceptions. This makes it possible to for example
2658 /// disable C++ exceptions but enable Objective-C exceptions.
2659 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2660                              const ToolChain &TC, bool KernelOrKext,
2661                              const ObjCRuntime &objcRuntime,
2662                              ArgStringList &CmdArgs) {
2663   const Driver &D = TC.getDriver();
2664   const llvm::Triple &Triple = TC.getTriple();
2665
2666   if (KernelOrKext) {
2667     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2668     // arguments now to avoid warnings about unused arguments.
2669     Args.ClaimAllArgs(options::OPT_fexceptions);
2670     Args.ClaimAllArgs(options::OPT_fno_exceptions);
2671     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2672     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2673     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2674     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2675     return;
2676   }
2677
2678   // See if the user explicitly enabled exceptions.
2679   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2680                          false);
2681
2682   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2683   // is not necessarily sensible, but follows GCC.
2684   if (types::isObjC(InputType) &&
2685       Args.hasFlag(options::OPT_fobjc_exceptions,
2686                    options::OPT_fno_objc_exceptions, true)) {
2687     CmdArgs.push_back("-fobjc-exceptions");
2688
2689     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2690   }
2691
2692   if (types::isCXX(InputType)) {
2693     // Disable C++ EH by default on XCore and PS4.
2694     bool CXXExceptionsEnabled =
2695         Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2696     Arg *ExceptionArg = Args.getLastArg(
2697         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2698         options::OPT_fexceptions, options::OPT_fno_exceptions);
2699     if (ExceptionArg)
2700       CXXExceptionsEnabled =
2701           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2702           ExceptionArg->getOption().matches(options::OPT_fexceptions);
2703
2704     if (CXXExceptionsEnabled) {
2705       if (Triple.isPS4CPU()) {
2706         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2707         assert(ExceptionArg &&
2708                "On the PS4 exceptions should only be enabled if passing "
2709                "an argument");
2710         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2711           const Arg *RTTIArg = TC.getRTTIArg();
2712           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2713           D.Diag(diag::err_drv_argument_not_allowed_with)
2714               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2715         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2716           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2717       } else
2718         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2719
2720       CmdArgs.push_back("-fcxx-exceptions");
2721
2722       EH = true;
2723     }
2724   }
2725
2726   if (EH)
2727     CmdArgs.push_back("-fexceptions");
2728 }
2729
2730 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2731   bool Default = true;
2732   if (TC.getTriple().isOSDarwin()) {
2733     // The native darwin assembler doesn't support the linker_option directives,
2734     // so we disable them if we think the .s file will be passed to it.
2735     Default = TC.useIntegratedAs();
2736   }
2737   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2738                        Default);
2739 }
2740
2741 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2742                                         const ToolChain &TC) {
2743   bool UseDwarfDirectory =
2744       Args.hasFlag(options::OPT_fdwarf_directory_asm,
2745                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2746   return !UseDwarfDirectory;
2747 }
2748
2749 /// \brief Check whether the given input tree contains any compilation actions.
2750 static bool ContainsCompileAction(const Action *A) {
2751   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2752     return true;
2753
2754   for (const auto &AI : A->inputs())
2755     if (ContainsCompileAction(AI))
2756       return true;
2757
2758   return false;
2759 }
2760
2761 /// \brief Check if -relax-all should be passed to the internal assembler.
2762 /// This is done by default when compiling non-assembler source with -O0.
2763 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2764   bool RelaxDefault = true;
2765
2766   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2767     RelaxDefault = A->getOption().matches(options::OPT_O0);
2768
2769   if (RelaxDefault) {
2770     RelaxDefault = false;
2771     for (const auto &Act : C.getActions()) {
2772       if (ContainsCompileAction(Act)) {
2773         RelaxDefault = true;
2774         break;
2775       }
2776     }
2777   }
2778
2779   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2780                       RelaxDefault);
2781 }
2782
2783 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2784 // to the corresponding DebugInfoKind.
2785 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2786   assert(A.getOption().matches(options::OPT_gN_Group) &&
2787          "Not a -g option that specifies a debug-info level");
2788   if (A.getOption().matches(options::OPT_g0) ||
2789       A.getOption().matches(options::OPT_ggdb0))
2790     return codegenoptions::NoDebugInfo;
2791   if (A.getOption().matches(options::OPT_gline_tables_only) ||
2792       A.getOption().matches(options::OPT_ggdb1))
2793     return codegenoptions::DebugLineTablesOnly;
2794   return codegenoptions::LimitedDebugInfo;
2795 }
2796
2797 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2798 // on mismatch. The StringRef input (rather than an Arg) allows
2799 // for use by the "-Xassembler" option parser.
2800 static unsigned DwarfVersionNum(StringRef ArgValue) {
2801   return llvm::StringSwitch<unsigned>(ArgValue)
2802       .Case("-gdwarf-2", 2)
2803       .Case("-gdwarf-3", 3)
2804       .Case("-gdwarf-4", 4)
2805       .Case("-gdwarf-5", 5)
2806       .Default(0);
2807 }
2808
2809 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2810                                     codegenoptions::DebugInfoKind DebugInfoKind,
2811                                     unsigned DwarfVersion,
2812                                     llvm::DebuggerKind DebuggerTuning) {
2813   switch (DebugInfoKind) {
2814   case codegenoptions::DebugLineTablesOnly:
2815     CmdArgs.push_back("-debug-info-kind=line-tables-only");
2816     break;
2817   case codegenoptions::LimitedDebugInfo:
2818     CmdArgs.push_back("-debug-info-kind=limited");
2819     break;
2820   case codegenoptions::FullDebugInfo:
2821     CmdArgs.push_back("-debug-info-kind=standalone");
2822     break;
2823   default:
2824     break;
2825   }
2826   if (DwarfVersion > 0)
2827     CmdArgs.push_back(
2828         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2829   switch (DebuggerTuning) {
2830   case llvm::DebuggerKind::GDB:
2831     CmdArgs.push_back("-debugger-tuning=gdb");
2832     break;
2833   case llvm::DebuggerKind::LLDB:
2834     CmdArgs.push_back("-debugger-tuning=lldb");
2835     break;
2836   case llvm::DebuggerKind::SCE:
2837     CmdArgs.push_back("-debugger-tuning=sce");
2838     break;
2839   default:
2840     break;
2841   }
2842 }
2843
2844 static void CollectArgsForIntegratedAssembler(Compilation &C,
2845                                               const ArgList &Args,
2846                                               ArgStringList &CmdArgs,
2847                                               const Driver &D) {
2848   if (UseRelaxAll(C, Args))
2849     CmdArgs.push_back("-mrelax-all");
2850
2851   // Only default to -mincremental-linker-compatible if we think we are
2852   // targeting the MSVC linker.
2853   bool DefaultIncrementalLinkerCompatible =
2854       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2855   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2856                    options::OPT_mno_incremental_linker_compatible,
2857                    DefaultIncrementalLinkerCompatible))
2858     CmdArgs.push_back("-mincremental-linker-compatible");
2859
2860   // When passing -I arguments to the assembler we sometimes need to
2861   // unconditionally take the next argument.  For example, when parsing
2862   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2863   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2864   // arg after parsing the '-I' arg.
2865   bool TakeNextArg = false;
2866
2867   // When using an integrated assembler, translate -Wa, and -Xassembler
2868   // options.
2869   bool CompressDebugSections = false;
2870
2871   bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
2872   const char *MipsTargetFeature = nullptr;
2873   for (const Arg *A :
2874        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2875     A->claim();
2876
2877     for (StringRef Value : A->getValues()) {
2878       if (TakeNextArg) {
2879         CmdArgs.push_back(Value.data());
2880         TakeNextArg = false;
2881         continue;
2882       }
2883
2884       switch (C.getDefaultToolChain().getArch()) {
2885       default:
2886         break;
2887       case llvm::Triple::mips:
2888       case llvm::Triple::mipsel:
2889       case llvm::Triple::mips64:
2890       case llvm::Triple::mips64el:
2891         if (Value == "--trap") {
2892           CmdArgs.push_back("-target-feature");
2893           CmdArgs.push_back("+use-tcc-in-div");
2894           continue;
2895         }
2896         if (Value == "--break") {
2897           CmdArgs.push_back("-target-feature");
2898           CmdArgs.push_back("-use-tcc-in-div");
2899           continue;
2900         }
2901         if (Value.startswith("-msoft-float")) {
2902           CmdArgs.push_back("-target-feature");
2903           CmdArgs.push_back("+soft-float");
2904           continue;
2905         }
2906         if (Value.startswith("-mhard-float")) {
2907           CmdArgs.push_back("-target-feature");
2908           CmdArgs.push_back("-soft-float");
2909           continue;
2910         }
2911
2912         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2913                                 .Case("-mips1", "+mips1")
2914                                 .Case("-mips2", "+mips2")
2915                                 .Case("-mips3", "+mips3")
2916                                 .Case("-mips4", "+mips4")
2917                                 .Case("-mips5", "+mips5")
2918                                 .Case("-mips32", "+mips32")
2919                                 .Case("-mips32r2", "+mips32r2")
2920                                 .Case("-mips32r3", "+mips32r3")
2921                                 .Case("-mips32r5", "+mips32r5")
2922                                 .Case("-mips32r6", "+mips32r6")
2923                                 .Case("-mips64", "+mips64")
2924                                 .Case("-mips64r2", "+mips64r2")
2925                                 .Case("-mips64r3", "+mips64r3")
2926                                 .Case("-mips64r5", "+mips64r5")
2927                                 .Case("-mips64r6", "+mips64r6")
2928                                 .Default(nullptr);
2929         if (MipsTargetFeature)
2930           continue;
2931       }
2932
2933       if (Value == "-force_cpusubtype_ALL") {
2934         // Do nothing, this is the default and we don't support anything else.
2935       } else if (Value == "-L") {
2936         CmdArgs.push_back("-msave-temp-labels");
2937       } else if (Value == "--fatal-warnings") {
2938         CmdArgs.push_back("-massembler-fatal-warnings");
2939       } else if (Value == "--noexecstack") {
2940         CmdArgs.push_back("-mnoexecstack");
2941       } else if (Value == "-compress-debug-sections" ||
2942                  Value == "--compress-debug-sections") {
2943         CompressDebugSections = true;
2944       } else if (Value == "-nocompress-debug-sections" ||
2945                  Value == "--nocompress-debug-sections") {
2946         CompressDebugSections = false;
2947       } else if (Value == "-mrelax-relocations=yes" ||
2948                  Value == "--mrelax-relocations=yes") {
2949         UseRelaxRelocations = true;
2950       } else if (Value == "-mrelax-relocations=no" ||
2951                  Value == "--mrelax-relocations=no") {
2952         UseRelaxRelocations = false;
2953       } else if (Value.startswith("-I")) {
2954         CmdArgs.push_back(Value.data());
2955         // We need to consume the next argument if the current arg is a plain
2956         // -I. The next arg will be the include directory.
2957         if (Value == "-I")
2958           TakeNextArg = true;
2959       } else if (Value.startswith("-gdwarf-")) {
2960         // "-gdwarf-N" options are not cc1as options.
2961         unsigned DwarfVersion = DwarfVersionNum(Value);
2962         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2963           CmdArgs.push_back(Value.data());
2964         } else {
2965           RenderDebugEnablingArgs(Args, CmdArgs,
2966                                   codegenoptions::LimitedDebugInfo,
2967                                   DwarfVersion, llvm::DebuggerKind::Default);
2968         }
2969       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2970                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2971         // Do nothing, we'll validate it later.
2972       } else {
2973         D.Diag(diag::err_drv_unsupported_option_argument)
2974             << A->getOption().getName() << Value;
2975       }
2976     }
2977   }
2978   if (CompressDebugSections) {
2979     if (llvm::zlib::isAvailable())
2980       CmdArgs.push_back("-compress-debug-sections");
2981     else
2982       D.Diag(diag::warn_debug_compression_unavailable);
2983   }
2984   if (UseRelaxRelocations)
2985     CmdArgs.push_back("--mrelax-relocations");
2986   if (MipsTargetFeature != nullptr) {
2987     CmdArgs.push_back("-target-feature");
2988     CmdArgs.push_back(MipsTargetFeature);
2989   }
2990 }
2991
2992 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2993 // FIXME: Make sure we can also emit shared objects if they're requested
2994 // and available, check for possible errors, etc.
2995 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2996                        ArgStringList &CmdArgs) {
2997   CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2998 }
2999
3000 namespace {
3001 enum OpenMPRuntimeKind {
3002   /// An unknown OpenMP runtime. We can't generate effective OpenMP code
3003   /// without knowing what runtime to target.
3004   OMPRT_Unknown,
3005
3006   /// The LLVM OpenMP runtime. When completed and integrated, this will become
3007   /// the default for Clang.
3008   OMPRT_OMP,
3009
3010   /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
3011   /// this runtime but can swallow the pragmas, and find and link against the
3012   /// runtime library itself.
3013   OMPRT_GOMP,
3014
3015   /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
3016   /// OpenMP runtime. We support this mode for users with existing dependencies
3017   /// on this runtime library name.
3018   OMPRT_IOMP5
3019 };
3020 }
3021
3022 /// Compute the desired OpenMP runtime from the flag provided.
3023 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
3024                                           const ArgList &Args) {
3025   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
3026
3027   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
3028   if (A)
3029     RuntimeName = A->getValue();
3030
3031   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
3032                 .Case("libomp", OMPRT_OMP)
3033                 .Case("libgomp", OMPRT_GOMP)
3034                 .Case("libiomp5", OMPRT_IOMP5)
3035                 .Default(OMPRT_Unknown);
3036
3037   if (RT == OMPRT_Unknown) {
3038     if (A)
3039       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
3040           << A->getOption().getName() << A->getValue();
3041     else
3042       // FIXME: We could use a nicer diagnostic here.
3043       TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
3044   }
3045
3046   return RT;
3047 }
3048
3049 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
3050                               const ArgList &Args) {
3051   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3052                     options::OPT_fno_openmp, false))
3053     return;
3054
3055   switch (getOpenMPRuntime(TC, Args)) {
3056   case OMPRT_OMP:
3057     CmdArgs.push_back("-lomp");
3058     break;
3059   case OMPRT_GOMP:
3060     CmdArgs.push_back("-lgomp");
3061     break;
3062   case OMPRT_IOMP5:
3063     CmdArgs.push_back("-liomp5");
3064     break;
3065   case OMPRT_Unknown:
3066     // Already diagnosed.
3067     break;
3068   }
3069 }
3070
3071 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
3072                                 ArgStringList &CmdArgs, StringRef Sanitizer,
3073                                 bool IsShared, bool IsWhole) {
3074   // Wrap any static runtimes that must be forced into executable in
3075   // whole-archive.
3076   if (IsWhole) CmdArgs.push_back("-whole-archive");
3077   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
3078   if (IsWhole) CmdArgs.push_back("-no-whole-archive");
3079 }
3080
3081 // Tries to use a file with the list of dynamic symbols that need to be exported
3082 // from the runtime library. Returns true if the file was found.
3083 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
3084                                     ArgStringList &CmdArgs,
3085                                     StringRef Sanitizer) {
3086   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
3087   if (llvm::sys::fs::exists(SanRT + ".syms")) {
3088     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
3089     return true;
3090   }
3091   return false;
3092 }
3093
3094 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
3095                                      ArgStringList &CmdArgs) {
3096   // Force linking against the system libraries sanitizers depends on
3097   // (see PR15823 why this is necessary).
3098   CmdArgs.push_back("--no-as-needed");
3099   CmdArgs.push_back("-lpthread");
3100   CmdArgs.push_back("-lrt");
3101   CmdArgs.push_back("-lm");
3102   // There's no libdl on FreeBSD.
3103   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3104     CmdArgs.push_back("-ldl");
3105 }
3106
3107 static void
3108 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3109                          SmallVectorImpl<StringRef> &SharedRuntimes,
3110                          SmallVectorImpl<StringRef> &StaticRuntimes,
3111                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
3112                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
3113                          SmallVectorImpl<StringRef> &RequiredSymbols) {
3114   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
3115   // Collect shared runtimes.
3116   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
3117     SharedRuntimes.push_back("asan");
3118   }
3119   // The stats_client library is also statically linked into DSOs.
3120   if (SanArgs.needsStatsRt())
3121     StaticRuntimes.push_back("stats_client");
3122
3123   // Collect static runtimes.
3124   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
3125     // Don't link static runtimes into DSOs or if compiling for Android.
3126     return;
3127   }
3128   if (SanArgs.needsAsanRt()) {
3129     if (SanArgs.needsSharedAsanRt()) {
3130       HelperStaticRuntimes.push_back("asan-preinit");
3131     } else {
3132       StaticRuntimes.push_back("asan");
3133       if (SanArgs.linkCXXRuntimes())
3134         StaticRuntimes.push_back("asan_cxx");
3135     }
3136   }
3137   if (SanArgs.needsDfsanRt())
3138     StaticRuntimes.push_back("dfsan");
3139   if (SanArgs.needsLsanRt())
3140     StaticRuntimes.push_back("lsan");
3141   if (SanArgs.needsMsanRt()) {
3142     StaticRuntimes.push_back("msan");
3143     if (SanArgs.linkCXXRuntimes())
3144       StaticRuntimes.push_back("msan_cxx");
3145   }
3146   if (SanArgs.needsTsanRt()) {
3147     StaticRuntimes.push_back("tsan");
3148     if (SanArgs.linkCXXRuntimes())
3149       StaticRuntimes.push_back("tsan_cxx");
3150   }
3151   if (SanArgs.needsUbsanRt()) {
3152     StaticRuntimes.push_back("ubsan_standalone");
3153     if (SanArgs.linkCXXRuntimes())
3154       StaticRuntimes.push_back("ubsan_standalone_cxx");
3155   }
3156   if (SanArgs.needsSafeStackRt())
3157     StaticRuntimes.push_back("safestack");
3158   if (SanArgs.needsCfiRt())
3159     StaticRuntimes.push_back("cfi");
3160   if (SanArgs.needsCfiDiagRt()) {
3161     StaticRuntimes.push_back("cfi_diag");
3162     if (SanArgs.linkCXXRuntimes())
3163       StaticRuntimes.push_back("ubsan_standalone_cxx");
3164   }
3165   if (SanArgs.needsStatsRt()) {
3166     NonWholeStaticRuntimes.push_back("stats");
3167     RequiredSymbols.push_back("__sanitizer_stats_register");
3168   }
3169   if (SanArgs.needsEsanRt())
3170     StaticRuntimes.push_back("esan");
3171 }
3172
3173 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
3174 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
3175 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3176                                  ArgStringList &CmdArgs) {
3177   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
3178       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
3179   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
3180                            NonWholeStaticRuntimes, HelperStaticRuntimes,
3181                            RequiredSymbols);
3182   for (auto RT : SharedRuntimes)
3183     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
3184   for (auto RT : HelperStaticRuntimes)
3185     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3186   bool AddExportDynamic = false;
3187   for (auto RT : StaticRuntimes) {
3188     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3189     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3190   }
3191   for (auto RT : NonWholeStaticRuntimes) {
3192     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
3193     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3194   }
3195   for (auto S : RequiredSymbols) {
3196     CmdArgs.push_back("-u");
3197     CmdArgs.push_back(Args.MakeArgString(S));
3198   }
3199   // If there is a static runtime with no dynamic list, force all the symbols
3200   // to be dynamic to be sure we export sanitizer interface functions.
3201   if (AddExportDynamic)
3202     CmdArgs.push_back("-export-dynamic");
3203   return !StaticRuntimes.empty();
3204 }
3205
3206 static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
3207                            ArgStringList &CmdArgs) {
3208   if (Args.hasFlag(options::OPT_fxray_instrument,
3209                    options::OPT_fnoxray_instrument, false)) {
3210     CmdArgs.push_back("-whole-archive");
3211     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
3212     CmdArgs.push_back("-no-whole-archive");
3213     return true;
3214   }
3215   return false;
3216 }
3217
3218 static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
3219                                 ArgStringList &CmdArgs) {
3220   CmdArgs.push_back("--no-as-needed");
3221   CmdArgs.push_back("-lpthread");
3222   CmdArgs.push_back("-lrt");
3223   CmdArgs.push_back("-lm");
3224   CmdArgs.push_back("-latomic");
3225   if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3226     CmdArgs.push_back("-lc++");
3227   else
3228     CmdArgs.push_back("-lstdc++");
3229   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3230     CmdArgs.push_back("-ldl");
3231 }
3232
3233 static bool areOptimizationsEnabled(const ArgList &Args) {
3234   // Find the last -O arg and see if it is non-zero.
3235   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
3236     return !A->getOption().matches(options::OPT_O0);
3237   // Defaults to -O0.
3238   return false;
3239 }
3240
3241 static bool shouldUseFramePointerForTarget(const ArgList &Args,
3242                                            const llvm::Triple &Triple) {
3243   switch (Triple.getArch()) {
3244   case llvm::Triple::xcore:
3245   case llvm::Triple::wasm32:
3246   case llvm::Triple::wasm64:
3247     // XCore never wants frame pointers, regardless of OS.
3248     // WebAssembly never wants frame pointers.
3249     return false;
3250   default:
3251     break;
3252   }
3253
3254   if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
3255     switch (Triple.getArch()) {
3256     // Don't use a frame pointer on linux if optimizing for certain targets.
3257     case llvm::Triple::mips64:
3258     case llvm::Triple::mips64el:
3259     case llvm::Triple::mips:
3260     case llvm::Triple::mipsel:
3261     case llvm::Triple::systemz:
3262     case llvm::Triple::x86:
3263     case llvm::Triple::x86_64:
3264       return !areOptimizationsEnabled(Args);
3265     default:
3266       return true;
3267     }
3268   }
3269
3270   if (Triple.isOSWindows()) {
3271     switch (Triple.getArch()) {
3272     case llvm::Triple::x86:
3273       return !areOptimizationsEnabled(Args);
3274     case llvm::Triple::x86_64:
3275       return Triple.isOSBinFormatMachO();
3276     case llvm::Triple::arm:
3277     case llvm::Triple::thumb:
3278       // Windows on ARM builds with FPO disabled to aid fast stack walking
3279       return true;
3280     default:
3281       // All other supported Windows ISAs use xdata unwind information, so frame
3282       // pointers are not generally useful.
3283       return false;
3284     }
3285   }
3286
3287   return true;
3288 }
3289
3290 static bool shouldUseFramePointer(const ArgList &Args,
3291                                   const llvm::Triple &Triple) {
3292   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
3293                                options::OPT_fomit_frame_pointer))
3294     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
3295   if (Args.hasArg(options::OPT_pg))
3296     return true;
3297
3298   return shouldUseFramePointerForTarget(Args, Triple);
3299 }
3300
3301 static bool shouldUseLeafFramePointer(const ArgList &Args,
3302                                       const llvm::Triple &Triple) {
3303   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
3304                                options::OPT_momit_leaf_frame_pointer))
3305     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
3306   if (Args.hasArg(options::OPT_pg))
3307     return true;
3308
3309   if (Triple.isPS4CPU())
3310     return false;
3311
3312   return shouldUseFramePointerForTarget(Args, Triple);
3313 }
3314
3315 /// Add a CC1 option to specify the debug compilation directory.
3316 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
3317   SmallString<128> cwd;
3318   if (!llvm::sys::fs::current_path(cwd)) {
3319     CmdArgs.push_back("-fdebug-compilation-dir");
3320     CmdArgs.push_back(Args.MakeArgString(cwd));
3321   }
3322 }
3323
3324 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
3325   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3326   if (FinalOutput && Args.hasArg(options::OPT_c)) {
3327     SmallString<128> T(FinalOutput->getValue());
3328     llvm::sys::path::replace_extension(T, "dwo");
3329     return Args.MakeArgString(T);
3330   } else {
3331     // Use the compilation dir.
3332     SmallString<128> T(
3333         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
3334     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
3335     llvm::sys::path::replace_extension(F, "dwo");
3336     T += F;
3337     return Args.MakeArgString(F);
3338   }
3339 }
3340
3341 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
3342                            const JobAction &JA, const ArgList &Args,
3343                            const InputInfo &Output, const char *OutFile) {
3344   ArgStringList ExtractArgs;
3345   ExtractArgs.push_back("--extract-dwo");
3346
3347   ArgStringList StripArgs;
3348   StripArgs.push_back("--strip-dwo");
3349
3350   // Grabbing the output of the earlier compile step.
3351   StripArgs.push_back(Output.getFilename());
3352   ExtractArgs.push_back(Output.getFilename());
3353   ExtractArgs.push_back(OutFile);
3354
3355   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
3356   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
3357
3358   // First extract the dwo sections.
3359   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
3360
3361   // Then remove them from the original .o file.
3362   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
3363 }
3364
3365 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
3366 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
3367 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3368   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3369     if (A->getOption().matches(options::OPT_O4) ||
3370         A->getOption().matches(options::OPT_Ofast))
3371       return true;
3372
3373     if (A->getOption().matches(options::OPT_O0))
3374       return false;
3375
3376     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3377
3378     // Vectorize -Os.
3379     StringRef S(A->getValue());
3380     if (S == "s")
3381       return true;
3382
3383     // Don't vectorize -Oz, unless it's the slp vectorizer.
3384     if (S == "z")
3385       return isSlpVec;
3386
3387     unsigned OptLevel = 0;
3388     if (S.getAsInteger(10, OptLevel))
3389       return false;
3390
3391     return OptLevel > 1;
3392   }
3393
3394   return false;
3395 }
3396
3397 /// Add -x lang to \p CmdArgs for \p Input.
3398 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3399                              ArgStringList &CmdArgs) {
3400   // When using -verify-pch, we don't want to provide the type
3401   // 'precompiled-header' if it was inferred from the file extension
3402   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3403     return;
3404
3405   CmdArgs.push_back("-x");
3406   if (Args.hasArg(options::OPT_rewrite_objc))
3407     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3408   else
3409     CmdArgs.push_back(types::getTypeName(Input.getType()));
3410 }
3411
3412 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3413   if (Version < 100)
3414     return VersionTuple(Version);
3415
3416   if (Version < 10000)
3417     return VersionTuple(Version / 100, Version % 100);
3418
3419   unsigned Build = 0, Factor = 1;
3420   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3421     Build = Build + (Version % 10) * Factor;
3422   return VersionTuple(Version / 100, Version % 100, Build);
3423 }
3424
3425 // Claim options we don't want to warn if they are unused. We do this for
3426 // options that build systems might add but are unused when assembling or only
3427 // running the preprocessor for example.
3428 static void claimNoWarnArgs(const ArgList &Args) {
3429   // Don't warn about unused -f(no-)?lto.  This can happen when we're
3430   // preprocessing, precompiling or assembling.
3431   Args.ClaimAllArgs(options::OPT_flto_EQ);
3432   Args.ClaimAllArgs(options::OPT_flto);
3433   Args.ClaimAllArgs(options::OPT_fno_lto);
3434 }
3435
3436 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3437 #ifdef LLVM_ON_UNIX
3438   const char *Username = getenv("LOGNAME");
3439 #else
3440   const char *Username = getenv("USERNAME");
3441 #endif
3442   if (Username) {
3443     // Validate that LoginName can be used in a path, and get its length.
3444     size_t Len = 0;
3445     for (const char *P = Username; *P; ++P, ++Len) {
3446       if (!isAlphanumeric(*P) && *P != '_') {
3447         Username = nullptr;
3448         break;
3449       }
3450     }
3451
3452     if (Username && Len > 0) {
3453       Result.append(Username, Username + Len);
3454       return;
3455     }
3456   }
3457
3458 // Fallback to user id.
3459 #ifdef LLVM_ON_UNIX
3460   std::string UID = llvm::utostr(getuid());
3461 #else
3462   // FIXME: Windows seems to have an 'SID' that might work.
3463   std::string UID = "9999";
3464 #endif
3465   Result.append(UID.begin(), UID.end());
3466 }
3467
3468 VersionTuple visualstudio::getMSVCVersion(const Driver *D, const ToolChain &TC,
3469                                           const llvm::Triple &Triple,
3470                                           const llvm::opt::ArgList &Args,
3471                                           bool IsWindowsMSVC) {
3472   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3473                    IsWindowsMSVC) ||
3474       Args.hasArg(options::OPT_fmsc_version) ||
3475       Args.hasArg(options::OPT_fms_compatibility_version)) {
3476     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3477     const Arg *MSCompatibilityVersion =
3478         Args.getLastArg(options::OPT_fms_compatibility_version);
3479
3480     if (MSCVersion && MSCompatibilityVersion) {
3481       if (D)
3482         D->Diag(diag::err_drv_argument_not_allowed_with)
3483             << MSCVersion->getAsString(Args)
3484             << MSCompatibilityVersion->getAsString(Args);
3485       return VersionTuple();
3486     }
3487
3488     if (MSCompatibilityVersion) {
3489       VersionTuple MSVT;
3490       if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3491         D->Diag(diag::err_drv_invalid_value)
3492             << MSCompatibilityVersion->getAsString(Args)
3493             << MSCompatibilityVersion->getValue();
3494       return MSVT;
3495     }
3496
3497     if (MSCVersion) {
3498       unsigned Version = 0;
3499       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3500         D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3501                                              << MSCVersion->getValue();
3502       return getMSCompatibilityVersion(Version);
3503     }
3504
3505     unsigned Major, Minor, Micro;
3506     Triple.getEnvironmentVersion(Major, Minor, Micro);
3507     if (Major || Minor || Micro)
3508       return VersionTuple(Major, Minor, Micro);
3509
3510     if (IsWindowsMSVC) {
3511       VersionTuple MSVT = TC.getMSVCVersionFromExe();
3512       if (!MSVT.empty())
3513         return MSVT;
3514
3515       // FIXME: Consider bumping this to 19 (MSVC2015) soon.
3516       return VersionTuple(18);
3517     }
3518   }
3519   return VersionTuple();
3520 }
3521
3522 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3523                                    const InputInfo &Output, const ArgList &Args,
3524                                    ArgStringList &CmdArgs) {
3525
3526   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
3527                                          options::OPT_fprofile_generate_EQ,
3528                                          options::OPT_fno_profile_generate);
3529   if (PGOGenerateArg &&
3530       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
3531     PGOGenerateArg = nullptr;
3532
3533   auto *ProfileGenerateArg = Args.getLastArg(
3534       options::OPT_fprofile_instr_generate,
3535       options::OPT_fprofile_instr_generate_EQ,
3536       options::OPT_fno_profile_instr_generate);
3537   if (ProfileGenerateArg &&
3538       ProfileGenerateArg->getOption().matches(
3539           options::OPT_fno_profile_instr_generate))
3540     ProfileGenerateArg = nullptr;
3541
3542   if (PGOGenerateArg && ProfileGenerateArg)
3543     D.Diag(diag::err_drv_argument_not_allowed_with)
3544         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
3545
3546   auto *ProfileUseArg = Args.getLastArg(
3547       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3548       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3549       options::OPT_fno_profile_instr_use);
3550   if (ProfileUseArg &&
3551       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3552     ProfileUseArg = nullptr;
3553
3554   if (PGOGenerateArg && ProfileUseArg)
3555     D.Diag(diag::err_drv_argument_not_allowed_with)
3556         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
3557
3558   if (ProfileGenerateArg && ProfileUseArg)
3559     D.Diag(diag::err_drv_argument_not_allowed_with)
3560         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3561
3562   if (ProfileGenerateArg) {
3563     if (ProfileGenerateArg->getOption().matches(
3564             options::OPT_fprofile_instr_generate_EQ))
3565       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
3566                                            ProfileGenerateArg->getValue()));
3567     // The default is to use Clang Instrumentation.
3568     CmdArgs.push_back("-fprofile-instrument=clang");
3569   }
3570
3571   if (PGOGenerateArg) {
3572     CmdArgs.push_back("-fprofile-instrument=llvm");
3573     if (PGOGenerateArg->getOption().matches(
3574             options::OPT_fprofile_generate_EQ)) {
3575       SmallString<128> Path(PGOGenerateArg->getValue());
3576       llvm::sys::path::append(Path, "default.profraw");
3577       CmdArgs.push_back(
3578           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
3579     }
3580   }
3581
3582   if (ProfileUseArg) {
3583     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3584       CmdArgs.push_back(Args.MakeArgString(
3585           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
3586     else if ((ProfileUseArg->getOption().matches(
3587                   options::OPT_fprofile_use_EQ) ||
3588               ProfileUseArg->getOption().matches(
3589                   options::OPT_fprofile_instr_use))) {
3590       SmallString<128> Path(
3591           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3592       if (Path.empty() || llvm::sys::fs::is_directory(Path))
3593         llvm::sys::path::append(Path, "default.profdata");
3594       CmdArgs.push_back(
3595           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
3596     }
3597   }
3598
3599   if (Args.hasArg(options::OPT_ftest_coverage) ||
3600       Args.hasArg(options::OPT_coverage))
3601     CmdArgs.push_back("-femit-coverage-notes");
3602   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3603                    false) ||
3604       Args.hasArg(options::OPT_coverage))
3605     CmdArgs.push_back("-femit-coverage-data");
3606
3607   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3608                    options::OPT_fno_coverage_mapping, false) &&
3609       !ProfileGenerateArg)
3610     D.Diag(diag::err_drv_argument_only_allowed_with)
3611         << "-fcoverage-mapping"
3612         << "-fprofile-instr-generate";
3613
3614   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3615                    options::OPT_fno_coverage_mapping, false))
3616     CmdArgs.push_back("-fcoverage-mapping");
3617
3618   if (C.getArgs().hasArg(options::OPT_c) ||
3619       C.getArgs().hasArg(options::OPT_S)) {
3620     if (Output.isFilename()) {
3621       CmdArgs.push_back("-coverage-file");
3622       SmallString<128> CoverageFilename;
3623       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3624         CoverageFilename = FinalOutput->getValue();
3625       } else {
3626         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3627       }
3628       if (llvm::sys::path::is_relative(CoverageFilename)) {
3629         SmallString<128> Pwd;
3630         if (!llvm::sys::fs::current_path(Pwd)) {
3631           llvm::sys::path::append(Pwd, CoverageFilename);
3632           CoverageFilename.swap(Pwd);
3633         }
3634       }
3635       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3636     }
3637   }
3638 }
3639
3640 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3641                                 ArgStringList &CmdArgs) {
3642   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3643                     false) ||
3644        Args.hasFlag(options::OPT_fprofile_generate,
3645                     options::OPT_fno_profile_instr_generate, false) ||
3646        Args.hasFlag(options::OPT_fprofile_generate_EQ,
3647                     options::OPT_fno_profile_instr_generate, false) ||
3648        Args.hasFlag(options::OPT_fprofile_instr_generate,
3649                     options::OPT_fno_profile_instr_generate, false) ||
3650        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3651                     options::OPT_fno_profile_instr_generate, false) ||
3652        Args.hasArg(options::OPT_fcreate_profile) ||
3653        Args.hasArg(options::OPT_coverage)))
3654     CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3655 }
3656
3657 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
3658 /// smooshes them together with platform defaults, to decide whether
3659 /// this compile should be using PIC mode or not. Returns a tuple of
3660 /// (RelocationModel, PICLevel, IsPIE).
3661 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3662 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3663              const ArgList &Args) {
3664   // FIXME: why does this code...and so much everywhere else, use both
3665   // ToolChain.getTriple() and Triple?
3666   bool PIE = ToolChain.isPIEDefault();
3667   bool PIC = PIE || ToolChain.isPICDefault();
3668   // The Darwin/MachO default to use PIC does not apply when using -static.
3669   if (ToolChain.getTriple().isOSBinFormatMachO() &&
3670       Args.hasArg(options::OPT_static))
3671     PIE = PIC = false;
3672   bool IsPICLevelTwo = PIC;
3673
3674   bool KernelOrKext =
3675       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3676
3677   // Android-specific defaults for PIC/PIE
3678   if (ToolChain.getTriple().isAndroid()) {
3679     switch (ToolChain.getArch()) {
3680     case llvm::Triple::arm:
3681     case llvm::Triple::armeb:
3682     case llvm::Triple::thumb:
3683     case llvm::Triple::thumbeb:
3684     case llvm::Triple::aarch64:
3685     case llvm::Triple::mips:
3686     case llvm::Triple::mipsel:
3687     case llvm::Triple::mips64:
3688     case llvm::Triple::mips64el:
3689       PIC = true; // "-fpic"
3690       break;
3691
3692     case llvm::Triple::x86:
3693     case llvm::Triple::x86_64:
3694       PIC = true; // "-fPIC"
3695       IsPICLevelTwo = true;
3696       break;
3697
3698     default:
3699       break;
3700     }
3701   }
3702
3703   // OpenBSD-specific defaults for PIE
3704   if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3705     switch (ToolChain.getArch()) {
3706     case llvm::Triple::mips64:
3707     case llvm::Triple::mips64el:
3708     case llvm::Triple::sparcel:
3709     case llvm::Triple::x86:
3710     case llvm::Triple::x86_64:
3711       IsPICLevelTwo = false; // "-fpie"
3712       break;
3713
3714     case llvm::Triple::ppc:
3715     case llvm::Triple::sparc:
3716     case llvm::Triple::sparcv9:
3717       IsPICLevelTwo = true; // "-fPIE"
3718       break;
3719
3720     default:
3721       break;
3722     }
3723   }
3724
3725   // The last argument relating to either PIC or PIE wins, and no
3726   // other argument is used. If the last argument is any flavor of the
3727   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3728   // option implicitly enables PIC at the same level.
3729   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3730                                     options::OPT_fpic, options::OPT_fno_pic,
3731                                     options::OPT_fPIE, options::OPT_fno_PIE,
3732                                     options::OPT_fpie, options::OPT_fno_pie);
3733   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3734   // is forced, then neither PIC nor PIE flags will have no effect.
3735   if (!ToolChain.isPICDefaultForced()) {
3736     if (LastPICArg) {
3737       Option O = LastPICArg->getOption();
3738       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3739           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3740         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3741         PIC =
3742             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3743         IsPICLevelTwo =
3744             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3745       } else {
3746         PIE = PIC = false;
3747         if (Triple.isPS4CPU()) {
3748           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3749           StringRef Model = ModelArg ? ModelArg->getValue() : "";
3750           if (Model != "kernel") {
3751             PIC = true;
3752             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3753                 << LastPICArg->getSpelling();
3754           }
3755         }
3756       }
3757     }
3758   }
3759
3760   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3761   // PIC level would've been set to level 1, force it back to level 2 PIC
3762   // instead.
3763   if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3764     IsPICLevelTwo |= ToolChain.isPICDefault();
3765
3766   // This kernel flags are a trump-card: they will disable PIC/PIE
3767   // generation, independent of the argument order.
3768   if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3769                        !Triple.isWatchOS()))
3770     PIC = PIE = false;
3771
3772   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3773     // This is a very special mode. It trumps the other modes, almost no one
3774     // uses it, and it isn't even valid on any OS but Darwin.
3775     if (!ToolChain.getTriple().isOSDarwin())
3776       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3777           << A->getSpelling() << ToolChain.getTriple().str();
3778
3779     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3780
3781     // Only a forced PIC mode can cause the actual compile to have PIC defines
3782     // etc., no flags are sufficient. This behavior was selected to closely
3783     // match that of llvm-gcc and Apple GCC before that.
3784     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3785
3786     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3787   }
3788
3789   if (PIC)
3790     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3791
3792   return std::make_tuple(llvm::Reloc::Static, 0, false);
3793 }
3794
3795 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3796   switch (Model) {
3797   case llvm::Reloc::Static:
3798     return "static";
3799   case llvm::Reloc::PIC_:
3800     return "pic";
3801   case llvm::Reloc::DynamicNoPIC:
3802     return "dynamic-no-pic";
3803   }
3804   llvm_unreachable("Unknown Reloc::Model kind");
3805 }
3806
3807 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3808                              ArgStringList &CmdArgs) {
3809   llvm::Reloc::Model RelocationModel;
3810   unsigned PICLevel;
3811   bool IsPIE;
3812   std::tie(RelocationModel, PICLevel, IsPIE) =
3813       ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3814
3815   if (RelocationModel != llvm::Reloc::Static)
3816     CmdArgs.push_back("-KPIC");
3817 }
3818
3819 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3820                          const InputInfo &Output, const InputInfoList &Inputs,
3821                          const ArgList &Args, const char *LinkingOutput) const {
3822   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3823   const llvm::Triple Triple(TripleStr);
3824
3825   bool KernelOrKext =
3826       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3827   const Driver &D = getToolChain().getDriver();
3828   ArgStringList CmdArgs;
3829
3830   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3831   bool IsWindowsCygnus =
3832       getToolChain().getTriple().isWindowsCygwinEnvironment();
3833   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3834   bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3835   bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
3836
3837   // Check number of inputs for sanity. We need at least one input.
3838   assert(Inputs.size() >= 1 && "Must have at least one input.");
3839   const InputInfo &Input = Inputs[0];
3840   // CUDA compilation may have multiple inputs (source file + results of
3841   // device-side compilations). All other jobs are expected to have exactly one
3842   // input.
3843   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3844   assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3845
3846   // C++ is not supported for IAMCU.
3847   if (IsIAMCU && types::isCXX(Input.getType()))
3848     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3849
3850   // Invoke ourselves in -cc1 mode.
3851   //
3852   // FIXME: Implement custom jobs for internal actions.
3853   CmdArgs.push_back("-cc1");
3854
3855   // Add the "effective" target triple.
3856   CmdArgs.push_back("-triple");
3857   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3858
3859   if (IsCuda) {
3860     // We have to pass the triple of the host if compiling for a CUDA device and
3861     // vice-versa.
3862     std::string NormalizedTriple;
3863     if (JA.isDeviceOffloading(Action::OFK_Cuda))
3864       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3865                              ->getTriple()
3866                              .normalize();
3867     else
3868       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3869                              ->getTriple()
3870                              .normalize();
3871
3872     CmdArgs.push_back("-aux-triple");
3873     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3874   }
3875
3876   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3877                                Triple.getArch() == llvm::Triple::thumb)) {
3878     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3879     unsigned Version;
3880     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3881     if (Version < 7)
3882       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3883                                                 << TripleStr;
3884   }
3885
3886   // Push all default warning arguments that are specific to
3887   // the given target.  These come before user provided warning options
3888   // are provided.
3889   getToolChain().addClangWarningOptions(CmdArgs);
3890
3891   // Select the appropriate action.
3892   RewriteKind rewriteKind = RK_None;
3893
3894   if (isa<AnalyzeJobAction>(JA)) {
3895     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3896     CmdArgs.push_back("-analyze");
3897   } else if (isa<MigrateJobAction>(JA)) {
3898     CmdArgs.push_back("-migrate");
3899   } else if (isa<PreprocessJobAction>(JA)) {
3900     if (Output.getType() == types::TY_Dependencies)
3901       CmdArgs.push_back("-Eonly");
3902     else {
3903       CmdArgs.push_back("-E");
3904       if (Args.hasArg(options::OPT_rewrite_objc) &&
3905           !Args.hasArg(options::OPT_g_Group))
3906         CmdArgs.push_back("-P");
3907     }
3908   } else if (isa<AssembleJobAction>(JA)) {
3909     CmdArgs.push_back("-emit-obj");
3910
3911     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3912
3913     // Also ignore explicit -force_cpusubtype_ALL option.
3914     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3915   } else if (isa<PrecompileJobAction>(JA)) {
3916     // Use PCH if the user requested it.
3917     bool UsePCH = D.CCCUsePCH;
3918
3919     if (JA.getType() == types::TY_Nothing)
3920       CmdArgs.push_back("-fsyntax-only");
3921     else if (UsePCH)
3922       CmdArgs.push_back("-emit-pch");
3923     else
3924       CmdArgs.push_back("-emit-pth");
3925   } else if (isa<VerifyPCHJobAction>(JA)) {
3926     CmdArgs.push_back("-verify-pch");
3927   } else {
3928     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3929            "Invalid action for clang tool.");
3930     if (JA.getType() == types::TY_Nothing) {
3931       CmdArgs.push_back("-fsyntax-only");
3932     } else if (JA.getType() == types::TY_LLVM_IR ||
3933                JA.getType() == types::TY_LTO_IR) {
3934       CmdArgs.push_back("-emit-llvm");
3935     } else if (JA.getType() == types::TY_LLVM_BC ||
3936                JA.getType() == types::TY_LTO_BC) {
3937       CmdArgs.push_back("-emit-llvm-bc");
3938     } else if (JA.getType() == types::TY_PP_Asm) {
3939       CmdArgs.push_back("-S");
3940     } else if (JA.getType() == types::TY_AST) {
3941       CmdArgs.push_back("-emit-pch");
3942     } else if (JA.getType() == types::TY_ModuleFile) {
3943       CmdArgs.push_back("-module-file-info");
3944     } else if (JA.getType() == types::TY_RewrittenObjC) {
3945       CmdArgs.push_back("-rewrite-objc");
3946       rewriteKind = RK_NonFragile;
3947     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3948       CmdArgs.push_back("-rewrite-objc");
3949       rewriteKind = RK_Fragile;
3950     } else {
3951       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3952     }
3953
3954     // Preserve use-list order by default when emitting bitcode, so that
3955     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3956     // same result as running passes here.  For LTO, we don't need to preserve
3957     // the use-list order, since serialization to bitcode is part of the flow.
3958     if (JA.getType() == types::TY_LLVM_BC)
3959       CmdArgs.push_back("-emit-llvm-uselists");
3960
3961     if (D.isUsingLTO())
3962       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3963   }
3964
3965   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3966     if (!types::isLLVMIR(Input.getType()))
3967       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3968                                                        << "-x ir";
3969     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3970   }
3971
3972   // Embed-bitcode option.
3973   if (C.getDriver().embedBitcodeEnabled() &&
3974       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3975     // Add flags implied by -fembed-bitcode.
3976     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3977     // Disable all llvm IR level optimizations.
3978     CmdArgs.push_back("-disable-llvm-optzns");
3979   }
3980   if (C.getDriver().embedBitcodeMarkerOnly())
3981     CmdArgs.push_back("-fembed-bitcode=marker");
3982
3983   // We normally speed up the clang process a bit by skipping destructors at
3984   // exit, but when we're generating diagnostics we can rely on some of the
3985   // cleanup.
3986   if (!C.isForDiagnostics())
3987     CmdArgs.push_back("-disable-free");
3988
3989 // Disable the verification pass in -asserts builds.
3990 #ifdef NDEBUG
3991   CmdArgs.push_back("-disable-llvm-verifier");
3992   // Discard LLVM value names in -asserts builds.
3993   CmdArgs.push_back("-discard-value-names");
3994 #endif
3995
3996   // Set the main file name, so that debug info works even with
3997   // -save-temps.
3998   CmdArgs.push_back("-main-file-name");
3999   CmdArgs.push_back(getBaseInputName(Args, Input));
4000
4001   // Some flags which affect the language (via preprocessor
4002   // defines).
4003   if (Args.hasArg(options::OPT_static))
4004     CmdArgs.push_back("-static-define");
4005
4006   if (isa<AnalyzeJobAction>(JA)) {
4007     // Enable region store model by default.
4008     CmdArgs.push_back("-analyzer-store=region");
4009
4010     // Treat blocks as analysis entry points.
4011     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
4012
4013     CmdArgs.push_back("-analyzer-eagerly-assume");
4014
4015     // Add default argument set.
4016     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
4017       CmdArgs.push_back("-analyzer-checker=core");
4018
4019     if (!IsWindowsMSVC) {
4020       CmdArgs.push_back("-analyzer-checker=unix");
4021     } else {
4022       // Enable "unix" checkers that also work on Windows.
4023       CmdArgs.push_back("-analyzer-checker=unix.API");
4024       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
4025       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
4026       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
4027       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
4028       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
4029     }
4030
4031       // Disable some unix checkers for PS4.
4032       if (IsPS4CPU) {
4033         CmdArgs.push_back("-analyzer-disable-checker=unix.API");
4034         CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
4035       }
4036
4037       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
4038         CmdArgs.push_back("-analyzer-checker=osx");
4039
4040       CmdArgs.push_back("-analyzer-checker=deadcode");
4041
4042       if (types::isCXX(Input.getType()))
4043         CmdArgs.push_back("-analyzer-checker=cplusplus");
4044
4045       if (!IsPS4CPU) {
4046         CmdArgs.push_back(
4047             "-analyzer-checker=security.insecureAPI.UncheckedReturn");
4048         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
4049         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
4050         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
4051         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
4052         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
4053       }
4054
4055       // Default nullability checks.
4056       CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
4057       CmdArgs.push_back(
4058           "-analyzer-checker=nullability.NullReturnedFromNonnull");
4059     }
4060
4061     // Set the output format. The default is plist, for (lame) historical
4062     // reasons.
4063     CmdArgs.push_back("-analyzer-output");
4064     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
4065       CmdArgs.push_back(A->getValue());
4066     else
4067       CmdArgs.push_back("plist");
4068
4069     // Disable the presentation of standard compiler warnings when
4070     // using --analyze.  We only want to show static analyzer diagnostics
4071     // or frontend errors.
4072     CmdArgs.push_back("-w");
4073
4074     // Add -Xanalyzer arguments when running as analyzer.
4075     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
4076   }
4077
4078   CheckCodeGenerationOptions(D, Args);
4079
4080   llvm::Reloc::Model RelocationModel;
4081   unsigned PICLevel;
4082   bool IsPIE;
4083   std::tie(RelocationModel, PICLevel, IsPIE) =
4084       ParsePICArgs(getToolChain(), Triple, Args);
4085
4086   const char *RMName = RelocationModelName(RelocationModel);
4087   if (RMName) {
4088     CmdArgs.push_back("-mrelocation-model");
4089     CmdArgs.push_back(RMName);
4090   }
4091   if (PICLevel > 0) {
4092     CmdArgs.push_back("-pic-level");
4093     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4094     if (IsPIE)
4095       CmdArgs.push_back("-pic-is-pie");
4096   }
4097
4098   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4099     CmdArgs.push_back("-meabi");
4100     CmdArgs.push_back(A->getValue());
4101   }
4102
4103   CmdArgs.push_back("-mthread-model");
4104   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
4105     CmdArgs.push_back(A->getValue());
4106   else
4107     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
4108
4109   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4110
4111   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
4112                     options::OPT_fno_merge_all_constants))
4113     CmdArgs.push_back("-fno-merge-all-constants");
4114
4115   // LLVM Code Generator Options.
4116
4117   if (Args.hasArg(options::OPT_frewrite_map_file) ||
4118       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
4119     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
4120                                       options::OPT_frewrite_map_file_EQ)) {
4121       CmdArgs.push_back("-frewrite-map-file");
4122       CmdArgs.push_back(A->getValue());
4123       A->claim();
4124     }
4125   }
4126
4127   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4128     StringRef v = A->getValue();
4129     CmdArgs.push_back("-mllvm");
4130     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4131     A->claim();
4132   }
4133
4134   if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4135                     true))
4136     CmdArgs.push_back("-fno-jump-tables");
4137
4138   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4139     CmdArgs.push_back("-mregparm");
4140     CmdArgs.push_back(A->getValue());
4141   }
4142
4143   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4144                                options::OPT_freg_struct_return)) {
4145     if (getToolChain().getArch() != llvm::Triple::x86) {
4146       D.Diag(diag::err_drv_unsupported_opt_for_target)
4147           << A->getSpelling() << getToolChain().getTriple().str();
4148     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4149       CmdArgs.push_back("-fpcc-struct-return");
4150     } else {
4151       assert(A->getOption().matches(options::OPT_freg_struct_return));
4152       CmdArgs.push_back("-freg-struct-return");
4153     }
4154   }
4155
4156   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4157     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4158
4159   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
4160     CmdArgs.push_back("-mdisable-fp-elim");
4161   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4162                     options::OPT_fno_zero_initialized_in_bss))
4163     CmdArgs.push_back("-mno-zero-initialized-in-bss");
4164
4165   bool OFastEnabled = isOptimizationLevelFast(Args);
4166   // If -Ofast is the optimization level, then -fstrict-aliasing should be
4167   // enabled.  This alias option is being used to simplify the hasFlag logic.
4168   OptSpecifier StrictAliasingAliasOption =
4169       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4170   // We turn strict aliasing off by default if we're in CL mode, since MSVC
4171   // doesn't do any TBAA.
4172   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
4173   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4174                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4175     CmdArgs.push_back("-relaxed-aliasing");
4176   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4177                     options::OPT_fno_struct_path_tbaa))
4178     CmdArgs.push_back("-no-struct-path-tbaa");
4179   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4180                    false))
4181     CmdArgs.push_back("-fstrict-enums");
4182   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4183                    options::OPT_fno_strict_vtable_pointers,
4184                    false))
4185     CmdArgs.push_back("-fstrict-vtable-pointers");
4186   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4187                     options::OPT_fno_optimize_sibling_calls))
4188     CmdArgs.push_back("-mdisable-tail-calls");
4189
4190   // Handle segmented stacks.
4191   if (Args.hasArg(options::OPT_fsplit_stack))
4192     CmdArgs.push_back("-split-stacks");
4193
4194   // If -Ofast is the optimization level, then -ffast-math should be enabled.
4195   // This alias option is being used to simplify the getLastArg logic.
4196   OptSpecifier FastMathAliasOption =
4197       OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
4198
4199   // Handle various floating point optimization flags, mapping them to the
4200   // appropriate LLVM code generation flags. The pattern for all of these is to
4201   // default off the codegen optimizations, and if any flag enables them and no
4202   // flag disables them after the flag enabling them, enable the codegen
4203   // optimization. This is complicated by several "umbrella" flags.
4204   if (Arg *A = Args.getLastArg(
4205           options::OPT_ffast_math, FastMathAliasOption,
4206           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4207           options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
4208           options::OPT_fno_honor_infinities))
4209     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4210         A->getOption().getID() != options::OPT_fno_finite_math_only &&
4211         A->getOption().getID() != options::OPT_fhonor_infinities)
4212       CmdArgs.push_back("-menable-no-infs");
4213   if (Arg *A = Args.getLastArg(
4214           options::OPT_ffast_math, FastMathAliasOption,
4215           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4216           options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
4217           options::OPT_fno_honor_nans))
4218     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4219         A->getOption().getID() != options::OPT_fno_finite_math_only &&
4220         A->getOption().getID() != options::OPT_fhonor_nans)
4221       CmdArgs.push_back("-menable-no-nans");
4222
4223   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
4224   bool MathErrno = getToolChain().IsMathErrnoDefault();
4225   if (Arg *A =
4226           Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4227                           options::OPT_fno_fast_math, options::OPT_fmath_errno,
4228                           options::OPT_fno_math_errno)) {
4229     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
4230     // However, turning *off* -ffast_math merely restores the toolchain default
4231     // (which may be false).
4232     if (A->getOption().getID() == options::OPT_fno_math_errno ||
4233         A->getOption().getID() == options::OPT_ffast_math ||
4234         A->getOption().getID() == options::OPT_Ofast)
4235       MathErrno = false;
4236     else if (A->getOption().getID() == options::OPT_fmath_errno)
4237       MathErrno = true;
4238   }
4239   if (MathErrno)
4240     CmdArgs.push_back("-fmath-errno");
4241
4242   // There are several flags which require disabling very specific
4243   // optimizations. Any of these being disabled forces us to turn off the
4244   // entire set of LLVM optimizations, so collect them through all the flag
4245   // madness.
4246   bool AssociativeMath = false;
4247   if (Arg *A = Args.getLastArg(
4248           options::OPT_ffast_math, FastMathAliasOption,
4249           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4250           options::OPT_fno_unsafe_math_optimizations,
4251           options::OPT_fassociative_math, options::OPT_fno_associative_math))
4252     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4253         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4254         A->getOption().getID() != options::OPT_fno_associative_math)
4255       AssociativeMath = true;
4256   bool ReciprocalMath = false;
4257   if (Arg *A = Args.getLastArg(
4258           options::OPT_ffast_math, FastMathAliasOption,
4259           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4260           options::OPT_fno_unsafe_math_optimizations,
4261           options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
4262     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4263         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4264         A->getOption().getID() != options::OPT_fno_reciprocal_math)
4265       ReciprocalMath = true;
4266   bool SignedZeros = true;
4267   if (Arg *A = Args.getLastArg(
4268           options::OPT_ffast_math, FastMathAliasOption,
4269           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4270           options::OPT_fno_unsafe_math_optimizations,
4271           options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
4272     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4273         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4274         A->getOption().getID() != options::OPT_fsigned_zeros)
4275       SignedZeros = false;
4276   bool TrappingMath = true;
4277   if (Arg *A = Args.getLastArg(
4278           options::OPT_ffast_math, FastMathAliasOption,
4279           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4280           options::OPT_fno_unsafe_math_optimizations,
4281           options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
4282     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4283         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4284         A->getOption().getID() != options::OPT_ftrapping_math)
4285       TrappingMath = false;
4286   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
4287       !TrappingMath)
4288     CmdArgs.push_back("-menable-unsafe-fp-math");
4289
4290   if (!SignedZeros)
4291     CmdArgs.push_back("-fno-signed-zeros");
4292
4293   if (ReciprocalMath)
4294     CmdArgs.push_back("-freciprocal-math");
4295
4296   // Validate and pass through -fp-contract option.
4297   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4298                                options::OPT_fno_fast_math,
4299                                options::OPT_ffp_contract)) {
4300     if (A->getOption().getID() == options::OPT_ffp_contract) {
4301       StringRef Val = A->getValue();
4302       if (Val == "fast" || Val == "on" || Val == "off") {
4303         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
4304       } else {
4305         D.Diag(diag::err_drv_unsupported_option_argument)
4306             << A->getOption().getName() << Val;
4307       }
4308     } else if (A->getOption().matches(options::OPT_ffast_math) ||
4309                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
4310       // If fast-math is set then set the fp-contract mode to fast.
4311       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
4312     }
4313   }
4314
4315   ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
4316
4317   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
4318   // and if we find them, tell the frontend to provide the appropriate
4319   // preprocessor macros. This is distinct from enabling any optimizations as
4320   // these options induce language changes which must survive serialization
4321   // and deserialization, etc.
4322   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4323                                options::OPT_fno_fast_math))
4324     if (!A->getOption().matches(options::OPT_fno_fast_math))
4325       CmdArgs.push_back("-ffast-math");
4326   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
4327                                options::OPT_fno_fast_math))
4328     if (A->getOption().matches(options::OPT_ffinite_math_only))
4329       CmdArgs.push_back("-ffinite-math-only");
4330
4331   // Decide whether to use verbose asm. Verbose assembly is the default on
4332   // toolchains which have the integrated assembler on by default.
4333   bool IsIntegratedAssemblerDefault =
4334       getToolChain().IsIntegratedAssemblerDefault();
4335   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4336                    IsIntegratedAssemblerDefault) ||
4337       Args.hasArg(options::OPT_dA))
4338     CmdArgs.push_back("-masm-verbose");
4339
4340   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
4341                     IsIntegratedAssemblerDefault))
4342     CmdArgs.push_back("-no-integrated-as");
4343
4344   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4345     CmdArgs.push_back("-mdebug-pass");
4346     CmdArgs.push_back("Structure");
4347   }
4348   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4349     CmdArgs.push_back("-mdebug-pass");
4350     CmdArgs.push_back("Arguments");
4351   }
4352
4353   // Enable -mconstructor-aliases except on darwin, where we have to work around
4354   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4355   // aliases aren't supported.
4356   if (!getToolChain().getTriple().isOSDarwin() &&
4357       !getToolChain().getTriple().isNVPTX())
4358     CmdArgs.push_back("-mconstructor-aliases");
4359
4360   // Darwin's kernel doesn't support guard variables; just die if we
4361   // try to use them.
4362   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
4363     CmdArgs.push_back("-fforbid-guard-variables");
4364
4365   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4366                    false)) {
4367     CmdArgs.push_back("-mms-bitfields");
4368   }
4369
4370   // This is a coarse approximation of what llvm-gcc actually does, both
4371   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4372   // complicated ways.
4373   bool AsynchronousUnwindTables =
4374       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4375                    options::OPT_fno_asynchronous_unwind_tables,
4376                    (getToolChain().IsUnwindTablesDefault() ||
4377                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
4378                        !KernelOrKext);
4379   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4380                    AsynchronousUnwindTables))
4381     CmdArgs.push_back("-munwind-tables");
4382
4383   getToolChain().addClangTargetOptions(Args, CmdArgs);
4384
4385   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
4386     CmdArgs.push_back("-mlimit-float-precision");
4387     CmdArgs.push_back(A->getValue());
4388   }
4389
4390   // FIXME: Handle -mtune=.
4391   (void)Args.hasArg(options::OPT_mtune_EQ);
4392
4393   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4394     CmdArgs.push_back("-mcode-model");
4395     CmdArgs.push_back(A->getValue());
4396   }
4397
4398   // Add the target cpu
4399   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4400   if (!CPU.empty()) {
4401     CmdArgs.push_back("-target-cpu");
4402     CmdArgs.push_back(Args.MakeArgString(CPU));
4403   }
4404
4405   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
4406     CmdArgs.push_back("-mfpmath");
4407     CmdArgs.push_back(A->getValue());
4408   }
4409
4410   // Add the target features
4411   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
4412
4413   // Add target specific flags.
4414   switch (getToolChain().getArch()) {
4415   default:
4416     break;
4417
4418   case llvm::Triple::arm:
4419   case llvm::Triple::armeb:
4420   case llvm::Triple::thumb:
4421   case llvm::Triple::thumbeb:
4422     // Use the effective triple, which takes into account the deployment target.
4423     AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
4424     break;
4425
4426   case llvm::Triple::aarch64:
4427   case llvm::Triple::aarch64_be:
4428     AddAArch64TargetArgs(Args, CmdArgs);
4429     break;
4430
4431   case llvm::Triple::mips:
4432   case llvm::Triple::mipsel:
4433   case llvm::Triple::mips64:
4434   case llvm::Triple::mips64el:
4435     AddMIPSTargetArgs(Args, CmdArgs);
4436     break;
4437
4438   case llvm::Triple::ppc:
4439   case llvm::Triple::ppc64:
4440   case llvm::Triple::ppc64le:
4441     AddPPCTargetArgs(Args, CmdArgs);
4442     break;
4443
4444   case llvm::Triple::sparc:
4445   case llvm::Triple::sparcel:
4446   case llvm::Triple::sparcv9:
4447     AddSparcTargetArgs(Args, CmdArgs);
4448     break;
4449
4450   case llvm::Triple::systemz:
4451     AddSystemZTargetArgs(Args, CmdArgs);
4452     break;
4453
4454   case llvm::Triple::x86:
4455   case llvm::Triple::x86_64:
4456     AddX86TargetArgs(Args, CmdArgs);
4457     break;
4458
4459   case llvm::Triple::lanai:
4460     AddLanaiTargetArgs(Args, CmdArgs);
4461     break;
4462
4463   case llvm::Triple::hexagon:
4464     AddHexagonTargetArgs(Args, CmdArgs);
4465     break;
4466
4467   case llvm::Triple::wasm32:
4468   case llvm::Triple::wasm64:
4469     AddWebAssemblyTargetArgs(Args, CmdArgs);
4470     break;
4471   }
4472
4473   // The 'g' groups options involve a somewhat intricate sequence of decisions
4474   // about what to pass from the driver to the frontend, but by the time they
4475   // reach cc1 they've been factored into three well-defined orthogonal choices:
4476   //  * what level of debug info to generate
4477   //  * what dwarf version to write
4478   //  * what debugger tuning to use
4479   // This avoids having to monkey around further in cc1 other than to disable
4480   // codeview if not running in a Windows environment. Perhaps even that
4481   // decision should be made in the driver as well though.
4482   unsigned DwarfVersion = 0;
4483   llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4484   // These two are potentially updated by AddClangCLArgs.
4485   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4486   bool EmitCodeView = false;
4487
4488   // Add clang-cl arguments.
4489   types::ID InputType = Input.getType();
4490   if (getToolChain().getDriver().IsCLMode())
4491     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4492
4493   // Pass the linker version in use.
4494   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4495     CmdArgs.push_back("-target-linker-version");
4496     CmdArgs.push_back(A->getValue());
4497   }
4498
4499   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4500     CmdArgs.push_back("-momit-leaf-frame-pointer");
4501
4502   // Explicitly error on some things we know we don't support and can't just
4503   // ignore.
4504   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4505     Arg *Unsupported;
4506     if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4507         getToolChain().getArch() == llvm::Triple::x86) {
4508       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4509           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4510         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4511             << Unsupported->getOption().getName();
4512     }
4513   }
4514
4515   Args.AddAllArgs(CmdArgs, options::OPT_v);
4516   Args.AddLastArg(CmdArgs, options::OPT_H);
4517   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4518     CmdArgs.push_back("-header-include-file");
4519     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4520                                                : "-");
4521   }
4522   Args.AddLastArg(CmdArgs, options::OPT_P);
4523   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4524
4525   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4526     CmdArgs.push_back("-diagnostic-log-file");
4527     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4528                                                  : "-");
4529   }
4530
4531   Args.ClaimAllArgs(options::OPT_g_Group);
4532   Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4533   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4534     // If the last option explicitly specified a debug-info level, use it.
4535     if (A->getOption().matches(options::OPT_gN_Group)) {
4536       DebugInfoKind = DebugLevelToInfoKind(*A);
4537       // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4538       // But -gsplit-dwarf is not a g_group option, hence we have to check the
4539       // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4540       if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
4541           A->getIndex() > SplitDwarfArg->getIndex())
4542         SplitDwarfArg = nullptr;
4543     } else
4544       // For any other 'g' option, use Limited.
4545       DebugInfoKind = codegenoptions::LimitedDebugInfo;
4546   }
4547
4548   // If a debugger tuning argument appeared, remember it.
4549   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4550                                options::OPT_ggdbN_Group)) {
4551     if (A->getOption().matches(options::OPT_glldb))
4552       DebuggerTuning = llvm::DebuggerKind::LLDB;
4553     else if (A->getOption().matches(options::OPT_gsce))
4554       DebuggerTuning = llvm::DebuggerKind::SCE;
4555     else
4556       DebuggerTuning = llvm::DebuggerKind::GDB;
4557   }
4558
4559   // If a -gdwarf argument appeared, remember it.
4560   if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4561                                options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4562     DwarfVersion = DwarfVersionNum(A->getSpelling());
4563
4564   // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
4565   // argument parsing.
4566   if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4567     // DwarfVersion remains at 0 if no explicit choice was made.
4568     CmdArgs.push_back("-gcodeview");
4569   } else if (DwarfVersion == 0 &&
4570              DebugInfoKind != codegenoptions::NoDebugInfo) {
4571     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4572   }
4573
4574   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4575   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4576
4577   // PS4 defaults to no column info
4578   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4579                    /*Default=*/ !IsPS4CPU))
4580     CmdArgs.push_back("-dwarf-column-info");
4581
4582   // FIXME: Move backend command line options to the module.
4583   if (Args.hasArg(options::OPT_gmodules)) {
4584     DebugInfoKind = codegenoptions::LimitedDebugInfo;
4585     CmdArgs.push_back("-dwarf-ext-refs");
4586     CmdArgs.push_back("-fmodule-format=obj");
4587   }
4588
4589   // -gsplit-dwarf should turn on -g and enable the backend dwarf
4590   // splitting and extraction.
4591   // FIXME: Currently only works on Linux.
4592   if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4593     DebugInfoKind = codegenoptions::LimitedDebugInfo;
4594     CmdArgs.push_back("-backend-option");
4595     CmdArgs.push_back("-split-dwarf=Enable");
4596   }
4597
4598   // After we've dealt with all combinations of things that could
4599   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4600   // figure out if we need to "upgrade" it to standalone debug info.
4601   // We parse these two '-f' options whether or not they will be used,
4602   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4603   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4604                                     options::OPT_fno_standalone_debug,
4605                                     getToolChain().GetDefaultStandaloneDebug());
4606   if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
4607     DebugInfoKind = codegenoptions::FullDebugInfo;
4608   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4609                           DebuggerTuning);
4610
4611   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4612   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4613     CmdArgs.push_back("-backend-option");
4614     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4615   }
4616
4617   // -gdwarf-aranges turns on the emission of the aranges section in the
4618   // backend.
4619   // Always enabled on the PS4.
4620   if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4621     CmdArgs.push_back("-backend-option");
4622     CmdArgs.push_back("-generate-arange-section");
4623   }
4624
4625   if (Args.hasFlag(options::OPT_fdebug_types_section,
4626                    options::OPT_fno_debug_types_section, false)) {
4627     CmdArgs.push_back("-backend-option");
4628     CmdArgs.push_back("-generate-type-units");
4629   }
4630
4631   // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4632   // default.
4633   bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4634                              Triple.getArch() == llvm::Triple::wasm32 ||
4635                              Triple.getArch() == llvm::Triple::wasm64;
4636
4637   if (Args.hasFlag(options::OPT_ffunction_sections,
4638                    options::OPT_fno_function_sections, UseSeparateSections)) {
4639     CmdArgs.push_back("-ffunction-sections");
4640   }
4641
4642   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4643                    UseSeparateSections)) {
4644     CmdArgs.push_back("-fdata-sections");
4645   }
4646
4647   if (!Args.hasFlag(options::OPT_funique_section_names,
4648                     options::OPT_fno_unique_section_names, true))
4649     CmdArgs.push_back("-fno-unique-section-names");
4650
4651   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4652
4653   if (Args.hasFlag(options::OPT_fxray_instrument,
4654                    options::OPT_fnoxray_instrument, false)) {
4655     CmdArgs.push_back("-fxray-instrument");
4656     if (const Arg *A =
4657             Args.getLastArg(options::OPT_fxray_instruction_threshold_,
4658                             options::OPT_fxray_instruction_threshold_EQ)) {
4659       CmdArgs.push_back("-fxray-instruction-threshold");
4660       CmdArgs.push_back(A->getValue());
4661     }
4662   }
4663
4664   addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4665
4666   // Add runtime flag for PS4 when PGO or Coverage are enabled.
4667   if (getToolChain().getTriple().isPS4CPU())
4668     addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4669
4670   // Pass options for controlling the default header search paths.
4671   if (Args.hasArg(options::OPT_nostdinc)) {
4672     CmdArgs.push_back("-nostdsysteminc");
4673     CmdArgs.push_back("-nobuiltininc");
4674   } else {
4675     if (Args.hasArg(options::OPT_nostdlibinc))
4676       CmdArgs.push_back("-nostdsysteminc");
4677     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4678     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4679   }
4680
4681   // Pass the path to compiler resource files.
4682   CmdArgs.push_back("-resource-dir");
4683   CmdArgs.push_back(D.ResourceDir.c_str());
4684
4685   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4686
4687   bool ARCMTEnabled = false;
4688   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4689     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4690                                        options::OPT_ccc_arcmt_modify,
4691                                        options::OPT_ccc_arcmt_migrate)) {
4692       ARCMTEnabled = true;
4693       switch (A->getOption().getID()) {
4694       default:
4695         llvm_unreachable("missed a case");
4696       case options::OPT_ccc_arcmt_check:
4697         CmdArgs.push_back("-arcmt-check");
4698         break;
4699       case options::OPT_ccc_arcmt_modify:
4700         CmdArgs.push_back("-arcmt-modify");
4701         break;
4702       case options::OPT_ccc_arcmt_migrate:
4703         CmdArgs.push_back("-arcmt-migrate");
4704         CmdArgs.push_back("-mt-migrate-directory");
4705         CmdArgs.push_back(A->getValue());
4706
4707         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4708         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4709         break;
4710       }
4711     }
4712   } else {
4713     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4714     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4715     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4716   }
4717
4718   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4719     if (ARCMTEnabled) {
4720       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4721                                                       << "-ccc-arcmt-migrate";
4722     }
4723     CmdArgs.push_back("-mt-migrate-directory");
4724     CmdArgs.push_back(A->getValue());
4725
4726     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4727                      options::OPT_objcmt_migrate_subscripting,
4728                      options::OPT_objcmt_migrate_property)) {
4729       // None specified, means enable them all.
4730       CmdArgs.push_back("-objcmt-migrate-literals");
4731       CmdArgs.push_back("-objcmt-migrate-subscripting");
4732       CmdArgs.push_back("-objcmt-migrate-property");
4733     } else {
4734       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4735       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4736       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4737     }
4738   } else {
4739     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4740     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4741     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4742     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4743     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4744     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4745     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4746     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4747     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4748     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4749     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4750     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4751     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4752     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4753     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4754     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4755   }
4756
4757   // Add preprocessing options like -I, -D, etc. if we are using the
4758   // preprocessor.
4759   //
4760   // FIXME: Support -fpreprocessed
4761   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4762     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4763
4764   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4765   // that "The compiler can only warn and ignore the option if not recognized".
4766   // When building with ccache, it will pass -D options to clang even on
4767   // preprocessed inputs and configure concludes that -fPIC is not supported.
4768   Args.ClaimAllArgs(options::OPT_D);
4769
4770   // Manually translate -O4 to -O3; let clang reject others.
4771   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4772     if (A->getOption().matches(options::OPT_O4)) {
4773       CmdArgs.push_back("-O3");
4774       D.Diag(diag::warn_O4_is_O3);
4775     } else {
4776       A->render(Args, CmdArgs);
4777     }
4778   }
4779
4780   // Warn about ignored options to clang.
4781   for (const Arg *A :
4782        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4783     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4784     A->claim();
4785   }
4786
4787   claimNoWarnArgs(Args);
4788
4789   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4790   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4791   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4792     CmdArgs.push_back("-pedantic");
4793   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4794   Args.AddLastArg(CmdArgs, options::OPT_w);
4795
4796   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4797   // (-ansi is equivalent to -std=c89 or -std=c++98).
4798   //
4799   // If a std is supplied, only add -trigraphs if it follows the
4800   // option.
4801   bool ImplyVCPPCXXVer = false;
4802   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4803     if (Std->getOption().matches(options::OPT_ansi))
4804       if (types::isCXX(InputType))
4805         CmdArgs.push_back("-std=c++98");
4806       else
4807         CmdArgs.push_back("-std=c89");
4808     else
4809       Std->render(Args, CmdArgs);
4810
4811     // If -f(no-)trigraphs appears after the language standard flag, honor it.
4812     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4813                                  options::OPT_ftrigraphs,
4814                                  options::OPT_fno_trigraphs))
4815       if (A != Std)
4816         A->render(Args, CmdArgs);
4817   } else {
4818     // Honor -std-default.
4819     //
4820     // FIXME: Clang doesn't correctly handle -std= when the input language
4821     // doesn't match. For the time being just ignore this for C++ inputs;
4822     // eventually we want to do all the standard defaulting here instead of
4823     // splitting it between the driver and clang -cc1.
4824     if (!types::isCXX(InputType))
4825       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4826                                 /*Joined=*/true);
4827     else if (IsWindowsMSVC)
4828       ImplyVCPPCXXVer = true;
4829
4830     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4831                     options::OPT_fno_trigraphs);
4832   }
4833
4834   // GCC's behavior for -Wwrite-strings is a bit strange:
4835   //  * In C, this "warning flag" changes the types of string literals from
4836   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4837   //    for the discarded qualifier.
4838   //  * In C++, this is just a normal warning flag.
4839   //
4840   // Implementing this warning correctly in C is hard, so we follow GCC's
4841   // behavior for now. FIXME: Directly diagnose uses of a string literal as
4842   // a non-const char* in C, rather than using this crude hack.
4843   if (!types::isCXX(InputType)) {
4844     // FIXME: This should behave just like a warning flag, and thus should also
4845     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4846     Arg *WriteStrings =
4847         Args.getLastArg(options::OPT_Wwrite_strings,
4848                         options::OPT_Wno_write_strings, options::OPT_w);
4849     if (WriteStrings &&
4850         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4851       CmdArgs.push_back("-fconst-strings");
4852   }
4853
4854   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4855   // during C++ compilation, which it is by default. GCC keeps this define even
4856   // in the presence of '-w', match this behavior bug-for-bug.
4857   if (types::isCXX(InputType) &&
4858       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4859                    true)) {
4860     CmdArgs.push_back("-fdeprecated-macro");
4861   }
4862
4863   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4864   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4865     if (Asm->getOption().matches(options::OPT_fasm))
4866       CmdArgs.push_back("-fgnu-keywords");
4867     else
4868       CmdArgs.push_back("-fno-gnu-keywords");
4869   }
4870
4871   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4872     CmdArgs.push_back("-fno-dwarf-directory-asm");
4873
4874   if (ShouldDisableAutolink(Args, getToolChain()))
4875     CmdArgs.push_back("-fno-autolink");
4876
4877   // Add in -fdebug-compilation-dir if necessary.
4878   addDebugCompDirArg(Args, CmdArgs);
4879
4880   for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4881     StringRef Map = A->getValue();
4882     if (Map.find('=') == StringRef::npos)
4883       D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4884     else
4885       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4886     A->claim();
4887   }
4888
4889   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4890                                options::OPT_ftemplate_depth_EQ)) {
4891     CmdArgs.push_back("-ftemplate-depth");
4892     CmdArgs.push_back(A->getValue());
4893   }
4894
4895   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4896     CmdArgs.push_back("-foperator-arrow-depth");
4897     CmdArgs.push_back(A->getValue());
4898   }
4899
4900   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4901     CmdArgs.push_back("-fconstexpr-depth");
4902     CmdArgs.push_back(A->getValue());
4903   }
4904
4905   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4906     CmdArgs.push_back("-fconstexpr-steps");
4907     CmdArgs.push_back(A->getValue());
4908   }
4909
4910   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4911     CmdArgs.push_back("-fbracket-depth");
4912     CmdArgs.push_back(A->getValue());
4913   }
4914
4915   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4916                                options::OPT_Wlarge_by_value_copy_def)) {
4917     if (A->getNumValues()) {
4918       StringRef bytes = A->getValue();
4919       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4920     } else
4921       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4922   }
4923
4924   if (Args.hasArg(options::OPT_relocatable_pch))
4925     CmdArgs.push_back("-relocatable-pch");
4926
4927   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4928     CmdArgs.push_back("-fconstant-string-class");
4929     CmdArgs.push_back(A->getValue());
4930   }
4931
4932   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4933     CmdArgs.push_back("-ftabstop");
4934     CmdArgs.push_back(A->getValue());
4935   }
4936
4937   CmdArgs.push_back("-ferror-limit");
4938   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4939     CmdArgs.push_back(A->getValue());
4940   else
4941     CmdArgs.push_back("19");
4942
4943   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4944     CmdArgs.push_back("-fmacro-backtrace-limit");
4945     CmdArgs.push_back(A->getValue());
4946   }
4947
4948   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4949     CmdArgs.push_back("-ftemplate-backtrace-limit");
4950     CmdArgs.push_back(A->getValue());
4951   }
4952
4953   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4954     CmdArgs.push_back("-fconstexpr-backtrace-limit");
4955     CmdArgs.push_back(A->getValue());
4956   }
4957
4958   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4959     CmdArgs.push_back("-fspell-checking-limit");
4960     CmdArgs.push_back(A->getValue());
4961   }
4962
4963   // Pass -fmessage-length=.
4964   CmdArgs.push_back("-fmessage-length");
4965   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4966     CmdArgs.push_back(A->getValue());
4967   } else {
4968     // If -fmessage-length=N was not specified, determine whether this is a
4969     // terminal and, if so, implicitly define -fmessage-length appropriately.
4970     unsigned N = llvm::sys::Process::StandardErrColumns();
4971     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4972   }
4973
4974   // -fvisibility= and -fvisibility-ms-compat are of a piece.
4975   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4976                                      options::OPT_fvisibility_ms_compat)) {
4977     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4978       CmdArgs.push_back("-fvisibility");
4979       CmdArgs.push_back(A->getValue());
4980     } else {
4981       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4982       CmdArgs.push_back("-fvisibility");
4983       CmdArgs.push_back("hidden");
4984       CmdArgs.push_back("-ftype-visibility");
4985       CmdArgs.push_back("default");
4986     }
4987   }
4988
4989   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4990
4991   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4992
4993   // -fhosted is default.
4994   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4995       KernelOrKext)
4996     CmdArgs.push_back("-ffreestanding");
4997
4998   // Forward -f (flag) options which we can pass directly.
4999   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5000   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5001   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
5002   // Emulated TLS is enabled by default on Android, and can be enabled manually
5003   // with -femulated-tls.
5004   bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
5005   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
5006                    EmulatedTLSDefault))
5007     CmdArgs.push_back("-femulated-tls");
5008   // AltiVec-like language extensions aren't relevant for assembling.
5009   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
5010     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
5011     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5012   }
5013   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5014   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5015
5016   // Forward flags for OpenMP. We don't do this if the current action is an
5017   // device offloading action.
5018   //
5019   // TODO: Allow OpenMP offload actions when they become available.
5020   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5021                    options::OPT_fno_openmp, false) &&
5022       JA.isDeviceOffloading(Action::OFK_None)) {
5023     switch (getOpenMPRuntime(getToolChain(), Args)) {
5024     case OMPRT_OMP:
5025     case OMPRT_IOMP5:
5026       // Clang can generate useful OpenMP code for these two runtime libraries.
5027       CmdArgs.push_back("-fopenmp");
5028
5029       // If no option regarding the use of TLS in OpenMP codegeneration is
5030       // given, decide a default based on the target. Otherwise rely on the
5031       // options and pass the right information to the frontend.
5032       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5033                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5034         CmdArgs.push_back("-fnoopenmp-use-tls");
5035       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5036       break;
5037     default:
5038       // By default, if Clang doesn't know how to generate useful OpenMP code
5039       // for a specific runtime library, we just don't pass the '-fopenmp' flag
5040       // down to the actual compilation.
5041       // FIXME: It would be better to have a mode which *only* omits IR
5042       // generation based on the OpenMP support so that we get consistent
5043       // semantic analysis, etc.
5044       break;
5045     }
5046   }
5047
5048   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
5049   Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
5050
5051   // Report an error for -faltivec on anything other than PowerPC.
5052   if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
5053     const llvm::Triple::ArchType Arch = getToolChain().getArch();
5054     if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
5055           Arch == llvm::Triple::ppc64le))
5056       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
5057                                                        << "ppc/ppc64/ppc64le";
5058   }
5059
5060   // -fzvector is incompatible with -faltivec.
5061   if (Arg *A = Args.getLastArg(options::OPT_fzvector))
5062     if (Args.hasArg(options::OPT_faltivec))
5063       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5064                                                       << "-faltivec";
5065
5066   if (getToolChain().SupportsProfiling())
5067     Args.AddLastArg(CmdArgs, options::OPT_pg);
5068
5069   // -flax-vector-conversions is default.
5070   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
5071                     options::OPT_fno_lax_vector_conversions))
5072     CmdArgs.push_back("-fno-lax-vector-conversions");
5073
5074   if (Args.getLastArg(options::OPT_fapple_kext) ||
5075       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5076     CmdArgs.push_back("-fapple-kext");
5077
5078   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5079   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5080   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5081   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5082   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5083
5084   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5085     CmdArgs.push_back("-ftrapv-handler");
5086     CmdArgs.push_back(A->getValue());
5087   }
5088
5089   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5090
5091   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5092   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5093   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5094     if (A->getOption().matches(options::OPT_fwrapv))
5095       CmdArgs.push_back("-fwrapv");
5096   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5097                                       options::OPT_fno_strict_overflow)) {
5098     if (A->getOption().matches(options::OPT_fno_strict_overflow))
5099       CmdArgs.push_back("-fwrapv");
5100   }
5101
5102   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5103                                options::OPT_fno_reroll_loops))
5104     if (A->getOption().matches(options::OPT_freroll_loops))
5105       CmdArgs.push_back("-freroll-loops");
5106
5107   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5108   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5109                   options::OPT_fno_unroll_loops);
5110
5111   Args.AddLastArg(CmdArgs, options::OPT_pthread);
5112
5113   // -stack-protector=0 is default.
5114   unsigned StackProtectorLevel = 0;
5115   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
5116                                options::OPT_fstack_protector_all,
5117                                options::OPT_fstack_protector_strong,
5118                                options::OPT_fstack_protector)) {
5119     if (A->getOption().matches(options::OPT_fstack_protector)) {
5120       StackProtectorLevel = std::max<unsigned>(
5121           LangOptions::SSPOn,
5122           getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
5123     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
5124       StackProtectorLevel = LangOptions::SSPStrong;
5125     else if (A->getOption().matches(options::OPT_fstack_protector_all))
5126       StackProtectorLevel = LangOptions::SSPReq;
5127   } else {
5128     StackProtectorLevel =
5129         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
5130   }
5131   if (StackProtectorLevel) {
5132     CmdArgs.push_back("-stack-protector");
5133     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
5134   }
5135
5136   // --param ssp-buffer-size=
5137   for (const Arg *A : Args.filtered(options::OPT__param)) {
5138     StringRef Str(A->getValue());
5139     if (Str.startswith("ssp-buffer-size=")) {
5140       if (StackProtectorLevel) {
5141         CmdArgs.push_back("-stack-protector-buffer-size");
5142         // FIXME: Verify the argument is a valid integer.
5143         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
5144       }
5145       A->claim();
5146     }
5147   }
5148
5149   // Translate -mstackrealign
5150   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5151                    false))
5152     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5153
5154   if (Args.hasArg(options::OPT_mstack_alignment)) {
5155     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5156     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5157   }
5158
5159   if (Args.hasArg(options::OPT_mstack_probe_size)) {
5160     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5161
5162     if (!Size.empty())
5163       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5164     else
5165       CmdArgs.push_back("-mstack-probe-size=0");
5166   }
5167
5168   switch (getToolChain().getArch()) {
5169   case llvm::Triple::aarch64:
5170   case llvm::Triple::aarch64_be:
5171   case llvm::Triple::arm:
5172   case llvm::Triple::armeb:
5173   case llvm::Triple::thumb:
5174   case llvm::Triple::thumbeb:
5175     CmdArgs.push_back("-fallow-half-arguments-and-returns");
5176     break;
5177
5178   default:
5179     break;
5180   }
5181
5182   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5183                                options::OPT_mno_restrict_it)) {
5184     if (A->getOption().matches(options::OPT_mrestrict_it)) {
5185       CmdArgs.push_back("-backend-option");
5186       CmdArgs.push_back("-arm-restrict-it");
5187     } else {
5188       CmdArgs.push_back("-backend-option");
5189       CmdArgs.push_back("-arm-no-restrict-it");
5190     }
5191   } else if (Triple.isOSWindows() &&
5192              (Triple.getArch() == llvm::Triple::arm ||
5193               Triple.getArch() == llvm::Triple::thumb)) {
5194     // Windows on ARM expects restricted IT blocks
5195     CmdArgs.push_back("-backend-option");
5196     CmdArgs.push_back("-arm-restrict-it");
5197   }
5198
5199   // Forward -cl options to -cc1
5200   if (Args.getLastArg(options::OPT_cl_opt_disable)) {
5201     CmdArgs.push_back("-cl-opt-disable");
5202   }
5203   if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
5204     CmdArgs.push_back("-cl-strict-aliasing");
5205   }
5206   if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
5207     CmdArgs.push_back("-cl-single-precision-constant");
5208   }
5209   if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
5210     CmdArgs.push_back("-cl-finite-math-only");
5211   }
5212   if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
5213     CmdArgs.push_back("-cl-kernel-arg-info");
5214   }
5215   if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
5216     CmdArgs.push_back("-cl-unsafe-math-optimizations");
5217   }
5218   if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
5219     CmdArgs.push_back("-cl-fast-relaxed-math");
5220   }
5221   if (Args.getLastArg(options::OPT_cl_mad_enable)) {
5222     CmdArgs.push_back("-cl-mad-enable");
5223   }
5224   if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
5225     CmdArgs.push_back("-cl-no-signed-zeros");
5226   }
5227   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
5228     std::string CLStdStr = "-cl-std=";
5229     CLStdStr += A->getValue();
5230     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
5231   }
5232   if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
5233     CmdArgs.push_back("-cl-denorms-are-zero");
5234   }
5235
5236   // Forward -f options with positive and negative forms; we translate
5237   // these by hand.
5238   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
5239     StringRef fname = A->getValue();
5240     if (!llvm::sys::fs::exists(fname))
5241       D.Diag(diag::err_drv_no_such_file) << fname;
5242     else
5243       A->render(Args, CmdArgs);
5244   }
5245
5246   // -fbuiltin is default unless -mkernel is used.
5247   bool UseBuiltins =
5248       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
5249                    !Args.hasArg(options::OPT_mkernel));
5250   if (!UseBuiltins)
5251     CmdArgs.push_back("-fno-builtin");
5252
5253   // -ffreestanding implies -fno-builtin.
5254   if (Args.hasArg(options::OPT_ffreestanding))
5255     UseBuiltins = false;
5256
5257   // Process the -fno-builtin-* options.
5258   for (const auto &Arg : Args) {
5259     const Option &O = Arg->getOption();
5260     if (!O.matches(options::OPT_fno_builtin_))
5261       continue;
5262
5263     Arg->claim();
5264     // If -fno-builtin is specified, then there's no need to pass the option to
5265     // the frontend.
5266     if (!UseBuiltins)
5267       continue;
5268
5269     StringRef FuncName = Arg->getValue();
5270     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
5271   }
5272
5273   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5274                     options::OPT_fno_assume_sane_operator_new))
5275     CmdArgs.push_back("-fno-assume-sane-operator-new");
5276
5277   // -fblocks=0 is default.
5278   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5279                    getToolChain().IsBlocksDefault()) ||
5280       (Args.hasArg(options::OPT_fgnu_runtime) &&
5281        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5282        !Args.hasArg(options::OPT_fno_blocks))) {
5283     CmdArgs.push_back("-fblocks");
5284
5285     if (!Args.hasArg(options::OPT_fgnu_runtime) &&
5286         !getToolChain().hasBlocksRuntime())
5287       CmdArgs.push_back("-fblocks-runtime-optional");
5288   }
5289
5290   // -fmodules enables the use of precompiled modules (off by default).
5291   // Users can pass -fno-cxx-modules to turn off modules support for
5292   // C++/Objective-C++ programs.
5293   bool HaveModules = false;
5294   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
5295     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
5296                                      options::OPT_fno_cxx_modules, true);
5297     if (AllowedInCXX || !types::isCXX(InputType)) {
5298       CmdArgs.push_back("-fmodules");
5299       HaveModules = true;
5300     }
5301   }
5302
5303   // -fmodule-maps enables implicit reading of module map files. By default,
5304   // this is enabled if we are using precompiled modules.
5305   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
5306                    options::OPT_fno_implicit_module_maps, HaveModules)) {
5307     CmdArgs.push_back("-fimplicit-module-maps");
5308   }
5309
5310   // -fmodules-decluse checks that modules used are declared so (off by
5311   // default).
5312   if (Args.hasFlag(options::OPT_fmodules_decluse,
5313                    options::OPT_fno_modules_decluse, false)) {
5314     CmdArgs.push_back("-fmodules-decluse");
5315   }
5316
5317   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
5318   // all #included headers are part of modules.
5319   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
5320                    options::OPT_fno_modules_strict_decluse, false)) {
5321     CmdArgs.push_back("-fmodules-strict-decluse");
5322   }
5323
5324   // -fno-implicit-modules turns off implicitly compiling modules on demand.
5325   if (!Args.hasFlag(options::OPT_fimplicit_modules,
5326                     options::OPT_fno_implicit_modules)) {
5327     CmdArgs.push_back("-fno-implicit-modules");
5328   } else if (HaveModules) {
5329     // -fmodule-cache-path specifies where our implicitly-built module files
5330     // should be written.
5331     SmallString<128> Path;
5332     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
5333       Path = A->getValue();
5334     if (C.isForDiagnostics()) {
5335       // When generating crash reports, we want to emit the modules along with
5336       // the reproduction sources, so we ignore any provided module path.
5337       Path = Output.getFilename();
5338       llvm::sys::path::replace_extension(Path, ".cache");
5339       llvm::sys::path::append(Path, "modules");
5340     } else if (Path.empty()) {
5341       // No module path was provided: use the default.
5342       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
5343       llvm::sys::path::append(Path, "org.llvm.clang.");
5344       appendUserToPath(Path);
5345       llvm::sys::path::append(Path, "ModuleCache");
5346     }
5347     const char Arg[] = "-fmodules-cache-path=";
5348     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
5349     CmdArgs.push_back(Args.MakeArgString(Path));
5350   }
5351
5352   // -fmodule-name specifies the module that is currently being built (or
5353   // used for header checking by -fmodule-maps).
5354   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
5355
5356   // -fmodule-map-file can be used to specify files containing module
5357   // definitions.
5358   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
5359
5360   // -fmodule-file can be used to specify files containing precompiled modules.
5361   if (HaveModules)
5362     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
5363   else
5364     Args.ClaimAllArgs(options::OPT_fmodule_file);
5365
5366   // When building modules and generating crashdumps, we need to dump a module
5367   // dependency VFS alongside the output.
5368   if (HaveModules && C.isForDiagnostics()) {
5369     SmallString<128> VFSDir(Output.getFilename());
5370     llvm::sys::path::replace_extension(VFSDir, ".cache");
5371     // Add the cache directory as a temp so the crash diagnostics pick it up.
5372     C.addTempFile(Args.MakeArgString(VFSDir));
5373
5374     llvm::sys::path::append(VFSDir, "vfs");
5375     CmdArgs.push_back("-module-dependency-dir");
5376     CmdArgs.push_back(Args.MakeArgString(VFSDir));
5377   }
5378
5379   if (HaveModules)
5380     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
5381
5382   // Pass through all -fmodules-ignore-macro arguments.
5383   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
5384   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
5385   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
5386
5387   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
5388
5389   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
5390     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
5391       D.Diag(diag::err_drv_argument_not_allowed_with)
5392           << A->getAsString(Args) << "-fbuild-session-timestamp";
5393
5394     llvm::sys::fs::file_status Status;
5395     if (llvm::sys::fs::status(A->getValue(), Status))
5396       D.Diag(diag::err_drv_no_such_file) << A->getValue();
5397     CmdArgs.push_back(Args.MakeArgString(
5398         "-fbuild-session-timestamp=" +
5399         Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
5400   }
5401
5402   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
5403     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
5404                          options::OPT_fbuild_session_file))
5405       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
5406
5407     Args.AddLastArg(CmdArgs,
5408                     options::OPT_fmodules_validate_once_per_build_session);
5409   }
5410
5411   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
5412
5413   // -faccess-control is default.
5414   if (Args.hasFlag(options::OPT_fno_access_control,
5415                    options::OPT_faccess_control, false))
5416     CmdArgs.push_back("-fno-access-control");
5417
5418   // -felide-constructors is the default.
5419   if (Args.hasFlag(options::OPT_fno_elide_constructors,
5420                    options::OPT_felide_constructors, false))
5421     CmdArgs.push_back("-fno-elide-constructors");
5422
5423   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5424
5425   if (KernelOrKext || (types::isCXX(InputType) &&
5426                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5427                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
5428     CmdArgs.push_back("-fno-rtti");
5429
5430   // -fshort-enums=0 is default for all architectures except Hexagon.
5431   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5432                    getToolChain().getArch() == llvm::Triple::hexagon))
5433     CmdArgs.push_back("-fshort-enums");
5434
5435   // -fsigned-char is default.
5436   if (Arg *A = Args.getLastArg(
5437           options::OPT_fsigned_char, options::OPT_fno_signed_char,
5438           options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5439     if (A->getOption().matches(options::OPT_funsigned_char) ||
5440         A->getOption().matches(options::OPT_fno_signed_char)) {
5441       CmdArgs.push_back("-fno-signed-char");
5442     }
5443   } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5444     CmdArgs.push_back("-fno-signed-char");
5445   }
5446
5447   // -fuse-cxa-atexit is default.
5448   if (!Args.hasFlag(
5449           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5450           !IsWindowsCygnus && !IsWindowsGNU &&
5451               getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5452               getToolChain().getArch() != llvm::Triple::hexagon &&
5453               getToolChain().getArch() != llvm::Triple::xcore &&
5454               ((getToolChain().getTriple().getVendor() !=
5455                 llvm::Triple::MipsTechnologies) ||
5456                getToolChain().getTriple().hasEnvironment())) ||
5457       KernelOrKext)
5458     CmdArgs.push_back("-fno-use-cxa-atexit");
5459
5460   // -fms-extensions=0 is default.
5461   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5462                    IsWindowsMSVC))
5463     CmdArgs.push_back("-fms-extensions");
5464
5465   // -fno-use-line-directives is default.
5466   if (Args.hasFlag(options::OPT_fuse_line_directives,
5467                    options::OPT_fno_use_line_directives, false))
5468     CmdArgs.push_back("-fuse-line-directives");
5469
5470   // -fms-compatibility=0 is default.
5471   if (Args.hasFlag(options::OPT_fms_compatibility,
5472                    options::OPT_fno_ms_compatibility,
5473                    (IsWindowsMSVC &&
5474                     Args.hasFlag(options::OPT_fms_extensions,
5475                                  options::OPT_fno_ms_extensions, true))))
5476     CmdArgs.push_back("-fms-compatibility");
5477
5478   // -fms-compatibility-version=18.00 is default.
5479   VersionTuple MSVT = visualstudio::getMSVCVersion(
5480       &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
5481   if (!MSVT.empty())
5482     CmdArgs.push_back(
5483         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5484
5485   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5486   if (ImplyVCPPCXXVer) {
5487     StringRef LanguageStandard;
5488     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
5489       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
5490                              .Case("c++14", "-std=c++14")
5491                              .Case("c++latest", "-std=c++1z")
5492                              .Default("");
5493       if (LanguageStandard.empty())
5494         D.Diag(clang::diag::warn_drv_unused_argument)
5495             << StdArg->getAsString(Args);
5496     }
5497
5498     if (LanguageStandard.empty()) {
5499       if (IsMSVC2015Compatible)
5500         LanguageStandard = "-std=c++14";
5501       else
5502         LanguageStandard = "-std=c++11";
5503     }
5504
5505     CmdArgs.push_back(LanguageStandard.data());
5506   }
5507
5508   // -fno-borland-extensions is default.
5509   if (Args.hasFlag(options::OPT_fborland_extensions,
5510                    options::OPT_fno_borland_extensions, false))
5511     CmdArgs.push_back("-fborland-extensions");
5512
5513   // -fno-declspec is default, except for PS4.
5514   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5515                    getToolChain().getTriple().isPS4()))
5516     CmdArgs.push_back("-fdeclspec");
5517   else if (Args.hasArg(options::OPT_fno_declspec))
5518     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5519
5520   // -fthreadsafe-static is default, except for MSVC compatibility versions less
5521   // than 19.
5522   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5523                     options::OPT_fno_threadsafe_statics,
5524                     !IsWindowsMSVC || IsMSVC2015Compatible))
5525     CmdArgs.push_back("-fno-threadsafe-statics");
5526
5527   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5528   // needs it.
5529   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5530                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5531     CmdArgs.push_back("-fdelayed-template-parsing");
5532
5533   // -fgnu-keywords default varies depending on language; only pass if
5534   // specified.
5535   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5536                                options::OPT_fno_gnu_keywords))
5537     A->render(Args, CmdArgs);
5538
5539   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5540                    false))
5541     CmdArgs.push_back("-fgnu89-inline");
5542
5543   if (Args.hasArg(options::OPT_fno_inline))
5544     CmdArgs.push_back("-fno-inline");
5545
5546   if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
5547                                        options::OPT_finline_hint_functions,
5548                                        options::OPT_fno_inline_functions))
5549     InlineArg->render(Args, CmdArgs);
5550
5551   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5552
5553   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5554   // legacy is the default. Except for deployment taget of 10.5,
5555   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5556   // gets ignored silently.
5557   if (objcRuntime.isNonFragile()) {
5558     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5559                       options::OPT_fno_objc_legacy_dispatch,
5560                       objcRuntime.isLegacyDispatchDefaultForArch(
5561                           getToolChain().getArch()))) {
5562       if (getToolChain().UseObjCMixedDispatch())
5563         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5564       else
5565         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5566     }
5567   }
5568
5569   // When ObjectiveC legacy runtime is in effect on MacOSX,
5570   // turn on the option to do Array/Dictionary subscripting
5571   // by default.
5572   if (getToolChain().getArch() == llvm::Triple::x86 &&
5573       getToolChain().getTriple().isMacOSX() &&
5574       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5575       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5576       objcRuntime.isNeXTFamily())
5577     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5578
5579   // -fencode-extended-block-signature=1 is default.
5580   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5581     CmdArgs.push_back("-fencode-extended-block-signature");
5582   }
5583
5584   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5585   // NOTE: This logic is duplicated in ToolChains.cpp.
5586   bool ARC = isObjCAutoRefCount(Args);
5587   if (ARC) {
5588     getToolChain().CheckObjCARC();
5589
5590     CmdArgs.push_back("-fobjc-arc");
5591
5592     // FIXME: It seems like this entire block, and several around it should be
5593     // wrapped in isObjC, but for now we just use it here as this is where it
5594     // was being used previously.
5595     if (types::isCXX(InputType) && types::isObjC(InputType)) {
5596       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5597         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5598       else
5599         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5600     }
5601
5602     // Allow the user to enable full exceptions code emission.
5603     // We define off for Objective-CC, on for Objective-C++.
5604     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5605                      options::OPT_fno_objc_arc_exceptions,
5606                      /*default*/ types::isCXX(InputType)))
5607       CmdArgs.push_back("-fobjc-arc-exceptions");
5608
5609   }
5610
5611   // -fobjc-infer-related-result-type is the default, except in the Objective-C
5612   // rewriter.
5613   if (rewriteKind != RK_None)
5614     CmdArgs.push_back("-fno-objc-infer-related-result-type");
5615
5616   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5617   // takes precedence.
5618   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5619   if (!GCArg)
5620     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5621   if (GCArg) {
5622     if (ARC) {
5623       D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5624     } else if (getToolChain().SupportsObjCGC()) {
5625       GCArg->render(Args, CmdArgs);
5626     } else {
5627       // FIXME: We should move this to a hard error.
5628       D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5629     }
5630   }
5631
5632   // Pass down -fobjc-weak or -fno-objc-weak if present.
5633   if (types::isObjC(InputType)) {
5634     auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5635                                    options::OPT_fno_objc_weak);
5636     if (!WeakArg) {
5637       // nothing to do
5638     } else if (GCArg) {
5639       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5640         D.Diag(diag::err_objc_weak_with_gc);
5641     } else if (!objcRuntime.allowsWeak()) {
5642       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5643         D.Diag(diag::err_objc_weak_unsupported);
5644     } else {
5645       WeakArg->render(Args, CmdArgs);
5646     }
5647   }
5648
5649   if (Args.hasFlag(options::OPT_fapplication_extension,
5650                    options::OPT_fno_application_extension, false))
5651     CmdArgs.push_back("-fapplication-extension");
5652
5653   // Handle GCC-style exception args.
5654   if (!C.getDriver().IsCLMode())
5655     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5656                      CmdArgs);
5657
5658   if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
5659       getToolChain().UseSjLjExceptions(Args))
5660     CmdArgs.push_back("-fsjlj-exceptions");
5661
5662   // C++ "sane" operator new.
5663   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5664                     options::OPT_fno_assume_sane_operator_new))
5665     CmdArgs.push_back("-fno-assume-sane-operator-new");
5666
5667   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5668   // most platforms.
5669   if (Args.hasFlag(options::OPT_fsized_deallocation,
5670                    options::OPT_fno_sized_deallocation, false))
5671     CmdArgs.push_back("-fsized-deallocation");
5672
5673   // -fconstant-cfstrings is default, and may be subject to argument translation
5674   // on Darwin.
5675   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5676                     options::OPT_fno_constant_cfstrings) ||
5677       !Args.hasFlag(options::OPT_mconstant_cfstrings,
5678                     options::OPT_mno_constant_cfstrings))
5679     CmdArgs.push_back("-fno-constant-cfstrings");
5680
5681   // -fshort-wchar default varies depending on platform; only
5682   // pass if specified.
5683   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5684                                options::OPT_fno_short_wchar))
5685     A->render(Args, CmdArgs);
5686
5687   // -fno-pascal-strings is default, only pass non-default.
5688   if (Args.hasFlag(options::OPT_fpascal_strings,
5689                    options::OPT_fno_pascal_strings, false))
5690     CmdArgs.push_back("-fpascal-strings");
5691
5692   // Honor -fpack-struct= and -fpack-struct, if given. Note that
5693   // -fno-pack-struct doesn't apply to -fpack-struct=.
5694   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5695     std::string PackStructStr = "-fpack-struct=";
5696     PackStructStr += A->getValue();
5697     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5698   } else if (Args.hasFlag(options::OPT_fpack_struct,
5699                           options::OPT_fno_pack_struct, false)) {
5700     CmdArgs.push_back("-fpack-struct=1");
5701   }
5702
5703   // Handle -fmax-type-align=N and -fno-type-align
5704   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5705   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5706     if (!SkipMaxTypeAlign) {
5707       std::string MaxTypeAlignStr = "-fmax-type-align=";
5708       MaxTypeAlignStr += A->getValue();
5709       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5710     }
5711   } else if (getToolChain().getTriple().isOSDarwin()) {
5712     if (!SkipMaxTypeAlign) {
5713       std::string MaxTypeAlignStr = "-fmax-type-align=16";
5714       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5715     }
5716   }
5717
5718   // -fcommon is the default unless compiling kernel code or the target says so
5719   bool NoCommonDefault =
5720       KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5721   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5722                     !NoCommonDefault))
5723     CmdArgs.push_back("-fno-common");
5724
5725   // -fsigned-bitfields is default, and clang doesn't yet support
5726   // -funsigned-bitfields.
5727   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5728                     options::OPT_funsigned_bitfields))
5729     D.Diag(diag::warn_drv_clang_unsupported)
5730         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5731
5732   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5733   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5734     D.Diag(diag::err_drv_clang_unsupported)
5735         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5736
5737   // -finput_charset=UTF-8 is default. Reject others
5738   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5739     StringRef value = inputCharset->getValue();
5740     if (value != "UTF-8")
5741       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5742                                           << value;
5743   }
5744
5745   // -fexec_charset=UTF-8 is default. Reject others
5746   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5747     StringRef value = execCharset->getValue();
5748     if (value != "UTF-8")
5749       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5750                                           << value;
5751   }
5752
5753   // -fcaret-diagnostics is default.
5754   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5755                     options::OPT_fno_caret_diagnostics, true))
5756     CmdArgs.push_back("-fno-caret-diagnostics");
5757
5758   // -fdiagnostics-fixit-info is default, only pass non-default.
5759   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5760                     options::OPT_fno_diagnostics_fixit_info))
5761     CmdArgs.push_back("-fno-diagnostics-fixit-info");
5762
5763   // Enable -fdiagnostics-show-option by default.
5764   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5765                    options::OPT_fno_diagnostics_show_option))
5766     CmdArgs.push_back("-fdiagnostics-show-option");
5767
5768   if (const Arg *A =
5769           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5770     CmdArgs.push_back("-fdiagnostics-show-category");
5771     CmdArgs.push_back(A->getValue());
5772   }
5773
5774   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5775     CmdArgs.push_back("-fdiagnostics-format");
5776     CmdArgs.push_back(A->getValue());
5777   }
5778
5779   if (Arg *A = Args.getLastArg(
5780           options::OPT_fdiagnostics_show_note_include_stack,
5781           options::OPT_fno_diagnostics_show_note_include_stack)) {
5782     if (A->getOption().matches(
5783             options::OPT_fdiagnostics_show_note_include_stack))
5784       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5785     else
5786       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5787   }
5788
5789   // Color diagnostics are parsed by the driver directly from argv
5790   // and later re-parsed to construct this job; claim any possible
5791   // color diagnostic here to avoid warn_drv_unused_argument and
5792   // diagnose bad OPT_fdiagnostics_color_EQ values.
5793   for (Arg *A : Args) {
5794     const Option &O = A->getOption();
5795     if (!O.matches(options::OPT_fcolor_diagnostics) &&
5796         !O.matches(options::OPT_fdiagnostics_color) &&
5797         !O.matches(options::OPT_fno_color_diagnostics) &&
5798         !O.matches(options::OPT_fno_diagnostics_color) &&
5799         !O.matches(options::OPT_fdiagnostics_color_EQ))
5800       continue;
5801     if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
5802       StringRef Value(A->getValue());
5803       if (Value != "always" && Value != "never" && Value != "auto")
5804         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5805               << ("-fdiagnostics-color=" + Value).str();
5806     }
5807     A->claim();
5808   }
5809   if (D.getDiags().getDiagnosticOptions().ShowColors)
5810     CmdArgs.push_back("-fcolor-diagnostics");
5811
5812   if (Args.hasArg(options::OPT_fansi_escape_codes))
5813     CmdArgs.push_back("-fansi-escape-codes");
5814
5815   if (!Args.hasFlag(options::OPT_fshow_source_location,
5816                     options::OPT_fno_show_source_location))
5817     CmdArgs.push_back("-fno-show-source-location");
5818
5819   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5820                     true))
5821     CmdArgs.push_back("-fno-show-column");
5822
5823   if (!Args.hasFlag(options::OPT_fspell_checking,
5824                     options::OPT_fno_spell_checking))
5825     CmdArgs.push_back("-fno-spell-checking");
5826
5827   // -fno-asm-blocks is default.
5828   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5829                    false))
5830     CmdArgs.push_back("-fasm-blocks");
5831
5832   // -fgnu-inline-asm is default.
5833   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5834                     options::OPT_fno_gnu_inline_asm, true))
5835     CmdArgs.push_back("-fno-gnu-inline-asm");
5836
5837   // Enable vectorization per default according to the optimization level
5838   // selected. For optimization levels that want vectorization we use the alias
5839   // option to simplify the hasFlag logic.
5840   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5841   OptSpecifier VectorizeAliasOption =
5842       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5843   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5844                    options::OPT_fno_vectorize, EnableVec))
5845     CmdArgs.push_back("-vectorize-loops");
5846
5847   // -fslp-vectorize is enabled based on the optimization level selected.
5848   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5849   OptSpecifier SLPVectAliasOption =
5850       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5851   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5852                    options::OPT_fno_slp_vectorize, EnableSLPVec))
5853     CmdArgs.push_back("-vectorize-slp");
5854
5855   // -fno-slp-vectorize-aggressive is default.
5856   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5857                    options::OPT_fno_slp_vectorize_aggressive, false))
5858     CmdArgs.push_back("-vectorize-slp-aggressive");
5859
5860   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5861     A->render(Args, CmdArgs);
5862
5863   if (Arg *A = Args.getLastArg(
5864           options::OPT_fsanitize_undefined_strip_path_components_EQ))
5865     A->render(Args, CmdArgs);
5866
5867   // -fdollars-in-identifiers default varies depending on platform and
5868   // language; only pass if specified.
5869   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5870                                options::OPT_fno_dollars_in_identifiers)) {
5871     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5872       CmdArgs.push_back("-fdollars-in-identifiers");
5873     else
5874       CmdArgs.push_back("-fno-dollars-in-identifiers");
5875   }
5876
5877   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5878   // practical purposes.
5879   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5880                                options::OPT_fno_unit_at_a_time)) {
5881     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5882       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5883   }
5884
5885   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5886                    options::OPT_fno_apple_pragma_pack, false))
5887     CmdArgs.push_back("-fapple-pragma-pack");
5888
5889   // le32-specific flags:
5890   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
5891   //                     by default.
5892   if (getToolChain().getArch() == llvm::Triple::le32) {
5893     CmdArgs.push_back("-fno-math-builtin");
5894   }
5895
5896 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5897 //
5898 // FIXME: Now that PR4941 has been fixed this can be enabled.
5899 #if 0
5900   if (getToolChain().getTriple().isOSDarwin() &&
5901       (getToolChain().getArch() == llvm::Triple::arm ||
5902        getToolChain().getArch() == llvm::Triple::thumb)) {
5903     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5904       CmdArgs.push_back("-fno-builtin-strcat");
5905     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5906       CmdArgs.push_back("-fno-builtin-strcpy");
5907   }
5908 #endif
5909
5910   // Enable rewrite includes if the user's asked for it or if we're generating
5911   // diagnostics.
5912   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5913   // nice to enable this when doing a crashdump for modules as well.
5914   if (Args.hasFlag(options::OPT_frewrite_includes,
5915                    options::OPT_fno_rewrite_includes, false) ||
5916       (C.isForDiagnostics() && !HaveModules))
5917     CmdArgs.push_back("-frewrite-includes");
5918
5919   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5920   if (Arg *A = Args.getLastArg(options::OPT_traditional,
5921                                options::OPT_traditional_cpp)) {
5922     if (isa<PreprocessJobAction>(JA))
5923       CmdArgs.push_back("-traditional-cpp");
5924     else
5925       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5926   }
5927
5928   Args.AddLastArg(CmdArgs, options::OPT_dM);
5929   Args.AddLastArg(CmdArgs, options::OPT_dD);
5930
5931   // Handle serialized diagnostics.
5932   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5933     CmdArgs.push_back("-serialize-diagnostic-file");
5934     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5935   }
5936
5937   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5938     CmdArgs.push_back("-fretain-comments-from-system-headers");
5939
5940   // Forward -fcomment-block-commands to -cc1.
5941   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5942   // Forward -fparse-all-comments to -cc1.
5943   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5944
5945   // Turn -fplugin=name.so into -load name.so
5946   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5947     CmdArgs.push_back("-load");
5948     CmdArgs.push_back(A->getValue());
5949     A->claim();
5950   }
5951
5952   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5953   // parser.
5954   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5955   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5956     A->claim();
5957
5958     // We translate this by hand to the -cc1 argument, since nightly test uses
5959     // it and developers have been trained to spell it with -mllvm.
5960     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5961       CmdArgs.push_back("-disable-llvm-optzns");
5962     } else
5963       A->render(Args, CmdArgs);
5964   }
5965
5966   // With -save-temps, we want to save the unoptimized bitcode output from the
5967   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5968   // by the frontend.
5969   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5970   // has slightly different breakdown between stages.
5971   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5972   // pristine IR generated by the frontend. Ideally, a new compile action should
5973   // be added so both IR can be captured.
5974   if (C.getDriver().isSaveTempsEnabled() &&
5975       !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
5976     CmdArgs.push_back("-disable-llvm-passes");
5977
5978   if (Output.getType() == types::TY_Dependencies) {
5979     // Handled with other dependency code.
5980   } else if (Output.isFilename()) {
5981     CmdArgs.push_back("-o");
5982     CmdArgs.push_back(Output.getFilename());
5983   } else {
5984     assert(Output.isNothing() && "Invalid output.");
5985   }
5986
5987   addDashXForInput(Args, Input, CmdArgs);
5988
5989   if (Input.isFilename())
5990     CmdArgs.push_back(Input.getFilename());
5991   else
5992     Input.getInputArg().renderAsInput(Args, CmdArgs);
5993
5994   Args.AddAllArgs(CmdArgs, options::OPT_undef);
5995
5996   const char *Exec = getToolChain().getDriver().getClangProgramPath();
5997
5998   // Optionally embed the -cc1 level arguments into the debug info, for build
5999   // analysis.
6000   if (getToolChain().UseDwarfDebugFlags()) {
6001     ArgStringList OriginalArgs;
6002     for (const auto &Arg : Args)
6003       Arg->render(Args, OriginalArgs);
6004
6005     SmallString<256> Flags;
6006     Flags += Exec;
6007     for (const char *OriginalArg : OriginalArgs) {
6008       SmallString<128> EscapedArg;
6009       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6010       Flags += " ";
6011       Flags += EscapedArg;
6012     }
6013     CmdArgs.push_back("-dwarf-debug-flags");
6014     CmdArgs.push_back(Args.MakeArgString(Flags));
6015   }
6016
6017   // Add the split debug info name to the command lines here so we
6018   // can propagate it to the backend.
6019   bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
6020                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6021                      isa<BackendJobAction>(JA));
6022   const char *SplitDwarfOut;
6023   if (SplitDwarf) {
6024     CmdArgs.push_back("-split-dwarf-file");
6025     SplitDwarfOut = SplitDebugName(Args, Input);
6026     CmdArgs.push_back(SplitDwarfOut);
6027   }
6028
6029   // Host-side cuda compilation receives device-side outputs as Inputs[1...].
6030   // Include them with -fcuda-include-gpubinary.
6031   if (IsCuda && Inputs.size() > 1)
6032     for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
6033       CmdArgs.push_back("-fcuda-include-gpubinary");
6034       CmdArgs.push_back(I->getFilename());
6035     }
6036
6037   bool WholeProgramVTables =
6038       Args.hasFlag(options::OPT_fwhole_program_vtables,
6039                    options::OPT_fno_whole_program_vtables, false);
6040   if (WholeProgramVTables) {
6041     if (!D.isUsingLTO())
6042       D.Diag(diag::err_drv_argument_only_allowed_with)
6043           << "-fwhole-program-vtables"
6044           << "-flto";
6045     CmdArgs.push_back("-fwhole-program-vtables");
6046   }
6047
6048   // Finally add the compile command to the compilation.
6049   if (Args.hasArg(options::OPT__SLASH_fallback) &&
6050       Output.getType() == types::TY_Object &&
6051       (InputType == types::TY_C || InputType == types::TY_CXX)) {
6052     auto CLCommand =
6053         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
6054     C.addCommand(llvm::make_unique<FallbackCommand>(
6055         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
6056   } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
6057              isa<PrecompileJobAction>(JA)) {
6058     // In /fallback builds, run the main compilation even if the pch generation
6059     // fails, so that the main compilation's fallback to cl.exe runs.
6060     C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
6061                                                         CmdArgs, Inputs));
6062   } else {
6063     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6064   }
6065
6066   // Handle the debug info splitting at object creation time if we're
6067   // creating an object.
6068   // TODO: Currently only works on linux with newer objcopy.
6069   if (SplitDwarf && Output.getType() == types::TY_Object)
6070     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
6071
6072   if (Arg *A = Args.getLastArg(options::OPT_pg))
6073     if (Args.hasArg(options::OPT_fomit_frame_pointer))
6074       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6075                                                       << A->getAsString(Args);
6076
6077   // Claim some arguments which clang supports automatically.
6078
6079   // -fpch-preprocess is used with gcc to add a special marker in the output to
6080   // include the PCH file. Clang's PTH solution is completely transparent, so we
6081   // do not need to deal with it at all.
6082   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6083
6084   // Claim some arguments which clang doesn't support, but we don't
6085   // care to warn the user about.
6086   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6087   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6088
6089   // Disable warnings for clang -E -emit-llvm foo.c
6090   Args.ClaimAllArgs(options::OPT_emit_llvm);
6091 }
6092
6093 /// Add options related to the Objective-C runtime/ABI.
6094 ///
6095 /// Returns true if the runtime is non-fragile.
6096 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6097                                       ArgStringList &cmdArgs,
6098                                       RewriteKind rewriteKind) const {
6099   // Look for the controlling runtime option.
6100   Arg *runtimeArg =
6101       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6102                       options::OPT_fobjc_runtime_EQ);
6103
6104   // Just forward -fobjc-runtime= to the frontend.  This supercedes
6105   // options about fragility.
6106   if (runtimeArg &&
6107       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6108     ObjCRuntime runtime;
6109     StringRef value = runtimeArg->getValue();
6110     if (runtime.tryParse(value)) {
6111       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6112           << value;
6113     }
6114
6115     runtimeArg->render(args, cmdArgs);
6116     return runtime;
6117   }
6118
6119   // Otherwise, we'll need the ABI "version".  Version numbers are
6120   // slightly confusing for historical reasons:
6121   //   1 - Traditional "fragile" ABI
6122   //   2 - Non-fragile ABI, version 1
6123   //   3 - Non-fragile ABI, version 2
6124   unsigned objcABIVersion = 1;
6125   // If -fobjc-abi-version= is present, use that to set the version.
6126   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6127     StringRef value = abiArg->getValue();
6128     if (value == "1")
6129       objcABIVersion = 1;
6130     else if (value == "2")
6131       objcABIVersion = 2;
6132     else if (value == "3")
6133       objcABIVersion = 3;
6134     else
6135       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6136   } else {
6137     // Otherwise, determine if we are using the non-fragile ABI.
6138     bool nonFragileABIIsDefault =
6139         (rewriteKind == RK_NonFragile ||
6140          (rewriteKind == RK_None &&
6141           getToolChain().IsObjCNonFragileABIDefault()));
6142     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6143                      options::OPT_fno_objc_nonfragile_abi,
6144                      nonFragileABIIsDefault)) {
6145 // Determine the non-fragile ABI version to use.
6146 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6147       unsigned nonFragileABIVersion = 1;
6148 #else
6149       unsigned nonFragileABIVersion = 2;
6150 #endif
6151
6152       if (Arg *abiArg =
6153               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6154         StringRef value = abiArg->getValue();
6155         if (value == "1")
6156           nonFragileABIVersion = 1;
6157         else if (value == "2")
6158           nonFragileABIVersion = 2;
6159         else
6160           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6161               << value;
6162       }
6163
6164       objcABIVersion = 1 + nonFragileABIVersion;
6165     } else {
6166       objcABIVersion = 1;
6167     }
6168   }
6169
6170   // We don't actually care about the ABI version other than whether
6171   // it's non-fragile.
6172   bool isNonFragile = objcABIVersion != 1;
6173
6174   // If we have no runtime argument, ask the toolchain for its default runtime.
6175   // However, the rewriter only really supports the Mac runtime, so assume that.
6176   ObjCRuntime runtime;
6177   if (!runtimeArg) {
6178     switch (rewriteKind) {
6179     case RK_None:
6180       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6181       break;
6182     case RK_Fragile:
6183       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6184       break;
6185     case RK_NonFragile:
6186       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6187       break;
6188     }
6189
6190     // -fnext-runtime
6191   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6192     // On Darwin, make this use the default behavior for the toolchain.
6193     if (getToolChain().getTriple().isOSDarwin()) {
6194       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6195
6196       // Otherwise, build for a generic macosx port.
6197     } else {
6198       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6199     }
6200
6201     // -fgnu-runtime
6202   } else {
6203     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6204     // Legacy behaviour is to target the gnustep runtime if we are in
6205     // non-fragile mode or the GCC runtime in fragile mode.
6206     if (isNonFragile)
6207       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
6208     else
6209       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6210   }
6211
6212   cmdArgs.push_back(
6213       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6214   return runtime;
6215 }
6216
6217 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6218   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6219   I += HaveDash;
6220   return !HaveDash;
6221 }
6222
6223 namespace {
6224 struct EHFlags {
6225   bool Synch = false;
6226   bool Asynch = false;
6227   bool NoUnwindC = false;
6228 };
6229 } // end anonymous namespace
6230
6231 /// /EH controls whether to run destructor cleanups when exceptions are
6232 /// thrown.  There are three modifiers:
6233 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
6234 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
6235 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
6236 /// - c: Assume that extern "C" functions are implicitly nounwind.
6237 /// The default is /EHs-c-, meaning cleanups are disabled.
6238 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
6239   EHFlags EH;
6240
6241   std::vector<std::string> EHArgs =
6242       Args.getAllArgValues(options::OPT__SLASH_EH);
6243   for (auto EHVal : EHArgs) {
6244     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
6245       switch (EHVal[I]) {
6246       case 'a':
6247         EH.Asynch = maybeConsumeDash(EHVal, I);
6248         if (EH.Asynch)
6249           EH.Synch = false;
6250         continue;
6251       case 'c':
6252         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
6253         continue;
6254       case 's':
6255         EH.Synch = maybeConsumeDash(EHVal, I);
6256         if (EH.Synch)
6257           EH.Asynch = false;
6258         continue;
6259       default:
6260         break;
6261       }
6262       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
6263       break;
6264     }
6265   }
6266   // The /GX, /GX- flags are only processed if there are not /EH flags.
6267   // The default is that /GX is not specified.
6268   if (EHArgs.empty() &&
6269       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
6270                    /*default=*/false)) {
6271     EH.Synch = true;
6272     EH.NoUnwindC = true;
6273   }
6274
6275   return EH;
6276 }
6277
6278 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
6279                            ArgStringList &CmdArgs,
6280                            codegenoptions::DebugInfoKind *DebugInfoKind,
6281                            bool *EmitCodeView) const {
6282   unsigned RTOptionID = options::OPT__SLASH_MT;
6283
6284   if (Args.hasArg(options::OPT__SLASH_LDd))
6285     // The /LDd option implies /MTd. The dependent lib part can be overridden,
6286     // but defining _DEBUG is sticky.
6287     RTOptionID = options::OPT__SLASH_MTd;
6288
6289   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
6290     RTOptionID = A->getOption().getID();
6291
6292   StringRef FlagForCRT;
6293   switch (RTOptionID) {
6294   case options::OPT__SLASH_MD:
6295     if (Args.hasArg(options::OPT__SLASH_LDd))
6296       CmdArgs.push_back("-D_DEBUG");
6297     CmdArgs.push_back("-D_MT");
6298     CmdArgs.push_back("-D_DLL");
6299     FlagForCRT = "--dependent-lib=msvcrt";
6300     break;
6301   case options::OPT__SLASH_MDd:
6302     CmdArgs.push_back("-D_DEBUG");
6303     CmdArgs.push_back("-D_MT");
6304     CmdArgs.push_back("-D_DLL");
6305     FlagForCRT = "--dependent-lib=msvcrtd";
6306     break;
6307   case options::OPT__SLASH_MT:
6308     if (Args.hasArg(options::OPT__SLASH_LDd))
6309       CmdArgs.push_back("-D_DEBUG");
6310     CmdArgs.push_back("-D_MT");
6311     CmdArgs.push_back("-flto-visibility-public-std");
6312     FlagForCRT = "--dependent-lib=libcmt";
6313     break;
6314   case options::OPT__SLASH_MTd:
6315     CmdArgs.push_back("-D_DEBUG");
6316     CmdArgs.push_back("-D_MT");
6317     CmdArgs.push_back("-flto-visibility-public-std");
6318     FlagForCRT = "--dependent-lib=libcmtd";
6319     break;
6320   default:
6321     llvm_unreachable("Unexpected option ID.");
6322   }
6323
6324   if (Args.hasArg(options::OPT__SLASH_Zl)) {
6325     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
6326   } else {
6327     CmdArgs.push_back(FlagForCRT.data());
6328
6329     // This provides POSIX compatibility (maps 'open' to '_open'), which most
6330     // users want.  The /Za flag to cl.exe turns this off, but it's not
6331     // implemented in clang.
6332     CmdArgs.push_back("--dependent-lib=oldnames");
6333   }
6334
6335   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
6336   // would produce interleaved output, so ignore /showIncludes in such cases.
6337   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
6338     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
6339       A->render(Args, CmdArgs);
6340
6341   // This controls whether or not we emit RTTI data for polymorphic types.
6342   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
6343                    /*default=*/false))
6344     CmdArgs.push_back("-fno-rtti-data");
6345
6346   // This controls whether or not we emit stack-protector instrumentation.
6347   // In MSVC, Buffer Security Check (/GS) is on by default.
6348   if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
6349                    /*default=*/true)) {
6350     CmdArgs.push_back("-stack-protector");
6351     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
6352   }
6353
6354   // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
6355   if (Arg *DebugInfoArg =
6356           Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
6357                           options::OPT_gline_tables_only)) {
6358     *EmitCodeView = true;
6359     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
6360       *DebugInfoKind = codegenoptions::LimitedDebugInfo;
6361     else
6362       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
6363     CmdArgs.push_back("-gcodeview");
6364   } else {
6365     *EmitCodeView = false;
6366   }
6367
6368   const Driver &D = getToolChain().getDriver();
6369   EHFlags EH = parseClangCLEHFlags(D, Args);
6370   if (EH.Synch || EH.Asynch) {
6371     if (types::isCXX(InputType))
6372       CmdArgs.push_back("-fcxx-exceptions");
6373     CmdArgs.push_back("-fexceptions");
6374   }
6375   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
6376     CmdArgs.push_back("-fexternc-nounwind");
6377
6378   // /EP should expand to -E -P.
6379   if (Args.hasArg(options::OPT__SLASH_EP)) {
6380     CmdArgs.push_back("-E");
6381     CmdArgs.push_back("-P");
6382   }
6383
6384   unsigned VolatileOptionID;
6385   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
6386       getToolChain().getArch() == llvm::Triple::x86)
6387     VolatileOptionID = options::OPT__SLASH_volatile_ms;
6388   else
6389     VolatileOptionID = options::OPT__SLASH_volatile_iso;
6390
6391   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
6392     VolatileOptionID = A->getOption().getID();
6393
6394   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
6395     CmdArgs.push_back("-fms-volatile");
6396
6397   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
6398   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
6399   if (MostGeneralArg && BestCaseArg)
6400     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6401         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
6402
6403   if (MostGeneralArg) {
6404     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
6405     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
6406     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
6407
6408     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
6409     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
6410     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
6411       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6412           << FirstConflict->getAsString(Args)
6413           << SecondConflict->getAsString(Args);
6414
6415     if (SingleArg)
6416       CmdArgs.push_back("-fms-memptr-rep=single");
6417     else if (MultipleArg)
6418       CmdArgs.push_back("-fms-memptr-rep=multiple");
6419     else
6420       CmdArgs.push_back("-fms-memptr-rep=virtual");
6421   }
6422
6423   if (Args.getLastArg(options::OPT__SLASH_Gd))
6424      CmdArgs.push_back("-fdefault-calling-conv=cdecl");
6425   else if (Args.getLastArg(options::OPT__SLASH_Gr))
6426      CmdArgs.push_back("-fdefault-calling-conv=fastcall");
6427   else if (Args.getLastArg(options::OPT__SLASH_Gz))
6428      CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6429   else if (Args.getLastArg(options::OPT__SLASH_Gv))
6430      CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
6431
6432   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
6433     A->render(Args, CmdArgs);
6434
6435   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6436     CmdArgs.push_back("-fdiagnostics-format");
6437     if (Args.hasArg(options::OPT__SLASH_fallback))
6438       CmdArgs.push_back("msvc-fallback");
6439     else
6440       CmdArgs.push_back("msvc");
6441   }
6442 }
6443
6444 visualstudio::Compiler *Clang::getCLFallback() const {
6445   if (!CLFallback)
6446     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6447   return CLFallback.get();
6448 }
6449
6450 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6451                                 ArgStringList &CmdArgs) const {
6452   StringRef CPUName;
6453   StringRef ABIName;
6454   const llvm::Triple &Triple = getToolChain().getTriple();
6455   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6456
6457   CmdArgs.push_back("-target-abi");
6458   CmdArgs.push_back(ABIName.data());
6459 }
6460
6461 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6462                            const InputInfo &Output, const InputInfoList &Inputs,
6463                            const ArgList &Args,
6464                            const char *LinkingOutput) const {
6465   ArgStringList CmdArgs;
6466
6467   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6468   const InputInfo &Input = Inputs[0];
6469
6470   std::string TripleStr =
6471       getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
6472   const llvm::Triple Triple(TripleStr);
6473
6474   // Don't warn about "clang -w -c foo.s"
6475   Args.ClaimAllArgs(options::OPT_w);
6476   // and "clang -emit-llvm -c foo.s"
6477   Args.ClaimAllArgs(options::OPT_emit_llvm);
6478
6479   claimNoWarnArgs(Args);
6480
6481   // Invoke ourselves in -cc1as mode.
6482   //
6483   // FIXME: Implement custom jobs for internal actions.
6484   CmdArgs.push_back("-cc1as");
6485
6486   // Add the "effective" target triple.
6487   CmdArgs.push_back("-triple");
6488   CmdArgs.push_back(Args.MakeArgString(TripleStr));
6489
6490   // Set the output mode, we currently only expect to be used as a real
6491   // assembler.
6492   CmdArgs.push_back("-filetype");
6493   CmdArgs.push_back("obj");
6494
6495   // Set the main file name, so that debug info works even with
6496   // -save-temps or preprocessed assembly.
6497   CmdArgs.push_back("-main-file-name");
6498   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6499
6500   // Add the target cpu
6501   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6502   if (!CPU.empty()) {
6503     CmdArgs.push_back("-target-cpu");
6504     CmdArgs.push_back(Args.MakeArgString(CPU));
6505   }
6506
6507   // Add the target features
6508   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6509
6510   // Ignore explicit -force_cpusubtype_ALL option.
6511   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6512
6513   // Pass along any -I options so we get proper .include search paths.
6514   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6515
6516   // Determine the original source input.
6517   const Action *SourceAction = &JA;
6518   while (SourceAction->getKind() != Action::InputClass) {
6519     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6520     SourceAction = SourceAction->getInputs()[0];
6521   }
6522
6523   // Forward -g and handle debug info related flags, assuming we are dealing
6524   // with an actual assembly file.
6525   bool WantDebug = false;
6526   unsigned DwarfVersion = 0;
6527   Args.ClaimAllArgs(options::OPT_g_Group);
6528   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6529     WantDebug = !A->getOption().matches(options::OPT_g0) &&
6530                 !A->getOption().matches(options::OPT_ggdb0);
6531     if (WantDebug)
6532       DwarfVersion = DwarfVersionNum(A->getSpelling());
6533   }
6534   if (DwarfVersion == 0)
6535     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6536
6537   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6538
6539   if (SourceAction->getType() == types::TY_Asm ||
6540       SourceAction->getType() == types::TY_PP_Asm) {
6541     // You might think that it would be ok to set DebugInfoKind outside of
6542     // the guard for source type, however there is a test which asserts
6543     // that some assembler invocation receives no -debug-info-kind,
6544     // and it's not clear whether that test is just overly restrictive.
6545     DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6546                                : codegenoptions::NoDebugInfo);
6547     // Add the -fdebug-compilation-dir flag if needed.
6548     addDebugCompDirArg(Args, CmdArgs);
6549
6550     // Set the AT_producer to the clang version when using the integrated
6551     // assembler on assembly source files.
6552     CmdArgs.push_back("-dwarf-debug-producer");
6553     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6554
6555     // And pass along -I options
6556     Args.AddAllArgs(CmdArgs, options::OPT_I);
6557   }
6558   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6559                           llvm::DebuggerKind::Default);
6560
6561   // Handle -fPIC et al -- the relocation-model affects the assembler
6562   // for some targets.
6563   llvm::Reloc::Model RelocationModel;
6564   unsigned PICLevel;
6565   bool IsPIE;
6566   std::tie(RelocationModel, PICLevel, IsPIE) =
6567       ParsePICArgs(getToolChain(), Triple, Args);
6568
6569   const char *RMName = RelocationModelName(RelocationModel);
6570   if (RMName) {
6571     CmdArgs.push_back("-mrelocation-model");
6572     CmdArgs.push_back(RMName);
6573   }
6574
6575   // Optionally embed the -cc1as level arguments into the debug info, for build
6576   // analysis.
6577   if (getToolChain().UseDwarfDebugFlags()) {
6578     ArgStringList OriginalArgs;
6579     for (const auto &Arg : Args)
6580       Arg->render(Args, OriginalArgs);
6581
6582     SmallString<256> Flags;
6583     const char *Exec = getToolChain().getDriver().getClangProgramPath();
6584     Flags += Exec;
6585     for (const char *OriginalArg : OriginalArgs) {
6586       SmallString<128> EscapedArg;
6587       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6588       Flags += " ";
6589       Flags += EscapedArg;
6590     }
6591     CmdArgs.push_back("-dwarf-debug-flags");
6592     CmdArgs.push_back(Args.MakeArgString(Flags));
6593   }
6594
6595   // FIXME: Add -static support, once we have it.
6596
6597   // Add target specific flags.
6598   switch (getToolChain().getArch()) {
6599   default:
6600     break;
6601
6602   case llvm::Triple::mips:
6603   case llvm::Triple::mipsel:
6604   case llvm::Triple::mips64:
6605   case llvm::Triple::mips64el:
6606     AddMIPSTargetArgs(Args, CmdArgs);
6607     break;
6608   }
6609
6610   // Consume all the warning flags. Usually this would be handled more
6611   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6612   // doesn't handle that so rather than warning about unused flags that are
6613   // actually used, we'll lie by omission instead.
6614   // FIXME: Stop lying and consume only the appropriate driver flags
6615   Args.ClaimAllArgs(options::OPT_W_Group);
6616
6617   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6618                                     getToolChain().getDriver());
6619
6620   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6621
6622   assert(Output.isFilename() && "Unexpected lipo output.");
6623   CmdArgs.push_back("-o");
6624   CmdArgs.push_back(Output.getFilename());
6625
6626   assert(Input.isFilename() && "Invalid input.");
6627   CmdArgs.push_back(Input.getFilename());
6628
6629   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6630   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6631
6632   // Handle the debug info splitting at object creation time if we're
6633   // creating an object.
6634   // TODO: Currently only works on linux with newer objcopy.
6635   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6636       getToolChain().getTriple().isOSLinux())
6637     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6638                    SplitDebugName(Args, Input));
6639 }
6640
6641 void GnuTool::anchor() {}
6642
6643 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6644                                const InputInfo &Output,
6645                                const InputInfoList &Inputs, const ArgList &Args,
6646                                const char *LinkingOutput) const {
6647   const Driver &D = getToolChain().getDriver();
6648   ArgStringList CmdArgs;
6649
6650   for (const auto &A : Args) {
6651     if (forwardToGCC(A->getOption())) {
6652       // It is unfortunate that we have to claim here, as this means
6653       // we will basically never report anything interesting for
6654       // platforms using a generic gcc, even if we are just using gcc
6655       // to get to the assembler.
6656       A->claim();
6657
6658       // Don't forward any -g arguments to assembly steps.
6659       if (isa<AssembleJobAction>(JA) &&
6660           A->getOption().matches(options::OPT_g_Group))
6661         continue;
6662
6663       // Don't forward any -W arguments to assembly and link steps.
6664       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6665           A->getOption().matches(options::OPT_W_Group))
6666         continue;
6667
6668       A->render(Args, CmdArgs);
6669     }
6670   }
6671
6672   RenderExtraToolArgs(JA, CmdArgs);
6673
6674   // If using a driver driver, force the arch.
6675   if (getToolChain().getTriple().isOSDarwin()) {
6676     CmdArgs.push_back("-arch");
6677     CmdArgs.push_back(
6678         Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6679   }
6680
6681   // Try to force gcc to match the tool chain we want, if we recognize
6682   // the arch.
6683   //
6684   // FIXME: The triple class should directly provide the information we want
6685   // here.
6686   switch (getToolChain().getArch()) {
6687   default:
6688     break;
6689   case llvm::Triple::x86:
6690   case llvm::Triple::ppc:
6691     CmdArgs.push_back("-m32");
6692     break;
6693   case llvm::Triple::x86_64:
6694   case llvm::Triple::ppc64:
6695   case llvm::Triple::ppc64le:
6696     CmdArgs.push_back("-m64");
6697     break;
6698   case llvm::Triple::sparcel:
6699     CmdArgs.push_back("-EL");
6700     break;
6701   }
6702
6703   if (Output.isFilename()) {
6704     CmdArgs.push_back("-o");
6705     CmdArgs.push_back(Output.getFilename());
6706   } else {
6707     assert(Output.isNothing() && "Unexpected output");
6708     CmdArgs.push_back("-fsyntax-only");
6709   }
6710
6711   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6712
6713   // Only pass -x if gcc will understand it; otherwise hope gcc
6714   // understands the suffix correctly. The main use case this would go
6715   // wrong in is for linker inputs if they happened to have an odd
6716   // suffix; really the only way to get this to happen is a command
6717   // like '-x foobar a.c' which will treat a.c like a linker input.
6718   //
6719   // FIXME: For the linker case specifically, can we safely convert
6720   // inputs into '-Wl,' options?
6721   for (const auto &II : Inputs) {
6722     // Don't try to pass LLVM or AST inputs to a generic gcc.
6723     if (types::isLLVMIR(II.getType()))
6724       D.Diag(diag::err_drv_no_linker_llvm_support)
6725           << getToolChain().getTripleString();
6726     else if (II.getType() == types::TY_AST)
6727       D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6728     else if (II.getType() == types::TY_ModuleFile)
6729       D.Diag(diag::err_drv_no_module_support)
6730           << getToolChain().getTripleString();
6731
6732     if (types::canTypeBeUserSpecified(II.getType())) {
6733       CmdArgs.push_back("-x");
6734       CmdArgs.push_back(types::getTypeName(II.getType()));
6735     }
6736
6737     if (II.isFilename())
6738       CmdArgs.push_back(II.getFilename());
6739     else {
6740       const Arg &A = II.getInputArg();
6741
6742       // Reverse translate some rewritten options.
6743       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6744         CmdArgs.push_back("-lstdc++");
6745         continue;
6746       }
6747
6748       // Don't render as input, we need gcc to do the translations.
6749       A.render(Args, CmdArgs);
6750     }
6751   }
6752
6753   const std::string &customGCCName = D.getCCCGenericGCCName();
6754   const char *GCCName;
6755   if (!customGCCName.empty())
6756     GCCName = customGCCName.c_str();
6757   else if (D.CCCIsCXX()) {
6758     GCCName = "g++";
6759   } else
6760     GCCName = "gcc";
6761
6762   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6763   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6764 }
6765
6766 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6767                                             ArgStringList &CmdArgs) const {
6768   CmdArgs.push_back("-E");
6769 }
6770
6771 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6772                                         ArgStringList &CmdArgs) const {
6773   const Driver &D = getToolChain().getDriver();
6774
6775   switch (JA.getType()) {
6776   // If -flto, etc. are present then make sure not to force assembly output.
6777   case types::TY_LLVM_IR:
6778   case types::TY_LTO_IR:
6779   case types::TY_LLVM_BC:
6780   case types::TY_LTO_BC:
6781     CmdArgs.push_back("-c");
6782     break;
6783   // We assume we've got an "integrated" assembler in that gcc will produce an
6784   // object file itself.
6785   case types::TY_Object:
6786     CmdArgs.push_back("-c");
6787     break;
6788   case types::TY_PP_Asm:
6789     CmdArgs.push_back("-S");
6790     break;
6791   case types::TY_Nothing:
6792     CmdArgs.push_back("-fsyntax-only");
6793     break;
6794   default:
6795     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6796   }
6797 }
6798
6799 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6800                                       ArgStringList &CmdArgs) const {
6801   // The types are (hopefully) good enough.
6802 }
6803
6804 // Hexagon tools start.
6805 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6806                                              ArgStringList &CmdArgs) const {
6807 }
6808
6809 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6810                                       const InputInfo &Output,
6811                                       const InputInfoList &Inputs,
6812                                       const ArgList &Args,
6813                                       const char *LinkingOutput) const {
6814   claimNoWarnArgs(Args);
6815
6816   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6817   const Driver &D = HTC.getDriver();
6818   ArgStringList CmdArgs;
6819
6820   std::string MArchString = "-march=hexagon";
6821   CmdArgs.push_back(Args.MakeArgString(MArchString));
6822
6823   RenderExtraToolArgs(JA, CmdArgs);
6824
6825   std::string AsName = "hexagon-llvm-mc";
6826   std::string MCpuString = "-mcpu=hexagon" +
6827         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6828   CmdArgs.push_back("-filetype=obj");
6829   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6830
6831   if (Output.isFilename()) {
6832     CmdArgs.push_back("-o");
6833     CmdArgs.push_back(Output.getFilename());
6834   } else {
6835     assert(Output.isNothing() && "Unexpected output");
6836     CmdArgs.push_back("-fsyntax-only");
6837   }
6838
6839   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6840     std::string N = llvm::utostr(G.getValue());
6841     CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6842   }
6843
6844   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6845
6846   // Only pass -x if gcc will understand it; otherwise hope gcc
6847   // understands the suffix correctly. The main use case this would go
6848   // wrong in is for linker inputs if they happened to have an odd
6849   // suffix; really the only way to get this to happen is a command
6850   // like '-x foobar a.c' which will treat a.c like a linker input.
6851   //
6852   // FIXME: For the linker case specifically, can we safely convert
6853   // inputs into '-Wl,' options?
6854   for (const auto &II : Inputs) {
6855     // Don't try to pass LLVM or AST inputs to a generic gcc.
6856     if (types::isLLVMIR(II.getType()))
6857       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6858           << HTC.getTripleString();
6859     else if (II.getType() == types::TY_AST)
6860       D.Diag(clang::diag::err_drv_no_ast_support)
6861           << HTC.getTripleString();
6862     else if (II.getType() == types::TY_ModuleFile)
6863       D.Diag(diag::err_drv_no_module_support)
6864           << HTC.getTripleString();
6865
6866     if (II.isFilename())
6867       CmdArgs.push_back(II.getFilename());
6868     else
6869       // Don't render as input, we need gcc to do the translations.
6870       // FIXME: What is this?
6871       II.getInputArg().render(Args, CmdArgs);
6872   }
6873
6874   auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6875   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6876 }
6877
6878 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6879                                           ArgStringList &CmdArgs) const {
6880 }
6881
6882 static void
6883 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6884                          const toolchains::HexagonToolChain &HTC,
6885                          const InputInfo &Output, const InputInfoList &Inputs,
6886                          const ArgList &Args, ArgStringList &CmdArgs,
6887                          const char *LinkingOutput) {
6888
6889   const Driver &D = HTC.getDriver();
6890
6891   //----------------------------------------------------------------------------
6892   //
6893   //----------------------------------------------------------------------------
6894   bool IsStatic = Args.hasArg(options::OPT_static);
6895   bool IsShared = Args.hasArg(options::OPT_shared);
6896   bool IsPIE = Args.hasArg(options::OPT_pie);
6897   bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6898   bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6899   bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6900   bool UseG0 = false;
6901   bool UseShared = IsShared && !IsStatic;
6902
6903   //----------------------------------------------------------------------------
6904   // Silence warnings for various options
6905   //----------------------------------------------------------------------------
6906   Args.ClaimAllArgs(options::OPT_g_Group);
6907   Args.ClaimAllArgs(options::OPT_emit_llvm);
6908   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6909                                      // handled somewhere else.
6910   Args.ClaimAllArgs(options::OPT_static_libgcc);
6911
6912   //----------------------------------------------------------------------------
6913   //
6914   //----------------------------------------------------------------------------
6915   if (Args.hasArg(options::OPT_s))
6916     CmdArgs.push_back("-s");
6917
6918   if (Args.hasArg(options::OPT_r))
6919     CmdArgs.push_back("-r");
6920
6921   for (const auto &Opt : HTC.ExtraOpts)
6922     CmdArgs.push_back(Opt.c_str());
6923
6924   CmdArgs.push_back("-march=hexagon");
6925   std::string CpuVer =
6926         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6927   std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6928   CmdArgs.push_back(Args.MakeArgString(MCpuString));
6929
6930   if (IsShared) {
6931     CmdArgs.push_back("-shared");
6932     // The following should be the default, but doing as hexagon-gcc does.
6933     CmdArgs.push_back("-call_shared");
6934   }
6935
6936   if (IsStatic)
6937     CmdArgs.push_back("-static");
6938
6939   if (IsPIE && !IsShared)
6940     CmdArgs.push_back("-pie");
6941
6942   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6943     std::string N = llvm::utostr(G.getValue());
6944     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6945     UseG0 = G.getValue() == 0;
6946   }
6947
6948   //----------------------------------------------------------------------------
6949   //
6950   //----------------------------------------------------------------------------
6951   CmdArgs.push_back("-o");
6952   CmdArgs.push_back(Output.getFilename());
6953
6954   //----------------------------------------------------------------------------
6955   // moslib
6956   //----------------------------------------------------------------------------
6957   std::vector<std::string> OsLibs;
6958   bool HasStandalone = false;
6959
6960   for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6961     A->claim();
6962     OsLibs.emplace_back(A->getValue());
6963     HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6964   }
6965   if (OsLibs.empty()) {
6966     OsLibs.push_back("standalone");
6967     HasStandalone = true;
6968   }
6969
6970   //----------------------------------------------------------------------------
6971   // Start Files
6972   //----------------------------------------------------------------------------
6973   const std::string MCpuSuffix = "/" + CpuVer;
6974   const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6975   const std::string RootDir =
6976       HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6977   const std::string StartSubDir =
6978       "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6979
6980   auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6981                       const char *Name) -> std::string {
6982     std::string RelName = SubDir + Name;
6983     std::string P = HTC.GetFilePath(RelName.c_str());
6984     if (llvm::sys::fs::exists(P))
6985       return P;
6986     return RootDir + RelName;
6987   };
6988
6989   if (IncStdLib && IncStartFiles) {
6990     if (!IsShared) {
6991       if (HasStandalone) {
6992         std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6993         CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6994       }
6995       std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6996       CmdArgs.push_back(Args.MakeArgString(Crt0));
6997     }
6998     std::string Init = UseShared
6999           ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
7000           : Find(RootDir, StartSubDir, "/init.o");
7001     CmdArgs.push_back(Args.MakeArgString(Init));
7002   }
7003
7004   //----------------------------------------------------------------------------
7005   // Library Search Paths
7006   //----------------------------------------------------------------------------
7007   const ToolChain::path_list &LibPaths = HTC.getFilePaths();
7008   for (const auto &LibPath : LibPaths)
7009     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
7010
7011   //----------------------------------------------------------------------------
7012   //
7013   //----------------------------------------------------------------------------
7014   Args.AddAllArgs(CmdArgs,
7015                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7016                    options::OPT_t, options::OPT_u_Group});
7017
7018   AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
7019
7020   //----------------------------------------------------------------------------
7021   // Libraries
7022   //----------------------------------------------------------------------------
7023   if (IncStdLib && IncDefLibs) {
7024     if (D.CCCIsCXX()) {
7025       HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
7026       CmdArgs.push_back("-lm");
7027     }
7028
7029     CmdArgs.push_back("--start-group");
7030
7031     if (!IsShared) {
7032       for (const std::string &Lib : OsLibs)
7033         CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
7034       CmdArgs.push_back("-lc");
7035     }
7036     CmdArgs.push_back("-lgcc");
7037
7038     CmdArgs.push_back("--end-group");
7039   }
7040
7041   //----------------------------------------------------------------------------
7042   // End files
7043   //----------------------------------------------------------------------------
7044   if (IncStdLib && IncStartFiles) {
7045     std::string Fini = UseShared
7046           ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
7047           : Find(RootDir, StartSubDir, "/fini.o");
7048     CmdArgs.push_back(Args.MakeArgString(Fini));
7049   }
7050 }
7051
7052 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7053                                    const InputInfo &Output,
7054                                    const InputInfoList &Inputs,
7055                                    const ArgList &Args,
7056                                    const char *LinkingOutput) const {
7057   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7058
7059   ArgStringList CmdArgs;
7060   constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
7061                            LinkingOutput);
7062
7063   std::string Linker = HTC.GetProgramPath("hexagon-link");
7064   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7065                                           CmdArgs, Inputs));
7066 }
7067 // Hexagon tools end.
7068
7069 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7070                                   const InputInfo &Output,
7071                                   const InputInfoList &Inputs,
7072                                   const ArgList &Args,
7073                                   const char *LinkingOutput) const {
7074
7075   std::string Linker = getToolChain().GetProgramPath(getShortName());
7076   ArgStringList CmdArgs;
7077   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7078   CmdArgs.push_back("-shared");
7079   CmdArgs.push_back("-o");
7080   CmdArgs.push_back(Output.getFilename());
7081   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7082                                           CmdArgs, Inputs));
7083 }
7084 // AMDGPU tools end.
7085
7086 wasm::Linker::Linker(const ToolChain &TC)
7087   : GnuTool("wasm::Linker", "lld", TC) {}
7088
7089 bool wasm::Linker::isLinkJob() const {
7090   return true;
7091 }
7092
7093 bool wasm::Linker::hasIntegratedCPP() const {
7094   return false;
7095 }
7096
7097 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7098                                 const InputInfo &Output,
7099                                 const InputInfoList &Inputs,
7100                                 const ArgList &Args,
7101                                 const char *LinkingOutput) const {
7102
7103   const ToolChain &ToolChain = getToolChain();
7104   const Driver &D = ToolChain.getDriver();
7105   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
7106   ArgStringList CmdArgs;
7107   CmdArgs.push_back("-flavor");
7108   CmdArgs.push_back("ld");
7109
7110   // Enable garbage collection of unused input sections by default, since code
7111   // size is of particular importance. This is significantly facilitated by
7112   // the enabling of -ffunction-sections and -fdata-sections in
7113   // Clang::ConstructJob.
7114   if (areOptimizationsEnabled(Args))
7115     CmdArgs.push_back("--gc-sections");
7116
7117   if (Args.hasArg(options::OPT_rdynamic))
7118     CmdArgs.push_back("-export-dynamic");
7119   if (Args.hasArg(options::OPT_s))
7120     CmdArgs.push_back("--strip-all");
7121   if (Args.hasArg(options::OPT_shared))
7122     CmdArgs.push_back("-shared");
7123   if (Args.hasArg(options::OPT_static))
7124     CmdArgs.push_back("-Bstatic");
7125
7126   Args.AddAllArgs(CmdArgs, options::OPT_L);
7127   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7128
7129   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7130     if (Args.hasArg(options::OPT_shared))
7131       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
7132     else if (Args.hasArg(options::OPT_pie))
7133       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
7134     else
7135       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
7136
7137     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7138   }
7139
7140   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7141
7142   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7143     if (D.CCCIsCXX())
7144       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7145
7146     if (Args.hasArg(options::OPT_pthread))
7147       CmdArgs.push_back("-lpthread");
7148
7149     CmdArgs.push_back("-lc");
7150     CmdArgs.push_back("-lcompiler_rt");
7151   }
7152
7153   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7154     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7155
7156   CmdArgs.push_back("-o");
7157   CmdArgs.push_back(Output.getFilename());
7158
7159   C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
7160 }
7161
7162 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
7163   std::string MArch;
7164   if (!Arch.empty())
7165     MArch = Arch;
7166   else
7167     MArch = Triple.getArchName();
7168   MArch = StringRef(MArch).split("+").first.lower();
7169
7170   // Handle -march=native.
7171   if (MArch == "native") {
7172     std::string CPU = llvm::sys::getHostCPUName();
7173     if (CPU != "generic") {
7174       // Translate the native cpu into the architecture suffix for that CPU.
7175       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
7176       // If there is no valid architecture suffix for this CPU we don't know how
7177       // to handle it, so return no architecture.
7178       if (Suffix.empty())
7179         MArch = "";
7180       else
7181         MArch = std::string("arm") + Suffix.str();
7182     }
7183   }
7184
7185   return MArch;
7186 }
7187
7188 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
7189 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
7190   std::string MArch = getARMArch(Arch, Triple);
7191   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
7192   // here means an -march=native that we can't handle, so instead return no CPU.
7193   if (MArch.empty())
7194     return StringRef();
7195
7196   // We need to return an empty string here on invalid MArch values as the
7197   // various places that call this function can't cope with a null result.
7198   return Triple.getARMCPUForArch(MArch);
7199 }
7200
7201 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
7202 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
7203                                  const llvm::Triple &Triple) {
7204   // FIXME: Warn on inconsistent use of -mcpu and -march.
7205   // If we have -mcpu=, use that.
7206   if (!CPU.empty()) {
7207     std::string MCPU = StringRef(CPU).split("+").first.lower();
7208     // Handle -mcpu=native.
7209     if (MCPU == "native")
7210       return llvm::sys::getHostCPUName();
7211     else
7212       return MCPU;
7213   }
7214
7215   return getARMCPUForMArch(Arch, Triple);
7216 }
7217
7218 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
7219 /// CPU  (or Arch, if CPU is generic).
7220 // FIXME: This is redundant with -mcpu, why does LLVM use this.
7221 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
7222                                        const llvm::Triple &Triple) {
7223   unsigned ArchKind;
7224   if (CPU == "generic") {
7225     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
7226     ArchKind = llvm::ARM::parseArch(ARMArch);
7227     if (ArchKind == llvm::ARM::AK_INVALID)
7228       // In case of generic Arch, i.e. "arm",
7229       // extract arch from default cpu of the Triple
7230       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
7231   } else {
7232     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
7233     // armv7k triple if it's actually been specified via "-arch armv7k".
7234     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
7235                           ? (unsigned)llvm::ARM::AK_ARMV7K
7236                           : llvm::ARM::parseCPUArch(CPU);
7237   }
7238   if (ArchKind == llvm::ARM::AK_INVALID)
7239     return "";
7240   return llvm::ARM::getSubArch(ArchKind);
7241 }
7242
7243 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
7244                             const llvm::Triple &Triple) {
7245   if (Args.hasArg(options::OPT_r))
7246     return;
7247
7248   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
7249   // to generate BE-8 executables.
7250   if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
7251     CmdArgs.push_back("--be8");
7252 }
7253
7254 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
7255   // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
7256   // was first introduced in Release 3. However, other compilers have
7257   // traditionally allowed it for Release 2 so we should do the same.
7258   return (NanEncoding)llvm::StringSwitch<int>(CPU)
7259       .Case("mips1", NanLegacy)
7260       .Case("mips2", NanLegacy)
7261       .Case("mips3", NanLegacy)
7262       .Case("mips4", NanLegacy)
7263       .Case("mips5", NanLegacy)
7264       .Case("mips32", NanLegacy)
7265       .Case("mips32r2", NanLegacy | Nan2008)
7266       .Case("mips32r3", NanLegacy | Nan2008)
7267       .Case("mips32r5", NanLegacy | Nan2008)
7268       .Case("mips32r6", Nan2008)
7269       .Case("mips64", NanLegacy)
7270       .Case("mips64r2", NanLegacy | Nan2008)
7271       .Case("mips64r3", NanLegacy | Nan2008)
7272       .Case("mips64r5", NanLegacy | Nan2008)
7273       .Case("mips64r6", Nan2008)
7274       .Default(NanLegacy);
7275 }
7276
7277 bool mips::hasCompactBranches(StringRef &CPU) {
7278   // mips32r6 and mips64r6 have compact branches.
7279   return llvm::StringSwitch<bool>(CPU)
7280       .Case("mips32r6", true)
7281       .Case("mips64r6", true)
7282       .Default(false);
7283 }
7284
7285 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
7286   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
7287   return A && (A->getValue() == StringRef(Value));
7288 }
7289
7290 bool mips::isUCLibc(const ArgList &Args) {
7291   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
7292   return A && A->getOption().matches(options::OPT_muclibc);
7293 }
7294
7295 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
7296   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
7297     return llvm::StringSwitch<bool>(NaNArg->getValue())
7298         .Case("2008", true)
7299         .Case("legacy", false)
7300         .Default(false);
7301
7302   // NaN2008 is the default for MIPS32r6/MIPS64r6.
7303   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
7304       .Cases("mips32r6", "mips64r6", true)
7305       .Default(false);
7306
7307   return false;
7308 }
7309
7310 bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
7311   if (!Triple.isAndroid())
7312     return false;
7313
7314   // Android MIPS32R6 defaults to FP64A.
7315   return llvm::StringSwitch<bool>(CPUName)
7316       .Case("mips32r6", true)
7317       .Default(false);
7318 }
7319
7320 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
7321                          StringRef ABIName, mips::FloatABI FloatABI) {
7322   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
7323       Triple.getVendor() != llvm::Triple::MipsTechnologies &&
7324       !Triple.isAndroid())
7325     return false;
7326
7327   if (ABIName != "32")
7328     return false;
7329
7330   // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
7331   // present.
7332   if (FloatABI == mips::FloatABI::Soft)
7333     return false;
7334
7335   return llvm::StringSwitch<bool>(CPUName)
7336       .Cases("mips2", "mips3", "mips4", "mips5", true)
7337       .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
7338       .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
7339       .Default(false);
7340 }
7341
7342 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
7343                          StringRef CPUName, StringRef ABIName,
7344                          mips::FloatABI FloatABI) {
7345   bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
7346
7347   // FPXX shouldn't be used if -msingle-float is present.
7348   if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
7349                                options::OPT_mdouble_float))
7350     if (A->getOption().matches(options::OPT_msingle_float))
7351       UseFPXX = false;
7352
7353   return UseFPXX;
7354 }
7355
7356 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
7357   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
7358   // archs which Darwin doesn't use.
7359
7360   // The matching this routine does is fairly pointless, since it is neither the
7361   // complete architecture list, nor a reasonable subset. The problem is that
7362   // historically the driver driver accepts this and also ties its -march=
7363   // handling to the architecture name, so we need to be careful before removing
7364   // support for it.
7365
7366   // This code must be kept in sync with Clang's Darwin specific argument
7367   // translation.
7368
7369   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
7370       .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
7371       .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
7372       .Case("ppc64", llvm::Triple::ppc64)
7373       .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
7374       .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
7375              llvm::Triple::x86)
7376       .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
7377       // This is derived from the driver driver.
7378       .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
7379       .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
7380       .Cases("armv7s", "xscale", llvm::Triple::arm)
7381       .Case("arm64", llvm::Triple::aarch64)
7382       .Case("r600", llvm::Triple::r600)
7383       .Case("amdgcn", llvm::Triple::amdgcn)
7384       .Case("nvptx", llvm::Triple::nvptx)
7385       .Case("nvptx64", llvm::Triple::nvptx64)
7386       .Case("amdil", llvm::Triple::amdil)
7387       .Case("spir", llvm::Triple::spir)
7388       .Default(llvm::Triple::UnknownArch);
7389 }
7390
7391 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
7392   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
7393   T.setArch(Arch);
7394
7395   if (Str == "x86_64h")
7396     T.setArchName(Str);
7397   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
7398     T.setOS(llvm::Triple::UnknownOS);
7399     T.setObjectFormat(llvm::Triple::MachO);
7400   }
7401 }
7402
7403 const char *Clang::getBaseInputName(const ArgList &Args,
7404                                     const InputInfo &Input) {
7405   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7406 }
7407
7408 const char *Clang::getBaseInputStem(const ArgList &Args,
7409                                     const InputInfoList &Inputs) {
7410   const char *Str = getBaseInputName(Args, Inputs[0]);
7411
7412   if (const char *End = strrchr(Str, '.'))
7413     return Args.MakeArgString(std::string(Str, End));
7414
7415   return Str;
7416 }
7417
7418 const char *Clang::getDependencyFileName(const ArgList &Args,
7419                                          const InputInfoList &Inputs) {
7420   // FIXME: Think about this more.
7421   std::string Res;
7422
7423   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7424     std::string Str(OutputOpt->getValue());
7425     Res = Str.substr(0, Str.rfind('.'));
7426   } else {
7427     Res = getBaseInputStem(Args, Inputs);
7428   }
7429   return Args.MakeArgString(Res + ".d");
7430 }
7431
7432 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7433                                     const InputInfo &Output,
7434                                     const InputInfoList &Inputs,
7435                                     const ArgList &Args,
7436                                     const char *LinkingOutput) const {
7437   const ToolChain &ToolChain = getToolChain();
7438   const Driver &D = ToolChain.getDriver();
7439   ArgStringList CmdArgs;
7440
7441   // Silence warning for "clang -g foo.o -o foo"
7442   Args.ClaimAllArgs(options::OPT_g_Group);
7443   // and "clang -emit-llvm foo.o -o foo"
7444   Args.ClaimAllArgs(options::OPT_emit_llvm);
7445   // and for "clang -w foo.o -o foo". Other warning options are already
7446   // handled somewhere else.
7447   Args.ClaimAllArgs(options::OPT_w);
7448
7449   if (!D.SysRoot.empty())
7450     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7451
7452   // CloudABI only supports static linkage.
7453   CmdArgs.push_back("-Bstatic");
7454   CmdArgs.push_back("--no-dynamic-linker");
7455
7456   // Provide PIE linker flags in case PIE is default for the architecture.
7457   if (ToolChain.isPIEDefault()) {
7458     CmdArgs.push_back("-pie");
7459     CmdArgs.push_back("-zrelro");
7460   }
7461
7462   CmdArgs.push_back("--eh-frame-hdr");
7463   CmdArgs.push_back("--gc-sections");
7464
7465   if (Output.isFilename()) {
7466     CmdArgs.push_back("-o");
7467     CmdArgs.push_back(Output.getFilename());
7468   } else {
7469     assert(Output.isNothing() && "Invalid output.");
7470   }
7471
7472   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7473     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
7474     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
7475   }
7476
7477   Args.AddAllArgs(CmdArgs, options::OPT_L);
7478   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7479   Args.AddAllArgs(CmdArgs,
7480                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7481                    options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
7482
7483   if (D.isUsingLTO())
7484     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7485
7486   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7487
7488   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7489     if (D.CCCIsCXX())
7490       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7491     CmdArgs.push_back("-lc");
7492     CmdArgs.push_back("-lcompiler_rt");
7493   }
7494
7495   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7496     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7497
7498   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
7499   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7500 }
7501
7502 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7503                                      const InputInfo &Output,
7504                                      const InputInfoList &Inputs,
7505                                      const ArgList &Args,
7506                                      const char *LinkingOutput) const {
7507   ArgStringList CmdArgs;
7508
7509   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7510   const InputInfo &Input = Inputs[0];
7511
7512   // Determine the original source input.
7513   const Action *SourceAction = &JA;
7514   while (SourceAction->getKind() != Action::InputClass) {
7515     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7516     SourceAction = SourceAction->getInputs()[0];
7517   }
7518
7519   // If -fno-integrated-as is used add -Q to the darwin assember driver to make
7520   // sure it runs its system assembler not clang's integrated assembler.
7521   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
7522   // FIXME: at run-time detect assembler capabilities or rely on version
7523   // information forwarded by -target-assembler-version.
7524   if (Args.hasArg(options::OPT_fno_integrated_as)) {
7525     const llvm::Triple &T(getToolChain().getTriple());
7526     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
7527       CmdArgs.push_back("-Q");
7528   }
7529
7530   // Forward -g, assuming we are dealing with an actual assembly file.
7531   if (SourceAction->getType() == types::TY_Asm ||
7532       SourceAction->getType() == types::TY_PP_Asm) {
7533     if (Args.hasArg(options::OPT_gstabs))
7534       CmdArgs.push_back("--gstabs");
7535     else if (Args.hasArg(options::OPT_g_Group))
7536       CmdArgs.push_back("-g");
7537   }
7538
7539   // Derived from asm spec.
7540   AddMachOArch(Args, CmdArgs);
7541
7542   // Use -force_cpusubtype_ALL on x86 by default.
7543   if (getToolChain().getArch() == llvm::Triple::x86 ||
7544       getToolChain().getArch() == llvm::Triple::x86_64 ||
7545       Args.hasArg(options::OPT_force__cpusubtype__ALL))
7546     CmdArgs.push_back("-force_cpusubtype_ALL");
7547
7548   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
7549       (((Args.hasArg(options::OPT_mkernel) ||
7550          Args.hasArg(options::OPT_fapple_kext)) &&
7551         getMachOToolChain().isKernelStatic()) ||
7552        Args.hasArg(options::OPT_static)))
7553     CmdArgs.push_back("-static");
7554
7555   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7556
7557   assert(Output.isFilename() && "Unexpected lipo output.");
7558   CmdArgs.push_back("-o");
7559   CmdArgs.push_back(Output.getFilename());
7560
7561   assert(Input.isFilename() && "Invalid input.");
7562   CmdArgs.push_back(Input.getFilename());
7563
7564   // asm_final spec is empty.
7565
7566   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7567   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7568 }
7569
7570 void darwin::MachOTool::anchor() {}
7571
7572 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
7573                                      ArgStringList &CmdArgs) const {
7574   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
7575
7576   // Derived from darwin_arch spec.
7577   CmdArgs.push_back("-arch");
7578   CmdArgs.push_back(Args.MakeArgString(ArchName));
7579
7580   // FIXME: Is this needed anymore?
7581   if (ArchName == "arm")
7582     CmdArgs.push_back("-force_cpusubtype_ALL");
7583 }
7584
7585 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
7586   // We only need to generate a temp path for LTO if we aren't compiling object
7587   // files. When compiling source files, we run 'dsymutil' after linking. We
7588   // don't run 'dsymutil' when compiling object files.
7589   for (const auto &Input : Inputs)
7590     if (Input.getType() != types::TY_Object)
7591       return true;
7592
7593   return false;
7594 }
7595
7596 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
7597                                  ArgStringList &CmdArgs,
7598                                  const InputInfoList &Inputs) const {
7599   const Driver &D = getToolChain().getDriver();
7600   const toolchains::MachO &MachOTC = getMachOToolChain();
7601
7602   unsigned Version[5] = {0, 0, 0, 0, 0};
7603   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
7604     if (!Driver::GetReleaseVersion(A->getValue(), Version))
7605       D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
7606   }
7607
7608   // Newer linkers support -demangle. Pass it if supported and not disabled by
7609   // the user.
7610   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7611     CmdArgs.push_back("-demangle");
7612
7613   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7614     CmdArgs.push_back("-export_dynamic");
7615
7616   // If we are using App Extension restrictions, pass a flag to the linker
7617   // telling it that the compiled code has been audited.
7618   if (Args.hasFlag(options::OPT_fapplication_extension,
7619                    options::OPT_fno_application_extension, false))
7620     CmdArgs.push_back("-application_extension");
7621
7622   if (D.isUsingLTO()) {
7623     // If we are using LTO, then automatically create a temporary file path for
7624     // the linker to use, so that it's lifetime will extend past a possible
7625     // dsymutil step.
7626     if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7627       const char *TmpPath = C.getArgs().MakeArgString(
7628           D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7629       C.addTempFile(TmpPath);
7630       CmdArgs.push_back("-object_path_lto");
7631       CmdArgs.push_back(TmpPath);
7632     }
7633   }
7634
7635   // Use -lto_library option to specify the libLTO.dylib path. Try to find
7636   // it in clang installed libraries. ld64 will only look at this argument
7637   // when it actually uses LTO, so libLTO.dylib only needs to exist at link
7638   // time if ld64 decides that it needs to use LTO.
7639   // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
7640   // next to it. That's ok since ld64 using a libLTO.dylib not matching the
7641   // clang version won't work anyways.
7642   if (Version[0] >= 133) {
7643     // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7644     StringRef P = llvm::sys::path::parent_path(D.Dir);
7645     SmallString<128> LibLTOPath(P);
7646     llvm::sys::path::append(LibLTOPath, "lib");
7647     llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7648     CmdArgs.push_back("-lto_library");
7649     CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7650   }
7651
7652   // Derived from the "link" spec.
7653   Args.AddAllArgs(CmdArgs, options::OPT_static);
7654   if (!Args.hasArg(options::OPT_static))
7655     CmdArgs.push_back("-dynamic");
7656   if (Args.hasArg(options::OPT_fgnu_runtime)) {
7657     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7658     // here. How do we wish to handle such things?
7659   }
7660
7661   if (!Args.hasArg(options::OPT_dynamiclib)) {
7662     AddMachOArch(Args, CmdArgs);
7663     // FIXME: Why do this only on this path?
7664     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7665
7666     Args.AddLastArg(CmdArgs, options::OPT_bundle);
7667     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7668     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7669
7670     Arg *A;
7671     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7672         (A = Args.getLastArg(options::OPT_current__version)) ||
7673         (A = Args.getLastArg(options::OPT_install__name)))
7674       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7675                                                        << "-dynamiclib";
7676
7677     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7678     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7679     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7680   } else {
7681     CmdArgs.push_back("-dylib");
7682
7683     Arg *A;
7684     if ((A = Args.getLastArg(options::OPT_bundle)) ||
7685         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7686         (A = Args.getLastArg(options::OPT_client__name)) ||
7687         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7688         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7689         (A = Args.getLastArg(options::OPT_private__bundle)))
7690       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7691                                                       << "-dynamiclib";
7692
7693     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7694                               "-dylib_compatibility_version");
7695     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7696                               "-dylib_current_version");
7697
7698     AddMachOArch(Args, CmdArgs);
7699
7700     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7701                               "-dylib_install_name");
7702   }
7703
7704   Args.AddLastArg(CmdArgs, options::OPT_all__load);
7705   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7706   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7707   if (MachOTC.isTargetIOSBased())
7708     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7709   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7710   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7711   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7712   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7713   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7714   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7715   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7716   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7717   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7718   Args.AddAllArgs(CmdArgs, options::OPT_init);
7719
7720   // Add the deployment target.
7721   MachOTC.addMinVersionArgs(Args, CmdArgs);
7722
7723   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7724   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7725   Args.AddLastArg(CmdArgs, options::OPT_single__module);
7726   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7727   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7728
7729   if (const Arg *A =
7730           Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7731                           options::OPT_fno_pie, options::OPT_fno_PIE)) {
7732     if (A->getOption().matches(options::OPT_fpie) ||
7733         A->getOption().matches(options::OPT_fPIE))
7734       CmdArgs.push_back("-pie");
7735     else
7736       CmdArgs.push_back("-no_pie");
7737   }
7738   // for embed-bitcode, use -bitcode_bundle in linker command
7739   if (C.getDriver().embedBitcodeEnabled() ||
7740       C.getDriver().embedBitcodeMarkerOnly()) {
7741     // Check if the toolchain supports bitcode build flow.
7742     if (MachOTC.SupportsEmbeddedBitcode())
7743       CmdArgs.push_back("-bitcode_bundle");
7744     else
7745       D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
7746   }
7747
7748   Args.AddLastArg(CmdArgs, options::OPT_prebind);
7749   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7750   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7751   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7752   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7753   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7754   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7755   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7756   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7757   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7758   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7759   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7760   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7761   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7762   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7763   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7764
7765   // Give --sysroot= preference, over the Apple specific behavior to also use
7766   // --isysroot as the syslibroot.
7767   StringRef sysroot = C.getSysRoot();
7768   if (sysroot != "") {
7769     CmdArgs.push_back("-syslibroot");
7770     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7771   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7772     CmdArgs.push_back("-syslibroot");
7773     CmdArgs.push_back(A->getValue());
7774   }
7775
7776   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7777   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7778   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7779   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7780   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7781   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7782   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7783   Args.AddAllArgs(CmdArgs, options::OPT_y);
7784   Args.AddLastArg(CmdArgs, options::OPT_w);
7785   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7786   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7787   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7788   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7789   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7790   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7791   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7792   Args.AddLastArg(CmdArgs, options::OPT_whyload);
7793   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7794   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7795   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7796   Args.AddLastArg(CmdArgs, options::OPT_Mach);
7797 }
7798
7799 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7800                                   const InputInfo &Output,
7801                                   const InputInfoList &Inputs,
7802                                   const ArgList &Args,
7803                                   const char *LinkingOutput) const {
7804   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7805
7806   // If the number of arguments surpasses the system limits, we will encode the
7807   // input files in a separate file, shortening the command line. To this end,
7808   // build a list of input file names that can be passed via a file with the
7809   // -filelist linker option.
7810   llvm::opt::ArgStringList InputFileList;
7811
7812   // The logic here is derived from gcc's behavior; most of which
7813   // comes from specs (starting with link_command). Consult gcc for
7814   // more information.
7815   ArgStringList CmdArgs;
7816
7817   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7818   if (Args.hasArg(options::OPT_ccc_arcmt_check,
7819                   options::OPT_ccc_arcmt_migrate)) {
7820     for (const auto &Arg : Args)
7821       Arg->claim();
7822     const char *Exec =
7823         Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7824     CmdArgs.push_back(Output.getFilename());
7825     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7826     return;
7827   }
7828
7829   // I'm not sure why this particular decomposition exists in gcc, but
7830   // we follow suite for ease of comparison.
7831   AddLinkArgs(C, Args, CmdArgs, Inputs);
7832
7833   // It seems that the 'e' option is completely ignored for dynamic executables
7834   // (the default), and with static executables, the last one wins, as expected.
7835   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7836                             options::OPT_Z_Flag, options::OPT_u_Group,
7837                             options::OPT_e, options::OPT_r});
7838
7839   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7840   // members of static archive libraries which implement Objective-C classes or
7841   // categories.
7842   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7843     CmdArgs.push_back("-ObjC");
7844
7845   CmdArgs.push_back("-o");
7846   CmdArgs.push_back(Output.getFilename());
7847
7848   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7849     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7850
7851   // SafeStack requires its own runtime libraries
7852   // These libraries should be linked first, to make sure the
7853   // __safestack_init constructor executes before everything else
7854   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7855     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7856                                           "libclang_rt.safestack_osx.a",
7857                                           /*AlwaysLink=*/true);
7858   }
7859
7860   Args.AddAllArgs(CmdArgs, options::OPT_L);
7861
7862   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7863   // Build the input file for -filelist (list of linker input files) in case we
7864   // need it later
7865   for (const auto &II : Inputs) {
7866     if (!II.isFilename()) {
7867       // This is a linker input argument.
7868       // We cannot mix input arguments and file names in a -filelist input, thus
7869       // we prematurely stop our list (remaining files shall be passed as
7870       // arguments).
7871       if (InputFileList.size() > 0)
7872         break;
7873
7874       continue;
7875     }
7876
7877     InputFileList.push_back(II.getFilename());
7878   }
7879
7880   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7881     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7882
7883   if (isObjCRuntimeLinked(Args) &&
7884       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7885     // We use arclite library for both ARC and subscripting support.
7886     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7887
7888     CmdArgs.push_back("-framework");
7889     CmdArgs.push_back("Foundation");
7890     // Link libobj.
7891     CmdArgs.push_back("-lobjc");
7892   }
7893
7894   if (LinkingOutput) {
7895     CmdArgs.push_back("-arch_multiple");
7896     CmdArgs.push_back("-final_output");
7897     CmdArgs.push_back(LinkingOutput);
7898   }
7899
7900   if (Args.hasArg(options::OPT_fnested_functions))
7901     CmdArgs.push_back("-allow_stack_execute");
7902
7903   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7904
7905   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7906     if (getToolChain().getDriver().CCCIsCXX())
7907       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7908
7909     // link_ssp spec is empty.
7910
7911     // Let the tool chain choose which runtime library to link.
7912     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7913   }
7914
7915   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7916     // endfile_spec is empty.
7917   }
7918
7919   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7920   Args.AddAllArgs(CmdArgs, options::OPT_F);
7921
7922   // -iframework should be forwarded as -F.
7923   for (const Arg *A : Args.filtered(options::OPT_iframework))
7924     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7925
7926   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7927     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7928       if (A->getValue() == StringRef("Accelerate")) {
7929         CmdArgs.push_back("-framework");
7930         CmdArgs.push_back("Accelerate");
7931       }
7932     }
7933   }
7934
7935   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7936   std::unique_ptr<Command> Cmd =
7937       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7938   Cmd->setInputFileList(std::move(InputFileList));
7939   C.addCommand(std::move(Cmd));
7940 }
7941
7942 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7943                                 const InputInfo &Output,
7944                                 const InputInfoList &Inputs,
7945                                 const ArgList &Args,
7946                                 const char *LinkingOutput) const {
7947   ArgStringList CmdArgs;
7948
7949   CmdArgs.push_back("-create");
7950   assert(Output.isFilename() && "Unexpected lipo output.");
7951
7952   CmdArgs.push_back("-output");
7953   CmdArgs.push_back(Output.getFilename());
7954
7955   for (const auto &II : Inputs) {
7956     assert(II.isFilename() && "Unexpected lipo input.");
7957     CmdArgs.push_back(II.getFilename());
7958   }
7959
7960   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7961   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7962 }
7963
7964 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7965                                     const InputInfo &Output,
7966                                     const InputInfoList &Inputs,
7967                                     const ArgList &Args,
7968                                     const char *LinkingOutput) const {
7969   ArgStringList CmdArgs;
7970
7971   CmdArgs.push_back("-o");
7972   CmdArgs.push_back(Output.getFilename());
7973
7974   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7975   const InputInfo &Input = Inputs[0];
7976   assert(Input.isFilename() && "Unexpected dsymutil input.");
7977   CmdArgs.push_back(Input.getFilename());
7978
7979   const char *Exec =
7980       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7981   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7982 }
7983
7984 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7985                                        const InputInfo &Output,
7986                                        const InputInfoList &Inputs,
7987                                        const ArgList &Args,
7988                                        const char *LinkingOutput) const {
7989   ArgStringList CmdArgs;
7990   CmdArgs.push_back("--verify");
7991   CmdArgs.push_back("--debug-info");
7992   CmdArgs.push_back("--eh-frame");
7993   CmdArgs.push_back("--quiet");
7994
7995   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7996   const InputInfo &Input = Inputs[0];
7997   assert(Input.isFilename() && "Unexpected verify input");
7998
7999   // Grabbing the output of the earlier dsymutil run.
8000   CmdArgs.push_back(Input.getFilename());
8001
8002   const char *Exec =
8003       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
8004   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8005 }
8006
8007 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8008                                       const InputInfo &Output,
8009                                       const InputInfoList &Inputs,
8010                                       const ArgList &Args,
8011                                       const char *LinkingOutput) const {
8012   claimNoWarnArgs(Args);
8013   ArgStringList CmdArgs;
8014
8015   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8016
8017   CmdArgs.push_back("-o");
8018   CmdArgs.push_back(Output.getFilename());
8019
8020   for (const auto &II : Inputs)
8021     CmdArgs.push_back(II.getFilename());
8022
8023   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8024   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8025 }
8026
8027 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8028                                    const InputInfo &Output,
8029                                    const InputInfoList &Inputs,
8030                                    const ArgList &Args,
8031                                    const char *LinkingOutput) const {
8032   ArgStringList CmdArgs;
8033
8034   // Demangle C++ names in errors
8035   CmdArgs.push_back("-C");
8036
8037   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8038     CmdArgs.push_back("-e");
8039     CmdArgs.push_back("_start");
8040   }
8041
8042   if (Args.hasArg(options::OPT_static)) {
8043     CmdArgs.push_back("-Bstatic");
8044     CmdArgs.push_back("-dn");
8045   } else {
8046     CmdArgs.push_back("-Bdynamic");
8047     if (Args.hasArg(options::OPT_shared)) {
8048       CmdArgs.push_back("-shared");
8049     } else {
8050       CmdArgs.push_back("--dynamic-linker");
8051       CmdArgs.push_back(
8052           Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
8053     }
8054   }
8055
8056   if (Output.isFilename()) {
8057     CmdArgs.push_back("-o");
8058     CmdArgs.push_back(Output.getFilename());
8059   } else {
8060     assert(Output.isNothing() && "Invalid output.");
8061   }
8062
8063   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8064     if (!Args.hasArg(options::OPT_shared))
8065       CmdArgs.push_back(
8066           Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8067
8068     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8069     CmdArgs.push_back(
8070         Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
8071     CmdArgs.push_back(
8072         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8073   }
8074
8075   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
8076
8077   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8078                             options::OPT_e, options::OPT_r});
8079
8080   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8081
8082   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8083     if (getToolChain().getDriver().CCCIsCXX())
8084       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8085     CmdArgs.push_back("-lgcc_s");
8086     CmdArgs.push_back("-lc");
8087     if (!Args.hasArg(options::OPT_shared)) {
8088       CmdArgs.push_back("-lgcc");
8089       CmdArgs.push_back("-lm");
8090     }
8091   }
8092
8093   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8094     CmdArgs.push_back(
8095         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8096   }
8097   CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8098
8099   getToolChain().addProfileRTLibs(Args, CmdArgs);
8100
8101   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8102   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8103 }
8104
8105 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8106                                       const InputInfo &Output,
8107                                       const InputInfoList &Inputs,
8108                                       const ArgList &Args,
8109                                       const char *LinkingOutput) const {
8110   claimNoWarnArgs(Args);
8111   ArgStringList CmdArgs;
8112
8113   switch (getToolChain().getArch()) {
8114   case llvm::Triple::x86:
8115     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
8116     // instruct as in the base system to assemble 32-bit code.
8117     CmdArgs.push_back("--32");
8118     break;
8119
8120   case llvm::Triple::ppc:
8121     CmdArgs.push_back("-mppc");
8122     CmdArgs.push_back("-many");
8123     break;
8124
8125   case llvm::Triple::sparc:
8126   case llvm::Triple::sparcel: {
8127     CmdArgs.push_back("-32");
8128     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8129     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8130     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8131     break;
8132   }
8133
8134   case llvm::Triple::sparcv9: {
8135     CmdArgs.push_back("-64");
8136     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8137     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8138     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8139     break;
8140   }
8141
8142   case llvm::Triple::mips64:
8143   case llvm::Triple::mips64el: {
8144     StringRef CPUName;
8145     StringRef ABIName;
8146     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8147
8148     CmdArgs.push_back("-mabi");
8149     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8150
8151     if (getToolChain().getArch() == llvm::Triple::mips64)
8152       CmdArgs.push_back("-EB");
8153     else
8154       CmdArgs.push_back("-EL");
8155
8156     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8157     break;
8158   }
8159
8160   default:
8161     break;
8162   }
8163
8164   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8165
8166   CmdArgs.push_back("-o");
8167   CmdArgs.push_back(Output.getFilename());
8168
8169   for (const auto &II : Inputs)
8170     CmdArgs.push_back(II.getFilename());
8171
8172   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8173   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8174 }
8175
8176 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8177                                    const InputInfo &Output,
8178                                    const InputInfoList &Inputs,
8179                                    const ArgList &Args,
8180                                    const char *LinkingOutput) const {
8181   const Driver &D = getToolChain().getDriver();
8182   ArgStringList CmdArgs;
8183
8184   // Silence warning for "clang -g foo.o -o foo"
8185   Args.ClaimAllArgs(options::OPT_g_Group);
8186   // and "clang -emit-llvm foo.o -o foo"
8187   Args.ClaimAllArgs(options::OPT_emit_llvm);
8188   // and for "clang -w foo.o -o foo". Other warning options are already
8189   // handled somewhere else.
8190   Args.ClaimAllArgs(options::OPT_w);
8191
8192   if (getToolChain().getArch() == llvm::Triple::mips64)
8193     CmdArgs.push_back("-EB");
8194   else if (getToolChain().getArch() == llvm::Triple::mips64el)
8195     CmdArgs.push_back("-EL");
8196
8197   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8198     CmdArgs.push_back("-e");
8199     CmdArgs.push_back("__start");
8200   }
8201
8202   if (Args.hasArg(options::OPT_static)) {
8203     CmdArgs.push_back("-Bstatic");
8204   } else {
8205     if (Args.hasArg(options::OPT_rdynamic))
8206       CmdArgs.push_back("-export-dynamic");
8207     CmdArgs.push_back("--eh-frame-hdr");
8208     CmdArgs.push_back("-Bdynamic");
8209     if (Args.hasArg(options::OPT_shared)) {
8210       CmdArgs.push_back("-shared");
8211     } else {
8212       CmdArgs.push_back("-dynamic-linker");
8213       CmdArgs.push_back("/usr/libexec/ld.so");
8214     }
8215   }
8216
8217   if (Args.hasArg(options::OPT_nopie))
8218     CmdArgs.push_back("-nopie");
8219
8220   if (Output.isFilename()) {
8221     CmdArgs.push_back("-o");
8222     CmdArgs.push_back(Output.getFilename());
8223   } else {
8224     assert(Output.isNothing() && "Invalid output.");
8225   }
8226
8227   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8228     if (!Args.hasArg(options::OPT_shared)) {
8229       if (Args.hasArg(options::OPT_pg))
8230         CmdArgs.push_back(
8231             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8232       else
8233         CmdArgs.push_back(
8234             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8235       CmdArgs.push_back(
8236           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8237     } else {
8238       CmdArgs.push_back(
8239           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8240     }
8241   }
8242
8243   std::string Triple = getToolChain().getTripleString();
8244   if (Triple.substr(0, 6) == "x86_64")
8245     Triple.replace(0, 6, "amd64");
8246   CmdArgs.push_back(
8247       Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
8248
8249   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8250                             options::OPT_e, options::OPT_s, options::OPT_t,
8251                             options::OPT_Z_Flag, options::OPT_r});
8252
8253   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8254
8255   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8256     if (D.CCCIsCXX()) {
8257       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8258       if (Args.hasArg(options::OPT_pg))
8259         CmdArgs.push_back("-lm_p");
8260       else
8261         CmdArgs.push_back("-lm");
8262     }
8263
8264     // FIXME: For some reason GCC passes -lgcc before adding
8265     // the default system libraries. Just mimic this for now.
8266     CmdArgs.push_back("-lgcc");
8267
8268     if (Args.hasArg(options::OPT_pthread)) {
8269       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8270         CmdArgs.push_back("-lpthread_p");
8271       else
8272         CmdArgs.push_back("-lpthread");
8273     }
8274
8275     if (!Args.hasArg(options::OPT_shared)) {
8276       if (Args.hasArg(options::OPT_pg))
8277         CmdArgs.push_back("-lc_p");
8278       else
8279         CmdArgs.push_back("-lc");
8280     }
8281
8282     CmdArgs.push_back("-lgcc");
8283   }
8284
8285   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8286     if (!Args.hasArg(options::OPT_shared))
8287       CmdArgs.push_back(
8288           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8289     else
8290       CmdArgs.push_back(
8291           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8292   }
8293
8294   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8295   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8296 }
8297
8298 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8299                                      const InputInfo &Output,
8300                                      const InputInfoList &Inputs,
8301                                      const ArgList &Args,
8302                                      const char *LinkingOutput) const {
8303   claimNoWarnArgs(Args);
8304   ArgStringList CmdArgs;
8305
8306   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8307
8308   CmdArgs.push_back("-o");
8309   CmdArgs.push_back(Output.getFilename());
8310
8311   for (const auto &II : Inputs)
8312     CmdArgs.push_back(II.getFilename());
8313
8314   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8315   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8316 }
8317
8318 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8319                                   const InputInfo &Output,
8320                                   const InputInfoList &Inputs,
8321                                   const ArgList &Args,
8322                                   const char *LinkingOutput) const {
8323   const Driver &D = getToolChain().getDriver();
8324   ArgStringList CmdArgs;
8325
8326   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8327     CmdArgs.push_back("-e");
8328     CmdArgs.push_back("__start");
8329   }
8330
8331   if (Args.hasArg(options::OPT_static)) {
8332     CmdArgs.push_back("-Bstatic");
8333   } else {
8334     if (Args.hasArg(options::OPT_rdynamic))
8335       CmdArgs.push_back("-export-dynamic");
8336     CmdArgs.push_back("--eh-frame-hdr");
8337     CmdArgs.push_back("-Bdynamic");
8338     if (Args.hasArg(options::OPT_shared)) {
8339       CmdArgs.push_back("-shared");
8340     } else {
8341       CmdArgs.push_back("-dynamic-linker");
8342       CmdArgs.push_back("/usr/libexec/ld.so");
8343     }
8344   }
8345
8346   if (Output.isFilename()) {
8347     CmdArgs.push_back("-o");
8348     CmdArgs.push_back(Output.getFilename());
8349   } else {
8350     assert(Output.isNothing() && "Invalid output.");
8351   }
8352
8353   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8354     if (!Args.hasArg(options::OPT_shared)) {
8355       if (Args.hasArg(options::OPT_pg))
8356         CmdArgs.push_back(
8357             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8358       else
8359         CmdArgs.push_back(
8360             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8361       CmdArgs.push_back(
8362           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8363     } else {
8364       CmdArgs.push_back(
8365           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8366     }
8367   }
8368
8369   Args.AddAllArgs(CmdArgs,
8370                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
8371
8372   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8373
8374   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8375     if (D.CCCIsCXX()) {
8376       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8377       if (Args.hasArg(options::OPT_pg))
8378         CmdArgs.push_back("-lm_p");
8379       else
8380         CmdArgs.push_back("-lm");
8381     }
8382
8383     if (Args.hasArg(options::OPT_pthread)) {
8384       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8385         CmdArgs.push_back("-lpthread_p");
8386       else
8387         CmdArgs.push_back("-lpthread");
8388     }
8389
8390     if (!Args.hasArg(options::OPT_shared)) {
8391       if (Args.hasArg(options::OPT_pg))
8392         CmdArgs.push_back("-lc_p");
8393       else
8394         CmdArgs.push_back("-lc");
8395     }
8396
8397     StringRef MyArch;
8398     switch (getToolChain().getArch()) {
8399     case llvm::Triple::arm:
8400       MyArch = "arm";
8401       break;
8402     case llvm::Triple::x86:
8403       MyArch = "i386";
8404       break;
8405     case llvm::Triple::x86_64:
8406       MyArch = "amd64";
8407       break;
8408     default:
8409       llvm_unreachable("Unsupported architecture");
8410     }
8411     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
8412   }
8413
8414   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8415     if (!Args.hasArg(options::OPT_shared))
8416       CmdArgs.push_back(
8417           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8418     else
8419       CmdArgs.push_back(
8420           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8421   }
8422
8423   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8424   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8425 }
8426
8427 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8428                                       const InputInfo &Output,
8429                                       const InputInfoList &Inputs,
8430                                       const ArgList &Args,
8431                                       const char *LinkingOutput) const {
8432   claimNoWarnArgs(Args);
8433   ArgStringList CmdArgs;
8434
8435   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8436   // instruct as in the base system to assemble 32-bit code.
8437   switch (getToolChain().getArch()) {
8438   default:
8439     break;
8440   case llvm::Triple::x86:
8441     CmdArgs.push_back("--32");
8442     break;
8443   case llvm::Triple::ppc:
8444     CmdArgs.push_back("-a32");
8445     break;
8446   case llvm::Triple::mips:
8447   case llvm::Triple::mipsel:
8448   case llvm::Triple::mips64:
8449   case llvm::Triple::mips64el: {
8450     StringRef CPUName;
8451     StringRef ABIName;
8452     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8453
8454     CmdArgs.push_back("-march");
8455     CmdArgs.push_back(CPUName.data());
8456
8457     CmdArgs.push_back("-mabi");
8458     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8459
8460     if (getToolChain().getArch() == llvm::Triple::mips ||
8461         getToolChain().getArch() == llvm::Triple::mips64)
8462       CmdArgs.push_back("-EB");
8463     else
8464       CmdArgs.push_back("-EL");
8465
8466     if (Arg *A = Args.getLastArg(options::OPT_G)) {
8467       StringRef v = A->getValue();
8468       CmdArgs.push_back(Args.MakeArgString("-G" + v));
8469       A->claim();
8470     }
8471
8472     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8473     break;
8474   }
8475   case llvm::Triple::arm:
8476   case llvm::Triple::armeb:
8477   case llvm::Triple::thumb:
8478   case llvm::Triple::thumbeb: {
8479     arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
8480
8481     if (ABI == arm::FloatABI::Hard)
8482       CmdArgs.push_back("-mfpu=vfp");
8483     else
8484       CmdArgs.push_back("-mfpu=softvfp");
8485
8486     switch (getToolChain().getTriple().getEnvironment()) {
8487     case llvm::Triple::GNUEABIHF:
8488     case llvm::Triple::GNUEABI:
8489     case llvm::Triple::EABI:
8490       CmdArgs.push_back("-meabi=5");
8491       break;
8492
8493     default:
8494       CmdArgs.push_back("-matpcs");
8495     }
8496     break;
8497   }
8498   case llvm::Triple::sparc:
8499   case llvm::Triple::sparcel:
8500   case llvm::Triple::sparcv9: {
8501     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8502     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8503     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8504     break;
8505   }
8506   }
8507
8508   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8509
8510   CmdArgs.push_back("-o");
8511   CmdArgs.push_back(Output.getFilename());
8512
8513   for (const auto &II : Inputs)
8514     CmdArgs.push_back(II.getFilename());
8515
8516   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8517   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8518 }
8519
8520 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8521                                    const InputInfo &Output,
8522                                    const InputInfoList &Inputs,
8523                                    const ArgList &Args,
8524                                    const char *LinkingOutput) const {
8525   const toolchains::FreeBSD &ToolChain =
8526       static_cast<const toolchains::FreeBSD &>(getToolChain());
8527   const Driver &D = ToolChain.getDriver();
8528   const llvm::Triple::ArchType Arch = ToolChain.getArch();
8529   const bool IsPIE =
8530       !Args.hasArg(options::OPT_shared) &&
8531       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8532   ArgStringList CmdArgs;
8533
8534   // Silence warning for "clang -g foo.o -o foo"
8535   Args.ClaimAllArgs(options::OPT_g_Group);
8536   // and "clang -emit-llvm foo.o -o foo"
8537   Args.ClaimAllArgs(options::OPT_emit_llvm);
8538   // and for "clang -w foo.o -o foo". Other warning options are already
8539   // handled somewhere else.
8540   Args.ClaimAllArgs(options::OPT_w);
8541
8542   if (!D.SysRoot.empty())
8543     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8544
8545   if (IsPIE)
8546     CmdArgs.push_back("-pie");
8547
8548   CmdArgs.push_back("--eh-frame-hdr");
8549   if (Args.hasArg(options::OPT_static)) {
8550     CmdArgs.push_back("-Bstatic");
8551   } else {
8552     if (Args.hasArg(options::OPT_rdynamic))
8553       CmdArgs.push_back("-export-dynamic");
8554     if (Args.hasArg(options::OPT_shared)) {
8555       CmdArgs.push_back("-Bshareable");
8556     } else {
8557       CmdArgs.push_back("-dynamic-linker");
8558       CmdArgs.push_back("/libexec/ld-elf.so.1");
8559     }
8560     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
8561       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
8562           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
8563         CmdArgs.push_back("--hash-style=both");
8564       }
8565     }
8566     CmdArgs.push_back("--enable-new-dtags");
8567   }
8568
8569   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8570   // instruct ld in the base system to link 32-bit code.
8571   if (Arch == llvm::Triple::x86) {
8572     CmdArgs.push_back("-m");
8573     CmdArgs.push_back("elf_i386_fbsd");
8574   }
8575
8576   if (Arch == llvm::Triple::ppc) {
8577     CmdArgs.push_back("-m");
8578     CmdArgs.push_back("elf32ppc_fbsd");
8579   }
8580
8581   if (Arg *A = Args.getLastArg(options::OPT_G)) {
8582     if (ToolChain.getArch() == llvm::Triple::mips ||
8583       ToolChain.getArch() == llvm::Triple::mipsel ||
8584       ToolChain.getArch() == llvm::Triple::mips64 ||
8585       ToolChain.getArch() == llvm::Triple::mips64el) {
8586       StringRef v = A->getValue();
8587       CmdArgs.push_back(Args.MakeArgString("-G" + v));
8588       A->claim();
8589     }
8590   }
8591
8592   if (Output.isFilename()) {
8593     CmdArgs.push_back("-o");
8594     CmdArgs.push_back(Output.getFilename());
8595   } else {
8596     assert(Output.isNothing() && "Invalid output.");
8597   }
8598
8599   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8600     const char *crt1 = nullptr;
8601     if (!Args.hasArg(options::OPT_shared)) {
8602       if (Args.hasArg(options::OPT_pg))
8603         crt1 = "gcrt1.o";
8604       else if (IsPIE)
8605         crt1 = "Scrt1.o";
8606       else
8607         crt1 = "crt1.o";
8608     }
8609     if (crt1)
8610       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8611
8612     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8613
8614     const char *crtbegin = nullptr;
8615     if (Args.hasArg(options::OPT_static))
8616       crtbegin = "crtbeginT.o";
8617     else if (Args.hasArg(options::OPT_shared) || IsPIE)
8618       crtbegin = "crtbeginS.o";
8619     else
8620       crtbegin = "crtbegin.o";
8621
8622     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8623   }
8624
8625   Args.AddAllArgs(CmdArgs, options::OPT_L);
8626   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8627   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8628   Args.AddAllArgs(CmdArgs, options::OPT_e);
8629   Args.AddAllArgs(CmdArgs, options::OPT_s);
8630   Args.AddAllArgs(CmdArgs, options::OPT_t);
8631   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8632   Args.AddAllArgs(CmdArgs, options::OPT_r);
8633
8634   if (D.isUsingLTO())
8635     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8636
8637   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8638   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8639
8640   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8641     addOpenMPRuntime(CmdArgs, ToolChain, Args);
8642     if (D.CCCIsCXX()) {
8643       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8644       if (Args.hasArg(options::OPT_pg))
8645         CmdArgs.push_back("-lm_p");
8646       else
8647         CmdArgs.push_back("-lm");
8648     }
8649     if (NeedsSanitizerDeps)
8650       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8651     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8652     // the default system libraries. Just mimic this for now.
8653     if (Args.hasArg(options::OPT_pg))
8654       CmdArgs.push_back("-lgcc_p");
8655     else
8656       CmdArgs.push_back("-lgcc");
8657     if (Args.hasArg(options::OPT_static)) {
8658       CmdArgs.push_back("-lgcc_eh");
8659     } else if (Args.hasArg(options::OPT_pg)) {
8660       CmdArgs.push_back("-lgcc_eh_p");
8661     } else {
8662       CmdArgs.push_back("--as-needed");
8663       CmdArgs.push_back("-lgcc_s");
8664       CmdArgs.push_back("--no-as-needed");
8665     }
8666
8667     if (Args.hasArg(options::OPT_pthread)) {
8668       if (Args.hasArg(options::OPT_pg))
8669         CmdArgs.push_back("-lpthread_p");
8670       else
8671         CmdArgs.push_back("-lpthread");
8672     }
8673
8674     if (Args.hasArg(options::OPT_pg)) {
8675       if (Args.hasArg(options::OPT_shared))
8676         CmdArgs.push_back("-lc");
8677       else
8678         CmdArgs.push_back("-lc_p");
8679       CmdArgs.push_back("-lgcc_p");
8680     } else {
8681       CmdArgs.push_back("-lc");
8682       CmdArgs.push_back("-lgcc");
8683     }
8684
8685     if (Args.hasArg(options::OPT_static)) {
8686       CmdArgs.push_back("-lgcc_eh");
8687     } else if (Args.hasArg(options::OPT_pg)) {
8688       CmdArgs.push_back("-lgcc_eh_p");
8689     } else {
8690       CmdArgs.push_back("--as-needed");
8691       CmdArgs.push_back("-lgcc_s");
8692       CmdArgs.push_back("--no-as-needed");
8693     }
8694   }
8695
8696   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8697     if (Args.hasArg(options::OPT_shared) || IsPIE)
8698       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8699     else
8700       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8701     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8702   }
8703
8704   ToolChain.addProfileRTLibs(Args, CmdArgs);
8705
8706   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8707   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8708 }
8709
8710 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8711                                      const InputInfo &Output,
8712                                      const InputInfoList &Inputs,
8713                                      const ArgList &Args,
8714                                      const char *LinkingOutput) const {
8715   claimNoWarnArgs(Args);
8716   ArgStringList CmdArgs;
8717
8718   // GNU as needs different flags for creating the correct output format
8719   // on architectures with different ABIs or optional feature sets.
8720   switch (getToolChain().getArch()) {
8721   case llvm::Triple::x86:
8722     CmdArgs.push_back("--32");
8723     break;
8724   case llvm::Triple::arm:
8725   case llvm::Triple::armeb:
8726   case llvm::Triple::thumb:
8727   case llvm::Triple::thumbeb: {
8728     StringRef MArch, MCPU;
8729     getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8730     std::string Arch =
8731         arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8732     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8733     break;
8734   }
8735
8736   case llvm::Triple::mips:
8737   case llvm::Triple::mipsel:
8738   case llvm::Triple::mips64:
8739   case llvm::Triple::mips64el: {
8740     StringRef CPUName;
8741     StringRef ABIName;
8742     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8743
8744     CmdArgs.push_back("-march");
8745     CmdArgs.push_back(CPUName.data());
8746
8747     CmdArgs.push_back("-mabi");
8748     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8749
8750     if (getToolChain().getArch() == llvm::Triple::mips ||
8751         getToolChain().getArch() == llvm::Triple::mips64)
8752       CmdArgs.push_back("-EB");
8753     else
8754       CmdArgs.push_back("-EL");
8755
8756     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8757     break;
8758   }
8759
8760   case llvm::Triple::sparc:
8761   case llvm::Triple::sparcel: {
8762     CmdArgs.push_back("-32");
8763     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8764     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8765     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8766     break;
8767   }
8768
8769   case llvm::Triple::sparcv9: {
8770     CmdArgs.push_back("-64");
8771     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8772     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8773     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8774     break;
8775   }
8776
8777   default:
8778     break;
8779   }
8780
8781   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8782
8783   CmdArgs.push_back("-o");
8784   CmdArgs.push_back(Output.getFilename());
8785
8786   for (const auto &II : Inputs)
8787     CmdArgs.push_back(II.getFilename());
8788
8789   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8790   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8791 }
8792
8793 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8794                                   const InputInfo &Output,
8795                                   const InputInfoList &Inputs,
8796                                   const ArgList &Args,
8797                                   const char *LinkingOutput) const {
8798   const Driver &D = getToolChain().getDriver();
8799   ArgStringList CmdArgs;
8800
8801   if (!D.SysRoot.empty())
8802     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8803
8804   CmdArgs.push_back("--eh-frame-hdr");
8805   if (Args.hasArg(options::OPT_static)) {
8806     CmdArgs.push_back("-Bstatic");
8807   } else {
8808     if (Args.hasArg(options::OPT_rdynamic))
8809       CmdArgs.push_back("-export-dynamic");
8810     if (Args.hasArg(options::OPT_shared)) {
8811       CmdArgs.push_back("-Bshareable");
8812     } else {
8813       Args.AddAllArgs(CmdArgs, options::OPT_pie);
8814       CmdArgs.push_back("-dynamic-linker");
8815       CmdArgs.push_back("/libexec/ld.elf_so");
8816     }
8817   }
8818
8819   // Many NetBSD architectures support more than one ABI.
8820   // Determine the correct emulation for ld.
8821   switch (getToolChain().getArch()) {
8822   case llvm::Triple::x86:
8823     CmdArgs.push_back("-m");
8824     CmdArgs.push_back("elf_i386");
8825     break;
8826   case llvm::Triple::arm:
8827   case llvm::Triple::thumb:
8828     CmdArgs.push_back("-m");
8829     switch (getToolChain().getTriple().getEnvironment()) {
8830     case llvm::Triple::EABI:
8831     case llvm::Triple::GNUEABI:
8832       CmdArgs.push_back("armelf_nbsd_eabi");
8833       break;
8834     case llvm::Triple::EABIHF:
8835     case llvm::Triple::GNUEABIHF:
8836       CmdArgs.push_back("armelf_nbsd_eabihf");
8837       break;
8838     default:
8839       CmdArgs.push_back("armelf_nbsd");
8840       break;
8841     }
8842     break;
8843   case llvm::Triple::armeb:
8844   case llvm::Triple::thumbeb:
8845     arm::appendEBLinkFlags(
8846         Args, CmdArgs,
8847         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8848     CmdArgs.push_back("-m");
8849     switch (getToolChain().getTriple().getEnvironment()) {
8850     case llvm::Triple::EABI:
8851     case llvm::Triple::GNUEABI:
8852       CmdArgs.push_back("armelfb_nbsd_eabi");
8853       break;
8854     case llvm::Triple::EABIHF:
8855     case llvm::Triple::GNUEABIHF:
8856       CmdArgs.push_back("armelfb_nbsd_eabihf");
8857       break;
8858     default:
8859       CmdArgs.push_back("armelfb_nbsd");
8860       break;
8861     }
8862     break;
8863   case llvm::Triple::mips64:
8864   case llvm::Triple::mips64el:
8865     if (mips::hasMipsAbiArg(Args, "32")) {
8866       CmdArgs.push_back("-m");
8867       if (getToolChain().getArch() == llvm::Triple::mips64)
8868         CmdArgs.push_back("elf32btsmip");
8869       else
8870         CmdArgs.push_back("elf32ltsmip");
8871     } else if (mips::hasMipsAbiArg(Args, "64")) {
8872       CmdArgs.push_back("-m");
8873       if (getToolChain().getArch() == llvm::Triple::mips64)
8874         CmdArgs.push_back("elf64btsmip");
8875       else
8876         CmdArgs.push_back("elf64ltsmip");
8877     }
8878     break;
8879   case llvm::Triple::ppc:
8880     CmdArgs.push_back("-m");
8881     CmdArgs.push_back("elf32ppc_nbsd");
8882     break;
8883
8884   case llvm::Triple::ppc64:
8885   case llvm::Triple::ppc64le:
8886     CmdArgs.push_back("-m");
8887     CmdArgs.push_back("elf64ppc");
8888     break;
8889
8890   case llvm::Triple::sparc:
8891     CmdArgs.push_back("-m");
8892     CmdArgs.push_back("elf32_sparc");
8893     break;
8894
8895   case llvm::Triple::sparcv9:
8896     CmdArgs.push_back("-m");
8897     CmdArgs.push_back("elf64_sparc");
8898     break;
8899
8900   default:
8901     break;
8902   }
8903
8904   if (Output.isFilename()) {
8905     CmdArgs.push_back("-o");
8906     CmdArgs.push_back(Output.getFilename());
8907   } else {
8908     assert(Output.isNothing() && "Invalid output.");
8909   }
8910
8911   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8912     if (!Args.hasArg(options::OPT_shared)) {
8913       CmdArgs.push_back(
8914           Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8915     }
8916     CmdArgs.push_back(
8917         Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8918     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
8919       CmdArgs.push_back(
8920           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8921     } else {
8922       CmdArgs.push_back(
8923           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8924     }
8925   }
8926
8927   Args.AddAllArgs(CmdArgs, options::OPT_L);
8928   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8929   Args.AddAllArgs(CmdArgs, options::OPT_e);
8930   Args.AddAllArgs(CmdArgs, options::OPT_s);
8931   Args.AddAllArgs(CmdArgs, options::OPT_t);
8932   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8933   Args.AddAllArgs(CmdArgs, options::OPT_r);
8934
8935   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8936
8937   unsigned Major, Minor, Micro;
8938   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8939   bool useLibgcc = true;
8940   if (Major >= 7 || Major == 0) {
8941     switch (getToolChain().getArch()) {
8942     case llvm::Triple::aarch64:
8943     case llvm::Triple::arm:
8944     case llvm::Triple::armeb:
8945     case llvm::Triple::thumb:
8946     case llvm::Triple::thumbeb:
8947     case llvm::Triple::ppc:
8948     case llvm::Triple::ppc64:
8949     case llvm::Triple::ppc64le:
8950     case llvm::Triple::sparc:
8951     case llvm::Triple::sparcv9:
8952     case llvm::Triple::x86:
8953     case llvm::Triple::x86_64:
8954       useLibgcc = false;
8955       break;
8956     default:
8957       break;
8958     }
8959   }
8960
8961   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8962     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8963     if (D.CCCIsCXX()) {
8964       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8965       CmdArgs.push_back("-lm");
8966     }
8967     if (Args.hasArg(options::OPT_pthread))
8968       CmdArgs.push_back("-lpthread");
8969     CmdArgs.push_back("-lc");
8970
8971     if (useLibgcc) {
8972       if (Args.hasArg(options::OPT_static)) {
8973         // libgcc_eh depends on libc, so resolve as much as possible,
8974         // pull in any new requirements from libc and then get the rest
8975         // of libgcc.
8976         CmdArgs.push_back("-lgcc_eh");
8977         CmdArgs.push_back("-lc");
8978         CmdArgs.push_back("-lgcc");
8979       } else {
8980         CmdArgs.push_back("-lgcc");
8981         CmdArgs.push_back("--as-needed");
8982         CmdArgs.push_back("-lgcc_s");
8983         CmdArgs.push_back("--no-as-needed");
8984       }
8985     }
8986   }
8987
8988   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8989     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8990       CmdArgs.push_back(
8991           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8992     else
8993       CmdArgs.push_back(
8994           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8995     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8996   }
8997
8998   getToolChain().addProfileRTLibs(Args, CmdArgs);
8999
9000   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9001   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9002 }
9003
9004 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9005                                        const InputInfo &Output,
9006                                        const InputInfoList &Inputs,
9007                                        const ArgList &Args,
9008                                        const char *LinkingOutput) const {
9009   claimNoWarnArgs(Args);
9010
9011   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9012   llvm::Triple Triple = llvm::Triple(TripleStr);
9013
9014   ArgStringList CmdArgs;
9015
9016   llvm::Reloc::Model RelocationModel;
9017   unsigned PICLevel;
9018   bool IsPIE;
9019   std::tie(RelocationModel, PICLevel, IsPIE) =
9020       ParsePICArgs(getToolChain(), Triple, Args);
9021
9022   switch (getToolChain().getArch()) {
9023   default:
9024     break;
9025   // Add --32/--64 to make sure we get the format we want.
9026   // This is incomplete
9027   case llvm::Triple::x86:
9028     CmdArgs.push_back("--32");
9029     break;
9030   case llvm::Triple::x86_64:
9031     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
9032       CmdArgs.push_back("--x32");
9033     else
9034       CmdArgs.push_back("--64");
9035     break;
9036   case llvm::Triple::ppc:
9037     CmdArgs.push_back("-a32");
9038     CmdArgs.push_back("-mppc");
9039     CmdArgs.push_back("-many");
9040     break;
9041   case llvm::Triple::ppc64:
9042     CmdArgs.push_back("-a64");
9043     CmdArgs.push_back("-mppc64");
9044     CmdArgs.push_back("-many");
9045     break;
9046   case llvm::Triple::ppc64le:
9047     CmdArgs.push_back("-a64");
9048     CmdArgs.push_back("-mppc64");
9049     CmdArgs.push_back("-many");
9050     CmdArgs.push_back("-mlittle-endian");
9051     break;
9052   case llvm::Triple::sparc:
9053   case llvm::Triple::sparcel: {
9054     CmdArgs.push_back("-32");
9055     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9056     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9057     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9058     break;
9059   }
9060   case llvm::Triple::sparcv9: {
9061     CmdArgs.push_back("-64");
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::arm:
9068   case llvm::Triple::armeb:
9069   case llvm::Triple::thumb:
9070   case llvm::Triple::thumbeb: {
9071     const llvm::Triple &Triple2 = getToolChain().getTriple();
9072     switch (Triple2.getSubArch()) {
9073     case llvm::Triple::ARMSubArch_v7:
9074       CmdArgs.push_back("-mfpu=neon");
9075       break;
9076     case llvm::Triple::ARMSubArch_v8:
9077       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
9078       break;
9079     default:
9080       break;
9081     }
9082
9083     switch (arm::getARMFloatABI(getToolChain(), Args)) {
9084     case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
9085     case arm::FloatABI::Soft:
9086       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
9087       break;
9088     case arm::FloatABI::SoftFP:
9089       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
9090       break;
9091     case arm::FloatABI::Hard:
9092       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
9093       break;
9094     }
9095
9096     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
9097
9098     // FIXME: remove krait check when GNU tools support krait cpu
9099     // for now replace it with -mcpu=cortex-a15 to avoid a lower
9100     // march from being picked in the absence of a cpu flag.
9101     Arg *A;
9102     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
9103         StringRef(A->getValue()).lower() == "krait")
9104       CmdArgs.push_back("-mcpu=cortex-a15");
9105     else
9106       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
9107     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
9108     break;
9109   }
9110   case llvm::Triple::mips:
9111   case llvm::Triple::mipsel:
9112   case llvm::Triple::mips64:
9113   case llvm::Triple::mips64el: {
9114     StringRef CPUName;
9115     StringRef ABIName;
9116     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9117     ABIName = getGnuCompatibleMipsABIName(ABIName);
9118
9119     CmdArgs.push_back("-march");
9120     CmdArgs.push_back(CPUName.data());
9121
9122     CmdArgs.push_back("-mabi");
9123     CmdArgs.push_back(ABIName.data());
9124
9125     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
9126     // or -mshared (not implemented) is in effect.
9127     if (RelocationModel == llvm::Reloc::Static)
9128       CmdArgs.push_back("-mno-shared");
9129
9130     // LLVM doesn't support -mplt yet and acts as if it is always given.
9131     // However, -mplt has no effect with the N64 ABI.
9132     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
9133
9134     if (getToolChain().getArch() == llvm::Triple::mips ||
9135         getToolChain().getArch() == llvm::Triple::mips64)
9136       CmdArgs.push_back("-EB");
9137     else
9138       CmdArgs.push_back("-EL");
9139
9140     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
9141       if (StringRef(A->getValue()) == "2008")
9142         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
9143     }
9144
9145     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
9146     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
9147                                  options::OPT_mfp64)) {
9148       A->claim();
9149       A->render(Args, CmdArgs);
9150     } else if (mips::shouldUseFPXX(
9151                    Args, getToolChain().getTriple(), CPUName, ABIName,
9152                    getMipsFloatABI(getToolChain().getDriver(), Args)))
9153       CmdArgs.push_back("-mfpxx");
9154
9155     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
9156     // -mno-mips16 is actually -no-mips16.
9157     if (Arg *A =
9158             Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
9159       if (A->getOption().matches(options::OPT_mips16)) {
9160         A->claim();
9161         A->render(Args, CmdArgs);
9162       } else {
9163         A->claim();
9164         CmdArgs.push_back("-no-mips16");
9165       }
9166     }
9167
9168     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
9169                     options::OPT_mno_micromips);
9170     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
9171     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
9172
9173     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
9174       // Do not use AddLastArg because not all versions of MIPS assembler
9175       // support -mmsa / -mno-msa options.
9176       if (A->getOption().matches(options::OPT_mmsa))
9177         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
9178     }
9179
9180     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
9181                     options::OPT_msoft_float);
9182
9183     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
9184                     options::OPT_msingle_float);
9185
9186     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
9187                     options::OPT_mno_odd_spreg);
9188
9189     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9190     break;
9191   }
9192   case llvm::Triple::systemz: {
9193     // Always pass an -march option, since our default of z10 is later
9194     // than the GNU assembler's default.
9195     StringRef CPUName = getSystemZTargetCPU(Args);
9196     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
9197     break;
9198   }
9199   }
9200
9201   Args.AddAllArgs(CmdArgs, options::OPT_I);
9202   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9203
9204   CmdArgs.push_back("-o");
9205   CmdArgs.push_back(Output.getFilename());
9206
9207   for (const auto &II : Inputs)
9208     CmdArgs.push_back(II.getFilename());
9209
9210   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9211   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9212
9213   // Handle the debug info splitting at object creation time if we're
9214   // creating an object.
9215   // TODO: Currently only works on linux with newer objcopy.
9216   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
9217       getToolChain().getTriple().isOSLinux())
9218     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9219                    SplitDebugName(Args, Inputs[0]));
9220 }
9221
9222 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
9223                       ArgStringList &CmdArgs, const ArgList &Args) {
9224   bool isAndroid = Triple.isAndroid();
9225   bool isCygMing = Triple.isOSCygMing();
9226   bool IsIAMCU = Triple.isOSIAMCU();
9227   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
9228                       Args.hasArg(options::OPT_static);
9229   if (!D.CCCIsCXX())
9230     CmdArgs.push_back("-lgcc");
9231
9232   if (StaticLibgcc || isAndroid) {
9233     if (D.CCCIsCXX())
9234       CmdArgs.push_back("-lgcc");
9235   } else {
9236     if (!D.CCCIsCXX() && !isCygMing)
9237       CmdArgs.push_back("--as-needed");
9238     CmdArgs.push_back("-lgcc_s");
9239     if (!D.CCCIsCXX() && !isCygMing)
9240       CmdArgs.push_back("--no-as-needed");
9241   }
9242
9243   if (StaticLibgcc && !isAndroid && !IsIAMCU)
9244     CmdArgs.push_back("-lgcc_eh");
9245   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
9246     CmdArgs.push_back("-lgcc");
9247
9248   // According to Android ABI, we have to link with libdl if we are
9249   // linking with non-static libgcc.
9250   //
9251   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
9252   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
9253   if (isAndroid && !StaticLibgcc)
9254     CmdArgs.push_back("-ldl");
9255 }
9256
9257 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
9258                            ArgStringList &CmdArgs, const ArgList &Args) {
9259   // Make use of compiler-rt if --rtlib option is used
9260   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
9261
9262   switch (RLT) {
9263   case ToolChain::RLT_CompilerRT:
9264     switch (TC.getTriple().getOS()) {
9265     default:
9266       llvm_unreachable("unsupported OS");
9267     case llvm::Triple::Win32:
9268     case llvm::Triple::Linux:
9269       addClangRT(TC, Args, CmdArgs);
9270       break;
9271     }
9272     break;
9273   case ToolChain::RLT_Libgcc:
9274     // Make sure libgcc is not used under MSVC environment by default
9275     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
9276       // Issue error diagnostic if libgcc is explicitly specified
9277       // through command line as --rtlib option argument.
9278       if (Args.hasArg(options::OPT_rtlib_EQ)) {
9279         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
9280             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
9281       }
9282     } else
9283       AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
9284     break;
9285   }
9286 }
9287
9288 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
9289   switch (T.getArch()) {
9290   case llvm::Triple::x86:
9291     if (T.isOSIAMCU())
9292       return "elf_iamcu";
9293     return "elf_i386";
9294   case llvm::Triple::aarch64:
9295     return "aarch64linux";
9296   case llvm::Triple::aarch64_be:
9297     return "aarch64_be_linux";
9298   case llvm::Triple::arm:
9299   case llvm::Triple::thumb:
9300     return "armelf_linux_eabi";
9301   case llvm::Triple::armeb:
9302   case llvm::Triple::thumbeb:
9303     return "armelfb_linux_eabi";
9304   case llvm::Triple::ppc:
9305     return "elf32ppclinux";
9306   case llvm::Triple::ppc64:
9307     return "elf64ppc";
9308   case llvm::Triple::ppc64le:
9309     return "elf64lppc";
9310   case llvm::Triple::sparc:
9311   case llvm::Triple::sparcel:
9312     return "elf32_sparc";
9313   case llvm::Triple::sparcv9:
9314     return "elf64_sparc";
9315   case llvm::Triple::mips:
9316     return "elf32btsmip";
9317   case llvm::Triple::mipsel:
9318     return "elf32ltsmip";
9319   case llvm::Triple::mips64:
9320     if (mips::hasMipsAbiArg(Args, "n32"))
9321       return "elf32btsmipn32";
9322     return "elf64btsmip";
9323   case llvm::Triple::mips64el:
9324     if (mips::hasMipsAbiArg(Args, "n32"))
9325       return "elf32ltsmipn32";
9326     return "elf64ltsmip";
9327   case llvm::Triple::systemz:
9328     return "elf64_s390";
9329   case llvm::Triple::x86_64:
9330     if (T.getEnvironment() == llvm::Triple::GNUX32)
9331       return "elf32_x86_64";
9332     return "elf_x86_64";
9333   default:
9334     llvm_unreachable("Unexpected arch");
9335   }
9336 }
9337
9338 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9339                                     const InputInfo &Output,
9340                                     const InputInfoList &Inputs,
9341                                     const ArgList &Args,
9342                                     const char *LinkingOutput) const {
9343   const toolchains::Linux &ToolChain =
9344       static_cast<const toolchains::Linux &>(getToolChain());
9345   const Driver &D = ToolChain.getDriver();
9346
9347   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9348   llvm::Triple Triple = llvm::Triple(TripleStr);
9349
9350   const llvm::Triple::ArchType Arch = ToolChain.getArch();
9351   const bool isAndroid = ToolChain.getTriple().isAndroid();
9352   const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
9353   const bool IsPIE =
9354       !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
9355       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
9356   const bool HasCRTBeginEndFiles =
9357       ToolChain.getTriple().hasEnvironment() ||
9358       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
9359
9360   ArgStringList CmdArgs;
9361
9362   // Silence warning for "clang -g foo.o -o foo"
9363   Args.ClaimAllArgs(options::OPT_g_Group);
9364   // and "clang -emit-llvm foo.o -o foo"
9365   Args.ClaimAllArgs(options::OPT_emit_llvm);
9366   // and for "clang -w foo.o -o foo". Other warning options are already
9367   // handled somewhere else.
9368   Args.ClaimAllArgs(options::OPT_w);
9369
9370   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9371   if (llvm::sys::path::filename(Exec) == "lld") {
9372     CmdArgs.push_back("-flavor");
9373     CmdArgs.push_back("old-gnu");
9374     CmdArgs.push_back("-target");
9375     CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
9376   }
9377
9378   if (!D.SysRoot.empty())
9379     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9380
9381   if (IsPIE)
9382     CmdArgs.push_back("-pie");
9383
9384   if (Args.hasArg(options::OPT_rdynamic))
9385     CmdArgs.push_back("-export-dynamic");
9386
9387   if (Args.hasArg(options::OPT_s))
9388     CmdArgs.push_back("-s");
9389
9390   if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
9391     arm::appendEBLinkFlags(Args, CmdArgs, Triple);
9392
9393   for (const auto &Opt : ToolChain.ExtraOpts)
9394     CmdArgs.push_back(Opt.c_str());
9395
9396   if (!Args.hasArg(options::OPT_static)) {
9397     CmdArgs.push_back("--eh-frame-hdr");
9398   }
9399
9400   CmdArgs.push_back("-m");
9401   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
9402
9403   if (Args.hasArg(options::OPT_static)) {
9404     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
9405         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
9406       CmdArgs.push_back("-Bstatic");
9407     else
9408       CmdArgs.push_back("-static");
9409   } else if (Args.hasArg(options::OPT_shared)) {
9410     CmdArgs.push_back("-shared");
9411   }
9412
9413   if (!Args.hasArg(options::OPT_static)) {
9414     if (Args.hasArg(options::OPT_rdynamic))
9415       CmdArgs.push_back("-export-dynamic");
9416
9417     if (!Args.hasArg(options::OPT_shared)) {
9418       const std::string Loader =
9419           D.DyldPrefix + ToolChain.getDynamicLinker(Args);
9420       CmdArgs.push_back("-dynamic-linker");
9421       CmdArgs.push_back(Args.MakeArgString(Loader));
9422     }
9423   }
9424
9425   CmdArgs.push_back("-o");
9426   CmdArgs.push_back(Output.getFilename());
9427
9428   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9429     if (!isAndroid && !IsIAMCU) {
9430       const char *crt1 = nullptr;
9431       if (!Args.hasArg(options::OPT_shared)) {
9432         if (Args.hasArg(options::OPT_pg))
9433           crt1 = "gcrt1.o";
9434         else if (IsPIE)
9435           crt1 = "Scrt1.o";
9436         else
9437           crt1 = "crt1.o";
9438       }
9439       if (crt1)
9440         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
9441
9442       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9443     }
9444
9445     if (IsIAMCU)
9446       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
9447     else {
9448       const char *crtbegin;
9449       if (Args.hasArg(options::OPT_static))
9450         crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
9451       else if (Args.hasArg(options::OPT_shared))
9452         crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
9453       else if (IsPIE)
9454         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
9455       else
9456         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
9457
9458       if (HasCRTBeginEndFiles)
9459         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9460     }
9461
9462     // Add crtfastmath.o if available and fast math is enabled.
9463     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9464   }
9465
9466   Args.AddAllArgs(CmdArgs, options::OPT_L);
9467   Args.AddAllArgs(CmdArgs, options::OPT_u);
9468
9469   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9470
9471   if (D.isUsingLTO())
9472     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
9473
9474   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9475     CmdArgs.push_back("--no-demangle");
9476
9477   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
9478   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
9479   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9480   // The profile runtime also needs access to system libraries.
9481   getToolChain().addProfileRTLibs(Args, CmdArgs);
9482
9483   if (D.CCCIsCXX() &&
9484       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9485     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9486                                !Args.hasArg(options::OPT_static);
9487     if (OnlyLibstdcxxStatic)
9488       CmdArgs.push_back("-Bstatic");
9489     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9490     if (OnlyLibstdcxxStatic)
9491       CmdArgs.push_back("-Bdynamic");
9492     CmdArgs.push_back("-lm");
9493   }
9494   // Silence warnings when linking C code with a C++ '-stdlib' argument.
9495   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
9496
9497   if (!Args.hasArg(options::OPT_nostdlib)) {
9498     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9499       if (Args.hasArg(options::OPT_static))
9500         CmdArgs.push_back("--start-group");
9501
9502       if (NeedsSanitizerDeps)
9503         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
9504
9505       if (NeedsXRayDeps)
9506         linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
9507
9508       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
9509                          Args.hasArg(options::OPT_pthreads);
9510
9511       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9512                        options::OPT_fno_openmp, false)) {
9513         // OpenMP runtimes implies pthreads when using the GNU toolchain.
9514         // FIXME: Does this really make sense for all GNU toolchains?
9515         WantPthread = true;
9516
9517         // Also link the particular OpenMP runtimes.
9518         switch (getOpenMPRuntime(ToolChain, Args)) {
9519         case OMPRT_OMP:
9520           CmdArgs.push_back("-lomp");
9521           break;
9522         case OMPRT_GOMP:
9523           CmdArgs.push_back("-lgomp");
9524
9525           // FIXME: Exclude this for platforms with libgomp that don't require
9526           // librt. Most modern Linux platforms require it, but some may not.
9527           CmdArgs.push_back("-lrt");
9528           break;
9529         case OMPRT_IOMP5:
9530           CmdArgs.push_back("-liomp5");
9531           break;
9532         case OMPRT_Unknown:
9533           // Already diagnosed.
9534           break;
9535         }
9536       }
9537
9538       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9539
9540       if (WantPthread && !isAndroid)
9541         CmdArgs.push_back("-lpthread");
9542
9543       if (Args.hasArg(options::OPT_fsplit_stack))
9544         CmdArgs.push_back("--wrap=pthread_create");
9545
9546       CmdArgs.push_back("-lc");
9547
9548       // Add IAMCU specific libs, if needed.
9549       if (IsIAMCU)
9550         CmdArgs.push_back("-lgloss");
9551
9552       if (Args.hasArg(options::OPT_static))
9553         CmdArgs.push_back("--end-group");
9554       else
9555         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9556
9557       // Add IAMCU specific libs (outside the group), if needed.
9558       if (IsIAMCU) {
9559         CmdArgs.push_back("--as-needed");
9560         CmdArgs.push_back("-lsoftfp");
9561         CmdArgs.push_back("--no-as-needed");
9562       }
9563     }
9564
9565     if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
9566       const char *crtend;
9567       if (Args.hasArg(options::OPT_shared))
9568         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
9569       else if (IsPIE)
9570         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
9571       else
9572         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
9573
9574       if (HasCRTBeginEndFiles)
9575         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9576       if (!isAndroid)
9577         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9578     }
9579   }
9580
9581   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9582 }
9583
9584 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
9585 // for the various SFI requirements like register masking. The assembly tool
9586 // inserts the file containing the macros as an input into all the assembly
9587 // jobs.
9588 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
9589                                            const InputInfo &Output,
9590                                            const InputInfoList &Inputs,
9591                                            const ArgList &Args,
9592                                            const char *LinkingOutput) const {
9593   const toolchains::NaClToolChain &ToolChain =
9594       static_cast<const toolchains::NaClToolChain &>(getToolChain());
9595   InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9596                        "nacl-arm-macros.s");
9597   InputInfoList NewInputs;
9598   NewInputs.push_back(NaClMacros);
9599   NewInputs.append(Inputs.begin(), Inputs.end());
9600   gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9601                                     LinkingOutput);
9602 }
9603
9604 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9605 // we use static by default, do not yet support sanitizers or LTO, and a few
9606 // others. Eventually we can support more of that and hopefully migrate back
9607 // to gnutools::Linker.
9608 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9609                                      const InputInfo &Output,
9610                                      const InputInfoList &Inputs,
9611                                      const ArgList &Args,
9612                                      const char *LinkingOutput) const {
9613
9614   const toolchains::NaClToolChain &ToolChain =
9615       static_cast<const toolchains::NaClToolChain &>(getToolChain());
9616   const Driver &D = ToolChain.getDriver();
9617   const llvm::Triple::ArchType Arch = ToolChain.getArch();
9618   const bool IsStatic =
9619       !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9620
9621   ArgStringList CmdArgs;
9622
9623   // Silence warning for "clang -g foo.o -o foo"
9624   Args.ClaimAllArgs(options::OPT_g_Group);
9625   // and "clang -emit-llvm foo.o -o foo"
9626   Args.ClaimAllArgs(options::OPT_emit_llvm);
9627   // and for "clang -w foo.o -o foo". Other warning options are already
9628   // handled somewhere else.
9629   Args.ClaimAllArgs(options::OPT_w);
9630
9631   if (!D.SysRoot.empty())
9632     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9633
9634   if (Args.hasArg(options::OPT_rdynamic))
9635     CmdArgs.push_back("-export-dynamic");
9636
9637   if (Args.hasArg(options::OPT_s))
9638     CmdArgs.push_back("-s");
9639
9640   // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9641   // from there is --build-id, which we do want.
9642   CmdArgs.push_back("--build-id");
9643
9644   if (!IsStatic)
9645     CmdArgs.push_back("--eh-frame-hdr");
9646
9647   CmdArgs.push_back("-m");
9648   if (Arch == llvm::Triple::x86)
9649     CmdArgs.push_back("elf_i386_nacl");
9650   else if (Arch == llvm::Triple::arm)
9651     CmdArgs.push_back("armelf_nacl");
9652   else if (Arch == llvm::Triple::x86_64)
9653     CmdArgs.push_back("elf_x86_64_nacl");
9654   else if (Arch == llvm::Triple::mipsel)
9655     CmdArgs.push_back("mipselelf_nacl");
9656   else
9657     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9658                                               << "Native Client";
9659
9660   if (IsStatic)
9661     CmdArgs.push_back("-static");
9662   else if (Args.hasArg(options::OPT_shared))
9663     CmdArgs.push_back("-shared");
9664
9665   CmdArgs.push_back("-o");
9666   CmdArgs.push_back(Output.getFilename());
9667   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9668     if (!Args.hasArg(options::OPT_shared))
9669       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9670     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9671
9672     const char *crtbegin;
9673     if (IsStatic)
9674       crtbegin = "crtbeginT.o";
9675     else if (Args.hasArg(options::OPT_shared))
9676       crtbegin = "crtbeginS.o";
9677     else
9678       crtbegin = "crtbegin.o";
9679     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9680   }
9681
9682   Args.AddAllArgs(CmdArgs, options::OPT_L);
9683   Args.AddAllArgs(CmdArgs, options::OPT_u);
9684
9685   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9686
9687   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9688     CmdArgs.push_back("--no-demangle");
9689
9690   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9691
9692   if (D.CCCIsCXX() &&
9693       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9694     bool OnlyLibstdcxxStatic =
9695         Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9696     if (OnlyLibstdcxxStatic)
9697       CmdArgs.push_back("-Bstatic");
9698     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9699     if (OnlyLibstdcxxStatic)
9700       CmdArgs.push_back("-Bdynamic");
9701     CmdArgs.push_back("-lm");
9702   }
9703
9704   if (!Args.hasArg(options::OPT_nostdlib)) {
9705     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9706       // Always use groups, since it has no effect on dynamic libraries.
9707       CmdArgs.push_back("--start-group");
9708       CmdArgs.push_back("-lc");
9709       // NaCl's libc++ currently requires libpthread, so just always include it
9710       // in the group for C++.
9711       if (Args.hasArg(options::OPT_pthread) ||
9712           Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9713         // Gold, used by Mips, handles nested groups differently than ld, and
9714         // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9715         // which is not a desired behaviour here.
9716         // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9717         if (getToolChain().getArch() == llvm::Triple::mipsel)
9718           CmdArgs.push_back("-lnacl");
9719
9720         CmdArgs.push_back("-lpthread");
9721       }
9722
9723       CmdArgs.push_back("-lgcc");
9724       CmdArgs.push_back("--as-needed");
9725       if (IsStatic)
9726         CmdArgs.push_back("-lgcc_eh");
9727       else
9728         CmdArgs.push_back("-lgcc_s");
9729       CmdArgs.push_back("--no-as-needed");
9730
9731       // Mips needs to create and use pnacl_legacy library that contains
9732       // definitions from bitcode/pnaclmm.c and definitions for
9733       // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9734       if (getToolChain().getArch() == llvm::Triple::mipsel)
9735         CmdArgs.push_back("-lpnacl_legacy");
9736
9737       CmdArgs.push_back("--end-group");
9738     }
9739
9740     if (!Args.hasArg(options::OPT_nostartfiles)) {
9741       const char *crtend;
9742       if (Args.hasArg(options::OPT_shared))
9743         crtend = "crtendS.o";
9744       else
9745         crtend = "crtend.o";
9746
9747       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9748       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9749     }
9750   }
9751
9752   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9753   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9754 }
9755
9756 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9757                                     const InputInfo &Output,
9758                                     const InputInfoList &Inputs,
9759                                     const ArgList &Args,
9760                                     const char *LinkingOutput) const {
9761   claimNoWarnArgs(Args);
9762   ArgStringList CmdArgs;
9763
9764   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9765
9766   CmdArgs.push_back("-o");
9767   CmdArgs.push_back(Output.getFilename());
9768
9769   for (const auto &II : Inputs)
9770     CmdArgs.push_back(II.getFilename());
9771
9772   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9773   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9774 }
9775
9776 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9777                                  const InputInfo &Output,
9778                                  const InputInfoList &Inputs,
9779                                  const ArgList &Args,
9780                                  const char *LinkingOutput) const {
9781   const Driver &D = getToolChain().getDriver();
9782   ArgStringList CmdArgs;
9783
9784   if (Output.isFilename()) {
9785     CmdArgs.push_back("-o");
9786     CmdArgs.push_back(Output.getFilename());
9787   } else {
9788     assert(Output.isNothing() && "Invalid output.");
9789   }
9790
9791   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9792     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9793     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9794     CmdArgs.push_back(
9795         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9796     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9797   }
9798
9799   Args.AddAllArgs(CmdArgs,
9800                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9801
9802   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9803
9804   getToolChain().addProfileRTLibs(Args, CmdArgs);
9805
9806   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9807     if (D.CCCIsCXX()) {
9808       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9809       CmdArgs.push_back("-lm");
9810     }
9811   }
9812
9813   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9814     if (Args.hasArg(options::OPT_pthread))
9815       CmdArgs.push_back("-lpthread");
9816     CmdArgs.push_back("-lc");
9817     CmdArgs.push_back("-lCompilerRT-Generic");
9818     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9819     CmdArgs.push_back(
9820         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9821   }
9822
9823   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9824   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9825 }
9826
9827 /// DragonFly Tools
9828
9829 // For now, DragonFly Assemble does just about the same as for
9830 // FreeBSD, but this may change soon.
9831 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9832                                         const InputInfo &Output,
9833                                         const InputInfoList &Inputs,
9834                                         const ArgList &Args,
9835                                         const char *LinkingOutput) const {
9836   claimNoWarnArgs(Args);
9837   ArgStringList CmdArgs;
9838
9839   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9840   // instruct as in the base system to assemble 32-bit code.
9841   if (getToolChain().getArch() == llvm::Triple::x86)
9842     CmdArgs.push_back("--32");
9843
9844   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9845
9846   CmdArgs.push_back("-o");
9847   CmdArgs.push_back(Output.getFilename());
9848
9849   for (const auto &II : Inputs)
9850     CmdArgs.push_back(II.getFilename());
9851
9852   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9853   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9854 }
9855
9856 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9857                                      const InputInfo &Output,
9858                                      const InputInfoList &Inputs,
9859                                      const ArgList &Args,
9860                                      const char *LinkingOutput) const {
9861   const Driver &D = getToolChain().getDriver();
9862   ArgStringList CmdArgs;
9863
9864   if (!D.SysRoot.empty())
9865     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9866
9867   CmdArgs.push_back("--eh-frame-hdr");
9868   if (Args.hasArg(options::OPT_static)) {
9869     CmdArgs.push_back("-Bstatic");
9870   } else {
9871     if (Args.hasArg(options::OPT_rdynamic))
9872       CmdArgs.push_back("-export-dynamic");
9873     if (Args.hasArg(options::OPT_shared))
9874       CmdArgs.push_back("-Bshareable");
9875     else {
9876       CmdArgs.push_back("-dynamic-linker");
9877       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9878     }
9879     CmdArgs.push_back("--hash-style=gnu");
9880     CmdArgs.push_back("--enable-new-dtags");
9881   }
9882
9883   // When building 32-bit code on DragonFly/pc64, we have to explicitly
9884   // instruct ld in the base system to link 32-bit code.
9885   if (getToolChain().getArch() == llvm::Triple::x86) {
9886     CmdArgs.push_back("-m");
9887     CmdArgs.push_back("elf_i386");
9888   }
9889
9890   if (Output.isFilename()) {
9891     CmdArgs.push_back("-o");
9892     CmdArgs.push_back(Output.getFilename());
9893   } else {
9894     assert(Output.isNothing() && "Invalid output.");
9895   }
9896
9897   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9898     if (!Args.hasArg(options::OPT_shared)) {
9899       if (Args.hasArg(options::OPT_pg))
9900         CmdArgs.push_back(
9901             Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9902       else {
9903         if (Args.hasArg(options::OPT_pie))
9904           CmdArgs.push_back(
9905               Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9906         else
9907           CmdArgs.push_back(
9908               Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9909       }
9910     }
9911     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9912     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9913       CmdArgs.push_back(
9914           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9915     else
9916       CmdArgs.push_back(
9917           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9918   }
9919
9920   Args.AddAllArgs(CmdArgs,
9921                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9922
9923   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9924
9925   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9926     CmdArgs.push_back("-L/usr/lib/gcc50");
9927
9928     if (!Args.hasArg(options::OPT_static)) {
9929       CmdArgs.push_back("-rpath");
9930       CmdArgs.push_back("/usr/lib/gcc50");
9931     }
9932
9933     if (D.CCCIsCXX()) {
9934       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9935       CmdArgs.push_back("-lm");
9936     }
9937
9938     if (Args.hasArg(options::OPT_pthread))
9939       CmdArgs.push_back("-lpthread");
9940
9941     if (!Args.hasArg(options::OPT_nolibc)) {
9942       CmdArgs.push_back("-lc");
9943     }
9944
9945     if (Args.hasArg(options::OPT_static) ||
9946         Args.hasArg(options::OPT_static_libgcc)) {
9947         CmdArgs.push_back("-lgcc");
9948         CmdArgs.push_back("-lgcc_eh");
9949     } else {
9950       if (Args.hasArg(options::OPT_shared_libgcc)) {
9951           CmdArgs.push_back("-lgcc_pic");
9952           if (!Args.hasArg(options::OPT_shared))
9953             CmdArgs.push_back("-lgcc");
9954       } else {
9955           CmdArgs.push_back("-lgcc");
9956           CmdArgs.push_back("--as-needed");
9957           CmdArgs.push_back("-lgcc_pic");
9958           CmdArgs.push_back("--no-as-needed");
9959       }
9960     }
9961   }
9962
9963   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9964     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9965       CmdArgs.push_back(
9966           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9967     else
9968       CmdArgs.push_back(
9969           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9970     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9971   }
9972
9973   getToolChain().addProfileRTLibs(Args, CmdArgs);
9974
9975   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9976   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9977 }
9978
9979 // Try to find Exe from a Visual Studio distribution.  This first tries to find
9980 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9981 // making sure that whatever executable that's found is not a same-named exe
9982 // from clang itself to prevent clang from falling back to itself.
9983 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9984                                               const char *Exe,
9985                                               const char *ClangProgramPath) {
9986   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9987   std::string visualStudioBinDir;
9988   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9989                                          visualStudioBinDir)) {
9990     SmallString<128> FilePath(visualStudioBinDir);
9991     llvm::sys::path::append(FilePath, Exe);
9992     if (llvm::sys::fs::can_execute(FilePath.c_str()))
9993       return FilePath.str();
9994   }
9995
9996   return Exe;
9997 }
9998
9999 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10000                                         const InputInfo &Output,
10001                                         const InputInfoList &Inputs,
10002                                         const ArgList &Args,
10003                                         const char *LinkingOutput) const {
10004   ArgStringList CmdArgs;
10005   const ToolChain &TC = getToolChain();
10006
10007   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
10008   if (Output.isFilename())
10009     CmdArgs.push_back(
10010         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
10011
10012   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
10013       !C.getDriver().IsCLMode())
10014     CmdArgs.push_back("-defaultlib:libcmt");
10015
10016   if (!llvm::sys::Process::GetEnv("LIB")) {
10017     // If the VC environment hasn't been configured (perhaps because the user
10018     // did not run vcvarsall), try to build a consistent link environment.  If
10019     // the environment variable is set however, assume the user knows what
10020     // they're doing.
10021     std::string VisualStudioDir;
10022     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
10023     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
10024       SmallString<128> LibDir(VisualStudioDir);
10025       llvm::sys::path::append(LibDir, "VC", "lib");
10026       switch (MSVC.getArch()) {
10027       case llvm::Triple::x86:
10028         // x86 just puts the libraries directly in lib
10029         break;
10030       case llvm::Triple::x86_64:
10031         llvm::sys::path::append(LibDir, "amd64");
10032         break;
10033       case llvm::Triple::arm:
10034         llvm::sys::path::append(LibDir, "arm");
10035         break;
10036       default:
10037         break;
10038       }
10039       CmdArgs.push_back(
10040           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
10041
10042       if (MSVC.useUniversalCRT(VisualStudioDir)) {
10043         std::string UniversalCRTLibPath;
10044         if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
10045           CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10046                                                UniversalCRTLibPath.c_str()));
10047       }
10048     }
10049
10050     std::string WindowsSdkLibPath;
10051     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
10052       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10053                                            WindowsSdkLibPath.c_str()));
10054   }
10055
10056   if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
10057     for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
10058       CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
10059
10060   CmdArgs.push_back("-nologo");
10061
10062   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
10063                   options::OPT__SLASH_Zd))
10064     CmdArgs.push_back("-debug");
10065
10066   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
10067                          options::OPT_shared);
10068   if (DLL) {
10069     CmdArgs.push_back(Args.MakeArgString("-dll"));
10070
10071     SmallString<128> ImplibName(Output.getFilename());
10072     llvm::sys::path::replace_extension(ImplibName, "lib");
10073     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
10074   }
10075
10076   if (TC.getSanitizerArgs().needsAsanRt()) {
10077     CmdArgs.push_back(Args.MakeArgString("-debug"));
10078     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
10079     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
10080       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10081         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10082       // Make sure the dynamic runtime thunk is not optimized out at link time
10083       // to ensure proper SEH handling.
10084       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
10085     } else if (DLL) {
10086       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10087     } else {
10088       for (const auto &Lib : {"asan", "asan_cxx"})
10089         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10090     }
10091   }
10092
10093   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
10094
10095   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10096                    options::OPT_fno_openmp, false)) {
10097     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
10098     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
10099     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10100                                          TC.getDriver().Dir + "/../lib"));
10101     switch (getOpenMPRuntime(getToolChain(), Args)) {
10102     case OMPRT_OMP:
10103       CmdArgs.push_back("-defaultlib:libomp.lib");
10104       break;
10105     case OMPRT_IOMP5:
10106       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
10107       break;
10108     case OMPRT_GOMP:
10109       break;
10110     case OMPRT_Unknown:
10111       // Already diagnosed.
10112       break;
10113     }
10114   }
10115
10116   // Add compiler-rt lib in case if it was explicitly
10117   // specified as an argument for --rtlib option.
10118   if (!Args.hasArg(options::OPT_nostdlib)) {
10119     AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
10120   }
10121
10122   // Add filenames, libraries, and other linker inputs.
10123   for (const auto &Input : Inputs) {
10124     if (Input.isFilename()) {
10125       CmdArgs.push_back(Input.getFilename());
10126       continue;
10127     }
10128
10129     const Arg &A = Input.getInputArg();
10130
10131     // Render -l options differently for the MSVC linker.
10132     if (A.getOption().matches(options::OPT_l)) {
10133       StringRef Lib = A.getValue();
10134       const char *LinkLibArg;
10135       if (Lib.endswith(".lib"))
10136         LinkLibArg = Args.MakeArgString(Lib);
10137       else
10138         LinkLibArg = Args.MakeArgString(Lib + ".lib");
10139       CmdArgs.push_back(LinkLibArg);
10140       continue;
10141     }
10142
10143     // Otherwise, this is some other kind of linker input option like -Wl, -z,
10144     // or -L. Render it, even if MSVC doesn't understand it.
10145     A.renderAsInput(Args, CmdArgs);
10146   }
10147
10148   TC.addProfileRTLibs(Args, CmdArgs);
10149
10150   // We need to special case some linker paths.  In the case of lld, we need to
10151   // translate 'lld' into 'lld-link', and in the case of the regular msvc
10152   // linker, we need to use a special search algorithm.
10153   llvm::SmallString<128> linkPath;
10154   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
10155   if (Linker.equals_lower("lld"))
10156     Linker = "lld-link";
10157
10158   if (Linker.equals_lower("link")) {
10159     // If we're using the MSVC linker, it's not sufficient to just use link
10160     // from the program PATH, because other environments like GnuWin32 install
10161     // their own link.exe which may come first.
10162     linkPath = FindVisualStudioExecutable(TC, "link.exe",
10163                                           C.getDriver().getClangProgramPath());
10164   } else {
10165     linkPath = Linker;
10166     llvm::sys::path::replace_extension(linkPath, "exe");
10167     linkPath = TC.GetProgramPath(linkPath.c_str());
10168   }
10169
10170   const char *Exec = Args.MakeArgString(linkPath);
10171   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10172 }
10173
10174 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10175                                           const InputInfo &Output,
10176                                           const InputInfoList &Inputs,
10177                                           const ArgList &Args,
10178                                           const char *LinkingOutput) const {
10179   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
10180 }
10181
10182 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
10183     Compilation &C, const JobAction &JA, const InputInfo &Output,
10184     const InputInfoList &Inputs, const ArgList &Args,
10185     const char *LinkingOutput) const {
10186   ArgStringList CmdArgs;
10187   CmdArgs.push_back("/nologo");
10188   CmdArgs.push_back("/c");  // Compile only.
10189   CmdArgs.push_back("/W0"); // No warnings.
10190
10191   // The goal is to be able to invoke this tool correctly based on
10192   // any flag accepted by clang-cl.
10193
10194   // These are spelled the same way in clang and cl.exe,.
10195   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
10196
10197   // Optimization level.
10198   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
10199     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
10200                                                                       : "/Oi-");
10201   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
10202     if (A->getOption().getID() == options::OPT_O0) {
10203       CmdArgs.push_back("/Od");
10204     } else {
10205       CmdArgs.push_back("/Og");
10206
10207       StringRef OptLevel = A->getValue();
10208       if (OptLevel == "s" || OptLevel == "z")
10209         CmdArgs.push_back("/Os");
10210       else
10211         CmdArgs.push_back("/Ot");
10212
10213       CmdArgs.push_back("/Ob2");
10214     }
10215   }
10216   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
10217                                options::OPT_fno_omit_frame_pointer))
10218     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
10219                           ? "/Oy"
10220                           : "/Oy-");
10221   if (!Args.hasArg(options::OPT_fwritable_strings))
10222     CmdArgs.push_back("/GF");
10223
10224   // Flags for which clang-cl has an alias.
10225   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
10226
10227   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
10228                    /*default=*/false))
10229     CmdArgs.push_back("/GR-");
10230
10231   if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
10232                    /*default=*/false))
10233     CmdArgs.push_back("/GS-");
10234
10235   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
10236                                options::OPT_fno_function_sections))
10237     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
10238                           ? "/Gy"
10239                           : "/Gy-");
10240   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
10241                                options::OPT_fno_data_sections))
10242     CmdArgs.push_back(
10243         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
10244   if (Args.hasArg(options::OPT_fsyntax_only))
10245     CmdArgs.push_back("/Zs");
10246   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
10247                   options::OPT__SLASH_Z7))
10248     CmdArgs.push_back("/Z7");
10249
10250   std::vector<std::string> Includes =
10251       Args.getAllArgValues(options::OPT_include);
10252   for (const auto &Include : Includes)
10253     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
10254
10255   // Flags that can simply be passed through.
10256   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
10257   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
10258   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
10259   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
10260   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
10261   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
10262
10263   // The order of these flags is relevant, so pick the last one.
10264   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
10265                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
10266     A->render(Args, CmdArgs);
10267
10268   // Pass through all unknown arguments so that the fallback command can see
10269   // them too.
10270   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
10271
10272   // Input filename.
10273   assert(Inputs.size() == 1);
10274   const InputInfo &II = Inputs[0];
10275   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
10276   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
10277   if (II.isFilename())
10278     CmdArgs.push_back(II.getFilename());
10279   else
10280     II.getInputArg().renderAsInput(Args, CmdArgs);
10281
10282   // Output filename.
10283   assert(Output.getType() == types::TY_Object);
10284   const char *Fo =
10285       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
10286   CmdArgs.push_back(Fo);
10287
10288   const Driver &D = getToolChain().getDriver();
10289   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
10290                                                 D.getClangProgramPath());
10291   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10292                                     CmdArgs, Inputs);
10293 }
10294
10295 /// MinGW Tools
10296 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10297                                     const InputInfo &Output,
10298                                     const InputInfoList &Inputs,
10299                                     const ArgList &Args,
10300                                     const char *LinkingOutput) const {
10301   claimNoWarnArgs(Args);
10302   ArgStringList CmdArgs;
10303
10304   if (getToolChain().getArch() == llvm::Triple::x86) {
10305     CmdArgs.push_back("--32");
10306   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
10307     CmdArgs.push_back("--64");
10308   }
10309
10310   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10311
10312   CmdArgs.push_back("-o");
10313   CmdArgs.push_back(Output.getFilename());
10314
10315   for (const auto &II : Inputs)
10316     CmdArgs.push_back(II.getFilename());
10317
10318   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10319   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10320
10321   if (Args.hasArg(options::OPT_gsplit_dwarf))
10322     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
10323                    SplitDebugName(Args, Inputs[0]));
10324 }
10325
10326 void MinGW::Linker::AddLibGCC(const ArgList &Args,
10327                               ArgStringList &CmdArgs) const {
10328   if (Args.hasArg(options::OPT_mthreads))
10329     CmdArgs.push_back("-lmingwthrd");
10330   CmdArgs.push_back("-lmingw32");
10331
10332   // Make use of compiler-rt if --rtlib option is used
10333   ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
10334   if (RLT == ToolChain::RLT_Libgcc) {
10335     bool Static = Args.hasArg(options::OPT_static_libgcc) ||
10336                   Args.hasArg(options::OPT_static);
10337     bool Shared = Args.hasArg(options::OPT_shared);
10338     bool CXX = getToolChain().getDriver().CCCIsCXX();
10339
10340     if (Static || (!CXX && !Shared)) {
10341       CmdArgs.push_back("-lgcc");
10342       CmdArgs.push_back("-lgcc_eh");
10343     } else {
10344       CmdArgs.push_back("-lgcc_s");
10345       CmdArgs.push_back("-lgcc");
10346     }
10347   } else {
10348     AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
10349   }
10350
10351   CmdArgs.push_back("-lmoldname");
10352   CmdArgs.push_back("-lmingwex");
10353   CmdArgs.push_back("-lmsvcrt");
10354 }
10355
10356 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10357                                  const InputInfo &Output,
10358                                  const InputInfoList &Inputs,
10359                                  const ArgList &Args,
10360                                  const char *LinkingOutput) const {
10361   const ToolChain &TC = getToolChain();
10362   const Driver &D = TC.getDriver();
10363   // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
10364
10365   ArgStringList CmdArgs;
10366
10367   // Silence warning for "clang -g foo.o -o foo"
10368   Args.ClaimAllArgs(options::OPT_g_Group);
10369   // and "clang -emit-llvm foo.o -o foo"
10370   Args.ClaimAllArgs(options::OPT_emit_llvm);
10371   // and for "clang -w foo.o -o foo". Other warning options are already
10372   // handled somewhere else.
10373   Args.ClaimAllArgs(options::OPT_w);
10374
10375   StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
10376   if (LinkerName.equals_lower("lld")) {
10377     CmdArgs.push_back("-flavor");
10378     CmdArgs.push_back("gnu");
10379   } else if (!LinkerName.equals_lower("ld")) {
10380     D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
10381   }
10382
10383   if (!D.SysRoot.empty())
10384     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10385
10386   if (Args.hasArg(options::OPT_s))
10387     CmdArgs.push_back("-s");
10388
10389   CmdArgs.push_back("-m");
10390   if (TC.getArch() == llvm::Triple::x86)
10391     CmdArgs.push_back("i386pe");
10392   if (TC.getArch() == llvm::Triple::x86_64)
10393     CmdArgs.push_back("i386pep");
10394   if (TC.getArch() == llvm::Triple::arm)
10395     CmdArgs.push_back("thumb2pe");
10396
10397   if (Args.hasArg(options::OPT_mwindows)) {
10398     CmdArgs.push_back("--subsystem");
10399     CmdArgs.push_back("windows");
10400   } else if (Args.hasArg(options::OPT_mconsole)) {
10401     CmdArgs.push_back("--subsystem");
10402     CmdArgs.push_back("console");
10403   }
10404
10405   if (Args.hasArg(options::OPT_static))
10406     CmdArgs.push_back("-Bstatic");
10407   else {
10408     if (Args.hasArg(options::OPT_mdll))
10409       CmdArgs.push_back("--dll");
10410     else if (Args.hasArg(options::OPT_shared))
10411       CmdArgs.push_back("--shared");
10412     CmdArgs.push_back("-Bdynamic");
10413     if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
10414       CmdArgs.push_back("-e");
10415       if (TC.getArch() == llvm::Triple::x86)
10416         CmdArgs.push_back("_DllMainCRTStartup@12");
10417       else
10418         CmdArgs.push_back("DllMainCRTStartup");
10419       CmdArgs.push_back("--enable-auto-image-base");
10420     }
10421   }
10422
10423   CmdArgs.push_back("-o");
10424   CmdArgs.push_back(Output.getFilename());
10425
10426   Args.AddAllArgs(CmdArgs, options::OPT_e);
10427   // FIXME: add -N, -n flags
10428   Args.AddLastArg(CmdArgs, options::OPT_r);
10429   Args.AddLastArg(CmdArgs, options::OPT_s);
10430   Args.AddLastArg(CmdArgs, options::OPT_t);
10431   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
10432   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
10433
10434   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10435     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
10436       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
10437     } else {
10438       if (Args.hasArg(options::OPT_municode))
10439         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
10440       else
10441         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
10442     }
10443     if (Args.hasArg(options::OPT_pg))
10444       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
10445     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10446   }
10447
10448   Args.AddAllArgs(CmdArgs, options::OPT_L);
10449   TC.AddFilePathLibArgs(Args, CmdArgs);
10450   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10451
10452   // TODO: Add ASan stuff here
10453
10454   // TODO: Add profile stuff here
10455
10456   if (D.CCCIsCXX() &&
10457       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10458     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10459                                !Args.hasArg(options::OPT_static);
10460     if (OnlyLibstdcxxStatic)
10461       CmdArgs.push_back("-Bstatic");
10462     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10463     if (OnlyLibstdcxxStatic)
10464       CmdArgs.push_back("-Bdynamic");
10465   }
10466
10467   if (!Args.hasArg(options::OPT_nostdlib)) {
10468     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10469       if (Args.hasArg(options::OPT_static))
10470         CmdArgs.push_back("--start-group");
10471
10472       if (Args.hasArg(options::OPT_fstack_protector) ||
10473           Args.hasArg(options::OPT_fstack_protector_strong) ||
10474           Args.hasArg(options::OPT_fstack_protector_all)) {
10475         CmdArgs.push_back("-lssp_nonshared");
10476         CmdArgs.push_back("-lssp");
10477       }
10478       if (Args.hasArg(options::OPT_fopenmp))
10479         CmdArgs.push_back("-lgomp");
10480
10481       AddLibGCC(Args, CmdArgs);
10482
10483       if (Args.hasArg(options::OPT_pg))
10484         CmdArgs.push_back("-lgmon");
10485
10486       if (Args.hasArg(options::OPT_pthread))
10487         CmdArgs.push_back("-lpthread");
10488
10489       // add system libraries
10490       if (Args.hasArg(options::OPT_mwindows)) {
10491         CmdArgs.push_back("-lgdi32");
10492         CmdArgs.push_back("-lcomdlg32");
10493       }
10494       CmdArgs.push_back("-ladvapi32");
10495       CmdArgs.push_back("-lshell32");
10496       CmdArgs.push_back("-luser32");
10497       CmdArgs.push_back("-lkernel32");
10498
10499       if (Args.hasArg(options::OPT_static))
10500         CmdArgs.push_back("--end-group");
10501       else if (!LinkerName.equals_lower("lld"))
10502         AddLibGCC(Args, CmdArgs);
10503     }
10504
10505     if (!Args.hasArg(options::OPT_nostartfiles)) {
10506       // Add crtfastmath.o if available and fast math is enabled.
10507       TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
10508
10509       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10510     }
10511   }
10512   const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
10513   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10514 }
10515
10516 /// XCore Tools
10517 // We pass assemble and link construction to the xcc tool.
10518
10519 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10520                                     const InputInfo &Output,
10521                                     const InputInfoList &Inputs,
10522                                     const ArgList &Args,
10523                                     const char *LinkingOutput) const {
10524   claimNoWarnArgs(Args);
10525   ArgStringList CmdArgs;
10526
10527   CmdArgs.push_back("-o");
10528   CmdArgs.push_back(Output.getFilename());
10529
10530   CmdArgs.push_back("-c");
10531
10532   if (Args.hasArg(options::OPT_v))
10533     CmdArgs.push_back("-v");
10534
10535   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
10536     if (!A->getOption().matches(options::OPT_g0))
10537       CmdArgs.push_back("-g");
10538
10539   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
10540                    false))
10541     CmdArgs.push_back("-fverbose-asm");
10542
10543   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10544
10545   for (const auto &II : Inputs)
10546     CmdArgs.push_back(II.getFilename());
10547
10548   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10549   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10550 }
10551
10552 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10553                                  const InputInfo &Output,
10554                                  const InputInfoList &Inputs,
10555                                  const ArgList &Args,
10556                                  const char *LinkingOutput) const {
10557   ArgStringList CmdArgs;
10558
10559   if (Output.isFilename()) {
10560     CmdArgs.push_back("-o");
10561     CmdArgs.push_back(Output.getFilename());
10562   } else {
10563     assert(Output.isNothing() && "Invalid output.");
10564   }
10565
10566   if (Args.hasArg(options::OPT_v))
10567     CmdArgs.push_back("-v");
10568
10569   // Pass -fexceptions through to the linker if it was present.
10570   if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
10571                    false))
10572     CmdArgs.push_back("-fexceptions");
10573
10574   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10575
10576   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10577   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10578 }
10579
10580 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10581                                            const InputInfo &Output,
10582                                            const InputInfoList &Inputs,
10583                                            const ArgList &Args,
10584                                            const char *LinkingOutput) const {
10585   claimNoWarnArgs(Args);
10586   const auto &TC =
10587       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10588   ArgStringList CmdArgs;
10589   const char *Exec;
10590
10591   switch (TC.getArch()) {
10592   default:
10593     llvm_unreachable("unsupported architecture");
10594   case llvm::Triple::arm:
10595   case llvm::Triple::thumb:
10596     break;
10597   case llvm::Triple::x86:
10598     CmdArgs.push_back("--32");
10599     break;
10600   case llvm::Triple::x86_64:
10601     CmdArgs.push_back("--64");
10602     break;
10603   }
10604
10605   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10606
10607   CmdArgs.push_back("-o");
10608   CmdArgs.push_back(Output.getFilename());
10609
10610   for (const auto &Input : Inputs)
10611     CmdArgs.push_back(Input.getFilename());
10612
10613   const std::string Assembler = TC.GetProgramPath("as");
10614   Exec = Args.MakeArgString(Assembler);
10615
10616   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10617 }
10618
10619 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10620                                         const InputInfo &Output,
10621                                         const InputInfoList &Inputs,
10622                                         const ArgList &Args,
10623                                         const char *LinkingOutput) const {
10624   const auto &TC =
10625       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10626   const llvm::Triple &T = TC.getTriple();
10627   const Driver &D = TC.getDriver();
10628   SmallString<128> EntryPoint;
10629   ArgStringList CmdArgs;
10630   const char *Exec;
10631
10632   // Silence warning for "clang -g foo.o -o foo"
10633   Args.ClaimAllArgs(options::OPT_g_Group);
10634   // and "clang -emit-llvm foo.o -o foo"
10635   Args.ClaimAllArgs(options::OPT_emit_llvm);
10636   // and for "clang -w foo.o -o foo"
10637   Args.ClaimAllArgs(options::OPT_w);
10638   // Other warning options are already handled somewhere else.
10639
10640   if (!D.SysRoot.empty())
10641     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10642
10643   if (Args.hasArg(options::OPT_pie))
10644     CmdArgs.push_back("-pie");
10645   if (Args.hasArg(options::OPT_rdynamic))
10646     CmdArgs.push_back("-export-dynamic");
10647   if (Args.hasArg(options::OPT_s))
10648     CmdArgs.push_back("--strip-all");
10649
10650   CmdArgs.push_back("-m");
10651   switch (TC.getArch()) {
10652   default:
10653     llvm_unreachable("unsupported architecture");
10654   case llvm::Triple::arm:
10655   case llvm::Triple::thumb:
10656     // FIXME: this is incorrect for WinCE
10657     CmdArgs.push_back("thumb2pe");
10658     break;
10659   case llvm::Triple::x86:
10660     CmdArgs.push_back("i386pe");
10661     EntryPoint.append("_");
10662     break;
10663   case llvm::Triple::x86_64:
10664     CmdArgs.push_back("i386pep");
10665     break;
10666   }
10667
10668   if (Args.hasArg(options::OPT_shared)) {
10669     switch (T.getArch()) {
10670     default:
10671       llvm_unreachable("unsupported architecture");
10672     case llvm::Triple::arm:
10673     case llvm::Triple::thumb:
10674     case llvm::Triple::x86_64:
10675       EntryPoint.append("_DllMainCRTStartup");
10676       break;
10677     case llvm::Triple::x86:
10678       EntryPoint.append("_DllMainCRTStartup@12");
10679       break;
10680     }
10681
10682     CmdArgs.push_back("-shared");
10683     CmdArgs.push_back("-Bdynamic");
10684
10685     CmdArgs.push_back("--enable-auto-image-base");
10686
10687     CmdArgs.push_back("--entry");
10688     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10689   } else {
10690     EntryPoint.append("mainCRTStartup");
10691
10692     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10693                                                        : "-Bdynamic");
10694
10695     if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10696       CmdArgs.push_back("--entry");
10697       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10698     }
10699
10700     // FIXME: handle subsystem
10701   }
10702
10703   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10704   CmdArgs.push_back("--allow-multiple-definition");
10705
10706   CmdArgs.push_back("-o");
10707   CmdArgs.push_back(Output.getFilename());
10708
10709   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10710     SmallString<261> ImpLib(Output.getFilename());
10711     llvm::sys::path::replace_extension(ImpLib, ".lib");
10712
10713     CmdArgs.push_back("--out-implib");
10714     CmdArgs.push_back(Args.MakeArgString(ImpLib));
10715   }
10716
10717   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10718     const std::string CRTPath(D.SysRoot + "/usr/lib/");
10719     const char *CRTBegin;
10720
10721     CRTBegin =
10722         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10723     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10724   }
10725
10726   Args.AddAllArgs(CmdArgs, options::OPT_L);
10727   TC.AddFilePathLibArgs(Args, CmdArgs);
10728   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10729
10730   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10731       !Args.hasArg(options::OPT_nodefaultlibs)) {
10732     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10733                      !Args.hasArg(options::OPT_static);
10734     if (StaticCXX)
10735       CmdArgs.push_back("-Bstatic");
10736     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10737     if (StaticCXX)
10738       CmdArgs.push_back("-Bdynamic");
10739   }
10740
10741   if (!Args.hasArg(options::OPT_nostdlib)) {
10742     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10743       // TODO handle /MT[d] /MD[d]
10744       CmdArgs.push_back("-lmsvcrt");
10745       AddRunTimeLibs(TC, D, CmdArgs, Args);
10746     }
10747   }
10748
10749   if (TC.getSanitizerArgs().needsAsanRt()) {
10750     // TODO handle /MT[d] /MD[d]
10751     if (Args.hasArg(options::OPT_shared)) {
10752       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10753     } else {
10754       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10755         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10756       // Make sure the dynamic runtime thunk is not optimized out at link time
10757       // to ensure proper SEH handling.
10758       CmdArgs.push_back(Args.MakeArgString("--undefined"));
10759       CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10760                                                ? "___asan_seh_interceptor"
10761                                                : "__asan_seh_interceptor"));
10762     }
10763   }
10764
10765   Exec = Args.MakeArgString(TC.GetLinkerPath());
10766
10767   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10768 }
10769
10770 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10771                                           const InputInfo &Output,
10772                                           const InputInfoList &Inputs,
10773                                           const ArgList &Args,
10774                                           const char *LinkingOutput) const {
10775   ArgStringList CmdArgs;
10776   assert(Inputs.size() == 1);
10777   const InputInfo &II = Inputs[0];
10778   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10779          II.getType() == types::TY_PP_CXX);
10780
10781   if (JA.getKind() == Action::PreprocessJobClass) {
10782     Args.ClaimAllArgs();
10783     CmdArgs.push_back("-E");
10784   } else {
10785     assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10786     CmdArgs.push_back("-S");
10787     CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10788   }
10789   CmdArgs.push_back("-DMYRIAD2");
10790
10791   // Append all -I, -iquote, -isystem paths, defines/undefines,
10792   // 'f' flags, optimize flags, and warning options.
10793   // These are spelled the same way in clang and moviCompile.
10794   Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10795                             options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10796                             options::OPT_f_Group, options::OPT_f_clang_Group,
10797                             options::OPT_g_Group, options::OPT_M_Group,
10798                             options::OPT_O_Group, options::OPT_W_Group,
10799                             options::OPT_mcpu_EQ});
10800
10801   // If we're producing a dependency file, and assembly is the final action,
10802   // then the name of the target in the dependency file should be the '.o'
10803   // file, not the '.s' file produced by this step. For example, instead of
10804   //  /tmp/mumble.s: mumble.c .../someheader.h
10805   // the filename on the lefthand side should be "mumble.o"
10806   if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10807       C.getActions().size() == 1 &&
10808       C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10809     Arg *A = Args.getLastArg(options::OPT_o);
10810     if (A) {
10811       CmdArgs.push_back("-MT");
10812       CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10813     }
10814   }
10815
10816   CmdArgs.push_back(II.getFilename());
10817   CmdArgs.push_back("-o");
10818   CmdArgs.push_back(Output.getFilename());
10819
10820   std::string Exec =
10821       Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10822   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10823                                           CmdArgs, Inputs));
10824 }
10825
10826 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10827                                            const InputInfo &Output,
10828                                            const InputInfoList &Inputs,
10829                                            const ArgList &Args,
10830                                            const char *LinkingOutput) const {
10831   ArgStringList CmdArgs;
10832
10833   assert(Inputs.size() == 1);
10834   const InputInfo &II = Inputs[0];
10835   assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10836   assert(Output.getType() == types::TY_Object);
10837
10838   CmdArgs.push_back("-no6thSlotCompression");
10839   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
10840   if (CPUArg)
10841     CmdArgs.push_back(
10842         Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
10843   CmdArgs.push_back("-noSPrefixing");
10844   CmdArgs.push_back("-a"); // Mystery option.
10845   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10846   for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10847     A->claim();
10848     CmdArgs.push_back(
10849         Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10850   }
10851   CmdArgs.push_back("-elf"); // Output format.
10852   CmdArgs.push_back(II.getFilename());
10853   CmdArgs.push_back(
10854       Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10855
10856   std::string Exec =
10857       Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10858   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10859                                           CmdArgs, Inputs));
10860 }
10861
10862 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10863                                          const InputInfo &Output,
10864                                          const InputInfoList &Inputs,
10865                                          const ArgList &Args,
10866                                          const char *LinkingOutput) const {
10867   const auto &TC =
10868       static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10869   const llvm::Triple &T = TC.getTriple();
10870   ArgStringList CmdArgs;
10871   bool UseStartfiles =
10872       !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10873   bool UseDefaultLibs =
10874       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10875
10876   if (T.getArch() == llvm::Triple::sparc)
10877     CmdArgs.push_back("-EB");
10878   else // SHAVE assumes little-endian, and sparcel is expressly so.
10879     CmdArgs.push_back("-EL");
10880
10881   // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10882   // but we never pass through a --sysroot option and various other bits.
10883   // For example, there are no sanitizers (yet) nor gold linker.
10884
10885   // Eat some arguments that may be present but have no effect.
10886   Args.ClaimAllArgs(options::OPT_g_Group);
10887   Args.ClaimAllArgs(options::OPT_w);
10888   Args.ClaimAllArgs(options::OPT_static_libgcc);
10889
10890   if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10891     CmdArgs.push_back("-s");
10892
10893   CmdArgs.push_back("-o");
10894   CmdArgs.push_back(Output.getFilename());
10895
10896   if (UseStartfiles) {
10897     // If you want startfiles, it means you want the builtin crti and crtbegin,
10898     // but not crt0. Myriad link commands provide their own crt0.o as needed.
10899     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10900     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10901   }
10902
10903   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10904                             options::OPT_e, options::OPT_s, options::OPT_t,
10905                             options::OPT_Z_Flag, options::OPT_r});
10906
10907   TC.AddFilePathLibArgs(Args, CmdArgs);
10908
10909   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10910
10911   if (UseDefaultLibs) {
10912     if (C.getDriver().CCCIsCXX())
10913       CmdArgs.push_back("-lstdc++");
10914     if (T.getOS() == llvm::Triple::RTEMS) {
10915       CmdArgs.push_back("--start-group");
10916       CmdArgs.push_back("-lc");
10917       // You must provide your own "-L" option to enable finding these.
10918       CmdArgs.push_back("-lrtemscpu");
10919       CmdArgs.push_back("-lrtemsbsp");
10920       CmdArgs.push_back("--end-group");
10921     } else {
10922       CmdArgs.push_back("-lc");
10923     }
10924     CmdArgs.push_back("-lgcc");
10925   }
10926   if (UseStartfiles) {
10927     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10928     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10929   }
10930
10931   std::string Exec =
10932       Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10933   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10934                                           CmdArgs, Inputs));
10935 }
10936
10937 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10938                                     const InputInfo &Output,
10939                                     const InputInfoList &Inputs,
10940                                     const ArgList &Args,
10941                                     const char *LinkingOutput) const {
10942   claimNoWarnArgs(Args);
10943   ArgStringList CmdArgs;
10944
10945   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10946
10947   CmdArgs.push_back("-o");
10948   CmdArgs.push_back(Output.getFilename());
10949
10950   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10951   const InputInfo &Input = Inputs[0];
10952   assert(Input.isFilename() && "Invalid input.");
10953   CmdArgs.push_back(Input.getFilename());
10954
10955   const char *Exec =
10956       Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
10957   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10958 }
10959
10960 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10961   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10962   if (SanArgs.needsUbsanRt()) {
10963     CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10964   }
10965   if (SanArgs.needsAsanRt()) {
10966     CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10967   }
10968 }
10969
10970 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10971                                 const JobAction &JA, const InputInfo &Output,
10972                                 const InputInfoList &Inputs,
10973                                 const ArgList &Args,
10974                                 const char *LinkingOutput) {
10975   const toolchains::FreeBSD &ToolChain =
10976       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10977   const Driver &D = ToolChain.getDriver();
10978   ArgStringList CmdArgs;
10979
10980   // Silence warning for "clang -g foo.o -o foo"
10981   Args.ClaimAllArgs(options::OPT_g_Group);
10982   // and "clang -emit-llvm foo.o -o foo"
10983   Args.ClaimAllArgs(options::OPT_emit_llvm);
10984   // and for "clang -w foo.o -o foo". Other warning options are already
10985   // handled somewhere else.
10986   Args.ClaimAllArgs(options::OPT_w);
10987
10988   if (!D.SysRoot.empty())
10989     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10990
10991   if (Args.hasArg(options::OPT_pie))
10992     CmdArgs.push_back("-pie");
10993
10994   if (Args.hasArg(options::OPT_rdynamic))
10995     CmdArgs.push_back("-export-dynamic");
10996   if (Args.hasArg(options::OPT_shared))
10997     CmdArgs.push_back("--oformat=so");
10998
10999   if (Output.isFilename()) {
11000     CmdArgs.push_back("-o");
11001     CmdArgs.push_back(Output.getFilename());
11002   } else {
11003     assert(Output.isNothing() && "Invalid output.");
11004   }
11005
11006   AddPS4SanitizerArgs(ToolChain, CmdArgs);
11007
11008   Args.AddAllArgs(CmdArgs, options::OPT_L);
11009   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11010   Args.AddAllArgs(CmdArgs, options::OPT_e);
11011   Args.AddAllArgs(CmdArgs, options::OPT_s);
11012   Args.AddAllArgs(CmdArgs, options::OPT_t);
11013   Args.AddAllArgs(CmdArgs, options::OPT_r);
11014
11015   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11016     CmdArgs.push_back("--no-demangle");
11017
11018   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11019
11020   if (Args.hasArg(options::OPT_pthread)) {
11021     CmdArgs.push_back("-lpthread");
11022   }
11023
11024   const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11025
11026   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11027 }
11028
11029 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
11030                                  const JobAction &JA, const InputInfo &Output,
11031                                  const InputInfoList &Inputs,
11032                                  const ArgList &Args,
11033                                  const char *LinkingOutput) {
11034   const toolchains::FreeBSD &ToolChain =
11035       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
11036   const Driver &D = ToolChain.getDriver();
11037   ArgStringList CmdArgs;
11038
11039   // Silence warning for "clang -g foo.o -o foo"
11040   Args.ClaimAllArgs(options::OPT_g_Group);
11041   // and "clang -emit-llvm foo.o -o foo"
11042   Args.ClaimAllArgs(options::OPT_emit_llvm);
11043   // and for "clang -w foo.o -o foo". Other warning options are already
11044   // handled somewhere else.
11045   Args.ClaimAllArgs(options::OPT_w);
11046
11047   if (!D.SysRoot.empty())
11048     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11049
11050   if (Args.hasArg(options::OPT_pie))
11051     CmdArgs.push_back("-pie");
11052
11053   if (Args.hasArg(options::OPT_static)) {
11054     CmdArgs.push_back("-Bstatic");
11055   } else {
11056     if (Args.hasArg(options::OPT_rdynamic))
11057       CmdArgs.push_back("-export-dynamic");
11058     CmdArgs.push_back("--eh-frame-hdr");
11059     if (Args.hasArg(options::OPT_shared)) {
11060       CmdArgs.push_back("-Bshareable");
11061     } else {
11062       CmdArgs.push_back("-dynamic-linker");
11063       CmdArgs.push_back("/libexec/ld-elf.so.1");
11064     }
11065     CmdArgs.push_back("--enable-new-dtags");
11066   }
11067
11068   if (Output.isFilename()) {
11069     CmdArgs.push_back("-o");
11070     CmdArgs.push_back(Output.getFilename());
11071   } else {
11072     assert(Output.isNothing() && "Invalid output.");
11073   }
11074
11075   AddPS4SanitizerArgs(ToolChain, CmdArgs);
11076
11077   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11078     const char *crt1 = nullptr;
11079     if (!Args.hasArg(options::OPT_shared)) {
11080       if (Args.hasArg(options::OPT_pg))
11081         crt1 = "gcrt1.o";
11082       else if (Args.hasArg(options::OPT_pie))
11083         crt1 = "Scrt1.o";
11084       else
11085         crt1 = "crt1.o";
11086     }
11087     if (crt1)
11088       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
11089
11090     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
11091
11092     const char *crtbegin = nullptr;
11093     if (Args.hasArg(options::OPT_static))
11094       crtbegin = "crtbeginT.o";
11095     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11096       crtbegin = "crtbeginS.o";
11097     else
11098       crtbegin = "crtbegin.o";
11099
11100     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
11101   }
11102
11103   Args.AddAllArgs(CmdArgs, options::OPT_L);
11104   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
11105   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11106   Args.AddAllArgs(CmdArgs, options::OPT_e);
11107   Args.AddAllArgs(CmdArgs, options::OPT_s);
11108   Args.AddAllArgs(CmdArgs, options::OPT_t);
11109   Args.AddAllArgs(CmdArgs, options::OPT_r);
11110
11111   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11112     CmdArgs.push_back("--no-demangle");
11113
11114   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11115
11116   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11117     // For PS4, we always want to pass libm, libstdc++ and libkernel
11118     // libraries for both C and C++ compilations.
11119     CmdArgs.push_back("-lkernel");
11120     if (D.CCCIsCXX()) {
11121       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
11122       if (Args.hasArg(options::OPT_pg))
11123         CmdArgs.push_back("-lm_p");
11124       else
11125         CmdArgs.push_back("-lm");
11126     }
11127     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
11128     // the default system libraries. Just mimic this for now.
11129     if (Args.hasArg(options::OPT_pg))
11130       CmdArgs.push_back("-lgcc_p");
11131     else
11132       CmdArgs.push_back("-lcompiler_rt");
11133     if (Args.hasArg(options::OPT_static)) {
11134       CmdArgs.push_back("-lstdc++");
11135     } else if (Args.hasArg(options::OPT_pg)) {
11136       CmdArgs.push_back("-lgcc_eh_p");
11137     } else {
11138       CmdArgs.push_back("--as-needed");
11139       CmdArgs.push_back("-lstdc++");
11140       CmdArgs.push_back("--no-as-needed");
11141     }
11142
11143     if (Args.hasArg(options::OPT_pthread)) {
11144       if (Args.hasArg(options::OPT_pg))
11145         CmdArgs.push_back("-lpthread_p");
11146       else
11147         CmdArgs.push_back("-lpthread");
11148     }
11149
11150     if (Args.hasArg(options::OPT_pg)) {
11151       if (Args.hasArg(options::OPT_shared))
11152         CmdArgs.push_back("-lc");
11153       else {
11154         if (Args.hasArg(options::OPT_static)) {
11155           CmdArgs.push_back("--start-group");
11156           CmdArgs.push_back("-lc_p");
11157           CmdArgs.push_back("-lpthread_p");
11158           CmdArgs.push_back("--end-group");
11159         } else {
11160           CmdArgs.push_back("-lc_p");
11161         }
11162       }
11163       CmdArgs.push_back("-lgcc_p");
11164     } else {
11165       if (Args.hasArg(options::OPT_static)) {
11166         CmdArgs.push_back("--start-group");
11167         CmdArgs.push_back("-lc");
11168         CmdArgs.push_back("-lpthread");
11169         CmdArgs.push_back("--end-group");
11170       } else {
11171         CmdArgs.push_back("-lc");
11172       }
11173       CmdArgs.push_back("-lcompiler_rt");
11174     }
11175
11176     if (Args.hasArg(options::OPT_static)) {
11177       CmdArgs.push_back("-lstdc++");
11178     } else if (Args.hasArg(options::OPT_pg)) {
11179       CmdArgs.push_back("-lgcc_eh_p");
11180     } else {
11181       CmdArgs.push_back("--as-needed");
11182       CmdArgs.push_back("-lstdc++");
11183       CmdArgs.push_back("--no-as-needed");
11184     }
11185   }
11186
11187   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11188     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11189       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
11190     else
11191       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
11192     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
11193   }
11194
11195   const char *Exec =
11196 #ifdef LLVM_ON_WIN32
11197       Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
11198 #else
11199       Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11200 #endif
11201
11202   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11203 }
11204
11205 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
11206                                 const InputInfo &Output,
11207                                 const InputInfoList &Inputs,
11208                                 const ArgList &Args,
11209                                 const char *LinkingOutput) const {
11210   const toolchains::FreeBSD &ToolChain =
11211       static_cast<const toolchains::FreeBSD &>(getToolChain());
11212   const Driver &D = ToolChain.getDriver();
11213   bool PS4Linker;
11214   StringRef LinkerOptName;
11215   if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
11216     LinkerOptName = A->getValue();
11217     if (LinkerOptName != "ps4" && LinkerOptName != "gold")
11218       D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
11219   }
11220
11221   if (LinkerOptName == "gold")
11222     PS4Linker = false;
11223   else if (LinkerOptName == "ps4")
11224     PS4Linker = true;
11225   else
11226     PS4Linker = !Args.hasArg(options::OPT_shared);
11227
11228   if (PS4Linker)
11229     ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11230   else
11231     ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11232 }
11233
11234 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11235                                     const InputInfo &Output,
11236                                     const InputInfoList &Inputs,
11237                                     const ArgList &Args,
11238                                     const char *LinkingOutput) const {
11239   const auto &TC =
11240       static_cast<const toolchains::CudaToolChain &>(getToolChain());
11241   assert(TC.getTriple().isNVPTX() && "Wrong platform");
11242
11243   // Obtain architecture from the action.
11244   CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
11245   assert(gpu_arch != CudaArch::UNKNOWN &&
11246          "Device action expected to have an architecture.");
11247
11248   // Check that our installation's ptxas supports gpu_arch.
11249   if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
11250     TC.cudaInstallation().CheckCudaVersionSupportsArch(gpu_arch);
11251   }
11252
11253   ArgStringList CmdArgs;
11254   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
11255   if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
11256                    options::OPT_no_cuda_noopt_device_debug, false)) {
11257     // ptxas does not accept -g option if optimization is enabled, so
11258     // we ignore the compiler's -O* options if we want debug info.
11259     CmdArgs.push_back("-g");
11260     CmdArgs.push_back("--dont-merge-basicblocks");
11261     CmdArgs.push_back("--return-at-end");
11262   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
11263     // Map the -O we received to -O{0,1,2,3}.
11264     //
11265     // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
11266     // default, so it may correspond more closely to the spirit of clang -O2.
11267
11268     // -O3 seems like the least-bad option when -Osomething is specified to
11269     // clang but it isn't handled below.
11270     StringRef OOpt = "3";
11271     if (A->getOption().matches(options::OPT_O4) ||
11272         A->getOption().matches(options::OPT_Ofast))
11273       OOpt = "3";
11274     else if (A->getOption().matches(options::OPT_O0))
11275       OOpt = "0";
11276     else if (A->getOption().matches(options::OPT_O)) {
11277       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
11278       OOpt = llvm::StringSwitch<const char *>(A->getValue())
11279                  .Case("1", "1")
11280                  .Case("2", "2")
11281                  .Case("3", "3")
11282                  .Case("s", "2")
11283                  .Case("z", "2")
11284                  .Default("2");
11285     }
11286     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
11287   } else {
11288     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
11289     // to no optimizations, but ptxas's default is -O3.
11290     CmdArgs.push_back("-O0");
11291   }
11292
11293   CmdArgs.push_back("--gpu-name");
11294   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
11295   CmdArgs.push_back("--output-file");
11296   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11297   for (const auto& II : Inputs)
11298     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
11299
11300   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
11301     CmdArgs.push_back(Args.MakeArgString(A));
11302
11303   const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
11304   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11305 }
11306
11307 // All inputs to this linker must be from CudaDeviceActions, as we need to look
11308 // at the Inputs' Actions in order to figure out which GPU architecture they
11309 // correspond to.
11310 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11311                                  const InputInfo &Output,
11312                                  const InputInfoList &Inputs,
11313                                  const ArgList &Args,
11314                                  const char *LinkingOutput) const {
11315   const auto &TC =
11316       static_cast<const toolchains::CudaToolChain &>(getToolChain());
11317   assert(TC.getTriple().isNVPTX() && "Wrong platform");
11318
11319   ArgStringList CmdArgs;
11320   CmdArgs.push_back("--cuda");
11321   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
11322   CmdArgs.push_back(Args.MakeArgString("--create"));
11323   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11324
11325   for (const auto& II : Inputs) {
11326     auto *A = II.getAction();
11327     assert(A->getInputs().size() == 1 &&
11328            "Device offload action is expected to have a single input");
11329     const char *gpu_arch_str = A->getOffloadingArch();
11330     assert(gpu_arch_str &&
11331            "Device action expected to have associated a GPU architecture!");
11332     CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
11333
11334     // We need to pass an Arch of the form "sm_XX" for cubin files and
11335     // "compute_XX" for ptx.
11336     const char *Arch =
11337         (II.getType() == types::TY_PP_Asm)
11338             ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
11339             : gpu_arch_str;
11340     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
11341                                          Arch + ",file=" + II.getFilename()));
11342   }
11343
11344   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
11345     CmdArgs.push_back(Args.MakeArgString(A));
11346
11347   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
11348   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11349 }