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