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