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