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