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