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