]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Tools.cpp
Merge llvm, clang, lld and lldb trunk r291012, and resolve conflicts.
[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/ScopedPrinter.h"
44 #include "llvm/Support/TargetParser.h"
45 #include "llvm/Support/YAMLParser.h"
46
47 #ifdef LLVM_ON_UNIX
48 #include <unistd.h> // For getuid().
49 #endif
50
51 using namespace clang::driver;
52 using namespace clang::driver::tools;
53 using namespace clang;
54 using namespace llvm::opt;
55
56 static void handleTargetFeaturesGroup(const ArgList &Args,
57                                       std::vector<StringRef> &Features,
58                                       OptSpecifier Group) {
59   for (const Arg *A : Args.filtered(Group)) {
60     StringRef Name = A->getOption().getName();
61     A->claim();
62
63     // Skip over "-m".
64     assert(Name.startswith("m") && "Invalid feature name.");
65     Name = Name.substr(1);
66
67     bool IsNegative = Name.startswith("no-");
68     if (IsNegative)
69       Name = Name.substr(3);
70     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
71   }
72 }
73
74 static const char *getSparcAsmModeForCPU(StringRef Name,
75                                          const llvm::Triple &Triple) {
76   if (Triple.getArch() == llvm::Triple::sparcv9) {
77     return llvm::StringSwitch<const char *>(Name)
78           .Case("niagara", "-Av9b")
79           .Case("niagara2", "-Av9b")
80           .Case("niagara3", "-Av9d")
81           .Case("niagara4", "-Av9d")
82           .Default("-Av9");
83   } else {
84     return llvm::StringSwitch<const char *>(Name)
85           .Case("v8", "-Av8")
86           .Case("supersparc", "-Av8")
87           .Case("sparclite", "-Asparclite")
88           .Case("f934", "-Asparclite")
89           .Case("hypersparc", "-Av8")
90           .Case("sparclite86x", "-Asparclite")
91           .Case("sparclet", "-Asparclet")
92           .Case("tsc701", "-Asparclet")
93           .Case("v9", "-Av8plus")
94           .Case("ultrasparc", "-Av8plus")
95           .Case("ultrasparc3", "-Av8plus")
96           .Case("niagara", "-Av8plusb")
97           .Case("niagara2", "-Av8plusb")
98           .Case("niagara3", "-Av8plusd")
99           .Case("niagara4", "-Av8plusd")
100           .Case("leon2", "-Av8")
101           .Case("at697e", "-Av8")
102           .Case("at697f", "-Av8")
103           .Case("leon3", "-Av8")
104           .Case("ut699", "-Av8")
105           .Case("gr712rc", "-Av8")
106           .Case("leon4", "-Av8")
107           .Case("gr740", "-Av8")
108           .Default("-Av8");
109   }
110 }
111
112 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
113   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
114     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
115         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
116       D.Diag(diag::err_drv_argument_only_allowed_with)
117           << A->getBaseArg().getAsString(Args)
118           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
119     }
120   }
121 }
122
123 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
124   // In gcc, only ARM checks this, but it seems reasonable to check universally.
125   if (Args.hasArg(options::OPT_static))
126     if (const Arg *A =
127             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
128       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
129                                                       << "-static";
130 }
131
132 // Add backslashes to escape spaces and other backslashes.
133 // This is used for the space-separated argument list specified with
134 // the -dwarf-debug-flags option.
135 static void EscapeSpacesAndBackslashes(const char *Arg,
136                                        SmallVectorImpl<char> &Res) {
137   for (; *Arg; ++Arg) {
138     switch (*Arg) {
139     default:
140       break;
141     case ' ':
142     case '\\':
143       Res.push_back('\\');
144       break;
145     }
146     Res.push_back(*Arg);
147   }
148 }
149
150 // Quote target names for inclusion in GNU Make dependency files.
151 // Only the characters '$', '#', ' ', '\t' are quoted.
152 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
153   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
154     switch (Target[i]) {
155     case ' ':
156     case '\t':
157       // Escape the preceding backslashes
158       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
159         Res.push_back('\\');
160
161       // Escape the space/tab
162       Res.push_back('\\');
163       break;
164     case '$':
165       Res.push_back('$');
166       break;
167     case '#':
168       Res.push_back('\\');
169       break;
170     default:
171       break;
172     }
173
174     Res.push_back(Target[i]);
175   }
176 }
177
178 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
179                              const char *ArgName, const char *EnvVar) {
180   const char *DirList = ::getenv(EnvVar);
181   bool CombinedArg = false;
182
183   if (!DirList)
184     return; // Nothing to do.
185
186   StringRef Name(ArgName);
187   if (Name.equals("-I") || Name.equals("-L"))
188     CombinedArg = true;
189
190   StringRef Dirs(DirList);
191   if (Dirs.empty()) // Empty string should not add '.'.
192     return;
193
194   StringRef::size_type Delim;
195   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
196     if (Delim == 0) { // Leading colon.
197       if (CombinedArg) {
198         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
199       } else {
200         CmdArgs.push_back(ArgName);
201         CmdArgs.push_back(".");
202       }
203     } else {
204       if (CombinedArg) {
205         CmdArgs.push_back(
206             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
207       } else {
208         CmdArgs.push_back(ArgName);
209         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
210       }
211     }
212     Dirs = Dirs.substr(Delim + 1);
213   }
214
215   if (Dirs.empty()) { // Trailing colon.
216     if (CombinedArg) {
217       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
218     } else {
219       CmdArgs.push_back(ArgName);
220       CmdArgs.push_back(".");
221     }
222   } else { // Add the last path.
223     if (CombinedArg) {
224       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
225     } else {
226       CmdArgs.push_back(ArgName);
227       CmdArgs.push_back(Args.MakeArgString(Dirs));
228     }
229   }
230 }
231
232 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
233                             const ArgList &Args, ArgStringList &CmdArgs,
234                             const JobAction &JA) {
235   const Driver &D = TC.getDriver();
236
237   // Add extra linker input arguments which are not treated as inputs
238   // (constructed via -Xarch_).
239   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
240
241   for (const auto &II : Inputs) {
242     // If the current tool chain refers to an OpenMP offloading host, we should
243     // ignore inputs that refer to OpenMP offloading devices - they will be
244     // embedded according to a proper linker script.
245     if (auto *IA = II.getAction())
246       if (JA.isHostOffloading(Action::OFK_OpenMP) &&
247           IA->isDeviceOffloading(Action::OFK_OpenMP))
248         continue;
249
250     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
251       // Don't try to pass LLVM inputs unless we have native support.
252       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
253
254     // Add filenames immediately.
255     if (II.isFilename()) {
256       CmdArgs.push_back(II.getFilename());
257       continue;
258     }
259
260     // Otherwise, this is a linker input argument.
261     const Arg &A = II.getInputArg();
262
263     // Handle reserved library options.
264     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
265       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
266     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
267       TC.AddCCKextLibArgs(Args, CmdArgs);
268     else if (A.getOption().matches(options::OPT_z)) {
269       // Pass -z prefix for gcc linker compatibility.
270       A.claim();
271       A.render(Args, CmdArgs);
272     } else {
273       A.renderAsInput(Args, CmdArgs);
274     }
275   }
276
277   // LIBRARY_PATH - included following the user specified library paths.
278   //                and only supported on native toolchains.
279   if (!TC.isCrossCompiling())
280     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
281 }
282
283 /// Add OpenMP linker script arguments at the end of the argument list so that
284 /// the fat binary is built by embedding each of the device images into the
285 /// host. The linker script also defines a few symbols required by the code
286 /// generation so that the images can be easily retrieved at runtime by the
287 /// offloading library. This should be used only in tool chains that support
288 /// linker scripts.
289 static void AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
290                                   const InputInfo &Output,
291                                   const InputInfoList &Inputs,
292                                   const ArgList &Args, ArgStringList &CmdArgs,
293                                   const JobAction &JA) {
294
295   // If this is not an OpenMP host toolchain, we don't need to do anything.
296   if (!JA.isHostOffloading(Action::OFK_OpenMP))
297     return;
298
299   // Create temporary linker script. Keep it if save-temps is enabled.
300   const char *LKS;
301   SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
302   if (C.getDriver().isSaveTempsEnabled()) {
303     llvm::sys::path::replace_extension(Name, "lk");
304     LKS = C.getArgs().MakeArgString(Name.c_str());
305   } else {
306     llvm::sys::path::replace_extension(Name, "");
307     Name = C.getDriver().GetTemporaryPath(Name, "lk");
308     LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
309   }
310
311   // Add linker script option to the command.
312   CmdArgs.push_back("-T");
313   CmdArgs.push_back(LKS);
314
315   // Create a buffer to write the contents of the linker script.
316   std::string LksBuffer;
317   llvm::raw_string_ostream LksStream(LksBuffer);
318
319   // Get the OpenMP offload tool chains so that we can extract the triple
320   // associated with each device input.
321   auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
322   assert(OpenMPToolChains.first != OpenMPToolChains.second &&
323          "No OpenMP toolchains??");
324
325   // Track the input file name and device triple in order to build the script,
326   // inserting binaries in the designated sections.
327   SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
328
329   // Add commands to embed target binaries. We ensure that each section and
330   // image is 16-byte aligned. This is not mandatory, but increases the
331   // likelihood of data to be aligned with a cache block in several main host
332   // machines.
333   LksStream << "/*\n";
334   LksStream << "       OpenMP Offload Linker Script\n";
335   LksStream << " *** Automatically generated by Clang ***\n";
336   LksStream << "*/\n";
337   LksStream << "TARGET(binary)\n";
338   auto DTC = OpenMPToolChains.first;
339   for (auto &II : Inputs) {
340     const Action *A = II.getAction();
341     // Is this a device linking action?
342     if (A && isa<LinkJobAction>(A) &&
343         A->isDeviceOffloading(Action::OFK_OpenMP)) {
344       assert(DTC != OpenMPToolChains.second &&
345              "More device inputs than device toolchains??");
346       InputBinaryInfo.push_back(std::make_pair(
347           DTC->second->getTriple().normalize(), II.getFilename()));
348       ++DTC;
349       LksStream << "INPUT(" << II.getFilename() << ")\n";
350     }
351   }
352
353   assert(DTC == OpenMPToolChains.second &&
354          "Less device inputs than device toolchains??");
355
356   LksStream << "SECTIONS\n";
357   LksStream << "{\n";
358   LksStream << "  .omp_offloading :\n";
359   LksStream << "  ALIGN(0x10)\n";
360   LksStream << "  {\n";
361
362   for (auto &BI : InputBinaryInfo) {
363     LksStream << "    . = ALIGN(0x10);\n";
364     LksStream << "    PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
365               << " = .);\n";
366     LksStream << "    " << BI.second << "\n";
367     LksStream << "    PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
368               << " = .);\n";
369   }
370
371   LksStream << "  }\n";
372   // Add commands to define host entries begin and end. We use 1-byte subalign
373   // so that the linker does not add any padding and the elements in this
374   // section form an array.
375   LksStream << "  .omp_offloading.entries :\n";
376   LksStream << "  ALIGN(0x10)\n";
377   LksStream << "  SUBALIGN(0x01)\n";
378   LksStream << "  {\n";
379   LksStream << "    PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
380   LksStream << "    *(.omp_offloading.entries)\n";
381   LksStream << "    PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
382   LksStream << "  }\n";
383   LksStream << "}\n";
384   LksStream << "INSERT BEFORE .data\n";
385   LksStream.flush();
386
387   // Dump the contents of the linker script if the user requested that. We
388   // support this option to enable testing of behavior with -###.
389   if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
390     llvm::errs() << LksBuffer;
391
392   // If this is a dry run, do not create the linker script file.
393   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
394     return;
395
396   // Open script file and write the contents.
397   std::error_code EC;
398   llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
399
400   if (EC) {
401     C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
402     return;
403   }
404
405   Lksf << LksBuffer;
406 }
407
408 /// \brief Determine whether Objective-C automated reference counting is
409 /// enabled.
410 static bool isObjCAutoRefCount(const ArgList &Args) {
411   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
412 }
413
414 /// \brief Determine whether we are linking the ObjC runtime.
415 static bool isObjCRuntimeLinked(const ArgList &Args) {
416   if (isObjCAutoRefCount(Args)) {
417     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
418     return true;
419   }
420   return Args.hasArg(options::OPT_fobjc_link_runtime);
421 }
422
423 static bool forwardToGCC(const Option &O) {
424   // Don't forward inputs from the original command line.  They are added from
425   // InputInfoList.
426   return O.getKind() != Option::InputClass &&
427          !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
428 }
429
430 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
431 /// offloading tool chain that is associated with the current action \a JA.
432 static void
433 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
434                            const ToolChain &RegularToolChain,
435                            llvm::function_ref<void(const ToolChain &)> Work) {
436   // Apply Work on the current/regular tool chain.
437   Work(RegularToolChain);
438
439   // Apply Work on all the offloading tool chains associated with the current
440   // action.
441   if (JA.isHostOffloading(Action::OFK_Cuda))
442     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
443   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
444     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
445
446   //
447   // TODO: Add support for other offloading programming models here.
448   //
449 }
450
451 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
452                                     const Driver &D, const ArgList &Args,
453                                     ArgStringList &CmdArgs,
454                                     const InputInfo &Output,
455                                     const InputInfoList &Inputs) const {
456   Arg *A;
457   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
458
459   CheckPreprocessingOptions(D, Args);
460
461   Args.AddLastArg(CmdArgs, options::OPT_C);
462   Args.AddLastArg(CmdArgs, options::OPT_CC);
463
464   // Handle dependency file generation.
465   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
466       (A = Args.getLastArg(options::OPT_MD)) ||
467       (A = Args.getLastArg(options::OPT_MMD))) {
468     // Determine the output location.
469     const char *DepFile;
470     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
471       DepFile = MF->getValue();
472       C.addFailureResultFile(DepFile, &JA);
473     } else if (Output.getType() == types::TY_Dependencies) {
474       DepFile = Output.getFilename();
475     } else if (A->getOption().matches(options::OPT_M) ||
476                A->getOption().matches(options::OPT_MM)) {
477       DepFile = "-";
478     } else {
479       DepFile = getDependencyFileName(Args, Inputs);
480       C.addFailureResultFile(DepFile, &JA);
481     }
482     CmdArgs.push_back("-dependency-file");
483     CmdArgs.push_back(DepFile);
484
485     // Add a default target if one wasn't specified.
486     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
487       const char *DepTarget;
488
489       // If user provided -o, that is the dependency target, except
490       // when we are only generating a dependency file.
491       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
492       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
493         DepTarget = OutputOpt->getValue();
494       } else {
495         // Otherwise derive from the base input.
496         //
497         // FIXME: This should use the computed output file location.
498         SmallString<128> P(Inputs[0].getBaseInput());
499         llvm::sys::path::replace_extension(P, "o");
500         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
501       }
502
503       CmdArgs.push_back("-MT");
504       SmallString<128> Quoted;
505       QuoteTarget(DepTarget, Quoted);
506       CmdArgs.push_back(Args.MakeArgString(Quoted));
507     }
508
509     if (A->getOption().matches(options::OPT_M) ||
510         A->getOption().matches(options::OPT_MD))
511       CmdArgs.push_back("-sys-header-deps");
512     if ((isa<PrecompileJobAction>(JA) &&
513          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
514         Args.hasArg(options::OPT_fmodule_file_deps))
515       CmdArgs.push_back("-module-file-deps");
516   }
517
518   if (Args.hasArg(options::OPT_MG)) {
519     if (!A || A->getOption().matches(options::OPT_MD) ||
520         A->getOption().matches(options::OPT_MMD))
521       D.Diag(diag::err_drv_mg_requires_m_or_mm);
522     CmdArgs.push_back("-MG");
523   }
524
525   Args.AddLastArg(CmdArgs, options::OPT_MP);
526   Args.AddLastArg(CmdArgs, options::OPT_MV);
527
528   // Convert all -MQ <target> args to -MT <quoted target>
529   for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
530     A->claim();
531
532     if (A->getOption().matches(options::OPT_MQ)) {
533       CmdArgs.push_back("-MT");
534       SmallString<128> Quoted;
535       QuoteTarget(A->getValue(), Quoted);
536       CmdArgs.push_back(Args.MakeArgString(Quoted));
537
538       // -MT flag - no change
539     } else {
540       A->render(Args, CmdArgs);
541     }
542   }
543
544   // Add offload include arguments specific for CUDA.  This must happen before
545   // we -I or -include anything else, because we must pick up the CUDA headers
546   // from the particular CUDA installation, rather than from e.g.
547   // /usr/local/include.
548   if (JA.isOffloading(Action::OFK_Cuda))
549     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
550
551   // Add -i* options, and automatically translate to
552   // -include-pch/-include-pth for transparent PCH support. It's
553   // wonky, but we include looking for .gch so we can support seamless
554   // replacement into a build system already set up to be generating
555   // .gch files.
556   int YcIndex = -1, YuIndex = -1;
557   {
558     int AI = -1;
559     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
560     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
561     for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
562       // Walk the whole i_Group and skip non "-include" flags so that the index
563       // here matches the index in the next loop below.
564       ++AI;
565       if (!A->getOption().matches(options::OPT_include))
566         continue;
567       if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
568         YcIndex = AI;
569       if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
570         YuIndex = AI;
571     }
572   }
573   if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
574     Driver::InputList Inputs;
575     D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
576     assert(Inputs.size() == 1 && "Need one input when building pch");
577     CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
578                                          Inputs[0].second->getValue()));
579   }
580
581   bool RenderedImplicitInclude = false;
582   int AI = -1;
583   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
584     ++AI;
585
586     if (getToolChain().getDriver().IsCLMode() &&
587         A->getOption().matches(options::OPT_include)) {
588       // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
589       // include is compiled into foo.h, and everything after goes into
590       // the .obj file. /Yufoo.h means that all includes prior to and including
591       // foo.h are completely skipped and replaced with a use of the pch file
592       // for foo.h.  (Each flag can have at most one value, multiple /Yc flags
593       // just mean that the last one wins.)  If /Yc and /Yu are both present
594       // and refer to the same file, /Yc wins.
595       // Note that OPT__SLASH_FI gets mapped to OPT_include.
596       // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
597       // cl.exe seems to support both flags with different values, but that
598       // seems strange (which flag does /Fp now refer to?), so don't implement
599       // that until someone needs it.
600       int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
601       if (PchIndex != -1) {
602         if (isa<PrecompileJobAction>(JA)) {
603           // When building the pch, skip all includes after the pch.
604           assert(YcIndex != -1 && PchIndex == YcIndex);
605           if (AI >= YcIndex)
606             continue;
607         } else {
608           // When using the pch, skip all includes prior to the pch.
609           if (AI < PchIndex) {
610             A->claim();
611             continue;
612           }
613           if (AI == PchIndex) {
614             A->claim();
615             CmdArgs.push_back("-include-pch");
616             CmdArgs.push_back(
617                 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
618             continue;
619           }
620         }
621       }
622     } else if (A->getOption().matches(options::OPT_include)) {
623       // Handling of gcc-style gch precompiled headers.
624       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
625       RenderedImplicitInclude = true;
626
627       // Use PCH if the user requested it.
628       bool UsePCH = D.CCCUsePCH;
629
630       bool FoundPTH = false;
631       bool FoundPCH = false;
632       SmallString<128> P(A->getValue());
633       // We want the files to have a name like foo.h.pch. Add a dummy extension
634       // so that replace_extension does the right thing.
635       P += ".dummy";
636       if (UsePCH) {
637         llvm::sys::path::replace_extension(P, "pch");
638         if (llvm::sys::fs::exists(P))
639           FoundPCH = true;
640       }
641
642       if (!FoundPCH) {
643         llvm::sys::path::replace_extension(P, "pth");
644         if (llvm::sys::fs::exists(P))
645           FoundPTH = true;
646       }
647
648       if (!FoundPCH && !FoundPTH) {
649         llvm::sys::path::replace_extension(P, "gch");
650         if (llvm::sys::fs::exists(P)) {
651           FoundPCH = UsePCH;
652           FoundPTH = !UsePCH;
653         }
654       }
655
656       if (FoundPCH || FoundPTH) {
657         if (IsFirstImplicitInclude) {
658           A->claim();
659           if (UsePCH)
660             CmdArgs.push_back("-include-pch");
661           else
662             CmdArgs.push_back("-include-pth");
663           CmdArgs.push_back(Args.MakeArgString(P));
664           continue;
665         } else {
666           // Ignore the PCH if not first on command line and emit warning.
667           D.Diag(diag::warn_drv_pch_not_first_include) << P
668                                                        << A->getAsString(Args);
669         }
670       }
671     } else if (A->getOption().matches(options::OPT_isystem_after)) {
672       // Handling of paths which must come late.  These entries are handled by
673       // the toolchain itself after the resource dir is inserted in the right
674       // search order.
675       // Do not claim the argument so that the use of the argument does not
676       // silently go unnoticed on toolchains which do not honour the option.
677       continue;
678     }
679
680     // Not translated, render as usual.
681     A->claim();
682     A->render(Args, CmdArgs);
683   }
684
685   Args.AddAllArgs(CmdArgs,
686                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
687                    options::OPT_F, options::OPT_index_header_map});
688
689   // Add -Wp, and -Xpreprocessor if using the preprocessor.
690
691   // FIXME: There is a very unfortunate problem here, some troubled
692   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
693   // really support that we would have to parse and then translate
694   // those options. :(
695   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
696                        options::OPT_Xpreprocessor);
697
698   // -I- is a deprecated GCC feature, reject it.
699   if (Arg *A = Args.getLastArg(options::OPT_I_))
700     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
701
702   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
703   // -isysroot to the CC1 invocation.
704   StringRef sysroot = C.getSysRoot();
705   if (sysroot != "") {
706     if (!Args.hasArg(options::OPT_isysroot)) {
707       CmdArgs.push_back("-isysroot");
708       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
709     }
710   }
711
712   // Parse additional include paths from environment variables.
713   // FIXME: We should probably sink the logic for handling these from the
714   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
715   // CPATH - included following the user specified includes (but prior to
716   // builtin and standard includes).
717   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
718   // C_INCLUDE_PATH - system includes enabled when compiling C.
719   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
720   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
721   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
722   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
723   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
724   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
725   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
726
727   // While adding the include arguments, we also attempt to retrieve the
728   // arguments of related offloading toolchains or arguments that are specific
729   // of an offloading programming model.
730
731   // Add C++ include arguments, if needed.
732   if (types::isCXX(Inputs[0].getType()))
733     forAllAssociatedToolChains(C, JA, getToolChain(),
734                                [&Args, &CmdArgs](const ToolChain &TC) {
735                                  TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
736                                });
737
738   // Add system include arguments for all targets but IAMCU.
739   if (!IsIAMCU)
740     forAllAssociatedToolChains(C, JA, getToolChain(),
741                                [&Args, &CmdArgs](const ToolChain &TC) {
742                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
743                                });
744   else {
745     // For IAMCU add special include arguments.
746     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
747   }
748 }
749
750 // FIXME: Move to target hook.
751 static bool isSignedCharDefault(const llvm::Triple &Triple) {
752   switch (Triple.getArch()) {
753   default:
754     return true;
755
756   case llvm::Triple::aarch64:
757   case llvm::Triple::aarch64_be:
758   case llvm::Triple::arm:
759   case llvm::Triple::armeb:
760   case llvm::Triple::thumb:
761   case llvm::Triple::thumbeb:
762     if (Triple.isOSDarwin() || Triple.isOSWindows())
763       return true;
764     return false;
765
766   case llvm::Triple::ppc:
767   case llvm::Triple::ppc64:
768     if (Triple.isOSDarwin())
769       return true;
770     return false;
771
772   case llvm::Triple::hexagon:
773   case llvm::Triple::ppc64le:
774   case llvm::Triple::systemz:
775   case llvm::Triple::xcore:
776     return false;
777   }
778 }
779
780 static bool isNoCommonDefault(const llvm::Triple &Triple) {
781   switch (Triple.getArch()) {
782   default:
783     return false;
784
785   case llvm::Triple::xcore:
786   case llvm::Triple::wasm32:
787   case llvm::Triple::wasm64:
788     return true;
789   }
790 }
791
792 // ARM tools start.
793
794 // Get SubArch (vN).
795 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
796   llvm::StringRef Arch = Triple.getArchName();
797   return llvm::ARM::parseArchVersion(Arch);
798 }
799
800 // True if M-profile.
801 static bool isARMMProfile(const llvm::Triple &Triple) {
802   llvm::StringRef Arch = Triple.getArchName();
803   unsigned Profile = llvm::ARM::parseArchProfile(Arch);
804   return Profile == llvm::ARM::PK_M;
805 }
806
807 // Get Arch/CPU from args.
808 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
809                                   llvm::StringRef &CPU, bool FromAs = false) {
810   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
811     CPU = A->getValue();
812   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
813     Arch = A->getValue();
814   if (!FromAs)
815     return;
816
817   for (const Arg *A :
818        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
819     StringRef Value = A->getValue();
820     if (Value.startswith("-mcpu="))
821       CPU = Value.substr(6);
822     if (Value.startswith("-march="))
823       Arch = Value.substr(7);
824   }
825 }
826
827 // Handle -mhwdiv=.
828 // FIXME: Use ARMTargetParser.
829 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
830                                 const ArgList &Args, StringRef HWDiv,
831                                 std::vector<StringRef> &Features) {
832   unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
833   if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
834     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
835 }
836
837 // Handle -mfpu=.
838 static void getARMFPUFeatures(const Driver &D, const Arg *A,
839                               const ArgList &Args, StringRef FPU,
840                               std::vector<StringRef> &Features) {
841   unsigned FPUID = llvm::ARM::parseFPU(FPU);
842   if (!llvm::ARM::getFPUFeatures(FPUID, Features))
843     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
844 }
845
846 // Decode ARM features from string like +[no]featureA+[no]featureB+...
847 static bool DecodeARMFeatures(const Driver &D, StringRef text,
848                               std::vector<StringRef> &Features) {
849   SmallVector<StringRef, 8> Split;
850   text.split(Split, StringRef("+"), -1, false);
851
852   for (StringRef Feature : Split) {
853     StringRef FeatureName = llvm::ARM::getArchExtFeature(Feature);
854     if (!FeatureName.empty())
855       Features.push_back(FeatureName);
856     else
857       return false;
858   }
859   return true;
860 }
861
862 // Check if -march is valid by checking if it can be canonicalised and parsed.
863 // getARMArch is used here instead of just checking the -march value in order
864 // to handle -march=native correctly.
865 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
866                              llvm::StringRef ArchName,
867                              std::vector<StringRef> &Features,
868                              const llvm::Triple &Triple) {
869   std::pair<StringRef, StringRef> Split = ArchName.split("+");
870
871   std::string MArch = arm::getARMArch(ArchName, Triple);
872   if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
873       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
874     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
875 }
876
877 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
878 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
879                             llvm::StringRef CPUName, llvm::StringRef ArchName,
880                             std::vector<StringRef> &Features,
881                             const llvm::Triple &Triple) {
882   std::pair<StringRef, StringRef> Split = CPUName.split("+");
883
884   std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
885   if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
886       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
887     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
888 }
889
890 static bool useAAPCSForMachO(const llvm::Triple &T) {
891   // The backend is hardwired to assume AAPCS for M-class processors, ensure
892   // the frontend matches that.
893   return T.getEnvironment() == llvm::Triple::EABI ||
894          T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
895 }
896
897 // Select the float ABI as determined by -msoft-float, -mhard-float, and
898 // -mfloat-abi=.
899 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
900   const Driver &D = TC.getDriver();
901   const llvm::Triple &Triple = TC.getEffectiveTriple();
902   auto SubArch = getARMSubArchVersionNumber(Triple);
903   arm::FloatABI ABI = FloatABI::Invalid;
904   if (Arg *A =
905           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
906                           options::OPT_mfloat_abi_EQ)) {
907     if (A->getOption().matches(options::OPT_msoft_float)) {
908       ABI = FloatABI::Soft;
909     } else if (A->getOption().matches(options::OPT_mhard_float)) {
910       ABI = FloatABI::Hard;
911     } else {
912       ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
913                 .Case("soft", FloatABI::Soft)
914                 .Case("softfp", FloatABI::SoftFP)
915                 .Case("hard", FloatABI::Hard)
916                 .Default(FloatABI::Invalid);
917       if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
918         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
919         ABI = FloatABI::Soft;
920       }
921     }
922
923     // It is incorrect to select hard float ABI on MachO platforms if the ABI is
924     // "apcs-gnu".
925     if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
926         ABI == FloatABI::Hard) {
927       D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
928                                                        << Triple.getArchName();
929     }
930   }
931
932   // If unspecified, choose the default based on the platform.
933   if (ABI == FloatABI::Invalid) {
934     switch (Triple.getOS()) {
935     case llvm::Triple::Darwin:
936     case llvm::Triple::MacOSX:
937     case llvm::Triple::IOS:
938     case llvm::Triple::TvOS: {
939       // Darwin defaults to "softfp" for v6 and v7.
940       ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
941       ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
942       break;
943     }
944     case llvm::Triple::WatchOS:
945       ABI = FloatABI::Hard;
946       break;
947
948     // FIXME: this is invalid for WindowsCE
949     case llvm::Triple::Win32:
950       ABI = FloatABI::Hard;
951       break;
952
953     case llvm::Triple::FreeBSD:
954       switch (Triple.getEnvironment()) {
955       case llvm::Triple::GNUEABIHF:
956         ABI = FloatABI::Hard;
957         break;
958       default:
959         // FreeBSD defaults to soft float
960         ABI = FloatABI::Soft;
961         break;
962       }
963       break;
964
965     default:
966       switch (Triple.getEnvironment()) {
967       case llvm::Triple::GNUEABIHF:
968       case llvm::Triple::MuslEABIHF:
969       case llvm::Triple::EABIHF:
970         ABI = FloatABI::Hard;
971         break;
972       case llvm::Triple::GNUEABI:
973       case llvm::Triple::MuslEABI:
974       case llvm::Triple::EABI:
975         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
976         ABI = FloatABI::SoftFP;
977         break;
978       case llvm::Triple::Android:
979         ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
980         break;
981       default:
982         // Assume "soft", but warn the user we are guessing.
983         if (Triple.isOSBinFormatMachO() &&
984             Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
985           ABI = FloatABI::Hard;
986         else
987           ABI = FloatABI::Soft;
988
989         if (Triple.getOS() != llvm::Triple::UnknownOS ||
990             !Triple.isOSBinFormatMachO())
991           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
992         break;
993       }
994     }
995   }
996
997   assert(ABI != FloatABI::Invalid && "must select an ABI");
998   return ABI;
999 }
1000
1001 static void getARMTargetFeatures(const ToolChain &TC,
1002                                  const llvm::Triple &Triple,
1003                                  const ArgList &Args,
1004                                  ArgStringList &CmdArgs,
1005                                  std::vector<StringRef> &Features,
1006                                  bool ForAS) {
1007   const Driver &D = TC.getDriver();
1008
1009   bool KernelOrKext =
1010       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1011   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
1012   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
1013   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
1014
1015   if (!ForAS) {
1016     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
1017     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
1018     // stripped out by the ARM target. We should probably pass this a new
1019     // -target-option, which is handled by the -cc1/-cc1as invocation.
1020     //
1021     // FIXME2:  For consistency, it would be ideal if we set up the target
1022     // machine state the same when using the frontend or the assembler. We don't
1023     // currently do that for the assembler, we pass the options directly to the
1024     // backend and never even instantiate the frontend TargetInfo. If we did,
1025     // and used its handleTargetFeatures hook, then we could ensure the
1026     // assembler and the frontend behave the same.
1027
1028     // Use software floating point operations?
1029     if (ABI == arm::FloatABI::Soft)
1030       Features.push_back("+soft-float");
1031
1032     // Use software floating point argument passing?
1033     if (ABI != arm::FloatABI::Hard)
1034       Features.push_back("+soft-float-abi");
1035   } else {
1036     // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
1037     // to the assembler correctly.
1038     for (const Arg *A :
1039          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1040       StringRef Value = A->getValue();
1041       if (Value.startswith("-mfpu=")) {
1042         WaFPU = A;
1043       } else if (Value.startswith("-mcpu=")) {
1044         WaCPU = A;
1045       } else if (Value.startswith("-mhwdiv=")) {
1046         WaHDiv = A;
1047       } else if (Value.startswith("-march=")) {
1048         WaArch = A;
1049       }
1050     }
1051   }
1052
1053   // Check -march. ClangAs gives preference to -Wa,-march=.
1054   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
1055   StringRef ArchName;
1056   if (WaArch) {
1057     if (ArchArg)
1058       D.Diag(clang::diag::warn_drv_unused_argument)
1059           << ArchArg->getAsString(Args);
1060     ArchName = StringRef(WaArch->getValue()).substr(7);
1061     checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
1062     // FIXME: Set Arch.
1063     D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
1064   } else if (ArchArg) {
1065     ArchName = ArchArg->getValue();
1066     checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
1067   }
1068
1069   // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
1070   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
1071   StringRef CPUName;
1072   if (WaCPU) {
1073     if (CPUArg)
1074       D.Diag(clang::diag::warn_drv_unused_argument)
1075           << CPUArg->getAsString(Args);
1076     CPUName = StringRef(WaCPU->getValue()).substr(6);
1077     checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
1078   } else if (CPUArg) {
1079     CPUName = CPUArg->getValue();
1080     checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
1081   }
1082
1083   // Add CPU features for generic CPUs
1084   if (CPUName == "native") {
1085     llvm::StringMap<bool> HostFeatures;
1086     if (llvm::sys::getHostCPUFeatures(HostFeatures))
1087       for (auto &F : HostFeatures)
1088         Features.push_back(
1089             Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1090   }
1091
1092   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
1093   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
1094   if (WaFPU) {
1095     if (FPUArg)
1096       D.Diag(clang::diag::warn_drv_unused_argument)
1097           << FPUArg->getAsString(Args);
1098     getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
1099                       Features);
1100   } else if (FPUArg) {
1101     getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
1102   }
1103
1104   // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
1105   const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
1106   if (WaHDiv) {
1107     if (HDivArg)
1108       D.Diag(clang::diag::warn_drv_unused_argument)
1109           << HDivArg->getAsString(Args);
1110     getARMHWDivFeatures(D, WaHDiv, Args,
1111                         StringRef(WaHDiv->getValue()).substr(8), Features);
1112   } else if (HDivArg)
1113     getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
1114
1115   // Setting -msoft-float effectively disables NEON because of the GCC
1116   // implementation, although the same isn't true of VFP or VFP3.
1117   if (ABI == arm::FloatABI::Soft) {
1118     Features.push_back("-neon");
1119     // Also need to explicitly disable features which imply NEON.
1120     Features.push_back("-crypto");
1121   }
1122
1123   // En/disable crc code generation.
1124   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
1125     if (A->getOption().matches(options::OPT_mcrc))
1126       Features.push_back("+crc");
1127     else
1128       Features.push_back("-crc");
1129   }
1130
1131   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
1132   // neither options are specified, see if we are compiling for kernel/kext and
1133   // decide whether to pass "+long-calls" based on the OS and its version.
1134   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
1135                                options::OPT_mno_long_calls)) {
1136     if (A->getOption().matches(options::OPT_mlong_calls))
1137       Features.push_back("+long-calls");
1138   } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
1139              !Triple.isWatchOS()) {
1140       Features.push_back("+long-calls");
1141   }
1142
1143   // Generate execute-only output (no data access to code sections).
1144   // Supported only on ARMv6T2 and ARMv7 and above.
1145   // Cannot be combined with -mno-movt or -mlong-calls
1146   if (Arg *A = Args.getLastArg(options::OPT_mexecute_only, options::OPT_mno_execute_only)) {
1147     if (A->getOption().matches(options::OPT_mexecute_only)) {
1148       if (getARMSubArchVersionNumber(Triple) < 7 &&
1149           llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::AK_ARMV6T2)
1150             D.Diag(diag::err_target_unsupported_execute_only) << Triple.getArchName();
1151       else if (Arg *B = Args.getLastArg(options::OPT_mno_movt))
1152         D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
1153       // Long calls create constant pool entries and have not yet been fixed up
1154       // to play nicely with execute-only. Hence, they cannot be used in
1155       // execute-only code for now
1156       else if (Arg *B = Args.getLastArg(options::OPT_mlong_calls, options::OPT_mno_long_calls)) {
1157         if (B->getOption().matches(options::OPT_mlong_calls))
1158           D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
1159       }
1160
1161       CmdArgs.push_back("-backend-option");
1162       CmdArgs.push_back("-arm-execute-only");
1163     }
1164   }
1165
1166   // Kernel code has more strict alignment requirements.
1167   if (KernelOrKext)
1168     Features.push_back("+strict-align");
1169   else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
1170                                     options::OPT_munaligned_access)) {
1171     if (A->getOption().matches(options::OPT_munaligned_access)) {
1172       // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
1173       if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1174         D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
1175       // v8M Baseline follows on from v6M, so doesn't support unaligned memory
1176       // access either.
1177       else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
1178         D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
1179     } else
1180       Features.push_back("+strict-align");
1181   } else {
1182     // Assume pre-ARMv6 doesn't support unaligned accesses.
1183     //
1184     // ARMv6 may or may not support unaligned accesses depending on the
1185     // SCTLR.U bit, which is architecture-specific. We assume ARMv6
1186     // Darwin and NetBSD targets support unaligned accesses, and others don't.
1187     //
1188     // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
1189     // which raises an alignment fault on unaligned accesses. Linux
1190     // defaults this bit to 0 and handles it as a system-wide (not
1191     // per-process) setting. It is therefore safe to assume that ARMv7+
1192     // Linux targets support unaligned accesses. The same goes for NaCl.
1193     //
1194     // The above behavior is consistent with GCC.
1195     int VersionNum = getARMSubArchVersionNumber(Triple);
1196     if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
1197       if (VersionNum < 6 ||
1198           Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1199         Features.push_back("+strict-align");
1200     } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
1201       if (VersionNum < 7)
1202         Features.push_back("+strict-align");
1203     } else
1204       Features.push_back("+strict-align");
1205   }
1206
1207   // llvm does not support reserving registers in general. There is support
1208   // for reserving r9 on ARM though (defined as a platform-specific register
1209   // in ARM EABI).
1210   if (Args.hasArg(options::OPT_ffixed_r9))
1211     Features.push_back("+reserve-r9");
1212
1213   // The kext linker doesn't know how to deal with movw/movt.
1214   if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
1215     Features.push_back("+no-movt");
1216 }
1217
1218 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1219                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1220   // Select the ABI to use.
1221   // FIXME: Support -meabi.
1222   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1223   const char *ABIName = nullptr;
1224   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1225     ABIName = A->getValue();
1226   } else if (Triple.isOSBinFormatMachO()) {
1227     if (useAAPCSForMachO(Triple)) {
1228       ABIName = "aapcs";
1229     } else if (Triple.isWatchABI()) {
1230       ABIName = "aapcs16";
1231     } else {
1232       ABIName = "apcs-gnu";
1233     }
1234   } else if (Triple.isOSWindows()) {
1235     // FIXME: this is invalid for WindowsCE
1236     ABIName = "aapcs";
1237   } else {
1238     // Select the default based on the platform.
1239     switch (Triple.getEnvironment()) {
1240     case llvm::Triple::Android:
1241     case llvm::Triple::GNUEABI:
1242     case llvm::Triple::GNUEABIHF:
1243     case llvm::Triple::MuslEABI:
1244     case llvm::Triple::MuslEABIHF:
1245       ABIName = "aapcs-linux";
1246       break;
1247     case llvm::Triple::EABIHF:
1248     case llvm::Triple::EABI:
1249       ABIName = "aapcs";
1250       break;
1251     default:
1252       if (Triple.getOS() == llvm::Triple::NetBSD)
1253         ABIName = "apcs-gnu";
1254       else
1255         ABIName = "aapcs";
1256       break;
1257     }
1258   }
1259   CmdArgs.push_back("-target-abi");
1260   CmdArgs.push_back(ABIName);
1261
1262   // Determine floating point ABI from the options & target defaults.
1263   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1264   if (ABI == arm::FloatABI::Soft) {
1265     // Floating point operations and argument passing are soft.
1266     // FIXME: This changes CPP defines, we need -target-soft-float.
1267     CmdArgs.push_back("-msoft-float");
1268     CmdArgs.push_back("-mfloat-abi");
1269     CmdArgs.push_back("soft");
1270   } else if (ABI == arm::FloatABI::SoftFP) {
1271     // Floating point operations are hard, but argument passing is soft.
1272     CmdArgs.push_back("-mfloat-abi");
1273     CmdArgs.push_back("soft");
1274   } else {
1275     // Floating point operations and argument passing are hard.
1276     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1277     CmdArgs.push_back("-mfloat-abi");
1278     CmdArgs.push_back("hard");
1279   }
1280
1281   // Forward the -mglobal-merge option for explicit control over the pass.
1282   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1283                                options::OPT_mno_global_merge)) {
1284     CmdArgs.push_back("-backend-option");
1285     if (A->getOption().matches(options::OPT_mno_global_merge))
1286       CmdArgs.push_back("-arm-global-merge=false");
1287     else
1288       CmdArgs.push_back("-arm-global-merge=true");
1289   }
1290
1291   if (!Args.hasFlag(options::OPT_mimplicit_float,
1292                     options::OPT_mno_implicit_float, true))
1293     CmdArgs.push_back("-no-implicit-float");
1294 }
1295 // ARM tools end.
1296
1297 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1298 /// targeting. Set \p A to the Arg corresponding to the -mcpu or -mtune
1299 /// arguments if they are provided, or to nullptr otherwise.
1300 static std::string getAArch64TargetCPU(const ArgList &Args, Arg *&A) {
1301   std::string CPU;
1302   // If we have -mtune or -mcpu, use that.
1303   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1304     CPU = StringRef(A->getValue()).lower();
1305   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1306     StringRef Mcpu = A->getValue();
1307     CPU = Mcpu.split("+").first.lower();
1308   }
1309
1310   // Handle CPU name is 'native'.
1311   if (CPU == "native")
1312     return llvm::sys::getHostCPUName();
1313   else if (CPU.size())
1314     return CPU;
1315
1316   // Make sure we pick "cyclone" if -arch is used.
1317   // FIXME: Should this be picked by checking the target triple instead?
1318   if (Args.getLastArg(options::OPT_arch))
1319     return "cyclone";
1320
1321   return "generic";
1322 }
1323
1324 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1325                                  ArgStringList &CmdArgs) const {
1326   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1327
1328   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1329       Args.hasArg(options::OPT_mkernel) ||
1330       Args.hasArg(options::OPT_fapple_kext))
1331     CmdArgs.push_back("-disable-red-zone");
1332
1333   if (!Args.hasFlag(options::OPT_mimplicit_float,
1334                     options::OPT_mno_implicit_float, true))
1335     CmdArgs.push_back("-no-implicit-float");
1336
1337   const char *ABIName = nullptr;
1338   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1339     ABIName = A->getValue();
1340   else if (Triple.isOSDarwin())
1341     ABIName = "darwinpcs";
1342   else
1343     ABIName = "aapcs";
1344
1345   CmdArgs.push_back("-target-abi");
1346   CmdArgs.push_back(ABIName);
1347
1348   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1349                                options::OPT_mno_fix_cortex_a53_835769)) {
1350     CmdArgs.push_back("-backend-option");
1351     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1352       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1353     else
1354       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1355   } else if (Triple.isAndroid()) {
1356     // Enabled A53 errata (835769) workaround by default on android
1357     CmdArgs.push_back("-backend-option");
1358     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1359   }
1360
1361   // Forward the -mglobal-merge option for explicit control over the pass.
1362   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1363                                options::OPT_mno_global_merge)) {
1364     CmdArgs.push_back("-backend-option");
1365     if (A->getOption().matches(options::OPT_mno_global_merge))
1366       CmdArgs.push_back("-aarch64-global-merge=false");
1367     else
1368       CmdArgs.push_back("-aarch64-global-merge=true");
1369   }
1370 }
1371
1372 // Get CPU and ABI names. They are not independent
1373 // so we have to calculate them together.
1374 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1375                             StringRef &CPUName, StringRef &ABIName) {
1376   const char *DefMips32CPU = "mips32r2";
1377   const char *DefMips64CPU = "mips64r2";
1378
1379   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1380   // default for mips64(el)?-img-linux-gnu.
1381   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1382       Triple.getEnvironment() == llvm::Triple::GNU) {
1383     DefMips32CPU = "mips32r6";
1384     DefMips64CPU = "mips64r6";
1385   }
1386
1387   // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1388   if (Triple.isAndroid()) {
1389     DefMips32CPU = "mips32";
1390     DefMips64CPU = "mips64r6";
1391   }
1392
1393   // MIPS3 is the default for mips64*-unknown-openbsd.
1394   if (Triple.getOS() == llvm::Triple::OpenBSD)
1395     DefMips64CPU = "mips3";
1396
1397   if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1398     CPUName = A->getValue();
1399
1400   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1401     ABIName = A->getValue();
1402     // Convert a GNU style Mips ABI name to the name
1403     // accepted by LLVM Mips backend.
1404     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1405                   .Case("32", "o32")
1406                   .Case("64", "n64")
1407                   .Default(ABIName);
1408   }
1409
1410   // Setup default CPU and ABI names.
1411   if (CPUName.empty() && ABIName.empty()) {
1412     switch (Triple.getArch()) {
1413     default:
1414       llvm_unreachable("Unexpected triple arch name");
1415     case llvm::Triple::mips:
1416     case llvm::Triple::mipsel:
1417       CPUName = DefMips32CPU;
1418       break;
1419     case llvm::Triple::mips64:
1420     case llvm::Triple::mips64el:
1421       CPUName = DefMips64CPU;
1422       break;
1423     }
1424   }
1425
1426   if (ABIName.empty() &&
1427       (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
1428        Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
1429     ABIName = llvm::StringSwitch<const char *>(CPUName)
1430                   .Case("mips1", "o32")
1431                   .Case("mips2", "o32")
1432                   .Case("mips3", "n64")
1433                   .Case("mips4", "n64")
1434                   .Case("mips5", "n64")
1435                   .Case("mips32", "o32")
1436                   .Case("mips32r2", "o32")
1437                   .Case("mips32r3", "o32")
1438                   .Case("mips32r5", "o32")
1439                   .Case("mips32r6", "o32")
1440                   .Case("mips64", "n64")
1441                   .Case("mips64r2", "n64")
1442                   .Case("mips64r3", "n64")
1443                   .Case("mips64r5", "n64")
1444                   .Case("mips64r6", "n64")
1445                   .Case("octeon", "n64")
1446                   .Case("p5600", "o32")
1447                   .Default("");
1448   }
1449
1450   if (ABIName.empty()) {
1451     // Deduce ABI name from the target triple.
1452     if (Triple.getArch() == llvm::Triple::mips ||
1453         Triple.getArch() == llvm::Triple::mipsel)
1454       ABIName = "o32";
1455     else
1456       ABIName = "n64";
1457   }
1458
1459   if (CPUName.empty()) {
1460     // Deduce CPU name from ABI name.
1461     CPUName = llvm::StringSwitch<const char *>(ABIName)
1462                   .Case("o32", DefMips32CPU)
1463                   .Cases("n32", "n64", DefMips64CPU)
1464                   .Default("");
1465   }
1466
1467   // FIXME: Warn on inconsistent use of -march and -mabi.
1468 }
1469
1470 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1471                                       const llvm::Triple &Triple) {
1472   StringRef CPUName, ABIName;
1473   tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1474   return llvm::StringSwitch<std::string>(ABIName)
1475       .Case("o32", "")
1476       .Case("n32", "32")
1477       .Case("n64", "64");
1478 }
1479
1480 // Convert ABI name to the GNU tools acceptable variant.
1481 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1482   return llvm::StringSwitch<llvm::StringRef>(ABI)
1483       .Case("o32", "32")
1484       .Case("n64", "64")
1485       .Default(ABI);
1486 }
1487
1488 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1489 // and -mfloat-abi=.
1490 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1491   mips::FloatABI ABI = mips::FloatABI::Invalid;
1492   if (Arg *A =
1493           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1494                           options::OPT_mfloat_abi_EQ)) {
1495     if (A->getOption().matches(options::OPT_msoft_float))
1496       ABI = mips::FloatABI::Soft;
1497     else if (A->getOption().matches(options::OPT_mhard_float))
1498       ABI = mips::FloatABI::Hard;
1499     else {
1500       ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1501                 .Case("soft", mips::FloatABI::Soft)
1502                 .Case("hard", mips::FloatABI::Hard)
1503                 .Default(mips::FloatABI::Invalid);
1504       if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1505         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1506         ABI = mips::FloatABI::Hard;
1507       }
1508     }
1509   }
1510
1511   // If unspecified, choose the default based on the platform.
1512   if (ABI == mips::FloatABI::Invalid) {
1513     // Assume "hard", because it's a default value used by gcc.
1514     // When we start to recognize specific target MIPS processors,
1515     // we will be able to select the default more correctly.
1516     ABI = mips::FloatABI::Hard;
1517   }
1518
1519   assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1520   return ABI;
1521 }
1522
1523 static void AddTargetFeature(const ArgList &Args,
1524                              std::vector<StringRef> &Features,
1525                              OptSpecifier OnOpt, OptSpecifier OffOpt,
1526                              StringRef FeatureName) {
1527   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1528     if (A->getOption().matches(OnOpt))
1529       Features.push_back(Args.MakeArgString("+" + FeatureName));
1530     else
1531       Features.push_back(Args.MakeArgString("-" + FeatureName));
1532   }
1533 }
1534
1535 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1536                                   const ArgList &Args,
1537                                   std::vector<StringRef> &Features) {
1538   StringRef CPUName;
1539   StringRef ABIName;
1540   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1541   ABIName = getGnuCompatibleMipsABIName(ABIName);
1542
1543   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1544                    options::OPT_mabicalls, "noabicalls");
1545
1546   mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1547   if (FloatABI == mips::FloatABI::Soft) {
1548     // FIXME: Note, this is a hack. We need to pass the selected float
1549     // mode to the MipsTargetInfoBase to define appropriate macros there.
1550     // Now it is the only method.
1551     Features.push_back("+soft-float");
1552   }
1553
1554   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1555     StringRef Val = StringRef(A->getValue());
1556     if (Val == "2008") {
1557       if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1558         Features.push_back("+nan2008");
1559       else {
1560         Features.push_back("-nan2008");
1561         D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1562       }
1563     } else if (Val == "legacy") {
1564       if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1565         Features.push_back("-nan2008");
1566       else {
1567         Features.push_back("+nan2008");
1568         D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1569       }
1570     } else
1571       D.Diag(diag::err_drv_unsupported_option_argument)
1572           << A->getOption().getName() << Val;
1573   }
1574
1575   AddTargetFeature(Args, Features, options::OPT_msingle_float,
1576                    options::OPT_mdouble_float, "single-float");
1577   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1578                    "mips16");
1579   AddTargetFeature(Args, Features, options::OPT_mmicromips,
1580                    options::OPT_mno_micromips, "micromips");
1581   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1582                    "dsp");
1583   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1584                    "dspr2");
1585   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1586                    "msa");
1587
1588   // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
1589   // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
1590   // nooddspreg.
1591   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1592                                options::OPT_mfp64)) {
1593     if (A->getOption().matches(options::OPT_mfp32))
1594       Features.push_back(Args.MakeArgString("-fp64"));
1595     else if (A->getOption().matches(options::OPT_mfpxx)) {
1596       Features.push_back(Args.MakeArgString("+fpxx"));
1597       Features.push_back(Args.MakeArgString("+nooddspreg"));
1598     } else
1599       Features.push_back(Args.MakeArgString("+fp64"));
1600   } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1601     Features.push_back(Args.MakeArgString("+fpxx"));
1602     Features.push_back(Args.MakeArgString("+nooddspreg"));
1603   } else if (mips::isFP64ADefault(Triple, CPUName)) {
1604     Features.push_back(Args.MakeArgString("+fp64"));
1605     Features.push_back(Args.MakeArgString("+nooddspreg"));
1606   }
1607
1608   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1609                    options::OPT_modd_spreg, "nooddspreg");
1610 }
1611
1612 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1613                               ArgStringList &CmdArgs) const {
1614   const Driver &D = getToolChain().getDriver();
1615   StringRef CPUName;
1616   StringRef ABIName;
1617   const llvm::Triple &Triple = getToolChain().getTriple();
1618   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1619
1620   CmdArgs.push_back("-target-abi");
1621   CmdArgs.push_back(ABIName.data());
1622
1623   mips::FloatABI ABI = getMipsFloatABI(D, Args);
1624   if (ABI == mips::FloatABI::Soft) {
1625     // Floating point operations and argument passing are soft.
1626     CmdArgs.push_back("-msoft-float");
1627     CmdArgs.push_back("-mfloat-abi");
1628     CmdArgs.push_back("soft");
1629   } else {
1630     // Floating point operations and argument passing are hard.
1631     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1632     CmdArgs.push_back("-mfloat-abi");
1633     CmdArgs.push_back("hard");
1634   }
1635
1636   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1637     if (A->getOption().matches(options::OPT_mxgot)) {
1638       CmdArgs.push_back("-mllvm");
1639       CmdArgs.push_back("-mxgot");
1640     }
1641   }
1642
1643   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1644                                options::OPT_mno_ldc1_sdc1)) {
1645     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1646       CmdArgs.push_back("-mllvm");
1647       CmdArgs.push_back("-mno-ldc1-sdc1");
1648     }
1649   }
1650
1651   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1652                                options::OPT_mno_check_zero_division)) {
1653     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1654       CmdArgs.push_back("-mllvm");
1655       CmdArgs.push_back("-mno-check-zero-division");
1656     }
1657   }
1658
1659   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1660     StringRef v = A->getValue();
1661     CmdArgs.push_back("-mllvm");
1662     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1663     A->claim();
1664   }
1665
1666   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1667     StringRef Val = StringRef(A->getValue());
1668     if (mips::hasCompactBranches(CPUName)) {
1669       if (Val == "never" || Val == "always" || Val == "optimal") {
1670         CmdArgs.push_back("-mllvm");
1671         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1672       } else
1673         D.Diag(diag::err_drv_unsupported_option_argument)
1674             << A->getOption().getName() << Val;
1675     } else
1676       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1677   }
1678 }
1679
1680 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1681 static std::string getPPCTargetCPU(const ArgList &Args) {
1682   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1683     StringRef CPUName = A->getValue();
1684
1685     if (CPUName == "native") {
1686       std::string CPU = llvm::sys::getHostCPUName();
1687       if (!CPU.empty() && CPU != "generic")
1688         return CPU;
1689       else
1690         return "";
1691     }
1692
1693     return llvm::StringSwitch<const char *>(CPUName)
1694         .Case("common", "generic")
1695         .Case("440", "440")
1696         .Case("440fp", "440")
1697         .Case("450", "450")
1698         .Case("601", "601")
1699         .Case("602", "602")
1700         .Case("603", "603")
1701         .Case("603e", "603e")
1702         .Case("603ev", "603ev")
1703         .Case("604", "604")
1704         .Case("604e", "604e")
1705         .Case("620", "620")
1706         .Case("630", "pwr3")
1707         .Case("G3", "g3")
1708         .Case("7400", "7400")
1709         .Case("G4", "g4")
1710         .Case("7450", "7450")
1711         .Case("G4+", "g4+")
1712         .Case("750", "750")
1713         .Case("970", "970")
1714         .Case("G5", "g5")
1715         .Case("a2", "a2")
1716         .Case("a2q", "a2q")
1717         .Case("e500mc", "e500mc")
1718         .Case("e5500", "e5500")
1719         .Case("power3", "pwr3")
1720         .Case("power4", "pwr4")
1721         .Case("power5", "pwr5")
1722         .Case("power5x", "pwr5x")
1723         .Case("power6", "pwr6")
1724         .Case("power6x", "pwr6x")
1725         .Case("power7", "pwr7")
1726         .Case("power8", "pwr8")
1727         .Case("power9", "pwr9")
1728         .Case("pwr3", "pwr3")
1729         .Case("pwr4", "pwr4")
1730         .Case("pwr5", "pwr5")
1731         .Case("pwr5x", "pwr5x")
1732         .Case("pwr6", "pwr6")
1733         .Case("pwr6x", "pwr6x")
1734         .Case("pwr7", "pwr7")
1735         .Case("pwr8", "pwr8")
1736         .Case("pwr9", "pwr9")
1737         .Case("powerpc", "ppc")
1738         .Case("powerpc64", "ppc64")
1739         .Case("powerpc64le", "ppc64le")
1740         .Default("");
1741   }
1742
1743   return "";
1744 }
1745
1746 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1747                                  const ArgList &Args,
1748                                  std::vector<StringRef> &Features) {
1749   handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1750
1751   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1752   if (FloatABI == ppc::FloatABI::Soft)
1753     Features.push_back("-hard-float");
1754
1755   // Altivec is a bit weird, allow overriding of the Altivec feature here.
1756   AddTargetFeature(Args, Features, options::OPT_faltivec,
1757                    options::OPT_fno_altivec, "altivec");
1758 }
1759
1760 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1761   ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1762   if (Arg *A =
1763           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1764                           options::OPT_mfloat_abi_EQ)) {
1765     if (A->getOption().matches(options::OPT_msoft_float))
1766       ABI = ppc::FloatABI::Soft;
1767     else if (A->getOption().matches(options::OPT_mhard_float))
1768       ABI = ppc::FloatABI::Hard;
1769     else {
1770       ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1771                 .Case("soft", ppc::FloatABI::Soft)
1772                 .Case("hard", ppc::FloatABI::Hard)
1773                 .Default(ppc::FloatABI::Invalid);
1774       if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1775         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1776         ABI = ppc::FloatABI::Hard;
1777       }
1778     }
1779   }
1780
1781   // If unspecified, choose the default based on the platform.
1782   if (ABI == ppc::FloatABI::Invalid) {
1783     ABI = ppc::FloatABI::Hard;
1784   }
1785
1786   return ABI;
1787 }
1788
1789 void Clang::AddPPCTargetArgs(const ArgList &Args,
1790                              ArgStringList &CmdArgs) const {
1791   // Select the ABI to use.
1792   const char *ABIName = nullptr;
1793   if (getToolChain().getTriple().isOSLinux())
1794     switch (getToolChain().getArch()) {
1795     case llvm::Triple::ppc64: {
1796       // When targeting a processor that supports QPX, or if QPX is
1797       // specifically enabled, default to using the ABI that supports QPX (so
1798       // long as it is not specifically disabled).
1799       bool HasQPX = false;
1800       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1801         HasQPX = A->getValue() == StringRef("a2q");
1802       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1803       if (HasQPX) {
1804         ABIName = "elfv1-qpx";
1805         break;
1806       }
1807
1808       ABIName = "elfv1";
1809       break;
1810     }
1811     case llvm::Triple::ppc64le:
1812       ABIName = "elfv2";
1813       break;
1814     default:
1815       break;
1816     }
1817
1818   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1819     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1820     // the option if given as we don't have backend support for any targets
1821     // that don't use the altivec abi.
1822     if (StringRef(A->getValue()) != "altivec")
1823       ABIName = A->getValue();
1824
1825   ppc::FloatABI FloatABI =
1826       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1827
1828   if (FloatABI == ppc::FloatABI::Soft) {
1829     // Floating point operations and argument passing are soft.
1830     CmdArgs.push_back("-msoft-float");
1831     CmdArgs.push_back("-mfloat-abi");
1832     CmdArgs.push_back("soft");
1833   } else {
1834     // Floating point operations and argument passing are hard.
1835     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1836     CmdArgs.push_back("-mfloat-abi");
1837     CmdArgs.push_back("hard");
1838   }
1839
1840   if (ABIName) {
1841     CmdArgs.push_back("-target-abi");
1842     CmdArgs.push_back(ABIName);
1843   }
1844 }
1845
1846 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1847   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1848   return A && (A->getValue() == StringRef(Value));
1849 }
1850
1851 /// Get the (LLVM) name of the R600 gpu we are targeting.
1852 static std::string getR600TargetGPU(const ArgList &Args) {
1853   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1854     const char *GPUName = A->getValue();
1855     return llvm::StringSwitch<const char *>(GPUName)
1856         .Cases("rv630", "rv635", "r600")
1857         .Cases("rv610", "rv620", "rs780", "rs880")
1858         .Case("rv740", "rv770")
1859         .Case("palm", "cedar")
1860         .Cases("sumo", "sumo2", "sumo")
1861         .Case("hemlock", "cypress")
1862         .Case("aruba", "cayman")
1863         .Default(GPUName);
1864   }
1865   return "";
1866 }
1867
1868 static std::string getLanaiTargetCPU(const ArgList &Args) {
1869   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1870     return A->getValue();
1871   }
1872   return "";
1873 }
1874
1875 sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
1876                                         const ArgList &Args) {
1877   sparc::FloatABI ABI = sparc::FloatABI::Invalid;
1878   if (Arg *A =
1879           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1880                           options::OPT_mfloat_abi_EQ)) {
1881     if (A->getOption().matches(options::OPT_msoft_float))
1882       ABI = sparc::FloatABI::Soft;
1883     else if (A->getOption().matches(options::OPT_mhard_float))
1884       ABI = sparc::FloatABI::Hard;
1885     else {
1886       ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
1887                 .Case("soft", sparc::FloatABI::Soft)
1888                 .Case("hard", sparc::FloatABI::Hard)
1889                 .Default(sparc::FloatABI::Invalid);
1890       if (ABI == sparc::FloatABI::Invalid &&
1891           !StringRef(A->getValue()).empty()) {
1892         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1893         ABI = sparc::FloatABI::Hard;
1894       }
1895     }
1896   }
1897
1898   // If unspecified, choose the default based on the platform.
1899   // Only the hard-float ABI on Sparc is standardized, and it is the
1900   // default. GCC also supports a nonstandard soft-float ABI mode, also
1901   // implemented in LLVM. However as this is not standard we set the default
1902   // to be hard-float.
1903   if (ABI == sparc::FloatABI::Invalid) {
1904     ABI = sparc::FloatABI::Hard;
1905   }
1906
1907   return ABI;
1908 }
1909
1910 static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
1911                                  std::vector<StringRef> &Features) {
1912   sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
1913   if (FloatABI == sparc::FloatABI::Soft)
1914     Features.push_back("+soft-float");
1915 }
1916
1917 void Clang::AddSparcTargetArgs(const ArgList &Args,
1918                                ArgStringList &CmdArgs) const {
1919   sparc::FloatABI FloatABI =
1920       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1921
1922   if (FloatABI == sparc::FloatABI::Soft) {
1923     // Floating point operations and argument passing are soft.
1924     CmdArgs.push_back("-msoft-float");
1925     CmdArgs.push_back("-mfloat-abi");
1926     CmdArgs.push_back("soft");
1927   } else {
1928     // Floating point operations and argument passing are hard.
1929     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1930     CmdArgs.push_back("-mfloat-abi");
1931     CmdArgs.push_back("hard");
1932   }
1933 }
1934
1935 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1936                                  ArgStringList &CmdArgs) const {
1937   if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1938     CmdArgs.push_back("-mbackchain");
1939 }
1940
1941 static const char *getSystemZTargetCPU(const ArgList &Args) {
1942   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1943     return A->getValue();
1944   return "z10";
1945 }
1946
1947 static void getSystemZTargetFeatures(const ArgList &Args,
1948                                      std::vector<StringRef> &Features) {
1949   // -m(no-)htm overrides use of the transactional-execution facility.
1950   if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1951     if (A->getOption().matches(options::OPT_mhtm))
1952       Features.push_back("+transactional-execution");
1953     else
1954       Features.push_back("-transactional-execution");
1955   }
1956   // -m(no-)vx overrides use of the vector facility.
1957   if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1958     if (A->getOption().matches(options::OPT_mvx))
1959       Features.push_back("+vector");
1960     else
1961       Features.push_back("-vector");
1962   }
1963 }
1964
1965 static const char *getX86TargetCPU(const ArgList &Args,
1966                                    const llvm::Triple &Triple) {
1967   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1968     if (StringRef(A->getValue()) != "native") {
1969       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1970         return "core-avx2";
1971
1972       return A->getValue();
1973     }
1974
1975     // FIXME: Reject attempts to use -march=native unless the target matches
1976     // the host.
1977     //
1978     // FIXME: We should also incorporate the detected target features for use
1979     // with -native.
1980     std::string CPU = llvm::sys::getHostCPUName();
1981     if (!CPU.empty() && CPU != "generic")
1982       return Args.MakeArgString(CPU);
1983   }
1984
1985   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1986     // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1987     StringRef Arch = A->getValue();
1988     const char *CPU;
1989     if (Triple.getArch() == llvm::Triple::x86) {
1990       CPU = llvm::StringSwitch<const char *>(Arch)
1991                 .Case("IA32", "i386")
1992                 .Case("SSE", "pentium3")
1993                 .Case("SSE2", "pentium4")
1994                 .Case("AVX", "sandybridge")
1995                 .Case("AVX2", "haswell")
1996                 .Default(nullptr);
1997     } else {
1998       CPU = llvm::StringSwitch<const char *>(Arch)
1999                 .Case("AVX", "sandybridge")
2000                 .Case("AVX2", "haswell")
2001                 .Default(nullptr);
2002     }
2003     if (CPU)
2004       return CPU;
2005   }
2006
2007   // Select the default CPU if none was given (or detection failed).
2008
2009   if (Triple.getArch() != llvm::Triple::x86_64 &&
2010       Triple.getArch() != llvm::Triple::x86)
2011     return nullptr; // This routine is only handling x86 targets.
2012
2013   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
2014
2015   // FIXME: Need target hooks.
2016   if (Triple.isOSDarwin()) {
2017     if (Triple.getArchName() == "x86_64h")
2018       return "core-avx2";
2019     // macosx10.12 drops support for all pre-Penryn Macs.
2020     // Simulators can still run on 10.11 though, like Xcode.
2021     if (Triple.isMacOSX() && !Triple.isOSVersionLT(10, 12))
2022       return "penryn";
2023     // The oldest x86_64 Macs have core2/Merom; the oldest x86 Macs have Yonah.
2024     return Is64Bit ? "core2" : "yonah";
2025   }
2026
2027   // Set up default CPU name for PS4 compilers.
2028   if (Triple.isPS4CPU())
2029     return "btver2";
2030
2031   // On Android use targets compatible with gcc
2032   if (Triple.isAndroid())
2033     return Is64Bit ? "x86-64" : "i686";
2034
2035   // Everything else goes to x86-64 in 64-bit mode.
2036   if (Is64Bit)
2037     return "x86-64";
2038
2039   switch (Triple.getOS()) {
2040   case llvm::Triple::FreeBSD:
2041   case llvm::Triple::NetBSD:
2042   case llvm::Triple::OpenBSD:
2043     return "i486";
2044   case llvm::Triple::Haiku:
2045     return "i586";
2046   case llvm::Triple::Bitrig:
2047     return "i686";
2048   default:
2049     // Fallback to p4.
2050     return "pentium4";
2051   }
2052 }
2053
2054 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
2055 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
2056   // If we have -mcpu=, use that.
2057   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2058     StringRef CPU = A->getValue();
2059
2060 #ifdef __wasm__
2061     // Handle "native" by examining the host. "native" isn't meaningful when
2062     // cross compiling, so only support this when the host is also WebAssembly.
2063     if (CPU == "native")
2064       return llvm::sys::getHostCPUName();
2065 #endif
2066
2067     return CPU;
2068   }
2069
2070   return "generic";
2071 }
2072
2073 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
2074                               bool FromAs = false) {
2075   Arg *A;
2076
2077   switch (T.getArch()) {
2078   default:
2079     return "";
2080
2081   case llvm::Triple::aarch64:
2082   case llvm::Triple::aarch64_be:
2083     return getAArch64TargetCPU(Args, A);
2084
2085   case llvm::Triple::arm:
2086   case llvm::Triple::armeb:
2087   case llvm::Triple::thumb:
2088   case llvm::Triple::thumbeb: {
2089     StringRef MArch, MCPU;
2090     getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
2091     return arm::getARMTargetCPU(MCPU, MArch, T);
2092   }
2093   case llvm::Triple::mips:
2094   case llvm::Triple::mipsel:
2095   case llvm::Triple::mips64:
2096   case llvm::Triple::mips64el: {
2097     StringRef CPUName;
2098     StringRef ABIName;
2099     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
2100     return CPUName;
2101   }
2102
2103   case llvm::Triple::nvptx:
2104   case llvm::Triple::nvptx64:
2105     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
2106       return A->getValue();
2107     return "";
2108
2109   case llvm::Triple::ppc:
2110   case llvm::Triple::ppc64:
2111   case llvm::Triple::ppc64le: {
2112     std::string TargetCPUName = getPPCTargetCPU(Args);
2113     // LLVM may default to generating code for the native CPU,
2114     // but, like gcc, we default to a more generic option for
2115     // each architecture. (except on Darwin)
2116     if (TargetCPUName.empty() && !T.isOSDarwin()) {
2117       if (T.getArch() == llvm::Triple::ppc64)
2118         TargetCPUName = "ppc64";
2119       else if (T.getArch() == llvm::Triple::ppc64le)
2120         TargetCPUName = "ppc64le";
2121       else
2122         TargetCPUName = "ppc";
2123     }
2124     return TargetCPUName;
2125   }
2126
2127   case llvm::Triple::sparc:
2128   case llvm::Triple::sparcel:
2129   case llvm::Triple::sparcv9:
2130     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
2131       return A->getValue();
2132     return "";
2133
2134   case llvm::Triple::x86:
2135   case llvm::Triple::x86_64:
2136     return getX86TargetCPU(Args, T);
2137
2138   case llvm::Triple::hexagon:
2139     return "hexagon" +
2140            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
2141
2142   case llvm::Triple::lanai:
2143     return getLanaiTargetCPU(Args);
2144
2145   case llvm::Triple::systemz:
2146     return getSystemZTargetCPU(Args);
2147
2148   case llvm::Triple::r600:
2149   case llvm::Triple::amdgcn:
2150     return getR600TargetGPU(Args);
2151
2152   case llvm::Triple::wasm32:
2153   case llvm::Triple::wasm64:
2154     return getWebAssemblyTargetCPU(Args);
2155   }
2156 }
2157
2158 static unsigned getLTOParallelism(const ArgList &Args, const Driver &D) {
2159   unsigned Parallelism = 0;
2160   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
2161   if (LtoJobsArg &&
2162       StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
2163     D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
2164                                             << LtoJobsArg->getValue();
2165   return Parallelism;
2166 }
2167
2168 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
2169 // default.
2170 static bool isUseSeparateSections(const llvm::Triple &Triple) {
2171   return Triple.getOS() == llvm::Triple::CloudABI ||
2172          Triple.getArch() == llvm::Triple::wasm32 ||
2173          Triple.getArch() == llvm::Triple::wasm64;
2174 }
2175
2176 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
2177                           ArgStringList &CmdArgs, bool IsThinLTO,
2178                           const Driver &D) {
2179   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
2180   // as gold requires -plugin to come before any -plugin-opt that -Wl might
2181   // forward.
2182   CmdArgs.push_back("-plugin");
2183   std::string Plugin =
2184       ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
2185   CmdArgs.push_back(Args.MakeArgString(Plugin));
2186
2187   // Try to pass driver level flags relevant to LTO code generation down to
2188   // the plugin.
2189
2190   // Handle flags for selecting CPU variants.
2191   std::string CPU = getCPUName(Args, ToolChain.getTriple());
2192   if (!CPU.empty())
2193     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
2194
2195   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2196     StringRef OOpt;
2197     if (A->getOption().matches(options::OPT_O4) ||
2198         A->getOption().matches(options::OPT_Ofast))
2199       OOpt = "3";
2200     else if (A->getOption().matches(options::OPT_O))
2201       OOpt = A->getValue();
2202     else if (A->getOption().matches(options::OPT_O0))
2203       OOpt = "0";
2204     if (!OOpt.empty())
2205       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
2206   }
2207
2208   if (IsThinLTO)
2209     CmdArgs.push_back("-plugin-opt=thinlto");
2210
2211   if (unsigned Parallelism = getLTOParallelism(Args, D))
2212     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
2213                                          llvm::to_string(Parallelism)));
2214
2215   // If an explicit debugger tuning argument appeared, pass it along.
2216   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2217                                options::OPT_ggdbN_Group)) {
2218     if (A->getOption().matches(options::OPT_glldb))
2219       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
2220     else if (A->getOption().matches(options::OPT_gsce))
2221       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
2222     else
2223       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
2224   }
2225
2226   bool UseSeparateSections =
2227       isUseSeparateSections(ToolChain.getEffectiveTriple());
2228
2229   if (Args.hasFlag(options::OPT_ffunction_sections,
2230                    options::OPT_fno_function_sections, UseSeparateSections)) {
2231     CmdArgs.push_back("-plugin-opt=-function-sections");
2232   }
2233
2234   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
2235                    UseSeparateSections)) {
2236     CmdArgs.push_back("-plugin-opt=-data-sections");
2237   }
2238
2239   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
2240     StringRef FName = A->getValue();
2241     if (!llvm::sys::fs::exists(FName))
2242       D.Diag(diag::err_drv_no_such_file) << FName;
2243     else
2244       CmdArgs.push_back(
2245           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
2246   }
2247 }
2248
2249 /// This is a helper function for validating the optional refinement step
2250 /// parameter in reciprocal argument strings. Return false if there is an error
2251 /// parsing the refinement step. Otherwise, return true and set the Position
2252 /// of the refinement step in the input string.
2253 static bool getRefinementStep(StringRef In, const Driver &D,
2254                               const Arg &A, size_t &Position) {
2255   const char RefinementStepToken = ':';
2256   Position = In.find(RefinementStepToken);
2257   if (Position != StringRef::npos) {
2258     StringRef Option = A.getOption().getName();
2259     StringRef RefStep = In.substr(Position + 1);
2260     // Allow exactly one numeric character for the additional refinement
2261     // step parameter. This is reasonable for all currently-supported
2262     // operations and architectures because we would expect that a larger value
2263     // of refinement steps would cause the estimate "optimization" to
2264     // under-perform the native operation. Also, if the estimate does not
2265     // converge quickly, it probably will not ever converge, so further
2266     // refinement steps will not produce a better answer.
2267     if (RefStep.size() != 1) {
2268       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2269       return false;
2270     }
2271     char RefStepChar = RefStep[0];
2272     if (RefStepChar < '0' || RefStepChar > '9') {
2273       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2274       return false;
2275     }
2276   }
2277   return true;
2278 }
2279
2280 /// The -mrecip flag requires processing of many optional parameters.
2281 static void ParseMRecip(const Driver &D, const ArgList &Args,
2282                         ArgStringList &OutStrings) {
2283   StringRef DisabledPrefixIn = "!";
2284   StringRef DisabledPrefixOut = "!";
2285   StringRef EnabledPrefixOut = "";
2286   StringRef Out = "-mrecip=";
2287
2288   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
2289   if (!A)
2290     return;
2291
2292   unsigned NumOptions = A->getNumValues();
2293   if (NumOptions == 0) {
2294     // No option is the same as "all".
2295     OutStrings.push_back(Args.MakeArgString(Out + "all"));
2296     return;
2297   }
2298
2299   // Pass through "all", "none", or "default" with an optional refinement step.
2300   if (NumOptions == 1) {
2301     StringRef Val = A->getValue(0);
2302     size_t RefStepLoc;
2303     if (!getRefinementStep(Val, D, *A, RefStepLoc))
2304       return;
2305     StringRef ValBase = Val.slice(0, RefStepLoc);
2306     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2307       OutStrings.push_back(Args.MakeArgString(Out + Val));
2308       return;
2309     }
2310   }
2311
2312   // Each reciprocal type may be enabled or disabled individually.
2313   // Check each input value for validity, concatenate them all back together,
2314   // and pass through.
2315
2316   llvm::StringMap<bool> OptionStrings;
2317   OptionStrings.insert(std::make_pair("divd", false));
2318   OptionStrings.insert(std::make_pair("divf", false));
2319   OptionStrings.insert(std::make_pair("vec-divd", false));
2320   OptionStrings.insert(std::make_pair("vec-divf", false));
2321   OptionStrings.insert(std::make_pair("sqrtd", false));
2322   OptionStrings.insert(std::make_pair("sqrtf", false));
2323   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2324   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
2325
2326   for (unsigned i = 0; i != NumOptions; ++i) {
2327     StringRef Val = A->getValue(i);
2328
2329     bool IsDisabled = Val.startswith(DisabledPrefixIn);
2330     // Ignore the disablement token for string matching.
2331     if (IsDisabled)
2332       Val = Val.substr(1);
2333
2334     size_t RefStep;
2335     if (!getRefinementStep(Val, D, *A, RefStep))
2336       return;
2337
2338     StringRef ValBase = Val.slice(0, RefStep);
2339     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2340     if (OptionIter == OptionStrings.end()) {
2341       // Try again specifying float suffix.
2342       OptionIter = OptionStrings.find(ValBase.str() + 'f');
2343       if (OptionIter == OptionStrings.end()) {
2344         // The input name did not match any known option string.
2345         D.Diag(diag::err_drv_unknown_argument) << Val;
2346         return;
2347       }
2348       // The option was specified without a float or double suffix.
2349       // Make sure that the double entry was not already specified.
2350       // The float entry will be checked below.
2351       if (OptionStrings[ValBase.str() + 'd']) {
2352         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2353         return;
2354       }
2355     }
2356
2357     if (OptionIter->second == true) {
2358       // Duplicate option specified.
2359       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2360       return;
2361     }
2362
2363     // Mark the matched option as found. Do not allow duplicate specifiers.
2364     OptionIter->second = true;
2365
2366     // If the precision was not specified, also mark the double entry as found.
2367     if (ValBase.back() != 'f' && ValBase.back() != 'd')
2368       OptionStrings[ValBase.str() + 'd'] = true;
2369
2370     // Build the output string.
2371     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2372     Out = Args.MakeArgString(Out + Prefix + Val);
2373     if (i != NumOptions - 1)
2374       Out = Args.MakeArgString(Out + ",");
2375   }
2376
2377   OutStrings.push_back(Args.MakeArgString(Out));
2378 }
2379
2380 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
2381                                  const ArgList &Args,
2382                                  std::vector<StringRef> &Features) {
2383   // If -march=native, autodetect the feature list.
2384   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
2385     if (StringRef(A->getValue()) == "native") {
2386       llvm::StringMap<bool> HostFeatures;
2387       if (llvm::sys::getHostCPUFeatures(HostFeatures))
2388         for (auto &F : HostFeatures)
2389           Features.push_back(
2390               Args.MakeArgString((F.second ? "+" : "-") + F.first()));
2391     }
2392   }
2393
2394   if (Triple.getArchName() == "x86_64h") {
2395     // x86_64h implies quite a few of the more modern subtarget features
2396     // for Haswell class CPUs, but not all of them. Opt-out of a few.
2397     Features.push_back("-rdrnd");
2398     Features.push_back("-aes");
2399     Features.push_back("-pclmul");
2400     Features.push_back("-rtm");
2401     Features.push_back("-hle");
2402     Features.push_back("-fsgsbase");
2403   }
2404
2405   const llvm::Triple::ArchType ArchType = Triple.getArch();
2406   // Add features to be compatible with gcc for Android.
2407   if (Triple.isAndroid()) {
2408     if (ArchType == llvm::Triple::x86_64) {
2409       Features.push_back("+sse4.2");
2410       Features.push_back("+popcnt");
2411     } else
2412       Features.push_back("+ssse3");
2413   }
2414
2415   // Set features according to the -arch flag on MSVC.
2416   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
2417     StringRef Arch = A->getValue();
2418     bool ArchUsed = false;
2419     // First, look for flags that are shared in x86 and x86-64.
2420     if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
2421       if (Arch == "AVX" || Arch == "AVX2") {
2422         ArchUsed = true;
2423         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2424       }
2425     }
2426     // Then, look for x86-specific flags.
2427     if (ArchType == llvm::Triple::x86) {
2428       if (Arch == "IA32") {
2429         ArchUsed = true;
2430       } else if (Arch == "SSE" || Arch == "SSE2") {
2431         ArchUsed = true;
2432         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2433       }
2434     }
2435     if (!ArchUsed)
2436       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2437   }
2438
2439   // Now add any that the user explicitly requested on the command line,
2440   // which may override the defaults.
2441   handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2442 }
2443
2444 void Clang::AddX86TargetArgs(const ArgList &Args,
2445                              ArgStringList &CmdArgs) const {
2446   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2447       Args.hasArg(options::OPT_mkernel) ||
2448       Args.hasArg(options::OPT_fapple_kext))
2449     CmdArgs.push_back("-disable-red-zone");
2450
2451   // Default to avoid implicit floating-point for kernel/kext code, but allow
2452   // that to be overridden with -mno-soft-float.
2453   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2454                           Args.hasArg(options::OPT_fapple_kext));
2455   if (Arg *A = Args.getLastArg(
2456           options::OPT_msoft_float, options::OPT_mno_soft_float,
2457           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2458     const Option &O = A->getOption();
2459     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2460                        O.matches(options::OPT_msoft_float));
2461   }
2462   if (NoImplicitFloat)
2463     CmdArgs.push_back("-no-implicit-float");
2464
2465   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2466     StringRef Value = A->getValue();
2467     if (Value == "intel" || Value == "att") {
2468       CmdArgs.push_back("-mllvm");
2469       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2470     } else {
2471       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2472           << A->getOption().getName() << Value;
2473     }
2474   }
2475
2476   // Set flags to support MCU ABI.
2477   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2478     CmdArgs.push_back("-mfloat-abi");
2479     CmdArgs.push_back("soft");
2480     CmdArgs.push_back("-mstack-alignment=4");
2481   }
2482 }
2483
2484 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2485                                  ArgStringList &CmdArgs) const {
2486   CmdArgs.push_back("-mqdsp6-compat");
2487   CmdArgs.push_back("-Wreturn-type");
2488
2489   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2490     std::string N = llvm::utostr(G.getValue());
2491     std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2492     CmdArgs.push_back("-mllvm");
2493     CmdArgs.push_back(Args.MakeArgString(Opt));
2494   }
2495
2496   if (!Args.hasArg(options::OPT_fno_short_enums))
2497     CmdArgs.push_back("-fshort-enums");
2498   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2499     CmdArgs.push_back("-mllvm");
2500     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2501   }
2502   CmdArgs.push_back("-mllvm");
2503   CmdArgs.push_back("-machine-sink-split=0");
2504 }
2505
2506 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2507                                ArgStringList &CmdArgs) const {
2508   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2509     StringRef CPUName = A->getValue();
2510
2511     CmdArgs.push_back("-target-cpu");
2512     CmdArgs.push_back(Args.MakeArgString(CPUName));
2513   }
2514   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2515     StringRef Value = A->getValue();
2516     // Only support mregparm=4 to support old usage. Report error for all other
2517     // cases.
2518     int Mregparm;
2519     if (Value.getAsInteger(10, Mregparm)) {
2520       if (Mregparm != 4) {
2521         getToolChain().getDriver().Diag(
2522             diag::err_drv_unsupported_option_argument)
2523             << A->getOption().getName() << Value;
2524       }
2525     }
2526   }
2527 }
2528
2529 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2530                                      ArgStringList &CmdArgs) const {
2531   // Default to "hidden" visibility.
2532   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2533                    options::OPT_fvisibility_ms_compat)) {
2534     CmdArgs.push_back("-fvisibility");
2535     CmdArgs.push_back("hidden");
2536   }
2537 }
2538
2539 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2540 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2541                                   std::vector<StringRef> &Features) {
2542   SmallVector<StringRef, 8> Split;
2543   text.split(Split, StringRef("+"), -1, false);
2544
2545   for (StringRef Feature : Split) {
2546     StringRef FeatureName = llvm::AArch64::getArchExtFeature(Feature);
2547     if (!FeatureName.empty())
2548       Features.push_back(FeatureName);
2549     else if (Feature == "neon" || Feature == "noneon")
2550       D.Diag(diag::err_drv_no_neon_modifier);
2551     else
2552       return false;
2553   }
2554   return true;
2555 }
2556
2557 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2558 // decode CPU and feature.
2559 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2560                               std::vector<StringRef> &Features) {
2561   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2562   CPU = Split.first;
2563
2564   if (CPU == "generic") {
2565     Features.push_back("+neon");
2566   } else {
2567     unsigned ArchKind = llvm::AArch64::parseCPUArch(CPU);
2568     if (!llvm::AArch64::getArchFeatures(ArchKind, Features))
2569       return false;
2570
2571     unsigned Extension = llvm::AArch64::getDefaultExtensions(CPU, ArchKind);
2572     if (!llvm::AArch64::getExtensionFeatures(Extension, Features))
2573       return false;
2574    }
2575
2576   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2577     return false;
2578
2579   return true;
2580 }
2581
2582 static bool
2583 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2584                                 const ArgList &Args,
2585                                 std::vector<StringRef> &Features) {
2586   std::string MarchLowerCase = March.lower();
2587   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2588
2589   unsigned ArchKind = llvm::AArch64::parseArch(Split.first);
2590   if (ArchKind == static_cast<unsigned>(llvm::AArch64::ArchKind::AK_INVALID) ||
2591       !llvm::AArch64::getArchFeatures(ArchKind, Features) ||
2592       (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features)))
2593     return false;
2594
2595   return true;
2596 }
2597
2598 static bool
2599 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2600                                const ArgList &Args,
2601                                std::vector<StringRef> &Features) {
2602   StringRef CPU;
2603   std::string McpuLowerCase = Mcpu.lower();
2604   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2605     return false;
2606
2607   return true;
2608 }
2609
2610 static bool
2611 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2612                                      const ArgList &Args,
2613                                      std::vector<StringRef> &Features) {
2614   std::string MtuneLowerCase = Mtune.lower();
2615   // Handle CPU name is 'native'.
2616   if (MtuneLowerCase == "native")
2617     MtuneLowerCase = llvm::sys::getHostCPUName();
2618   if (MtuneLowerCase == "cyclone") {
2619     Features.push_back("+zcm");
2620     Features.push_back("+zcz");
2621   }
2622   return true;
2623 }
2624
2625 static bool
2626 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2627                                     const ArgList &Args,
2628                                     std::vector<StringRef> &Features) {
2629   StringRef CPU;
2630   std::vector<StringRef> DecodedFeature;
2631   std::string McpuLowerCase = Mcpu.lower();
2632   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2633     return false;
2634
2635   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2636 }
2637
2638 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2639                                      std::vector<StringRef> &Features) {
2640   Arg *A;
2641   bool success = true;
2642   // Enable NEON by default.
2643   Features.push_back("+neon");
2644   if ((A = Args.getLastArg(options::OPT_march_EQ)))
2645     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2646   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2647     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2648   else if (Args.hasArg(options::OPT_arch))
2649     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args, A),
2650                                              Args, Features);
2651
2652   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2653     success =
2654         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2655   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2656     success =
2657         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2658   else if (success && Args.hasArg(options::OPT_arch))
2659     success = getAArch64MicroArchFeaturesFromMcpu(
2660         D, getAArch64TargetCPU(Args, A), Args, Features);
2661
2662   if (!success)
2663     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2664
2665   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2666     Features.push_back("-fp-armv8");
2667     Features.push_back("-crypto");
2668     Features.push_back("-neon");
2669   }
2670
2671   // En/disable crc
2672   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2673     if (A->getOption().matches(options::OPT_mcrc))
2674       Features.push_back("+crc");
2675     else
2676       Features.push_back("-crc");
2677   }
2678
2679   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2680                                options::OPT_munaligned_access))
2681     if (A->getOption().matches(options::OPT_mno_unaligned_access))
2682       Features.push_back("+strict-align");
2683
2684   if (Args.hasArg(options::OPT_ffixed_x18))
2685     Features.push_back("+reserve-x18");
2686 }
2687
2688 static void getHexagonTargetFeatures(const ArgList &Args,
2689                                      std::vector<StringRef> &Features) {
2690   handleTargetFeaturesGroup(Args, Features,
2691                             options::OPT_m_hexagon_Features_Group);
2692
2693   bool UseLongCalls = false;
2694   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
2695                                options::OPT_mno_long_calls)) {
2696     if (A->getOption().matches(options::OPT_mlong_calls))
2697       UseLongCalls = true;
2698   }
2699
2700   Features.push_back(UseLongCalls ? "+long-calls" : "-long-calls");
2701 }
2702
2703 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2704                                          std::vector<StringRef> &Features) {
2705   handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2706 }
2707
2708 static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
2709                                     std::vector<StringRef> &Features) {
2710   if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
2711     StringRef value = dAbi->getValue();
2712     if (value == "1.0") {
2713       Features.push_back("+amdgpu-debugger-insert-nops");
2714       Features.push_back("+amdgpu-debugger-reserve-regs");
2715       Features.push_back("+amdgpu-debugger-emit-prologue");
2716     } else {
2717       D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
2718     }
2719   }
2720
2721   handleTargetFeaturesGroup(
2722     Args, Features, options::OPT_m_amdgpu_Features_Group);
2723 }
2724
2725 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2726                               const ArgList &Args, ArgStringList &CmdArgs,
2727                               bool ForAS) {
2728   const Driver &D = TC.getDriver();
2729   std::vector<StringRef> Features;
2730   switch (Triple.getArch()) {
2731   default:
2732     break;
2733   case llvm::Triple::mips:
2734   case llvm::Triple::mipsel:
2735   case llvm::Triple::mips64:
2736   case llvm::Triple::mips64el:
2737     getMIPSTargetFeatures(D, Triple, Args, Features);
2738     break;
2739
2740   case llvm::Triple::arm:
2741   case llvm::Triple::armeb:
2742   case llvm::Triple::thumb:
2743   case llvm::Triple::thumbeb:
2744     getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
2745     break;
2746
2747   case llvm::Triple::ppc:
2748   case llvm::Triple::ppc64:
2749   case llvm::Triple::ppc64le:
2750     getPPCTargetFeatures(D, Triple, Args, Features);
2751     break;
2752   case llvm::Triple::systemz:
2753     getSystemZTargetFeatures(Args, Features);
2754     break;
2755   case llvm::Triple::aarch64:
2756   case llvm::Triple::aarch64_be:
2757     getAArch64TargetFeatures(D, Args, Features);
2758     break;
2759   case llvm::Triple::x86:
2760   case llvm::Triple::x86_64:
2761     getX86TargetFeatures(D, Triple, Args, Features);
2762     break;
2763   case llvm::Triple::hexagon:
2764     getHexagonTargetFeatures(Args, Features);
2765     break;
2766   case llvm::Triple::wasm32:
2767   case llvm::Triple::wasm64:
2768     getWebAssemblyTargetFeatures(Args, Features);
2769     break;
2770   case llvm::Triple::sparc:
2771   case llvm::Triple::sparcel:
2772   case llvm::Triple::sparcv9:
2773     getSparcTargetFeatures(D, Args, Features);
2774     break;
2775   case llvm::Triple::r600:
2776   case llvm::Triple::amdgcn:
2777     getAMDGPUTargetFeatures(D, Args, Features);
2778     break;
2779   }
2780
2781   // Find the last of each feature.
2782   llvm::StringMap<unsigned> LastOpt;
2783   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2784     StringRef Name = Features[I];
2785     assert(Name[0] == '-' || Name[0] == '+');
2786     LastOpt[Name.drop_front(1)] = I;
2787   }
2788
2789   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2790     // If this feature was overridden, ignore it.
2791     StringRef Name = Features[I];
2792     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
2793     assert(LastI != LastOpt.end());
2794     unsigned Last = LastI->second;
2795     if (Last != I)
2796       continue;
2797
2798     CmdArgs.push_back("-target-feature");
2799     CmdArgs.push_back(Name.data());
2800   }
2801 }
2802
2803 static bool
2804 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2805                                           const llvm::Triple &Triple) {
2806   // We use the zero-cost exception tables for Objective-C if the non-fragile
2807   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2808   // later.
2809   if (runtime.isNonFragile())
2810     return true;
2811
2812   if (!Triple.isMacOSX())
2813     return false;
2814
2815   return (!Triple.isMacOSXVersionLT(10, 5) &&
2816           (Triple.getArch() == llvm::Triple::x86_64 ||
2817            Triple.getArch() == llvm::Triple::arm));
2818 }
2819
2820 /// Adds exception related arguments to the driver command arguments. There's a
2821 /// master flag, -fexceptions and also language specific flags to enable/disable
2822 /// C++ and Objective-C exceptions. This makes it possible to for example
2823 /// disable C++ exceptions but enable Objective-C exceptions.
2824 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2825                              const ToolChain &TC, bool KernelOrKext,
2826                              const ObjCRuntime &objcRuntime,
2827                              ArgStringList &CmdArgs) {
2828   const Driver &D = TC.getDriver();
2829   const llvm::Triple &Triple = TC.getTriple();
2830
2831   if (KernelOrKext) {
2832     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2833     // arguments now to avoid warnings about unused arguments.
2834     Args.ClaimAllArgs(options::OPT_fexceptions);
2835     Args.ClaimAllArgs(options::OPT_fno_exceptions);
2836     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2837     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2838     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2839     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2840     return;
2841   }
2842
2843   // See if the user explicitly enabled exceptions.
2844   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2845                          false);
2846
2847   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2848   // is not necessarily sensible, but follows GCC.
2849   if (types::isObjC(InputType) &&
2850       Args.hasFlag(options::OPT_fobjc_exceptions,
2851                    options::OPT_fno_objc_exceptions, true)) {
2852     CmdArgs.push_back("-fobjc-exceptions");
2853
2854     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2855   }
2856
2857   if (types::isCXX(InputType)) {
2858     // Disable C++ EH by default on XCore and PS4.
2859     bool CXXExceptionsEnabled =
2860         Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2861     Arg *ExceptionArg = Args.getLastArg(
2862         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2863         options::OPT_fexceptions, options::OPT_fno_exceptions);
2864     if (ExceptionArg)
2865       CXXExceptionsEnabled =
2866           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2867           ExceptionArg->getOption().matches(options::OPT_fexceptions);
2868
2869     if (CXXExceptionsEnabled) {
2870       if (Triple.isPS4CPU()) {
2871         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2872         assert(ExceptionArg &&
2873                "On the PS4 exceptions should only be enabled if passing "
2874                "an argument");
2875         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2876           const Arg *RTTIArg = TC.getRTTIArg();
2877           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2878           D.Diag(diag::err_drv_argument_not_allowed_with)
2879               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2880         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2881           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2882       } else
2883         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2884
2885       CmdArgs.push_back("-fcxx-exceptions");
2886
2887       EH = true;
2888     }
2889   }
2890
2891   if (EH)
2892     CmdArgs.push_back("-fexceptions");
2893 }
2894
2895 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2896   bool Default = true;
2897   if (TC.getTriple().isOSDarwin()) {
2898     // The native darwin assembler doesn't support the linker_option directives,
2899     // so we disable them if we think the .s file will be passed to it.
2900     Default = TC.useIntegratedAs();
2901   }
2902   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2903                        Default);
2904 }
2905
2906 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2907                                         const ToolChain &TC) {
2908   bool UseDwarfDirectory =
2909       Args.hasFlag(options::OPT_fdwarf_directory_asm,
2910                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2911   return !UseDwarfDirectory;
2912 }
2913
2914 /// \brief Check whether the given input tree contains any compilation actions.
2915 static bool ContainsCompileAction(const Action *A) {
2916   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2917     return true;
2918
2919   for (const auto &AI : A->inputs())
2920     if (ContainsCompileAction(AI))
2921       return true;
2922
2923   return false;
2924 }
2925
2926 /// \brief Check if -relax-all should be passed to the internal assembler.
2927 /// This is done by default when compiling non-assembler source with -O0.
2928 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2929   bool RelaxDefault = true;
2930
2931   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2932     RelaxDefault = A->getOption().matches(options::OPT_O0);
2933
2934   if (RelaxDefault) {
2935     RelaxDefault = false;
2936     for (const auto &Act : C.getActions()) {
2937       if (ContainsCompileAction(Act)) {
2938         RelaxDefault = true;
2939         break;
2940       }
2941     }
2942   }
2943
2944   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2945                       RelaxDefault);
2946 }
2947
2948 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2949 // to the corresponding DebugInfoKind.
2950 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2951   assert(A.getOption().matches(options::OPT_gN_Group) &&
2952          "Not a -g option that specifies a debug-info level");
2953   if (A.getOption().matches(options::OPT_g0) ||
2954       A.getOption().matches(options::OPT_ggdb0))
2955     return codegenoptions::NoDebugInfo;
2956   if (A.getOption().matches(options::OPT_gline_tables_only) ||
2957       A.getOption().matches(options::OPT_ggdb1))
2958     return codegenoptions::DebugLineTablesOnly;
2959   return codegenoptions::LimitedDebugInfo;
2960 }
2961
2962 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2963 // on mismatch. The StringRef input (rather than an Arg) allows
2964 // for use by the "-Xassembler" option parser.
2965 static unsigned DwarfVersionNum(StringRef ArgValue) {
2966   return llvm::StringSwitch<unsigned>(ArgValue)
2967       .Case("-gdwarf-2", 2)
2968       .Case("-gdwarf-3", 3)
2969       .Case("-gdwarf-4", 4)
2970       .Case("-gdwarf-5", 5)
2971       .Default(0);
2972 }
2973
2974 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2975                                     codegenoptions::DebugInfoKind DebugInfoKind,
2976                                     unsigned DwarfVersion,
2977                                     llvm::DebuggerKind DebuggerTuning) {
2978   switch (DebugInfoKind) {
2979   case codegenoptions::DebugLineTablesOnly:
2980     CmdArgs.push_back("-debug-info-kind=line-tables-only");
2981     break;
2982   case codegenoptions::LimitedDebugInfo:
2983     CmdArgs.push_back("-debug-info-kind=limited");
2984     break;
2985   case codegenoptions::FullDebugInfo:
2986     CmdArgs.push_back("-debug-info-kind=standalone");
2987     break;
2988   default:
2989     break;
2990   }
2991   if (DwarfVersion > 0)
2992     CmdArgs.push_back(
2993         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2994   switch (DebuggerTuning) {
2995   case llvm::DebuggerKind::GDB:
2996     CmdArgs.push_back("-debugger-tuning=gdb");
2997     break;
2998   case llvm::DebuggerKind::LLDB:
2999     CmdArgs.push_back("-debugger-tuning=lldb");
3000     break;
3001   case llvm::DebuggerKind::SCE:
3002     CmdArgs.push_back("-debugger-tuning=sce");
3003     break;
3004   default:
3005     break;
3006   }
3007 }
3008
3009 static void CollectArgsForIntegratedAssembler(Compilation &C,
3010                                               const ArgList &Args,
3011                                               ArgStringList &CmdArgs,
3012                                               const Driver &D) {
3013   if (UseRelaxAll(C, Args))
3014     CmdArgs.push_back("-mrelax-all");
3015
3016   // Only default to -mincremental-linker-compatible if we think we are
3017   // targeting the MSVC linker.
3018   bool DefaultIncrementalLinkerCompatible =
3019       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
3020   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
3021                    options::OPT_mno_incremental_linker_compatible,
3022                    DefaultIncrementalLinkerCompatible))
3023     CmdArgs.push_back("-mincremental-linker-compatible");
3024
3025   switch (C.getDefaultToolChain().getArch()) {
3026   case llvm::Triple::arm:
3027   case llvm::Triple::armeb:
3028   case llvm::Triple::thumb:
3029   case llvm::Triple::thumbeb:
3030     if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
3031       StringRef Value = A->getValue();
3032       if (Value == "always" || Value == "never" || Value == "arm" ||
3033           Value == "thumb") {
3034         CmdArgs.push_back("-mllvm");
3035         CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
3036       } else {
3037         D.Diag(diag::err_drv_unsupported_option_argument)
3038             << A->getOption().getName() << Value;
3039       }
3040     }
3041     break;
3042   default:
3043     break;
3044   }
3045
3046   // When passing -I arguments to the assembler we sometimes need to
3047   // unconditionally take the next argument.  For example, when parsing
3048   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
3049   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
3050   // arg after parsing the '-I' arg.
3051   bool TakeNextArg = false;
3052
3053   // When using an integrated assembler, translate -Wa, and -Xassembler
3054   // options.
3055   bool CompressDebugSections = false;
3056
3057   bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
3058   const char *MipsTargetFeature = nullptr;
3059   for (const Arg *A :
3060        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
3061     A->claim();
3062
3063     for (StringRef Value : A->getValues()) {
3064       if (TakeNextArg) {
3065         CmdArgs.push_back(Value.data());
3066         TakeNextArg = false;
3067         continue;
3068       }
3069
3070       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
3071           Value == "-mbig-obj")
3072         continue; // LLVM handles bigobj automatically
3073
3074       switch (C.getDefaultToolChain().getArch()) {
3075       default:
3076         break;
3077       case llvm::Triple::mips:
3078       case llvm::Triple::mipsel:
3079       case llvm::Triple::mips64:
3080       case llvm::Triple::mips64el:
3081         if (Value == "--trap") {
3082           CmdArgs.push_back("-target-feature");
3083           CmdArgs.push_back("+use-tcc-in-div");
3084           continue;
3085         }
3086         if (Value == "--break") {
3087           CmdArgs.push_back("-target-feature");
3088           CmdArgs.push_back("-use-tcc-in-div");
3089           continue;
3090         }
3091         if (Value.startswith("-msoft-float")) {
3092           CmdArgs.push_back("-target-feature");
3093           CmdArgs.push_back("+soft-float");
3094           continue;
3095         }
3096         if (Value.startswith("-mhard-float")) {
3097           CmdArgs.push_back("-target-feature");
3098           CmdArgs.push_back("-soft-float");
3099           continue;
3100         }
3101
3102         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
3103                                 .Case("-mips1", "+mips1")
3104                                 .Case("-mips2", "+mips2")
3105                                 .Case("-mips3", "+mips3")
3106                                 .Case("-mips4", "+mips4")
3107                                 .Case("-mips5", "+mips5")
3108                                 .Case("-mips32", "+mips32")
3109                                 .Case("-mips32r2", "+mips32r2")
3110                                 .Case("-mips32r3", "+mips32r3")
3111                                 .Case("-mips32r5", "+mips32r5")
3112                                 .Case("-mips32r6", "+mips32r6")
3113                                 .Case("-mips64", "+mips64")
3114                                 .Case("-mips64r2", "+mips64r2")
3115                                 .Case("-mips64r3", "+mips64r3")
3116                                 .Case("-mips64r5", "+mips64r5")
3117                                 .Case("-mips64r6", "+mips64r6")
3118                                 .Default(nullptr);
3119         if (MipsTargetFeature)
3120           continue;
3121       }
3122
3123       if (Value == "-force_cpusubtype_ALL") {
3124         // Do nothing, this is the default and we don't support anything else.
3125       } else if (Value == "-L") {
3126         CmdArgs.push_back("-msave-temp-labels");
3127       } else if (Value == "--fatal-warnings") {
3128         CmdArgs.push_back("-massembler-fatal-warnings");
3129       } else if (Value == "--noexecstack") {
3130         CmdArgs.push_back("-mnoexecstack");
3131       } else if (Value == "-compress-debug-sections" ||
3132                  Value == "--compress-debug-sections") {
3133         CompressDebugSections = true;
3134       } else if (Value == "-nocompress-debug-sections" ||
3135                  Value == "--nocompress-debug-sections") {
3136         CompressDebugSections = false;
3137       } else if (Value == "-mrelax-relocations=yes" ||
3138                  Value == "--mrelax-relocations=yes") {
3139         UseRelaxRelocations = true;
3140       } else if (Value == "-mrelax-relocations=no" ||
3141                  Value == "--mrelax-relocations=no") {
3142         UseRelaxRelocations = false;
3143       } else if (Value.startswith("-I")) {
3144         CmdArgs.push_back(Value.data());
3145         // We need to consume the next argument if the current arg is a plain
3146         // -I. The next arg will be the include directory.
3147         if (Value == "-I")
3148           TakeNextArg = true;
3149       } else if (Value.startswith("-gdwarf-")) {
3150         // "-gdwarf-N" options are not cc1as options.
3151         unsigned DwarfVersion = DwarfVersionNum(Value);
3152         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
3153           CmdArgs.push_back(Value.data());
3154         } else {
3155           RenderDebugEnablingArgs(Args, CmdArgs,
3156                                   codegenoptions::LimitedDebugInfo,
3157                                   DwarfVersion, llvm::DebuggerKind::Default);
3158         }
3159       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
3160                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
3161         // Do nothing, we'll validate it later.
3162       } else if (Value == "-defsym") {
3163           if (A->getNumValues() != 2) {
3164             D.Diag(diag::err_drv_defsym_invalid_format) << Value;
3165             break;
3166           }
3167           const char *S = A->getValue(1);
3168           auto Pair = StringRef(S).split('=');
3169           auto Sym = Pair.first;
3170           auto SVal = Pair.second;
3171
3172           if (Sym.empty() || SVal.empty()) {
3173             D.Diag(diag::err_drv_defsym_invalid_format) << S;
3174             break;
3175           }
3176           int64_t IVal;
3177           if (SVal.getAsInteger(0, IVal)) {
3178             D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
3179             break;
3180           }
3181           CmdArgs.push_back(Value.data());
3182           TakeNextArg = true;
3183       } else {
3184         D.Diag(diag::err_drv_unsupported_option_argument)
3185             << A->getOption().getName() << Value;
3186       }
3187     }
3188   }
3189   if (CompressDebugSections) {
3190     if (llvm::zlib::isAvailable())
3191       CmdArgs.push_back("-compress-debug-sections");
3192     else
3193       D.Diag(diag::warn_debug_compression_unavailable);
3194   }
3195   if (UseRelaxRelocations)
3196     CmdArgs.push_back("--mrelax-relocations");
3197   if (MipsTargetFeature != nullptr) {
3198     CmdArgs.push_back("-target-feature");
3199     CmdArgs.push_back(MipsTargetFeature);
3200   }
3201 }
3202
3203 // This adds the static libclang_rt.builtins-arch.a directly to the command line
3204 // FIXME: Make sure we can also emit shared objects if they're requested
3205 // and available, check for possible errors, etc.
3206 static void addClangRT(const ToolChain &TC, const ArgList &Args,
3207                        ArgStringList &CmdArgs) {
3208   CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
3209 }
3210
3211 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
3212                               const ArgList &Args) {
3213   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3214                     options::OPT_fno_openmp, false))
3215     return;
3216
3217   switch (TC.getDriver().getOpenMPRuntime(Args)) {
3218   case Driver::OMPRT_OMP:
3219     CmdArgs.push_back("-lomp");
3220     break;
3221   case Driver::OMPRT_GOMP:
3222     CmdArgs.push_back("-lgomp");
3223     break;
3224   case Driver::OMPRT_IOMP5:
3225     CmdArgs.push_back("-liomp5");
3226     break;
3227   case Driver::OMPRT_Unknown:
3228     // Already diagnosed.
3229     break;
3230   }
3231 }
3232
3233 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
3234                                 ArgStringList &CmdArgs, StringRef Sanitizer,
3235                                 bool IsShared, bool IsWhole) {
3236   // Wrap any static runtimes that must be forced into executable in
3237   // whole-archive.
3238   if (IsWhole) CmdArgs.push_back("-whole-archive");
3239   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
3240   if (IsWhole) CmdArgs.push_back("-no-whole-archive");
3241 }
3242
3243 // Tries to use a file with the list of dynamic symbols that need to be exported
3244 // from the runtime library. Returns true if the file was found.
3245 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
3246                                     ArgStringList &CmdArgs,
3247                                     StringRef Sanitizer) {
3248   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
3249   if (llvm::sys::fs::exists(SanRT + ".syms")) {
3250     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
3251     return true;
3252   }
3253   return false;
3254 }
3255
3256 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
3257                                      ArgStringList &CmdArgs) {
3258   // Force linking against the system libraries sanitizers depends on
3259   // (see PR15823 why this is necessary).
3260   CmdArgs.push_back("--no-as-needed");
3261   // There's no libpthread or librt on RTEMS.
3262   if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
3263     CmdArgs.push_back("-lpthread");
3264     CmdArgs.push_back("-lrt");
3265   }
3266   CmdArgs.push_back("-lm");
3267   // There's no libdl on FreeBSD or RTEMS.
3268   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
3269       TC.getTriple().getOS() != llvm::Triple::RTEMS)
3270     CmdArgs.push_back("-ldl");
3271 }
3272
3273 static void
3274 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3275                          SmallVectorImpl<StringRef> &SharedRuntimes,
3276                          SmallVectorImpl<StringRef> &StaticRuntimes,
3277                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
3278                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
3279                          SmallVectorImpl<StringRef> &RequiredSymbols) {
3280   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
3281   // Collect shared runtimes.
3282   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
3283     SharedRuntimes.push_back("asan");
3284   }
3285   // The stats_client library is also statically linked into DSOs.
3286   if (SanArgs.needsStatsRt())
3287     StaticRuntimes.push_back("stats_client");
3288
3289   // Collect static runtimes.
3290   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
3291     // Don't link static runtimes into DSOs or if compiling for Android.
3292     return;
3293   }
3294   if (SanArgs.needsAsanRt()) {
3295     if (SanArgs.needsSharedAsanRt()) {
3296       HelperStaticRuntimes.push_back("asan-preinit");
3297     } else {
3298       StaticRuntimes.push_back("asan");
3299       if (SanArgs.linkCXXRuntimes())
3300         StaticRuntimes.push_back("asan_cxx");
3301     }
3302   }
3303   if (SanArgs.needsDfsanRt())
3304     StaticRuntimes.push_back("dfsan");
3305   if (SanArgs.needsLsanRt())
3306     StaticRuntimes.push_back("lsan");
3307   if (SanArgs.needsMsanRt()) {
3308     StaticRuntimes.push_back("msan");
3309     if (SanArgs.linkCXXRuntimes())
3310       StaticRuntimes.push_back("msan_cxx");
3311   }
3312   if (SanArgs.needsTsanRt()) {
3313     StaticRuntimes.push_back("tsan");
3314     if (SanArgs.linkCXXRuntimes())
3315       StaticRuntimes.push_back("tsan_cxx");
3316   }
3317   if (SanArgs.needsUbsanRt()) {
3318     StaticRuntimes.push_back("ubsan_standalone");
3319     if (SanArgs.linkCXXRuntimes())
3320       StaticRuntimes.push_back("ubsan_standalone_cxx");
3321   }
3322   if (SanArgs.needsSafeStackRt())
3323     StaticRuntimes.push_back("safestack");
3324   if (SanArgs.needsCfiRt())
3325     StaticRuntimes.push_back("cfi");
3326   if (SanArgs.needsCfiDiagRt()) {
3327     StaticRuntimes.push_back("cfi_diag");
3328     if (SanArgs.linkCXXRuntimes())
3329       StaticRuntimes.push_back("ubsan_standalone_cxx");
3330   }
3331   if (SanArgs.needsStatsRt()) {
3332     NonWholeStaticRuntimes.push_back("stats");
3333     RequiredSymbols.push_back("__sanitizer_stats_register");
3334   }
3335   if (SanArgs.needsEsanRt())
3336     StaticRuntimes.push_back("esan");
3337 }
3338
3339 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
3340 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
3341 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3342                                  ArgStringList &CmdArgs) {
3343   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
3344       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
3345   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
3346                            NonWholeStaticRuntimes, HelperStaticRuntimes,
3347                            RequiredSymbols);
3348   for (auto RT : SharedRuntimes)
3349     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
3350   for (auto RT : HelperStaticRuntimes)
3351     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3352   bool AddExportDynamic = false;
3353   for (auto RT : StaticRuntimes) {
3354     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3355     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3356   }
3357   for (auto RT : NonWholeStaticRuntimes) {
3358     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
3359     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3360   }
3361   for (auto S : RequiredSymbols) {
3362     CmdArgs.push_back("-u");
3363     CmdArgs.push_back(Args.MakeArgString(S));
3364   }
3365   // If there is a static runtime with no dynamic list, force all the symbols
3366   // to be dynamic to be sure we export sanitizer interface functions.
3367   if (AddExportDynamic)
3368     CmdArgs.push_back("-export-dynamic");
3369
3370   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
3371   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
3372     CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
3373
3374   return !StaticRuntimes.empty();
3375 }
3376
3377 static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
3378                            ArgStringList &CmdArgs) {
3379   if (Args.hasFlag(options::OPT_fxray_instrument,
3380                    options::OPT_fnoxray_instrument, false)) {
3381     CmdArgs.push_back("-whole-archive");
3382     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
3383     CmdArgs.push_back("-no-whole-archive");
3384     return true;
3385   }
3386   return false;
3387 }
3388
3389 static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
3390                                 ArgStringList &CmdArgs) {
3391   CmdArgs.push_back("--no-as-needed");
3392   CmdArgs.push_back("-lpthread");
3393   CmdArgs.push_back("-lrt");
3394   CmdArgs.push_back("-lm");
3395   CmdArgs.push_back("-latomic");
3396   if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3397     CmdArgs.push_back("-lc++");
3398   else
3399     CmdArgs.push_back("-lstdc++");
3400   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3401     CmdArgs.push_back("-ldl");
3402 }
3403
3404 static bool areOptimizationsEnabled(const ArgList &Args) {
3405   // Find the last -O arg and see if it is non-zero.
3406   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
3407     return !A->getOption().matches(options::OPT_O0);
3408   // Defaults to -O0.
3409   return false;
3410 }
3411
3412 static bool mustUseFramePointerForTarget(const llvm::Triple &Triple) {
3413   switch (Triple.getArch()){
3414   default:
3415     return false;
3416   case llvm::Triple::arm:
3417   case llvm::Triple::thumb:
3418     // ARM Darwin targets require a frame pointer to be always present to aid
3419     // offline debugging via backtraces.
3420     return Triple.isOSDarwin();
3421   }
3422 }
3423
3424 static bool useFramePointerForTargetByDefault(const ArgList &Args,
3425                                               const llvm::Triple &Triple) {
3426   switch (Triple.getArch()) {
3427   case llvm::Triple::xcore:
3428   case llvm::Triple::wasm32:
3429   case llvm::Triple::wasm64:
3430     // XCore never wants frame pointers, regardless of OS.
3431     // WebAssembly never wants frame pointers.
3432     return false;
3433   default:
3434     break;
3435   }
3436
3437   if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
3438     switch (Triple.getArch()) {
3439     // Don't use a frame pointer on linux if optimizing for certain targets.
3440     case llvm::Triple::mips64:
3441     case llvm::Triple::mips64el:
3442     case llvm::Triple::mips:
3443     case llvm::Triple::mipsel:
3444     case llvm::Triple::systemz:
3445     case llvm::Triple::x86:
3446     case llvm::Triple::x86_64:
3447       return !areOptimizationsEnabled(Args);
3448     default:
3449       return true;
3450     }
3451   }
3452
3453   if (Triple.isOSWindows()) {
3454     switch (Triple.getArch()) {
3455     case llvm::Triple::x86:
3456       return !areOptimizationsEnabled(Args);
3457     case llvm::Triple::x86_64:
3458       return Triple.isOSBinFormatMachO();
3459     case llvm::Triple::arm:
3460     case llvm::Triple::thumb:
3461       // Windows on ARM builds with FPO disabled to aid fast stack walking
3462       return true;
3463     default:
3464       // All other supported Windows ISAs use xdata unwind information, so frame
3465       // pointers are not generally useful.
3466       return false;
3467     }
3468   }
3469
3470   return true;
3471 }
3472
3473 static bool shouldUseFramePointer(const ArgList &Args,
3474                                   const llvm::Triple &Triple) {
3475   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
3476                                options::OPT_fomit_frame_pointer))
3477     return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
3478            mustUseFramePointerForTarget(Triple);
3479
3480   if (Args.hasArg(options::OPT_pg))
3481     return true;
3482
3483   return useFramePointerForTargetByDefault(Args, Triple);
3484 }
3485
3486 static bool shouldUseLeafFramePointer(const ArgList &Args,
3487                                       const llvm::Triple &Triple) {
3488   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
3489                                options::OPT_momit_leaf_frame_pointer))
3490     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer) ||
3491            mustUseFramePointerForTarget(Triple);
3492
3493   if (Args.hasArg(options::OPT_pg))
3494     return true;
3495
3496   if (Triple.isPS4CPU())
3497     return false;
3498
3499   return useFramePointerForTargetByDefault(Args, Triple);
3500 }
3501
3502 /// Add a CC1 option to specify the debug compilation directory.
3503 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
3504   SmallString<128> cwd;
3505   if (!llvm::sys::fs::current_path(cwd)) {
3506     CmdArgs.push_back("-fdebug-compilation-dir");
3507     CmdArgs.push_back(Args.MakeArgString(cwd));
3508   }
3509 }
3510
3511 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
3512   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3513   if (FinalOutput && Args.hasArg(options::OPT_c)) {
3514     SmallString<128> T(FinalOutput->getValue());
3515     llvm::sys::path::replace_extension(T, "dwo");
3516     return Args.MakeArgString(T);
3517   } else {
3518     // Use the compilation dir.
3519     SmallString<128> T(
3520         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
3521     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
3522     llvm::sys::path::replace_extension(F, "dwo");
3523     T += F;
3524     return Args.MakeArgString(F);
3525   }
3526 }
3527
3528 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
3529                            const JobAction &JA, const ArgList &Args,
3530                            const InputInfo &Output, const char *OutFile) {
3531   ArgStringList ExtractArgs;
3532   ExtractArgs.push_back("--extract-dwo");
3533
3534   ArgStringList StripArgs;
3535   StripArgs.push_back("--strip-dwo");
3536
3537   // Grabbing the output of the earlier compile step.
3538   StripArgs.push_back(Output.getFilename());
3539   ExtractArgs.push_back(Output.getFilename());
3540   ExtractArgs.push_back(OutFile);
3541
3542   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
3543   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
3544
3545   // First extract the dwo sections.
3546   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
3547
3548   // Then remove them from the original .o file.
3549   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
3550 }
3551
3552 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
3553 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
3554 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3555   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3556     if (A->getOption().matches(options::OPT_O4) ||
3557         A->getOption().matches(options::OPT_Ofast))
3558       return true;
3559
3560     if (A->getOption().matches(options::OPT_O0))
3561       return false;
3562
3563     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3564
3565     // Vectorize -Os.
3566     StringRef S(A->getValue());
3567     if (S == "s")
3568       return true;
3569
3570     // Don't vectorize -Oz, unless it's the slp vectorizer.
3571     if (S == "z")
3572       return isSlpVec;
3573
3574     unsigned OptLevel = 0;
3575     if (S.getAsInteger(10, OptLevel))
3576       return false;
3577
3578     return OptLevel > 1;
3579   }
3580
3581   return false;
3582 }
3583
3584 /// Add -x lang to \p CmdArgs for \p Input.
3585 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3586                              ArgStringList &CmdArgs) {
3587   // When using -verify-pch, we don't want to provide the type
3588   // 'precompiled-header' if it was inferred from the file extension
3589   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3590     return;
3591
3592   CmdArgs.push_back("-x");
3593   if (Args.hasArg(options::OPT_rewrite_objc))
3594     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3595   else
3596     CmdArgs.push_back(types::getTypeName(Input.getType()));
3597 }
3598
3599 // Claim options we don't want to warn if they are unused. We do this for
3600 // options that build systems might add but are unused when assembling or only
3601 // running the preprocessor for example.
3602 static void claimNoWarnArgs(const ArgList &Args) {
3603   // Don't warn about unused -f(no-)?lto.  This can happen when we're
3604   // preprocessing, precompiling or assembling.
3605   Args.ClaimAllArgs(options::OPT_flto_EQ);
3606   Args.ClaimAllArgs(options::OPT_flto);
3607   Args.ClaimAllArgs(options::OPT_fno_lto);
3608 }
3609
3610 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3611 #ifdef LLVM_ON_UNIX
3612   const char *Username = getenv("LOGNAME");
3613 #else
3614   const char *Username = getenv("USERNAME");
3615 #endif
3616   if (Username) {
3617     // Validate that LoginName can be used in a path, and get its length.
3618     size_t Len = 0;
3619     for (const char *P = Username; *P; ++P, ++Len) {
3620       if (!isAlphanumeric(*P) && *P != '_') {
3621         Username = nullptr;
3622         break;
3623       }
3624     }
3625
3626     if (Username && Len > 0) {
3627       Result.append(Username, Username + Len);
3628       return;
3629     }
3630   }
3631
3632 // Fallback to user id.
3633 #ifdef LLVM_ON_UNIX
3634   std::string UID = llvm::utostr(getuid());
3635 #else
3636   // FIXME: Windows seems to have an 'SID' that might work.
3637   std::string UID = "9999";
3638 #endif
3639   Result.append(UID.begin(), UID.end());
3640 }
3641
3642 static Arg *getLastProfileUseArg(const ArgList &Args) {
3643   auto *ProfileUseArg = Args.getLastArg(
3644       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3645       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3646       options::OPT_fno_profile_instr_use);
3647
3648   if (ProfileUseArg &&
3649       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3650     ProfileUseArg = nullptr;
3651
3652   return ProfileUseArg;
3653 }
3654
3655 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3656                                    const InputInfo &Output, const ArgList &Args,
3657                                    ArgStringList &CmdArgs) {
3658
3659   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
3660                                          options::OPT_fprofile_generate_EQ,
3661                                          options::OPT_fno_profile_generate);
3662   if (PGOGenerateArg &&
3663       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
3664     PGOGenerateArg = nullptr;
3665
3666   auto *ProfileGenerateArg = Args.getLastArg(
3667       options::OPT_fprofile_instr_generate,
3668       options::OPT_fprofile_instr_generate_EQ,
3669       options::OPT_fno_profile_instr_generate);
3670   if (ProfileGenerateArg &&
3671       ProfileGenerateArg->getOption().matches(
3672           options::OPT_fno_profile_instr_generate))
3673     ProfileGenerateArg = nullptr;
3674
3675   if (PGOGenerateArg && ProfileGenerateArg)
3676     D.Diag(diag::err_drv_argument_not_allowed_with)
3677         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
3678
3679   auto *ProfileUseArg = getLastProfileUseArg(Args);
3680
3681   if (PGOGenerateArg && ProfileUseArg)
3682     D.Diag(diag::err_drv_argument_not_allowed_with)
3683         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
3684
3685   if (ProfileGenerateArg && ProfileUseArg)
3686     D.Diag(diag::err_drv_argument_not_allowed_with)
3687         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3688
3689   if (ProfileGenerateArg) {
3690     if (ProfileGenerateArg->getOption().matches(
3691             options::OPT_fprofile_instr_generate_EQ))
3692       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
3693                                            ProfileGenerateArg->getValue()));
3694     // The default is to use Clang Instrumentation.
3695     CmdArgs.push_back("-fprofile-instrument=clang");
3696   }
3697
3698   if (PGOGenerateArg) {
3699     CmdArgs.push_back("-fprofile-instrument=llvm");
3700     if (PGOGenerateArg->getOption().matches(
3701             options::OPT_fprofile_generate_EQ)) {
3702       SmallString<128> Path(PGOGenerateArg->getValue());
3703       llvm::sys::path::append(Path, "default_%m.profraw");
3704       CmdArgs.push_back(
3705           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
3706     }
3707   }
3708
3709   if (ProfileUseArg) {
3710     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3711       CmdArgs.push_back(Args.MakeArgString(
3712           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
3713     else if ((ProfileUseArg->getOption().matches(
3714                   options::OPT_fprofile_use_EQ) ||
3715               ProfileUseArg->getOption().matches(
3716                   options::OPT_fprofile_instr_use))) {
3717       SmallString<128> Path(
3718           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3719       if (Path.empty() || llvm::sys::fs::is_directory(Path))
3720         llvm::sys::path::append(Path, "default.profdata");
3721       CmdArgs.push_back(
3722           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
3723     }
3724   }
3725
3726   if (Args.hasArg(options::OPT_ftest_coverage) ||
3727       Args.hasArg(options::OPT_coverage))
3728     CmdArgs.push_back("-femit-coverage-notes");
3729   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3730                    false) ||
3731       Args.hasArg(options::OPT_coverage))
3732     CmdArgs.push_back("-femit-coverage-data");
3733
3734   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3735                    options::OPT_fno_coverage_mapping, false) &&
3736       !ProfileGenerateArg)
3737     D.Diag(diag::err_drv_argument_only_allowed_with)
3738         << "-fcoverage-mapping"
3739         << "-fprofile-instr-generate";
3740
3741   if (Args.hasFlag(options::OPT_fcoverage_mapping,
3742                    options::OPT_fno_coverage_mapping, false))
3743     CmdArgs.push_back("-fcoverage-mapping");
3744
3745   if (C.getArgs().hasArg(options::OPT_c) ||
3746       C.getArgs().hasArg(options::OPT_S)) {
3747     if (Output.isFilename()) {
3748       CmdArgs.push_back("-coverage-notes-file");
3749       SmallString<128> OutputFilename;
3750       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3751         OutputFilename = FinalOutput->getValue();
3752       else
3753         OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
3754       SmallString<128> CoverageFilename = OutputFilename;
3755       if (llvm::sys::path::is_relative(CoverageFilename)) {
3756         SmallString<128> Pwd;
3757         if (!llvm::sys::fs::current_path(Pwd)) {
3758           llvm::sys::path::append(Pwd, CoverageFilename);
3759           CoverageFilename.swap(Pwd);
3760         }
3761       }
3762       llvm::sys::path::replace_extension(CoverageFilename, "gcno");
3763       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3764
3765       // Leave -fprofile-dir= an unused argument unless .gcda emission is
3766       // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
3767       // the flag used. There is no -fno-profile-dir, so the user has no
3768       // targeted way to suppress the warning.
3769       if (Args.hasArg(options::OPT_fprofile_arcs) ||
3770           Args.hasArg(options::OPT_coverage)) {
3771         CmdArgs.push_back("-coverage-data-file");
3772         if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
3773           CoverageFilename = FProfileDir->getValue();
3774           llvm::sys::path::append(CoverageFilename, OutputFilename);
3775         }
3776         llvm::sys::path::replace_extension(CoverageFilename, "gcda");
3777         CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3778       }
3779     }
3780   }
3781 }
3782
3783 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3784                                 ArgStringList &CmdArgs) {
3785   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3786                     false) ||
3787        Args.hasFlag(options::OPT_fprofile_generate,
3788                     options::OPT_fno_profile_instr_generate, false) ||
3789        Args.hasFlag(options::OPT_fprofile_generate_EQ,
3790                     options::OPT_fno_profile_instr_generate, false) ||
3791        Args.hasFlag(options::OPT_fprofile_instr_generate,
3792                     options::OPT_fno_profile_instr_generate, false) ||
3793        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3794                     options::OPT_fno_profile_instr_generate, false) ||
3795        Args.hasArg(options::OPT_fcreate_profile) ||
3796        Args.hasArg(options::OPT_coverage)))
3797     CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3798 }
3799
3800 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
3801 /// smooshes them together with platform defaults, to decide whether
3802 /// this compile should be using PIC mode or not. Returns a tuple of
3803 /// (RelocationModel, PICLevel, IsPIE).
3804 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3805 ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
3806   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
3807   const llvm::Triple &Triple = ToolChain.getTriple();
3808
3809   bool PIE = ToolChain.isPIEDefault();
3810   bool PIC = PIE || ToolChain.isPICDefault();
3811   // The Darwin/MachO default to use PIC does not apply when using -static.
3812   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
3813     PIE = PIC = false;
3814   bool IsPICLevelTwo = PIC;
3815
3816   bool KernelOrKext =
3817       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3818
3819   // Android-specific defaults for PIC/PIE
3820   if (Triple.isAndroid()) {
3821     switch (Triple.getArch()) {
3822     case llvm::Triple::arm:
3823     case llvm::Triple::armeb:
3824     case llvm::Triple::thumb:
3825     case llvm::Triple::thumbeb:
3826     case llvm::Triple::aarch64:
3827     case llvm::Triple::mips:
3828     case llvm::Triple::mipsel:
3829     case llvm::Triple::mips64:
3830     case llvm::Triple::mips64el:
3831       PIC = true; // "-fpic"
3832       break;
3833
3834     case llvm::Triple::x86:
3835     case llvm::Triple::x86_64:
3836       PIC = true; // "-fPIC"
3837       IsPICLevelTwo = true;
3838       break;
3839
3840     default:
3841       break;
3842     }
3843   }
3844
3845   // OpenBSD-specific defaults for PIE
3846   if (Triple.getOS() == llvm::Triple::OpenBSD) {
3847     switch (ToolChain.getArch()) {
3848     case llvm::Triple::mips64:
3849     case llvm::Triple::mips64el:
3850     case llvm::Triple::sparcel:
3851     case llvm::Triple::x86:
3852     case llvm::Triple::x86_64:
3853       IsPICLevelTwo = false; // "-fpie"
3854       break;
3855
3856     case llvm::Triple::ppc:
3857     case llvm::Triple::sparc:
3858     case llvm::Triple::sparcv9:
3859       IsPICLevelTwo = true; // "-fPIE"
3860       break;
3861
3862     default:
3863       break;
3864     }
3865   }
3866
3867   // The last argument relating to either PIC or PIE wins, and no
3868   // other argument is used. If the last argument is any flavor of the
3869   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3870   // option implicitly enables PIC at the same level.
3871   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3872                                     options::OPT_fpic, options::OPT_fno_pic,
3873                                     options::OPT_fPIE, options::OPT_fno_PIE,
3874                                     options::OPT_fpie, options::OPT_fno_pie);
3875   if (Triple.isOSWindows() && LastPICArg &&
3876       LastPICArg ==
3877           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
3878                           options::OPT_fPIE, options::OPT_fpie)) {
3879     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3880         << LastPICArg->getSpelling() << Triple.str();
3881     if (Triple.getArch() == llvm::Triple::x86_64)
3882       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
3883     return std::make_tuple(llvm::Reloc::Static, 0U, false);
3884   }
3885
3886   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3887   // is forced, then neither PIC nor PIE flags will have no effect.
3888   if (!ToolChain.isPICDefaultForced()) {
3889     if (LastPICArg) {
3890       Option O = LastPICArg->getOption();
3891       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3892           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3893         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3894         PIC =
3895             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3896         IsPICLevelTwo =
3897             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3898       } else {
3899         PIE = PIC = false;
3900         if (EffectiveTriple.isPS4CPU()) {
3901           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3902           StringRef Model = ModelArg ? ModelArg->getValue() : "";
3903           if (Model != "kernel") {
3904             PIC = true;
3905             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3906                 << LastPICArg->getSpelling();
3907           }
3908         }
3909       }
3910     }
3911   }
3912
3913   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3914   // PIC level would've been set to level 1, force it back to level 2 PIC
3915   // instead.
3916   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
3917     IsPICLevelTwo |= ToolChain.isPICDefault();
3918
3919   // This kernel flags are a trump-card: they will disable PIC/PIE
3920   // generation, independent of the argument order.
3921   if (KernelOrKext &&
3922       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
3923        !EffectiveTriple.isWatchOS()))
3924     PIC = PIE = false;
3925
3926   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3927     // This is a very special mode. It trumps the other modes, almost no one
3928     // uses it, and it isn't even valid on any OS but Darwin.
3929     if (!Triple.isOSDarwin())
3930       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3931           << A->getSpelling() << Triple.str();
3932
3933     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3934
3935     // Only a forced PIC mode can cause the actual compile to have PIC defines
3936     // etc., no flags are sufficient. This behavior was selected to closely
3937     // match that of llvm-gcc and Apple GCC before that.
3938     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3939
3940     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
3941   }
3942
3943   bool EmbeddedPISupported;
3944   switch (Triple.getArch()) {
3945     case llvm::Triple::arm:
3946     case llvm::Triple::armeb:
3947     case llvm::Triple::thumb:
3948     case llvm::Triple::thumbeb:
3949       EmbeddedPISupported = true;
3950       break;
3951     default:
3952       EmbeddedPISupported = false;
3953       break;
3954   }
3955
3956   bool ROPI = false, RWPI = false;
3957   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
3958   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
3959     if (!EmbeddedPISupported)
3960       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3961           << LastROPIArg->getSpelling() << Triple.str();
3962     ROPI = true;
3963   }
3964   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
3965   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
3966     if (!EmbeddedPISupported)
3967       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3968           << LastRWPIArg->getSpelling() << Triple.str();
3969     RWPI = true;
3970   }
3971
3972   // ROPI and RWPI are not comaptible with PIC or PIE.
3973   if ((ROPI || RWPI) && (PIC || PIE))
3974     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
3975
3976   if (PIC)
3977     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
3978
3979   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
3980   if (ROPI && RWPI)
3981     RelocM = llvm::Reloc::ROPI_RWPI;
3982   else if (ROPI)
3983     RelocM = llvm::Reloc::ROPI;
3984   else if (RWPI)
3985     RelocM = llvm::Reloc::RWPI;
3986
3987   return std::make_tuple(RelocM, 0U, false);
3988 }
3989
3990 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3991   switch (Model) {
3992   case llvm::Reloc::Static:
3993     return "static";
3994   case llvm::Reloc::PIC_:
3995     return "pic";
3996   case llvm::Reloc::DynamicNoPIC:
3997     return "dynamic-no-pic";
3998   case llvm::Reloc::ROPI:
3999     return "ropi";
4000   case llvm::Reloc::RWPI:
4001     return "rwpi";
4002   case llvm::Reloc::ROPI_RWPI:
4003     return "ropi-rwpi";
4004   }
4005   llvm_unreachable("Unknown Reloc::Model kind");
4006 }
4007
4008 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
4009                              ArgStringList &CmdArgs) {
4010   llvm::Reloc::Model RelocationModel;
4011   unsigned PICLevel;
4012   bool IsPIE;
4013   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
4014
4015   if (RelocationModel != llvm::Reloc::Static)
4016     CmdArgs.push_back("-KPIC");
4017 }
4018
4019 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
4020                                     StringRef Target, const InputInfo &Output,
4021                                     const InputInfo &Input, const ArgList &Args) const {
4022   // If this is a dry run, do not create the compilation database file.
4023   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
4024     return;
4025
4026   using llvm::yaml::escape;
4027   const Driver &D = getToolChain().getDriver();
4028
4029   if (!CompilationDatabase) {
4030     std::error_code EC;
4031     auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
4032     if (EC) {
4033       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
4034                                                        << EC.message();
4035       return;
4036     }
4037     CompilationDatabase = std::move(File);
4038   }
4039   auto &CDB = *CompilationDatabase;
4040   SmallString<128> Buf;
4041   if (llvm::sys::fs::current_path(Buf))
4042     Buf = ".";
4043   CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
4044   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
4045   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
4046   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
4047   Buf = "-x";
4048   Buf += types::getTypeName(Input.getType());
4049   CDB << ", \"" << escape(Buf) << "\"";
4050   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
4051     Buf = "--sysroot=";
4052     Buf += D.SysRoot;
4053     CDB << ", \"" << escape(Buf) << "\"";
4054   }
4055   CDB << ", \"" << escape(Input.getFilename()) << "\"";
4056   for (auto &A: Args) {
4057     auto &O = A->getOption();
4058     // Skip language selection, which is positional.
4059     if (O.getID() == options::OPT_x)
4060       continue;
4061     // Skip writing dependency output and the compilation database itself.
4062     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
4063       continue;
4064     // Skip inputs.
4065     if (O.getKind() == Option::InputClass)
4066       continue;
4067     // All other arguments are quoted and appended.
4068     ArgStringList ASL;
4069     A->render(Args, ASL);
4070     for (auto &it: ASL)
4071       CDB << ", \"" << escape(it) << "\"";
4072   }
4073   Buf = "--target=";
4074   Buf += Target;
4075   CDB << ", \"" << escape(Buf) << "\"]},\n";
4076 }
4077
4078 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4079                          const InputInfo &Output, const InputInfoList &Inputs,
4080                          const ArgList &Args, const char *LinkingOutput) const {
4081   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
4082   const std::string &TripleStr = Triple.getTriple();
4083
4084   bool KernelOrKext =
4085       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4086   const Driver &D = getToolChain().getDriver();
4087   ArgStringList CmdArgs;
4088
4089   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
4090   bool IsWindowsCygnus =
4091       getToolChain().getTriple().isWindowsCygwinEnvironment();
4092   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
4093   bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
4094   bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
4095
4096   // Check number of inputs for sanity. We need at least one input.
4097   assert(Inputs.size() >= 1 && "Must have at least one input.");
4098   const InputInfo &Input = Inputs[0];
4099   // CUDA compilation may have multiple inputs (source file + results of
4100   // device-side compilations). OpenMP device jobs also take the host IR as a
4101   // second input. All other jobs are expected to have exactly one
4102   // input.
4103   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4104   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4105   assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
4106           Inputs.size() == 1) &&
4107          "Unable to handle multiple inputs.");
4108
4109   // C++ is not supported for IAMCU.
4110   if (IsIAMCU && types::isCXX(Input.getType()))
4111     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4112
4113   // Invoke ourselves in -cc1 mode.
4114   //
4115   // FIXME: Implement custom jobs for internal actions.
4116   CmdArgs.push_back("-cc1");
4117
4118   // Add the "effective" target triple.
4119   CmdArgs.push_back("-triple");
4120   CmdArgs.push_back(Args.MakeArgString(TripleStr));
4121
4122   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4123     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4124     Args.ClaimAllArgs(options::OPT_MJ);
4125   }
4126
4127   if (IsCuda) {
4128     // We have to pass the triple of the host if compiling for a CUDA device and
4129     // vice-versa.
4130     std::string NormalizedTriple;
4131     if (JA.isDeviceOffloading(Action::OFK_Cuda))
4132       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4133                              ->getTriple()
4134                              .normalize();
4135     else
4136       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4137                              ->getTriple()
4138                              .normalize();
4139
4140     CmdArgs.push_back("-aux-triple");
4141     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4142   }
4143
4144   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4145                                Triple.getArch() == llvm::Triple::thumb)) {
4146     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4147     unsigned Version;
4148     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
4149     if (Version < 7)
4150       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4151                                                 << TripleStr;
4152   }
4153
4154   // Push all default warning arguments that are specific to
4155   // the given target.  These come before user provided warning options
4156   // are provided.
4157   getToolChain().addClangWarningOptions(CmdArgs);
4158
4159   // Select the appropriate action.
4160   RewriteKind rewriteKind = RK_None;
4161
4162   if (isa<AnalyzeJobAction>(JA)) {
4163     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4164     CmdArgs.push_back("-analyze");
4165   } else if (isa<MigrateJobAction>(JA)) {
4166     CmdArgs.push_back("-migrate");
4167   } else if (isa<PreprocessJobAction>(JA)) {
4168     if (Output.getType() == types::TY_Dependencies)
4169       CmdArgs.push_back("-Eonly");
4170     else {
4171       CmdArgs.push_back("-E");
4172       if (Args.hasArg(options::OPT_rewrite_objc) &&
4173           !Args.hasArg(options::OPT_g_Group))
4174         CmdArgs.push_back("-P");
4175     }
4176   } else if (isa<AssembleJobAction>(JA)) {
4177     CmdArgs.push_back("-emit-obj");
4178
4179     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4180
4181     // Also ignore explicit -force_cpusubtype_ALL option.
4182     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4183   } else if (isa<PrecompileJobAction>(JA)) {
4184     // Use PCH if the user requested it.
4185     bool UsePCH = D.CCCUsePCH;
4186
4187     if (JA.getType() == types::TY_Nothing)
4188       CmdArgs.push_back("-fsyntax-only");
4189     else if (JA.getType() == types::TY_ModuleFile)
4190       CmdArgs.push_back("-emit-module-interface");
4191     else if (UsePCH)
4192       CmdArgs.push_back("-emit-pch");
4193     else
4194       CmdArgs.push_back("-emit-pth");
4195   } else if (isa<VerifyPCHJobAction>(JA)) {
4196     CmdArgs.push_back("-verify-pch");
4197   } else {
4198     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4199            "Invalid action for clang tool.");
4200     if (JA.getType() == types::TY_Nothing) {
4201       CmdArgs.push_back("-fsyntax-only");
4202     } else if (JA.getType() == types::TY_LLVM_IR ||
4203                JA.getType() == types::TY_LTO_IR) {
4204       CmdArgs.push_back("-emit-llvm");
4205     } else if (JA.getType() == types::TY_LLVM_BC ||
4206                JA.getType() == types::TY_LTO_BC) {
4207       CmdArgs.push_back("-emit-llvm-bc");
4208     } else if (JA.getType() == types::TY_PP_Asm) {
4209       CmdArgs.push_back("-S");
4210     } else if (JA.getType() == types::TY_AST) {
4211       CmdArgs.push_back("-emit-pch");
4212     } else if (JA.getType() == types::TY_ModuleFile) {
4213       CmdArgs.push_back("-module-file-info");
4214     } else if (JA.getType() == types::TY_RewrittenObjC) {
4215       CmdArgs.push_back("-rewrite-objc");
4216       rewriteKind = RK_NonFragile;
4217     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4218       CmdArgs.push_back("-rewrite-objc");
4219       rewriteKind = RK_Fragile;
4220     } else {
4221       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4222     }
4223
4224     // Preserve use-list order by default when emitting bitcode, so that
4225     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4226     // same result as running passes here.  For LTO, we don't need to preserve
4227     // the use-list order, since serialization to bitcode is part of the flow.
4228     if (JA.getType() == types::TY_LLVM_BC)
4229       CmdArgs.push_back("-emit-llvm-uselists");
4230
4231     if (D.isUsingLTO())
4232       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
4233   }
4234
4235   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4236     if (!types::isLLVMIR(Input.getType()))
4237       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4238                                                        << "-x ir";
4239     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4240   }
4241
4242   // Embed-bitcode option.
4243   if (C.getDriver().embedBitcodeInObject() &&
4244       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4245     // Add flags implied by -fembed-bitcode.
4246     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4247     // Disable all llvm IR level optimizations.
4248     CmdArgs.push_back("-disable-llvm-passes");
4249   }
4250   if (C.getDriver().embedBitcodeMarkerOnly())
4251     CmdArgs.push_back("-fembed-bitcode=marker");
4252
4253   // We normally speed up the clang process a bit by skipping destructors at
4254   // exit, but when we're generating diagnostics we can rely on some of the
4255   // cleanup.
4256   if (!C.isForDiagnostics())
4257     CmdArgs.push_back("-disable-free");
4258
4259 // Disable the verification pass in -asserts builds.
4260 #ifdef NDEBUG
4261   CmdArgs.push_back("-disable-llvm-verifier");
4262   // Discard LLVM value names in -asserts builds.
4263   CmdArgs.push_back("-discard-value-names");
4264 #endif
4265
4266   // Set the main file name, so that debug info works even with
4267   // -save-temps.
4268   CmdArgs.push_back("-main-file-name");
4269   CmdArgs.push_back(getBaseInputName(Args, Input));
4270
4271   // Some flags which affect the language (via preprocessor
4272   // defines).
4273   if (Args.hasArg(options::OPT_static))
4274     CmdArgs.push_back("-static-define");
4275
4276   if (isa<AnalyzeJobAction>(JA)) {
4277     // Enable region store model by default.
4278     CmdArgs.push_back("-analyzer-store=region");
4279
4280     // Treat blocks as analysis entry points.
4281     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
4282
4283     CmdArgs.push_back("-analyzer-eagerly-assume");
4284
4285     // Add default argument set.
4286     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
4287       CmdArgs.push_back("-analyzer-checker=core");
4288       CmdArgs.push_back("-analyzer-checker=apiModeling");
4289
4290     if (!IsWindowsMSVC) {
4291       CmdArgs.push_back("-analyzer-checker=unix");
4292     } else {
4293       // Enable "unix" checkers that also work on Windows.
4294       CmdArgs.push_back("-analyzer-checker=unix.API");
4295       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
4296       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
4297       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
4298       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
4299       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
4300     }
4301
4302       // Disable some unix checkers for PS4.
4303       if (IsPS4CPU) {
4304         CmdArgs.push_back("-analyzer-disable-checker=unix.API");
4305         CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
4306       }
4307
4308       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
4309         CmdArgs.push_back("-analyzer-checker=osx");
4310
4311       CmdArgs.push_back("-analyzer-checker=deadcode");
4312
4313       if (types::isCXX(Input.getType()))
4314         CmdArgs.push_back("-analyzer-checker=cplusplus");
4315
4316       if (!IsPS4CPU) {
4317         CmdArgs.push_back(
4318             "-analyzer-checker=security.insecureAPI.UncheckedReturn");
4319         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
4320         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
4321         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
4322         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
4323         CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
4324       }
4325
4326       // Default nullability checks.
4327       CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
4328       CmdArgs.push_back(
4329           "-analyzer-checker=nullability.NullReturnedFromNonnull");
4330     }
4331
4332     // Set the output format. The default is plist, for (lame) historical
4333     // reasons.
4334     CmdArgs.push_back("-analyzer-output");
4335     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
4336       CmdArgs.push_back(A->getValue());
4337     else
4338       CmdArgs.push_back("plist");
4339
4340     // Disable the presentation of standard compiler warnings when
4341     // using --analyze.  We only want to show static analyzer diagnostics
4342     // or frontend errors.
4343     CmdArgs.push_back("-w");
4344
4345     // Add -Xanalyzer arguments when running as analyzer.
4346     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
4347   }
4348
4349   CheckCodeGenerationOptions(D, Args);
4350
4351   llvm::Reloc::Model RelocationModel;
4352   unsigned PICLevel;
4353   bool IsPIE;
4354   std::tie(RelocationModel, PICLevel, IsPIE) =
4355       ParsePICArgs(getToolChain(), Args);
4356
4357   const char *RMName = RelocationModelName(RelocationModel);
4358
4359   if ((RelocationModel == llvm::Reloc::ROPI ||
4360        RelocationModel == llvm::Reloc::ROPI_RWPI) &&
4361       types::isCXX(Input.getType()) &&
4362       !Args.hasArg(options::OPT_fallow_unsupported))
4363     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
4364
4365   if (RMName) {
4366     CmdArgs.push_back("-mrelocation-model");
4367     CmdArgs.push_back(RMName);
4368   }
4369   if (PICLevel > 0) {
4370     CmdArgs.push_back("-pic-level");
4371     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4372     if (IsPIE)
4373       CmdArgs.push_back("-pic-is-pie");
4374   }
4375
4376   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4377     CmdArgs.push_back("-meabi");
4378     CmdArgs.push_back(A->getValue());
4379   }
4380
4381   CmdArgs.push_back("-mthread-model");
4382   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
4383     CmdArgs.push_back(A->getValue());
4384   else
4385     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
4386
4387   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4388
4389   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
4390                     options::OPT_fno_merge_all_constants))
4391     CmdArgs.push_back("-fno-merge-all-constants");
4392
4393   // LLVM Code Generator Options.
4394
4395   if (Args.hasArg(options::OPT_frewrite_map_file) ||
4396       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
4397     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
4398                                       options::OPT_frewrite_map_file_EQ)) {
4399       StringRef Map = A->getValue();
4400       if (!llvm::sys::fs::exists(Map)) {
4401         D.Diag(diag::err_drv_no_such_file) << Map;
4402       } else {
4403         CmdArgs.push_back("-frewrite-map-file");
4404         CmdArgs.push_back(A->getValue());
4405         A->claim();
4406       }
4407     }
4408   }
4409
4410   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4411     StringRef v = A->getValue();
4412     CmdArgs.push_back("-mllvm");
4413     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4414     A->claim();
4415   }
4416
4417   if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4418                     true))
4419     CmdArgs.push_back("-fno-jump-tables");
4420
4421   if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
4422                     options::OPT_fno_preserve_as_comments, true))
4423     CmdArgs.push_back("-fno-preserve-as-comments");
4424
4425   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4426     CmdArgs.push_back("-mregparm");
4427     CmdArgs.push_back(A->getValue());
4428   }
4429
4430   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4431                                options::OPT_freg_struct_return)) {
4432     if (getToolChain().getArch() != llvm::Triple::x86) {
4433       D.Diag(diag::err_drv_unsupported_opt_for_target)
4434           << A->getSpelling() << getToolChain().getTriple().str();
4435     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4436       CmdArgs.push_back("-fpcc-struct-return");
4437     } else {
4438       assert(A->getOption().matches(options::OPT_freg_struct_return));
4439       CmdArgs.push_back("-freg-struct-return");
4440     }
4441   }
4442
4443   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4444     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4445
4446   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
4447     CmdArgs.push_back("-mdisable-fp-elim");
4448   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4449                     options::OPT_fno_zero_initialized_in_bss))
4450     CmdArgs.push_back("-mno-zero-initialized-in-bss");
4451
4452   bool OFastEnabled = isOptimizationLevelFast(Args);
4453   // If -Ofast is the optimization level, then -fstrict-aliasing should be
4454   // enabled.  This alias option is being used to simplify the hasFlag logic.
4455   OptSpecifier StrictAliasingAliasOption =
4456       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4457   // We turn strict aliasing off by default if we're in CL mode, since MSVC
4458   // doesn't do any TBAA.
4459   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
4460   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4461                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4462     CmdArgs.push_back("-relaxed-aliasing");
4463   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4464                     options::OPT_fno_struct_path_tbaa))
4465     CmdArgs.push_back("-no-struct-path-tbaa");
4466   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4467                    false))
4468     CmdArgs.push_back("-fstrict-enums");
4469   if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4470                     true))
4471     CmdArgs.push_back("-fno-strict-return");
4472   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4473                    options::OPT_fno_strict_vtable_pointers,
4474                    false))
4475     CmdArgs.push_back("-fstrict-vtable-pointers");
4476   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4477                     options::OPT_fno_optimize_sibling_calls))
4478     CmdArgs.push_back("-mdisable-tail-calls");
4479
4480   // Handle segmented stacks.
4481   if (Args.hasArg(options::OPT_fsplit_stack))
4482     CmdArgs.push_back("-split-stacks");
4483
4484   // If -Ofast is the optimization level, then -ffast-math should be enabled.
4485   // This alias option is being used to simplify the getLastArg logic.
4486   OptSpecifier FastMathAliasOption =
4487       OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
4488
4489   // Handle various floating point optimization flags, mapping them to the
4490   // appropriate LLVM code generation flags. The pattern for all of these is to
4491   // default off the codegen optimizations, and if any flag enables them and no
4492   // flag disables them after the flag enabling them, enable the codegen
4493   // optimization. This is complicated by several "umbrella" flags.
4494   if (Arg *A = Args.getLastArg(
4495           options::OPT_ffast_math, FastMathAliasOption,
4496           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4497           options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
4498           options::OPT_fno_honor_infinities))
4499     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4500         A->getOption().getID() != options::OPT_fno_finite_math_only &&
4501         A->getOption().getID() != options::OPT_fhonor_infinities)
4502       CmdArgs.push_back("-menable-no-infs");
4503   if (Arg *A = Args.getLastArg(
4504           options::OPT_ffast_math, FastMathAliasOption,
4505           options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4506           options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
4507           options::OPT_fno_honor_nans))
4508     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4509         A->getOption().getID() != options::OPT_fno_finite_math_only &&
4510         A->getOption().getID() != options::OPT_fhonor_nans)
4511       CmdArgs.push_back("-menable-no-nans");
4512
4513   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
4514   bool MathErrno = getToolChain().IsMathErrnoDefault();
4515   if (Arg *A =
4516           Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4517                           options::OPT_fno_fast_math, options::OPT_fmath_errno,
4518                           options::OPT_fno_math_errno)) {
4519     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
4520     // However, turning *off* -ffast_math merely restores the toolchain default
4521     // (which may be false).
4522     if (A->getOption().getID() == options::OPT_fno_math_errno ||
4523         A->getOption().getID() == options::OPT_ffast_math ||
4524         A->getOption().getID() == options::OPT_Ofast)
4525       MathErrno = false;
4526     else if (A->getOption().getID() == options::OPT_fmath_errno)
4527       MathErrno = true;
4528   }
4529   if (MathErrno)
4530     CmdArgs.push_back("-fmath-errno");
4531
4532   // There are several flags which require disabling very specific
4533   // optimizations. Any of these being disabled forces us to turn off the
4534   // entire set of LLVM optimizations, so collect them through all the flag
4535   // madness.
4536   bool AssociativeMath = false;
4537   if (Arg *A = Args.getLastArg(
4538           options::OPT_ffast_math, FastMathAliasOption,
4539           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4540           options::OPT_fno_unsafe_math_optimizations,
4541           options::OPT_fassociative_math, options::OPT_fno_associative_math))
4542     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4543         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4544         A->getOption().getID() != options::OPT_fno_associative_math)
4545       AssociativeMath = true;
4546   bool ReciprocalMath = false;
4547   if (Arg *A = Args.getLastArg(
4548           options::OPT_ffast_math, FastMathAliasOption,
4549           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4550           options::OPT_fno_unsafe_math_optimizations,
4551           options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
4552     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4553         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4554         A->getOption().getID() != options::OPT_fno_reciprocal_math)
4555       ReciprocalMath = true;
4556   bool SignedZeros = true;
4557   if (Arg *A = Args.getLastArg(
4558           options::OPT_ffast_math, FastMathAliasOption,
4559           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4560           options::OPT_fno_unsafe_math_optimizations,
4561           options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
4562     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4563         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4564         A->getOption().getID() != options::OPT_fsigned_zeros)
4565       SignedZeros = false;
4566   bool TrappingMath = true;
4567   if (Arg *A = Args.getLastArg(
4568           options::OPT_ffast_math, FastMathAliasOption,
4569           options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4570           options::OPT_fno_unsafe_math_optimizations,
4571           options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
4572     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4573         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4574         A->getOption().getID() != options::OPT_ftrapping_math)
4575       TrappingMath = false;
4576   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
4577       !TrappingMath)
4578     CmdArgs.push_back("-menable-unsafe-fp-math");
4579
4580   if (!SignedZeros)
4581     CmdArgs.push_back("-fno-signed-zeros");
4582
4583   if (ReciprocalMath)
4584     CmdArgs.push_back("-freciprocal-math");
4585
4586   if (!TrappingMath)
4587     CmdArgs.push_back("-fno-trapping-math");
4588
4589
4590   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4591                                options::OPT_fno_fast_math,
4592                                options::OPT_funsafe_math_optimizations,
4593                                options::OPT_fno_unsafe_math_optimizations,
4594                                options::OPT_fdenormal_fp_math_EQ))
4595     if (A->getOption().getID() != options::OPT_fno_fast_math &&
4596         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations)
4597       Args.AddLastArg(CmdArgs, options::OPT_fdenormal_fp_math_EQ);
4598
4599   // Validate and pass through -fp-contract option.
4600   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4601                                options::OPT_fno_fast_math,
4602                                options::OPT_ffp_contract)) {
4603     if (A->getOption().getID() == options::OPT_ffp_contract) {
4604       StringRef Val = A->getValue();
4605       if (Val == "fast" || Val == "on" || Val == "off") {
4606         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
4607       } else {
4608         D.Diag(diag::err_drv_unsupported_option_argument)
4609             << A->getOption().getName() << Val;
4610       }
4611     } else if (A->getOption().matches(options::OPT_ffast_math) ||
4612                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
4613       // If fast-math is set then set the fp-contract mode to fast.
4614       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
4615     }
4616   }
4617
4618   ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
4619
4620   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
4621   // and if we find them, tell the frontend to provide the appropriate
4622   // preprocessor macros. This is distinct from enabling any optimizations as
4623   // these options induce language changes which must survive serialization
4624   // and deserialization, etc.
4625   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4626                                options::OPT_fno_fast_math))
4627     if (!A->getOption().matches(options::OPT_fno_fast_math))
4628       CmdArgs.push_back("-ffast-math");
4629   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
4630                                options::OPT_fno_fast_math))
4631     if (A->getOption().matches(options::OPT_ffinite_math_only))
4632       CmdArgs.push_back("-ffinite-math-only");
4633
4634   // Decide whether to use verbose asm. Verbose assembly is the default on
4635   // toolchains which have the integrated assembler on by default.
4636   bool IsIntegratedAssemblerDefault =
4637       getToolChain().IsIntegratedAssemblerDefault();
4638   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4639                    IsIntegratedAssemblerDefault) ||
4640       Args.hasArg(options::OPT_dA))
4641     CmdArgs.push_back("-masm-verbose");
4642
4643   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
4644                     IsIntegratedAssemblerDefault))
4645     CmdArgs.push_back("-no-integrated-as");
4646
4647   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4648     CmdArgs.push_back("-mdebug-pass");
4649     CmdArgs.push_back("Structure");
4650   }
4651   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4652     CmdArgs.push_back("-mdebug-pass");
4653     CmdArgs.push_back("Arguments");
4654   }
4655
4656   // Enable -mconstructor-aliases except on darwin, where we have to work around
4657   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4658   // aliases aren't supported.
4659   if (!getToolChain().getTriple().isOSDarwin() &&
4660       !getToolChain().getTriple().isNVPTX())
4661     CmdArgs.push_back("-mconstructor-aliases");
4662
4663   // Darwin's kernel doesn't support guard variables; just die if we
4664   // try to use them.
4665   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
4666     CmdArgs.push_back("-fforbid-guard-variables");
4667
4668   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4669                    false)) {
4670     CmdArgs.push_back("-mms-bitfields");
4671   }
4672
4673   if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4674                    options::OPT_mno_pie_copy_relocations,
4675                    false)) {
4676     CmdArgs.push_back("-mpie-copy-relocations");
4677   }
4678
4679   // This is a coarse approximation of what llvm-gcc actually does, both
4680   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4681   // complicated ways.
4682   bool AsynchronousUnwindTables =
4683       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4684                    options::OPT_fno_asynchronous_unwind_tables,
4685                    (getToolChain().IsUnwindTablesDefault() ||
4686                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
4687                        !KernelOrKext);
4688   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4689                    AsynchronousUnwindTables))
4690     CmdArgs.push_back("-munwind-tables");
4691
4692   getToolChain().addClangTargetOptions(Args, CmdArgs);
4693
4694   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
4695     CmdArgs.push_back("-mlimit-float-precision");
4696     CmdArgs.push_back(A->getValue());
4697   }
4698
4699   // FIXME: Handle -mtune=.
4700   (void)Args.hasArg(options::OPT_mtune_EQ);
4701
4702   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4703     CmdArgs.push_back("-mcode-model");
4704     CmdArgs.push_back(A->getValue());
4705   }
4706
4707   // Add the target cpu
4708   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4709   if (!CPU.empty()) {
4710     CmdArgs.push_back("-target-cpu");
4711     CmdArgs.push_back(Args.MakeArgString(CPU));
4712   }
4713
4714   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
4715     CmdArgs.push_back("-mfpmath");
4716     CmdArgs.push_back(A->getValue());
4717   }
4718
4719   // Add the target features
4720   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
4721
4722   // Add target specific flags.
4723   switch (getToolChain().getArch()) {
4724   default:
4725     break;
4726
4727   case llvm::Triple::arm:
4728   case llvm::Triple::armeb:
4729   case llvm::Triple::thumb:
4730   case llvm::Triple::thumbeb:
4731     // Use the effective triple, which takes into account the deployment target.
4732     AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
4733     break;
4734
4735   case llvm::Triple::aarch64:
4736   case llvm::Triple::aarch64_be:
4737     AddAArch64TargetArgs(Args, CmdArgs);
4738     break;
4739
4740   case llvm::Triple::mips:
4741   case llvm::Triple::mipsel:
4742   case llvm::Triple::mips64:
4743   case llvm::Triple::mips64el:
4744     AddMIPSTargetArgs(Args, CmdArgs);
4745     break;
4746
4747   case llvm::Triple::ppc:
4748   case llvm::Triple::ppc64:
4749   case llvm::Triple::ppc64le:
4750     AddPPCTargetArgs(Args, CmdArgs);
4751     break;
4752
4753   case llvm::Triple::sparc:
4754   case llvm::Triple::sparcel:
4755   case llvm::Triple::sparcv9:
4756     AddSparcTargetArgs(Args, CmdArgs);
4757     break;
4758
4759   case llvm::Triple::systemz:
4760     AddSystemZTargetArgs(Args, CmdArgs);
4761     break;
4762
4763   case llvm::Triple::x86:
4764   case llvm::Triple::x86_64:
4765     AddX86TargetArgs(Args, CmdArgs);
4766     break;
4767
4768   case llvm::Triple::lanai:
4769     AddLanaiTargetArgs(Args, CmdArgs);
4770     break;
4771
4772   case llvm::Triple::hexagon:
4773     AddHexagonTargetArgs(Args, CmdArgs);
4774     break;
4775
4776   case llvm::Triple::wasm32:
4777   case llvm::Triple::wasm64:
4778     AddWebAssemblyTargetArgs(Args, CmdArgs);
4779     break;
4780   }
4781
4782   // The 'g' groups options involve a somewhat intricate sequence of decisions
4783   // about what to pass from the driver to the frontend, but by the time they
4784   // reach cc1 they've been factored into three well-defined orthogonal choices:
4785   //  * what level of debug info to generate
4786   //  * what dwarf version to write
4787   //  * what debugger tuning to use
4788   // This avoids having to monkey around further in cc1 other than to disable
4789   // codeview if not running in a Windows environment. Perhaps even that
4790   // decision should be made in the driver as well though.
4791   unsigned DwarfVersion = 0;
4792   llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4793   // These two are potentially updated by AddClangCLArgs.
4794   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4795   bool EmitCodeView = false;
4796
4797   // Add clang-cl arguments.
4798   types::ID InputType = Input.getType();
4799   if (getToolChain().getDriver().IsCLMode())
4800     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4801
4802   // Pass the linker version in use.
4803   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4804     CmdArgs.push_back("-target-linker-version");
4805     CmdArgs.push_back(A->getValue());
4806   }
4807
4808   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4809     CmdArgs.push_back("-momit-leaf-frame-pointer");
4810
4811   // Explicitly error on some things we know we don't support and can't just
4812   // ignore.
4813   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4814     Arg *Unsupported;
4815     if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4816         getToolChain().getArch() == llvm::Triple::x86) {
4817       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4818           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4819         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4820             << Unsupported->getOption().getName();
4821     }
4822   }
4823
4824   Args.AddAllArgs(CmdArgs, options::OPT_v);
4825   Args.AddLastArg(CmdArgs, options::OPT_H);
4826   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4827     CmdArgs.push_back("-header-include-file");
4828     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4829                                                : "-");
4830   }
4831   Args.AddLastArg(CmdArgs, options::OPT_P);
4832   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4833
4834   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4835     CmdArgs.push_back("-diagnostic-log-file");
4836     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4837                                                  : "-");
4838   }
4839
4840   bool splitDwarfInlining =
4841       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4842                    options::OPT_fno_split_dwarf_inlining, true);
4843
4844   Args.ClaimAllArgs(options::OPT_g_Group);
4845   Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4846   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4847     // If the last option explicitly specified a debug-info level, use it.
4848     if (A->getOption().matches(options::OPT_gN_Group)) {
4849       DebugInfoKind = DebugLevelToInfoKind(*A);
4850       // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4851       // But -gsplit-dwarf is not a g_group option, hence we have to check the
4852       // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4853       // This gets a bit more complicated if you've disabled inline info in the
4854       // skeleton CUs (splitDwarfInlining) - then there's value in composing
4855       // split-dwarf and line-tables-only, so let those compose naturally in
4856       // that case.
4857       // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
4858       if (SplitDwarfArg) {
4859         if (A->getIndex() > SplitDwarfArg->getIndex()) {
4860           if (DebugInfoKind == codegenoptions::NoDebugInfo ||
4861               (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
4862                splitDwarfInlining))
4863             SplitDwarfArg = nullptr;
4864         } else if (splitDwarfInlining)
4865           DebugInfoKind = codegenoptions::NoDebugInfo;
4866       }
4867     } else
4868       // For any other 'g' option, use Limited.
4869       DebugInfoKind = codegenoptions::LimitedDebugInfo;
4870   }
4871
4872   // If a debugger tuning argument appeared, remember it.
4873   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4874                                options::OPT_ggdbN_Group)) {
4875     if (A->getOption().matches(options::OPT_glldb))
4876       DebuggerTuning = llvm::DebuggerKind::LLDB;
4877     else if (A->getOption().matches(options::OPT_gsce))
4878       DebuggerTuning = llvm::DebuggerKind::SCE;
4879     else
4880       DebuggerTuning = llvm::DebuggerKind::GDB;
4881   }
4882
4883   // If a -gdwarf argument appeared, remember it.
4884   if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4885                                options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4886     DwarfVersion = DwarfVersionNum(A->getSpelling());
4887
4888   // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
4889   // argument parsing.
4890   if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4891     // DwarfVersion remains at 0 if no explicit choice was made.
4892     CmdArgs.push_back("-gcodeview");
4893   } else if (DwarfVersion == 0 &&
4894              DebugInfoKind != codegenoptions::NoDebugInfo) {
4895     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4896   }
4897
4898   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4899   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4900
4901   // Column info is included by default for everything except PS4 and CodeView.
4902   // Clang doesn't track end columns, just starting columns, which, in theory,
4903   // is fine for CodeView (and PDB).  In practice, however, the Microsoft
4904   // debuggers don't handle missing end columns well, so it's better not to
4905   // include any column info.
4906   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4907                    /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
4908     CmdArgs.push_back("-dwarf-column-info");
4909
4910   // FIXME: Move backend command line options to the module.
4911   // If -gline-tables-only is the last option it wins.
4912   if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
4913       Args.hasArg(options::OPT_gmodules)) {
4914     DebugInfoKind = codegenoptions::LimitedDebugInfo;
4915     CmdArgs.push_back("-dwarf-ext-refs");
4916     CmdArgs.push_back("-fmodule-format=obj");
4917   }
4918
4919   // -gsplit-dwarf should turn on -g and enable the backend dwarf
4920   // splitting and extraction.
4921   // FIXME: Currently only works on Linux.
4922   if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4923     if (!splitDwarfInlining)
4924       CmdArgs.push_back("-fno-split-dwarf-inlining");
4925     if (DebugInfoKind == codegenoptions::NoDebugInfo)
4926       DebugInfoKind = codegenoptions::LimitedDebugInfo;
4927     CmdArgs.push_back("-backend-option");
4928     CmdArgs.push_back("-split-dwarf=Enable");
4929   }
4930
4931   // After we've dealt with all combinations of things that could
4932   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4933   // figure out if we need to "upgrade" it to standalone debug info.
4934   // We parse these two '-f' options whether or not they will be used,
4935   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4936   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4937                                     options::OPT_fno_standalone_debug,
4938                                     getToolChain().GetDefaultStandaloneDebug());
4939   if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
4940     DebugInfoKind = codegenoptions::FullDebugInfo;
4941   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4942                           DebuggerTuning);
4943
4944   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4945   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4946     CmdArgs.push_back("-backend-option");
4947     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4948   }
4949
4950   // -gdwarf-aranges turns on the emission of the aranges section in the
4951   // backend.
4952   // Always enabled on the PS4.
4953   if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4954     CmdArgs.push_back("-backend-option");
4955     CmdArgs.push_back("-generate-arange-section");
4956   }
4957
4958   if (Args.hasFlag(options::OPT_fdebug_types_section,
4959                    options::OPT_fno_debug_types_section, false)) {
4960     CmdArgs.push_back("-backend-option");
4961     CmdArgs.push_back("-generate-type-units");
4962   }
4963
4964   bool UseSeparateSections = isUseSeparateSections(Triple);
4965
4966   if (Args.hasFlag(options::OPT_ffunction_sections,
4967                    options::OPT_fno_function_sections, UseSeparateSections)) {
4968     CmdArgs.push_back("-ffunction-sections");
4969   }
4970
4971   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4972                    UseSeparateSections)) {
4973     CmdArgs.push_back("-fdata-sections");
4974   }
4975
4976   if (!Args.hasFlag(options::OPT_funique_section_names,
4977                     options::OPT_fno_unique_section_names, true))
4978     CmdArgs.push_back("-fno-unique-section-names");
4979
4980   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4981
4982   if (Args.hasFlag(options::OPT_fxray_instrument,
4983                    options::OPT_fnoxray_instrument, false)) {
4984     const char *const XRayInstrumentOption = "-fxray-instrument";
4985     if (Triple.getOS() == llvm::Triple::Linux)
4986       switch (Triple.getArch()) {
4987       case llvm::Triple::x86_64:
4988       case llvm::Triple::arm:
4989       case llvm::Triple::aarch64:
4990         // Supported.
4991         break;
4992       default:
4993         D.Diag(diag::err_drv_clang_unsupported)
4994             << (std::string(XRayInstrumentOption) + " on " + Triple.str());
4995       }
4996     else
4997       D.Diag(diag::err_drv_clang_unsupported)
4998           << (std::string(XRayInstrumentOption) + " on non-Linux target OS");
4999     CmdArgs.push_back(XRayInstrumentOption);
5000     if (const Arg *A =
5001             Args.getLastArg(options::OPT_fxray_instruction_threshold_,
5002                             options::OPT_fxray_instruction_threshold_EQ)) {
5003       CmdArgs.push_back("-fxray-instruction-threshold");
5004       CmdArgs.push_back(A->getValue());
5005     }
5006   }
5007
5008   addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
5009
5010   // Add runtime flag for PS4 when PGO or Coverage are enabled.
5011   if (getToolChain().getTriple().isPS4CPU())
5012     addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
5013
5014   // Pass options for controlling the default header search paths.
5015   if (Args.hasArg(options::OPT_nostdinc)) {
5016     CmdArgs.push_back("-nostdsysteminc");
5017     CmdArgs.push_back("-nobuiltininc");
5018   } else {
5019     if (Args.hasArg(options::OPT_nostdlibinc))
5020       CmdArgs.push_back("-nostdsysteminc");
5021     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5022     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5023   }
5024
5025   // Pass the path to compiler resource files.
5026   CmdArgs.push_back("-resource-dir");
5027   CmdArgs.push_back(D.ResourceDir.c_str());
5028
5029   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5030
5031   bool ARCMTEnabled = false;
5032   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
5033     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
5034                                        options::OPT_ccc_arcmt_modify,
5035                                        options::OPT_ccc_arcmt_migrate)) {
5036       ARCMTEnabled = true;
5037       switch (A->getOption().getID()) {
5038       default:
5039         llvm_unreachable("missed a case");
5040       case options::OPT_ccc_arcmt_check:
5041         CmdArgs.push_back("-arcmt-check");
5042         break;
5043       case options::OPT_ccc_arcmt_modify:
5044         CmdArgs.push_back("-arcmt-modify");
5045         break;
5046       case options::OPT_ccc_arcmt_migrate:
5047         CmdArgs.push_back("-arcmt-migrate");
5048         CmdArgs.push_back("-mt-migrate-directory");
5049         CmdArgs.push_back(A->getValue());
5050
5051         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
5052         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
5053         break;
5054       }
5055     }
5056   } else {
5057     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
5058     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
5059     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
5060   }
5061
5062   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
5063     if (ARCMTEnabled) {
5064       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5065                                                       << "-ccc-arcmt-migrate";
5066     }
5067     CmdArgs.push_back("-mt-migrate-directory");
5068     CmdArgs.push_back(A->getValue());
5069
5070     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
5071                      options::OPT_objcmt_migrate_subscripting,
5072                      options::OPT_objcmt_migrate_property)) {
5073       // None specified, means enable them all.
5074       CmdArgs.push_back("-objcmt-migrate-literals");
5075       CmdArgs.push_back("-objcmt-migrate-subscripting");
5076       CmdArgs.push_back("-objcmt-migrate-property");
5077     } else {
5078       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
5079       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
5080       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
5081     }
5082   } else {
5083     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
5084     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
5085     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
5086     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
5087     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
5088     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
5089     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
5090     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
5091     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
5092     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
5093     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
5094     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
5095     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
5096     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
5097     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
5098     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
5099   }
5100
5101   // Add preprocessing options like -I, -D, etc. if we are using the
5102   // preprocessor.
5103   //
5104   // FIXME: Support -fpreprocessed
5105   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5106     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5107
5108   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5109   // that "The compiler can only warn and ignore the option if not recognized".
5110   // When building with ccache, it will pass -D options to clang even on
5111   // preprocessed inputs and configure concludes that -fPIC is not supported.
5112   Args.ClaimAllArgs(options::OPT_D);
5113
5114   // Manually translate -O4 to -O3; let clang reject others.
5115   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5116     if (A->getOption().matches(options::OPT_O4)) {
5117       CmdArgs.push_back("-O3");
5118       D.Diag(diag::warn_O4_is_O3);
5119     } else {
5120       A->render(Args, CmdArgs);
5121     }
5122   }
5123
5124   // Warn about ignored options to clang.
5125   for (const Arg *A :
5126        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5127     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5128     A->claim();
5129   }
5130
5131   claimNoWarnArgs(Args);
5132
5133   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5134
5135   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
5136   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5137     CmdArgs.push_back("-pedantic");
5138   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5139   Args.AddLastArg(CmdArgs, options::OPT_w);
5140
5141   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5142   // (-ansi is equivalent to -std=c89 or -std=c++98).
5143   //
5144   // If a std is supplied, only add -trigraphs if it follows the
5145   // option.
5146   bool ImplyVCPPCXXVer = false;
5147   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
5148     if (Std->getOption().matches(options::OPT_ansi))
5149       if (types::isCXX(InputType))
5150         CmdArgs.push_back("-std=c++98");
5151       else
5152         CmdArgs.push_back("-std=c89");
5153     else
5154       Std->render(Args, CmdArgs);
5155
5156     // If -f(no-)trigraphs appears after the language standard flag, honor it.
5157     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
5158                                  options::OPT_ftrigraphs,
5159                                  options::OPT_fno_trigraphs))
5160       if (A != Std)
5161         A->render(Args, CmdArgs);
5162   } else {
5163     // Honor -std-default.
5164     //
5165     // FIXME: Clang doesn't correctly handle -std= when the input language
5166     // doesn't match. For the time being just ignore this for C++ inputs;
5167     // eventually we want to do all the standard defaulting here instead of
5168     // splitting it between the driver and clang -cc1.
5169     if (!types::isCXX(InputType))
5170       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
5171                                 /*Joined=*/true);
5172     else if (IsWindowsMSVC)
5173       ImplyVCPPCXXVer = true;
5174
5175     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
5176                     options::OPT_fno_trigraphs);
5177   }
5178
5179   // GCC's behavior for -Wwrite-strings is a bit strange:
5180   //  * In C, this "warning flag" changes the types of string literals from
5181   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
5182   //    for the discarded qualifier.
5183   //  * In C++, this is just a normal warning flag.
5184   //
5185   // Implementing this warning correctly in C is hard, so we follow GCC's
5186   // behavior for now. FIXME: Directly diagnose uses of a string literal as
5187   // a non-const char* in C, rather than using this crude hack.
5188   if (!types::isCXX(InputType)) {
5189     // FIXME: This should behave just like a warning flag, and thus should also
5190     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
5191     Arg *WriteStrings =
5192         Args.getLastArg(options::OPT_Wwrite_strings,
5193                         options::OPT_Wno_write_strings, options::OPT_w);
5194     if (WriteStrings &&
5195         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
5196       CmdArgs.push_back("-fconst-strings");
5197   }
5198
5199   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
5200   // during C++ compilation, which it is by default. GCC keeps this define even
5201   // in the presence of '-w', match this behavior bug-for-bug.
5202   if (types::isCXX(InputType) &&
5203       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
5204                    true)) {
5205     CmdArgs.push_back("-fdeprecated-macro");
5206   }
5207
5208   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
5209   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
5210     if (Asm->getOption().matches(options::OPT_fasm))
5211       CmdArgs.push_back("-fgnu-keywords");
5212     else
5213       CmdArgs.push_back("-fno-gnu-keywords");
5214   }
5215
5216   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
5217     CmdArgs.push_back("-fno-dwarf-directory-asm");
5218
5219   if (ShouldDisableAutolink(Args, getToolChain()))
5220     CmdArgs.push_back("-fno-autolink");
5221
5222   // Add in -fdebug-compilation-dir if necessary.
5223   addDebugCompDirArg(Args, CmdArgs);
5224
5225   for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
5226     StringRef Map = A->getValue();
5227     if (Map.find('=') == StringRef::npos)
5228       D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
5229     else
5230       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
5231     A->claim();
5232   }
5233
5234   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
5235                                options::OPT_ftemplate_depth_EQ)) {
5236     CmdArgs.push_back("-ftemplate-depth");
5237     CmdArgs.push_back(A->getValue());
5238   }
5239
5240   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
5241     CmdArgs.push_back("-foperator-arrow-depth");
5242     CmdArgs.push_back(A->getValue());
5243   }
5244
5245   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
5246     CmdArgs.push_back("-fconstexpr-depth");
5247     CmdArgs.push_back(A->getValue());
5248   }
5249
5250   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
5251     CmdArgs.push_back("-fconstexpr-steps");
5252     CmdArgs.push_back(A->getValue());
5253   }
5254
5255   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
5256     CmdArgs.push_back("-fbracket-depth");
5257     CmdArgs.push_back(A->getValue());
5258   }
5259
5260   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
5261                                options::OPT_Wlarge_by_value_copy_def)) {
5262     if (A->getNumValues()) {
5263       StringRef bytes = A->getValue();
5264       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
5265     } else
5266       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
5267   }
5268
5269   if (Args.hasArg(options::OPT_relocatable_pch))
5270     CmdArgs.push_back("-relocatable-pch");
5271
5272   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
5273     CmdArgs.push_back("-fconstant-string-class");
5274     CmdArgs.push_back(A->getValue());
5275   }
5276
5277   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
5278     CmdArgs.push_back("-ftabstop");
5279     CmdArgs.push_back(A->getValue());
5280   }
5281
5282   CmdArgs.push_back("-ferror-limit");
5283   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
5284     CmdArgs.push_back(A->getValue());
5285   else
5286     CmdArgs.push_back("19");
5287
5288   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
5289     CmdArgs.push_back("-fmacro-backtrace-limit");
5290     CmdArgs.push_back(A->getValue());
5291   }
5292
5293   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
5294     CmdArgs.push_back("-ftemplate-backtrace-limit");
5295     CmdArgs.push_back(A->getValue());
5296   }
5297
5298   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
5299     CmdArgs.push_back("-fconstexpr-backtrace-limit");
5300     CmdArgs.push_back(A->getValue());
5301   }
5302
5303   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
5304     CmdArgs.push_back("-fspell-checking-limit");
5305     CmdArgs.push_back(A->getValue());
5306   }
5307
5308   // Pass -fmessage-length=.
5309   CmdArgs.push_back("-fmessage-length");
5310   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
5311     CmdArgs.push_back(A->getValue());
5312   } else {
5313     // If -fmessage-length=N was not specified, determine whether this is a
5314     // terminal and, if so, implicitly define -fmessage-length appropriately.
5315     unsigned N = llvm::sys::Process::StandardErrColumns();
5316     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
5317   }
5318
5319   // -fvisibility= and -fvisibility-ms-compat are of a piece.
5320   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
5321                                      options::OPT_fvisibility_ms_compat)) {
5322     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
5323       CmdArgs.push_back("-fvisibility");
5324       CmdArgs.push_back(A->getValue());
5325     } else {
5326       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
5327       CmdArgs.push_back("-fvisibility");
5328       CmdArgs.push_back("hidden");
5329       CmdArgs.push_back("-ftype-visibility");
5330       CmdArgs.push_back("default");
5331     }
5332   }
5333
5334   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
5335
5336   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
5337
5338   // -fhosted is default.
5339   bool IsHosted = true;
5340   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5341       KernelOrKext) {
5342     CmdArgs.push_back("-ffreestanding");
5343     IsHosted = false;
5344   }
5345
5346   // Forward -f (flag) options which we can pass directly.
5347   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5348   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5349   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
5350   // Emulated TLS is enabled by default on Android, and can be enabled manually
5351   // with -femulated-tls.
5352   bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
5353   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
5354                    EmulatedTLSDefault))
5355     CmdArgs.push_back("-femulated-tls");
5356   // AltiVec-like language extensions aren't relevant for assembling.
5357   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
5358     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
5359     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5360   }
5361   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5362   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5363
5364   // Forward flags for OpenMP. We don't do this if the current action is an
5365   // device offloading action other than OpenMP.
5366   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5367                    options::OPT_fno_openmp, false) &&
5368       (JA.isDeviceOffloading(Action::OFK_None) ||
5369        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
5370     switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
5371     case Driver::OMPRT_OMP:
5372     case Driver::OMPRT_IOMP5:
5373       // Clang can generate useful OpenMP code for these two runtime libraries.
5374       CmdArgs.push_back("-fopenmp");
5375
5376       // If no option regarding the use of TLS in OpenMP codegeneration is
5377       // given, decide a default based on the target. Otherwise rely on the
5378       // options and pass the right information to the frontend.
5379       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5380                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5381         CmdArgs.push_back("-fnoopenmp-use-tls");
5382       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5383       break;
5384     default:
5385       // By default, if Clang doesn't know how to generate useful OpenMP code
5386       // for a specific runtime library, we just don't pass the '-fopenmp' flag
5387       // down to the actual compilation.
5388       // FIXME: It would be better to have a mode which *only* omits IR
5389       // generation based on the OpenMP support so that we get consistent
5390       // semantic analysis, etc.
5391       break;
5392     }
5393   }
5394
5395   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
5396   Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
5397
5398   // Report an error for -faltivec on anything other than PowerPC.
5399   if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
5400     const llvm::Triple::ArchType Arch = getToolChain().getArch();
5401     if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
5402           Arch == llvm::Triple::ppc64le))
5403       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
5404                                                        << "ppc/ppc64/ppc64le";
5405   }
5406
5407   // -fzvector is incompatible with -faltivec.
5408   if (Arg *A = Args.getLastArg(options::OPT_fzvector))
5409     if (Args.hasArg(options::OPT_faltivec))
5410       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5411                                                       << "-faltivec";
5412
5413   if (getToolChain().SupportsProfiling())
5414     Args.AddLastArg(CmdArgs, options::OPT_pg);
5415
5416   // -flax-vector-conversions is default.
5417   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
5418                     options::OPT_fno_lax_vector_conversions))
5419     CmdArgs.push_back("-fno-lax-vector-conversions");
5420
5421   if (Args.getLastArg(options::OPT_fapple_kext) ||
5422       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5423     CmdArgs.push_back("-fapple-kext");
5424
5425   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5426   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5427   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5428   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5429   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5430
5431   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5432     CmdArgs.push_back("-ftrapv-handler");
5433     CmdArgs.push_back(A->getValue());
5434   }
5435
5436   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5437
5438   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5439   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5440   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5441     if (A->getOption().matches(options::OPT_fwrapv))
5442       CmdArgs.push_back("-fwrapv");
5443   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5444                                       options::OPT_fno_strict_overflow)) {
5445     if (A->getOption().matches(options::OPT_fno_strict_overflow))
5446       CmdArgs.push_back("-fwrapv");
5447   }
5448
5449   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5450                                options::OPT_fno_reroll_loops))
5451     if (A->getOption().matches(options::OPT_freroll_loops))
5452       CmdArgs.push_back("-freroll-loops");
5453
5454   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5455   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5456                   options::OPT_fno_unroll_loops);
5457
5458   Args.AddLastArg(CmdArgs, options::OPT_pthread);
5459
5460   // -stack-protector=0 is default.
5461   unsigned StackProtectorLevel = 0;
5462   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
5463                                options::OPT_fstack_protector_all,
5464                                options::OPT_fstack_protector_strong,
5465                                options::OPT_fstack_protector)) {
5466     if (A->getOption().matches(options::OPT_fstack_protector)) {
5467       StackProtectorLevel = std::max<unsigned>(
5468           LangOptions::SSPOn,
5469           getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
5470     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
5471       StackProtectorLevel = LangOptions::SSPStrong;
5472     else if (A->getOption().matches(options::OPT_fstack_protector_all))
5473       StackProtectorLevel = LangOptions::SSPReq;
5474   } else {
5475     StackProtectorLevel =
5476         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
5477     // Only use a default stack protector on Darwin in case -ffreestanding
5478     // is not specified.
5479     if (Triple.isOSDarwin() && !IsHosted)
5480       StackProtectorLevel = 0;
5481   }
5482   if (StackProtectorLevel) {
5483     CmdArgs.push_back("-stack-protector");
5484     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
5485   }
5486
5487   // --param ssp-buffer-size=
5488   for (const Arg *A : Args.filtered(options::OPT__param)) {
5489     StringRef Str(A->getValue());
5490     if (Str.startswith("ssp-buffer-size=")) {
5491       if (StackProtectorLevel) {
5492         CmdArgs.push_back("-stack-protector-buffer-size");
5493         // FIXME: Verify the argument is a valid integer.
5494         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
5495       }
5496       A->claim();
5497     }
5498   }
5499
5500   // Translate -mstackrealign
5501   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5502                    false))
5503     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5504
5505   if (Args.hasArg(options::OPT_mstack_alignment)) {
5506     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5507     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5508   }
5509
5510   if (Args.hasArg(options::OPT_mstack_probe_size)) {
5511     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5512
5513     if (!Size.empty())
5514       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5515     else
5516       CmdArgs.push_back("-mstack-probe-size=0");
5517   }
5518
5519   switch (getToolChain().getArch()) {
5520   case llvm::Triple::aarch64:
5521   case llvm::Triple::aarch64_be:
5522   case llvm::Triple::arm:
5523   case llvm::Triple::armeb:
5524   case llvm::Triple::thumb:
5525   case llvm::Triple::thumbeb:
5526     CmdArgs.push_back("-fallow-half-arguments-and-returns");
5527     break;
5528
5529   default:
5530     break;
5531   }
5532
5533   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5534                                options::OPT_mno_restrict_it)) {
5535     if (A->getOption().matches(options::OPT_mrestrict_it)) {
5536       CmdArgs.push_back("-backend-option");
5537       CmdArgs.push_back("-arm-restrict-it");
5538     } else {
5539       CmdArgs.push_back("-backend-option");
5540       CmdArgs.push_back("-arm-no-restrict-it");
5541     }
5542   } else if (Triple.isOSWindows() &&
5543              (Triple.getArch() == llvm::Triple::arm ||
5544               Triple.getArch() == llvm::Triple::thumb)) {
5545     // Windows on ARM expects restricted IT blocks
5546     CmdArgs.push_back("-backend-option");
5547     CmdArgs.push_back("-arm-restrict-it");
5548   }
5549
5550   // Forward -cl options to -cc1
5551   if (Args.getLastArg(options::OPT_cl_opt_disable)) {
5552     CmdArgs.push_back("-cl-opt-disable");
5553   }
5554   if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
5555     CmdArgs.push_back("-cl-strict-aliasing");
5556   }
5557   if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
5558     CmdArgs.push_back("-cl-single-precision-constant");
5559   }
5560   if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
5561     CmdArgs.push_back("-cl-finite-math-only");
5562   }
5563   if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
5564     CmdArgs.push_back("-cl-kernel-arg-info");
5565   }
5566   if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
5567     CmdArgs.push_back("-cl-unsafe-math-optimizations");
5568   }
5569   if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
5570     CmdArgs.push_back("-cl-fast-relaxed-math");
5571   }
5572   if (Args.getLastArg(options::OPT_cl_mad_enable)) {
5573     CmdArgs.push_back("-cl-mad-enable");
5574   }
5575   if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
5576     CmdArgs.push_back("-cl-no-signed-zeros");
5577   }
5578   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
5579     std::string CLStdStr = "-cl-std=";
5580     CLStdStr += A->getValue();
5581     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
5582   }
5583   if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
5584     CmdArgs.push_back("-cl-denorms-are-zero");
5585   }
5586   if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
5587     CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
5588   }
5589
5590   // Forward -f options with positive and negative forms; we translate
5591   // these by hand.
5592   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
5593     StringRef fname = A->getValue();
5594     if (!llvm::sys::fs::exists(fname))
5595       D.Diag(diag::err_drv_no_such_file) << fname;
5596     else
5597       A->render(Args, CmdArgs);
5598   }
5599
5600   // -fbuiltin is default unless -mkernel is used.
5601   bool UseBuiltins =
5602       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
5603                    !Args.hasArg(options::OPT_mkernel));
5604   if (!UseBuiltins)
5605     CmdArgs.push_back("-fno-builtin");
5606
5607   // -ffreestanding implies -fno-builtin.
5608   if (Args.hasArg(options::OPT_ffreestanding))
5609     UseBuiltins = false;
5610
5611   // Process the -fno-builtin-* options.
5612   for (const auto &Arg : Args) {
5613     const Option &O = Arg->getOption();
5614     if (!O.matches(options::OPT_fno_builtin_))
5615       continue;
5616
5617     Arg->claim();
5618     // If -fno-builtin is specified, then there's no need to pass the option to
5619     // the frontend.
5620     if (!UseBuiltins)
5621       continue;
5622
5623     StringRef FuncName = Arg->getValue();
5624     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
5625   }
5626
5627   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5628                     options::OPT_fno_assume_sane_operator_new))
5629     CmdArgs.push_back("-fno-assume-sane-operator-new");
5630
5631   // -fblocks=0 is default.
5632   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5633                    getToolChain().IsBlocksDefault()) ||
5634       (Args.hasArg(options::OPT_fgnu_runtime) &&
5635        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5636        !Args.hasArg(options::OPT_fno_blocks))) {
5637     CmdArgs.push_back("-fblocks");
5638
5639     if (!Args.hasArg(options::OPT_fgnu_runtime) &&
5640         !getToolChain().hasBlocksRuntime())
5641       CmdArgs.push_back("-fblocks-runtime-optional");
5642   }
5643
5644   if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
5645                    false) &&
5646       types::isCXX(InputType)) {
5647     CmdArgs.push_back("-fcoroutines-ts");
5648   }
5649
5650   // -fmodules enables the use of precompiled modules (off by default).
5651   // Users can pass -fno-cxx-modules to turn off modules support for
5652   // C++/Objective-C++ programs.
5653   bool HaveClangModules = false;
5654   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
5655     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
5656                                      options::OPT_fno_cxx_modules, true);
5657     if (AllowedInCXX || !types::isCXX(InputType)) {
5658       CmdArgs.push_back("-fmodules");
5659       HaveClangModules = true;
5660     }
5661   }
5662
5663   bool HaveAnyModules = HaveClangModules;
5664   if (Args.hasArg(options::OPT_fmodules_ts)) {
5665     CmdArgs.push_back("-fmodules-ts");
5666     HaveAnyModules = true;
5667   }
5668
5669   // -fmodule-maps enables implicit reading of module map files. By default,
5670   // this is enabled if we are using Clang's flavor of precompiled modules.
5671   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
5672                    options::OPT_fno_implicit_module_maps, HaveClangModules)) {
5673     CmdArgs.push_back("-fimplicit-module-maps");
5674   }
5675
5676   // -fmodules-decluse checks that modules used are declared so (off by
5677   // default).
5678   if (Args.hasFlag(options::OPT_fmodules_decluse,
5679                    options::OPT_fno_modules_decluse, false)) {
5680     CmdArgs.push_back("-fmodules-decluse");
5681   }
5682
5683   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
5684   // all #included headers are part of modules.
5685   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
5686                    options::OPT_fno_modules_strict_decluse, false)) {
5687     CmdArgs.push_back("-fmodules-strict-decluse");
5688   }
5689
5690   // -fno-implicit-modules turns off implicitly compiling modules on demand.
5691   if (!Args.hasFlag(options::OPT_fimplicit_modules,
5692                     options::OPT_fno_implicit_modules, HaveClangModules)) {
5693     if (HaveAnyModules)
5694       CmdArgs.push_back("-fno-implicit-modules");
5695   } else if (HaveAnyModules) {
5696     // -fmodule-cache-path specifies where our implicitly-built module files
5697     // should be written.
5698     SmallString<128> Path;
5699     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
5700       Path = A->getValue();
5701     if (C.isForDiagnostics()) {
5702       // When generating crash reports, we want to emit the modules along with
5703       // the reproduction sources, so we ignore any provided module path.
5704       Path = Output.getFilename();
5705       llvm::sys::path::replace_extension(Path, ".cache");
5706       llvm::sys::path::append(Path, "modules");
5707     } else if (Path.empty()) {
5708       // No module path was provided: use the default.
5709       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
5710       llvm::sys::path::append(Path, "org.llvm.clang.");
5711       appendUserToPath(Path);
5712       llvm::sys::path::append(Path, "ModuleCache");
5713     }
5714     const char Arg[] = "-fmodules-cache-path=";
5715     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
5716     CmdArgs.push_back(Args.MakeArgString(Path));
5717   }
5718
5719   if (HaveAnyModules) {
5720     // -fprebuilt-module-path specifies where to load the prebuilt module files.
5721     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
5722       CmdArgs.push_back(Args.MakeArgString(
5723           std::string("-fprebuilt-module-path=") + A->getValue()));
5724   }
5725       
5726   // -fmodule-name specifies the module that is currently being built (or
5727   // used for header checking by -fmodule-maps).
5728   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
5729
5730   // -fmodule-map-file can be used to specify files containing module
5731   // definitions.
5732   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
5733
5734   // -fbuiltin-module-map can be used to load the clang
5735   // builtin headers modulemap file.
5736   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
5737     SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
5738     llvm::sys::path::append(BuiltinModuleMap, "include");
5739     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
5740     if (llvm::sys::fs::exists(BuiltinModuleMap)) {
5741       CmdArgs.push_back(Args.MakeArgString("-fmodule-map-file=" +
5742                                            BuiltinModuleMap));
5743     }
5744   }
5745
5746   // -fmodule-file can be used to specify files containing precompiled modules.
5747   if (HaveAnyModules)
5748     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
5749   else
5750     Args.ClaimAllArgs(options::OPT_fmodule_file);
5751
5752   // When building modules and generating crashdumps, we need to dump a module
5753   // dependency VFS alongside the output.
5754   if (HaveClangModules && C.isForDiagnostics()) {
5755     SmallString<128> VFSDir(Output.getFilename());
5756     llvm::sys::path::replace_extension(VFSDir, ".cache");
5757     // Add the cache directory as a temp so the crash diagnostics pick it up.
5758     C.addTempFile(Args.MakeArgString(VFSDir));
5759
5760     llvm::sys::path::append(VFSDir, "vfs");
5761     CmdArgs.push_back("-module-dependency-dir");
5762     CmdArgs.push_back(Args.MakeArgString(VFSDir));
5763   }
5764
5765   if (HaveClangModules)
5766     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
5767
5768   // Pass through all -fmodules-ignore-macro arguments.
5769   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
5770   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
5771   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
5772
5773   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
5774
5775   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
5776     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
5777       D.Diag(diag::err_drv_argument_not_allowed_with)
5778           << A->getAsString(Args) << "-fbuild-session-timestamp";
5779
5780     llvm::sys::fs::file_status Status;
5781     if (llvm::sys::fs::status(A->getValue(), Status))
5782       D.Diag(diag::err_drv_no_such_file) << A->getValue();
5783     CmdArgs.push_back(
5784         Args.MakeArgString("-fbuild-session-timestamp=" +
5785                            Twine((uint64_t)Status.getLastModificationTime()
5786                                      .time_since_epoch()
5787                                      .count())));
5788   }
5789
5790   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
5791     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
5792                          options::OPT_fbuild_session_file))
5793       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
5794
5795     Args.AddLastArg(CmdArgs,
5796                     options::OPT_fmodules_validate_once_per_build_session);
5797   }
5798
5799   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
5800   Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
5801
5802   // -faccess-control is default.
5803   if (Args.hasFlag(options::OPT_fno_access_control,
5804                    options::OPT_faccess_control, false))
5805     CmdArgs.push_back("-fno-access-control");
5806
5807   // -felide-constructors is the default.
5808   if (Args.hasFlag(options::OPT_fno_elide_constructors,
5809                    options::OPT_felide_constructors, false))
5810     CmdArgs.push_back("-fno-elide-constructors");
5811
5812   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5813
5814   if (KernelOrKext || (types::isCXX(InputType) &&
5815                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5816                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
5817     CmdArgs.push_back("-fno-rtti");
5818
5819   // -fshort-enums=0 is default for all architectures except Hexagon.
5820   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5821                    getToolChain().getArch() == llvm::Triple::hexagon))
5822     CmdArgs.push_back("-fshort-enums");
5823
5824   // -fsigned-char is default.
5825   if (Arg *A = Args.getLastArg(
5826           options::OPT_fsigned_char, options::OPT_fno_signed_char,
5827           options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5828     if (A->getOption().matches(options::OPT_funsigned_char) ||
5829         A->getOption().matches(options::OPT_fno_signed_char)) {
5830       CmdArgs.push_back("-fno-signed-char");
5831     }
5832   } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5833     CmdArgs.push_back("-fno-signed-char");
5834   }
5835
5836   // -fuse-cxa-atexit is default.
5837   if (!Args.hasFlag(
5838           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5839           !IsWindowsCygnus && !IsWindowsGNU &&
5840               getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5841               getToolChain().getArch() != llvm::Triple::hexagon &&
5842               getToolChain().getArch() != llvm::Triple::xcore &&
5843               ((getToolChain().getTriple().getVendor() !=
5844                 llvm::Triple::MipsTechnologies) ||
5845                getToolChain().getTriple().hasEnvironment())) ||
5846       KernelOrKext)
5847     CmdArgs.push_back("-fno-use-cxa-atexit");
5848
5849   // -fms-extensions=0 is default.
5850   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5851                    IsWindowsMSVC))
5852     CmdArgs.push_back("-fms-extensions");
5853
5854   // -fno-use-line-directives is default.
5855   if (Args.hasFlag(options::OPT_fuse_line_directives,
5856                    options::OPT_fno_use_line_directives, false))
5857     CmdArgs.push_back("-fuse-line-directives");
5858
5859   // -fms-compatibility=0 is default.
5860   if (Args.hasFlag(options::OPT_fms_compatibility,
5861                    options::OPT_fno_ms_compatibility,
5862                    (IsWindowsMSVC &&
5863                     Args.hasFlag(options::OPT_fms_extensions,
5864                                  options::OPT_fno_ms_extensions, true))))
5865     CmdArgs.push_back("-fms-compatibility");
5866
5867   VersionTuple MSVT =
5868       getToolChain().computeMSVCVersion(&getToolChain().getDriver(), Args);
5869   if (!MSVT.empty())
5870     CmdArgs.push_back(
5871         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5872
5873   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5874   if (ImplyVCPPCXXVer) {
5875     StringRef LanguageStandard;
5876     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
5877       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
5878                              .Case("c++14", "-std=c++14")
5879                              .Case("c++latest", "-std=c++1z")
5880                              .Default("");
5881       if (LanguageStandard.empty())
5882         D.Diag(clang::diag::warn_drv_unused_argument)
5883             << StdArg->getAsString(Args);
5884     }
5885
5886     if (LanguageStandard.empty()) {
5887       if (IsMSVC2015Compatible)
5888         LanguageStandard = "-std=c++14";
5889       else
5890         LanguageStandard = "-std=c++11";
5891     }
5892
5893     CmdArgs.push_back(LanguageStandard.data());
5894   }
5895
5896   // -fno-borland-extensions is default.
5897   if (Args.hasFlag(options::OPT_fborland_extensions,
5898                    options::OPT_fno_borland_extensions, false))
5899     CmdArgs.push_back("-fborland-extensions");
5900
5901   // -fno-declspec is default, except for PS4.
5902   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5903                    getToolChain().getTriple().isPS4()))
5904     CmdArgs.push_back("-fdeclspec");
5905   else if (Args.hasArg(options::OPT_fno_declspec))
5906     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5907
5908   // -fthreadsafe-static is default, except for MSVC compatibility versions less
5909   // than 19.
5910   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5911                     options::OPT_fno_threadsafe_statics,
5912                     !IsWindowsMSVC || IsMSVC2015Compatible))
5913     CmdArgs.push_back("-fno-threadsafe-statics");
5914
5915   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5916   // needs it.
5917   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5918                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5919     CmdArgs.push_back("-fdelayed-template-parsing");
5920
5921   // -fgnu-keywords default varies depending on language; only pass if
5922   // specified.
5923   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5924                                options::OPT_fno_gnu_keywords))
5925     A->render(Args, CmdArgs);
5926
5927   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5928                    false))
5929     CmdArgs.push_back("-fgnu89-inline");
5930
5931   if (Args.hasArg(options::OPT_fno_inline))
5932     CmdArgs.push_back("-fno-inline");
5933
5934   if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
5935                                        options::OPT_finline_hint_functions,
5936                                        options::OPT_fno_inline_functions))
5937     InlineArg->render(Args, CmdArgs);
5938
5939   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
5940                   options::OPT_fno_experimental_new_pass_manager);
5941
5942   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5943
5944   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5945   // legacy is the default. Except for deployment target of 10.5,
5946   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5947   // gets ignored silently.
5948   if (objcRuntime.isNonFragile()) {
5949     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5950                       options::OPT_fno_objc_legacy_dispatch,
5951                       objcRuntime.isLegacyDispatchDefaultForArch(
5952                           getToolChain().getArch()))) {
5953       if (getToolChain().UseObjCMixedDispatch())
5954         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5955       else
5956         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5957     }
5958   }
5959
5960   // When ObjectiveC legacy runtime is in effect on MacOSX,
5961   // turn on the option to do Array/Dictionary subscripting
5962   // by default.
5963   if (getToolChain().getArch() == llvm::Triple::x86 &&
5964       getToolChain().getTriple().isMacOSX() &&
5965       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5966       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5967       objcRuntime.isNeXTFamily())
5968     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5969
5970   // -fencode-extended-block-signature=1 is default.
5971   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5972     CmdArgs.push_back("-fencode-extended-block-signature");
5973   }
5974
5975   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5976   // NOTE: This logic is duplicated in ToolChains.cpp.
5977   bool ARC = isObjCAutoRefCount(Args);
5978   if (ARC) {
5979     getToolChain().CheckObjCARC();
5980
5981     CmdArgs.push_back("-fobjc-arc");
5982
5983     // FIXME: It seems like this entire block, and several around it should be
5984     // wrapped in isObjC, but for now we just use it here as this is where it
5985     // was being used previously.
5986     if (types::isCXX(InputType) && types::isObjC(InputType)) {
5987       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5988         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5989       else
5990         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5991     }
5992
5993     // Allow the user to enable full exceptions code emission.
5994     // We define off for Objective-CC, on for Objective-C++.
5995     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5996                      options::OPT_fno_objc_arc_exceptions,
5997                      /*default*/ types::isCXX(InputType)))
5998       CmdArgs.push_back("-fobjc-arc-exceptions");
5999
6000   }
6001
6002   // -fobjc-infer-related-result-type is the default, except in the Objective-C
6003   // rewriter.
6004   if (rewriteKind != RK_None)
6005     CmdArgs.push_back("-fno-objc-infer-related-result-type");
6006
6007   // Pass down -fobjc-weak or -fno-objc-weak if present.
6008   if (types::isObjC(InputType)) {
6009     auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
6010                                    options::OPT_fno_objc_weak);
6011     if (!WeakArg) {
6012       // nothing to do
6013     } else if (!objcRuntime.allowsWeak()) {
6014       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
6015         D.Diag(diag::err_objc_weak_unsupported);
6016     } else {
6017       WeakArg->render(Args, CmdArgs);
6018     }
6019   }
6020
6021   if (Args.hasFlag(options::OPT_fapplication_extension,
6022                    options::OPT_fno_application_extension, false))
6023     CmdArgs.push_back("-fapplication-extension");
6024
6025   // Handle GCC-style exception args.
6026   if (!C.getDriver().IsCLMode())
6027     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
6028                      CmdArgs);
6029
6030   if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
6031       getToolChain().UseSjLjExceptions(Args))
6032     CmdArgs.push_back("-fsjlj-exceptions");
6033
6034   // C++ "sane" operator new.
6035   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
6036                     options::OPT_fno_assume_sane_operator_new))
6037     CmdArgs.push_back("-fno-assume-sane-operator-new");
6038
6039   // -frelaxed-template-template-args is off by default, as it is a severe
6040   // breaking change until a corresponding change to template partial ordering
6041   // is provided.
6042   if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
6043                    options::OPT_fno_relaxed_template_template_args, false))
6044     CmdArgs.push_back("-frelaxed-template-template-args");
6045
6046   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
6047   // most platforms.
6048   if (Args.hasFlag(options::OPT_fsized_deallocation,
6049                    options::OPT_fno_sized_deallocation, false))
6050     CmdArgs.push_back("-fsized-deallocation");
6051
6052   // -faligned-allocation is on by default in C++17 onwards and otherwise off
6053   // by default.
6054   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
6055                                options::OPT_fno_aligned_allocation,
6056                                options::OPT_faligned_new_EQ)) {
6057     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
6058       CmdArgs.push_back("-fno-aligned-allocation");
6059     else
6060       CmdArgs.push_back("-faligned-allocation");
6061   }
6062
6063   // The default new alignment can be specified using a dedicated option or via
6064   // a GCC-compatible option that also turns on aligned allocation.
6065   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
6066                                options::OPT_faligned_new_EQ))
6067     CmdArgs.push_back(
6068         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
6069
6070   // -fconstant-cfstrings is default, and may be subject to argument translation
6071   // on Darwin.
6072   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
6073                     options::OPT_fno_constant_cfstrings) ||
6074       !Args.hasFlag(options::OPT_mconstant_cfstrings,
6075                     options::OPT_mno_constant_cfstrings))
6076     CmdArgs.push_back("-fno-constant-cfstrings");
6077
6078   // -fshort-wchar default varies depending on platform; only
6079   // pass if specified.
6080   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
6081                                options::OPT_fno_short_wchar))
6082     A->render(Args, CmdArgs);
6083
6084   // -fno-pascal-strings is default, only pass non-default.
6085   if (Args.hasFlag(options::OPT_fpascal_strings,
6086                    options::OPT_fno_pascal_strings, false))
6087     CmdArgs.push_back("-fpascal-strings");
6088
6089   // Honor -fpack-struct= and -fpack-struct, if given. Note that
6090   // -fno-pack-struct doesn't apply to -fpack-struct=.
6091   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
6092     std::string PackStructStr = "-fpack-struct=";
6093     PackStructStr += A->getValue();
6094     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
6095   } else if (Args.hasFlag(options::OPT_fpack_struct,
6096                           options::OPT_fno_pack_struct, false)) {
6097     CmdArgs.push_back("-fpack-struct=1");
6098   }
6099
6100   // Handle -fmax-type-align=N and -fno-type-align
6101   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
6102   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
6103     if (!SkipMaxTypeAlign) {
6104       std::string MaxTypeAlignStr = "-fmax-type-align=";
6105       MaxTypeAlignStr += A->getValue();
6106       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6107     }
6108   } else if (getToolChain().getTriple().isOSDarwin()) {
6109     if (!SkipMaxTypeAlign) {
6110       std::string MaxTypeAlignStr = "-fmax-type-align=16";
6111       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6112     }
6113   }
6114
6115   // -fcommon is the default unless compiling kernel code or the target says so
6116   bool NoCommonDefault =
6117       KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
6118   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
6119                     !NoCommonDefault))
6120     CmdArgs.push_back("-fno-common");
6121
6122   // -fsigned-bitfields is default, and clang doesn't yet support
6123   // -funsigned-bitfields.
6124   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
6125                     options::OPT_funsigned_bitfields))
6126     D.Diag(diag::warn_drv_clang_unsupported)
6127         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
6128
6129   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
6130   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
6131     D.Diag(diag::err_drv_clang_unsupported)
6132         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
6133
6134   // -finput_charset=UTF-8 is default. Reject others
6135   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
6136     StringRef value = inputCharset->getValue();
6137     if (!value.equals_lower("utf-8"))
6138       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
6139                                           << value;
6140   }
6141
6142   // -fexec_charset=UTF-8 is default. Reject others
6143   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
6144     StringRef value = execCharset->getValue();
6145     if (!value.equals_lower("utf-8"))
6146       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
6147                                           << value;
6148   }
6149
6150   // -fcaret-diagnostics is default.
6151   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
6152                     options::OPT_fno_caret_diagnostics, true))
6153     CmdArgs.push_back("-fno-caret-diagnostics");
6154
6155   // -fdiagnostics-fixit-info is default, only pass non-default.
6156   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
6157                     options::OPT_fno_diagnostics_fixit_info))
6158     CmdArgs.push_back("-fno-diagnostics-fixit-info");
6159
6160   // Enable -fdiagnostics-show-option by default.
6161   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
6162                    options::OPT_fno_diagnostics_show_option))
6163     CmdArgs.push_back("-fdiagnostics-show-option");
6164
6165   if (const Arg *A =
6166           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
6167     CmdArgs.push_back("-fdiagnostics-show-category");
6168     CmdArgs.push_back(A->getValue());
6169   }
6170
6171   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
6172                    options::OPT_fno_diagnostics_show_hotness, false))
6173     CmdArgs.push_back("-fdiagnostics-show-hotness");
6174
6175   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
6176     CmdArgs.push_back("-fdiagnostics-format");
6177     CmdArgs.push_back(A->getValue());
6178   }
6179
6180   if (Arg *A = Args.getLastArg(
6181           options::OPT_fdiagnostics_show_note_include_stack,
6182           options::OPT_fno_diagnostics_show_note_include_stack)) {
6183     if (A->getOption().matches(
6184             options::OPT_fdiagnostics_show_note_include_stack))
6185       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
6186     else
6187       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
6188   }
6189
6190   // Color diagnostics are parsed by the driver directly from argv
6191   // and later re-parsed to construct this job; claim any possible
6192   // color diagnostic here to avoid warn_drv_unused_argument and
6193   // diagnose bad OPT_fdiagnostics_color_EQ values.
6194   for (Arg *A : Args) {
6195     const Option &O = A->getOption();
6196     if (!O.matches(options::OPT_fcolor_diagnostics) &&
6197         !O.matches(options::OPT_fdiagnostics_color) &&
6198         !O.matches(options::OPT_fno_color_diagnostics) &&
6199         !O.matches(options::OPT_fno_diagnostics_color) &&
6200         !O.matches(options::OPT_fdiagnostics_color_EQ))
6201       continue;
6202     if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
6203       StringRef Value(A->getValue());
6204       if (Value != "always" && Value != "never" && Value != "auto")
6205         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6206               << ("-fdiagnostics-color=" + Value).str();
6207     }
6208     A->claim();
6209   }
6210   if (D.getDiags().getDiagnosticOptions().ShowColors)
6211     CmdArgs.push_back("-fcolor-diagnostics");
6212
6213   if (Args.hasArg(options::OPT_fansi_escape_codes))
6214     CmdArgs.push_back("-fansi-escape-codes");
6215
6216   if (!Args.hasFlag(options::OPT_fshow_source_location,
6217                     options::OPT_fno_show_source_location))
6218     CmdArgs.push_back("-fno-show-source-location");
6219
6220   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
6221     CmdArgs.push_back("-fdiagnostics-absolute-paths");
6222
6223   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
6224                     true))
6225     CmdArgs.push_back("-fno-show-column");
6226
6227   if (!Args.hasFlag(options::OPT_fspell_checking,
6228                     options::OPT_fno_spell_checking))
6229     CmdArgs.push_back("-fno-spell-checking");
6230
6231   // -fno-asm-blocks is default.
6232   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
6233                    false))
6234     CmdArgs.push_back("-fasm-blocks");
6235
6236   // -fgnu-inline-asm is default.
6237   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
6238                     options::OPT_fno_gnu_inline_asm, true))
6239     CmdArgs.push_back("-fno-gnu-inline-asm");
6240
6241   // Enable vectorization per default according to the optimization level
6242   // selected. For optimization levels that want vectorization we use the alias
6243   // option to simplify the hasFlag logic.
6244   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
6245   OptSpecifier VectorizeAliasOption =
6246       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
6247   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
6248                    options::OPT_fno_vectorize, EnableVec))
6249     CmdArgs.push_back("-vectorize-loops");
6250
6251   // -fslp-vectorize is enabled based on the optimization level selected.
6252   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
6253   OptSpecifier SLPVectAliasOption =
6254       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
6255   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
6256                    options::OPT_fno_slp_vectorize, EnableSLPVec))
6257     CmdArgs.push_back("-vectorize-slp");
6258
6259   // -fno-slp-vectorize-aggressive is default.
6260   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
6261                    options::OPT_fno_slp_vectorize_aggressive, false))
6262     CmdArgs.push_back("-vectorize-slp-aggressive");
6263
6264   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
6265     A->render(Args, CmdArgs);
6266
6267   if (Arg *A = Args.getLastArg(
6268           options::OPT_fsanitize_undefined_strip_path_components_EQ))
6269     A->render(Args, CmdArgs);
6270
6271   // -fdollars-in-identifiers default varies depending on platform and
6272   // language; only pass if specified.
6273   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
6274                                options::OPT_fno_dollars_in_identifiers)) {
6275     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
6276       CmdArgs.push_back("-fdollars-in-identifiers");
6277     else
6278       CmdArgs.push_back("-fno-dollars-in-identifiers");
6279   }
6280
6281   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
6282   // practical purposes.
6283   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
6284                                options::OPT_fno_unit_at_a_time)) {
6285     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
6286       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
6287   }
6288
6289   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
6290                    options::OPT_fno_apple_pragma_pack, false))
6291     CmdArgs.push_back("-fapple-pragma-pack");
6292
6293   // le32-specific flags:
6294   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
6295   //                     by default.
6296   if (getToolChain().getArch() == llvm::Triple::le32) {
6297     CmdArgs.push_back("-fno-math-builtin");
6298   }
6299
6300   if (Args.hasFlag(options::OPT_fsave_optimization_record,
6301                    options::OPT_fno_save_optimization_record, false)) {
6302     CmdArgs.push_back("-opt-record-file");
6303
6304     const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
6305     if (A) {
6306       CmdArgs.push_back(A->getValue());
6307     } else {
6308       SmallString<128> F;
6309       if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
6310                                   Args.hasArg(options::OPT_S))) {
6311         F = Output.getFilename();
6312       } else {
6313         // Use the input filename.
6314         F = llvm::sys::path::stem(Input.getBaseInput());
6315
6316         // If we're compiling for an offload architecture (i.e. a CUDA device),
6317         // we need to make the file name for the device compilation different
6318         // from the host compilation.
6319         if (!JA.isDeviceOffloading(Action::OFK_None) &&
6320             !JA.isDeviceOffloading(Action::OFK_Host)) {
6321           llvm::sys::path::replace_extension(F, "");
6322           F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
6323                                                    Triple.normalize());
6324           F += "-";
6325           F += JA.getOffloadingArch();
6326         }
6327       }
6328
6329       llvm::sys::path::replace_extension(F, "opt.yaml");
6330       CmdArgs.push_back(Args.MakeArgString(F));
6331     }
6332   }
6333
6334 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
6335 //
6336 // FIXME: Now that PR4941 has been fixed this can be enabled.
6337 #if 0
6338   if (getToolChain().getTriple().isOSDarwin() &&
6339       (getToolChain().getArch() == llvm::Triple::arm ||
6340        getToolChain().getArch() == llvm::Triple::thumb)) {
6341     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
6342       CmdArgs.push_back("-fno-builtin-strcat");
6343     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
6344       CmdArgs.push_back("-fno-builtin-strcpy");
6345   }
6346 #endif
6347
6348   // Enable rewrite includes if the user's asked for it or if we're generating
6349   // diagnostics.
6350   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
6351   // nice to enable this when doing a crashdump for modules as well.
6352   if (Args.hasFlag(options::OPT_frewrite_includes,
6353                    options::OPT_fno_rewrite_includes, false) ||
6354       (C.isForDiagnostics() && !HaveAnyModules))
6355     CmdArgs.push_back("-frewrite-includes");
6356
6357   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
6358   if (Arg *A = Args.getLastArg(options::OPT_traditional,
6359                                options::OPT_traditional_cpp)) {
6360     if (isa<PreprocessJobAction>(JA))
6361       CmdArgs.push_back("-traditional-cpp");
6362     else
6363       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
6364   }
6365
6366   Args.AddLastArg(CmdArgs, options::OPT_dM);
6367   Args.AddLastArg(CmdArgs, options::OPT_dD);
6368
6369   // Handle serialized diagnostics.
6370   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
6371     CmdArgs.push_back("-serialize-diagnostic-file");
6372     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
6373   }
6374
6375   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
6376     CmdArgs.push_back("-fretain-comments-from-system-headers");
6377
6378   // Forward -fcomment-block-commands to -cc1.
6379   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
6380   // Forward -fparse-all-comments to -cc1.
6381   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
6382
6383   // Turn -fplugin=name.so into -load name.so
6384   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
6385     CmdArgs.push_back("-load");
6386     CmdArgs.push_back(A->getValue());
6387     A->claim();
6388   }
6389
6390   // Setup statistics file output.
6391   if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
6392     StringRef SaveStats = A->getValue();
6393
6394     SmallString<128> StatsFile;
6395     bool DoSaveStats = false;
6396     if (SaveStats == "obj") {
6397       if (Output.isFilename()) {
6398         StatsFile.assign(Output.getFilename());
6399         llvm::sys::path::remove_filename(StatsFile);
6400       }
6401       DoSaveStats = true;
6402     } else if (SaveStats == "cwd") {
6403       DoSaveStats = true;
6404     } else {
6405       D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
6406     }
6407
6408     if (DoSaveStats) {
6409       StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
6410       llvm::sys::path::append(StatsFile, BaseName);
6411       llvm::sys::path::replace_extension(StatsFile, "stats");
6412       CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
6413                                            StatsFile));
6414     }
6415   }
6416
6417   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
6418   // parser.
6419   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
6420   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
6421     A->claim();
6422
6423     // We translate this by hand to the -cc1 argument, since nightly test uses
6424     // it and developers have been trained to spell it with -mllvm.
6425     if (StringRef(A->getValue(0)) == "-disable-llvm-passes") {
6426       CmdArgs.push_back("-disable-llvm-passes");
6427     } else
6428       A->render(Args, CmdArgs);
6429   }
6430
6431   // With -save-temps, we want to save the unoptimized bitcode output from the
6432   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
6433   // by the frontend.
6434   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
6435   // has slightly different breakdown between stages.
6436   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
6437   // pristine IR generated by the frontend. Ideally, a new compile action should
6438   // be added so both IR can be captured.
6439   if (C.getDriver().isSaveTempsEnabled() &&
6440       !C.getDriver().embedBitcodeInObject() && isa<CompileJobAction>(JA))
6441     CmdArgs.push_back("-disable-llvm-passes");
6442
6443   if (Output.getType() == types::TY_Dependencies) {
6444     // Handled with other dependency code.
6445   } else if (Output.isFilename()) {
6446     CmdArgs.push_back("-o");
6447     CmdArgs.push_back(Output.getFilename());
6448   } else {
6449     assert(Output.isNothing() && "Invalid output.");
6450   }
6451
6452   addDashXForInput(Args, Input, CmdArgs);
6453
6454   if (Input.isFilename())
6455     CmdArgs.push_back(Input.getFilename());
6456   else
6457     Input.getInputArg().renderAsInput(Args, CmdArgs);
6458
6459   Args.AddAllArgs(CmdArgs, options::OPT_undef);
6460
6461   const char *Exec = getToolChain().getDriver().getClangProgramPath();
6462
6463   // Optionally embed the -cc1 level arguments into the debug info, for build
6464   // analysis.
6465   if (getToolChain().UseDwarfDebugFlags()) {
6466     ArgStringList OriginalArgs;
6467     for (const auto &Arg : Args)
6468       Arg->render(Args, OriginalArgs);
6469
6470     SmallString<256> Flags;
6471     Flags += Exec;
6472     for (const char *OriginalArg : OriginalArgs) {
6473       SmallString<128> EscapedArg;
6474       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6475       Flags += " ";
6476       Flags += EscapedArg;
6477     }
6478     CmdArgs.push_back("-dwarf-debug-flags");
6479     CmdArgs.push_back(Args.MakeArgString(Flags));
6480   }
6481
6482   // Add the split debug info name to the command lines here so we
6483   // can propagate it to the backend.
6484   bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
6485                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6486                      isa<BackendJobAction>(JA));
6487   const char *SplitDwarfOut;
6488   if (SplitDwarf) {
6489     CmdArgs.push_back("-split-dwarf-file");
6490     SplitDwarfOut = SplitDebugName(Args, Input);
6491     CmdArgs.push_back(SplitDwarfOut);
6492   }
6493
6494   // Host-side cuda compilation receives device-side outputs as Inputs[1...].
6495   // Include them with -fcuda-include-gpubinary.
6496   if (IsCuda && Inputs.size() > 1)
6497     for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
6498       CmdArgs.push_back("-fcuda-include-gpubinary");
6499       CmdArgs.push_back(I->getFilename());
6500     }
6501
6502   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
6503   // to specify the result of the compile phase on the host, so the meaningful
6504   // device declarations can be identified. Also, -fopenmp-is-device is passed
6505   // along to tell the frontend that it is generating code for a device, so that
6506   // only the relevant declarations are emitted.
6507   if (IsOpenMPDevice && Inputs.size() == 2) {
6508     CmdArgs.push_back("-fopenmp-is-device");
6509     CmdArgs.push_back("-fopenmp-host-ir-file-path");
6510     CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
6511   }
6512
6513   // For all the host OpenMP offloading compile jobs we need to pass the targets
6514   // information using -fopenmp-targets= option.
6515   if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
6516     SmallString<128> TargetInfo("-fopenmp-targets=");
6517
6518     Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
6519     assert(Tgts && Tgts->getNumValues() &&
6520            "OpenMP offloading has to have targets specified.");
6521     for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
6522       if (i)
6523         TargetInfo += ',';
6524       // We need to get the string from the triple because it may be not exactly
6525       // the same as the one we get directly from the arguments.
6526       llvm::Triple T(Tgts->getValue(i));
6527       TargetInfo += T.getTriple();
6528     }
6529     CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
6530   }
6531
6532   bool WholeProgramVTables =
6533       Args.hasFlag(options::OPT_fwhole_program_vtables,
6534                    options::OPT_fno_whole_program_vtables, false);
6535   if (WholeProgramVTables) {
6536     if (!D.isUsingLTO())
6537       D.Diag(diag::err_drv_argument_only_allowed_with)
6538           << "-fwhole-program-vtables"
6539           << "-flto";
6540     CmdArgs.push_back("-fwhole-program-vtables");
6541   }
6542
6543   // Finally add the compile command to the compilation.
6544   if (Args.hasArg(options::OPT__SLASH_fallback) &&
6545       Output.getType() == types::TY_Object &&
6546       (InputType == types::TY_C || InputType == types::TY_CXX)) {
6547     auto CLCommand =
6548         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
6549     C.addCommand(llvm::make_unique<FallbackCommand>(
6550         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
6551   } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
6552              isa<PrecompileJobAction>(JA)) {
6553     // In /fallback builds, run the main compilation even if the pch generation
6554     // fails, so that the main compilation's fallback to cl.exe runs.
6555     C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
6556                                                         CmdArgs, Inputs));
6557   } else {
6558     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6559   }
6560
6561   // Handle the debug info splitting at object creation time if we're
6562   // creating an object.
6563   // TODO: Currently only works on linux with newer objcopy.
6564   if (SplitDwarf && Output.getType() == types::TY_Object)
6565     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
6566
6567   if (Arg *A = Args.getLastArg(options::OPT_pg))
6568     if (Args.hasArg(options::OPT_fomit_frame_pointer))
6569       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6570                                                       << A->getAsString(Args);
6571
6572   // Claim some arguments which clang supports automatically.
6573
6574   // -fpch-preprocess is used with gcc to add a special marker in the output to
6575   // include the PCH file. Clang's PTH solution is completely transparent, so we
6576   // do not need to deal with it at all.
6577   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6578
6579   // Claim some arguments which clang doesn't support, but we don't
6580   // care to warn the user about.
6581   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6582   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6583
6584   // Disable warnings for clang -E -emit-llvm foo.c
6585   Args.ClaimAllArgs(options::OPT_emit_llvm);
6586 }
6587
6588 /// Add options related to the Objective-C runtime/ABI.
6589 ///
6590 /// Returns true if the runtime is non-fragile.
6591 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6592                                       ArgStringList &cmdArgs,
6593                                       RewriteKind rewriteKind) const {
6594   // Look for the controlling runtime option.
6595   Arg *runtimeArg =
6596       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6597                       options::OPT_fobjc_runtime_EQ);
6598
6599   // Just forward -fobjc-runtime= to the frontend.  This supercedes
6600   // options about fragility.
6601   if (runtimeArg &&
6602       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6603     ObjCRuntime runtime;
6604     StringRef value = runtimeArg->getValue();
6605     if (runtime.tryParse(value)) {
6606       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6607           << value;
6608     }
6609
6610     runtimeArg->render(args, cmdArgs);
6611     return runtime;
6612   }
6613
6614   // Otherwise, we'll need the ABI "version".  Version numbers are
6615   // slightly confusing for historical reasons:
6616   //   1 - Traditional "fragile" ABI
6617   //   2 - Non-fragile ABI, version 1
6618   //   3 - Non-fragile ABI, version 2
6619   unsigned objcABIVersion = 1;
6620   // If -fobjc-abi-version= is present, use that to set the version.
6621   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6622     StringRef value = abiArg->getValue();
6623     if (value == "1")
6624       objcABIVersion = 1;
6625     else if (value == "2")
6626       objcABIVersion = 2;
6627     else if (value == "3")
6628       objcABIVersion = 3;
6629     else
6630       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6631   } else {
6632     // Otherwise, determine if we are using the non-fragile ABI.
6633     bool nonFragileABIIsDefault =
6634         (rewriteKind == RK_NonFragile ||
6635          (rewriteKind == RK_None &&
6636           getToolChain().IsObjCNonFragileABIDefault()));
6637     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6638                      options::OPT_fno_objc_nonfragile_abi,
6639                      nonFragileABIIsDefault)) {
6640 // Determine the non-fragile ABI version to use.
6641 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6642       unsigned nonFragileABIVersion = 1;
6643 #else
6644       unsigned nonFragileABIVersion = 2;
6645 #endif
6646
6647       if (Arg *abiArg =
6648               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6649         StringRef value = abiArg->getValue();
6650         if (value == "1")
6651           nonFragileABIVersion = 1;
6652         else if (value == "2")
6653           nonFragileABIVersion = 2;
6654         else
6655           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6656               << value;
6657       }
6658
6659       objcABIVersion = 1 + nonFragileABIVersion;
6660     } else {
6661       objcABIVersion = 1;
6662     }
6663   }
6664
6665   // We don't actually care about the ABI version other than whether
6666   // it's non-fragile.
6667   bool isNonFragile = objcABIVersion != 1;
6668
6669   // If we have no runtime argument, ask the toolchain for its default runtime.
6670   // However, the rewriter only really supports the Mac runtime, so assume that.
6671   ObjCRuntime runtime;
6672   if (!runtimeArg) {
6673     switch (rewriteKind) {
6674     case RK_None:
6675       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6676       break;
6677     case RK_Fragile:
6678       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6679       break;
6680     case RK_NonFragile:
6681       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6682       break;
6683     }
6684
6685     // -fnext-runtime
6686   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6687     // On Darwin, make this use the default behavior for the toolchain.
6688     if (getToolChain().getTriple().isOSDarwin()) {
6689       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6690
6691       // Otherwise, build for a generic macosx port.
6692     } else {
6693       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6694     }
6695
6696     // -fgnu-runtime
6697   } else {
6698     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6699     // Legacy behaviour is to target the gnustep runtime if we are in
6700     // non-fragile mode or the GCC runtime in fragile mode.
6701     if (isNonFragile)
6702       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
6703     else
6704       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6705   }
6706
6707   cmdArgs.push_back(
6708       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6709   return runtime;
6710 }
6711
6712 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6713   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6714   I += HaveDash;
6715   return !HaveDash;
6716 }
6717
6718 namespace {
6719 struct EHFlags {
6720   bool Synch = false;
6721   bool Asynch = false;
6722   bool NoUnwindC = false;
6723 };
6724 } // end anonymous namespace
6725
6726 /// /EH controls whether to run destructor cleanups when exceptions are
6727 /// thrown.  There are three modifiers:
6728 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
6729 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
6730 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
6731 /// - c: Assume that extern "C" functions are implicitly nounwind.
6732 /// The default is /EHs-c-, meaning cleanups are disabled.
6733 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
6734   EHFlags EH;
6735
6736   std::vector<std::string> EHArgs =
6737       Args.getAllArgValues(options::OPT__SLASH_EH);
6738   for (auto EHVal : EHArgs) {
6739     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
6740       switch (EHVal[I]) {
6741       case 'a':
6742         EH.Asynch = maybeConsumeDash(EHVal, I);
6743         if (EH.Asynch)
6744           EH.Synch = false;
6745         continue;
6746       case 'c':
6747         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
6748         continue;
6749       case 's':
6750         EH.Synch = maybeConsumeDash(EHVal, I);
6751         if (EH.Synch)
6752           EH.Asynch = false;
6753         continue;
6754       default:
6755         break;
6756       }
6757       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
6758       break;
6759     }
6760   }
6761   // The /GX, /GX- flags are only processed if there are not /EH flags.
6762   // The default is that /GX is not specified.
6763   if (EHArgs.empty() &&
6764       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
6765                    /*default=*/false)) {
6766     EH.Synch = true;
6767     EH.NoUnwindC = true;
6768   }
6769
6770   return EH;
6771 }
6772
6773 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
6774                            ArgStringList &CmdArgs,
6775                            codegenoptions::DebugInfoKind *DebugInfoKind,
6776                            bool *EmitCodeView) const {
6777   unsigned RTOptionID = options::OPT__SLASH_MT;
6778
6779   if (Args.hasArg(options::OPT__SLASH_LDd))
6780     // The /LDd option implies /MTd. The dependent lib part can be overridden,
6781     // but defining _DEBUG is sticky.
6782     RTOptionID = options::OPT__SLASH_MTd;
6783
6784   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
6785     RTOptionID = A->getOption().getID();
6786
6787   StringRef FlagForCRT;
6788   switch (RTOptionID) {
6789   case options::OPT__SLASH_MD:
6790     if (Args.hasArg(options::OPT__SLASH_LDd))
6791       CmdArgs.push_back("-D_DEBUG");
6792     CmdArgs.push_back("-D_MT");
6793     CmdArgs.push_back("-D_DLL");
6794     FlagForCRT = "--dependent-lib=msvcrt";
6795     break;
6796   case options::OPT__SLASH_MDd:
6797     CmdArgs.push_back("-D_DEBUG");
6798     CmdArgs.push_back("-D_MT");
6799     CmdArgs.push_back("-D_DLL");
6800     FlagForCRT = "--dependent-lib=msvcrtd";
6801     break;
6802   case options::OPT__SLASH_MT:
6803     if (Args.hasArg(options::OPT__SLASH_LDd))
6804       CmdArgs.push_back("-D_DEBUG");
6805     CmdArgs.push_back("-D_MT");
6806     CmdArgs.push_back("-flto-visibility-public-std");
6807     FlagForCRT = "--dependent-lib=libcmt";
6808     break;
6809   case options::OPT__SLASH_MTd:
6810     CmdArgs.push_back("-D_DEBUG");
6811     CmdArgs.push_back("-D_MT");
6812     CmdArgs.push_back("-flto-visibility-public-std");
6813     FlagForCRT = "--dependent-lib=libcmtd";
6814     break;
6815   default:
6816     llvm_unreachable("Unexpected option ID.");
6817   }
6818
6819   if (Args.hasArg(options::OPT__SLASH_Zl)) {
6820     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
6821   } else {
6822     CmdArgs.push_back(FlagForCRT.data());
6823
6824     // This provides POSIX compatibility (maps 'open' to '_open'), which most
6825     // users want.  The /Za flag to cl.exe turns this off, but it's not
6826     // implemented in clang.
6827     CmdArgs.push_back("--dependent-lib=oldnames");
6828   }
6829
6830   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
6831   // would produce interleaved output, so ignore /showIncludes in such cases.
6832   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
6833     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
6834       A->render(Args, CmdArgs);
6835
6836   // This controls whether or not we emit RTTI data for polymorphic types.
6837   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
6838                    /*default=*/false))
6839     CmdArgs.push_back("-fno-rtti-data");
6840
6841   // This controls whether or not we emit stack-protector instrumentation.
6842   // In MSVC, Buffer Security Check (/GS) is on by default.
6843   if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
6844                    /*default=*/true)) {
6845     CmdArgs.push_back("-stack-protector");
6846     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
6847   }
6848
6849   // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
6850   if (Arg *DebugInfoArg =
6851           Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
6852                           options::OPT_gline_tables_only)) {
6853     *EmitCodeView = true;
6854     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
6855       *DebugInfoKind = codegenoptions::LimitedDebugInfo;
6856     else
6857       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
6858     CmdArgs.push_back("-gcodeview");
6859   } else {
6860     *EmitCodeView = false;
6861   }
6862
6863   const Driver &D = getToolChain().getDriver();
6864   EHFlags EH = parseClangCLEHFlags(D, Args);
6865   if (EH.Synch || EH.Asynch) {
6866     if (types::isCXX(InputType))
6867       CmdArgs.push_back("-fcxx-exceptions");
6868     CmdArgs.push_back("-fexceptions");
6869   }
6870   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
6871     CmdArgs.push_back("-fexternc-nounwind");
6872
6873   // /EP should expand to -E -P.
6874   if (Args.hasArg(options::OPT__SLASH_EP)) {
6875     CmdArgs.push_back("-E");
6876     CmdArgs.push_back("-P");
6877   }
6878
6879   unsigned VolatileOptionID;
6880   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
6881       getToolChain().getArch() == llvm::Triple::x86)
6882     VolatileOptionID = options::OPT__SLASH_volatile_ms;
6883   else
6884     VolatileOptionID = options::OPT__SLASH_volatile_iso;
6885
6886   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
6887     VolatileOptionID = A->getOption().getID();
6888
6889   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
6890     CmdArgs.push_back("-fms-volatile");
6891
6892   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
6893   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
6894   if (MostGeneralArg && BestCaseArg)
6895     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6896         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
6897
6898   if (MostGeneralArg) {
6899     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
6900     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
6901     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
6902
6903     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
6904     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
6905     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
6906       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6907           << FirstConflict->getAsString(Args)
6908           << SecondConflict->getAsString(Args);
6909
6910     if (SingleArg)
6911       CmdArgs.push_back("-fms-memptr-rep=single");
6912     else if (MultipleArg)
6913       CmdArgs.push_back("-fms-memptr-rep=multiple");
6914     else
6915       CmdArgs.push_back("-fms-memptr-rep=virtual");
6916   }
6917
6918   if (Args.getLastArg(options::OPT__SLASH_Gd))
6919      CmdArgs.push_back("-fdefault-calling-conv=cdecl");
6920   else if (Args.getLastArg(options::OPT__SLASH_Gr))
6921      CmdArgs.push_back("-fdefault-calling-conv=fastcall");
6922   else if (Args.getLastArg(options::OPT__SLASH_Gz))
6923      CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6924   else if (Args.getLastArg(options::OPT__SLASH_Gv))
6925      CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
6926
6927   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
6928     A->render(Args, CmdArgs);
6929
6930   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6931     CmdArgs.push_back("-fdiagnostics-format");
6932     if (Args.hasArg(options::OPT__SLASH_fallback))
6933       CmdArgs.push_back("msvc-fallback");
6934     else
6935       CmdArgs.push_back("msvc");
6936   }
6937 }
6938
6939 visualstudio::Compiler *Clang::getCLFallback() const {
6940   if (!CLFallback)
6941     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6942   return CLFallback.get();
6943 }
6944
6945 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6946                                 ArgStringList &CmdArgs) const {
6947   StringRef CPUName;
6948   StringRef ABIName;
6949   const llvm::Triple &Triple = getToolChain().getTriple();
6950   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6951
6952   CmdArgs.push_back("-target-abi");
6953   CmdArgs.push_back(ABIName.data());
6954 }
6955
6956 void ClangAs::AddX86TargetArgs(const ArgList &Args,
6957                                ArgStringList &CmdArgs) const {
6958   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
6959     StringRef Value = A->getValue();
6960     if (Value == "intel" || Value == "att") {
6961       CmdArgs.push_back("-mllvm");
6962       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
6963     } else {
6964       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6965           << A->getOption().getName() << Value;
6966     }
6967   }
6968 }
6969
6970 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6971                            const InputInfo &Output, const InputInfoList &Inputs,
6972                            const ArgList &Args,
6973                            const char *LinkingOutput) const {
6974   ArgStringList CmdArgs;
6975
6976   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6977   const InputInfo &Input = Inputs[0];
6978
6979   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
6980   const std::string &TripleStr = Triple.getTriple();
6981
6982   // Don't warn about "clang -w -c foo.s"
6983   Args.ClaimAllArgs(options::OPT_w);
6984   // and "clang -emit-llvm -c foo.s"
6985   Args.ClaimAllArgs(options::OPT_emit_llvm);
6986
6987   claimNoWarnArgs(Args);
6988
6989   // Invoke ourselves in -cc1as mode.
6990   //
6991   // FIXME: Implement custom jobs for internal actions.
6992   CmdArgs.push_back("-cc1as");
6993
6994   // Add the "effective" target triple.
6995   CmdArgs.push_back("-triple");
6996   CmdArgs.push_back(Args.MakeArgString(TripleStr));
6997
6998   // Set the output mode, we currently only expect to be used as a real
6999   // assembler.
7000   CmdArgs.push_back("-filetype");
7001   CmdArgs.push_back("obj");
7002
7003   // Set the main file name, so that debug info works even with
7004   // -save-temps or preprocessed assembly.
7005   CmdArgs.push_back("-main-file-name");
7006   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
7007
7008   // Add the target cpu
7009   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
7010   if (!CPU.empty()) {
7011     CmdArgs.push_back("-target-cpu");
7012     CmdArgs.push_back(Args.MakeArgString(CPU));
7013   }
7014
7015   // Add the target features
7016   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
7017
7018   // Ignore explicit -force_cpusubtype_ALL option.
7019   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
7020
7021   // Pass along any -I options so we get proper .include search paths.
7022   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
7023
7024   // Determine the original source input.
7025   const Action *SourceAction = &JA;
7026   while (SourceAction->getKind() != Action::InputClass) {
7027     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7028     SourceAction = SourceAction->getInputs()[0];
7029   }
7030
7031   // Forward -g and handle debug info related flags, assuming we are dealing
7032   // with an actual assembly file.
7033   bool WantDebug = false;
7034   unsigned DwarfVersion = 0;
7035   Args.ClaimAllArgs(options::OPT_g_Group);
7036   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
7037     WantDebug = !A->getOption().matches(options::OPT_g0) &&
7038                 !A->getOption().matches(options::OPT_ggdb0);
7039     if (WantDebug)
7040       DwarfVersion = DwarfVersionNum(A->getSpelling());
7041   }
7042   if (DwarfVersion == 0)
7043     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
7044
7045   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
7046
7047   if (SourceAction->getType() == types::TY_Asm ||
7048       SourceAction->getType() == types::TY_PP_Asm) {
7049     // You might think that it would be ok to set DebugInfoKind outside of
7050     // the guard for source type, however there is a test which asserts
7051     // that some assembler invocation receives no -debug-info-kind,
7052     // and it's not clear whether that test is just overly restrictive.
7053     DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
7054                                : codegenoptions::NoDebugInfo);
7055     // Add the -fdebug-compilation-dir flag if needed.
7056     addDebugCompDirArg(Args, CmdArgs);
7057
7058     // Set the AT_producer to the clang version when using the integrated
7059     // assembler on assembly source files.
7060     CmdArgs.push_back("-dwarf-debug-producer");
7061     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
7062
7063     // And pass along -I options
7064     Args.AddAllArgs(CmdArgs, options::OPT_I);
7065   }
7066   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
7067                           llvm::DebuggerKind::Default);
7068
7069   // Handle -fPIC et al -- the relocation-model affects the assembler
7070   // for some targets.
7071   llvm::Reloc::Model RelocationModel;
7072   unsigned PICLevel;
7073   bool IsPIE;
7074   std::tie(RelocationModel, PICLevel, IsPIE) =
7075       ParsePICArgs(getToolChain(), Args);
7076
7077   const char *RMName = RelocationModelName(RelocationModel);
7078   if (RMName) {
7079     CmdArgs.push_back("-mrelocation-model");
7080     CmdArgs.push_back(RMName);
7081   }
7082
7083   // Optionally embed the -cc1as level arguments into the debug info, for build
7084   // analysis.
7085   if (getToolChain().UseDwarfDebugFlags()) {
7086     ArgStringList OriginalArgs;
7087     for (const auto &Arg : Args)
7088       Arg->render(Args, OriginalArgs);
7089
7090     SmallString<256> Flags;
7091     const char *Exec = getToolChain().getDriver().getClangProgramPath();
7092     Flags += Exec;
7093     for (const char *OriginalArg : OriginalArgs) {
7094       SmallString<128> EscapedArg;
7095       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7096       Flags += " ";
7097       Flags += EscapedArg;
7098     }
7099     CmdArgs.push_back("-dwarf-debug-flags");
7100     CmdArgs.push_back(Args.MakeArgString(Flags));
7101   }
7102
7103   // FIXME: Add -static support, once we have it.
7104
7105   // Add target specific flags.
7106   switch (getToolChain().getArch()) {
7107   default:
7108     break;
7109
7110   case llvm::Triple::mips:
7111   case llvm::Triple::mipsel:
7112   case llvm::Triple::mips64:
7113   case llvm::Triple::mips64el:
7114     AddMIPSTargetArgs(Args, CmdArgs);
7115     break;
7116
7117   case llvm::Triple::x86:
7118   case llvm::Triple::x86_64:
7119     AddX86TargetArgs(Args, CmdArgs);
7120     break;
7121   }
7122
7123   // Consume all the warning flags. Usually this would be handled more
7124   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
7125   // doesn't handle that so rather than warning about unused flags that are
7126   // actually used, we'll lie by omission instead.
7127   // FIXME: Stop lying and consume only the appropriate driver flags
7128   Args.ClaimAllArgs(options::OPT_W_Group);
7129
7130   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
7131                                     getToolChain().getDriver());
7132
7133   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
7134
7135   assert(Output.isFilename() && "Unexpected lipo output.");
7136   CmdArgs.push_back("-o");
7137   CmdArgs.push_back(Output.getFilename());
7138
7139   assert(Input.isFilename() && "Invalid input.");
7140   CmdArgs.push_back(Input.getFilename());
7141
7142   const char *Exec = getToolChain().getDriver().getClangProgramPath();
7143   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7144
7145   // Handle the debug info splitting at object creation time if we're
7146   // creating an object.
7147   // TODO: Currently only works on linux with newer objcopy.
7148   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7149       getToolChain().getTriple().isOSLinux())
7150     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7151                    SplitDebugName(Args, Input));
7152 }
7153
7154 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
7155                                   const InputInfo &Output,
7156                                   const InputInfoList &Inputs,
7157                                   const llvm::opt::ArgList &TCArgs,
7158                                   const char *LinkingOutput) const {
7159   // The version with only one output is expected to refer to a bundling job.
7160   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
7161
7162   // The bundling command looks like this:
7163   // clang-offload-bundler -type=bc
7164   //   -targets=host-triple,openmp-triple1,openmp-triple2
7165   //   -outputs=input_file
7166   //   -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
7167
7168   ArgStringList CmdArgs;
7169
7170   // Get the type.
7171   CmdArgs.push_back(TCArgs.MakeArgString(
7172       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
7173
7174   assert(JA.getInputs().size() == Inputs.size() &&
7175          "Not have inputs for all dependence actions??");
7176
7177   // Get the targets.
7178   SmallString<128> Triples;
7179   Triples += "-targets=";
7180   for (unsigned I = 0; I < Inputs.size(); ++I) {
7181     if (I)
7182       Triples += ',';
7183
7184     Action::OffloadKind CurKind = Action::OFK_Host;
7185     const ToolChain *CurTC = &getToolChain();
7186     const Action *CurDep = JA.getInputs()[I];
7187
7188     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
7189       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
7190         CurKind = A->getOffloadingDeviceKind();
7191         CurTC = TC;
7192       });
7193     }
7194     Triples += Action::GetOffloadKindName(CurKind);
7195     Triples += '-';
7196     Triples += CurTC->getTriple().normalize();
7197   }
7198   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
7199
7200   // Get bundled file command.
7201   CmdArgs.push_back(
7202       TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
7203
7204   // Get unbundled files command.
7205   SmallString<128> UB;
7206   UB += "-inputs=";
7207   for (unsigned I = 0; I < Inputs.size(); ++I) {
7208     if (I)
7209       UB += ',';
7210     UB += Inputs[I].getFilename();
7211   }
7212   CmdArgs.push_back(TCArgs.MakeArgString(UB));
7213
7214   // All the inputs are encoded as commands.
7215   C.addCommand(llvm::make_unique<Command>(
7216       JA, *this,
7217       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7218       CmdArgs, None));
7219 }
7220
7221 void OffloadBundler::ConstructJobMultipleOutputs(
7222     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
7223     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
7224     const char *LinkingOutput) const {
7225   // The version with multiple outputs is expected to refer to a unbundling job.
7226   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
7227
7228   // The unbundling command looks like this:
7229   // clang-offload-bundler -type=bc
7230   //   -targets=host-triple,openmp-triple1,openmp-triple2
7231   //   -inputs=input_file
7232   //   -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
7233   //   -unbundle
7234
7235   ArgStringList CmdArgs;
7236
7237   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
7238   InputInfo Input = Inputs.front();
7239
7240   // Get the type.
7241   CmdArgs.push_back(TCArgs.MakeArgString(
7242       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
7243
7244   // Get the targets.
7245   SmallString<128> Triples;
7246   Triples += "-targets=";
7247   auto DepInfo = UA.getDependentActionsInfo();
7248   for (unsigned I = 0; I < DepInfo.size(); ++I) {
7249     if (I)
7250       Triples += ',';
7251
7252     auto &Dep = DepInfo[I];
7253     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
7254     Triples += '-';
7255     Triples += Dep.DependentToolChain->getTriple().normalize();
7256   }
7257
7258   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
7259
7260   // Get bundled file command.
7261   CmdArgs.push_back(
7262       TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
7263
7264   // Get unbundled files command.
7265   SmallString<128> UB;
7266   UB += "-outputs=";
7267   for (unsigned I = 0; I < Outputs.size(); ++I) {
7268     if (I)
7269       UB += ',';
7270     UB += Outputs[I].getFilename();
7271   }
7272   CmdArgs.push_back(TCArgs.MakeArgString(UB));
7273   CmdArgs.push_back("-unbundle");
7274
7275   // All the inputs are encoded as commands.
7276   C.addCommand(llvm::make_unique<Command>(
7277       JA, *this,
7278       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7279       CmdArgs, None));
7280 }
7281
7282 void GnuTool::anchor() {}
7283
7284 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
7285                                const InputInfo &Output,
7286                                const InputInfoList &Inputs, const ArgList &Args,
7287                                const char *LinkingOutput) const {
7288   const Driver &D = getToolChain().getDriver();
7289   ArgStringList CmdArgs;
7290
7291   for (const auto &A : Args) {
7292     if (forwardToGCC(A->getOption())) {
7293       // It is unfortunate that we have to claim here, as this means
7294       // we will basically never report anything interesting for
7295       // platforms using a generic gcc, even if we are just using gcc
7296       // to get to the assembler.
7297       A->claim();
7298
7299       // Don't forward any -g arguments to assembly steps.
7300       if (isa<AssembleJobAction>(JA) &&
7301           A->getOption().matches(options::OPT_g_Group))
7302         continue;
7303
7304       // Don't forward any -W arguments to assembly and link steps.
7305       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
7306           A->getOption().matches(options::OPT_W_Group))
7307         continue;
7308
7309       A->render(Args, CmdArgs);
7310     }
7311   }
7312
7313   RenderExtraToolArgs(JA, CmdArgs);
7314
7315   // If using a driver driver, force the arch.
7316   if (getToolChain().getTriple().isOSDarwin()) {
7317     CmdArgs.push_back("-arch");
7318     CmdArgs.push_back(
7319         Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
7320   }
7321
7322   // Try to force gcc to match the tool chain we want, if we recognize
7323   // the arch.
7324   //
7325   // FIXME: The triple class should directly provide the information we want
7326   // here.
7327   switch (getToolChain().getArch()) {
7328   default:
7329     break;
7330   case llvm::Triple::x86:
7331   case llvm::Triple::ppc:
7332     CmdArgs.push_back("-m32");
7333     break;
7334   case llvm::Triple::x86_64:
7335   case llvm::Triple::ppc64:
7336   case llvm::Triple::ppc64le:
7337     CmdArgs.push_back("-m64");
7338     break;
7339   case llvm::Triple::sparcel:
7340     CmdArgs.push_back("-EL");
7341     break;
7342   }
7343
7344   if (Output.isFilename()) {
7345     CmdArgs.push_back("-o");
7346     CmdArgs.push_back(Output.getFilename());
7347   } else {
7348     assert(Output.isNothing() && "Unexpected output");
7349     CmdArgs.push_back("-fsyntax-only");
7350   }
7351
7352   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7353
7354   // Only pass -x if gcc will understand it; otherwise hope gcc
7355   // understands the suffix correctly. The main use case this would go
7356   // wrong in is for linker inputs if they happened to have an odd
7357   // suffix; really the only way to get this to happen is a command
7358   // like '-x foobar a.c' which will treat a.c like a linker input.
7359   //
7360   // FIXME: For the linker case specifically, can we safely convert
7361   // inputs into '-Wl,' options?
7362   for (const auto &II : Inputs) {
7363     // Don't try to pass LLVM or AST inputs to a generic gcc.
7364     if (types::isLLVMIR(II.getType()))
7365       D.Diag(diag::err_drv_no_linker_llvm_support)
7366           << getToolChain().getTripleString();
7367     else if (II.getType() == types::TY_AST)
7368       D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
7369     else if (II.getType() == types::TY_ModuleFile)
7370       D.Diag(diag::err_drv_no_module_support)
7371           << getToolChain().getTripleString();
7372
7373     if (types::canTypeBeUserSpecified(II.getType())) {
7374       CmdArgs.push_back("-x");
7375       CmdArgs.push_back(types::getTypeName(II.getType()));
7376     }
7377
7378     if (II.isFilename())
7379       CmdArgs.push_back(II.getFilename());
7380     else {
7381       const Arg &A = II.getInputArg();
7382
7383       // Reverse translate some rewritten options.
7384       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
7385         CmdArgs.push_back("-lstdc++");
7386         continue;
7387       }
7388
7389       // Don't render as input, we need gcc to do the translations.
7390       A.render(Args, CmdArgs);
7391     }
7392   }
7393
7394   const std::string &customGCCName = D.getCCCGenericGCCName();
7395   const char *GCCName;
7396   if (!customGCCName.empty())
7397     GCCName = customGCCName.c_str();
7398   else if (D.CCCIsCXX()) {
7399     GCCName = "g++";
7400   } else
7401     GCCName = "gcc";
7402
7403   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
7404   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7405 }
7406
7407 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
7408                                             ArgStringList &CmdArgs) const {
7409   CmdArgs.push_back("-E");
7410 }
7411
7412 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
7413                                         ArgStringList &CmdArgs) const {
7414   const Driver &D = getToolChain().getDriver();
7415
7416   switch (JA.getType()) {
7417   // If -flto, etc. are present then make sure not to force assembly output.
7418   case types::TY_LLVM_IR:
7419   case types::TY_LTO_IR:
7420   case types::TY_LLVM_BC:
7421   case types::TY_LTO_BC:
7422     CmdArgs.push_back("-c");
7423     break;
7424   // We assume we've got an "integrated" assembler in that gcc will produce an
7425   // object file itself.
7426   case types::TY_Object:
7427     CmdArgs.push_back("-c");
7428     break;
7429   case types::TY_PP_Asm:
7430     CmdArgs.push_back("-S");
7431     break;
7432   case types::TY_Nothing:
7433     CmdArgs.push_back("-fsyntax-only");
7434     break;
7435   default:
7436     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
7437   }
7438 }
7439
7440 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
7441                                       ArgStringList &CmdArgs) const {
7442   // The types are (hopefully) good enough.
7443 }
7444
7445 // Hexagon tools start.
7446 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
7447                                              ArgStringList &CmdArgs) const {
7448 }
7449
7450 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7451                                       const InputInfo &Output,
7452                                       const InputInfoList &Inputs,
7453                                       const ArgList &Args,
7454                                       const char *LinkingOutput) const {
7455   claimNoWarnArgs(Args);
7456
7457   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7458   const Driver &D = HTC.getDriver();
7459   ArgStringList CmdArgs;
7460
7461   std::string MArchString = "-march=hexagon";
7462   CmdArgs.push_back(Args.MakeArgString(MArchString));
7463
7464   RenderExtraToolArgs(JA, CmdArgs);
7465
7466   std::string AsName = "hexagon-llvm-mc";
7467   std::string MCpuString = "-mcpu=hexagon" +
7468         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
7469   CmdArgs.push_back("-filetype=obj");
7470   CmdArgs.push_back(Args.MakeArgString(MCpuString));
7471
7472   if (Output.isFilename()) {
7473     CmdArgs.push_back("-o");
7474     CmdArgs.push_back(Output.getFilename());
7475   } else {
7476     assert(Output.isNothing() && "Unexpected output");
7477     CmdArgs.push_back("-fsyntax-only");
7478   }
7479
7480   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
7481     std::string N = llvm::utostr(G.getValue());
7482     CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
7483   }
7484
7485   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7486
7487   // Only pass -x if gcc will understand it; otherwise hope gcc
7488   // understands the suffix correctly. The main use case this would go
7489   // wrong in is for linker inputs if they happened to have an odd
7490   // suffix; really the only way to get this to happen is a command
7491   // like '-x foobar a.c' which will treat a.c like a linker input.
7492   //
7493   // FIXME: For the linker case specifically, can we safely convert
7494   // inputs into '-Wl,' options?
7495   for (const auto &II : Inputs) {
7496     // Don't try to pass LLVM or AST inputs to a generic gcc.
7497     if (types::isLLVMIR(II.getType()))
7498       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
7499           << HTC.getTripleString();
7500     else if (II.getType() == types::TY_AST)
7501       D.Diag(clang::diag::err_drv_no_ast_support)
7502           << HTC.getTripleString();
7503     else if (II.getType() == types::TY_ModuleFile)
7504       D.Diag(diag::err_drv_no_module_support)
7505           << HTC.getTripleString();
7506
7507     if (II.isFilename())
7508       CmdArgs.push_back(II.getFilename());
7509     else
7510       // Don't render as input, we need gcc to do the translations.
7511       // FIXME: What is this?
7512       II.getInputArg().render(Args, CmdArgs);
7513   }
7514
7515   auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
7516   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7517 }
7518
7519 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
7520                                           ArgStringList &CmdArgs) const {
7521 }
7522
7523 static void
7524 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
7525                          const toolchains::HexagonToolChain &HTC,
7526                          const InputInfo &Output, const InputInfoList &Inputs,
7527                          const ArgList &Args, ArgStringList &CmdArgs,
7528                          const char *LinkingOutput) {
7529
7530   const Driver &D = HTC.getDriver();
7531
7532   //----------------------------------------------------------------------------
7533   //
7534   //----------------------------------------------------------------------------
7535   bool IsStatic = Args.hasArg(options::OPT_static);
7536   bool IsShared = Args.hasArg(options::OPT_shared);
7537   bool IsPIE = Args.hasArg(options::OPT_pie);
7538   bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
7539   bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
7540   bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
7541   bool UseG0 = false;
7542   bool UseShared = IsShared && !IsStatic;
7543
7544   //----------------------------------------------------------------------------
7545   // Silence warnings for various options
7546   //----------------------------------------------------------------------------
7547   Args.ClaimAllArgs(options::OPT_g_Group);
7548   Args.ClaimAllArgs(options::OPT_emit_llvm);
7549   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
7550                                      // handled somewhere else.
7551   Args.ClaimAllArgs(options::OPT_static_libgcc);
7552
7553   //----------------------------------------------------------------------------
7554   //
7555   //----------------------------------------------------------------------------
7556   if (Args.hasArg(options::OPT_s))
7557     CmdArgs.push_back("-s");
7558
7559   if (Args.hasArg(options::OPT_r))
7560     CmdArgs.push_back("-r");
7561
7562   for (const auto &Opt : HTC.ExtraOpts)
7563     CmdArgs.push_back(Opt.c_str());
7564
7565   CmdArgs.push_back("-march=hexagon");
7566   std::string CpuVer =
7567         toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
7568   std::string MCpuString = "-mcpu=hexagon" + CpuVer;
7569   CmdArgs.push_back(Args.MakeArgString(MCpuString));
7570
7571   if (IsShared) {
7572     CmdArgs.push_back("-shared");
7573     // The following should be the default, but doing as hexagon-gcc does.
7574     CmdArgs.push_back("-call_shared");
7575   }
7576
7577   if (IsStatic)
7578     CmdArgs.push_back("-static");
7579
7580   if (IsPIE && !IsShared)
7581     CmdArgs.push_back("-pie");
7582
7583   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
7584     std::string N = llvm::utostr(G.getValue());
7585     CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
7586     UseG0 = G.getValue() == 0;
7587   }
7588
7589   //----------------------------------------------------------------------------
7590   //
7591   //----------------------------------------------------------------------------
7592   CmdArgs.push_back("-o");
7593   CmdArgs.push_back(Output.getFilename());
7594
7595   //----------------------------------------------------------------------------
7596   // moslib
7597   //----------------------------------------------------------------------------
7598   std::vector<std::string> OsLibs;
7599   bool HasStandalone = false;
7600
7601   for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
7602     A->claim();
7603     OsLibs.emplace_back(A->getValue());
7604     HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
7605   }
7606   if (OsLibs.empty()) {
7607     OsLibs.push_back("standalone");
7608     HasStandalone = true;
7609   }
7610
7611   //----------------------------------------------------------------------------
7612   // Start Files
7613   //----------------------------------------------------------------------------
7614   const std::string MCpuSuffix = "/" + CpuVer;
7615   const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
7616   const std::string RootDir =
7617       HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
7618   const std::string StartSubDir =
7619       "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
7620
7621   auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
7622                       const char *Name) -> std::string {
7623     std::string RelName = SubDir + Name;
7624     std::string P = HTC.GetFilePath(RelName.c_str());
7625     if (llvm::sys::fs::exists(P))
7626       return P;
7627     return RootDir + RelName;
7628   };
7629
7630   if (IncStdLib && IncStartFiles) {
7631     if (!IsShared) {
7632       if (HasStandalone) {
7633         std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
7634         CmdArgs.push_back(Args.MakeArgString(Crt0SA));
7635       }
7636       std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
7637       CmdArgs.push_back(Args.MakeArgString(Crt0));
7638     }
7639     std::string Init = UseShared
7640           ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
7641           : Find(RootDir, StartSubDir, "/init.o");
7642     CmdArgs.push_back(Args.MakeArgString(Init));
7643   }
7644
7645   //----------------------------------------------------------------------------
7646   // Library Search Paths
7647   //----------------------------------------------------------------------------
7648   const ToolChain::path_list &LibPaths = HTC.getFilePaths();
7649   for (const auto &LibPath : LibPaths)
7650     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
7651
7652   //----------------------------------------------------------------------------
7653   //
7654   //----------------------------------------------------------------------------
7655   Args.AddAllArgs(CmdArgs,
7656                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7657                    options::OPT_t, options::OPT_u_Group});
7658
7659   AddLinkerInputs(HTC, Inputs, Args, CmdArgs, JA);
7660
7661   //----------------------------------------------------------------------------
7662   // Libraries
7663   //----------------------------------------------------------------------------
7664   if (IncStdLib && IncDefLibs) {
7665     if (D.CCCIsCXX()) {
7666       HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
7667       CmdArgs.push_back("-lm");
7668     }
7669
7670     CmdArgs.push_back("--start-group");
7671
7672     if (!IsShared) {
7673       for (const std::string &Lib : OsLibs)
7674         CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
7675       CmdArgs.push_back("-lc");
7676     }
7677     CmdArgs.push_back("-lgcc");
7678
7679     CmdArgs.push_back("--end-group");
7680   }
7681
7682   //----------------------------------------------------------------------------
7683   // End files
7684   //----------------------------------------------------------------------------
7685   if (IncStdLib && IncStartFiles) {
7686     std::string Fini = UseShared
7687           ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
7688           : Find(RootDir, StartSubDir, "/fini.o");
7689     CmdArgs.push_back(Args.MakeArgString(Fini));
7690   }
7691 }
7692
7693 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7694                                    const InputInfo &Output,
7695                                    const InputInfoList &Inputs,
7696                                    const ArgList &Args,
7697                                    const char *LinkingOutput) const {
7698   auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7699
7700   ArgStringList CmdArgs;
7701   constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
7702                            LinkingOutput);
7703
7704   std::string Linker = HTC.GetProgramPath("hexagon-link");
7705   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7706                                           CmdArgs, Inputs));
7707 }
7708 // Hexagon tools end.
7709
7710 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7711                                   const InputInfo &Output,
7712                                   const InputInfoList &Inputs,
7713                                   const ArgList &Args,
7714                                   const char *LinkingOutput) const {
7715
7716   std::string Linker = getToolChain().GetProgramPath(getShortName());
7717   ArgStringList CmdArgs;
7718   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
7719   CmdArgs.push_back("-shared");
7720   CmdArgs.push_back("-o");
7721   CmdArgs.push_back(Output.getFilename());
7722   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7723                                           CmdArgs, Inputs));
7724 }
7725 // AMDGPU tools end.
7726
7727 wasm::Linker::Linker(const ToolChain &TC)
7728   : GnuTool("wasm::Linker", "lld", TC) {}
7729
7730 bool wasm::Linker::isLinkJob() const {
7731   return true;
7732 }
7733
7734 bool wasm::Linker::hasIntegratedCPP() const {
7735   return false;
7736 }
7737
7738 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7739                                 const InputInfo &Output,
7740                                 const InputInfoList &Inputs,
7741                                 const ArgList &Args,
7742                                 const char *LinkingOutput) const {
7743
7744   const ToolChain &ToolChain = getToolChain();
7745   const Driver &D = ToolChain.getDriver();
7746   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
7747   ArgStringList CmdArgs;
7748   CmdArgs.push_back("-flavor");
7749   CmdArgs.push_back("ld");
7750
7751   // Enable garbage collection of unused input sections by default, since code
7752   // size is of particular importance. This is significantly facilitated by
7753   // the enabling of -ffunction-sections and -fdata-sections in
7754   // Clang::ConstructJob.
7755   if (areOptimizationsEnabled(Args))
7756     CmdArgs.push_back("--gc-sections");
7757
7758   if (Args.hasArg(options::OPT_rdynamic))
7759     CmdArgs.push_back("-export-dynamic");
7760   if (Args.hasArg(options::OPT_s))
7761     CmdArgs.push_back("--strip-all");
7762   if (Args.hasArg(options::OPT_shared))
7763     CmdArgs.push_back("-shared");
7764   if (Args.hasArg(options::OPT_static))
7765     CmdArgs.push_back("-Bstatic");
7766
7767   Args.AddAllArgs(CmdArgs, options::OPT_L);
7768   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7769
7770   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7771     if (Args.hasArg(options::OPT_shared))
7772       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
7773     else if (Args.hasArg(options::OPT_pie))
7774       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
7775     else
7776       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
7777
7778     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7779   }
7780
7781   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
7782
7783   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7784     if (D.CCCIsCXX())
7785       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7786
7787     if (Args.hasArg(options::OPT_pthread))
7788       CmdArgs.push_back("-lpthread");
7789
7790     CmdArgs.push_back("-lc");
7791     CmdArgs.push_back("-lcompiler_rt");
7792   }
7793
7794   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7795     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7796
7797   CmdArgs.push_back("-o");
7798   CmdArgs.push_back(Output.getFilename());
7799
7800   C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
7801 }
7802
7803 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
7804   std::string MArch;
7805   if (!Arch.empty())
7806     MArch = Arch;
7807   else
7808     MArch = Triple.getArchName();
7809   MArch = StringRef(MArch).split("+").first.lower();
7810
7811   // Handle -march=native.
7812   if (MArch == "native") {
7813     std::string CPU = llvm::sys::getHostCPUName();
7814     if (CPU != "generic") {
7815       // Translate the native cpu into the architecture suffix for that CPU.
7816       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
7817       // If there is no valid architecture suffix for this CPU we don't know how
7818       // to handle it, so return no architecture.
7819       if (Suffix.empty())
7820         MArch = "";
7821       else
7822         MArch = std::string("arm") + Suffix.str();
7823     }
7824   }
7825
7826   return MArch;
7827 }
7828
7829 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
7830 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
7831   std::string MArch = getARMArch(Arch, Triple);
7832   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
7833   // here means an -march=native that we can't handle, so instead return no CPU.
7834   if (MArch.empty())
7835     return StringRef();
7836
7837   // We need to return an empty string here on invalid MArch values as the
7838   // various places that call this function can't cope with a null result.
7839   return Triple.getARMCPUForArch(MArch);
7840 }
7841
7842 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
7843 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
7844                                  const llvm::Triple &Triple) {
7845   // FIXME: Warn on inconsistent use of -mcpu and -march.
7846   // If we have -mcpu=, use that.
7847   if (!CPU.empty()) {
7848     std::string MCPU = StringRef(CPU).split("+").first.lower();
7849     // Handle -mcpu=native.
7850     if (MCPU == "native")
7851       return llvm::sys::getHostCPUName();
7852     else
7853       return MCPU;
7854   }
7855
7856   return getARMCPUForMArch(Arch, Triple);
7857 }
7858
7859 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
7860 /// CPU  (or Arch, if CPU is generic).
7861 // FIXME: This is redundant with -mcpu, why does LLVM use this.
7862 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
7863                                        const llvm::Triple &Triple) {
7864   unsigned ArchKind;
7865   if (CPU == "generic") {
7866     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
7867     ArchKind = llvm::ARM::parseArch(ARMArch);
7868     if (ArchKind == llvm::ARM::AK_INVALID)
7869       // In case of generic Arch, i.e. "arm",
7870       // extract arch from default cpu of the Triple
7871       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
7872   } else {
7873     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
7874     // armv7k triple if it's actually been specified via "-arch armv7k".
7875     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
7876                           ? (unsigned)llvm::ARM::AK_ARMV7K
7877                           : llvm::ARM::parseCPUArch(CPU);
7878   }
7879   if (ArchKind == llvm::ARM::AK_INVALID)
7880     return "";
7881   return llvm::ARM::getSubArch(ArchKind);
7882 }
7883
7884 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
7885                             const llvm::Triple &Triple) {
7886   if (Args.hasArg(options::OPT_r))
7887     return;
7888
7889   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
7890   // to generate BE-8 executables.
7891   if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
7892     CmdArgs.push_back("--be8");
7893 }
7894
7895 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
7896   // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
7897   // was first introduced in Release 3. However, other compilers have
7898   // traditionally allowed it for Release 2 so we should do the same.
7899   return (NanEncoding)llvm::StringSwitch<int>(CPU)
7900       .Case("mips1", NanLegacy)
7901       .Case("mips2", NanLegacy)
7902       .Case("mips3", NanLegacy)
7903       .Case("mips4", NanLegacy)
7904       .Case("mips5", NanLegacy)
7905       .Case("mips32", NanLegacy)
7906       .Case("mips32r2", NanLegacy | Nan2008)
7907       .Case("mips32r3", NanLegacy | Nan2008)
7908       .Case("mips32r5", NanLegacy | Nan2008)
7909       .Case("mips32r6", Nan2008)
7910       .Case("mips64", NanLegacy)
7911       .Case("mips64r2", NanLegacy | Nan2008)
7912       .Case("mips64r3", NanLegacy | Nan2008)
7913       .Case("mips64r5", NanLegacy | Nan2008)
7914       .Case("mips64r6", Nan2008)
7915       .Default(NanLegacy);
7916 }
7917
7918 bool mips::hasCompactBranches(StringRef &CPU) {
7919   // mips32r6 and mips64r6 have compact branches.
7920   return llvm::StringSwitch<bool>(CPU)
7921       .Case("mips32r6", true)
7922       .Case("mips64r6", true)
7923       .Default(false);
7924 }
7925
7926 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
7927   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
7928   return A && (A->getValue() == StringRef(Value));
7929 }
7930
7931 bool mips::isUCLibc(const ArgList &Args) {
7932   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
7933   return A && A->getOption().matches(options::OPT_muclibc);
7934 }
7935
7936 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
7937   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
7938     return llvm::StringSwitch<bool>(NaNArg->getValue())
7939         .Case("2008", true)
7940         .Case("legacy", false)
7941         .Default(false);
7942
7943   // NaN2008 is the default for MIPS32r6/MIPS64r6.
7944   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
7945       .Cases("mips32r6", "mips64r6", true)
7946       .Default(false);
7947
7948   return false;
7949 }
7950
7951 bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
7952   if (!Triple.isAndroid())
7953     return false;
7954
7955   // Android MIPS32R6 defaults to FP64A.
7956   return llvm::StringSwitch<bool>(CPUName)
7957       .Case("mips32r6", true)
7958       .Default(false);
7959 }
7960
7961 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
7962                          StringRef ABIName, mips::FloatABI FloatABI) {
7963   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
7964       Triple.getVendor() != llvm::Triple::MipsTechnologies &&
7965       !Triple.isAndroid())
7966     return false;
7967
7968   if (ABIName != "32")
7969     return false;
7970
7971   // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
7972   // present.
7973   if (FloatABI == mips::FloatABI::Soft)
7974     return false;
7975
7976   return llvm::StringSwitch<bool>(CPUName)
7977       .Cases("mips2", "mips3", "mips4", "mips5", true)
7978       .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
7979       .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
7980       .Default(false);
7981 }
7982
7983 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
7984                          StringRef CPUName, StringRef ABIName,
7985                          mips::FloatABI FloatABI) {
7986   bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
7987
7988   // FPXX shouldn't be used if -msingle-float is present.
7989   if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
7990                                options::OPT_mdouble_float))
7991     if (A->getOption().matches(options::OPT_msingle_float))
7992       UseFPXX = false;
7993
7994   return UseFPXX;
7995 }
7996
7997 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
7998   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
7999   // archs which Darwin doesn't use.
8000
8001   // The matching this routine does is fairly pointless, since it is neither the
8002   // complete architecture list, nor a reasonable subset. The problem is that
8003   // historically the driver driver accepts this and also ties its -march=
8004   // handling to the architecture name, so we need to be careful before removing
8005   // support for it.
8006
8007   // This code must be kept in sync with Clang's Darwin specific argument
8008   // translation.
8009
8010   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
8011       .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
8012       .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
8013       .Case("ppc64", llvm::Triple::ppc64)
8014       .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
8015       .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
8016              llvm::Triple::x86)
8017       .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
8018       // This is derived from the driver driver.
8019       .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
8020       .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
8021       .Cases("armv7s", "xscale", llvm::Triple::arm)
8022       .Case("arm64", llvm::Triple::aarch64)
8023       .Case("r600", llvm::Triple::r600)
8024       .Case("amdgcn", llvm::Triple::amdgcn)
8025       .Case("nvptx", llvm::Triple::nvptx)
8026       .Case("nvptx64", llvm::Triple::nvptx64)
8027       .Case("amdil", llvm::Triple::amdil)
8028       .Case("spir", llvm::Triple::spir)
8029       .Default(llvm::Triple::UnknownArch);
8030 }
8031
8032 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
8033   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
8034   unsigned ArchKind = llvm::ARM::parseArch(Str);
8035   T.setArch(Arch);
8036
8037   if (Str == "x86_64h")
8038     T.setArchName(Str);
8039   else if (ArchKind == llvm::ARM::AK_ARMV6M ||
8040            ArchKind == llvm::ARM::AK_ARMV7M ||
8041            ArchKind == llvm::ARM::AK_ARMV7EM) {
8042     T.setOS(llvm::Triple::UnknownOS);
8043     T.setObjectFormat(llvm::Triple::MachO);
8044   }
8045 }
8046
8047 const char *Clang::getBaseInputName(const ArgList &Args,
8048                                     const InputInfo &Input) {
8049   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
8050 }
8051
8052 const char *Clang::getBaseInputStem(const ArgList &Args,
8053                                     const InputInfoList &Inputs) {
8054   const char *Str = getBaseInputName(Args, Inputs[0]);
8055
8056   if (const char *End = strrchr(Str, '.'))
8057     return Args.MakeArgString(std::string(Str, End));
8058
8059   return Str;
8060 }
8061
8062 const char *Clang::getDependencyFileName(const ArgList &Args,
8063                                          const InputInfoList &Inputs) {
8064   // FIXME: Think about this more.
8065   std::string Res;
8066
8067   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8068     std::string Str(OutputOpt->getValue());
8069     Res = Str.substr(0, Str.rfind('.'));
8070   } else {
8071     Res = getBaseInputStem(Args, Inputs);
8072   }
8073   return Args.MakeArgString(Res + ".d");
8074 }
8075
8076 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8077                                     const InputInfo &Output,
8078                                     const InputInfoList &Inputs,
8079                                     const ArgList &Args,
8080                                     const char *LinkingOutput) const {
8081   const ToolChain &ToolChain = getToolChain();
8082   const Driver &D = ToolChain.getDriver();
8083   ArgStringList CmdArgs;
8084
8085   // Silence warning for "clang -g foo.o -o foo"
8086   Args.ClaimAllArgs(options::OPT_g_Group);
8087   // and "clang -emit-llvm foo.o -o foo"
8088   Args.ClaimAllArgs(options::OPT_emit_llvm);
8089   // and for "clang -w foo.o -o foo". Other warning options are already
8090   // handled somewhere else.
8091   Args.ClaimAllArgs(options::OPT_w);
8092
8093   if (!D.SysRoot.empty())
8094     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8095
8096   // CloudABI only supports static linkage.
8097   CmdArgs.push_back("-Bstatic");
8098   CmdArgs.push_back("--no-dynamic-linker");
8099
8100   // Provide PIE linker flags in case PIE is default for the architecture.
8101   if (ToolChain.isPIEDefault()) {
8102     CmdArgs.push_back("-pie");
8103     CmdArgs.push_back("-zrelro");
8104   }
8105
8106   CmdArgs.push_back("--eh-frame-hdr");
8107   CmdArgs.push_back("--gc-sections");
8108
8109   if (Output.isFilename()) {
8110     CmdArgs.push_back("-o");
8111     CmdArgs.push_back(Output.getFilename());
8112   } else {
8113     assert(Output.isNothing() && "Invalid output.");
8114   }
8115
8116   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8117     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
8118     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
8119   }
8120
8121   Args.AddAllArgs(CmdArgs, options::OPT_L);
8122   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8123   Args.AddAllArgs(CmdArgs,
8124                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
8125                    options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
8126
8127   if (D.isUsingLTO())
8128     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
8129
8130   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
8131
8132   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8133     if (D.CCCIsCXX())
8134       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8135     CmdArgs.push_back("-lc");
8136     CmdArgs.push_back("-lcompiler_rt");
8137   }
8138
8139   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
8140     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8141
8142   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8143   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8144 }
8145
8146 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8147                                      const InputInfo &Output,
8148                                      const InputInfoList &Inputs,
8149                                      const ArgList &Args,
8150                                      const char *LinkingOutput) const {
8151   ArgStringList CmdArgs;
8152
8153   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8154   const InputInfo &Input = Inputs[0];
8155
8156   // Determine the original source input.
8157   const Action *SourceAction = &JA;
8158   while (SourceAction->getKind() != Action::InputClass) {
8159     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8160     SourceAction = SourceAction->getInputs()[0];
8161   }
8162
8163   // If -fno-integrated-as is used add -Q to the darwin assember driver to make
8164   // sure it runs its system assembler not clang's integrated assembler.
8165   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
8166   // FIXME: at run-time detect assembler capabilities or rely on version
8167   // information forwarded by -target-assembler-version.
8168   if (Args.hasArg(options::OPT_fno_integrated_as)) {
8169     const llvm::Triple &T(getToolChain().getTriple());
8170     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
8171       CmdArgs.push_back("-Q");
8172   }
8173
8174   // Forward -g, assuming we are dealing with an actual assembly file.
8175   if (SourceAction->getType() == types::TY_Asm ||
8176       SourceAction->getType() == types::TY_PP_Asm) {
8177     if (Args.hasArg(options::OPT_gstabs))
8178       CmdArgs.push_back("--gstabs");
8179     else if (Args.hasArg(options::OPT_g_Group))
8180       CmdArgs.push_back("-g");
8181   }
8182
8183   // Derived from asm spec.
8184   AddMachOArch(Args, CmdArgs);
8185
8186   // Use -force_cpusubtype_ALL on x86 by default.
8187   if (getToolChain().getArch() == llvm::Triple::x86 ||
8188       getToolChain().getArch() == llvm::Triple::x86_64 ||
8189       Args.hasArg(options::OPT_force__cpusubtype__ALL))
8190     CmdArgs.push_back("-force_cpusubtype_ALL");
8191
8192   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
8193       (((Args.hasArg(options::OPT_mkernel) ||
8194          Args.hasArg(options::OPT_fapple_kext)) &&
8195         getMachOToolChain().isKernelStatic()) ||
8196        Args.hasArg(options::OPT_static)))
8197     CmdArgs.push_back("-static");
8198
8199   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8200
8201   assert(Output.isFilename() && "Unexpected lipo output.");
8202   CmdArgs.push_back("-o");
8203   CmdArgs.push_back(Output.getFilename());
8204
8205   assert(Input.isFilename() && "Invalid input.");
8206   CmdArgs.push_back(Input.getFilename());
8207
8208   // asm_final spec is empty.
8209
8210   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8211   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8212 }
8213
8214 void darwin::MachOTool::anchor() {}
8215
8216 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
8217                                      ArgStringList &CmdArgs) const {
8218   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
8219
8220   // Derived from darwin_arch spec.
8221   CmdArgs.push_back("-arch");
8222   CmdArgs.push_back(Args.MakeArgString(ArchName));
8223
8224   // FIXME: Is this needed anymore?
8225   if (ArchName == "arm")
8226     CmdArgs.push_back("-force_cpusubtype_ALL");
8227 }
8228
8229 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
8230   // We only need to generate a temp path for LTO if we aren't compiling object
8231   // files. When compiling source files, we run 'dsymutil' after linking. We
8232   // don't run 'dsymutil' when compiling object files.
8233   for (const auto &Input : Inputs)
8234     if (Input.getType() != types::TY_Object)
8235       return true;
8236
8237   return false;
8238 }
8239
8240 /// \brief Pass -no_deduplicate to ld64 under certain conditions:
8241 ///
8242 /// - Either -O0 or -O1 is explicitly specified
8243 /// - No -O option is specified *and* this is a compile+link (implicit -O0)
8244 ///
8245 /// Also do *not* add -no_deduplicate when no -O option is specified and this
8246 /// is just a link (we can't imply -O0)
8247 static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
8248   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
8249     if (A->getOption().matches(options::OPT_O0))
8250       return true;
8251     if (A->getOption().matches(options::OPT_O))
8252       return llvm::StringSwitch<bool>(A->getValue())
8253                     .Case("1", true)
8254                     .Default(false);
8255     return false; // OPT_Ofast & OPT_O4
8256   }
8257
8258   if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
8259     return true;
8260   return false;
8261 }
8262
8263 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
8264                                  ArgStringList &CmdArgs,
8265                                  const InputInfoList &Inputs) const {
8266   const Driver &D = getToolChain().getDriver();
8267   const toolchains::MachO &MachOTC = getMachOToolChain();
8268
8269   unsigned Version[5] = {0, 0, 0, 0, 0};
8270   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
8271     if (!Driver::GetReleaseVersion(A->getValue(), Version))
8272       D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
8273   }
8274
8275   // Newer linkers support -demangle. Pass it if supported and not disabled by
8276   // the user.
8277   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8278     CmdArgs.push_back("-demangle");
8279
8280   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
8281     CmdArgs.push_back("-export_dynamic");
8282
8283   // If we are using App Extension restrictions, pass a flag to the linker
8284   // telling it that the compiled code has been audited.
8285   if (Args.hasFlag(options::OPT_fapplication_extension,
8286                    options::OPT_fno_application_extension, false))
8287     CmdArgs.push_back("-application_extension");
8288
8289   if (D.isUsingLTO()) {
8290     // If we are using LTO, then automatically create a temporary file path for
8291     // the linker to use, so that it's lifetime will extend past a possible
8292     // dsymutil step.
8293     if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
8294       const char *TmpPath = C.getArgs().MakeArgString(
8295           D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
8296       C.addTempFile(TmpPath);
8297       CmdArgs.push_back("-object_path_lto");
8298       CmdArgs.push_back(TmpPath);
8299     }
8300   }
8301
8302   // Use -lto_library option to specify the libLTO.dylib path. Try to find
8303   // it in clang installed libraries. ld64 will only look at this argument
8304   // when it actually uses LTO, so libLTO.dylib only needs to exist at link
8305   // time if ld64 decides that it needs to use LTO.
8306   // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
8307   // next to it. That's ok since ld64 using a libLTO.dylib not matching the
8308   // clang version won't work anyways.
8309   if (Version[0] >= 133) {
8310     // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
8311     StringRef P = llvm::sys::path::parent_path(D.Dir);
8312     SmallString<128> LibLTOPath(P);
8313     llvm::sys::path::append(LibLTOPath, "lib");
8314     llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
8315     CmdArgs.push_back("-lto_library");
8316     CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
8317   }
8318
8319   // ld64 version 262 and above run the deduplicate pass by default.
8320   if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
8321     CmdArgs.push_back("-no_deduplicate");
8322
8323   // Derived from the "link" spec.
8324   Args.AddAllArgs(CmdArgs, options::OPT_static);
8325   if (!Args.hasArg(options::OPT_static))
8326     CmdArgs.push_back("-dynamic");
8327   if (Args.hasArg(options::OPT_fgnu_runtime)) {
8328     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
8329     // here. How do we wish to handle such things?
8330   }
8331
8332   if (!Args.hasArg(options::OPT_dynamiclib)) {
8333     AddMachOArch(Args, CmdArgs);
8334     // FIXME: Why do this only on this path?
8335     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
8336
8337     Args.AddLastArg(CmdArgs, options::OPT_bundle);
8338     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
8339     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
8340
8341     Arg *A;
8342     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
8343         (A = Args.getLastArg(options::OPT_current__version)) ||
8344         (A = Args.getLastArg(options::OPT_install__name)))
8345       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
8346                                                        << "-dynamiclib";
8347
8348     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
8349     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
8350     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
8351   } else {
8352     CmdArgs.push_back("-dylib");
8353
8354     Arg *A;
8355     if ((A = Args.getLastArg(options::OPT_bundle)) ||
8356         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
8357         (A = Args.getLastArg(options::OPT_client__name)) ||
8358         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
8359         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
8360         (A = Args.getLastArg(options::OPT_private__bundle)))
8361       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
8362                                                       << "-dynamiclib";
8363
8364     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
8365                               "-dylib_compatibility_version");
8366     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
8367                               "-dylib_current_version");
8368
8369     AddMachOArch(Args, CmdArgs);
8370
8371     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
8372                               "-dylib_install_name");
8373   }
8374
8375   Args.AddLastArg(CmdArgs, options::OPT_all__load);
8376   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
8377   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
8378   if (MachOTC.isTargetIOSBased())
8379     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
8380   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
8381   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
8382   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
8383   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
8384   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
8385   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
8386   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
8387   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
8388   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
8389   Args.AddAllArgs(CmdArgs, options::OPT_init);
8390
8391   // Add the deployment target.
8392   MachOTC.addMinVersionArgs(Args, CmdArgs);
8393
8394   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
8395   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
8396   Args.AddLastArg(CmdArgs, options::OPT_single__module);
8397   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
8398   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
8399
8400   if (const Arg *A =
8401           Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
8402                           options::OPT_fno_pie, options::OPT_fno_PIE)) {
8403     if (A->getOption().matches(options::OPT_fpie) ||
8404         A->getOption().matches(options::OPT_fPIE))
8405       CmdArgs.push_back("-pie");
8406     else
8407       CmdArgs.push_back("-no_pie");
8408   }
8409
8410   // for embed-bitcode, use -bitcode_bundle in linker command
8411   if (C.getDriver().embedBitcodeEnabled()) {
8412     // Check if the toolchain supports bitcode build flow.
8413     if (MachOTC.SupportsEmbeddedBitcode())
8414       CmdArgs.push_back("-bitcode_bundle");
8415     else
8416       D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
8417   }
8418
8419   Args.AddLastArg(CmdArgs, options::OPT_prebind);
8420   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
8421   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
8422   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
8423   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
8424   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
8425   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
8426   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
8427   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
8428   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
8429   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
8430   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
8431   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
8432   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
8433   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
8434   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
8435
8436   // Give --sysroot= preference, over the Apple specific behavior to also use
8437   // --isysroot as the syslibroot.
8438   StringRef sysroot = C.getSysRoot();
8439   if (sysroot != "") {
8440     CmdArgs.push_back("-syslibroot");
8441     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
8442   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
8443     CmdArgs.push_back("-syslibroot");
8444     CmdArgs.push_back(A->getValue());
8445   }
8446
8447   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
8448   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
8449   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
8450   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
8451   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
8452   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
8453   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
8454   Args.AddAllArgs(CmdArgs, options::OPT_y);
8455   Args.AddLastArg(CmdArgs, options::OPT_w);
8456   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
8457   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
8458   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
8459   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
8460   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
8461   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
8462   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
8463   Args.AddLastArg(CmdArgs, options::OPT_whyload);
8464   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
8465   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
8466   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
8467   Args.AddLastArg(CmdArgs, options::OPT_Mach);
8468 }
8469
8470 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8471                                   const InputInfo &Output,
8472                                   const InputInfoList &Inputs,
8473                                   const ArgList &Args,
8474                                   const char *LinkingOutput) const {
8475   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
8476
8477   // If the number of arguments surpasses the system limits, we will encode the
8478   // input files in a separate file, shortening the command line. To this end,
8479   // build a list of input file names that can be passed via a file with the
8480   // -filelist linker option.
8481   llvm::opt::ArgStringList InputFileList;
8482
8483   // The logic here is derived from gcc's behavior; most of which
8484   // comes from specs (starting with link_command). Consult gcc for
8485   // more information.
8486   ArgStringList CmdArgs;
8487
8488   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
8489   if (Args.hasArg(options::OPT_ccc_arcmt_check,
8490                   options::OPT_ccc_arcmt_migrate)) {
8491     for (const auto &Arg : Args)
8492       Arg->claim();
8493     const char *Exec =
8494         Args.MakeArgString(getToolChain().GetProgramPath("touch"));
8495     CmdArgs.push_back(Output.getFilename());
8496     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
8497     return;
8498   }
8499
8500   // I'm not sure why this particular decomposition exists in gcc, but
8501   // we follow suite for ease of comparison.
8502   AddLinkArgs(C, Args, CmdArgs, Inputs);
8503
8504   // For LTO, pass the name of the optimization record file.
8505   if (Args.hasFlag(options::OPT_fsave_optimization_record,
8506                    options::OPT_fno_save_optimization_record, false)) {
8507     CmdArgs.push_back("-mllvm");
8508     CmdArgs.push_back("-lto-pass-remarks-output");
8509     CmdArgs.push_back("-mllvm");
8510
8511     SmallString<128> F;
8512     F = Output.getFilename();
8513     F += ".opt.yaml";
8514     CmdArgs.push_back(Args.MakeArgString(F));
8515
8516     if (getLastProfileUseArg(Args)) {
8517       CmdArgs.push_back("-mllvm");
8518       CmdArgs.push_back("-lto-pass-remarks-with-hotness");
8519     }
8520   }
8521
8522   // It seems that the 'e' option is completely ignored for dynamic executables
8523   // (the default), and with static executables, the last one wins, as expected.
8524   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
8525                             options::OPT_Z_Flag, options::OPT_u_Group,
8526                             options::OPT_e, options::OPT_r});
8527
8528   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
8529   // members of static archive libraries which implement Objective-C classes or
8530   // categories.
8531   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
8532     CmdArgs.push_back("-ObjC");
8533
8534   CmdArgs.push_back("-o");
8535   CmdArgs.push_back(Output.getFilename());
8536
8537   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
8538     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
8539
8540   // SafeStack requires its own runtime libraries
8541   // These libraries should be linked first, to make sure the
8542   // __safestack_init constructor executes before everything else
8543   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
8544     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
8545                                           "libclang_rt.safestack_osx.a",
8546                                           /*AlwaysLink=*/true);
8547   }
8548
8549   Args.AddAllArgs(CmdArgs, options::OPT_L);
8550
8551   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
8552   // Build the input file for -filelist (list of linker input files) in case we
8553   // need it later
8554   for (const auto &II : Inputs) {
8555     if (!II.isFilename()) {
8556       // This is a linker input argument.
8557       // We cannot mix input arguments and file names in a -filelist input, thus
8558       // we prematurely stop our list (remaining files shall be passed as
8559       // arguments).
8560       if (InputFileList.size() > 0)
8561         break;
8562
8563       continue;
8564     }
8565
8566     InputFileList.push_back(II.getFilename());
8567   }
8568
8569   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
8570     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8571
8572   if (isObjCRuntimeLinked(Args) &&
8573       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8574     // We use arclite library for both ARC and subscripting support.
8575     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
8576
8577     CmdArgs.push_back("-framework");
8578     CmdArgs.push_back("Foundation");
8579     // Link libobj.
8580     CmdArgs.push_back("-lobjc");
8581   }
8582
8583   if (LinkingOutput) {
8584     CmdArgs.push_back("-arch_multiple");
8585     CmdArgs.push_back("-final_output");
8586     CmdArgs.push_back(LinkingOutput);
8587   }
8588
8589   if (Args.hasArg(options::OPT_fnested_functions))
8590     CmdArgs.push_back("-allow_stack_execute");
8591
8592   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
8593
8594   if (unsigned Parallelism =
8595           getLTOParallelism(Args, getToolChain().getDriver())) {
8596     CmdArgs.push_back("-mllvm");
8597     CmdArgs.push_back(
8598         Args.MakeArgString(Twine("-threads=") + llvm::to_string(Parallelism)));
8599   }
8600
8601   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8602     if (getToolChain().getDriver().CCCIsCXX())
8603       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8604
8605     // link_ssp spec is empty.
8606
8607     // Let the tool chain choose which runtime library to link.
8608     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
8609   }
8610
8611   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8612     // endfile_spec is empty.
8613   }
8614
8615   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8616   Args.AddAllArgs(CmdArgs, options::OPT_F);
8617
8618   // -iframework should be forwarded as -F.
8619   for (const Arg *A : Args.filtered(options::OPT_iframework))
8620     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
8621
8622   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8623     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
8624       if (A->getValue() == StringRef("Accelerate")) {
8625         CmdArgs.push_back("-framework");
8626         CmdArgs.push_back("Accelerate");
8627       }
8628     }
8629   }
8630
8631   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8632   std::unique_ptr<Command> Cmd =
8633       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
8634   Cmd->setInputFileList(std::move(InputFileList));
8635   C.addCommand(std::move(Cmd));
8636 }
8637
8638 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
8639                                 const InputInfo &Output,
8640                                 const InputInfoList &Inputs,
8641                                 const ArgList &Args,
8642                                 const char *LinkingOutput) const {
8643   ArgStringList CmdArgs;
8644
8645   CmdArgs.push_back("-create");
8646   assert(Output.isFilename() && "Unexpected lipo output.");
8647
8648   CmdArgs.push_back("-output");
8649   CmdArgs.push_back(Output.getFilename());
8650
8651   for (const auto &II : Inputs) {
8652     assert(II.isFilename() && "Unexpected lipo input.");
8653     CmdArgs.push_back(II.getFilename());
8654   }
8655
8656   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
8657   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8658 }
8659
8660 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
8661                                     const InputInfo &Output,
8662                                     const InputInfoList &Inputs,
8663                                     const ArgList &Args,
8664                                     const char *LinkingOutput) const {
8665   ArgStringList CmdArgs;
8666
8667   CmdArgs.push_back("-o");
8668   CmdArgs.push_back(Output.getFilename());
8669
8670   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
8671   const InputInfo &Input = Inputs[0];
8672   assert(Input.isFilename() && "Unexpected dsymutil input.");
8673   CmdArgs.push_back(Input.getFilename());
8674
8675   const char *Exec =
8676       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
8677   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8678 }
8679
8680 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
8681                                        const InputInfo &Output,
8682                                        const InputInfoList &Inputs,
8683                                        const ArgList &Args,
8684                                        const char *LinkingOutput) const {
8685   ArgStringList CmdArgs;
8686   CmdArgs.push_back("--verify");
8687   CmdArgs.push_back("--debug-info");
8688   CmdArgs.push_back("--eh-frame");
8689   CmdArgs.push_back("--quiet");
8690
8691   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
8692   const InputInfo &Input = Inputs[0];
8693   assert(Input.isFilename() && "Unexpected verify input");
8694
8695   // Grabbing the output of the earlier dsymutil run.
8696   CmdArgs.push_back(Input.getFilename());
8697
8698   const char *Exec =
8699       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
8700   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8701 }
8702
8703 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8704                                       const InputInfo &Output,
8705                                       const InputInfoList &Inputs,
8706                                       const ArgList &Args,
8707                                       const char *LinkingOutput) const {
8708   claimNoWarnArgs(Args);
8709   ArgStringList CmdArgs;
8710
8711   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8712
8713   CmdArgs.push_back("-o");
8714   CmdArgs.push_back(Output.getFilename());
8715
8716   for (const auto &II : Inputs)
8717     CmdArgs.push_back(II.getFilename());
8718
8719   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8720   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8721 }
8722
8723 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8724                                    const InputInfo &Output,
8725                                    const InputInfoList &Inputs,
8726                                    const ArgList &Args,
8727                                    const char *LinkingOutput) const {
8728   ArgStringList CmdArgs;
8729
8730   // Demangle C++ names in errors
8731   CmdArgs.push_back("-C");
8732
8733   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8734     CmdArgs.push_back("-e");
8735     CmdArgs.push_back("_start");
8736   }
8737
8738   if (Args.hasArg(options::OPT_static)) {
8739     CmdArgs.push_back("-Bstatic");
8740     CmdArgs.push_back("-dn");
8741   } else {
8742     CmdArgs.push_back("-Bdynamic");
8743     if (Args.hasArg(options::OPT_shared)) {
8744       CmdArgs.push_back("-shared");
8745     } else {
8746       CmdArgs.push_back("--dynamic-linker");
8747       CmdArgs.push_back(
8748           Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
8749     }
8750   }
8751
8752   if (Output.isFilename()) {
8753     CmdArgs.push_back("-o");
8754     CmdArgs.push_back(Output.getFilename());
8755   } else {
8756     assert(Output.isNothing() && "Invalid output.");
8757   }
8758
8759   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8760     if (!Args.hasArg(options::OPT_shared))
8761       CmdArgs.push_back(
8762           Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8763
8764     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8765     CmdArgs.push_back(
8766         Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
8767     CmdArgs.push_back(
8768         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8769   }
8770
8771   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
8772
8773   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8774                             options::OPT_e, options::OPT_r});
8775
8776   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
8777
8778   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8779     if (getToolChain().getDriver().CCCIsCXX())
8780       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8781     CmdArgs.push_back("-lgcc_s");
8782     CmdArgs.push_back("-lc");
8783     if (!Args.hasArg(options::OPT_shared)) {
8784       CmdArgs.push_back("-lgcc");
8785       CmdArgs.push_back("-lm");
8786     }
8787   }
8788
8789   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8790     CmdArgs.push_back(
8791         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8792   }
8793   CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8794
8795   getToolChain().addProfileRTLibs(Args, CmdArgs);
8796
8797   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8798   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8799 }
8800
8801 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8802                                       const InputInfo &Output,
8803                                       const InputInfoList &Inputs,
8804                                       const ArgList &Args,
8805                                       const char *LinkingOutput) const {
8806   claimNoWarnArgs(Args);
8807   ArgStringList CmdArgs;
8808
8809   switch (getToolChain().getArch()) {
8810   case llvm::Triple::x86:
8811     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
8812     // instruct as in the base system to assemble 32-bit code.
8813     CmdArgs.push_back("--32");
8814     break;
8815
8816   case llvm::Triple::ppc:
8817     CmdArgs.push_back("-mppc");
8818     CmdArgs.push_back("-many");
8819     break;
8820
8821   case llvm::Triple::sparc:
8822   case llvm::Triple::sparcel: {
8823     CmdArgs.push_back("-32");
8824     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8825     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8826     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8827     break;
8828   }
8829
8830   case llvm::Triple::sparcv9: {
8831     CmdArgs.push_back("-64");
8832     std::string CPU = getCPUName(Args, getToolChain().getTriple());
8833     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8834     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8835     break;
8836   }
8837
8838   case llvm::Triple::mips64:
8839   case llvm::Triple::mips64el: {
8840     StringRef CPUName;
8841     StringRef ABIName;
8842     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8843
8844     CmdArgs.push_back("-mabi");
8845     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8846
8847     if (getToolChain().getArch() == llvm::Triple::mips64)
8848       CmdArgs.push_back("-EB");
8849     else
8850       CmdArgs.push_back("-EL");
8851
8852     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8853     break;
8854   }
8855
8856   default:
8857     break;
8858   }
8859
8860   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8861
8862   CmdArgs.push_back("-o");
8863   CmdArgs.push_back(Output.getFilename());
8864
8865   for (const auto &II : Inputs)
8866     CmdArgs.push_back(II.getFilename());
8867
8868   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8869   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8870 }
8871
8872 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8873                                    const InputInfo &Output,
8874                                    const InputInfoList &Inputs,
8875                                    const ArgList &Args,
8876                                    const char *LinkingOutput) const {
8877   const Driver &D = getToolChain().getDriver();
8878   ArgStringList CmdArgs;
8879
8880   // Silence warning for "clang -g foo.o -o foo"
8881   Args.ClaimAllArgs(options::OPT_g_Group);
8882   // and "clang -emit-llvm foo.o -o foo"
8883   Args.ClaimAllArgs(options::OPT_emit_llvm);
8884   // and for "clang -w foo.o -o foo". Other warning options are already
8885   // handled somewhere else.
8886   Args.ClaimAllArgs(options::OPT_w);
8887
8888   if (getToolChain().getArch() == llvm::Triple::mips64)
8889     CmdArgs.push_back("-EB");
8890   else if (getToolChain().getArch() == llvm::Triple::mips64el)
8891     CmdArgs.push_back("-EL");
8892
8893   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8894     CmdArgs.push_back("-e");
8895     CmdArgs.push_back("__start");
8896   }
8897
8898   if (Args.hasArg(options::OPT_static)) {
8899     CmdArgs.push_back("-Bstatic");
8900   } else {
8901     if (Args.hasArg(options::OPT_rdynamic))
8902       CmdArgs.push_back("-export-dynamic");
8903     CmdArgs.push_back("--eh-frame-hdr");
8904     CmdArgs.push_back("-Bdynamic");
8905     if (Args.hasArg(options::OPT_shared)) {
8906       CmdArgs.push_back("-shared");
8907     } else {
8908       CmdArgs.push_back("-dynamic-linker");
8909       CmdArgs.push_back("/usr/libexec/ld.so");
8910     }
8911   }
8912
8913   if (Args.hasArg(options::OPT_nopie))
8914     CmdArgs.push_back("-nopie");
8915
8916   if (Output.isFilename()) {
8917     CmdArgs.push_back("-o");
8918     CmdArgs.push_back(Output.getFilename());
8919   } else {
8920     assert(Output.isNothing() && "Invalid output.");
8921   }
8922
8923   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8924     if (!Args.hasArg(options::OPT_shared)) {
8925       if (Args.hasArg(options::OPT_pg))
8926         CmdArgs.push_back(
8927             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8928       else
8929         CmdArgs.push_back(
8930             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8931       CmdArgs.push_back(
8932           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8933     } else {
8934       CmdArgs.push_back(
8935           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8936     }
8937   }
8938
8939   std::string Triple = getToolChain().getTripleString();
8940   if (Triple.substr(0, 6) == "x86_64")
8941     Triple.replace(0, 6, "amd64");
8942   CmdArgs.push_back(
8943       Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
8944
8945   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8946                             options::OPT_e, options::OPT_s, options::OPT_t,
8947                             options::OPT_Z_Flag, options::OPT_r});
8948
8949   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
8950
8951   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8952     if (D.CCCIsCXX()) {
8953       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8954       if (Args.hasArg(options::OPT_pg))
8955         CmdArgs.push_back("-lm_p");
8956       else
8957         CmdArgs.push_back("-lm");
8958     }
8959
8960     // FIXME: For some reason GCC passes -lgcc before adding
8961     // the default system libraries. Just mimic this for now.
8962     CmdArgs.push_back("-lgcc");
8963
8964     if (Args.hasArg(options::OPT_pthread)) {
8965       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8966         CmdArgs.push_back("-lpthread_p");
8967       else
8968         CmdArgs.push_back("-lpthread");
8969     }
8970
8971     if (!Args.hasArg(options::OPT_shared)) {
8972       if (Args.hasArg(options::OPT_pg))
8973         CmdArgs.push_back("-lc_p");
8974       else
8975         CmdArgs.push_back("-lc");
8976     }
8977
8978     CmdArgs.push_back("-lgcc");
8979   }
8980
8981   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8982     if (!Args.hasArg(options::OPT_shared))
8983       CmdArgs.push_back(
8984           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8985     else
8986       CmdArgs.push_back(
8987           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8988   }
8989
8990   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8991   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8992 }
8993
8994 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8995                                      const InputInfo &Output,
8996                                      const InputInfoList &Inputs,
8997                                      const ArgList &Args,
8998                                      const char *LinkingOutput) const {
8999   claimNoWarnArgs(Args);
9000   ArgStringList CmdArgs;
9001
9002   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9003
9004   CmdArgs.push_back("-o");
9005   CmdArgs.push_back(Output.getFilename());
9006
9007   for (const auto &II : Inputs)
9008     CmdArgs.push_back(II.getFilename());
9009
9010   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9011   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9012 }
9013
9014 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9015                                   const InputInfo &Output,
9016                                   const InputInfoList &Inputs,
9017                                   const ArgList &Args,
9018                                   const char *LinkingOutput) const {
9019   const Driver &D = getToolChain().getDriver();
9020   ArgStringList CmdArgs;
9021
9022   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
9023     CmdArgs.push_back("-e");
9024     CmdArgs.push_back("__start");
9025   }
9026
9027   if (Args.hasArg(options::OPT_static)) {
9028     CmdArgs.push_back("-Bstatic");
9029   } else {
9030     if (Args.hasArg(options::OPT_rdynamic))
9031       CmdArgs.push_back("-export-dynamic");
9032     CmdArgs.push_back("--eh-frame-hdr");
9033     CmdArgs.push_back("-Bdynamic");
9034     if (Args.hasArg(options::OPT_shared)) {
9035       CmdArgs.push_back("-shared");
9036     } else {
9037       CmdArgs.push_back("-dynamic-linker");
9038       CmdArgs.push_back("/usr/libexec/ld.so");
9039     }
9040   }
9041
9042   if (Output.isFilename()) {
9043     CmdArgs.push_back("-o");
9044     CmdArgs.push_back(Output.getFilename());
9045   } else {
9046     assert(Output.isNothing() && "Invalid output.");
9047   }
9048
9049   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9050     if (!Args.hasArg(options::OPT_shared)) {
9051       if (Args.hasArg(options::OPT_pg))
9052         CmdArgs.push_back(
9053             Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
9054       else
9055         CmdArgs.push_back(
9056             Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
9057       CmdArgs.push_back(
9058           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9059     } else {
9060       CmdArgs.push_back(
9061           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9062     }
9063   }
9064
9065   Args.AddAllArgs(CmdArgs,
9066                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9067
9068   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
9069
9070   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9071     if (D.CCCIsCXX()) {
9072       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9073       if (Args.hasArg(options::OPT_pg))
9074         CmdArgs.push_back("-lm_p");
9075       else
9076         CmdArgs.push_back("-lm");
9077     }
9078
9079     if (Args.hasArg(options::OPT_pthread)) {
9080       if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
9081         CmdArgs.push_back("-lpthread_p");
9082       else
9083         CmdArgs.push_back("-lpthread");
9084     }
9085
9086     if (!Args.hasArg(options::OPT_shared)) {
9087       if (Args.hasArg(options::OPT_pg))
9088         CmdArgs.push_back("-lc_p");
9089       else
9090         CmdArgs.push_back("-lc");
9091     }
9092
9093     StringRef MyArch;
9094     switch (getToolChain().getArch()) {
9095     case llvm::Triple::arm:
9096       MyArch = "arm";
9097       break;
9098     case llvm::Triple::x86:
9099       MyArch = "i386";
9100       break;
9101     case llvm::Triple::x86_64:
9102       MyArch = "amd64";
9103       break;
9104     default:
9105       llvm_unreachable("Unsupported architecture");
9106     }
9107     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
9108   }
9109
9110   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9111     if (!Args.hasArg(options::OPT_shared))
9112       CmdArgs.push_back(
9113           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9114     else
9115       CmdArgs.push_back(
9116           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9117   }
9118
9119   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9120   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9121 }
9122
9123 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9124                                       const InputInfo &Output,
9125                                       const InputInfoList &Inputs,
9126                                       const ArgList &Args,
9127                                       const char *LinkingOutput) const {
9128   claimNoWarnArgs(Args);
9129   ArgStringList CmdArgs;
9130
9131   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
9132   // instruct as in the base system to assemble 32-bit code.
9133   switch (getToolChain().getArch()) {
9134   default:
9135     break;
9136   case llvm::Triple::x86:
9137     CmdArgs.push_back("--32");
9138     break;
9139   case llvm::Triple::ppc:
9140     CmdArgs.push_back("-a32");
9141     break;
9142   case llvm::Triple::mips:
9143   case llvm::Triple::mipsel:
9144   case llvm::Triple::mips64:
9145   case llvm::Triple::mips64el: {
9146     StringRef CPUName;
9147     StringRef ABIName;
9148     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9149
9150     CmdArgs.push_back("-march");
9151     CmdArgs.push_back(CPUName.data());
9152
9153     CmdArgs.push_back("-mabi");
9154     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
9155
9156     if (getToolChain().getArch() == llvm::Triple::mips ||
9157         getToolChain().getArch() == llvm::Triple::mips64)
9158       CmdArgs.push_back("-EB");
9159     else
9160       CmdArgs.push_back("-EL");
9161
9162     if (Arg *A = Args.getLastArg(options::OPT_G)) {
9163       StringRef v = A->getValue();
9164       CmdArgs.push_back(Args.MakeArgString("-G" + v));
9165       A->claim();
9166     }
9167
9168     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9169     break;
9170   }
9171   case llvm::Triple::arm:
9172   case llvm::Triple::armeb:
9173   case llvm::Triple::thumb:
9174   case llvm::Triple::thumbeb: {
9175     arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
9176
9177     if (ABI == arm::FloatABI::Hard)
9178       CmdArgs.push_back("-mfpu=vfp");
9179     else
9180       CmdArgs.push_back("-mfpu=softvfp");
9181
9182     switch (getToolChain().getTriple().getEnvironment()) {
9183     case llvm::Triple::GNUEABIHF:
9184     case llvm::Triple::GNUEABI:
9185     case llvm::Triple::EABI:
9186       CmdArgs.push_back("-meabi=5");
9187       break;
9188
9189     default:
9190       CmdArgs.push_back("-matpcs");
9191     }
9192     break;
9193   }
9194   case llvm::Triple::sparc:
9195   case llvm::Triple::sparcel:
9196   case llvm::Triple::sparcv9: {
9197     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9198     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9199     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9200     break;
9201   }
9202   }
9203
9204   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9205
9206   CmdArgs.push_back("-o");
9207   CmdArgs.push_back(Output.getFilename());
9208
9209   for (const auto &II : Inputs)
9210     CmdArgs.push_back(II.getFilename());
9211
9212   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9213   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9214 }
9215
9216 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9217                                    const InputInfo &Output,
9218                                    const InputInfoList &Inputs,
9219                                    const ArgList &Args,
9220                                    const char *LinkingOutput) const {
9221   const toolchains::FreeBSD &ToolChain =
9222       static_cast<const toolchains::FreeBSD &>(getToolChain());
9223   const Driver &D = ToolChain.getDriver();
9224   const llvm::Triple::ArchType Arch = ToolChain.getArch();
9225   const bool IsPIE =
9226       !Args.hasArg(options::OPT_shared) &&
9227       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
9228   ArgStringList CmdArgs;
9229
9230   // Silence warning for "clang -g foo.o -o foo"
9231   Args.ClaimAllArgs(options::OPT_g_Group);
9232   // and "clang -emit-llvm foo.o -o foo"
9233   Args.ClaimAllArgs(options::OPT_emit_llvm);
9234   // and for "clang -w foo.o -o foo". Other warning options are already
9235   // handled somewhere else.
9236   Args.ClaimAllArgs(options::OPT_w);
9237
9238   if (!D.SysRoot.empty())
9239     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9240
9241   if (IsPIE)
9242     CmdArgs.push_back("-pie");
9243
9244   CmdArgs.push_back("--eh-frame-hdr");
9245   if (Args.hasArg(options::OPT_static)) {
9246     CmdArgs.push_back("-Bstatic");
9247   } else {
9248     if (Args.hasArg(options::OPT_rdynamic))
9249       CmdArgs.push_back("-export-dynamic");
9250     if (Args.hasArg(options::OPT_shared)) {
9251       CmdArgs.push_back("-Bshareable");
9252     } else {
9253       CmdArgs.push_back("-dynamic-linker");
9254       CmdArgs.push_back("/libexec/ld-elf.so.1");
9255     }
9256     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
9257       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
9258           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
9259         CmdArgs.push_back("--hash-style=both");
9260       }
9261     }
9262     CmdArgs.push_back("--enable-new-dtags");
9263   }
9264
9265   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
9266   // instruct ld in the base system to link 32-bit code.
9267   if (Arch == llvm::Triple::x86) {
9268     CmdArgs.push_back("-m");
9269     CmdArgs.push_back("elf_i386_fbsd");
9270   }
9271
9272   if (Arch == llvm::Triple::ppc) {
9273     CmdArgs.push_back("-m");
9274     CmdArgs.push_back("elf32ppc_fbsd");
9275   }
9276
9277   if (Arg *A = Args.getLastArg(options::OPT_G)) {
9278     if (ToolChain.getArch() == llvm::Triple::mips ||
9279       ToolChain.getArch() == llvm::Triple::mipsel ||
9280       ToolChain.getArch() == llvm::Triple::mips64 ||
9281       ToolChain.getArch() == llvm::Triple::mips64el) {
9282       StringRef v = A->getValue();
9283       CmdArgs.push_back(Args.MakeArgString("-G" + v));
9284       A->claim();
9285     }
9286   }
9287
9288   if (Output.isFilename()) {
9289     CmdArgs.push_back("-o");
9290     CmdArgs.push_back(Output.getFilename());
9291   } else {
9292     assert(Output.isNothing() && "Invalid output.");
9293   }
9294
9295   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9296     const char *crt1 = nullptr;
9297     if (!Args.hasArg(options::OPT_shared)) {
9298       if (Args.hasArg(options::OPT_pg))
9299         crt1 = "gcrt1.o";
9300       else if (IsPIE)
9301         crt1 = "Scrt1.o";
9302       else
9303         crt1 = "crt1.o";
9304     }
9305     if (crt1)
9306       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
9307
9308     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9309
9310     const char *crtbegin = nullptr;
9311     if (Args.hasArg(options::OPT_static))
9312       crtbegin = "crtbeginT.o";
9313     else if (Args.hasArg(options::OPT_shared) || IsPIE)
9314       crtbegin = "crtbeginS.o";
9315     else
9316       crtbegin = "crtbegin.o";
9317
9318     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9319   }
9320
9321   Args.AddAllArgs(CmdArgs, options::OPT_L);
9322   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9323   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
9324   Args.AddAllArgs(CmdArgs, options::OPT_e);
9325   Args.AddAllArgs(CmdArgs, options::OPT_s);
9326   Args.AddAllArgs(CmdArgs, options::OPT_t);
9327   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
9328   Args.AddAllArgs(CmdArgs, options::OPT_r);
9329
9330   if (D.isUsingLTO())
9331     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
9332
9333   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
9334   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
9335
9336   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9337     addOpenMPRuntime(CmdArgs, ToolChain, Args);
9338     if (D.CCCIsCXX()) {
9339       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9340       if (Args.hasArg(options::OPT_pg))
9341         CmdArgs.push_back("-lm_p");
9342       else
9343         CmdArgs.push_back("-lm");
9344     }
9345     if (NeedsSanitizerDeps)
9346       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
9347     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
9348     // the default system libraries. Just mimic this for now.
9349     if (Args.hasArg(options::OPT_pg))
9350       CmdArgs.push_back("-lgcc_p");
9351     else
9352       CmdArgs.push_back("-lgcc");
9353     if (Args.hasArg(options::OPT_static)) {
9354       CmdArgs.push_back("-lgcc_eh");
9355     } else if (Args.hasArg(options::OPT_pg)) {
9356       CmdArgs.push_back("-lgcc_eh_p");
9357     } else {
9358       CmdArgs.push_back("--as-needed");
9359       CmdArgs.push_back("-lgcc_s");
9360       CmdArgs.push_back("--no-as-needed");
9361     }
9362
9363     if (Args.hasArg(options::OPT_pthread)) {
9364       if (Args.hasArg(options::OPT_pg))
9365         CmdArgs.push_back("-lpthread_p");
9366       else
9367         CmdArgs.push_back("-lpthread");
9368     }
9369
9370     if (Args.hasArg(options::OPT_pg)) {
9371       if (Args.hasArg(options::OPT_shared))
9372         CmdArgs.push_back("-lc");
9373       else
9374         CmdArgs.push_back("-lc_p");
9375       CmdArgs.push_back("-lgcc_p");
9376     } else {
9377       CmdArgs.push_back("-lc");
9378       CmdArgs.push_back("-lgcc");
9379     }
9380
9381     if (Args.hasArg(options::OPT_static)) {
9382       CmdArgs.push_back("-lgcc_eh");
9383     } else if (Args.hasArg(options::OPT_pg)) {
9384       CmdArgs.push_back("-lgcc_eh_p");
9385     } else {
9386       CmdArgs.push_back("--as-needed");
9387       CmdArgs.push_back("-lgcc_s");
9388       CmdArgs.push_back("--no-as-needed");
9389     }
9390   }
9391
9392   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9393     if (Args.hasArg(options::OPT_shared) || IsPIE)
9394       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
9395     else
9396       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
9397     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9398   }
9399
9400   ToolChain.addProfileRTLibs(Args, CmdArgs);
9401
9402   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9403   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9404 }
9405
9406 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9407                                      const InputInfo &Output,
9408                                      const InputInfoList &Inputs,
9409                                      const ArgList &Args,
9410                                      const char *LinkingOutput) const {
9411   claimNoWarnArgs(Args);
9412   ArgStringList CmdArgs;
9413
9414   // GNU as needs different flags for creating the correct output format
9415   // on architectures with different ABIs or optional feature sets.
9416   switch (getToolChain().getArch()) {
9417   case llvm::Triple::x86:
9418     CmdArgs.push_back("--32");
9419     break;
9420   case llvm::Triple::arm:
9421   case llvm::Triple::armeb:
9422   case llvm::Triple::thumb:
9423   case llvm::Triple::thumbeb: {
9424     StringRef MArch, MCPU;
9425     getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
9426     std::string Arch =
9427         arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
9428     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
9429     break;
9430   }
9431
9432   case llvm::Triple::mips:
9433   case llvm::Triple::mipsel:
9434   case llvm::Triple::mips64:
9435   case llvm::Triple::mips64el: {
9436     StringRef CPUName;
9437     StringRef ABIName;
9438     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9439
9440     CmdArgs.push_back("-march");
9441     CmdArgs.push_back(CPUName.data());
9442
9443     CmdArgs.push_back("-mabi");
9444     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
9445
9446     if (getToolChain().getArch() == llvm::Triple::mips ||
9447         getToolChain().getArch() == llvm::Triple::mips64)
9448       CmdArgs.push_back("-EB");
9449     else
9450       CmdArgs.push_back("-EL");
9451
9452     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9453     break;
9454   }
9455
9456   case llvm::Triple::sparc:
9457   case llvm::Triple::sparcel: {
9458     CmdArgs.push_back("-32");
9459     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9460     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9461     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9462     break;
9463   }
9464
9465   case llvm::Triple::sparcv9: {
9466     CmdArgs.push_back("-64");
9467     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9468     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9469     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9470     break;
9471   }
9472
9473   default:
9474     break;
9475   }
9476
9477   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9478
9479   CmdArgs.push_back("-o");
9480   CmdArgs.push_back(Output.getFilename());
9481
9482   for (const auto &II : Inputs)
9483     CmdArgs.push_back(II.getFilename());
9484
9485   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
9486   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9487 }
9488
9489 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9490                                   const InputInfo &Output,
9491                                   const InputInfoList &Inputs,
9492                                   const ArgList &Args,
9493                                   const char *LinkingOutput) const {
9494   const Driver &D = getToolChain().getDriver();
9495   ArgStringList CmdArgs;
9496
9497   if (!D.SysRoot.empty())
9498     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9499
9500   CmdArgs.push_back("--eh-frame-hdr");
9501   if (Args.hasArg(options::OPT_static)) {
9502     CmdArgs.push_back("-Bstatic");
9503   } else {
9504     if (Args.hasArg(options::OPT_rdynamic))
9505       CmdArgs.push_back("-export-dynamic");
9506     if (Args.hasArg(options::OPT_shared)) {
9507       CmdArgs.push_back("-Bshareable");
9508     } else {
9509       Args.AddAllArgs(CmdArgs, options::OPT_pie);
9510       CmdArgs.push_back("-dynamic-linker");
9511       CmdArgs.push_back("/libexec/ld.elf_so");
9512     }
9513   }
9514
9515   // Many NetBSD architectures support more than one ABI.
9516   // Determine the correct emulation for ld.
9517   switch (getToolChain().getArch()) {
9518   case llvm::Triple::x86:
9519     CmdArgs.push_back("-m");
9520     CmdArgs.push_back("elf_i386");
9521     break;
9522   case llvm::Triple::arm:
9523   case llvm::Triple::thumb:
9524     CmdArgs.push_back("-m");
9525     switch (getToolChain().getTriple().getEnvironment()) {
9526     case llvm::Triple::EABI:
9527     case llvm::Triple::GNUEABI:
9528       CmdArgs.push_back("armelf_nbsd_eabi");
9529       break;
9530     case llvm::Triple::EABIHF:
9531     case llvm::Triple::GNUEABIHF:
9532       CmdArgs.push_back("armelf_nbsd_eabihf");
9533       break;
9534     default:
9535       CmdArgs.push_back("armelf_nbsd");
9536       break;
9537     }
9538     break;
9539   case llvm::Triple::armeb:
9540   case llvm::Triple::thumbeb:
9541     arm::appendEBLinkFlags(Args, CmdArgs, getToolChain().getEffectiveTriple());
9542     CmdArgs.push_back("-m");
9543     switch (getToolChain().getTriple().getEnvironment()) {
9544     case llvm::Triple::EABI:
9545     case llvm::Triple::GNUEABI:
9546       CmdArgs.push_back("armelfb_nbsd_eabi");
9547       break;
9548     case llvm::Triple::EABIHF:
9549     case llvm::Triple::GNUEABIHF:
9550       CmdArgs.push_back("armelfb_nbsd_eabihf");
9551       break;
9552     default:
9553       CmdArgs.push_back("armelfb_nbsd");
9554       break;
9555     }
9556     break;
9557   case llvm::Triple::mips64:
9558   case llvm::Triple::mips64el:
9559     if (mips::hasMipsAbiArg(Args, "32")) {
9560       CmdArgs.push_back("-m");
9561       if (getToolChain().getArch() == llvm::Triple::mips64)
9562         CmdArgs.push_back("elf32btsmip");
9563       else
9564         CmdArgs.push_back("elf32ltsmip");
9565     } else if (mips::hasMipsAbiArg(Args, "64")) {
9566       CmdArgs.push_back("-m");
9567       if (getToolChain().getArch() == llvm::Triple::mips64)
9568         CmdArgs.push_back("elf64btsmip");
9569       else
9570         CmdArgs.push_back("elf64ltsmip");
9571     }
9572     break;
9573   case llvm::Triple::ppc:
9574     CmdArgs.push_back("-m");
9575     CmdArgs.push_back("elf32ppc_nbsd");
9576     break;
9577
9578   case llvm::Triple::ppc64:
9579   case llvm::Triple::ppc64le:
9580     CmdArgs.push_back("-m");
9581     CmdArgs.push_back("elf64ppc");
9582     break;
9583
9584   case llvm::Triple::sparc:
9585     CmdArgs.push_back("-m");
9586     CmdArgs.push_back("elf32_sparc");
9587     break;
9588
9589   case llvm::Triple::sparcv9:
9590     CmdArgs.push_back("-m");
9591     CmdArgs.push_back("elf64_sparc");
9592     break;
9593
9594   default:
9595     break;
9596   }
9597
9598   if (Output.isFilename()) {
9599     CmdArgs.push_back("-o");
9600     CmdArgs.push_back(Output.getFilename());
9601   } else {
9602     assert(Output.isNothing() && "Invalid output.");
9603   }
9604
9605   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9606     if (!Args.hasArg(options::OPT_shared)) {
9607       CmdArgs.push_back(
9608           Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
9609     }
9610     CmdArgs.push_back(
9611         Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9612     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
9613       CmdArgs.push_back(
9614           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9615     } else {
9616       CmdArgs.push_back(
9617           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9618     }
9619   }
9620
9621   Args.AddAllArgs(CmdArgs, options::OPT_L);
9622   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
9623   Args.AddAllArgs(CmdArgs, options::OPT_e);
9624   Args.AddAllArgs(CmdArgs, options::OPT_s);
9625   Args.AddAllArgs(CmdArgs, options::OPT_t);
9626   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
9627   Args.AddAllArgs(CmdArgs, options::OPT_r);
9628
9629   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
9630
9631   unsigned Major, Minor, Micro;
9632   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
9633   bool useLibgcc = true;
9634   if (Major >= 7 || Major == 0) {
9635     switch (getToolChain().getArch()) {
9636     case llvm::Triple::aarch64:
9637     case llvm::Triple::arm:
9638     case llvm::Triple::armeb:
9639     case llvm::Triple::thumb:
9640     case llvm::Triple::thumbeb:
9641     case llvm::Triple::ppc:
9642     case llvm::Triple::ppc64:
9643     case llvm::Triple::ppc64le:
9644     case llvm::Triple::sparc:
9645     case llvm::Triple::sparcv9:
9646     case llvm::Triple::x86:
9647     case llvm::Triple::x86_64:
9648       useLibgcc = false;
9649       break;
9650     default:
9651       break;
9652     }
9653   }
9654
9655   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9656     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
9657     if (D.CCCIsCXX()) {
9658       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9659       CmdArgs.push_back("-lm");
9660     }
9661     if (Args.hasArg(options::OPT_pthread))
9662       CmdArgs.push_back("-lpthread");
9663     CmdArgs.push_back("-lc");
9664
9665     if (useLibgcc) {
9666       if (Args.hasArg(options::OPT_static)) {
9667         // libgcc_eh depends on libc, so resolve as much as possible,
9668         // pull in any new requirements from libc and then get the rest
9669         // of libgcc.
9670         CmdArgs.push_back("-lgcc_eh");
9671         CmdArgs.push_back("-lc");
9672         CmdArgs.push_back("-lgcc");
9673       } else {
9674         CmdArgs.push_back("-lgcc");
9675         CmdArgs.push_back("--as-needed");
9676         CmdArgs.push_back("-lgcc_s");
9677         CmdArgs.push_back("--no-as-needed");
9678       }
9679     }
9680   }
9681
9682   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9683     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9684       CmdArgs.push_back(
9685           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9686     else
9687       CmdArgs.push_back(
9688           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9689     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9690   }
9691
9692   getToolChain().addProfileRTLibs(Args, CmdArgs);
9693
9694   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9695   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9696 }
9697
9698 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9699                                        const InputInfo &Output,
9700                                        const InputInfoList &Inputs,
9701                                        const ArgList &Args,
9702                                        const char *LinkingOutput) const {
9703   claimNoWarnArgs(Args);
9704
9705   ArgStringList CmdArgs;
9706
9707   llvm::Reloc::Model RelocationModel;
9708   unsigned PICLevel;
9709   bool IsPIE;
9710   std::tie(RelocationModel, PICLevel, IsPIE) =
9711       ParsePICArgs(getToolChain(), Args);
9712
9713   switch (getToolChain().getArch()) {
9714   default:
9715     break;
9716   // Add --32/--64 to make sure we get the format we want.
9717   // This is incomplete
9718   case llvm::Triple::x86:
9719     CmdArgs.push_back("--32");
9720     break;
9721   case llvm::Triple::x86_64:
9722     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
9723       CmdArgs.push_back("--x32");
9724     else
9725       CmdArgs.push_back("--64");
9726     break;
9727   case llvm::Triple::ppc:
9728     CmdArgs.push_back("-a32");
9729     CmdArgs.push_back("-mppc");
9730     CmdArgs.push_back("-many");
9731     break;
9732   case llvm::Triple::ppc64:
9733     CmdArgs.push_back("-a64");
9734     CmdArgs.push_back("-mppc64");
9735     CmdArgs.push_back("-many");
9736     break;
9737   case llvm::Triple::ppc64le:
9738     CmdArgs.push_back("-a64");
9739     CmdArgs.push_back("-mppc64");
9740     CmdArgs.push_back("-many");
9741     CmdArgs.push_back("-mlittle-endian");
9742     break;
9743   case llvm::Triple::sparc:
9744   case llvm::Triple::sparcel: {
9745     CmdArgs.push_back("-32");
9746     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9747     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9748     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9749     break;
9750   }
9751   case llvm::Triple::sparcv9: {
9752     CmdArgs.push_back("-64");
9753     std::string CPU = getCPUName(Args, getToolChain().getTriple());
9754     CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9755     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9756     break;
9757   }
9758   case llvm::Triple::arm:
9759   case llvm::Triple::armeb:
9760   case llvm::Triple::thumb:
9761   case llvm::Triple::thumbeb: {
9762     const llvm::Triple &Triple2 = getToolChain().getTriple();
9763     switch (Triple2.getSubArch()) {
9764     case llvm::Triple::ARMSubArch_v7:
9765       CmdArgs.push_back("-mfpu=neon");
9766       break;
9767     case llvm::Triple::ARMSubArch_v8:
9768       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
9769       break;
9770     default:
9771       break;
9772     }
9773
9774     switch (arm::getARMFloatABI(getToolChain(), Args)) {
9775     case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
9776     case arm::FloatABI::Soft:
9777       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
9778       break;
9779     case arm::FloatABI::SoftFP:
9780       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
9781       break;
9782     case arm::FloatABI::Hard:
9783       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
9784       break;
9785     }
9786
9787     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
9788
9789     // FIXME: remove krait check when GNU tools support krait cpu
9790     // for now replace it with -mcpu=cortex-a15 to avoid a lower
9791     // march from being picked in the absence of a cpu flag.
9792     Arg *A;
9793     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
9794         StringRef(A->getValue()).equals_lower("krait"))
9795       CmdArgs.push_back("-mcpu=cortex-a15");
9796     else
9797       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
9798     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
9799     break;
9800   }
9801   case llvm::Triple::mips:
9802   case llvm::Triple::mipsel:
9803   case llvm::Triple::mips64:
9804   case llvm::Triple::mips64el: {
9805     StringRef CPUName;
9806     StringRef ABIName;
9807     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9808     ABIName = getGnuCompatibleMipsABIName(ABIName);
9809
9810     CmdArgs.push_back("-march");
9811     CmdArgs.push_back(CPUName.data());
9812
9813     CmdArgs.push_back("-mabi");
9814     CmdArgs.push_back(ABIName.data());
9815
9816     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
9817     // or -mshared (not implemented) is in effect.
9818     if (RelocationModel == llvm::Reloc::Static)
9819       CmdArgs.push_back("-mno-shared");
9820
9821     // LLVM doesn't support -mplt yet and acts as if it is always given.
9822     // However, -mplt has no effect with the N64 ABI.
9823     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
9824
9825     if (getToolChain().getArch() == llvm::Triple::mips ||
9826         getToolChain().getArch() == llvm::Triple::mips64)
9827       CmdArgs.push_back("-EB");
9828     else
9829       CmdArgs.push_back("-EL");
9830
9831     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
9832       if (StringRef(A->getValue()) == "2008")
9833         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
9834     }
9835
9836     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
9837     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
9838                                  options::OPT_mfp64)) {
9839       A->claim();
9840       A->render(Args, CmdArgs);
9841     } else if (mips::shouldUseFPXX(
9842                    Args, getToolChain().getTriple(), CPUName, ABIName,
9843                    getMipsFloatABI(getToolChain().getDriver(), Args)))
9844       CmdArgs.push_back("-mfpxx");
9845
9846     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
9847     // -mno-mips16 is actually -no-mips16.
9848     if (Arg *A =
9849             Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
9850       if (A->getOption().matches(options::OPT_mips16)) {
9851         A->claim();
9852         A->render(Args, CmdArgs);
9853       } else {
9854         A->claim();
9855         CmdArgs.push_back("-no-mips16");
9856       }
9857     }
9858
9859     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
9860                     options::OPT_mno_micromips);
9861     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
9862     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
9863
9864     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
9865       // Do not use AddLastArg because not all versions of MIPS assembler
9866       // support -mmsa / -mno-msa options.
9867       if (A->getOption().matches(options::OPT_mmsa))
9868         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
9869     }
9870
9871     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
9872                     options::OPT_msoft_float);
9873
9874     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
9875                     options::OPT_msingle_float);
9876
9877     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
9878                     options::OPT_mno_odd_spreg);
9879
9880     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9881     break;
9882   }
9883   case llvm::Triple::systemz: {
9884     // Always pass an -march option, since our default of z10 is later
9885     // than the GNU assembler's default.
9886     StringRef CPUName = getSystemZTargetCPU(Args);
9887     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
9888     break;
9889   }
9890   }
9891
9892   Args.AddAllArgs(CmdArgs, options::OPT_I);
9893   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9894
9895   CmdArgs.push_back("-o");
9896   CmdArgs.push_back(Output.getFilename());
9897
9898   for (const auto &II : Inputs)
9899     CmdArgs.push_back(II.getFilename());
9900
9901   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9902   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9903
9904   // Handle the debug info splitting at object creation time if we're
9905   // creating an object.
9906   // TODO: Currently only works on linux with newer objcopy.
9907   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
9908       getToolChain().getTriple().isOSLinux())
9909     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9910                    SplitDebugName(Args, Inputs[0]));
9911 }
9912
9913 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
9914                       ArgStringList &CmdArgs, const ArgList &Args) {
9915   bool isAndroid = Triple.isAndroid();
9916   bool isCygMing = Triple.isOSCygMing();
9917   bool IsIAMCU = Triple.isOSIAMCU();
9918   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
9919                       Args.hasArg(options::OPT_static);
9920   if (!D.CCCIsCXX())
9921     CmdArgs.push_back("-lgcc");
9922
9923   if (StaticLibgcc || isAndroid) {
9924     if (D.CCCIsCXX())
9925       CmdArgs.push_back("-lgcc");
9926   } else {
9927     if (!D.CCCIsCXX() && !isCygMing)
9928       CmdArgs.push_back("--as-needed");
9929     CmdArgs.push_back("-lgcc_s");
9930     if (!D.CCCIsCXX() && !isCygMing)
9931       CmdArgs.push_back("--no-as-needed");
9932   }
9933
9934   if (StaticLibgcc && !isAndroid && !IsIAMCU)
9935     CmdArgs.push_back("-lgcc_eh");
9936   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
9937     CmdArgs.push_back("-lgcc");
9938
9939   // According to Android ABI, we have to link with libdl if we are
9940   // linking with non-static libgcc.
9941   //
9942   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
9943   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
9944   if (isAndroid && !StaticLibgcc)
9945     CmdArgs.push_back("-ldl");
9946 }
9947
9948 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
9949                            ArgStringList &CmdArgs, const ArgList &Args) {
9950   // Make use of compiler-rt if --rtlib option is used
9951   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
9952
9953   switch (RLT) {
9954   case ToolChain::RLT_CompilerRT:
9955     switch (TC.getTriple().getOS()) {
9956     default:
9957       llvm_unreachable("unsupported OS");
9958     case llvm::Triple::Win32:
9959     case llvm::Triple::Linux:
9960     case llvm::Triple::Fuchsia:
9961       addClangRT(TC, Args, CmdArgs);
9962       break;
9963     }
9964     break;
9965   case ToolChain::RLT_Libgcc:
9966     // Make sure libgcc is not used under MSVC environment by default
9967     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
9968       // Issue error diagnostic if libgcc is explicitly specified
9969       // through command line as --rtlib option argument.
9970       if (Args.hasArg(options::OPT_rtlib_EQ)) {
9971         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
9972             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
9973       }
9974     } else
9975       AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
9976     break;
9977   }
9978 }
9979
9980 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
9981   switch (T.getArch()) {
9982   case llvm::Triple::x86:
9983     if (T.isOSIAMCU())
9984       return "elf_iamcu";
9985     return "elf_i386";
9986   case llvm::Triple::aarch64:
9987     return "aarch64linux";
9988   case llvm::Triple::aarch64_be:
9989     return "aarch64_be_linux";
9990   case llvm::Triple::arm:
9991   case llvm::Triple::thumb:
9992     return "armelf_linux_eabi";
9993   case llvm::Triple::armeb:
9994   case llvm::Triple::thumbeb:
9995     return "armelfb_linux_eabi";
9996   case llvm::Triple::ppc:
9997     return "elf32ppclinux";
9998   case llvm::Triple::ppc64:
9999     return "elf64ppc";
10000   case llvm::Triple::ppc64le:
10001     return "elf64lppc";
10002   case llvm::Triple::sparc:
10003   case llvm::Triple::sparcel:
10004     return "elf32_sparc";
10005   case llvm::Triple::sparcv9:
10006     return "elf64_sparc";
10007   case llvm::Triple::mips:
10008     return "elf32btsmip";
10009   case llvm::Triple::mipsel:
10010     return "elf32ltsmip";
10011   case llvm::Triple::mips64:
10012     if (mips::hasMipsAbiArg(Args, "n32"))
10013       return "elf32btsmipn32";
10014     return "elf64btsmip";
10015   case llvm::Triple::mips64el:
10016     if (mips::hasMipsAbiArg(Args, "n32"))
10017       return "elf32ltsmipn32";
10018     return "elf64ltsmip";
10019   case llvm::Triple::systemz:
10020     return "elf64_s390";
10021   case llvm::Triple::x86_64:
10022     if (T.getEnvironment() == llvm::Triple::GNUX32)
10023       return "elf32_x86_64";
10024     return "elf_x86_64";
10025   default:
10026     return nullptr;
10027   }
10028 }
10029
10030 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10031                                     const InputInfo &Output,
10032                                     const InputInfoList &Inputs,
10033                                     const ArgList &Args,
10034                                     const char *LinkingOutput) const {
10035   const toolchains::Linux &ToolChain =
10036       static_cast<const toolchains::Linux &>(getToolChain());
10037   const Driver &D = ToolChain.getDriver();
10038
10039   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
10040
10041   const llvm::Triple::ArchType Arch = ToolChain.getArch();
10042   const bool isAndroid = ToolChain.getTriple().isAndroid();
10043   const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
10044   const bool IsPIE =
10045       !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
10046       (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
10047   const bool HasCRTBeginEndFiles =
10048       ToolChain.getTriple().hasEnvironment() ||
10049       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
10050
10051   ArgStringList CmdArgs;
10052
10053   // Silence warning for "clang -g foo.o -o foo"
10054   Args.ClaimAllArgs(options::OPT_g_Group);
10055   // and "clang -emit-llvm foo.o -o foo"
10056   Args.ClaimAllArgs(options::OPT_emit_llvm);
10057   // and for "clang -w foo.o -o foo". Other warning options are already
10058   // handled somewhere else.
10059   Args.ClaimAllArgs(options::OPT_w);
10060
10061   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
10062   if (llvm::sys::path::filename(Exec) == "lld") {
10063     CmdArgs.push_back("-flavor");
10064     CmdArgs.push_back("old-gnu");
10065     CmdArgs.push_back("-target");
10066     CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
10067   }
10068
10069   if (!D.SysRoot.empty())
10070     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10071
10072   if (IsPIE)
10073     CmdArgs.push_back("-pie");
10074
10075   if (Args.hasArg(options::OPT_rdynamic))
10076     CmdArgs.push_back("-export-dynamic");
10077
10078   if (Args.hasArg(options::OPT_s))
10079     CmdArgs.push_back("-s");
10080
10081   if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
10082     arm::appendEBLinkFlags(Args, CmdArgs, Triple);
10083
10084   // Most Android ARM64 targets should enable the linker fix for erratum
10085   // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
10086   if (Arch == llvm::Triple::aarch64 && isAndroid) {
10087     std::string CPU = getCPUName(Args, Triple);
10088     if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
10089       CmdArgs.push_back("--fix-cortex-a53-843419");
10090   }
10091
10092   for (const auto &Opt : ToolChain.ExtraOpts)
10093     CmdArgs.push_back(Opt.c_str());
10094
10095   if (!Args.hasArg(options::OPT_static)) {
10096     CmdArgs.push_back("--eh-frame-hdr");
10097   }
10098
10099   if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
10100     CmdArgs.push_back("-m");
10101     CmdArgs.push_back(LDMOption);
10102   } else {
10103     D.Diag(diag::err_target_unknown_triple) << Triple.str();
10104     return;
10105   }
10106
10107   if (Args.hasArg(options::OPT_static)) {
10108     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
10109         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
10110       CmdArgs.push_back("-Bstatic");
10111     else
10112       CmdArgs.push_back("-static");
10113   } else if (Args.hasArg(options::OPT_shared)) {
10114     CmdArgs.push_back("-shared");
10115   }
10116
10117   if (!Args.hasArg(options::OPT_static)) {
10118     if (Args.hasArg(options::OPT_rdynamic))
10119       CmdArgs.push_back("-export-dynamic");
10120
10121     if (!Args.hasArg(options::OPT_shared)) {
10122       const std::string Loader =
10123           D.DyldPrefix + ToolChain.getDynamicLinker(Args);
10124       CmdArgs.push_back("-dynamic-linker");
10125       CmdArgs.push_back(Args.MakeArgString(Loader));
10126     }
10127   }
10128
10129   CmdArgs.push_back("-o");
10130   CmdArgs.push_back(Output.getFilename());
10131
10132   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10133     if (!isAndroid && !IsIAMCU) {
10134       const char *crt1 = nullptr;
10135       if (!Args.hasArg(options::OPT_shared)) {
10136         if (Args.hasArg(options::OPT_pg))
10137           crt1 = "gcrt1.o";
10138         else if (IsPIE)
10139           crt1 = "Scrt1.o";
10140         else
10141           crt1 = "crt1.o";
10142       }
10143       if (crt1)
10144         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10145
10146       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10147     }
10148
10149     if (IsIAMCU)
10150       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
10151     else {
10152       const char *crtbegin;
10153       if (Args.hasArg(options::OPT_static))
10154         crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
10155       else if (Args.hasArg(options::OPT_shared))
10156         crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
10157       else if (IsPIE)
10158         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
10159       else
10160         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
10161
10162       if (HasCRTBeginEndFiles)
10163         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10164     }
10165
10166     // Add crtfastmath.o if available and fast math is enabled.
10167     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
10168   }
10169
10170   Args.AddAllArgs(CmdArgs, options::OPT_L);
10171   Args.AddAllArgs(CmdArgs, options::OPT_u);
10172
10173   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10174
10175   if (D.isUsingLTO())
10176     AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
10177
10178   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10179     CmdArgs.push_back("--no-demangle");
10180
10181   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
10182   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
10183   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
10184   // The profile runtime also needs access to system libraries.
10185   getToolChain().addProfileRTLibs(Args, CmdArgs);
10186
10187   if (D.CCCIsCXX() &&
10188       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10189     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10190                                !Args.hasArg(options::OPT_static);
10191     if (OnlyLibstdcxxStatic)
10192       CmdArgs.push_back("-Bstatic");
10193     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10194     if (OnlyLibstdcxxStatic)
10195       CmdArgs.push_back("-Bdynamic");
10196     CmdArgs.push_back("-lm");
10197   }
10198   // Silence warnings when linking C code with a C++ '-stdlib' argument.
10199   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
10200
10201   if (!Args.hasArg(options::OPT_nostdlib)) {
10202     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10203       if (Args.hasArg(options::OPT_static))
10204         CmdArgs.push_back("--start-group");
10205
10206       if (NeedsSanitizerDeps)
10207         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
10208
10209       if (NeedsXRayDeps)
10210         linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
10211
10212       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
10213                          Args.hasArg(options::OPT_pthreads);
10214
10215       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10216                        options::OPT_fno_openmp, false)) {
10217         // OpenMP runtimes implies pthreads when using the GNU toolchain.
10218         // FIXME: Does this really make sense for all GNU toolchains?
10219         WantPthread = true;
10220
10221         // Also link the particular OpenMP runtimes.
10222         switch (ToolChain.getDriver().getOpenMPRuntime(Args)) {
10223         case Driver::OMPRT_OMP:
10224           CmdArgs.push_back("-lomp");
10225           break;
10226         case Driver::OMPRT_GOMP:
10227           CmdArgs.push_back("-lgomp");
10228
10229           // FIXME: Exclude this for platforms with libgomp that don't require
10230           // librt. Most modern Linux platforms require it, but some may not.
10231           CmdArgs.push_back("-lrt");
10232           break;
10233         case Driver::OMPRT_IOMP5:
10234           CmdArgs.push_back("-liomp5");
10235           break;
10236         case Driver::OMPRT_Unknown:
10237           // Already diagnosed.
10238           break;
10239         }
10240         if (JA.isHostOffloading(Action::OFK_OpenMP))
10241           CmdArgs.push_back("-lomptarget");
10242       }
10243
10244       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
10245
10246       if (WantPthread && !isAndroid)
10247         CmdArgs.push_back("-lpthread");
10248
10249       if (Args.hasArg(options::OPT_fsplit_stack))
10250         CmdArgs.push_back("--wrap=pthread_create");
10251
10252       CmdArgs.push_back("-lc");
10253
10254       // Add IAMCU specific libs, if needed.
10255       if (IsIAMCU)
10256         CmdArgs.push_back("-lgloss");
10257
10258       if (Args.hasArg(options::OPT_static))
10259         CmdArgs.push_back("--end-group");
10260       else
10261         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
10262
10263       // Add IAMCU specific libs (outside the group), if needed.
10264       if (IsIAMCU) {
10265         CmdArgs.push_back("--as-needed");
10266         CmdArgs.push_back("-lsoftfp");
10267         CmdArgs.push_back("--no-as-needed");
10268       }
10269     }
10270
10271     if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
10272       const char *crtend;
10273       if (Args.hasArg(options::OPT_shared))
10274         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
10275       else if (IsPIE)
10276         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
10277       else
10278         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
10279
10280       if (HasCRTBeginEndFiles)
10281         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
10282       if (!isAndroid)
10283         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10284     }
10285   }
10286
10287   // Add OpenMP offloading linker script args if required.
10288   AddOpenMPLinkerScript(getToolChain(), C, Output, Inputs, Args, CmdArgs, JA);
10289
10290   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10291 }
10292
10293 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
10294 // for the various SFI requirements like register masking. The assembly tool
10295 // inserts the file containing the macros as an input into all the assembly
10296 // jobs.
10297 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
10298                                            const InputInfo &Output,
10299                                            const InputInfoList &Inputs,
10300                                            const ArgList &Args,
10301                                            const char *LinkingOutput) const {
10302   const toolchains::NaClToolChain &ToolChain =
10303       static_cast<const toolchains::NaClToolChain &>(getToolChain());
10304   InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
10305                        "nacl-arm-macros.s");
10306   InputInfoList NewInputs;
10307   NewInputs.push_back(NaClMacros);
10308   NewInputs.append(Inputs.begin(), Inputs.end());
10309   gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
10310                                     LinkingOutput);
10311 }
10312
10313 // This is quite similar to gnutools::Linker::ConstructJob with changes that
10314 // we use static by default, do not yet support sanitizers or LTO, and a few
10315 // others. Eventually we can support more of that and hopefully migrate back
10316 // to gnutools::Linker.
10317 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10318                                      const InputInfo &Output,
10319                                      const InputInfoList &Inputs,
10320                                      const ArgList &Args,
10321                                      const char *LinkingOutput) const {
10322
10323   const toolchains::NaClToolChain &ToolChain =
10324       static_cast<const toolchains::NaClToolChain &>(getToolChain());
10325   const Driver &D = ToolChain.getDriver();
10326   const llvm::Triple::ArchType Arch = ToolChain.getArch();
10327   const bool IsStatic =
10328       !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
10329
10330   ArgStringList CmdArgs;
10331
10332   // Silence warning for "clang -g foo.o -o foo"
10333   Args.ClaimAllArgs(options::OPT_g_Group);
10334   // and "clang -emit-llvm foo.o -o foo"
10335   Args.ClaimAllArgs(options::OPT_emit_llvm);
10336   // and for "clang -w foo.o -o foo". Other warning options are already
10337   // handled somewhere else.
10338   Args.ClaimAllArgs(options::OPT_w);
10339
10340   if (!D.SysRoot.empty())
10341     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10342
10343   if (Args.hasArg(options::OPT_rdynamic))
10344     CmdArgs.push_back("-export-dynamic");
10345
10346   if (Args.hasArg(options::OPT_s))
10347     CmdArgs.push_back("-s");
10348
10349   // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
10350   // from there is --build-id, which we do want.
10351   CmdArgs.push_back("--build-id");
10352
10353   if (!IsStatic)
10354     CmdArgs.push_back("--eh-frame-hdr");
10355
10356   CmdArgs.push_back("-m");
10357   if (Arch == llvm::Triple::x86)
10358     CmdArgs.push_back("elf_i386_nacl");
10359   else if (Arch == llvm::Triple::arm)
10360     CmdArgs.push_back("armelf_nacl");
10361   else if (Arch == llvm::Triple::x86_64)
10362     CmdArgs.push_back("elf_x86_64_nacl");
10363   else if (Arch == llvm::Triple::mipsel)
10364     CmdArgs.push_back("mipselelf_nacl");
10365   else
10366     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
10367                                               << "Native Client";
10368
10369   if (IsStatic)
10370     CmdArgs.push_back("-static");
10371   else if (Args.hasArg(options::OPT_shared))
10372     CmdArgs.push_back("-shared");
10373
10374   CmdArgs.push_back("-o");
10375   CmdArgs.push_back(Output.getFilename());
10376   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10377     if (!Args.hasArg(options::OPT_shared))
10378       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
10379     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10380
10381     const char *crtbegin;
10382     if (IsStatic)
10383       crtbegin = "crtbeginT.o";
10384     else if (Args.hasArg(options::OPT_shared))
10385       crtbegin = "crtbeginS.o";
10386     else
10387       crtbegin = "crtbegin.o";
10388     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10389   }
10390
10391   Args.AddAllArgs(CmdArgs, options::OPT_L);
10392   Args.AddAllArgs(CmdArgs, options::OPT_u);
10393
10394   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10395
10396   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10397     CmdArgs.push_back("--no-demangle");
10398
10399   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
10400
10401   if (D.CCCIsCXX() &&
10402       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10403     bool OnlyLibstdcxxStatic =
10404         Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
10405     if (OnlyLibstdcxxStatic)
10406       CmdArgs.push_back("-Bstatic");
10407     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10408     if (OnlyLibstdcxxStatic)
10409       CmdArgs.push_back("-Bdynamic");
10410     CmdArgs.push_back("-lm");
10411   }
10412
10413   if (!Args.hasArg(options::OPT_nostdlib)) {
10414     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10415       // Always use groups, since it has no effect on dynamic libraries.
10416       CmdArgs.push_back("--start-group");
10417       CmdArgs.push_back("-lc");
10418       // NaCl's libc++ currently requires libpthread, so just always include it
10419       // in the group for C++.
10420       if (Args.hasArg(options::OPT_pthread) ||
10421           Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
10422         // Gold, used by Mips, handles nested groups differently than ld, and
10423         // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
10424         // which is not a desired behaviour here.
10425         // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
10426         if (getToolChain().getArch() == llvm::Triple::mipsel)
10427           CmdArgs.push_back("-lnacl");
10428
10429         CmdArgs.push_back("-lpthread");
10430       }
10431
10432       CmdArgs.push_back("-lgcc");
10433       CmdArgs.push_back("--as-needed");
10434       if (IsStatic)
10435         CmdArgs.push_back("-lgcc_eh");
10436       else
10437         CmdArgs.push_back("-lgcc_s");
10438       CmdArgs.push_back("--no-as-needed");
10439
10440       // Mips needs to create and use pnacl_legacy library that contains
10441       // definitions from bitcode/pnaclmm.c and definitions for
10442       // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
10443       if (getToolChain().getArch() == llvm::Triple::mipsel)
10444         CmdArgs.push_back("-lpnacl_legacy");
10445
10446       CmdArgs.push_back("--end-group");
10447     }
10448
10449     if (!Args.hasArg(options::OPT_nostartfiles)) {
10450       const char *crtend;
10451       if (Args.hasArg(options::OPT_shared))
10452         crtend = "crtendS.o";
10453       else
10454         crtend = "crtend.o";
10455
10456       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
10457       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10458     }
10459   }
10460
10461   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
10462   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10463 }
10464
10465 void fuchsia::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10466                                    const InputInfo &Output,
10467                                    const InputInfoList &Inputs,
10468                                    const ArgList &Args,
10469                                    const char *LinkingOutput) const {
10470   const toolchains::Fuchsia &ToolChain =
10471       static_cast<const toolchains::Fuchsia &>(getToolChain());
10472   const Driver &D = ToolChain.getDriver();
10473
10474   ArgStringList CmdArgs;
10475
10476   // Silence warning for "clang -g foo.o -o foo"
10477   Args.ClaimAllArgs(options::OPT_g_Group);
10478   // and "clang -emit-llvm foo.o -o foo"
10479   Args.ClaimAllArgs(options::OPT_emit_llvm);
10480   // and for "clang -w foo.o -o foo". Other warning options are already
10481   // handled somewhere else.
10482   Args.ClaimAllArgs(options::OPT_w);
10483
10484   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
10485   if (llvm::sys::path::stem(Exec).equals_lower("lld")) {
10486     CmdArgs.push_back("-flavor");
10487     CmdArgs.push_back("gnu");
10488   }
10489
10490   if (!D.SysRoot.empty())
10491     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10492
10493   if (!Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_r))
10494     CmdArgs.push_back("-pie");
10495
10496   if (Args.hasArg(options::OPT_rdynamic))
10497     CmdArgs.push_back("-export-dynamic");
10498
10499   if (Args.hasArg(options::OPT_s))
10500     CmdArgs.push_back("-s");
10501
10502   if (Args.hasArg(options::OPT_r))
10503     CmdArgs.push_back("-r");
10504   else
10505     CmdArgs.push_back("--build-id");
10506
10507   if (!Args.hasArg(options::OPT_static))
10508     CmdArgs.push_back("--eh-frame-hdr");
10509
10510   if (Args.hasArg(options::OPT_static))
10511     CmdArgs.push_back("-Bstatic");
10512   else if (Args.hasArg(options::OPT_shared))
10513     CmdArgs.push_back("-shared");
10514
10515   if (!Args.hasArg(options::OPT_static)) {
10516     if (Args.hasArg(options::OPT_rdynamic))
10517       CmdArgs.push_back("-export-dynamic");
10518
10519     if (!Args.hasArg(options::OPT_shared)) {
10520       CmdArgs.push_back("-dynamic-linker");
10521       CmdArgs.push_back(Args.MakeArgString(D.DyldPrefix + "ld.so.1"));
10522     }
10523   }
10524
10525   CmdArgs.push_back("-o");
10526   CmdArgs.push_back(Output.getFilename());
10527
10528   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10529     if (!Args.hasArg(options::OPT_shared)) {
10530       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
10531     }
10532   }
10533
10534   Args.AddAllArgs(CmdArgs, options::OPT_L);
10535   Args.AddAllArgs(CmdArgs, options::OPT_u);
10536
10537   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10538
10539   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
10540
10541   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10542     if (Args.hasArg(options::OPT_static))
10543       CmdArgs.push_back("-Bdynamic");
10544
10545     if (D.CCCIsCXX()) {
10546       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10547                                  !Args.hasArg(options::OPT_static);
10548       if (OnlyLibstdcxxStatic)
10549         CmdArgs.push_back("-Bstatic");
10550       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10551       if (OnlyLibstdcxxStatic)
10552         CmdArgs.push_back("-Bdynamic");
10553       CmdArgs.push_back("-lm");
10554     }
10555
10556     AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
10557
10558     if (Args.hasArg(options::OPT_pthread) ||
10559         Args.hasArg(options::OPT_pthreads))
10560       CmdArgs.push_back("-lpthread");
10561
10562     if (Args.hasArg(options::OPT_fsplit_stack))
10563       CmdArgs.push_back("--wrap=pthread_create");
10564
10565     CmdArgs.push_back("-lc");
10566   }
10567
10568   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10569 }
10570
10571 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10572                                     const InputInfo &Output,
10573                                     const InputInfoList &Inputs,
10574                                     const ArgList &Args,
10575                                     const char *LinkingOutput) const {
10576   claimNoWarnArgs(Args);
10577   ArgStringList CmdArgs;
10578
10579   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10580
10581   CmdArgs.push_back("-o");
10582   CmdArgs.push_back(Output.getFilename());
10583
10584   for (const auto &II : Inputs)
10585     CmdArgs.push_back(II.getFilename());
10586
10587   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10588   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10589 }
10590
10591 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10592                                  const InputInfo &Output,
10593                                  const InputInfoList &Inputs,
10594                                  const ArgList &Args,
10595                                  const char *LinkingOutput) const {
10596   const Driver &D = getToolChain().getDriver();
10597   ArgStringList CmdArgs;
10598
10599   if (Output.isFilename()) {
10600     CmdArgs.push_back("-o");
10601     CmdArgs.push_back(Output.getFilename());
10602   } else {
10603     assert(Output.isNothing() && "Invalid output.");
10604   }
10605
10606   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10607     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
10608     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
10609     CmdArgs.push_back(
10610         Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
10611     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
10612   }
10613
10614   Args.AddAllArgs(CmdArgs,
10615                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
10616
10617   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
10618
10619   getToolChain().addProfileRTLibs(Args, CmdArgs);
10620
10621   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10622     if (D.CCCIsCXX()) {
10623       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
10624       CmdArgs.push_back("-lm");
10625     }
10626   }
10627
10628   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10629     if (Args.hasArg(options::OPT_pthread))
10630       CmdArgs.push_back("-lpthread");
10631     CmdArgs.push_back("-lc");
10632     CmdArgs.push_back("-lCompilerRT-Generic");
10633     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
10634     CmdArgs.push_back(
10635         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
10636   }
10637
10638   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
10639   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10640 }
10641
10642 /// DragonFly Tools
10643
10644 // For now, DragonFly Assemble does just about the same as for
10645 // FreeBSD, but this may change soon.
10646 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10647                                         const InputInfo &Output,
10648                                         const InputInfoList &Inputs,
10649                                         const ArgList &Args,
10650                                         const char *LinkingOutput) const {
10651   claimNoWarnArgs(Args);
10652   ArgStringList CmdArgs;
10653
10654   // When building 32-bit code on DragonFly/pc64, we have to explicitly
10655   // instruct as in the base system to assemble 32-bit code.
10656   if (getToolChain().getArch() == llvm::Triple::x86)
10657     CmdArgs.push_back("--32");
10658
10659   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10660
10661   CmdArgs.push_back("-o");
10662   CmdArgs.push_back(Output.getFilename());
10663
10664   for (const auto &II : Inputs)
10665     CmdArgs.push_back(II.getFilename());
10666
10667   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10668   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10669 }
10670
10671 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10672                                      const InputInfo &Output,
10673                                      const InputInfoList &Inputs,
10674                                      const ArgList &Args,
10675                                      const char *LinkingOutput) const {
10676   const Driver &D = getToolChain().getDriver();
10677   ArgStringList CmdArgs;
10678
10679   if (!D.SysRoot.empty())
10680     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10681
10682   CmdArgs.push_back("--eh-frame-hdr");
10683   if (Args.hasArg(options::OPT_static)) {
10684     CmdArgs.push_back("-Bstatic");
10685   } else {
10686     if (Args.hasArg(options::OPT_rdynamic))
10687       CmdArgs.push_back("-export-dynamic");
10688     if (Args.hasArg(options::OPT_shared))
10689       CmdArgs.push_back("-Bshareable");
10690     else {
10691       CmdArgs.push_back("-dynamic-linker");
10692       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
10693     }
10694     CmdArgs.push_back("--hash-style=gnu");
10695     CmdArgs.push_back("--enable-new-dtags");
10696   }
10697
10698   // When building 32-bit code on DragonFly/pc64, we have to explicitly
10699   // instruct ld in the base system to link 32-bit code.
10700   if (getToolChain().getArch() == llvm::Triple::x86) {
10701     CmdArgs.push_back("-m");
10702     CmdArgs.push_back("elf_i386");
10703   }
10704
10705   if (Output.isFilename()) {
10706     CmdArgs.push_back("-o");
10707     CmdArgs.push_back(Output.getFilename());
10708   } else {
10709     assert(Output.isNothing() && "Invalid output.");
10710   }
10711
10712   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10713     if (!Args.hasArg(options::OPT_shared)) {
10714       if (Args.hasArg(options::OPT_pg))
10715         CmdArgs.push_back(
10716             Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
10717       else {
10718         if (Args.hasArg(options::OPT_pie))
10719           CmdArgs.push_back(
10720               Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
10721         else
10722           CmdArgs.push_back(
10723               Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
10724       }
10725     }
10726     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
10727     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10728       CmdArgs.push_back(
10729           Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
10730     else
10731       CmdArgs.push_back(
10732           Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
10733   }
10734
10735   Args.AddAllArgs(CmdArgs,
10736                   {options::OPT_L, options::OPT_T_Group, options::OPT_e});
10737
10738   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
10739
10740   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10741     CmdArgs.push_back("-L/usr/lib/gcc50");
10742
10743     if (!Args.hasArg(options::OPT_static)) {
10744       CmdArgs.push_back("-rpath");
10745       CmdArgs.push_back("/usr/lib/gcc50");
10746     }
10747
10748     if (D.CCCIsCXX()) {
10749       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
10750       CmdArgs.push_back("-lm");
10751     }
10752
10753     if (Args.hasArg(options::OPT_pthread))
10754       CmdArgs.push_back("-lpthread");
10755
10756     if (!Args.hasArg(options::OPT_nolibc)) {
10757       CmdArgs.push_back("-lc");
10758     }
10759
10760     if (Args.hasArg(options::OPT_static) ||
10761         Args.hasArg(options::OPT_static_libgcc)) {
10762         CmdArgs.push_back("-lgcc");
10763         CmdArgs.push_back("-lgcc_eh");
10764     } else {
10765       if (Args.hasArg(options::OPT_shared_libgcc)) {
10766           CmdArgs.push_back("-lgcc_pic");
10767           if (!Args.hasArg(options::OPT_shared))
10768             CmdArgs.push_back("-lgcc");
10769       } else {
10770           CmdArgs.push_back("-lgcc");
10771           CmdArgs.push_back("--as-needed");
10772           CmdArgs.push_back("-lgcc_pic");
10773           CmdArgs.push_back("--no-as-needed");
10774       }
10775     }
10776   }
10777
10778   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10779     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10780       CmdArgs.push_back(
10781           Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
10782     else
10783       CmdArgs.push_back(
10784           Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
10785     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
10786   }
10787
10788   getToolChain().addProfileRTLibs(Args, CmdArgs);
10789
10790   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
10791   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10792 }
10793
10794 // Try to find Exe from a Visual Studio distribution.  This first tries to find
10795 // an installed copy of Visual Studio and, failing that, looks in the PATH,
10796 // making sure that whatever executable that's found is not a same-named exe
10797 // from clang itself to prevent clang from falling back to itself.
10798 static std::string FindVisualStudioExecutable(const ToolChain &TC,
10799                                               const char *Exe,
10800                                               const char *ClangProgramPath) {
10801   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
10802   std::string visualStudioBinDir;
10803   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
10804                                          visualStudioBinDir)) {
10805     SmallString<128> FilePath(visualStudioBinDir);
10806     llvm::sys::path::append(FilePath, Exe);
10807     if (llvm::sys::fs::can_execute(FilePath.c_str()))
10808       return FilePath.str();
10809   }
10810
10811   return Exe;
10812 }
10813
10814 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10815                                         const InputInfo &Output,
10816                                         const InputInfoList &Inputs,
10817                                         const ArgList &Args,
10818                                         const char *LinkingOutput) const {
10819   ArgStringList CmdArgs;
10820   const ToolChain &TC = getToolChain();
10821
10822   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
10823   if (Output.isFilename())
10824     CmdArgs.push_back(
10825         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
10826
10827   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
10828       !C.getDriver().IsCLMode())
10829     CmdArgs.push_back("-defaultlib:libcmt");
10830
10831   if (!llvm::sys::Process::GetEnv("LIB")) {
10832     // If the VC environment hasn't been configured (perhaps because the user
10833     // did not run vcvarsall), try to build a consistent link environment.  If
10834     // the environment variable is set however, assume the user knows what
10835     // they're doing.
10836     std::string VisualStudioDir;
10837     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
10838     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
10839       SmallString<128> LibDir(VisualStudioDir);
10840       llvm::sys::path::append(LibDir, "VC", "lib");
10841       switch (MSVC.getArch()) {
10842       case llvm::Triple::x86:
10843         // x86 just puts the libraries directly in lib
10844         break;
10845       case llvm::Triple::x86_64:
10846         llvm::sys::path::append(LibDir, "amd64");
10847         break;
10848       case llvm::Triple::arm:
10849         llvm::sys::path::append(LibDir, "arm");
10850         break;
10851       default:
10852         break;
10853       }
10854       CmdArgs.push_back(
10855           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
10856
10857       if (MSVC.useUniversalCRT(VisualStudioDir)) {
10858         std::string UniversalCRTLibPath;
10859         if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
10860           CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10861                                                UniversalCRTLibPath));
10862       }
10863     }
10864
10865     std::string WindowsSdkLibPath;
10866     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
10867       CmdArgs.push_back(
10868           Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
10869   }
10870
10871   if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
10872     for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
10873       CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
10874
10875   CmdArgs.push_back("-nologo");
10876
10877   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
10878                   options::OPT__SLASH_Zd))
10879     CmdArgs.push_back("-debug");
10880
10881   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
10882                          options::OPT_shared);
10883   if (DLL) {
10884     CmdArgs.push_back(Args.MakeArgString("-dll"));
10885
10886     SmallString<128> ImplibName(Output.getFilename());
10887     llvm::sys::path::replace_extension(ImplibName, "lib");
10888     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
10889   }
10890
10891   if (TC.getSanitizerArgs().needsAsanRt()) {
10892     CmdArgs.push_back(Args.MakeArgString("-debug"));
10893     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
10894     if (TC.getSanitizerArgs().needsSharedAsanRt() ||
10895         Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
10896       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10897         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10898       // Make sure the dynamic runtime thunk is not optimized out at link time
10899       // to ensure proper SEH handling.
10900       CmdArgs.push_back(Args.MakeArgString(
10901           TC.getArch() == llvm::Triple::x86
10902               ? "-include:___asan_seh_interceptor"
10903               : "-include:__asan_seh_interceptor"));
10904     } else if (DLL) {
10905       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10906     } else {
10907       for (const auto &Lib : {"asan", "asan_cxx"})
10908         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10909     }
10910   }
10911
10912   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
10913
10914   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10915                    options::OPT_fno_openmp, false)) {
10916     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
10917     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
10918     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10919                                          TC.getDriver().Dir + "/../lib"));
10920     switch (TC.getDriver().getOpenMPRuntime(Args)) {
10921     case Driver::OMPRT_OMP:
10922       CmdArgs.push_back("-defaultlib:libomp.lib");
10923       break;
10924     case Driver::OMPRT_IOMP5:
10925       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
10926       break;
10927     case Driver::OMPRT_GOMP:
10928       break;
10929     case Driver::OMPRT_Unknown:
10930       // Already diagnosed.
10931       break;
10932     }
10933   }
10934
10935   // Add compiler-rt lib in case if it was explicitly
10936   // specified as an argument for --rtlib option.
10937   if (!Args.hasArg(options::OPT_nostdlib)) {
10938     AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
10939   }
10940
10941   // Add filenames, libraries, and other linker inputs.
10942   for (const auto &Input : Inputs) {
10943     if (Input.isFilename()) {
10944       CmdArgs.push_back(Input.getFilename());
10945       continue;
10946     }
10947
10948     const Arg &A = Input.getInputArg();
10949
10950     // Render -l options differently for the MSVC linker.
10951     if (A.getOption().matches(options::OPT_l)) {
10952       StringRef Lib = A.getValue();
10953       const char *LinkLibArg;
10954       if (Lib.endswith(".lib"))
10955         LinkLibArg = Args.MakeArgString(Lib);
10956       else
10957         LinkLibArg = Args.MakeArgString(Lib + ".lib");
10958       CmdArgs.push_back(LinkLibArg);
10959       continue;
10960     }
10961
10962     // Otherwise, this is some other kind of linker input option like -Wl, -z,
10963     // or -L. Render it, even if MSVC doesn't understand it.
10964     A.renderAsInput(Args, CmdArgs);
10965   }
10966
10967   TC.addProfileRTLibs(Args, CmdArgs);
10968
10969   // We need to special case some linker paths.  In the case of lld, we need to
10970   // translate 'lld' into 'lld-link', and in the case of the regular msvc
10971   // linker, we need to use a special search algorithm.
10972   llvm::SmallString<128> linkPath;
10973   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
10974   if (Linker.equals_lower("lld"))
10975     Linker = "lld-link";
10976
10977   if (Linker.equals_lower("link")) {
10978     // If we're using the MSVC linker, it's not sufficient to just use link
10979     // from the program PATH, because other environments like GnuWin32 install
10980     // their own link.exe which may come first.
10981     linkPath = FindVisualStudioExecutable(TC, "link.exe",
10982                                           C.getDriver().getClangProgramPath());
10983   } else {
10984     linkPath = Linker;
10985     llvm::sys::path::replace_extension(linkPath, "exe");
10986     linkPath = TC.GetProgramPath(linkPath.c_str());
10987   }
10988
10989   const char *Exec = Args.MakeArgString(linkPath);
10990   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10991 }
10992
10993 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10994                                           const InputInfo &Output,
10995                                           const InputInfoList &Inputs,
10996                                           const ArgList &Args,
10997                                           const char *LinkingOutput) const {
10998   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
10999 }
11000
11001 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
11002     Compilation &C, const JobAction &JA, const InputInfo &Output,
11003     const InputInfoList &Inputs, const ArgList &Args,
11004     const char *LinkingOutput) const {
11005   ArgStringList CmdArgs;
11006   CmdArgs.push_back("/nologo");
11007   CmdArgs.push_back("/c");  // Compile only.
11008   CmdArgs.push_back("/W0"); // No warnings.
11009
11010   // The goal is to be able to invoke this tool correctly based on
11011   // any flag accepted by clang-cl.
11012
11013   // These are spelled the same way in clang and cl.exe,.
11014   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
11015
11016   // Optimization level.
11017   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
11018     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
11019                                                                       : "/Oi-");
11020   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
11021     if (A->getOption().getID() == options::OPT_O0) {
11022       CmdArgs.push_back("/Od");
11023     } else {
11024       CmdArgs.push_back("/Og");
11025
11026       StringRef OptLevel = A->getValue();
11027       if (OptLevel == "s" || OptLevel == "z")
11028         CmdArgs.push_back("/Os");
11029       else
11030         CmdArgs.push_back("/Ot");
11031
11032       CmdArgs.push_back("/Ob2");
11033     }
11034   }
11035   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
11036                                options::OPT_fno_omit_frame_pointer))
11037     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
11038                           ? "/Oy"
11039                           : "/Oy-");
11040   if (!Args.hasArg(options::OPT_fwritable_strings))
11041     CmdArgs.push_back("/GF");
11042
11043   // Flags for which clang-cl has an alias.
11044   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
11045
11046   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
11047                    /*default=*/false))
11048     CmdArgs.push_back("/GR-");
11049
11050   if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
11051                    /*default=*/false))
11052     CmdArgs.push_back("/GS-");
11053
11054   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
11055                                options::OPT_fno_function_sections))
11056     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
11057                           ? "/Gy"
11058                           : "/Gy-");
11059   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
11060                                options::OPT_fno_data_sections))
11061     CmdArgs.push_back(
11062         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
11063   if (Args.hasArg(options::OPT_fsyntax_only))
11064     CmdArgs.push_back("/Zs");
11065   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
11066                   options::OPT__SLASH_Z7))
11067     CmdArgs.push_back("/Z7");
11068
11069   std::vector<std::string> Includes =
11070       Args.getAllArgValues(options::OPT_include);
11071   for (const auto &Include : Includes)
11072     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
11073
11074   // Flags that can simply be passed through.
11075   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
11076   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
11077   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
11078   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
11079   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
11080   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
11081
11082   // The order of these flags is relevant, so pick the last one.
11083   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
11084                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
11085     A->render(Args, CmdArgs);
11086
11087   // Use MSVC's default threadsafe statics behaviour unless there was a flag.
11088   if (Arg *A = Args.getLastArg(options::OPT_fthreadsafe_statics,
11089                                options::OPT_fno_threadsafe_statics)) {
11090     CmdArgs.push_back(A->getOption().getID() == options::OPT_fthreadsafe_statics
11091                           ? "/Zc:threadSafeInit"
11092                           : "/Zc:threadSafeInit-");
11093   }
11094
11095   // Pass through all unknown arguments so that the fallback command can see
11096   // them too.
11097   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
11098
11099   // Input filename.
11100   assert(Inputs.size() == 1);
11101   const InputInfo &II = Inputs[0];
11102   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
11103   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
11104   if (II.isFilename())
11105     CmdArgs.push_back(II.getFilename());
11106   else
11107     II.getInputArg().renderAsInput(Args, CmdArgs);
11108
11109   // Output filename.
11110   assert(Output.getType() == types::TY_Object);
11111   const char *Fo =
11112       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
11113   CmdArgs.push_back(Fo);
11114
11115   const Driver &D = getToolChain().getDriver();
11116   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
11117                                                 D.getClangProgramPath());
11118   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
11119                                     CmdArgs, Inputs);
11120 }
11121
11122 /// MinGW Tools
11123 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11124                                     const InputInfo &Output,
11125                                     const InputInfoList &Inputs,
11126                                     const ArgList &Args,
11127                                     const char *LinkingOutput) const {
11128   claimNoWarnArgs(Args);
11129   ArgStringList CmdArgs;
11130
11131   if (getToolChain().getArch() == llvm::Triple::x86) {
11132     CmdArgs.push_back("--32");
11133   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
11134     CmdArgs.push_back("--64");
11135   }
11136
11137   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
11138
11139   CmdArgs.push_back("-o");
11140   CmdArgs.push_back(Output.getFilename());
11141
11142   for (const auto &II : Inputs)
11143     CmdArgs.push_back(II.getFilename());
11144
11145   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
11146   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11147
11148   if (Args.hasArg(options::OPT_gsplit_dwarf))
11149     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
11150                    SplitDebugName(Args, Inputs[0]));
11151 }
11152
11153 void MinGW::Linker::AddLibGCC(const ArgList &Args,
11154                               ArgStringList &CmdArgs) const {
11155   if (Args.hasArg(options::OPT_mthreads))
11156     CmdArgs.push_back("-lmingwthrd");
11157   CmdArgs.push_back("-lmingw32");
11158
11159   // Make use of compiler-rt if --rtlib option is used
11160   ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
11161   if (RLT == ToolChain::RLT_Libgcc) {
11162     bool Static = Args.hasArg(options::OPT_static_libgcc) ||
11163                   Args.hasArg(options::OPT_static);
11164     bool Shared = Args.hasArg(options::OPT_shared);
11165     bool CXX = getToolChain().getDriver().CCCIsCXX();
11166
11167     if (Static || (!CXX && !Shared)) {
11168       CmdArgs.push_back("-lgcc");
11169       CmdArgs.push_back("-lgcc_eh");
11170     } else {
11171       CmdArgs.push_back("-lgcc_s");
11172       CmdArgs.push_back("-lgcc");
11173     }
11174   } else {
11175     AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
11176   }
11177
11178   CmdArgs.push_back("-lmoldname");
11179   CmdArgs.push_back("-lmingwex");
11180   CmdArgs.push_back("-lmsvcrt");
11181 }
11182
11183 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11184                                  const InputInfo &Output,
11185                                  const InputInfoList &Inputs,
11186                                  const ArgList &Args,
11187                                  const char *LinkingOutput) const {
11188   const ToolChain &TC = getToolChain();
11189   const Driver &D = TC.getDriver();
11190   // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
11191
11192   ArgStringList CmdArgs;
11193
11194   // Silence warning for "clang -g foo.o -o foo"
11195   Args.ClaimAllArgs(options::OPT_g_Group);
11196   // and "clang -emit-llvm foo.o -o foo"
11197   Args.ClaimAllArgs(options::OPT_emit_llvm);
11198   // and for "clang -w foo.o -o foo". Other warning options are already
11199   // handled somewhere else.
11200   Args.ClaimAllArgs(options::OPT_w);
11201
11202   StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
11203   if (LinkerName.equals_lower("lld")) {
11204     CmdArgs.push_back("-flavor");
11205     CmdArgs.push_back("gnu");
11206   } else if (!LinkerName.equals_lower("ld")) {
11207     D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
11208   }
11209
11210   if (!D.SysRoot.empty())
11211     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11212
11213   if (Args.hasArg(options::OPT_s))
11214     CmdArgs.push_back("-s");
11215
11216   CmdArgs.push_back("-m");
11217   if (TC.getArch() == llvm::Triple::x86)
11218     CmdArgs.push_back("i386pe");
11219   if (TC.getArch() == llvm::Triple::x86_64)
11220     CmdArgs.push_back("i386pep");
11221   if (TC.getArch() == llvm::Triple::arm)
11222     CmdArgs.push_back("thumb2pe");
11223
11224   if (Args.hasArg(options::OPT_mwindows)) {
11225     CmdArgs.push_back("--subsystem");
11226     CmdArgs.push_back("windows");
11227   } else if (Args.hasArg(options::OPT_mconsole)) {
11228     CmdArgs.push_back("--subsystem");
11229     CmdArgs.push_back("console");
11230   }
11231
11232   if (Args.hasArg(options::OPT_static))
11233     CmdArgs.push_back("-Bstatic");
11234   else {
11235     if (Args.hasArg(options::OPT_mdll))
11236       CmdArgs.push_back("--dll");
11237     else if (Args.hasArg(options::OPT_shared))
11238       CmdArgs.push_back("--shared");
11239     CmdArgs.push_back("-Bdynamic");
11240     if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
11241       CmdArgs.push_back("-e");
11242       if (TC.getArch() == llvm::Triple::x86)
11243         CmdArgs.push_back("_DllMainCRTStartup@12");
11244       else
11245         CmdArgs.push_back("DllMainCRTStartup");
11246       CmdArgs.push_back("--enable-auto-image-base");
11247     }
11248   }
11249
11250   CmdArgs.push_back("-o");
11251   CmdArgs.push_back(Output.getFilename());
11252
11253   Args.AddAllArgs(CmdArgs, options::OPT_e);
11254   // FIXME: add -N, -n flags
11255   Args.AddLastArg(CmdArgs, options::OPT_r);
11256   Args.AddLastArg(CmdArgs, options::OPT_s);
11257   Args.AddLastArg(CmdArgs, options::OPT_t);
11258   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
11259   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
11260
11261   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11262     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
11263       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
11264     } else {
11265       if (Args.hasArg(options::OPT_municode))
11266         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
11267       else
11268         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
11269     }
11270     if (Args.hasArg(options::OPT_pg))
11271       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
11272     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
11273   }
11274
11275   Args.AddAllArgs(CmdArgs, options::OPT_L);
11276   TC.AddFilePathLibArgs(Args, CmdArgs);
11277   AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
11278
11279   // TODO: Add ASan stuff here
11280
11281   // TODO: Add profile stuff here
11282
11283   if (D.CCCIsCXX() &&
11284       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11285     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
11286                                !Args.hasArg(options::OPT_static);
11287     if (OnlyLibstdcxxStatic)
11288       CmdArgs.push_back("-Bstatic");
11289     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
11290     if (OnlyLibstdcxxStatic)
11291       CmdArgs.push_back("-Bdynamic");
11292   }
11293
11294   if (!Args.hasArg(options::OPT_nostdlib)) {
11295     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
11296       if (Args.hasArg(options::OPT_static))
11297         CmdArgs.push_back("--start-group");
11298
11299       if (Args.hasArg(options::OPT_fstack_protector) ||
11300           Args.hasArg(options::OPT_fstack_protector_strong) ||
11301           Args.hasArg(options::OPT_fstack_protector_all)) {
11302         CmdArgs.push_back("-lssp_nonshared");
11303         CmdArgs.push_back("-lssp");
11304       }
11305       if (Args.hasArg(options::OPT_fopenmp))
11306         CmdArgs.push_back("-lgomp");
11307
11308       AddLibGCC(Args, CmdArgs);
11309
11310       if (Args.hasArg(options::OPT_pg))
11311         CmdArgs.push_back("-lgmon");
11312
11313       if (Args.hasArg(options::OPT_pthread))
11314         CmdArgs.push_back("-lpthread");
11315
11316       // add system libraries
11317       if (Args.hasArg(options::OPT_mwindows)) {
11318         CmdArgs.push_back("-lgdi32");
11319         CmdArgs.push_back("-lcomdlg32");
11320       }
11321       CmdArgs.push_back("-ladvapi32");
11322       CmdArgs.push_back("-lshell32");
11323       CmdArgs.push_back("-luser32");
11324       CmdArgs.push_back("-lkernel32");
11325
11326       if (Args.hasArg(options::OPT_static))
11327         CmdArgs.push_back("--end-group");
11328       else if (!LinkerName.equals_lower("lld"))
11329         AddLibGCC(Args, CmdArgs);
11330     }
11331
11332     if (!Args.hasArg(options::OPT_nostartfiles)) {
11333       // Add crtfastmath.o if available and fast math is enabled.
11334       TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
11335
11336       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
11337     }
11338   }
11339   const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
11340   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11341 }
11342
11343 /// XCore Tools
11344 // We pass assemble and link construction to the xcc tool.
11345
11346 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11347                                     const InputInfo &Output,
11348                                     const InputInfoList &Inputs,
11349                                     const ArgList &Args,
11350                                     const char *LinkingOutput) const {
11351   claimNoWarnArgs(Args);
11352   ArgStringList CmdArgs;
11353
11354   CmdArgs.push_back("-o");
11355   CmdArgs.push_back(Output.getFilename());
11356
11357   CmdArgs.push_back("-c");
11358
11359   if (Args.hasArg(options::OPT_v))
11360     CmdArgs.push_back("-v");
11361
11362   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
11363     if (!A->getOption().matches(options::OPT_g0))
11364       CmdArgs.push_back("-g");
11365
11366   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
11367                    false))
11368     CmdArgs.push_back("-fverbose-asm");
11369
11370   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
11371
11372   for (const auto &II : Inputs)
11373     CmdArgs.push_back(II.getFilename());
11374
11375   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
11376   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11377 }
11378
11379 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11380                                  const InputInfo &Output,
11381                                  const InputInfoList &Inputs,
11382                                  const ArgList &Args,
11383                                  const char *LinkingOutput) const {
11384   ArgStringList CmdArgs;
11385
11386   if (Output.isFilename()) {
11387     CmdArgs.push_back("-o");
11388     CmdArgs.push_back(Output.getFilename());
11389   } else {
11390     assert(Output.isNothing() && "Invalid output.");
11391   }
11392
11393   if (Args.hasArg(options::OPT_v))
11394     CmdArgs.push_back("-v");
11395
11396   // Pass -fexceptions through to the linker if it was present.
11397   if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
11398                    false))
11399     CmdArgs.push_back("-fexceptions");
11400
11401   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
11402
11403   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
11404   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11405 }
11406
11407 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11408                                            const InputInfo &Output,
11409                                            const InputInfoList &Inputs,
11410                                            const ArgList &Args,
11411                                            const char *LinkingOutput) const {
11412   claimNoWarnArgs(Args);
11413   const auto &TC =
11414       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
11415   ArgStringList CmdArgs;
11416   const char *Exec;
11417
11418   switch (TC.getArch()) {
11419   default:
11420     llvm_unreachable("unsupported architecture");
11421   case llvm::Triple::arm:
11422   case llvm::Triple::thumb:
11423     break;
11424   case llvm::Triple::x86:
11425     CmdArgs.push_back("--32");
11426     break;
11427   case llvm::Triple::x86_64:
11428     CmdArgs.push_back("--64");
11429     break;
11430   }
11431
11432   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
11433
11434   CmdArgs.push_back("-o");
11435   CmdArgs.push_back(Output.getFilename());
11436
11437   for (const auto &Input : Inputs)
11438     CmdArgs.push_back(Input.getFilename());
11439
11440   const std::string Assembler = TC.GetProgramPath("as");
11441   Exec = Args.MakeArgString(Assembler);
11442
11443   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11444 }
11445
11446 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11447                                         const InputInfo &Output,
11448                                         const InputInfoList &Inputs,
11449                                         const ArgList &Args,
11450                                         const char *LinkingOutput) const {
11451   const auto &TC =
11452       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
11453   const llvm::Triple &T = TC.getTriple();
11454   const Driver &D = TC.getDriver();
11455   SmallString<128> EntryPoint;
11456   ArgStringList CmdArgs;
11457   const char *Exec;
11458
11459   // Silence warning for "clang -g foo.o -o foo"
11460   Args.ClaimAllArgs(options::OPT_g_Group);
11461   // and "clang -emit-llvm foo.o -o foo"
11462   Args.ClaimAllArgs(options::OPT_emit_llvm);
11463   // and for "clang -w foo.o -o foo"
11464   Args.ClaimAllArgs(options::OPT_w);
11465   // Other warning options are already handled somewhere else.
11466
11467   if (!D.SysRoot.empty())
11468     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11469
11470   if (Args.hasArg(options::OPT_pie))
11471     CmdArgs.push_back("-pie");
11472   if (Args.hasArg(options::OPT_rdynamic))
11473     CmdArgs.push_back("-export-dynamic");
11474   if (Args.hasArg(options::OPT_s))
11475     CmdArgs.push_back("--strip-all");
11476
11477   CmdArgs.push_back("-m");
11478   switch (TC.getArch()) {
11479   default:
11480     llvm_unreachable("unsupported architecture");
11481   case llvm::Triple::arm:
11482   case llvm::Triple::thumb:
11483     // FIXME: this is incorrect for WinCE
11484     CmdArgs.push_back("thumb2pe");
11485     break;
11486   case llvm::Triple::x86:
11487     CmdArgs.push_back("i386pe");
11488     EntryPoint.append("_");
11489     break;
11490   case llvm::Triple::x86_64:
11491     CmdArgs.push_back("i386pep");
11492     break;
11493   }
11494
11495   if (Args.hasArg(options::OPT_shared)) {
11496     switch (T.getArch()) {
11497     default:
11498       llvm_unreachable("unsupported architecture");
11499     case llvm::Triple::arm:
11500     case llvm::Triple::thumb:
11501     case llvm::Triple::x86_64:
11502       EntryPoint.append("_DllMainCRTStartup");
11503       break;
11504     case llvm::Triple::x86:
11505       EntryPoint.append("_DllMainCRTStartup@12");
11506       break;
11507     }
11508
11509     CmdArgs.push_back("-shared");
11510     CmdArgs.push_back("-Bdynamic");
11511
11512     CmdArgs.push_back("--enable-auto-image-base");
11513
11514     CmdArgs.push_back("--entry");
11515     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
11516   } else {
11517     EntryPoint.append("mainCRTStartup");
11518
11519     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
11520                                                        : "-Bdynamic");
11521
11522     if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11523       CmdArgs.push_back("--entry");
11524       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
11525     }
11526
11527     // FIXME: handle subsystem
11528   }
11529
11530   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
11531   CmdArgs.push_back("--allow-multiple-definition");
11532
11533   CmdArgs.push_back("-o");
11534   CmdArgs.push_back(Output.getFilename());
11535
11536   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
11537     SmallString<261> ImpLib(Output.getFilename());
11538     llvm::sys::path::replace_extension(ImpLib, ".lib");
11539
11540     CmdArgs.push_back("--out-implib");
11541     CmdArgs.push_back(Args.MakeArgString(ImpLib));
11542   }
11543
11544   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11545     const std::string CRTPath(D.SysRoot + "/usr/lib/");
11546     const char *CRTBegin;
11547
11548     CRTBegin =
11549         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
11550     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
11551   }
11552
11553   Args.AddAllArgs(CmdArgs, options::OPT_L);
11554   TC.AddFilePathLibArgs(Args, CmdArgs);
11555   AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
11556
11557   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
11558       !Args.hasArg(options::OPT_nodefaultlibs)) {
11559     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
11560                      !Args.hasArg(options::OPT_static);
11561     if (StaticCXX)
11562       CmdArgs.push_back("-Bstatic");
11563     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
11564     if (StaticCXX)
11565       CmdArgs.push_back("-Bdynamic");
11566   }
11567
11568   if (!Args.hasArg(options::OPT_nostdlib)) {
11569     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
11570       // TODO handle /MT[d] /MD[d]
11571       CmdArgs.push_back("-lmsvcrt");
11572       AddRunTimeLibs(TC, D, CmdArgs, Args);
11573     }
11574   }
11575
11576   if (TC.getSanitizerArgs().needsAsanRt()) {
11577     // TODO handle /MT[d] /MD[d]
11578     if (Args.hasArg(options::OPT_shared)) {
11579       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
11580     } else {
11581       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
11582         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
11583       // Make sure the dynamic runtime thunk is not optimized out at link time
11584       // to ensure proper SEH handling.
11585       CmdArgs.push_back(Args.MakeArgString("--undefined"));
11586       CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
11587                                                ? "___asan_seh_interceptor"
11588                                                : "__asan_seh_interceptor"));
11589     }
11590   }
11591
11592   Exec = Args.MakeArgString(TC.GetLinkerPath());
11593
11594   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11595 }
11596
11597 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
11598                                           const InputInfo &Output,
11599                                           const InputInfoList &Inputs,
11600                                           const ArgList &Args,
11601                                           const char *LinkingOutput) const {
11602   ArgStringList CmdArgs;
11603   assert(Inputs.size() == 1);
11604   const InputInfo &II = Inputs[0];
11605   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
11606          II.getType() == types::TY_PP_CXX);
11607
11608   if (JA.getKind() == Action::PreprocessJobClass) {
11609     Args.ClaimAllArgs();
11610     CmdArgs.push_back("-E");
11611   } else {
11612     assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
11613     CmdArgs.push_back("-S");
11614     CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
11615   }
11616   CmdArgs.push_back("-DMYRIAD2");
11617
11618   // Append all -I, -iquote, -isystem paths, defines/undefines,
11619   // 'f' flags, optimize flags, and warning options.
11620   // These are spelled the same way in clang and moviCompile.
11621   Args.AddAllArgsExcept(
11622       CmdArgs,
11623       {options::OPT_I_Group, options::OPT_clang_i_Group, options::OPT_std_EQ,
11624        options::OPT_D, options::OPT_U, options::OPT_f_Group,
11625        options::OPT_f_clang_Group, options::OPT_g_Group, options::OPT_M_Group,
11626        options::OPT_O_Group, options::OPT_W_Group, options::OPT_mcpu_EQ},
11627       {options::OPT_fno_split_dwarf_inlining});
11628   Args.hasArg(options::OPT_fno_split_dwarf_inlining); // Claim it if present.
11629
11630   // If we're producing a dependency file, and assembly is the final action,
11631   // then the name of the target in the dependency file should be the '.o'
11632   // file, not the '.s' file produced by this step. For example, instead of
11633   //  /tmp/mumble.s: mumble.c .../someheader.h
11634   // the filename on the lefthand side should be "mumble.o"
11635   if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
11636       C.getActions().size() == 1 &&
11637       C.getActions()[0]->getKind() == Action::AssembleJobClass) {
11638     Arg *A = Args.getLastArg(options::OPT_o);
11639     if (A) {
11640       CmdArgs.push_back("-MT");
11641       CmdArgs.push_back(Args.MakeArgString(A->getValue()));
11642     }
11643   }
11644
11645   CmdArgs.push_back(II.getFilename());
11646   CmdArgs.push_back("-o");
11647   CmdArgs.push_back(Output.getFilename());
11648
11649   std::string Exec =
11650       Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
11651   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
11652                                           CmdArgs, Inputs));
11653 }
11654
11655 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11656                                            const InputInfo &Output,
11657                                            const InputInfoList &Inputs,
11658                                            const ArgList &Args,
11659                                            const char *LinkingOutput) const {
11660   ArgStringList CmdArgs;
11661
11662   assert(Inputs.size() == 1);
11663   const InputInfo &II = Inputs[0];
11664   assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
11665   assert(Output.getType() == types::TY_Object);
11666
11667   CmdArgs.push_back("-no6thSlotCompression");
11668   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
11669   if (CPUArg)
11670     CmdArgs.push_back(
11671         Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
11672   CmdArgs.push_back("-noSPrefixing");
11673   CmdArgs.push_back("-a"); // Mystery option.
11674   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
11675   for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
11676     A->claim();
11677     CmdArgs.push_back(
11678         Args.MakeArgString(std::string("-i:") + A->getValue(0)));
11679   }
11680   CmdArgs.push_back("-elf"); // Output format.
11681   CmdArgs.push_back(II.getFilename());
11682   CmdArgs.push_back(
11683       Args.MakeArgString(std::string("-o:") + Output.getFilename()));
11684
11685   std::string Exec =
11686       Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
11687   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
11688                                           CmdArgs, Inputs));
11689 }
11690
11691 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11692                                          const InputInfo &Output,
11693                                          const InputInfoList &Inputs,
11694                                          const ArgList &Args,
11695                                          const char *LinkingOutput) const {
11696   const auto &TC =
11697       static_cast<const toolchains::MyriadToolChain &>(getToolChain());
11698   const llvm::Triple &T = TC.getTriple();
11699   ArgStringList CmdArgs;
11700   bool UseStartfiles =
11701       !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
11702   bool UseDefaultLibs =
11703       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
11704   // Silence warning if the args contain both -nostdlib and -stdlib=.
11705   Args.getLastArg(options::OPT_stdlib_EQ);
11706
11707   if (T.getArch() == llvm::Triple::sparc)
11708     CmdArgs.push_back("-EB");
11709   else // SHAVE assumes little-endian, and sparcel is expressly so.
11710     CmdArgs.push_back("-EL");
11711
11712   // The remaining logic is mostly like gnutools::Linker::ConstructJob,
11713   // but we never pass through a --sysroot option and various other bits.
11714   // For example, there are no sanitizers (yet) nor gold linker.
11715
11716   // Eat some arguments that may be present but have no effect.
11717   Args.ClaimAllArgs(options::OPT_g_Group);
11718   Args.ClaimAllArgs(options::OPT_w);
11719   Args.ClaimAllArgs(options::OPT_static_libgcc);
11720
11721   if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
11722     CmdArgs.push_back("-s");
11723
11724   CmdArgs.push_back("-o");
11725   CmdArgs.push_back(Output.getFilename());
11726
11727   if (UseStartfiles) {
11728     // If you want startfiles, it means you want the builtin crti and crtbegin,
11729     // but not crt0. Myriad link commands provide their own crt0.o as needed.
11730     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
11731     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
11732   }
11733
11734   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
11735                             options::OPT_e, options::OPT_s, options::OPT_t,
11736                             options::OPT_Z_Flag, options::OPT_r});
11737
11738   TC.AddFilePathLibArgs(Args, CmdArgs);
11739
11740   bool NeedsSanitizerDeps = addSanitizerRuntimes(TC, Args, CmdArgs);
11741   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
11742
11743   if (UseDefaultLibs) {
11744     if (NeedsSanitizerDeps)
11745       linkSanitizerRuntimeDeps(TC, CmdArgs);
11746     if (C.getDriver().CCCIsCXX()) {
11747       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
11748         CmdArgs.push_back("-lc++");
11749         CmdArgs.push_back("-lc++abi");
11750       } else
11751         CmdArgs.push_back("-lstdc++");
11752     }
11753     if (T.getOS() == llvm::Triple::RTEMS) {
11754       CmdArgs.push_back("--start-group");
11755       CmdArgs.push_back("-lc");
11756       CmdArgs.push_back("-lgcc"); // circularly dependent on rtems
11757       // You must provide your own "-L" option to enable finding these.
11758       CmdArgs.push_back("-lrtemscpu");
11759       CmdArgs.push_back("-lrtemsbsp");
11760       CmdArgs.push_back("--end-group");
11761     } else {
11762       CmdArgs.push_back("-lc");
11763       CmdArgs.push_back("-lgcc");
11764     }
11765   }
11766   if (UseStartfiles) {
11767     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
11768     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
11769   }
11770
11771   std::string Exec =
11772       Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
11773   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
11774                                           CmdArgs, Inputs));
11775 }
11776
11777 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
11778                                     const InputInfo &Output,
11779                                     const InputInfoList &Inputs,
11780                                     const ArgList &Args,
11781                                     const char *LinkingOutput) const {
11782   claimNoWarnArgs(Args);
11783   ArgStringList CmdArgs;
11784
11785   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
11786
11787   CmdArgs.push_back("-o");
11788   CmdArgs.push_back(Output.getFilename());
11789
11790   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
11791   const InputInfo &Input = Inputs[0];
11792   assert(Input.isFilename() && "Invalid input.");
11793   CmdArgs.push_back(Input.getFilename());
11794
11795   const char *Exec =
11796       Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
11797   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11798 }
11799
11800 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
11801   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
11802   if (SanArgs.needsUbsanRt()) {
11803     CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
11804   }
11805   if (SanArgs.needsAsanRt()) {
11806     CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
11807   }
11808 }
11809
11810 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
11811                                 const JobAction &JA, const InputInfo &Output,
11812                                 const InputInfoList &Inputs,
11813                                 const ArgList &Args,
11814                                 const char *LinkingOutput) {
11815   const toolchains::FreeBSD &ToolChain =
11816       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
11817   const Driver &D = ToolChain.getDriver();
11818   ArgStringList CmdArgs;
11819
11820   // Silence warning for "clang -g foo.o -o foo"
11821   Args.ClaimAllArgs(options::OPT_g_Group);
11822   // and "clang -emit-llvm foo.o -o foo"
11823   Args.ClaimAllArgs(options::OPT_emit_llvm);
11824   // and for "clang -w foo.o -o foo". Other warning options are already
11825   // handled somewhere else.
11826   Args.ClaimAllArgs(options::OPT_w);
11827
11828   if (!D.SysRoot.empty())
11829     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11830
11831   if (Args.hasArg(options::OPT_pie))
11832     CmdArgs.push_back("-pie");
11833
11834   if (Args.hasArg(options::OPT_rdynamic))
11835     CmdArgs.push_back("-export-dynamic");
11836   if (Args.hasArg(options::OPT_shared))
11837     CmdArgs.push_back("--oformat=so");
11838
11839   if (Output.isFilename()) {
11840     CmdArgs.push_back("-o");
11841     CmdArgs.push_back(Output.getFilename());
11842   } else {
11843     assert(Output.isNothing() && "Invalid output.");
11844   }
11845
11846   AddPS4SanitizerArgs(ToolChain, CmdArgs);
11847
11848   Args.AddAllArgs(CmdArgs, options::OPT_L);
11849   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11850   Args.AddAllArgs(CmdArgs, options::OPT_e);
11851   Args.AddAllArgs(CmdArgs, options::OPT_s);
11852   Args.AddAllArgs(CmdArgs, options::OPT_t);
11853   Args.AddAllArgs(CmdArgs, options::OPT_r);
11854
11855   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11856     CmdArgs.push_back("--no-demangle");
11857
11858   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
11859
11860   if (Args.hasArg(options::OPT_pthread)) {
11861     CmdArgs.push_back("-lpthread");
11862   }
11863
11864   const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11865
11866   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11867 }
11868
11869 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
11870                                  const JobAction &JA, const InputInfo &Output,
11871                                  const InputInfoList &Inputs,
11872                                  const ArgList &Args,
11873                                  const char *LinkingOutput) {
11874   const toolchains::FreeBSD &ToolChain =
11875       static_cast<const toolchains::FreeBSD &>(T.getToolChain());
11876   const Driver &D = ToolChain.getDriver();
11877   ArgStringList CmdArgs;
11878
11879   // Silence warning for "clang -g foo.o -o foo"
11880   Args.ClaimAllArgs(options::OPT_g_Group);
11881   // and "clang -emit-llvm foo.o -o foo"
11882   Args.ClaimAllArgs(options::OPT_emit_llvm);
11883   // and for "clang -w foo.o -o foo". Other warning options are already
11884   // handled somewhere else.
11885   Args.ClaimAllArgs(options::OPT_w);
11886
11887   if (!D.SysRoot.empty())
11888     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11889
11890   if (Args.hasArg(options::OPT_pie))
11891     CmdArgs.push_back("-pie");
11892
11893   if (Args.hasArg(options::OPT_static)) {
11894     CmdArgs.push_back("-Bstatic");
11895   } else {
11896     if (Args.hasArg(options::OPT_rdynamic))
11897       CmdArgs.push_back("-export-dynamic");
11898     CmdArgs.push_back("--eh-frame-hdr");
11899     if (Args.hasArg(options::OPT_shared)) {
11900       CmdArgs.push_back("-Bshareable");
11901     } else {
11902       CmdArgs.push_back("-dynamic-linker");
11903       CmdArgs.push_back("/libexec/ld-elf.so.1");
11904     }
11905     CmdArgs.push_back("--enable-new-dtags");
11906   }
11907
11908   if (Output.isFilename()) {
11909     CmdArgs.push_back("-o");
11910     CmdArgs.push_back(Output.getFilename());
11911   } else {
11912     assert(Output.isNothing() && "Invalid output.");
11913   }
11914
11915   AddPS4SanitizerArgs(ToolChain, CmdArgs);
11916
11917   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11918     const char *crt1 = nullptr;
11919     if (!Args.hasArg(options::OPT_shared)) {
11920       if (Args.hasArg(options::OPT_pg))
11921         crt1 = "gcrt1.o";
11922       else if (Args.hasArg(options::OPT_pie))
11923         crt1 = "Scrt1.o";
11924       else
11925         crt1 = "crt1.o";
11926     }
11927     if (crt1)
11928       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
11929
11930     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
11931
11932     const char *crtbegin = nullptr;
11933     if (Args.hasArg(options::OPT_static))
11934       crtbegin = "crtbeginT.o";
11935     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11936       crtbegin = "crtbeginS.o";
11937     else
11938       crtbegin = "crtbegin.o";
11939
11940     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
11941   }
11942
11943   Args.AddAllArgs(CmdArgs, options::OPT_L);
11944   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
11945   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11946   Args.AddAllArgs(CmdArgs, options::OPT_e);
11947   Args.AddAllArgs(CmdArgs, options::OPT_s);
11948   Args.AddAllArgs(CmdArgs, options::OPT_t);
11949   Args.AddAllArgs(CmdArgs, options::OPT_r);
11950
11951   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11952     CmdArgs.push_back("--no-demangle");
11953
11954   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
11955
11956   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11957     // For PS4, we always want to pass libm, libstdc++ and libkernel
11958     // libraries for both C and C++ compilations.
11959     CmdArgs.push_back("-lkernel");
11960     if (D.CCCIsCXX()) {
11961       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
11962       if (Args.hasArg(options::OPT_pg))
11963         CmdArgs.push_back("-lm_p");
11964       else
11965         CmdArgs.push_back("-lm");
11966     }
11967     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
11968     // the default system libraries. Just mimic this for now.
11969     if (Args.hasArg(options::OPT_pg))
11970       CmdArgs.push_back("-lgcc_p");
11971     else
11972       CmdArgs.push_back("-lcompiler_rt");
11973     if (Args.hasArg(options::OPT_static)) {
11974       CmdArgs.push_back("-lstdc++");
11975     } else if (Args.hasArg(options::OPT_pg)) {
11976       CmdArgs.push_back("-lgcc_eh_p");
11977     } else {
11978       CmdArgs.push_back("--as-needed");
11979       CmdArgs.push_back("-lstdc++");
11980       CmdArgs.push_back("--no-as-needed");
11981     }
11982
11983     if (Args.hasArg(options::OPT_pthread)) {
11984       if (Args.hasArg(options::OPT_pg))
11985         CmdArgs.push_back("-lpthread_p");
11986       else
11987         CmdArgs.push_back("-lpthread");
11988     }
11989
11990     if (Args.hasArg(options::OPT_pg)) {
11991       if (Args.hasArg(options::OPT_shared))
11992         CmdArgs.push_back("-lc");
11993       else {
11994         if (Args.hasArg(options::OPT_static)) {
11995           CmdArgs.push_back("--start-group");
11996           CmdArgs.push_back("-lc_p");
11997           CmdArgs.push_back("-lpthread_p");
11998           CmdArgs.push_back("--end-group");
11999         } else {
12000           CmdArgs.push_back("-lc_p");
12001         }
12002       }
12003       CmdArgs.push_back("-lgcc_p");
12004     } else {
12005       if (Args.hasArg(options::OPT_static)) {
12006         CmdArgs.push_back("--start-group");
12007         CmdArgs.push_back("-lc");
12008         CmdArgs.push_back("-lpthread");
12009         CmdArgs.push_back("--end-group");
12010       } else {
12011         CmdArgs.push_back("-lc");
12012       }
12013       CmdArgs.push_back("-lcompiler_rt");
12014     }
12015
12016     if (Args.hasArg(options::OPT_static)) {
12017       CmdArgs.push_back("-lstdc++");
12018     } else if (Args.hasArg(options::OPT_pg)) {
12019       CmdArgs.push_back("-lgcc_eh_p");
12020     } else {
12021       CmdArgs.push_back("--as-needed");
12022       CmdArgs.push_back("-lstdc++");
12023       CmdArgs.push_back("--no-as-needed");
12024     }
12025   }
12026
12027   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
12028     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
12029       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
12030     else
12031       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
12032     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
12033   }
12034
12035   const char *Exec =
12036 #ifdef LLVM_ON_WIN32
12037       Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
12038 #else
12039       Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
12040 #endif
12041
12042   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
12043 }
12044
12045 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
12046                                 const InputInfo &Output,
12047                                 const InputInfoList &Inputs,
12048                                 const ArgList &Args,
12049                                 const char *LinkingOutput) const {
12050   const toolchains::FreeBSD &ToolChain =
12051       static_cast<const toolchains::FreeBSD &>(getToolChain());
12052   const Driver &D = ToolChain.getDriver();
12053   bool PS4Linker;
12054   StringRef LinkerOptName;
12055   if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
12056     LinkerOptName = A->getValue();
12057     if (LinkerOptName != "ps4" && LinkerOptName != "gold")
12058       D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
12059   }
12060
12061   if (LinkerOptName == "gold")
12062     PS4Linker = false;
12063   else if (LinkerOptName == "ps4")
12064     PS4Linker = true;
12065   else
12066     PS4Linker = !Args.hasArg(options::OPT_shared);
12067
12068   if (PS4Linker)
12069     ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
12070   else
12071     ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
12072 }
12073
12074 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
12075                                     const InputInfo &Output,
12076                                     const InputInfoList &Inputs,
12077                                     const ArgList &Args,
12078                                     const char *LinkingOutput) const {
12079   const auto &TC =
12080       static_cast<const toolchains::CudaToolChain &>(getToolChain());
12081   assert(TC.getTriple().isNVPTX() && "Wrong platform");
12082
12083   // Obtain architecture from the action.
12084   CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
12085   assert(gpu_arch != CudaArch::UNKNOWN &&
12086          "Device action expected to have an architecture.");
12087
12088   // Check that our installation's ptxas supports gpu_arch.
12089   if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
12090     TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
12091   }
12092
12093   ArgStringList CmdArgs;
12094   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
12095   if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
12096                    options::OPT_no_cuda_noopt_device_debug, false)) {
12097     // ptxas does not accept -g option if optimization is enabled, so
12098     // we ignore the compiler's -O* options if we want debug info.
12099     CmdArgs.push_back("-g");
12100     CmdArgs.push_back("--dont-merge-basicblocks");
12101     CmdArgs.push_back("--return-at-end");
12102   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
12103     // Map the -O we received to -O{0,1,2,3}.
12104     //
12105     // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
12106     // default, so it may correspond more closely to the spirit of clang -O2.
12107
12108     // -O3 seems like the least-bad option when -Osomething is specified to
12109     // clang but it isn't handled below.
12110     StringRef OOpt = "3";
12111     if (A->getOption().matches(options::OPT_O4) ||
12112         A->getOption().matches(options::OPT_Ofast))
12113       OOpt = "3";
12114     else if (A->getOption().matches(options::OPT_O0))
12115       OOpt = "0";
12116     else if (A->getOption().matches(options::OPT_O)) {
12117       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
12118       OOpt = llvm::StringSwitch<const char *>(A->getValue())
12119                  .Case("1", "1")
12120                  .Case("2", "2")
12121                  .Case("3", "3")
12122                  .Case("s", "2")
12123                  .Case("z", "2")
12124                  .Default("2");
12125     }
12126     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
12127   } else {
12128     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
12129     // to no optimizations, but ptxas's default is -O3.
12130     CmdArgs.push_back("-O0");
12131   }
12132
12133   CmdArgs.push_back("--gpu-name");
12134   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
12135   CmdArgs.push_back("--output-file");
12136   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
12137   for (const auto& II : Inputs)
12138     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
12139
12140   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
12141     CmdArgs.push_back(Args.MakeArgString(A));
12142
12143   const char *Exec;
12144   if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
12145     Exec = A->getValue();
12146   else
12147     Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
12148   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
12149 }
12150
12151 // All inputs to this linker must be from CudaDeviceActions, as we need to look
12152 // at the Inputs' Actions in order to figure out which GPU architecture they
12153 // correspond to.
12154 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
12155                                  const InputInfo &Output,
12156                                  const InputInfoList &Inputs,
12157                                  const ArgList &Args,
12158                                  const char *LinkingOutput) const {
12159   const auto &TC =
12160       static_cast<const toolchains::CudaToolChain &>(getToolChain());
12161   assert(TC.getTriple().isNVPTX() && "Wrong platform");
12162
12163   ArgStringList CmdArgs;
12164   CmdArgs.push_back("--cuda");
12165   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
12166   CmdArgs.push_back(Args.MakeArgString("--create"));
12167   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
12168
12169   for (const auto& II : Inputs) {
12170     auto *A = II.getAction();
12171     assert(A->getInputs().size() == 1 &&
12172            "Device offload action is expected to have a single input");
12173     const char *gpu_arch_str = A->getOffloadingArch();
12174     assert(gpu_arch_str &&
12175            "Device action expected to have associated a GPU architecture!");
12176     CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
12177
12178     // We need to pass an Arch of the form "sm_XX" for cubin files and
12179     // "compute_XX" for ptx.
12180     const char *Arch =
12181         (II.getType() == types::TY_PP_Asm)
12182             ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
12183             : gpu_arch_str;
12184     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
12185                                          Arch + ",file=" + II.getFilename()));
12186   }
12187
12188   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
12189     CmdArgs.push_back(Args.MakeArgString(A));
12190
12191   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
12192   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
12193 }