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