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