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