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