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