Tools.cpp revision 5adb5a84bfb4f2e5f1ea28fdfc6ee1cd9b622c60
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/HostInfo.h"
20#include "clang/Driver/Option.h"
21#include "clang/Driver/Options.h"
22#include "clang/Driver/ToolChain.h"
23#include "clang/Driver/Util.h"
24
25#include "llvm/ADT/SmallString.h"
26#include "llvm/ADT/StringSwitch.h"
27#include "llvm/ADT/Twine.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Support/Host.h"
32#include "llvm/Support/Process.h"
33
34#include "InputInfo.h"
35#include "ToolChains.h"
36
37using namespace clang::driver;
38using namespace clang::driver::tools;
39
40/// FindTargetProgramPath - Return path of the target specific version of
41/// ProgName.  If it doesn't exist, return path of ProgName itself.
42static std::string FindTargetProgramPath(const ToolChain &TheToolChain,
43                                         const char *ProgName) {
44  std::string Executable(TheToolChain.getTripleString() + "-" + ProgName);
45  std::string Path(TheToolChain.GetProgramPath(Executable.c_str()));
46  if (Path != Executable)
47    return Path;
48  return TheToolChain.GetProgramPath(ProgName);
49}
50
51/// CheckPreprocessingOptions - Perform some validation of preprocessing
52/// arguments that is shared with gcc.
53static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
54  if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
55    if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP)
56      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
57        << A->getAsString(Args) << "-E";
58}
59
60/// CheckCodeGenerationOptions - Perform some validation of code generation
61/// arguments that is shared with gcc.
62static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
63  // In gcc, only ARM checks this, but it seems reasonable to check universally.
64  if (Args.hasArg(options::OPT_static))
65    if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
66                                       options::OPT_mdynamic_no_pic))
67      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
68        << A->getAsString(Args) << "-static";
69}
70
71// Quote target names for inclusion in GNU Make dependency files.
72// Only the characters '$', '#', ' ', '\t' are quoted.
73static void QuoteTarget(llvm::StringRef Target,
74                        llvm::SmallVectorImpl<char> &Res) {
75  for (unsigned i = 0, e = Target.size(); i != e; ++i) {
76    switch (Target[i]) {
77    case ' ':
78    case '\t':
79      // Escape the preceding backslashes
80      for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
81        Res.push_back('\\');
82
83      // Escape the space/tab
84      Res.push_back('\\');
85      break;
86    case '$':
87      Res.push_back('$');
88      break;
89    case '#':
90      Res.push_back('\\');
91      break;
92    default:
93      break;
94    }
95
96    Res.push_back(Target[i]);
97  }
98}
99
100static void AddLinkerInputs(const ToolChain &TC,
101                            const InputInfoList &Inputs, const ArgList &Args,
102                            ArgStringList &CmdArgs) {
103  const Driver &D = TC.getDriver();
104
105  // Add extra linker input arguments which are not treated as inputs
106  // (constructed via -Xarch_).
107  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
108
109  for (InputInfoList::const_iterator
110         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
111    const InputInfo &II = *it;
112
113    if (!TC.HasNativeLLVMSupport()) {
114      // Don't try to pass LLVM inputs unless we have native support.
115      if (II.getType() == types::TY_LLVM_IR ||
116          II.getType() == types::TY_LTO_IR ||
117          II.getType() == types::TY_LLVM_BC ||
118          II.getType() == types::TY_LTO_BC)
119        D.Diag(clang::diag::err_drv_no_linker_llvm_support)
120          << TC.getTripleString();
121    }
122
123    // Add filenames immediately.
124    if (II.isFilename()) {
125      CmdArgs.push_back(II.getFilename());
126      continue;
127    }
128
129    // Otherwise, this is a linker input argument.
130    const Arg &A = II.getInputArg();
131
132    // Handle reserved library options.
133    if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
134      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
135    } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
136      TC.AddCCKextLibArgs(Args, CmdArgs);
137    } else
138      A.renderAsInput(Args, CmdArgs);
139  }
140}
141
142void Clang::AddPreprocessingOptions(const Driver &D,
143                                    const ArgList &Args,
144                                    ArgStringList &CmdArgs,
145                                    const InputInfo &Output,
146                                    const InputInfoList &Inputs) const {
147  Arg *A;
148
149  CheckPreprocessingOptions(D, Args);
150
151  Args.AddLastArg(CmdArgs, options::OPT_C);
152  Args.AddLastArg(CmdArgs, options::OPT_CC);
153
154  // Handle dependency file generation.
155  if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
156      (A = Args.getLastArg(options::OPT_MD)) ||
157      (A = Args.getLastArg(options::OPT_MMD))) {
158    // Determine the output location.
159    const char *DepFile;
160    if (Output.getType() == types::TY_Dependencies) {
161      DepFile = Output.getFilename();
162    } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
163      DepFile = MF->getValue(Args);
164    } else if (A->getOption().matches(options::OPT_M) ||
165               A->getOption().matches(options::OPT_MM)) {
166      DepFile = "-";
167    } else {
168      DepFile = darwin::CC1::getDependencyFileName(Args, Inputs);
169    }
170    CmdArgs.push_back("-dependency-file");
171    CmdArgs.push_back(DepFile);
172
173    // Add a default target if one wasn't specified.
174    if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
175      const char *DepTarget;
176
177      // If user provided -o, that is the dependency target, except
178      // when we are only generating a dependency file.
179      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
180      if (OutputOpt && Output.getType() != types::TY_Dependencies) {
181        DepTarget = OutputOpt->getValue(Args);
182      } else {
183        // Otherwise derive from the base input.
184        //
185        // FIXME: This should use the computed output file location.
186        llvm::SmallString<128> P(Inputs[0].getBaseInput());
187        llvm::sys::path::replace_extension(P, "o");
188        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
189      }
190
191      CmdArgs.push_back("-MT");
192      llvm::SmallString<128> Quoted;
193      QuoteTarget(DepTarget, Quoted);
194      CmdArgs.push_back(Args.MakeArgString(Quoted));
195    }
196
197    if (A->getOption().matches(options::OPT_M) ||
198        A->getOption().matches(options::OPT_MD))
199      CmdArgs.push_back("-sys-header-deps");
200  }
201
202  Args.AddLastArg(CmdArgs, options::OPT_MP);
203
204  // Convert all -MQ <target> args to -MT <quoted target>
205  for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
206                                             options::OPT_MQ),
207         ie = Args.filtered_end(); it != ie; ++it) {
208    const Arg *A = *it;
209    A->claim();
210
211    if (A->getOption().matches(options::OPT_MQ)) {
212      CmdArgs.push_back("-MT");
213      llvm::SmallString<128> Quoted;
214      QuoteTarget(A->getValue(Args), Quoted);
215      CmdArgs.push_back(Args.MakeArgString(Quoted));
216
217    // -MT flag - no change
218    } else {
219      A->render(Args, CmdArgs);
220    }
221  }
222
223  // Add -i* options, and automatically translate to
224  // -include-pch/-include-pth for transparent PCH support. It's
225  // wonky, but we include looking for .gch so we can support seamless
226  // replacement into a build system already set up to be generating
227  // .gch files.
228  bool RenderedImplicitInclude = false;
229  for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
230         ie = Args.filtered_end(); it != ie; ++it) {
231    const Arg *A = it;
232
233    if (A->getOption().matches(options::OPT_include)) {
234      bool IsFirstImplicitInclude = !RenderedImplicitInclude;
235      RenderedImplicitInclude = true;
236
237      // Use PCH if the user requested it.
238      bool UsePCH = D.CCCUsePCH;
239
240      bool FoundPTH = false;
241      bool FoundPCH = false;
242      llvm::sys::Path P(A->getValue(Args));
243      bool Exists;
244      if (UsePCH) {
245        P.appendSuffix("pch");
246        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
247          FoundPCH = true;
248        else
249          P.eraseSuffix();
250      }
251
252      if (!FoundPCH) {
253        P.appendSuffix("pth");
254        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
255          FoundPTH = true;
256        else
257          P.eraseSuffix();
258      }
259
260      if (!FoundPCH && !FoundPTH) {
261        P.appendSuffix("gch");
262        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
263          FoundPCH = UsePCH;
264          FoundPTH = !UsePCH;
265        }
266        else
267          P.eraseSuffix();
268      }
269
270      if (FoundPCH || FoundPTH) {
271        if (IsFirstImplicitInclude) {
272          A->claim();
273          if (UsePCH)
274            CmdArgs.push_back("-include-pch");
275          else
276            CmdArgs.push_back("-include-pth");
277          CmdArgs.push_back(Args.MakeArgString(P.str()));
278          continue;
279        } else {
280          // Ignore the PCH if not first on command line and emit warning.
281          D.Diag(clang::diag::warn_drv_pch_not_first_include)
282              << P.str() << A->getAsString(Args);
283        }
284      }
285    }
286
287    // Not translated, render as usual.
288    A->claim();
289    A->render(Args, CmdArgs);
290  }
291
292  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
293  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
294
295  // Add C++ include arguments, if needed.
296  types::ID InputType = Inputs[0].getType();
297  if (types::isCXX(InputType))
298    getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
299
300  // Add -Wp, and -Xassembler if using the preprocessor.
301
302  // FIXME: There is a very unfortunate problem here, some troubled
303  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
304  // really support that we would have to parse and then translate
305  // those options. :(
306  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
307                       options::OPT_Xpreprocessor);
308
309  // -I- is a deprecated GCC feature, reject it.
310  if (Arg *A = Args.getLastArg(options::OPT_I_))
311    D.Diag(clang::diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
312
313  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
314  // -isysroot to the CC1 invocation.
315  if (Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) {
316    if (!Args.hasArg(options::OPT_isysroot)) {
317      CmdArgs.push_back("-isysroot");
318      CmdArgs.push_back(A->getValue(Args));
319    }
320  }
321}
322
323/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targetting.
324//
325// FIXME: tblgen this.
326static const char *getARMTargetCPU(const ArgList &Args,
327                                   const llvm::Triple &Triple) {
328  // FIXME: Warn on inconsistent use of -mcpu and -march.
329
330  // If we have -mcpu=, use that.
331  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
332    return A->getValue(Args);
333
334  llvm::StringRef MArch;
335  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
336    // Otherwise, if we have -march= choose the base CPU for that arch.
337    MArch = A->getValue(Args);
338  } else {
339    // Otherwise, use the Arch from the triple.
340    MArch = Triple.getArchName();
341  }
342
343  if (MArch == "armv2" || MArch == "armv2a")
344    return "arm2";
345  if (MArch == "armv3")
346    return "arm6";
347  if (MArch == "armv3m")
348    return "arm7m";
349  if (MArch == "armv4" || MArch == "armv4t")
350    return "arm7tdmi";
351  if (MArch == "armv5" || MArch == "armv5t")
352    return "arm10tdmi";
353  if (MArch == "armv5e" || MArch == "armv5te")
354    return "arm1026ejs";
355  if (MArch == "armv5tej")
356    return "arm926ej-s";
357  if (MArch == "armv6" || MArch == "armv6k")
358    return "arm1136jf-s";
359  if (MArch == "armv6j")
360    return "arm1136j-s";
361  if (MArch == "armv6z" || MArch == "armv6zk")
362    return "arm1176jzf-s";
363  if (MArch == "armv6t2")
364    return "arm1156t2-s";
365  if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
366    return "cortex-a8";
367  if (MArch == "armv7r" || MArch == "armv7-r")
368    return "cortex-r4";
369  if (MArch == "armv7m" || MArch == "armv7-m")
370    return "cortex-m3";
371  if (MArch == "ep9312")
372    return "ep9312";
373  if (MArch == "iwmmxt")
374    return "iwmmxt";
375  if (MArch == "xscale")
376    return "xscale";
377  if (MArch == "armv6m" || MArch == "armv6-m")
378    return "cortex-m0";
379
380  // If all else failed, return the most base CPU LLVM supports.
381  return "arm7tdmi";
382}
383
384/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
385/// CPU.
386//
387// FIXME: This is redundant with -mcpu, why does LLVM use this.
388// FIXME: tblgen this, or kill it!
389static const char *getLLVMArchSuffixForARM(llvm::StringRef CPU) {
390  if (CPU == "arm7tdmi" || CPU == "arm7tdmi-s" || CPU == "arm710t" ||
391      CPU == "arm720t" || CPU == "arm9" || CPU == "arm9tdmi" ||
392      CPU == "arm920" || CPU == "arm920t" || CPU == "arm922t" ||
393      CPU == "arm940t" || CPU == "ep9312")
394    return "v4t";
395
396  if (CPU == "arm10tdmi" || CPU == "arm1020t")
397    return "v5";
398
399  if (CPU == "arm9e" || CPU == "arm926ej-s" || CPU == "arm946e-s" ||
400      CPU == "arm966e-s" || CPU == "arm968e-s" || CPU == "arm10e" ||
401      CPU == "arm1020e" || CPU == "arm1022e" || CPU == "xscale" ||
402      CPU == "iwmmxt")
403    return "v5e";
404
405  if (CPU == "arm1136j-s" || CPU == "arm1136jf-s" || CPU == "arm1176jz-s" ||
406      CPU == "arm1176jzf-s" || CPU == "mpcorenovfp" || CPU == "mpcore")
407    return "v6";
408
409  if (CPU == "arm1156t2-s" || CPU == "arm1156t2f-s")
410    return "v6t2";
411
412  if (CPU == "cortex-a8" || CPU == "cortex-a9")
413    return "v7";
414
415  return "";
416}
417
418// FIXME: Move to target hook.
419static bool isSignedCharDefault(const llvm::Triple &Triple) {
420  switch (Triple.getArch()) {
421  default:
422    return true;
423
424  case llvm::Triple::ppc:
425  case llvm::Triple::ppc64:
426    if (Triple.getOS() == llvm::Triple::Darwin)
427      return true;
428    return false;
429
430  case llvm::Triple::systemz:
431    return false;
432  }
433}
434
435void Clang::AddARMTargetArgs(const ArgList &Args,
436                             ArgStringList &CmdArgs,
437                             bool KernelOrKext) const {
438  const Driver &D = getToolChain().getDriver();
439  llvm::Triple Triple = getToolChain().getTriple();
440
441  // Disable movt generation, if requested.
442#ifdef DISABLE_ARM_DARWIN_USE_MOVT
443  CmdArgs.push_back("-backend-option");
444  CmdArgs.push_back("-arm-darwin-use-movt=0");
445#endif
446
447  // Select the ABI to use.
448  //
449  // FIXME: Support -meabi.
450  const char *ABIName = 0;
451  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
452    ABIName = A->getValue(Args);
453  } else {
454    // Select the default based on the platform.
455    switch(Triple.getEnvironment()) {
456    case llvm::Triple::GNUEABI:
457      ABIName = "aapcs-linux";
458      break;
459    case llvm::Triple::EABI:
460      ABIName = "aapcs";
461      break;
462    default:
463      ABIName = "apcs-gnu";
464    }
465  }
466  CmdArgs.push_back("-target-abi");
467  CmdArgs.push_back(ABIName);
468
469  // Set the CPU based on -march= and -mcpu=.
470  CmdArgs.push_back("-target-cpu");
471  CmdArgs.push_back(getARMTargetCPU(Args, Triple));
472
473  // Select the float ABI as determined by -msoft-float, -mhard-float, and
474  // -mfloat-abi=.
475  llvm::StringRef FloatABI;
476  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
477                               options::OPT_mhard_float,
478                               options::OPT_mfloat_abi_EQ)) {
479    if (A->getOption().matches(options::OPT_msoft_float))
480      FloatABI = "soft";
481    else if (A->getOption().matches(options::OPT_mhard_float))
482      FloatABI = "hard";
483    else {
484      FloatABI = A->getValue(Args);
485      if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
486        D.Diag(clang::diag::err_drv_invalid_mfloat_abi)
487          << A->getAsString(Args);
488        FloatABI = "soft";
489      }
490    }
491  }
492
493  // If unspecified, choose the default based on the platform.
494  if (FloatABI.empty()) {
495    const llvm::Triple &Triple = getToolChain().getTriple();
496    switch (Triple.getOS()) {
497    case llvm::Triple::Darwin: {
498      // Darwin defaults to "softfp" for v6 and v7.
499      //
500      // FIXME: Factor out an ARM class so we can cache the arch somewhere.
501      llvm::StringRef ArchName =
502        getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
503      if (ArchName.startswith("v6") || ArchName.startswith("v7"))
504        FloatABI = "softfp";
505      else
506        FloatABI = "soft";
507      break;
508    }
509
510    case llvm::Triple::Linux: {
511      if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUEABI) {
512        FloatABI = "softfp";
513        break;
514      }
515    }
516    // fall through
517
518    default:
519      switch(Triple.getEnvironment()) {
520      case llvm::Triple::GNUEABI:
521        FloatABI = "softfp";
522        break;
523      case llvm::Triple::EABI:
524        // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
525        FloatABI = "softfp";
526        break;
527      default:
528        // Assume "soft", but warn the user we are guessing.
529        FloatABI = "soft";
530        D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
531        break;
532      }
533    }
534  }
535
536  if (FloatABI == "soft") {
537    // Floating point operations and argument passing are soft.
538    //
539    // FIXME: This changes CPP defines, we need -target-soft-float.
540    CmdArgs.push_back("-msoft-float");
541    CmdArgs.push_back("-mfloat-abi");
542    CmdArgs.push_back("soft");
543  } else if (FloatABI == "softfp") {
544    // Floating point operations are hard, but argument passing is soft.
545    CmdArgs.push_back("-mfloat-abi");
546    CmdArgs.push_back("soft");
547  } else {
548    // Floating point operations and argument passing are hard.
549    assert(FloatABI == "hard" && "Invalid float abi!");
550    CmdArgs.push_back("-mfloat-abi");
551    CmdArgs.push_back("hard");
552  }
553
554  // Set appropriate target features for floating point mode.
555  //
556  // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
557  // yet (it uses the -mfloat-abi and -msoft-float options above), and it is
558  // stripped out by the ARM target.
559
560  // Use software floating point operations?
561  if (FloatABI == "soft") {
562    CmdArgs.push_back("-target-feature");
563    CmdArgs.push_back("+soft-float");
564  }
565
566  // Use software floating point argument passing?
567  if (FloatABI != "hard") {
568    CmdArgs.push_back("-target-feature");
569    CmdArgs.push_back("+soft-float-abi");
570  }
571
572  // Honor -mfpu=.
573  //
574  // FIXME: Centralize feature selection, defaulting shouldn't be also in the
575  // frontend target.
576  if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ)) {
577    llvm::StringRef FPU = A->getValue(Args);
578
579    // Set the target features based on the FPU.
580    if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
581      // Disable any default FPU support.
582      CmdArgs.push_back("-target-feature");
583      CmdArgs.push_back("-vfp2");
584      CmdArgs.push_back("-target-feature");
585      CmdArgs.push_back("-vfp3");
586      CmdArgs.push_back("-target-feature");
587      CmdArgs.push_back("-neon");
588    } else if (FPU == "vfp") {
589      CmdArgs.push_back("-target-feature");
590      CmdArgs.push_back("+vfp2");
591    } else if (FPU == "vfp3") {
592      CmdArgs.push_back("-target-feature");
593      CmdArgs.push_back("+vfp3");
594    } else if (FPU == "neon") {
595      CmdArgs.push_back("-target-feature");
596      CmdArgs.push_back("+neon");
597    } else
598      D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
599  }
600
601  // Setting -msoft-float effectively disables NEON because of the GCC
602  // implementation, although the same isn't true of VFP or VFP3.
603  if (FloatABI == "soft") {
604    CmdArgs.push_back("-target-feature");
605    CmdArgs.push_back("-neon");
606  }
607
608  // Kernel code has more strict alignment requirements.
609  if (KernelOrKext) {
610    CmdArgs.push_back("-backend-option");
611    CmdArgs.push_back("-arm-long-calls");
612
613    CmdArgs.push_back("-backend-option");
614    CmdArgs.push_back("-arm-strict-align");
615  }
616}
617
618void Clang::AddMIPSTargetArgs(const ArgList &Args,
619                             ArgStringList &CmdArgs) const {
620  const Driver &D = getToolChain().getDriver();
621
622  // Select the ABI to use.
623  const char *ABIName = 0;
624  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
625    ABIName = A->getValue(Args);
626  } else {
627    ABIName = "o32";
628  }
629
630  CmdArgs.push_back("-target-abi");
631  CmdArgs.push_back(ABIName);
632
633  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
634    llvm::StringRef MArch = A->getValue(Args);
635    CmdArgs.push_back("-target-cpu");
636
637    if ((MArch == "r2000") || (MArch == "r3000"))
638      CmdArgs.push_back("mips1");
639    else if (MArch == "r6000")
640      CmdArgs.push_back("mips2");
641    else
642      CmdArgs.push_back(MArch.str().c_str());
643  }
644
645  // Select the float ABI as determined by -msoft-float, -mhard-float, and
646  llvm::StringRef FloatABI;
647  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
648                               options::OPT_mhard_float)) {
649    if (A->getOption().matches(options::OPT_msoft_float))
650      FloatABI = "soft";
651    else if (A->getOption().matches(options::OPT_mhard_float))
652      FloatABI = "hard";
653  }
654
655  // If unspecified, choose the default based on the platform.
656  if (FloatABI.empty()) {
657    // Assume "soft", but warn the user we are guessing.
658    FloatABI = "soft";
659    D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
660  }
661
662  if (FloatABI == "soft") {
663    // Floating point operations and argument passing are soft.
664    //
665    // FIXME: This changes CPP defines, we need -target-soft-float.
666    CmdArgs.push_back("-msoft-float");
667  } else {
668    assert(FloatABI == "hard" && "Invalid float abi!");
669    CmdArgs.push_back("-mhard-float");
670  }
671}
672
673void Clang::AddSparcTargetArgs(const ArgList &Args,
674                             ArgStringList &CmdArgs) const {
675  const Driver &D = getToolChain().getDriver();
676
677  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
678    llvm::StringRef MArch = A->getValue(Args);
679    CmdArgs.push_back("-target-cpu");
680    CmdArgs.push_back(MArch.str().c_str());
681  }
682
683  // Select the float ABI as determined by -msoft-float, -mhard-float, and
684  llvm::StringRef FloatABI;
685  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
686                               options::OPT_mhard_float)) {
687    if (A->getOption().matches(options::OPT_msoft_float))
688      FloatABI = "soft";
689    else if (A->getOption().matches(options::OPT_mhard_float))
690      FloatABI = "hard";
691  }
692
693  // If unspecified, choose the default based on the platform.
694  if (FloatABI.empty()) {
695    switch (getToolChain().getTriple().getOS()) {
696    default:
697      // Assume "soft", but warn the user we are guessing.
698      FloatABI = "soft";
699      D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
700      break;
701    }
702  }
703
704  if (FloatABI == "soft") {
705    // Floating point operations and argument passing are soft.
706    //
707    // FIXME: This changes CPP defines, we need -target-soft-float.
708    CmdArgs.push_back("-msoft-float");
709    CmdArgs.push_back("soft");
710    CmdArgs.push_back("-target-feature");
711    CmdArgs.push_back("+soft-float");
712  } else {
713    assert(FloatABI == "hard" && "Invalid float abi!");
714    CmdArgs.push_back("-mhard-float");
715  }
716}
717
718void Clang::AddX86TargetArgs(const ArgList &Args,
719                             ArgStringList &CmdArgs) const {
720  if (!Args.hasFlag(options::OPT_mred_zone,
721                    options::OPT_mno_red_zone,
722                    true) ||
723      Args.hasArg(options::OPT_mkernel) ||
724      Args.hasArg(options::OPT_fapple_kext))
725    CmdArgs.push_back("-disable-red-zone");
726
727  if (Args.hasFlag(options::OPT_msoft_float,
728                   options::OPT_mno_soft_float,
729                   false))
730    CmdArgs.push_back("-no-implicit-float");
731
732  const char *CPUName = 0;
733  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
734    if (llvm::StringRef(A->getValue(Args)) == "native") {
735      // FIXME: Reject attempts to use -march=native unless the target matches
736      // the host.
737      //
738      // FIXME: We should also incorporate the detected target features for use
739      // with -native.
740      std::string CPU = llvm::sys::getHostCPUName();
741      if (!CPU.empty())
742        CPUName = Args.MakeArgString(CPU);
743    } else
744      CPUName = A->getValue(Args);
745  }
746
747  // Select the default CPU if none was given (or detection failed).
748  if (!CPUName) {
749    // FIXME: Need target hooks.
750    if (getToolChain().getOS().startswith("darwin")) {
751      if (getToolChain().getArchName() == "x86_64")
752        CPUName = "core2";
753      else if (getToolChain().getArchName() == "i386")
754        CPUName = "yonah";
755    } else if (getToolChain().getOS().startswith("haiku"))  {
756      if (getToolChain().getArchName() == "x86_64")
757        CPUName = "x86-64";
758      else if (getToolChain().getArchName() == "i386")
759        CPUName = "i586";
760    } else if (getToolChain().getOS().startswith("openbsd"))  {
761      if (getToolChain().getArchName() == "x86_64")
762        CPUName = "x86-64";
763      else if (getToolChain().getArchName() == "i386")
764        CPUName = "i486";
765    } else if (getToolChain().getOS().startswith("freebsd"))  {
766      if (getToolChain().getArchName() == "x86_64")
767        CPUName = "x86-64";
768      else if (getToolChain().getArchName() == "i386")
769        CPUName = "i486";
770    } else if (getToolChain().getOS().startswith("netbsd"))  {
771      if (getToolChain().getArchName() == "x86_64")
772        CPUName = "x86-64";
773      else if (getToolChain().getArchName() == "i386")
774        CPUName = "i486";
775    } else {
776      if (getToolChain().getArchName() == "x86_64")
777        CPUName = "x86-64";
778      else if (getToolChain().getArchName() == "i386")
779        CPUName = "pentium4";
780    }
781  }
782
783  if (CPUName) {
784    CmdArgs.push_back("-target-cpu");
785    CmdArgs.push_back(CPUName);
786  }
787
788  for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
789         ie = Args.filtered_end(); it != ie; ++it) {
790    llvm::StringRef Name = (*it)->getOption().getName();
791    (*it)->claim();
792
793    // Skip over "-m".
794    assert(Name.startswith("-m") && "Invalid feature name.");
795    Name = Name.substr(2);
796
797    bool IsNegative = Name.startswith("no-");
798    if (IsNegative)
799      Name = Name.substr(3);
800
801    CmdArgs.push_back("-target-feature");
802    CmdArgs.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
803  }
804}
805
806static bool
807shouldUseExceptionTablesForObjCExceptions(const ArgList &Args,
808                                          const llvm::Triple &Triple) {
809  // We use the zero-cost exception tables for Objective-C if the non-fragile
810  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
811  // later.
812
813  if (Args.hasArg(options::OPT_fobjc_nonfragile_abi))
814    return true;
815
816  if (Triple.getOS() != llvm::Triple::Darwin)
817    return false;
818
819  return (Triple.getDarwinMajorNumber() >= 9 &&
820          (Triple.getArch() == llvm::Triple::x86_64 ||
821           Triple.getArch() == llvm::Triple::arm));
822}
823
824/// addExceptionArgs - Adds exception related arguments to the driver command
825/// arguments. There's a master flag, -fexceptions and also language specific
826/// flags to enable/disable C++ and Objective-C exceptions.
827/// This makes it possible to for example disable C++ exceptions but enable
828/// Objective-C exceptions.
829static void addExceptionArgs(const ArgList &Args, types::ID InputType,
830                             const llvm::Triple &Triple,
831                             bool KernelOrKext, bool IsRewriter,
832                             ArgStringList &CmdArgs) {
833  if (KernelOrKext)
834    return;
835
836  // Exceptions are enabled by default.
837  bool ExceptionsEnabled = true;
838
839  // This keeps track of whether exceptions were explicitly turned on or off.
840  bool DidHaveExplicitExceptionFlag = false;
841
842  if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
843                               options::OPT_fno_exceptions)) {
844    if (A->getOption().matches(options::OPT_fexceptions))
845      ExceptionsEnabled = true;
846    else
847      ExceptionsEnabled = false;
848
849    DidHaveExplicitExceptionFlag = true;
850  }
851
852  bool ShouldUseExceptionTables = false;
853
854  // Exception tables and cleanups can be enabled with -fexceptions even if the
855  // language itself doesn't support exceptions.
856  if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
857    ShouldUseExceptionTables = true;
858
859  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
860  // is not necessarily sensible, but follows GCC.
861  if (types::isObjC(InputType) &&
862      Args.hasFlag(options::OPT_fobjc_exceptions,
863                   options::OPT_fno_objc_exceptions,
864                   true)) {
865    CmdArgs.push_back("-fobjc-exceptions");
866
867    ShouldUseExceptionTables |=
868      shouldUseExceptionTablesForObjCExceptions(Args, Triple);
869  }
870
871  if (types::isCXX(InputType)) {
872    bool CXXExceptionsEnabled = ExceptionsEnabled;
873
874    if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
875                                 options::OPT_fno_cxx_exceptions,
876                                 options::OPT_fexceptions,
877                                 options::OPT_fno_exceptions)) {
878      if (A->getOption().matches(options::OPT_fcxx_exceptions))
879        CXXExceptionsEnabled = true;
880      else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
881        CXXExceptionsEnabled = false;
882    }
883
884    if (CXXExceptionsEnabled) {
885      CmdArgs.push_back("-fcxx-exceptions");
886
887      ShouldUseExceptionTables = true;
888    }
889  }
890
891  if (ShouldUseExceptionTables)
892    CmdArgs.push_back("-fexceptions");
893}
894
895void Clang::ConstructJob(Compilation &C, const JobAction &JA,
896                         const InputInfo &Output,
897                         const InputInfoList &Inputs,
898                         const ArgList &Args,
899                         const char *LinkingOutput) const {
900  bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
901                                  options::OPT_fapple_kext);
902  const Driver &D = getToolChain().getDriver();
903  ArgStringList CmdArgs;
904
905  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
906
907  // Invoke ourselves in -cc1 mode.
908  //
909  // FIXME: Implement custom jobs for internal actions.
910  CmdArgs.push_back("-cc1");
911
912  // Add the "effective" target triple.
913  CmdArgs.push_back("-triple");
914  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
915  CmdArgs.push_back(Args.MakeArgString(TripleStr));
916
917  // Select the appropriate action.
918  bool IsRewriter = false;
919  if (isa<AnalyzeJobAction>(JA)) {
920    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
921    CmdArgs.push_back("-analyze");
922  } else if (isa<PreprocessJobAction>(JA)) {
923    if (Output.getType() == types::TY_Dependencies)
924      CmdArgs.push_back("-Eonly");
925    else
926      CmdArgs.push_back("-E");
927  } else if (isa<AssembleJobAction>(JA)) {
928    CmdArgs.push_back("-emit-obj");
929
930    // At -O0, we use -mrelax-all by default.
931    bool IsOpt = false;
932    if (Arg *A = Args.getLastArg(options::OPT_O_Group))
933      IsOpt = !A->getOption().matches(options::OPT_O0);
934    if (Args.hasFlag(options::OPT_mrelax_all,
935                      options::OPT_mno_relax_all,
936                      !IsOpt))
937      CmdArgs.push_back("-mrelax-all");
938
939    // When using an integrated assembler, translate -Wa, and -Xassembler
940    // options.
941    for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
942                                               options::OPT_Xassembler),
943           ie = Args.filtered_end(); it != ie; ++it) {
944      const Arg *A = *it;
945      A->claim();
946
947      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
948        llvm::StringRef Value = A->getValue(Args, i);
949
950        if (Value == "-force_cpusubtype_ALL") {
951          // Do nothing, this is the default and we don't support anything else.
952        } else if (Value == "-L") {
953          // We don't support -L yet, but it isn't important enough to error
954          // on. No one should really be using it for a semantic change.
955          D.Diag(clang::diag::warn_drv_unsupported_option_argument)
956            << A->getOption().getName() << Value;
957        } else {
958          D.Diag(clang::diag::err_drv_unsupported_option_argument)
959            << A->getOption().getName() << Value;
960        }
961      }
962    }
963
964    // Also ignore explicit -force_cpusubtype_ALL option.
965    (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
966  } else if (isa<PrecompileJobAction>(JA)) {
967    // Use PCH if the user requested it.
968    bool UsePCH = D.CCCUsePCH;
969
970    if (UsePCH)
971      CmdArgs.push_back("-emit-pch");
972    else
973      CmdArgs.push_back("-emit-pth");
974  } else {
975    assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
976
977    if (JA.getType() == types::TY_Nothing) {
978      CmdArgs.push_back("-fsyntax-only");
979    } else if (JA.getType() == types::TY_LLVM_IR ||
980               JA.getType() == types::TY_LTO_IR) {
981      CmdArgs.push_back("-emit-llvm");
982    } else if (JA.getType() == types::TY_LLVM_BC ||
983               JA.getType() == types::TY_LTO_BC) {
984      CmdArgs.push_back("-emit-llvm-bc");
985    } else if (JA.getType() == types::TY_PP_Asm) {
986      CmdArgs.push_back("-S");
987    } else if (JA.getType() == types::TY_AST) {
988      CmdArgs.push_back("-emit-pch");
989    } else if (JA.getType() == types::TY_RewrittenObjC) {
990      CmdArgs.push_back("-rewrite-objc");
991      IsRewriter = true;
992    } else {
993      assert(JA.getType() == types::TY_PP_Asm &&
994             "Unexpected output type!");
995    }
996  }
997
998  // The make clang go fast button.
999  CmdArgs.push_back("-disable-free");
1000
1001  // Disable the verification pass in -asserts builds.
1002#ifdef NDEBUG
1003  CmdArgs.push_back("-disable-llvm-verifier");
1004#endif
1005
1006  // Set the main file name, so that debug info works even with
1007  // -save-temps.
1008  CmdArgs.push_back("-main-file-name");
1009  CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
1010
1011  // Some flags which affect the language (via preprocessor
1012  // defines). See darwin::CC1::AddCPPArgs.
1013  if (Args.hasArg(options::OPT_static))
1014    CmdArgs.push_back("-static-define");
1015
1016  if (isa<AnalyzeJobAction>(JA)) {
1017    // Enable region store model by default.
1018    CmdArgs.push_back("-analyzer-store=region");
1019
1020    // Treat blocks as analysis entry points.
1021    CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
1022
1023    CmdArgs.push_back("-analyzer-eagerly-assume");
1024
1025    // Add default argument set.
1026    if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
1027      CmdArgs.push_back("-analyzer-checker=core");
1028      CmdArgs.push_back("-analyzer-checker=deadcode");
1029      CmdArgs.push_back("-analyzer-checker=security");
1030
1031      if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
1032        CmdArgs.push_back("-analyzer-checker=unix");
1033
1034      if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
1035        CmdArgs.push_back("-analyzer-checker=osx");
1036    }
1037
1038    // Set the output format. The default is plist, for (lame) historical
1039    // reasons.
1040    CmdArgs.push_back("-analyzer-output");
1041    if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
1042      CmdArgs.push_back(A->getValue(Args));
1043    else
1044      CmdArgs.push_back("plist");
1045
1046    // Disable the presentation of standard compiler warnings when
1047    // using --analyze.  We only want to show static analyzer diagnostics
1048    // or frontend errors.
1049    CmdArgs.push_back("-w");
1050
1051    // Add -Xanalyzer arguments when running as analyzer.
1052    Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
1053  }
1054
1055  CheckCodeGenerationOptions(D, Args);
1056
1057  // Perform argument translation for LLVM backend. This
1058  // takes some care in reconciling with llvm-gcc. The
1059  // issue is that llvm-gcc translates these options based on
1060  // the values in cc1, whereas we are processing based on
1061  // the driver arguments.
1062
1063  // This comes from the default translation the driver + cc1
1064  // would do to enable flag_pic.
1065  //
1066  // FIXME: Centralize this code.
1067  bool PICEnabled = (Args.hasArg(options::OPT_fPIC) ||
1068                     Args.hasArg(options::OPT_fpic) ||
1069                     Args.hasArg(options::OPT_fPIE) ||
1070                     Args.hasArg(options::OPT_fpie));
1071  bool PICDisabled = (Args.hasArg(options::OPT_mkernel) ||
1072                      Args.hasArg(options::OPT_static));
1073  const char *Model = getToolChain().GetForcedPicModel();
1074  if (!Model) {
1075    if (Args.hasArg(options::OPT_mdynamic_no_pic))
1076      Model = "dynamic-no-pic";
1077    else if (PICDisabled)
1078      Model = "static";
1079    else if (PICEnabled)
1080      Model = "pic";
1081    else
1082      Model = getToolChain().GetDefaultRelocationModel();
1083  }
1084  if (llvm::StringRef(Model) != "pic") {
1085    CmdArgs.push_back("-mrelocation-model");
1086    CmdArgs.push_back(Model);
1087  }
1088
1089  // Infer the __PIC__ value.
1090  //
1091  // FIXME:  This isn't quite right on Darwin, which always sets
1092  // __PIC__=2.
1093  if (strcmp(Model, "pic") == 0 || strcmp(Model, "dynamic-no-pic") == 0) {
1094    CmdArgs.push_back("-pic-level");
1095    CmdArgs.push_back(Args.hasArg(options::OPT_fPIC) ? "2" : "1");
1096  }
1097  if (!Args.hasFlag(options::OPT_fmerge_all_constants,
1098                    options::OPT_fno_merge_all_constants))
1099    CmdArgs.push_back("-no-merge-all-constants");
1100
1101  // LLVM Code Generator Options.
1102
1103  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1104    CmdArgs.push_back("-mregparm");
1105    CmdArgs.push_back(A->getValue(Args));
1106  }
1107
1108  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
1109    CmdArgs.push_back("-mrtd");
1110
1111  // FIXME: Set --enable-unsafe-fp-math.
1112  if (Args.hasFlag(options::OPT_fno_omit_frame_pointer,
1113                   options::OPT_fomit_frame_pointer))
1114    CmdArgs.push_back("-mdisable-fp-elim");
1115  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
1116                    options::OPT_fno_zero_initialized_in_bss))
1117    CmdArgs.push_back("-mno-zero-initialized-in-bss");
1118  if (!Args.hasFlag(options::OPT_fstrict_aliasing,
1119                    options::OPT_fno_strict_aliasing,
1120                    getToolChain().IsStrictAliasingDefault()))
1121    CmdArgs.push_back("-relaxed-aliasing");
1122
1123  // Decide whether to use verbose asm. Verbose assembly is the default on
1124  // toolchains which have the integrated assembler on by default.
1125  bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
1126  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
1127                   IsVerboseAsmDefault) ||
1128      Args.hasArg(options::OPT_dA))
1129    CmdArgs.push_back("-masm-verbose");
1130
1131  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
1132    CmdArgs.push_back("-mdebug-pass");
1133    CmdArgs.push_back("Structure");
1134  }
1135  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
1136    CmdArgs.push_back("-mdebug-pass");
1137    CmdArgs.push_back("Arguments");
1138  }
1139
1140  // Enable -mconstructor-aliases except on darwin, where we have to
1141  // work around a linker bug;  see <rdar://problem/7651567>.
1142  if (getToolChain().getTriple().getOS() != llvm::Triple::Darwin)
1143    CmdArgs.push_back("-mconstructor-aliases");
1144
1145  // Darwin's kernel doesn't support guard variables; just die if we
1146  // try to use them.
1147  if (KernelOrKext &&
1148      getToolChain().getTriple().getOS() == llvm::Triple::Darwin)
1149    CmdArgs.push_back("-fforbid-guard-variables");
1150
1151  if (Args.hasArg(options::OPT_mms_bitfields)) {
1152    CmdArgs.push_back("-mms-bitfields");
1153  }
1154
1155  // This is a coarse approximation of what llvm-gcc actually does, both
1156  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
1157  // complicated ways.
1158  bool AsynchronousUnwindTables =
1159    Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
1160                 options::OPT_fno_asynchronous_unwind_tables,
1161                 getToolChain().IsUnwindTablesDefault() &&
1162                 !KernelOrKext);
1163  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
1164                   AsynchronousUnwindTables))
1165    CmdArgs.push_back("-munwind-tables");
1166
1167  if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
1168    CmdArgs.push_back("-mlimit-float-precision");
1169    CmdArgs.push_back(A->getValue(Args));
1170  }
1171
1172  // FIXME: Handle -mtune=.
1173  (void) Args.hasArg(options::OPT_mtune_EQ);
1174
1175  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
1176    CmdArgs.push_back("-mcode-model");
1177    CmdArgs.push_back(A->getValue(Args));
1178  }
1179
1180  // Add target specific cpu and features flags.
1181  switch(getToolChain().getTriple().getArch()) {
1182  default:
1183    break;
1184
1185  case llvm::Triple::arm:
1186  case llvm::Triple::thumb:
1187    AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
1188    break;
1189
1190  case llvm::Triple::mips:
1191  case llvm::Triple::mipsel:
1192    AddMIPSTargetArgs(Args, CmdArgs);
1193    break;
1194
1195  case llvm::Triple::sparc:
1196    AddSparcTargetArgs(Args, CmdArgs);
1197    break;
1198
1199  case llvm::Triple::x86:
1200  case llvm::Triple::x86_64:
1201    AddX86TargetArgs(Args, CmdArgs);
1202    break;
1203  }
1204
1205  // Pass the linker version in use.
1206  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
1207    CmdArgs.push_back("-target-linker-version");
1208    CmdArgs.push_back(A->getValue(Args));
1209  }
1210
1211  // -mno-omit-leaf-frame-pointer is the default on Darwin.
1212  if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
1213                   options::OPT_mno_omit_leaf_frame_pointer,
1214                   getToolChain().getTriple().getOS() != llvm::Triple::Darwin))
1215    CmdArgs.push_back("-momit-leaf-frame-pointer");
1216
1217  // -fno-math-errno is default.
1218  if (Args.hasFlag(options::OPT_fmath_errno,
1219                   options::OPT_fno_math_errno,
1220                   false))
1221    CmdArgs.push_back("-fmath-errno");
1222
1223  // Explicitly error on some things we know we don't support and can't just
1224  // ignore.
1225  types::ID InputType = Inputs[0].getType();
1226  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
1227    Arg *Unsupported;
1228    if ((Unsupported = Args.getLastArg(options::OPT_MG)) ||
1229        (Unsupported = Args.getLastArg(options::OPT_iframework)))
1230      D.Diag(clang::diag::err_drv_clang_unsupported)
1231        << Unsupported->getOption().getName();
1232
1233    if (types::isCXX(InputType) &&
1234        getToolChain().getTriple().getOS() == llvm::Triple::Darwin &&
1235        getToolChain().getTriple().getArch() == llvm::Triple::x86) {
1236      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)))
1237        D.Diag(clang::diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
1238          << Unsupported->getOption().getName();
1239    }
1240  }
1241
1242  Args.AddAllArgs(CmdArgs, options::OPT_v);
1243  Args.AddLastArg(CmdArgs, options::OPT_H);
1244  if (D.CCPrintHeaders) {
1245    CmdArgs.push_back("-header-include-file");
1246    CmdArgs.push_back(D.CCPrintHeadersFilename ?
1247                      D.CCPrintHeadersFilename : "-");
1248  }
1249  Args.AddLastArg(CmdArgs, options::OPT_P);
1250  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
1251
1252  // Special case debug options to only pass -g to clang. This is
1253  // wrong.
1254  Args.ClaimAllArgs(options::OPT_g_Group);
1255  if (Arg *A = Args.getLastArg(options::OPT_g_Group))
1256    if (!A->getOption().matches(options::OPT_g0))
1257      CmdArgs.push_back("-g");
1258
1259  Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
1260  Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
1261
1262  Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
1263
1264  Args.AddLastArg(CmdArgs, options::OPT_nostdinc);
1265  Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
1266  Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
1267
1268  // Pass the path to compiler resource files.
1269  CmdArgs.push_back("-resource-dir");
1270  CmdArgs.push_back(D.ResourceDir.c_str());
1271
1272  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
1273
1274  // Add preprocessing options like -I, -D, etc. if we are using the
1275  // preprocessor.
1276  //
1277  // FIXME: Support -fpreprocessed
1278  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
1279    AddPreprocessingOptions(D, Args, CmdArgs, Output, Inputs);
1280
1281  // Manually translate -O to -O2 and -O4 to -O3; let clang reject
1282  // others.
1283  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1284    if (A->getOption().matches(options::OPT_O4))
1285      CmdArgs.push_back("-O3");
1286    else if (A->getOption().matches(options::OPT_O) &&
1287             A->getValue(Args)[0] == '\0')
1288      CmdArgs.push_back("-O2");
1289    else if (A->getOption().matches(options::OPT_O) &&
1290             A->getValue(Args)[0] == 'z' &&
1291             A->getValue(Args)[1] == '\0')
1292      CmdArgs.push_back("-Os");
1293    else
1294      A->render(Args, CmdArgs);
1295  }
1296
1297  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
1298  Args.AddLastArg(CmdArgs, options::OPT_pedantic);
1299  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
1300  Args.AddLastArg(CmdArgs, options::OPT_w);
1301
1302  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
1303  // (-ansi is equivalent to -std=c89).
1304  //
1305  // If a std is supplied, only add -trigraphs if it follows the
1306  // option.
1307  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
1308    if (Std->getOption().matches(options::OPT_ansi))
1309      if (types::isCXX(InputType))
1310        CmdArgs.push_back("-std=c++98");
1311      else
1312        CmdArgs.push_back("-std=c89");
1313    else
1314      Std->render(Args, CmdArgs);
1315
1316    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
1317                                 options::OPT_trigraphs))
1318      if (A != Std)
1319        A->render(Args, CmdArgs);
1320  } else {
1321    // Honor -std-default.
1322    //
1323    // FIXME: Clang doesn't correctly handle -std= when the input language
1324    // doesn't match. For the time being just ignore this for C++ inputs;
1325    // eventually we want to do all the standard defaulting here instead of
1326    // splitting it between the driver and clang -cc1.
1327    if (!types::isCXX(InputType))
1328        Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
1329                                  "-std=", /*Joined=*/true);
1330    Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
1331  }
1332
1333  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
1334  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
1335    if (Asm->getOption().matches(options::OPT_fasm))
1336      CmdArgs.push_back("-fgnu-keywords");
1337    else
1338      CmdArgs.push_back("-fno-gnu-keywords");
1339  }
1340
1341  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_)) {
1342    CmdArgs.push_back("-ftemplate-depth");
1343    CmdArgs.push_back(A->getValue(Args));
1344  }
1345
1346  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
1347                               options::OPT_Wlarge_by_value_copy_def)) {
1348    CmdArgs.push_back("-Wlarge-by-value-copy");
1349    if (A->getNumValues())
1350      CmdArgs.push_back(A->getValue(Args));
1351    else
1352      CmdArgs.push_back("64"); // default value for -Wlarge-by-value-copy.
1353  }
1354
1355  if (Args.hasArg(options::OPT__relocatable_pch))
1356    CmdArgs.push_back("-relocatable-pch");
1357
1358  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
1359    CmdArgs.push_back("-fconstant-string-class");
1360    CmdArgs.push_back(A->getValue(Args));
1361  }
1362
1363  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
1364    CmdArgs.push_back("-ftabstop");
1365    CmdArgs.push_back(A->getValue(Args));
1366  }
1367
1368  CmdArgs.push_back("-ferror-limit");
1369  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
1370    CmdArgs.push_back(A->getValue(Args));
1371  else
1372    CmdArgs.push_back("19");
1373
1374  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
1375    CmdArgs.push_back("-fmacro-backtrace-limit");
1376    CmdArgs.push_back(A->getValue(Args));
1377  }
1378
1379  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
1380    CmdArgs.push_back("-ftemplate-backtrace-limit");
1381    CmdArgs.push_back(A->getValue(Args));
1382  }
1383
1384  // Pass -fmessage-length=.
1385  CmdArgs.push_back("-fmessage-length");
1386  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
1387    CmdArgs.push_back(A->getValue(Args));
1388  } else {
1389    // If -fmessage-length=N was not specified, determine whether this is a
1390    // terminal and, if so, implicitly define -fmessage-length appropriately.
1391    unsigned N = llvm::sys::Process::StandardErrColumns();
1392    CmdArgs.push_back(Args.MakeArgString(llvm::Twine(N)));
1393  }
1394
1395  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) {
1396    CmdArgs.push_back("-fvisibility");
1397    CmdArgs.push_back(A->getValue(Args));
1398  }
1399
1400  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
1401
1402  // -fhosted is default.
1403  if (KernelOrKext || Args.hasFlag(options::OPT_ffreestanding,
1404                                   options::OPT_fhosted,
1405                                   false))
1406    CmdArgs.push_back("-ffreestanding");
1407
1408  // Forward -f (flag) options which we can pass directly.
1409  Args.AddLastArg(CmdArgs, options::OPT_fcatch_undefined_behavior);
1410  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
1411  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
1412  Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
1413  if (getToolChain().SupportsProfiling())
1414    Args.AddLastArg(CmdArgs, options::OPT_pg);
1415
1416  // -flax-vector-conversions is default.
1417  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
1418                    options::OPT_fno_lax_vector_conversions))
1419    CmdArgs.push_back("-fno-lax-vector-conversions");
1420
1421  // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
1422  // takes precedence.
1423  const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
1424  if (!GCArg)
1425    GCArg = Args.getLastArg(options::OPT_fobjc_gc);
1426  if (GCArg) {
1427    if (getToolChain().SupportsObjCGC()) {
1428      GCArg->render(Args, CmdArgs);
1429    } else {
1430      // FIXME: We should move this to a hard error.
1431      D.Diag(clang::diag::warn_drv_objc_gc_unsupported)
1432        << GCArg->getAsString(Args);
1433    }
1434  }
1435
1436  if (Args.getLastArg(options::OPT_fapple_kext))
1437    CmdArgs.push_back("-fapple-kext");
1438
1439  Args.AddLastArg(CmdArgs, options::OPT_fno_show_column);
1440  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
1441  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
1442  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
1443  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
1444  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
1445
1446  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
1447    CmdArgs.push_back("-ftrapv-handler");
1448    CmdArgs.push_back(A->getValue(Args));
1449  }
1450
1451  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
1452  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
1453  if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
1454                               options::OPT_fno_wrapv)) {
1455    if (A->getOption().matches(options::OPT_fwrapv))
1456      CmdArgs.push_back("-fwrapv");
1457  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
1458                                      options::OPT_fno_strict_overflow)) {
1459    if (A->getOption().matches(options::OPT_fno_strict_overflow))
1460      CmdArgs.push_back("-fwrapv");
1461  }
1462  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
1463  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
1464
1465  Args.AddLastArg(CmdArgs, options::OPT_pthread);
1466
1467  // -stack-protector=0 is default.
1468  unsigned StackProtectorLevel = 0;
1469  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
1470                               options::OPT_fstack_protector_all,
1471                               options::OPT_fstack_protector)) {
1472    if (A->getOption().matches(options::OPT_fstack_protector))
1473      StackProtectorLevel = 1;
1474    else if (A->getOption().matches(options::OPT_fstack_protector_all))
1475      StackProtectorLevel = 2;
1476  } else
1477    StackProtectorLevel = getToolChain().GetDefaultStackProtectorLevel();
1478  if (StackProtectorLevel) {
1479    CmdArgs.push_back("-stack-protector");
1480    CmdArgs.push_back(Args.MakeArgString(llvm::Twine(StackProtectorLevel)));
1481  }
1482
1483  // Forward -f options with positive and negative forms; we translate
1484  // these by hand.
1485
1486  if (Args.hasArg(options::OPT_mkernel)) {
1487    if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
1488      CmdArgs.push_back("-fapple-kext");
1489    if (!Args.hasArg(options::OPT_fbuiltin))
1490      CmdArgs.push_back("-fno-builtin");
1491  }
1492  // -fbuiltin is default.
1493  else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
1494    CmdArgs.push_back("-fno-builtin");
1495
1496  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1497                    options::OPT_fno_assume_sane_operator_new))
1498    CmdArgs.push_back("-fno-assume-sane-operator-new");
1499
1500  // -fblocks=0 is default.
1501  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
1502                   getToolChain().IsBlocksDefault()) ||
1503        (Args.hasArg(options::OPT_fgnu_runtime) &&
1504         Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
1505         !Args.hasArg(options::OPT_fno_blocks))) {
1506    CmdArgs.push_back("-fblocks");
1507  }
1508
1509  // -faccess-control is default.
1510  if (Args.hasFlag(options::OPT_fno_access_control,
1511                   options::OPT_faccess_control,
1512                   false))
1513    CmdArgs.push_back("-fno-access-control");
1514
1515  // -felide-constructors is the default.
1516  if (Args.hasFlag(options::OPT_fno_elide_constructors,
1517                   options::OPT_felide_constructors,
1518                   false))
1519    CmdArgs.push_back("-fno-elide-constructors");
1520
1521  // Add exception args.
1522  addExceptionArgs(Args, InputType, getToolChain().getTriple(),
1523                   KernelOrKext, IsRewriter, CmdArgs);
1524
1525  if (getToolChain().UseSjLjExceptions())
1526    CmdArgs.push_back("-fsjlj-exceptions");
1527
1528  // -frtti is default.
1529  if (KernelOrKext ||
1530      !Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti))
1531    CmdArgs.push_back("-fno-rtti");
1532
1533  // -fshort-enums=0 is default.
1534  // FIXME: Are there targers where -fshort-enums is on by default ?
1535  if (Args.hasFlag(options::OPT_fshort_enums,
1536                   options::OPT_fno_short_enums, false))
1537    CmdArgs.push_back("-fshort-enums");
1538
1539  // -fsigned-char is default.
1540  if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
1541                    isSignedCharDefault(getToolChain().getTriple())))
1542    CmdArgs.push_back("-fno-signed-char");
1543
1544  // -fthreadsafe-static is default.
1545  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
1546                    options::OPT_fno_threadsafe_statics))
1547    CmdArgs.push_back("-fno-threadsafe-statics");
1548
1549  // -fuse-cxa-atexit is default.
1550  if (KernelOrKext ||
1551    !Args.hasFlag(options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
1552                  getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
1553                  getToolChain().getTriple().getOS() != llvm::Triple::MinGW32))
1554    CmdArgs.push_back("-fno-use-cxa-atexit");
1555
1556  // -fms-extensions=0 is default.
1557  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1558                   getToolChain().getTriple().getOS() == llvm::Triple::Win32))
1559    CmdArgs.push_back("-fms-extensions");
1560
1561  // -fmsc-version=1300 is default.
1562  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1563                   getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
1564      Args.hasArg(options::OPT_fmsc_version)) {
1565    llvm::StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
1566    if (msc_ver.empty())
1567      CmdArgs.push_back("-fmsc-version=1300");
1568    else
1569      CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
1570  }
1571
1572
1573  // -fborland-extensions=0 is default.
1574  if (Args.hasFlag(options::OPT_fborland_extensions,
1575                   options::OPT_fno_borland_extensions, false))
1576    CmdArgs.push_back("-fborland-extensions");
1577
1578  // -fgnu-keywords default varies depending on language; only pass if
1579  // specified.
1580  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
1581                               options::OPT_fno_gnu_keywords))
1582    A->render(Args, CmdArgs);
1583
1584  // -fnext-runtime defaults to on Darwin and when rewriting Objective-C, and is
1585  // -the -cc1 default.
1586  bool NeXTRuntimeIsDefault =
1587    IsRewriter || getToolChain().getTriple().getOS() == llvm::Triple::Darwin;
1588  if (!Args.hasFlag(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
1589                    NeXTRuntimeIsDefault))
1590    CmdArgs.push_back("-fgnu-runtime");
1591
1592  // -fobjc-nonfragile-abi=0 is default.
1593  if (types::isObjC(InputType)) {
1594    // Compute the Objective-C ABI "version" to use. Version numbers are
1595    // slightly confusing for historical reasons:
1596    //   1 - Traditional "fragile" ABI
1597    //   2 - Non-fragile ABI, version 1
1598    //   3 - Non-fragile ABI, version 2
1599    unsigned Version = 1;
1600    // If -fobjc-abi-version= is present, use that to set the version.
1601    if (Arg *A = Args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
1602      if (llvm::StringRef(A->getValue(Args)) == "1")
1603        Version = 1;
1604      else if (llvm::StringRef(A->getValue(Args)) == "2")
1605        Version = 2;
1606      else if (llvm::StringRef(A->getValue(Args)) == "3")
1607        Version = 3;
1608      else
1609        D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
1610    } else {
1611      // Otherwise, determine if we are using the non-fragile ABI.
1612      if (Args.hasFlag(options::OPT_fobjc_nonfragile_abi,
1613                       options::OPT_fno_objc_nonfragile_abi,
1614                       getToolChain().IsObjCNonFragileABIDefault())) {
1615        // Determine the non-fragile ABI version to use.
1616#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
1617        unsigned NonFragileABIVersion = 1;
1618#else
1619        unsigned NonFragileABIVersion = 2;
1620#endif
1621
1622        if (Arg *A = Args.getLastArg(
1623              options::OPT_fobjc_nonfragile_abi_version_EQ)) {
1624          if (llvm::StringRef(A->getValue(Args)) == "1")
1625            NonFragileABIVersion = 1;
1626          else if (llvm::StringRef(A->getValue(Args)) == "2")
1627            NonFragileABIVersion = 2;
1628          else
1629            D.Diag(clang::diag::err_drv_clang_unsupported)
1630              << A->getAsString(Args);
1631        }
1632
1633        Version = 1 + NonFragileABIVersion;
1634      } else {
1635        Version = 1;
1636      }
1637    }
1638
1639    if (Version == 2 || Version == 3) {
1640      CmdArgs.push_back("-fobjc-nonfragile-abi");
1641
1642      // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
1643      // legacy is the default.
1644      if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
1645                        options::OPT_fno_objc_legacy_dispatch,
1646                        getToolChain().IsObjCLegacyDispatchDefault())) {
1647        if (getToolChain().UseObjCMixedDispatch())
1648          CmdArgs.push_back("-fobjc-dispatch-method=mixed");
1649        else
1650          CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
1651      }
1652    }
1653
1654    // -fobjc-default-synthesize-properties=0 is default.
1655    if (Args.hasFlag(options::OPT_fobjc_default_synthesize_properties,
1656                     options::OPT_fno_objc_default_synthesize_properties,
1657                     getToolChain().IsObjCDefaultSynthPropertiesDefault())) {
1658      CmdArgs.push_back("-fobjc-default-synthesize-properties");
1659    }
1660  }
1661
1662  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1663                    options::OPT_fno_assume_sane_operator_new))
1664    CmdArgs.push_back("-fno-assume-sane-operator-new");
1665
1666  // -fconstant-cfstrings is default, and may be subject to argument translation
1667  // on Darwin.
1668  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
1669                    options::OPT_fno_constant_cfstrings) ||
1670      !Args.hasFlag(options::OPT_mconstant_cfstrings,
1671                    options::OPT_mno_constant_cfstrings))
1672    CmdArgs.push_back("-fno-constant-cfstrings");
1673
1674  // -fshort-wchar default varies depending on platform; only
1675  // pass if specified.
1676  if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
1677    A->render(Args, CmdArgs);
1678
1679  // -fno-pascal-strings is default, only pass non-default. If the tool chain
1680  // happened to translate to -mpascal-strings, we want to back translate here.
1681  //
1682  // FIXME: This is gross; that translation should be pulled from the
1683  // tool chain.
1684  if (Args.hasFlag(options::OPT_fpascal_strings,
1685                   options::OPT_fno_pascal_strings,
1686                   false) ||
1687      Args.hasFlag(options::OPT_mpascal_strings,
1688                   options::OPT_mno_pascal_strings,
1689                   false))
1690    CmdArgs.push_back("-fpascal-strings");
1691
1692  if (Args.hasArg(options::OPT_mkernel) ||
1693      Args.hasArg(options::OPT_fapple_kext)) {
1694    if (!Args.hasArg(options::OPT_fcommon))
1695      CmdArgs.push_back("-fno-common");
1696  }
1697  // -fcommon is default, only pass non-default.
1698  else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
1699    CmdArgs.push_back("-fno-common");
1700
1701  // -fsigned-bitfields is default, and clang doesn't yet support
1702  // -funsigned-bitfields.
1703  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
1704                    options::OPT_funsigned_bitfields))
1705    D.Diag(clang::diag::warn_drv_clang_unsupported)
1706      << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
1707
1708  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
1709  if (!Args.hasFlag(options::OPT_ffor_scope,
1710                    options::OPT_fno_for_scope))
1711    D.Diag(clang::diag::err_drv_clang_unsupported)
1712      << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
1713
1714  // -fcaret-diagnostics is default.
1715  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
1716                    options::OPT_fno_caret_diagnostics, true))
1717    CmdArgs.push_back("-fno-caret-diagnostics");
1718
1719  // -fdiagnostics-fixit-info is default, only pass non-default.
1720  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
1721                    options::OPT_fno_diagnostics_fixit_info))
1722    CmdArgs.push_back("-fno-diagnostics-fixit-info");
1723
1724  // Enable -fdiagnostics-show-option by default.
1725  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
1726                   options::OPT_fno_diagnostics_show_option))
1727    CmdArgs.push_back("-fdiagnostics-show-option");
1728
1729  if (const Arg *A =
1730        Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
1731    CmdArgs.push_back("-fdiagnostics-show-category");
1732    CmdArgs.push_back(A->getValue(Args));
1733  }
1734
1735  // Color diagnostics are the default, unless the terminal doesn't support
1736  // them.
1737  if (Args.hasFlag(options::OPT_fcolor_diagnostics,
1738                   options::OPT_fno_color_diagnostics,
1739                   llvm::sys::Process::StandardErrHasColors()))
1740    CmdArgs.push_back("-fcolor-diagnostics");
1741
1742  if (!Args.hasFlag(options::OPT_fshow_source_location,
1743                    options::OPT_fno_show_source_location))
1744    CmdArgs.push_back("-fno-show-source-location");
1745
1746  if (!Args.hasFlag(options::OPT_fspell_checking,
1747                    options::OPT_fno_spell_checking))
1748    CmdArgs.push_back("-fno-spell-checking");
1749
1750
1751  // Silently ignore -fasm-blocks for now.
1752  (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
1753                      false);
1754
1755  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
1756    A->render(Args, CmdArgs);
1757
1758  // -fdollars-in-identifiers default varies depending on platform and
1759  // language; only pass if specified.
1760  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
1761                               options::OPT_fno_dollars_in_identifiers)) {
1762    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
1763      CmdArgs.push_back("-fdollars-in-identifiers");
1764    else
1765      CmdArgs.push_back("-fno-dollars-in-identifiers");
1766  }
1767
1768  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
1769  // practical purposes.
1770  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
1771                               options::OPT_fno_unit_at_a_time)) {
1772    if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
1773      D.Diag(clang::diag::warn_drv_clang_unsupported) << A->getAsString(Args);
1774  }
1775
1776  // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
1777  //
1778  // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
1779#if 0
1780  if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin &&
1781      (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
1782       getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
1783    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
1784      CmdArgs.push_back("-fno-builtin-strcat");
1785    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
1786      CmdArgs.push_back("-fno-builtin-strcpy");
1787  }
1788#endif
1789
1790  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
1791  if (Arg *A = Args.getLastArg(options::OPT_traditional,
1792                               options::OPT_traditional_cpp)) {
1793    if (isa<PreprocessJobAction>(JA))
1794      CmdArgs.push_back("-traditional-cpp");
1795    else
1796      D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
1797  }
1798
1799  Args.AddLastArg(CmdArgs, options::OPT_dM);
1800  Args.AddLastArg(CmdArgs, options::OPT_dD);
1801
1802  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
1803  // parser.
1804  Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
1805  for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
1806         ie = Args.filtered_end(); it != ie; ++it) {
1807    (*it)->claim();
1808
1809    // We translate this by hand to the -cc1 argument, since nightly test uses
1810    // it and developers have been trained to spell it with -mllvm.
1811    if (llvm::StringRef((*it)->getValue(Args, 0)) == "-disable-llvm-optzns")
1812      CmdArgs.push_back("-disable-llvm-optzns");
1813    else
1814      (*it)->render(Args, CmdArgs);
1815  }
1816
1817  if (Output.getType() == types::TY_Dependencies) {
1818    // Handled with other dependency code.
1819  } else if (Output.isFilename()) {
1820    CmdArgs.push_back("-o");
1821    CmdArgs.push_back(Output.getFilename());
1822  } else {
1823    assert(Output.isNothing() && "Invalid output.");
1824  }
1825
1826  for (InputInfoList::const_iterator
1827         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
1828    const InputInfo &II = *it;
1829    CmdArgs.push_back("-x");
1830    CmdArgs.push_back(types::getTypeName(II.getType()));
1831    if (II.isFilename())
1832      CmdArgs.push_back(II.getFilename());
1833    else
1834      II.getInputArg().renderAsInput(Args, CmdArgs);
1835  }
1836
1837  Args.AddAllArgs(CmdArgs, options::OPT_undef);
1838
1839  const char *Exec = getToolChain().getDriver().getClangProgramPath();
1840
1841  // Optionally embed the -cc1 level arguments into the debug info, for build
1842  // analysis.
1843  if (getToolChain().UseDwarfDebugFlags()) {
1844    ArgStringList OriginalArgs;
1845    for (ArgList::const_iterator it = Args.begin(),
1846           ie = Args.end(); it != ie; ++it)
1847      (*it)->render(Args, OriginalArgs);
1848
1849    llvm::SmallString<256> Flags;
1850    Flags += Exec;
1851    for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
1852      Flags += " ";
1853      Flags += OriginalArgs[i];
1854    }
1855    CmdArgs.push_back("-dwarf-debug-flags");
1856    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
1857  }
1858
1859  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
1860
1861  if (Arg *A = Args.getLastArg(options::OPT_pg))
1862    if (Args.hasArg(options::OPT_fomit_frame_pointer))
1863      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
1864        << "-fomit-frame-pointer" << A->getAsString(Args);
1865
1866  // Claim some arguments which clang supports automatically.
1867
1868  // -fpch-preprocess is used with gcc to add a special marker in the output to
1869  // include the PCH file. Clang's PTH solution is completely transparent, so we
1870  // do not need to deal with it at all.
1871  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
1872
1873  // Claim some arguments which clang doesn't support, but we don't
1874  // care to warn the user about.
1875  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
1876  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
1877
1878  // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
1879  Args.ClaimAllArgs(options::OPT_use_gold_plugin);
1880  Args.ClaimAllArgs(options::OPT_emit_llvm);
1881}
1882
1883void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
1884                           const InputInfo &Output,
1885                           const InputInfoList &Inputs,
1886                           const ArgList &Args,
1887                           const char *LinkingOutput) const {
1888  ArgStringList CmdArgs;
1889
1890  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
1891  const InputInfo &Input = Inputs[0];
1892
1893  // Don't warn about "clang -w -c foo.s"
1894  Args.ClaimAllArgs(options::OPT_w);
1895  // and "clang -emit-llvm -c foo.s"
1896  Args.ClaimAllArgs(options::OPT_emit_llvm);
1897  // and "clang -use-gold-plugin -c foo.s"
1898  Args.ClaimAllArgs(options::OPT_use_gold_plugin);
1899
1900  // Invoke ourselves in -cc1as mode.
1901  //
1902  // FIXME: Implement custom jobs for internal actions.
1903  CmdArgs.push_back("-cc1as");
1904
1905  // Add the "effective" target triple.
1906  CmdArgs.push_back("-triple");
1907  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1908  CmdArgs.push_back(Args.MakeArgString(TripleStr));
1909
1910  // Set the output mode, we currently only expect to be used as a real
1911  // assembler.
1912  CmdArgs.push_back("-filetype");
1913  CmdArgs.push_back("obj");
1914
1915  // At -O0, we use -mrelax-all by default.
1916  bool IsOpt = false;
1917  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1918    IsOpt = !A->getOption().matches(options::OPT_O0);
1919  if (Args.hasFlag(options::OPT_mrelax_all,
1920                    options::OPT_mno_relax_all,
1921                    !IsOpt))
1922    CmdArgs.push_back("-relax-all");
1923
1924  // Ignore explicit -force_cpusubtype_ALL option.
1925  (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
1926
1927  // FIXME: Add -g support, once we have it.
1928
1929  // FIXME: Add -static support, once we have it.
1930
1931  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
1932                       options::OPT_Xassembler);
1933
1934  assert(Output.isFilename() && "Unexpected lipo output.");
1935  CmdArgs.push_back("-o");
1936  CmdArgs.push_back(Output.getFilename());
1937
1938  assert(Input.isFilename() && "Invalid input.");
1939  CmdArgs.push_back(Input.getFilename());
1940
1941  const char *Exec = getToolChain().getDriver().getClangProgramPath();
1942  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
1943}
1944
1945void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
1946                               const InputInfo &Output,
1947                               const InputInfoList &Inputs,
1948                               const ArgList &Args,
1949                               const char *LinkingOutput) const {
1950  const Driver &D = getToolChain().getDriver();
1951  ArgStringList CmdArgs;
1952
1953  for (ArgList::const_iterator
1954         it = Args.begin(), ie = Args.end(); it != ie; ++it) {
1955    Arg *A = *it;
1956    if (A->getOption().hasForwardToGCC()) {
1957      // Don't forward any -g arguments to assembly steps.
1958      if (isa<AssembleJobAction>(JA) &&
1959          A->getOption().matches(options::OPT_g_Group))
1960        continue;
1961
1962      // It is unfortunate that we have to claim here, as this means
1963      // we will basically never report anything interesting for
1964      // platforms using a generic gcc, even if we are just using gcc
1965      // to get to the assembler.
1966      A->claim();
1967      A->render(Args, CmdArgs);
1968    }
1969  }
1970
1971  RenderExtraToolArgs(JA, CmdArgs);
1972
1973  // If using a driver driver, force the arch.
1974  const std::string &Arch = getToolChain().getArchName();
1975  if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin) {
1976    CmdArgs.push_back("-arch");
1977
1978    // FIXME: Remove these special cases.
1979    if (Arch == "powerpc")
1980      CmdArgs.push_back("ppc");
1981    else if (Arch == "powerpc64")
1982      CmdArgs.push_back("ppc64");
1983    else
1984      CmdArgs.push_back(Args.MakeArgString(Arch));
1985  }
1986
1987  // Try to force gcc to match the tool chain we want, if we recognize
1988  // the arch.
1989  //
1990  // FIXME: The triple class should directly provide the information we want
1991  // here.
1992  if (Arch == "i386" || Arch == "powerpc")
1993    CmdArgs.push_back("-m32");
1994  else if (Arch == "x86_64" || Arch == "powerpc64")
1995    CmdArgs.push_back("-m64");
1996
1997  if (Output.isFilename()) {
1998    CmdArgs.push_back("-o");
1999    CmdArgs.push_back(Output.getFilename());
2000  } else {
2001    assert(Output.isNothing() && "Unexpected output");
2002    CmdArgs.push_back("-fsyntax-only");
2003  }
2004
2005
2006  // Only pass -x if gcc will understand it; otherwise hope gcc
2007  // understands the suffix correctly. The main use case this would go
2008  // wrong in is for linker inputs if they happened to have an odd
2009  // suffix; really the only way to get this to happen is a command
2010  // like '-x foobar a.c' which will treat a.c like a linker input.
2011  //
2012  // FIXME: For the linker case specifically, can we safely convert
2013  // inputs into '-Wl,' options?
2014  for (InputInfoList::const_iterator
2015         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2016    const InputInfo &II = *it;
2017
2018    // Don't try to pass LLVM or AST inputs to a generic gcc.
2019    if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
2020        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
2021      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
2022        << getToolChain().getTripleString();
2023    else if (II.getType() == types::TY_AST)
2024      D.Diag(clang::diag::err_drv_no_ast_support)
2025        << getToolChain().getTripleString();
2026
2027    if (types::canTypeBeUserSpecified(II.getType())) {
2028      CmdArgs.push_back("-x");
2029      CmdArgs.push_back(types::getTypeName(II.getType()));
2030    }
2031
2032    if (II.isFilename())
2033      CmdArgs.push_back(II.getFilename());
2034    else {
2035      const Arg &A = II.getInputArg();
2036
2037      // Reverse translate some rewritten options.
2038      if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
2039        CmdArgs.push_back("-lstdc++");
2040        continue;
2041      }
2042
2043      // Don't render as input, we need gcc to do the translations.
2044      A.render(Args, CmdArgs);
2045    }
2046  }
2047
2048  const char *GCCName = getToolChain().getDriver().getCCCGenericGCCName().c_str();
2049  const char *Exec =
2050    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
2051  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2052}
2053
2054void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
2055                                          ArgStringList &CmdArgs) const {
2056  CmdArgs.push_back("-E");
2057}
2058
2059void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
2060                                          ArgStringList &CmdArgs) const {
2061  // The type is good enough.
2062}
2063
2064void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
2065                                       ArgStringList &CmdArgs) const {
2066  const Driver &D = getToolChain().getDriver();
2067
2068  // If -flto, etc. are present then make sure not to force assembly output.
2069  if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
2070      JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
2071    CmdArgs.push_back("-c");
2072  else {
2073    if (JA.getType() != types::TY_PP_Asm)
2074      D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
2075        << getTypeName(JA.getType());
2076
2077    CmdArgs.push_back("-S");
2078  }
2079}
2080
2081void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
2082                                        ArgStringList &CmdArgs) const {
2083  CmdArgs.push_back("-c");
2084}
2085
2086void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
2087                                    ArgStringList &CmdArgs) const {
2088  // The types are (hopefully) good enough.
2089}
2090
2091const char *darwin::CC1::getCC1Name(types::ID Type) const {
2092  switch (Type) {
2093  default:
2094    assert(0 && "Unexpected type for Darwin CC1 tool.");
2095  case types::TY_Asm:
2096  case types::TY_C: case types::TY_CHeader:
2097  case types::TY_PP_C: case types::TY_PP_CHeader:
2098    return "cc1";
2099  case types::TY_ObjC: case types::TY_ObjCHeader:
2100  case types::TY_PP_ObjC: case types::TY_PP_ObjCHeader:
2101    return "cc1obj";
2102  case types::TY_CXX: case types::TY_CXXHeader:
2103  case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
2104    return "cc1plus";
2105  case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
2106  case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXXHeader:
2107    return "cc1objplus";
2108  }
2109}
2110
2111const char *darwin::CC1::getBaseInputName(const ArgList &Args,
2112                                          const InputInfoList &Inputs) {
2113  return Args.MakeArgString(
2114    llvm::sys::path::filename(Inputs[0].getBaseInput()));
2115}
2116
2117const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
2118                                          const InputInfoList &Inputs) {
2119  const char *Str = getBaseInputName(Args, Inputs);
2120
2121  if (const char *End = strrchr(Str, '.'))
2122    return Args.MakeArgString(std::string(Str, End));
2123
2124  return Str;
2125}
2126
2127const char *
2128darwin::CC1::getDependencyFileName(const ArgList &Args,
2129                                   const InputInfoList &Inputs) {
2130  // FIXME: Think about this more.
2131  std::string Res;
2132
2133  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
2134    std::string Str(OutputOpt->getValue(Args));
2135
2136    Res = Str.substr(0, Str.rfind('.'));
2137  } else
2138    Res = darwin::CC1::getBaseInputStem(Args, Inputs);
2139
2140  return Args.MakeArgString(Res + ".d");
2141}
2142
2143void darwin::CC1::AddCC1Args(const ArgList &Args,
2144                             ArgStringList &CmdArgs) const {
2145  const Driver &D = getToolChain().getDriver();
2146
2147  CheckCodeGenerationOptions(D, Args);
2148
2149  // Derived from cc1 spec.
2150  if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) &&
2151      !Args.hasArg(options::OPT_mdynamic_no_pic))
2152    CmdArgs.push_back("-fPIC");
2153
2154  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2155      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
2156    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
2157      CmdArgs.push_back("-fno-builtin-strcat");
2158    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
2159      CmdArgs.push_back("-fno-builtin-strcpy");
2160  }
2161
2162  // gcc has some code here to deal with when no -mmacosx-version-min
2163  // and no -miphoneos-version-min is present, but this never happens
2164  // due to tool chain specific argument translation.
2165
2166  if (Args.hasArg(options::OPT_g_Flag) &&
2167      !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
2168    CmdArgs.push_back("-feliminate-unused-debug-symbols");
2169}
2170
2171void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
2172                                    const InputInfoList &Inputs,
2173                                    const ArgStringList &OutputArgs) const {
2174  const Driver &D = getToolChain().getDriver();
2175
2176  // Derived from cc1_options spec.
2177  if (Args.hasArg(options::OPT_fast) ||
2178      Args.hasArg(options::OPT_fastf) ||
2179      Args.hasArg(options::OPT_fastcp))
2180    CmdArgs.push_back("-O3");
2181
2182  if (Arg *A = Args.getLastArg(options::OPT_pg))
2183    if (Args.hasArg(options::OPT_fomit_frame_pointer))
2184      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
2185        << A->getAsString(Args) << "-fomit-frame-pointer";
2186
2187  AddCC1Args(Args, CmdArgs);
2188
2189  if (!Args.hasArg(options::OPT_Q))
2190    CmdArgs.push_back("-quiet");
2191
2192  CmdArgs.push_back("-dumpbase");
2193  CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
2194
2195  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
2196
2197  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
2198  Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
2199
2200  // FIXME: The goal is to use the user provided -o if that is our
2201  // final output, otherwise to drive from the original input
2202  // name. Find a clean way to go about this.
2203  if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
2204      Args.hasArg(options::OPT_o)) {
2205    Arg *OutputOpt = Args.getLastArg(options::OPT_o);
2206    CmdArgs.push_back("-auxbase-strip");
2207    CmdArgs.push_back(OutputOpt->getValue(Args));
2208  } else {
2209    CmdArgs.push_back("-auxbase");
2210    CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
2211  }
2212
2213  Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
2214
2215  Args.AddAllArgs(CmdArgs, options::OPT_O);
2216  // FIXME: -Wall is getting some special treatment. Investigate.
2217  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
2218  Args.AddLastArg(CmdArgs, options::OPT_w);
2219  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
2220                  options::OPT_trigraphs);
2221  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2222    // Honor -std-default.
2223    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2224                              "-std=", /*Joined=*/true);
2225  }
2226
2227  if (Args.hasArg(options::OPT_v))
2228    CmdArgs.push_back("-version");
2229  if (Args.hasArg(options::OPT_pg) &&
2230      getToolChain().SupportsProfiling())
2231    CmdArgs.push_back("-p");
2232  Args.AddLastArg(CmdArgs, options::OPT_p);
2233
2234  // The driver treats -fsyntax-only specially.
2235  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2236      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
2237    // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
2238    // used to inhibit the default -fno-builtin-str{cat,cpy}.
2239    //
2240    // FIXME: Should we grow a better way to deal with "removing" args?
2241    for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
2242                                               options::OPT_fsyntax_only),
2243           ie = Args.filtered_end(); it != ie; ++it) {
2244      if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) &&
2245          !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) {
2246        (*it)->claim();
2247        (*it)->render(Args, CmdArgs);
2248      }
2249    }
2250  } else
2251    Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
2252
2253  Args.AddAllArgs(CmdArgs, options::OPT_undef);
2254  if (Args.hasArg(options::OPT_Qn))
2255    CmdArgs.push_back("-fno-ident");
2256
2257  // FIXME: This isn't correct.
2258  //Args.AddLastArg(CmdArgs, options::OPT__help)
2259  //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
2260
2261  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2262
2263  // FIXME: Still don't get what is happening here. Investigate.
2264  Args.AddAllArgs(CmdArgs, options::OPT__param);
2265
2266  if (Args.hasArg(options::OPT_fmudflap) ||
2267      Args.hasArg(options::OPT_fmudflapth)) {
2268    CmdArgs.push_back("-fno-builtin");
2269    CmdArgs.push_back("-fno-merge-constants");
2270  }
2271
2272  if (Args.hasArg(options::OPT_coverage)) {
2273    CmdArgs.push_back("-fprofile-arcs");
2274    CmdArgs.push_back("-ftest-coverage");
2275  }
2276
2277  if (types::isCXX(Inputs[0].getType()))
2278    CmdArgs.push_back("-D__private_extern__=extern");
2279}
2280
2281void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
2282                                    const InputInfoList &Inputs,
2283                                    const ArgStringList &OutputArgs) const {
2284  // Derived from cpp_options
2285  AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
2286
2287  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2288
2289  AddCC1Args(Args, CmdArgs);
2290
2291  // NOTE: The code below has some commonality with cpp_options, but
2292  // in classic gcc style ends up sending things in different
2293  // orders. This may be a good merge candidate once we drop pedantic
2294  // compatibility.
2295
2296  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
2297  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
2298                  options::OPT_trigraphs);
2299  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2300    // Honor -std-default.
2301    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2302                              "-std=", /*Joined=*/true);
2303  }
2304  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
2305  Args.AddLastArg(CmdArgs, options::OPT_w);
2306
2307  // The driver treats -fsyntax-only specially.
2308  Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
2309
2310  if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
2311      !Args.hasArg(options::OPT_fno_working_directory))
2312    CmdArgs.push_back("-fworking-directory");
2313
2314  Args.AddAllArgs(CmdArgs, options::OPT_O);
2315  Args.AddAllArgs(CmdArgs, options::OPT_undef);
2316  if (Args.hasArg(options::OPT_save_temps))
2317    CmdArgs.push_back("-fpch-preprocess");
2318}
2319
2320void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
2321                                          ArgStringList &CmdArgs,
2322                                          const InputInfoList &Inputs) const {
2323  const Driver &D = getToolChain().getDriver();
2324
2325  CheckPreprocessingOptions(D, Args);
2326
2327  // Derived from cpp_unique_options.
2328  // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
2329  Args.AddLastArg(CmdArgs, options::OPT_C);
2330  Args.AddLastArg(CmdArgs, options::OPT_CC);
2331  if (!Args.hasArg(options::OPT_Q))
2332    CmdArgs.push_back("-quiet");
2333  Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
2334  Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
2335  Args.AddLastArg(CmdArgs, options::OPT_v);
2336  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
2337  Args.AddLastArg(CmdArgs, options::OPT_P);
2338
2339  // FIXME: Handle %I properly.
2340  if (getToolChain().getArchName() == "x86_64") {
2341    CmdArgs.push_back("-imultilib");
2342    CmdArgs.push_back("x86_64");
2343  }
2344
2345  if (Args.hasArg(options::OPT_MD)) {
2346    CmdArgs.push_back("-MD");
2347    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
2348  }
2349
2350  if (Args.hasArg(options::OPT_MMD)) {
2351    CmdArgs.push_back("-MMD");
2352    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
2353  }
2354
2355  Args.AddLastArg(CmdArgs, options::OPT_M);
2356  Args.AddLastArg(CmdArgs, options::OPT_MM);
2357  Args.AddAllArgs(CmdArgs, options::OPT_MF);
2358  Args.AddLastArg(CmdArgs, options::OPT_MG);
2359  Args.AddLastArg(CmdArgs, options::OPT_MP);
2360  Args.AddAllArgs(CmdArgs, options::OPT_MQ);
2361  Args.AddAllArgs(CmdArgs, options::OPT_MT);
2362  if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
2363      (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
2364    if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
2365      CmdArgs.push_back("-MQ");
2366      CmdArgs.push_back(OutputOpt->getValue(Args));
2367    }
2368  }
2369
2370  Args.AddLastArg(CmdArgs, options::OPT_remap);
2371  if (Args.hasArg(options::OPT_g3))
2372    CmdArgs.push_back("-dD");
2373  Args.AddLastArg(CmdArgs, options::OPT_H);
2374
2375  AddCPPArgs(Args, CmdArgs);
2376
2377  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
2378  Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
2379
2380  for (InputInfoList::const_iterator
2381         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2382    const InputInfo &II = *it;
2383
2384    CmdArgs.push_back(II.getFilename());
2385  }
2386
2387  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
2388                       options::OPT_Xpreprocessor);
2389
2390  if (Args.hasArg(options::OPT_fmudflap)) {
2391    CmdArgs.push_back("-D_MUDFLAP");
2392    CmdArgs.push_back("-include");
2393    CmdArgs.push_back("mf-runtime.h");
2394  }
2395
2396  if (Args.hasArg(options::OPT_fmudflapth)) {
2397    CmdArgs.push_back("-D_MUDFLAP");
2398    CmdArgs.push_back("-D_MUDFLAPTH");
2399    CmdArgs.push_back("-include");
2400    CmdArgs.push_back("mf-runtime.h");
2401  }
2402}
2403
2404void darwin::CC1::AddCPPArgs(const ArgList &Args,
2405                             ArgStringList &CmdArgs) const {
2406  // Derived from cpp spec.
2407
2408  if (Args.hasArg(options::OPT_static)) {
2409    // The gcc spec is broken here, it refers to dynamic but
2410    // that has been translated. Start by being bug compatible.
2411
2412    // if (!Args.hasArg(arglist.parser.dynamicOption))
2413    CmdArgs.push_back("-D__STATIC__");
2414  } else
2415    CmdArgs.push_back("-D__DYNAMIC__");
2416
2417  if (Args.hasArg(options::OPT_pthread))
2418    CmdArgs.push_back("-D_REENTRANT");
2419}
2420
2421void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
2422                                      const InputInfo &Output,
2423                                      const InputInfoList &Inputs,
2424                                      const ArgList &Args,
2425                                      const char *LinkingOutput) const {
2426  ArgStringList CmdArgs;
2427
2428  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
2429
2430  CmdArgs.push_back("-E");
2431
2432  if (Args.hasArg(options::OPT_traditional) ||
2433      Args.hasArg(options::OPT_traditional_cpp))
2434    CmdArgs.push_back("-traditional-cpp");
2435
2436  ArgStringList OutputArgs;
2437  assert(Output.isFilename() && "Unexpected CC1 output.");
2438  OutputArgs.push_back("-o");
2439  OutputArgs.push_back(Output.getFilename());
2440
2441  if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) {
2442    AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2443  } else {
2444    AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2445    CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2446  }
2447
2448  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
2449
2450  const char *CC1Name = getCC1Name(Inputs[0].getType());
2451  const char *Exec =
2452    Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
2453  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2454}
2455
2456void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
2457                                   const InputInfo &Output,
2458                                   const InputInfoList &Inputs,
2459                                   const ArgList &Args,
2460                                   const char *LinkingOutput) const {
2461  const Driver &D = getToolChain().getDriver();
2462  ArgStringList CmdArgs;
2463
2464  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
2465
2466  types::ID InputType = Inputs[0].getType();
2467  const Arg *A;
2468  if ((A = Args.getLastArg(options::OPT_traditional)))
2469    D.Diag(clang::diag::err_drv_argument_only_allowed_with)
2470      << A->getAsString(Args) << "-E";
2471
2472  if (JA.getType() == types::TY_LLVM_IR ||
2473      JA.getType() == types::TY_LTO_IR)
2474    CmdArgs.push_back("-emit-llvm");
2475  else if (JA.getType() == types::TY_LLVM_BC ||
2476           JA.getType() == types::TY_LTO_BC)
2477    CmdArgs.push_back("-emit-llvm-bc");
2478  else if (Output.getType() == types::TY_AST)
2479    D.Diag(clang::diag::err_drv_no_ast_support)
2480      << getToolChain().getTripleString();
2481  else if (JA.getType() != types::TY_PP_Asm &&
2482           JA.getType() != types::TY_PCH)
2483    D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
2484      << getTypeName(JA.getType());
2485
2486  ArgStringList OutputArgs;
2487  if (Output.getType() != types::TY_PCH) {
2488    OutputArgs.push_back("-o");
2489    if (Output.isNothing())
2490      OutputArgs.push_back("/dev/null");
2491    else
2492      OutputArgs.push_back(Output.getFilename());
2493  }
2494
2495  // There is no need for this level of compatibility, but it makes
2496  // diffing easier.
2497  bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
2498                          Args.hasArg(options::OPT_S));
2499
2500  if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
2501    AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
2502    if (OutputArgsEarly) {
2503      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2504    } else {
2505      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2506      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2507    }
2508  } else {
2509    CmdArgs.push_back("-fpreprocessed");
2510
2511    for (InputInfoList::const_iterator
2512           it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2513      const InputInfo &II = *it;
2514
2515      // Reject AST inputs.
2516      if (II.getType() == types::TY_AST) {
2517        D.Diag(clang::diag::err_drv_no_ast_support)
2518          << getToolChain().getTripleString();
2519        return;
2520      }
2521
2522      CmdArgs.push_back(II.getFilename());
2523    }
2524
2525    if (OutputArgsEarly) {
2526      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2527    } else {
2528      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2529      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2530    }
2531  }
2532
2533  if (Output.getType() == types::TY_PCH) {
2534    assert(Output.isFilename() && "Invalid PCH output.");
2535
2536    CmdArgs.push_back("-o");
2537    // NOTE: gcc uses a temp .s file for this, but there doesn't seem
2538    // to be a good reason.
2539    CmdArgs.push_back("/dev/null");
2540
2541    CmdArgs.push_back("--output-pch=");
2542    CmdArgs.push_back(Output.getFilename());
2543  }
2544
2545  const char *CC1Name = getCC1Name(Inputs[0].getType());
2546  const char *Exec =
2547    Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
2548  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2549}
2550
2551void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2552                                    const InputInfo &Output,
2553                                    const InputInfoList &Inputs,
2554                                    const ArgList &Args,
2555                                    const char *LinkingOutput) const {
2556  ArgStringList CmdArgs;
2557
2558  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
2559  const InputInfo &Input = Inputs[0];
2560
2561  // Bit of a hack, this is only used for original inputs.
2562  //
2563  // FIXME: This is broken for preprocessed .s inputs.
2564  if (Input.isFilename() &&
2565      strcmp(Input.getFilename(), Input.getBaseInput()) == 0) {
2566    if (Args.hasArg(options::OPT_gstabs))
2567      CmdArgs.push_back("--gstabs");
2568    else if (Args.hasArg(options::OPT_g_Group))
2569      CmdArgs.push_back("--gdwarf2");
2570  }
2571
2572  // Derived from asm spec.
2573  AddDarwinArch(Args, CmdArgs);
2574
2575  // Use -force_cpusubtype_ALL on x86 by default.
2576  if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
2577      getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
2578      Args.hasArg(options::OPT_force__cpusubtype__ALL))
2579    CmdArgs.push_back("-force_cpusubtype_ALL");
2580
2581  if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
2582      (Args.hasArg(options::OPT_mkernel) ||
2583       Args.hasArg(options::OPT_static) ||
2584       Args.hasArg(options::OPT_fapple_kext)))
2585    CmdArgs.push_back("-static");
2586
2587  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2588                       options::OPT_Xassembler);
2589
2590  assert(Output.isFilename() && "Unexpected lipo output.");
2591  CmdArgs.push_back("-o");
2592  CmdArgs.push_back(Output.getFilename());
2593
2594  assert(Input.isFilename() && "Invalid input.");
2595  CmdArgs.push_back(Input.getFilename());
2596
2597  // asm_final spec is empty.
2598
2599  const char *Exec =
2600    Args.MakeArgString(getToolChain().GetProgramPath("as"));
2601  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2602}
2603
2604void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
2605                                       ArgStringList &CmdArgs) const {
2606  llvm::StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
2607
2608  // Derived from darwin_arch spec.
2609  CmdArgs.push_back("-arch");
2610  CmdArgs.push_back(Args.MakeArgString(ArchName));
2611
2612  // FIXME: Is this needed anymore?
2613  if (ArchName == "arm")
2614    CmdArgs.push_back("-force_cpusubtype_ALL");
2615}
2616
2617void darwin::Link::AddLinkArgs(Compilation &C,
2618                               const ArgList &Args,
2619                               ArgStringList &CmdArgs) const {
2620  const Driver &D = getToolChain().getDriver();
2621
2622  unsigned Version[3] = { 0, 0, 0 };
2623  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2624    bool HadExtra;
2625    if (!Driver::GetReleaseVersion(A->getValue(Args), Version[0],
2626                                   Version[1], Version[2], HadExtra) ||
2627        HadExtra)
2628      D.Diag(clang::diag::err_drv_invalid_version_number)
2629        << A->getAsString(Args);
2630  }
2631
2632  // Newer linkers support -demangle, pass it if supported and not disabled by
2633  // the user.
2634  //
2635  // FIXME: We temporarily avoid passing -demangle to any iOS linker, because
2636  // unfortunately we can't be guaranteed that the linker version used there
2637  // will match the linker version detected at configure time. We need the
2638  // universal driver.
2639  if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle) &&
2640      !getDarwinToolChain().isTargetIPhoneOS()) {
2641    // Don't pass -demangle to ld_classic.
2642    //
2643    // FIXME: This is a temporary workaround, ld should be handling this.
2644    bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
2645                          Args.hasArg(options::OPT_static));
2646    if (getToolChain().getArch() == llvm::Triple::x86) {
2647      for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
2648                                                 options::OPT_Wl_COMMA),
2649             ie = Args.filtered_end(); it != ie; ++it) {
2650        const Arg *A = *it;
2651        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
2652          if (llvm::StringRef(A->getValue(Args, i)) == "-kext")
2653            UsesLdClassic = true;
2654      }
2655    }
2656    if (!UsesLdClassic)
2657      CmdArgs.push_back("-demangle");
2658  }
2659
2660  // Derived from the "link" spec.
2661  Args.AddAllArgs(CmdArgs, options::OPT_static);
2662  if (!Args.hasArg(options::OPT_static))
2663    CmdArgs.push_back("-dynamic");
2664  if (Args.hasArg(options::OPT_fgnu_runtime)) {
2665    // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
2666    // here. How do we wish to handle such things?
2667  }
2668
2669  if (!Args.hasArg(options::OPT_dynamiclib)) {
2670    AddDarwinArch(Args, CmdArgs);
2671    // FIXME: Why do this only on this path?
2672    Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
2673
2674    Args.AddLastArg(CmdArgs, options::OPT_bundle);
2675    Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
2676    Args.AddAllArgs(CmdArgs, options::OPT_client__name);
2677
2678    Arg *A;
2679    if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
2680        (A = Args.getLastArg(options::OPT_current__version)) ||
2681        (A = Args.getLastArg(options::OPT_install__name)))
2682      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
2683        << A->getAsString(Args) << "-dynamiclib";
2684
2685    Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
2686    Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
2687    Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
2688  } else {
2689    CmdArgs.push_back("-dylib");
2690
2691    Arg *A;
2692    if ((A = Args.getLastArg(options::OPT_bundle)) ||
2693        (A = Args.getLastArg(options::OPT_bundle__loader)) ||
2694        (A = Args.getLastArg(options::OPT_client__name)) ||
2695        (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
2696        (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
2697        (A = Args.getLastArg(options::OPT_private__bundle)))
2698      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
2699        << A->getAsString(Args) << "-dynamiclib";
2700
2701    Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
2702                              "-dylib_compatibility_version");
2703    Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
2704                              "-dylib_current_version");
2705
2706    AddDarwinArch(Args, CmdArgs);
2707
2708    Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
2709                              "-dylib_install_name");
2710  }
2711
2712  Args.AddLastArg(CmdArgs, options::OPT_all__load);
2713  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
2714  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
2715  if (getDarwinToolChain().isTargetIPhoneOS())
2716    Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
2717  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
2718  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
2719  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
2720  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
2721  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
2722  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
2723  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
2724  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
2725  Args.AddAllArgs(CmdArgs, options::OPT_init);
2726
2727  // Adding all arguments doesn't make sense here but this is what gcc does. One
2728  // of this should always be present thanks to argument translation.
2729  assert((Args.hasArg(options::OPT_mmacosx_version_min_EQ) ||
2730          Args.hasArg(options::OPT_miphoneos_version_min_EQ)) &&
2731         "Missing version argument (lost in translation)?");
2732  Args.AddAllArgsTranslated(CmdArgs, options::OPT_mmacosx_version_min_EQ,
2733                            "-macosx_version_min");
2734  Args.AddAllArgsTranslated(CmdArgs, options::OPT_miphoneos_version_min_EQ,
2735                            "-iphoneos_version_min");
2736  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
2737  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
2738  Args.AddLastArg(CmdArgs, options::OPT_single__module);
2739  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
2740  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
2741
2742  if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
2743                                     options::OPT_fno_pie,
2744                                     options::OPT_fno_PIE)) {
2745    if (A->getOption().matches(options::OPT_fpie) ||
2746        A->getOption().matches(options::OPT_fPIE))
2747      CmdArgs.push_back("-pie");
2748    else
2749      CmdArgs.push_back("-no_pie");
2750  }
2751
2752  Args.AddLastArg(CmdArgs, options::OPT_prebind);
2753  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
2754  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
2755  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
2756  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
2757  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
2758  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
2759  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
2760  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
2761  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
2762  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
2763  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
2764  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
2765  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
2766  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
2767  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
2768
2769  Args.AddAllArgsTranslated(CmdArgs, options::OPT_isysroot, "-syslibroot");
2770  if (getDarwinToolChain().isTargetIPhoneOS()) {
2771    if (!Args.hasArg(options::OPT_isysroot)) {
2772      CmdArgs.push_back("-syslibroot");
2773      CmdArgs.push_back("/Developer/SDKs/Extra");
2774    }
2775  }
2776
2777  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
2778  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
2779  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
2780  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
2781  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
2782  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
2783  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
2784  Args.AddAllArgs(CmdArgs, options::OPT_y);
2785  Args.AddLastArg(CmdArgs, options::OPT_w);
2786  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
2787  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
2788  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
2789  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
2790  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
2791  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
2792  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
2793  Args.AddLastArg(CmdArgs, options::OPT_whyload);
2794  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
2795  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
2796  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
2797  Args.AddLastArg(CmdArgs, options::OPT_Mach);
2798}
2799
2800void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
2801                                const InputInfo &Output,
2802                                const InputInfoList &Inputs,
2803                                const ArgList &Args,
2804                                const char *LinkingOutput) const {
2805  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
2806
2807  // The logic here is derived from gcc's behavior; most of which
2808  // comes from specs (starting with link_command). Consult gcc for
2809  // more information.
2810  ArgStringList CmdArgs;
2811
2812  // I'm not sure why this particular decomposition exists in gcc, but
2813  // we follow suite for ease of comparison.
2814  AddLinkArgs(C, Args, CmdArgs);
2815
2816  Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
2817  Args.AddAllArgs(CmdArgs, options::OPT_s);
2818  Args.AddAllArgs(CmdArgs, options::OPT_t);
2819  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
2820  Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
2821  Args.AddAllArgs(CmdArgs, options::OPT_A);
2822  Args.AddLastArg(CmdArgs, options::OPT_e);
2823  Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
2824  Args.AddAllArgs(CmdArgs, options::OPT_r);
2825
2826  // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
2827  // members of static archive libraries which implement Objective-C classes or
2828  // categories.
2829  if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
2830    CmdArgs.push_back("-ObjC");
2831
2832  CmdArgs.push_back("-o");
2833  CmdArgs.push_back(Output.getFilename());
2834
2835  if (!Args.hasArg(options::OPT_A) &&
2836      !Args.hasArg(options::OPT_nostdlib) &&
2837      !Args.hasArg(options::OPT_nostartfiles)) {
2838    // Derived from startfile spec.
2839    if (Args.hasArg(options::OPT_dynamiclib)) {
2840      // Derived from darwin_dylib1 spec.
2841      if (getDarwinToolChain().isTargetIPhoneOS()) {
2842        if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2843          CmdArgs.push_back("-ldylib1.o");
2844      } else {
2845        if (getDarwinToolChain().isMacosxVersionLT(10, 5))
2846          CmdArgs.push_back("-ldylib1.o");
2847        else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2848          CmdArgs.push_back("-ldylib1.10.5.o");
2849      }
2850    } else {
2851      if (Args.hasArg(options::OPT_bundle)) {
2852        if (!Args.hasArg(options::OPT_static)) {
2853          // Derived from darwin_bundle1 spec.
2854          if (getDarwinToolChain().isTargetIPhoneOS()) {
2855            if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2856              CmdArgs.push_back("-lbundle1.o");
2857          } else {
2858            if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2859              CmdArgs.push_back("-lbundle1.o");
2860          }
2861        }
2862      } else {
2863        if (Args.hasArg(options::OPT_pg) &&
2864            getToolChain().SupportsProfiling()) {
2865          if (Args.hasArg(options::OPT_static) ||
2866              Args.hasArg(options::OPT_object) ||
2867              Args.hasArg(options::OPT_preload)) {
2868            CmdArgs.push_back("-lgcrt0.o");
2869          } else {
2870            CmdArgs.push_back("-lgcrt1.o");
2871
2872            // darwin_crt2 spec is empty.
2873          }
2874        } else {
2875          if (Args.hasArg(options::OPT_static) ||
2876              Args.hasArg(options::OPT_object) ||
2877              Args.hasArg(options::OPT_preload)) {
2878            CmdArgs.push_back("-lcrt0.o");
2879          } else {
2880            // Derived from darwin_crt1 spec.
2881            if (getDarwinToolChain().isTargetIPhoneOS()) {
2882              if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2883                CmdArgs.push_back("-lcrt1.o");
2884              else
2885                CmdArgs.push_back("-lcrt1.3.1.o");
2886            } else {
2887              if (getDarwinToolChain().isMacosxVersionLT(10, 5))
2888                CmdArgs.push_back("-lcrt1.o");
2889              else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2890                CmdArgs.push_back("-lcrt1.10.5.o");
2891              else
2892                CmdArgs.push_back("-lcrt1.10.6.o");
2893
2894              // darwin_crt2 spec is empty.
2895            }
2896          }
2897        }
2898      }
2899    }
2900
2901    if (!getDarwinToolChain().isTargetIPhoneOS() &&
2902        Args.hasArg(options::OPT_shared_libgcc) &&
2903        getDarwinToolChain().isMacosxVersionLT(10, 5)) {
2904      const char *Str =
2905        Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
2906      CmdArgs.push_back(Str);
2907    }
2908  }
2909
2910  Args.AddAllArgs(CmdArgs, options::OPT_L);
2911
2912  if (Args.hasArg(options::OPT_fopenmp))
2913    // This is more complicated in gcc...
2914    CmdArgs.push_back("-lgomp");
2915
2916  getDarwinToolChain().AddLinkSearchPathArgs(Args, CmdArgs);
2917
2918  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
2919
2920  if (LinkingOutput) {
2921    CmdArgs.push_back("-arch_multiple");
2922    CmdArgs.push_back("-final_output");
2923    CmdArgs.push_back(LinkingOutput);
2924  }
2925
2926  if (Args.hasArg(options::OPT_fprofile_arcs) ||
2927      Args.hasArg(options::OPT_fprofile_generate) ||
2928      Args.hasArg(options::OPT_fcreate_profile) ||
2929      Args.hasArg(options::OPT_coverage))
2930    CmdArgs.push_back("-lgcov");
2931
2932  if (Args.hasArg(options::OPT_fnested_functions))
2933    CmdArgs.push_back("-allow_stack_execute");
2934
2935  if (!Args.hasArg(options::OPT_nostdlib) &&
2936      !Args.hasArg(options::OPT_nodefaultlibs)) {
2937    if (getToolChain().getDriver().CCCIsCXX)
2938      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
2939
2940    // link_ssp spec is empty.
2941
2942    // Let the tool chain choose which runtime library to link.
2943    getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
2944  }
2945
2946  if (!Args.hasArg(options::OPT_A) &&
2947      !Args.hasArg(options::OPT_nostdlib) &&
2948      !Args.hasArg(options::OPT_nostartfiles)) {
2949    // endfile_spec is empty.
2950  }
2951
2952  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
2953  Args.AddAllArgs(CmdArgs, options::OPT_F);
2954
2955  const char *Exec =
2956    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
2957  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2958}
2959
2960void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
2961                                const InputInfo &Output,
2962                                const InputInfoList &Inputs,
2963                                const ArgList &Args,
2964                                const char *LinkingOutput) const {
2965  ArgStringList CmdArgs;
2966
2967  CmdArgs.push_back("-create");
2968  assert(Output.isFilename() && "Unexpected lipo output.");
2969
2970  CmdArgs.push_back("-output");
2971  CmdArgs.push_back(Output.getFilename());
2972
2973  for (InputInfoList::const_iterator
2974         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2975    const InputInfo &II = *it;
2976    assert(II.isFilename() && "Unexpected lipo input.");
2977    CmdArgs.push_back(II.getFilename());
2978  }
2979  const char *Exec =
2980    Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
2981  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
2982}
2983
2984void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
2985                                    const InputInfo &Output,
2986                                    const InputInfoList &Inputs,
2987                                    const ArgList &Args,
2988                                    const char *LinkingOutput) const {
2989  ArgStringList CmdArgs;
2990
2991  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2992  const InputInfo &Input = Inputs[0];
2993  assert(Input.isFilename() && "Unexpected dsymutil input.");
2994  CmdArgs.push_back(Input.getFilename());
2995
2996  CmdArgs.push_back("-o");
2997  CmdArgs.push_back(Output.getFilename());
2998
2999  const char *Exec =
3000    Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
3001  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3002}
3003
3004void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3005                                      const InputInfo &Output,
3006                                      const InputInfoList &Inputs,
3007                                      const ArgList &Args,
3008                                      const char *LinkingOutput) const {
3009  ArgStringList CmdArgs;
3010
3011  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3012                       options::OPT_Xassembler);
3013
3014  CmdArgs.push_back("-o");
3015  CmdArgs.push_back(Output.getFilename());
3016
3017  for (InputInfoList::const_iterator
3018         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3019    const InputInfo &II = *it;
3020    CmdArgs.push_back(II.getFilename());
3021  }
3022
3023  const char *Exec =
3024    Args.MakeArgString(getToolChain().GetProgramPath("gas"));
3025  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3026}
3027
3028void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
3029                                  const InputInfo &Output,
3030                                  const InputInfoList &Inputs,
3031                                  const ArgList &Args,
3032                                  const char *LinkingOutput) const {
3033  ArgStringList CmdArgs;
3034
3035  if ((!Args.hasArg(options::OPT_nostdlib)) &&
3036      (!Args.hasArg(options::OPT_shared))) {
3037    CmdArgs.push_back("-e");
3038    CmdArgs.push_back("_start");
3039  }
3040
3041  if (Args.hasArg(options::OPT_static)) {
3042    CmdArgs.push_back("-Bstatic");
3043    CmdArgs.push_back("-dn");
3044  } else {
3045//    CmdArgs.push_back("--eh-frame-hdr");
3046    CmdArgs.push_back("-Bdynamic");
3047    if (Args.hasArg(options::OPT_shared)) {
3048      CmdArgs.push_back("-shared");
3049    } else {
3050      CmdArgs.push_back("--dynamic-linker");
3051      CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
3052    }
3053  }
3054
3055  if (Output.isFilename()) {
3056    CmdArgs.push_back("-o");
3057    CmdArgs.push_back(Output.getFilename());
3058  } else {
3059    assert(Output.isNothing() && "Invalid output.");
3060  }
3061
3062  if (!Args.hasArg(options::OPT_nostdlib) &&
3063      !Args.hasArg(options::OPT_nostartfiles)) {
3064    if (!Args.hasArg(options::OPT_shared)) {
3065      CmdArgs.push_back(Args.MakeArgString(
3066                                getToolChain().GetFilePath("crt1.o")));
3067      CmdArgs.push_back(Args.MakeArgString(
3068                                getToolChain().GetFilePath("crti.o")));
3069      CmdArgs.push_back(Args.MakeArgString(
3070                                getToolChain().GetFilePath("crtbegin.o")));
3071    } else {
3072      CmdArgs.push_back(Args.MakeArgString(
3073                                getToolChain().GetFilePath("crti.o")));
3074    }
3075    CmdArgs.push_back(Args.MakeArgString(
3076                                getToolChain().GetFilePath("crtn.o")));
3077  }
3078
3079  CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
3080                                       + getToolChain().getTripleString()
3081                                       + "/4.2.4"));
3082
3083  Args.AddAllArgs(CmdArgs, options::OPT_L);
3084  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3085  Args.AddAllArgs(CmdArgs, options::OPT_e);
3086
3087  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3088
3089  if (!Args.hasArg(options::OPT_nostdlib) &&
3090      !Args.hasArg(options::OPT_nodefaultlibs)) {
3091    // FIXME: For some reason GCC passes -lgcc before adding
3092    // the default system libraries. Just mimic this for now.
3093    CmdArgs.push_back("-lgcc");
3094
3095    if (Args.hasArg(options::OPT_pthread))
3096      CmdArgs.push_back("-pthread");
3097    if (!Args.hasArg(options::OPT_shared))
3098      CmdArgs.push_back("-lc");
3099    CmdArgs.push_back("-lgcc");
3100  }
3101
3102  if (!Args.hasArg(options::OPT_nostdlib) &&
3103      !Args.hasArg(options::OPT_nostartfiles)) {
3104    if (!Args.hasArg(options::OPT_shared))
3105      CmdArgs.push_back(Args.MakeArgString(
3106                                getToolChain().GetFilePath("crtend.o")));
3107  }
3108
3109  const char *Exec =
3110    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3111  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3112}
3113
3114void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3115                                     const InputInfo &Output,
3116                                     const InputInfoList &Inputs,
3117                                     const ArgList &Args,
3118                                     const char *LinkingOutput) const {
3119  ArgStringList CmdArgs;
3120
3121  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3122                       options::OPT_Xassembler);
3123
3124  CmdArgs.push_back("-o");
3125  CmdArgs.push_back(Output.getFilename());
3126
3127  for (InputInfoList::const_iterator
3128         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3129    const InputInfo &II = *it;
3130    CmdArgs.push_back(II.getFilename());
3131  }
3132
3133  const char *Exec =
3134    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3135  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3136}
3137
3138void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3139                                 const InputInfo &Output,
3140                                 const InputInfoList &Inputs,
3141                                 const ArgList &Args,
3142                                 const char *LinkingOutput) const {
3143  const Driver &D = getToolChain().getDriver();
3144  ArgStringList CmdArgs;
3145
3146  if ((!Args.hasArg(options::OPT_nostdlib)) &&
3147      (!Args.hasArg(options::OPT_shared))) {
3148    CmdArgs.push_back("-e");
3149    CmdArgs.push_back("__start");
3150  }
3151
3152  if (Args.hasArg(options::OPT_static)) {
3153    CmdArgs.push_back("-Bstatic");
3154  } else {
3155    if (Args.hasArg(options::OPT_rdynamic))
3156      CmdArgs.push_back("-export-dynamic");
3157    CmdArgs.push_back("--eh-frame-hdr");
3158    CmdArgs.push_back("-Bdynamic");
3159    if (Args.hasArg(options::OPT_shared)) {
3160      CmdArgs.push_back("-shared");
3161    } else {
3162      CmdArgs.push_back("-dynamic-linker");
3163      CmdArgs.push_back("/usr/libexec/ld.so");
3164    }
3165  }
3166
3167  if (Output.isFilename()) {
3168    CmdArgs.push_back("-o");
3169    CmdArgs.push_back(Output.getFilename());
3170  } else {
3171    assert(Output.isNothing() && "Invalid output.");
3172  }
3173
3174  if (!Args.hasArg(options::OPT_nostdlib) &&
3175      !Args.hasArg(options::OPT_nostartfiles)) {
3176    if (!Args.hasArg(options::OPT_shared)) {
3177      CmdArgs.push_back(Args.MakeArgString(
3178                              getToolChain().GetFilePath("crt0.o")));
3179      CmdArgs.push_back(Args.MakeArgString(
3180                              getToolChain().GetFilePath("crtbegin.o")));
3181    } else {
3182      CmdArgs.push_back(Args.MakeArgString(
3183                              getToolChain().GetFilePath("crtbeginS.o")));
3184    }
3185  }
3186
3187  std::string Triple = getToolChain().getTripleString();
3188  if (Triple.substr(0, 6) == "x86_64")
3189    Triple.replace(0, 6, "amd64");
3190  CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
3191                                       "/4.2.1"));
3192
3193  Args.AddAllArgs(CmdArgs, options::OPT_L);
3194  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3195  Args.AddAllArgs(CmdArgs, options::OPT_e);
3196
3197  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3198
3199  if (!Args.hasArg(options::OPT_nostdlib) &&
3200      !Args.hasArg(options::OPT_nodefaultlibs)) {
3201    if (D.CCCIsCXX) {
3202      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3203      CmdArgs.push_back("-lm");
3204    }
3205
3206    // FIXME: For some reason GCC passes -lgcc before adding
3207    // the default system libraries. Just mimic this for now.
3208    CmdArgs.push_back("-lgcc");
3209
3210    if (Args.hasArg(options::OPT_pthread))
3211      CmdArgs.push_back("-lpthread");
3212    if (!Args.hasArg(options::OPT_shared))
3213      CmdArgs.push_back("-lc");
3214    CmdArgs.push_back("-lgcc");
3215  }
3216
3217  if (!Args.hasArg(options::OPT_nostdlib) &&
3218      !Args.hasArg(options::OPT_nostartfiles)) {
3219    if (!Args.hasArg(options::OPT_shared))
3220      CmdArgs.push_back(Args.MakeArgString(
3221                              getToolChain().GetFilePath("crtend.o")));
3222    else
3223      CmdArgs.push_back(Args.MakeArgString(
3224                              getToolChain().GetFilePath("crtendS.o")));
3225  }
3226
3227  const char *Exec =
3228    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3229  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3230}
3231
3232void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3233                                     const InputInfo &Output,
3234                                     const InputInfoList &Inputs,
3235                                     const ArgList &Args,
3236                                     const char *LinkingOutput) const {
3237  ArgStringList CmdArgs;
3238
3239  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
3240  // instruct as in the base system to assemble 32-bit code.
3241  if (getToolChain().getArchName() == "i386")
3242    CmdArgs.push_back("--32");
3243
3244
3245  // Set byte order explicitly
3246  if (getToolChain().getArchName() == "mips")
3247    CmdArgs.push_back("-EB");
3248  else if (getToolChain().getArchName() == "mipsel")
3249    CmdArgs.push_back("-EL");
3250
3251  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3252                       options::OPT_Xassembler);
3253
3254  CmdArgs.push_back("-o");
3255  CmdArgs.push_back(Output.getFilename());
3256
3257  for (InputInfoList::const_iterator
3258         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3259    const InputInfo &II = *it;
3260    CmdArgs.push_back(II.getFilename());
3261  }
3262
3263  const char *Exec =
3264    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3265  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3266}
3267
3268void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3269                                 const InputInfo &Output,
3270                                 const InputInfoList &Inputs,
3271                                 const ArgList &Args,
3272                                 const char *LinkingOutput) const {
3273  const Driver &D = getToolChain().getDriver();
3274  ArgStringList CmdArgs;
3275
3276  if (!D.SysRoot.empty())
3277    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3278
3279  if (Args.hasArg(options::OPT_static)) {
3280    CmdArgs.push_back("-Bstatic");
3281  } else {
3282    if (Args.hasArg(options::OPT_rdynamic))
3283      CmdArgs.push_back("-export-dynamic");
3284    CmdArgs.push_back("--eh-frame-hdr");
3285    if (Args.hasArg(options::OPT_shared)) {
3286      CmdArgs.push_back("-Bshareable");
3287    } else {
3288      CmdArgs.push_back("-dynamic-linker");
3289      CmdArgs.push_back("/libexec/ld-elf.so.1");
3290    }
3291  }
3292
3293  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
3294  // instruct ld in the base system to link 32-bit code.
3295  if (getToolChain().getArchName() == "i386") {
3296    CmdArgs.push_back("-m");
3297    CmdArgs.push_back("elf_i386_fbsd");
3298  }
3299
3300  if (Output.isFilename()) {
3301    CmdArgs.push_back("-o");
3302    CmdArgs.push_back(Output.getFilename());
3303  } else {
3304    assert(Output.isNothing() && "Invalid output.");
3305  }
3306
3307  if (!Args.hasArg(options::OPT_nostdlib) &&
3308      !Args.hasArg(options::OPT_nostartfiles)) {
3309    if (!Args.hasArg(options::OPT_shared)) {
3310      if (Args.hasArg(options::OPT_pg))
3311        CmdArgs.push_back(Args.MakeArgString(
3312                                getToolChain().GetFilePath("gcrt1.o")));
3313      else
3314        CmdArgs.push_back(Args.MakeArgString(
3315                                getToolChain().GetFilePath("crt1.o")));
3316      CmdArgs.push_back(Args.MakeArgString(
3317                              getToolChain().GetFilePath("crti.o")));
3318      CmdArgs.push_back(Args.MakeArgString(
3319                              getToolChain().GetFilePath("crtbegin.o")));
3320    } else {
3321      CmdArgs.push_back(Args.MakeArgString(
3322                              getToolChain().GetFilePath("crti.o")));
3323      CmdArgs.push_back(Args.MakeArgString(
3324                              getToolChain().GetFilePath("crtbeginS.o")));
3325    }
3326  }
3327
3328  Args.AddAllArgs(CmdArgs, options::OPT_L);
3329  const ToolChain::path_list Paths = getToolChain().getFilePaths();
3330  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
3331       i != e; ++i)
3332    CmdArgs.push_back(Args.MakeArgString(llvm::StringRef("-L") + *i));
3333  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3334  Args.AddAllArgs(CmdArgs, options::OPT_e);
3335  Args.AddAllArgs(CmdArgs, options::OPT_s);
3336  Args.AddAllArgs(CmdArgs, options::OPT_t);
3337  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
3338  Args.AddAllArgs(CmdArgs, options::OPT_r);
3339
3340  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3341
3342  if (!Args.hasArg(options::OPT_nostdlib) &&
3343      !Args.hasArg(options::OPT_nodefaultlibs)) {
3344    if (D.CCCIsCXX) {
3345      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3346      if (Args.hasArg(options::OPT_pg))
3347        CmdArgs.push_back("-lm_p");
3348      else
3349        CmdArgs.push_back("-lm");
3350    }
3351    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
3352    // the default system libraries. Just mimic this for now.
3353    if (Args.hasArg(options::OPT_pg))
3354      CmdArgs.push_back("-lgcc_p");
3355    else
3356      CmdArgs.push_back("-lgcc");
3357    if (Args.hasArg(options::OPT_static)) {
3358      CmdArgs.push_back("-lgcc_eh");
3359    } else if (Args.hasArg(options::OPT_pg)) {
3360      CmdArgs.push_back("-lgcc_eh_p");
3361    } else {
3362      CmdArgs.push_back("--as-needed");
3363      CmdArgs.push_back("-lgcc_s");
3364      CmdArgs.push_back("--no-as-needed");
3365    }
3366
3367    if (Args.hasArg(options::OPT_pthread)) {
3368      if (Args.hasArg(options::OPT_pg))
3369        CmdArgs.push_back("-lpthread_p");
3370      else
3371        CmdArgs.push_back("-lpthread");
3372    }
3373
3374    if (Args.hasArg(options::OPT_pg)) {
3375      if (Args.hasArg(options::OPT_shared))
3376        CmdArgs.push_back("-lc");
3377      else
3378        CmdArgs.push_back("-lc_p");
3379      CmdArgs.push_back("-lgcc_p");
3380    } else {
3381      CmdArgs.push_back("-lc");
3382      CmdArgs.push_back("-lgcc");
3383    }
3384
3385    if (Args.hasArg(options::OPT_static)) {
3386      CmdArgs.push_back("-lgcc_eh");
3387    } else if (Args.hasArg(options::OPT_pg)) {
3388      CmdArgs.push_back("-lgcc_eh_p");
3389    } else {
3390      CmdArgs.push_back("--as-needed");
3391      CmdArgs.push_back("-lgcc_s");
3392      CmdArgs.push_back("--no-as-needed");
3393    }
3394  }
3395
3396  if (!Args.hasArg(options::OPT_nostdlib) &&
3397      !Args.hasArg(options::OPT_nostartfiles)) {
3398    if (!Args.hasArg(options::OPT_shared))
3399      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3400                                                                  "crtend.o")));
3401    else
3402      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3403                                                                 "crtendS.o")));
3404    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3405                                                                    "crtn.o")));
3406  }
3407
3408  const char *Exec =
3409    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
3410  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3411}
3412
3413void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3414                                     const InputInfo &Output,
3415                                     const InputInfoList &Inputs,
3416                                     const ArgList &Args,
3417                                     const char *LinkingOutput) const {
3418  ArgStringList CmdArgs;
3419
3420  // When building 32-bit code on NetBSD/amd64, we have to explicitly
3421  // instruct as in the base system to assemble 32-bit code.
3422  if (getToolChain().getArchName() == "i386")
3423    CmdArgs.push_back("--32");
3424
3425
3426  // Set byte order explicitly
3427  if (getToolChain().getArchName() == "mips")
3428    CmdArgs.push_back("-EB");
3429  else if (getToolChain().getArchName() == "mipsel")
3430    CmdArgs.push_back("-EL");
3431
3432  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3433                       options::OPT_Xassembler);
3434
3435  CmdArgs.push_back("-o");
3436  CmdArgs.push_back(Output.getFilename());
3437
3438  for (InputInfoList::const_iterator
3439         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3440    const InputInfo &II = *it;
3441    CmdArgs.push_back(II.getFilename());
3442  }
3443
3444  const char *Exec = Args.MakeArgString(FindTargetProgramPath(getToolChain(),
3445                                                              "as"));
3446  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3447}
3448
3449void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
3450                                 const InputInfo &Output,
3451                                 const InputInfoList &Inputs,
3452                                 const ArgList &Args,
3453                                 const char *LinkingOutput) const {
3454  const Driver &D = getToolChain().getDriver();
3455  ArgStringList CmdArgs;
3456
3457  if (!D.SysRoot.empty())
3458    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3459
3460  if (Args.hasArg(options::OPT_static)) {
3461    CmdArgs.push_back("-Bstatic");
3462  } else {
3463    if (Args.hasArg(options::OPT_rdynamic))
3464      CmdArgs.push_back("-export-dynamic");
3465    CmdArgs.push_back("--eh-frame-hdr");
3466    if (Args.hasArg(options::OPT_shared)) {
3467      CmdArgs.push_back("-Bshareable");
3468    } else {
3469      CmdArgs.push_back("-dynamic-linker");
3470      CmdArgs.push_back("/libexec/ld.elf_so");
3471    }
3472  }
3473
3474  // When building 32-bit code on NetBSD/amd64, we have to explicitly
3475  // instruct ld in the base system to link 32-bit code.
3476  if (getToolChain().getArchName() == "i386") {
3477    CmdArgs.push_back("-m");
3478    CmdArgs.push_back("elf_i386");
3479  }
3480
3481  if (Output.isFilename()) {
3482    CmdArgs.push_back("-o");
3483    CmdArgs.push_back(Output.getFilename());
3484  } else {
3485    assert(Output.isNothing() && "Invalid output.");
3486  }
3487
3488  if (!Args.hasArg(options::OPT_nostdlib) &&
3489      !Args.hasArg(options::OPT_nostartfiles)) {
3490    if (!Args.hasArg(options::OPT_shared)) {
3491      CmdArgs.push_back(Args.MakeArgString(
3492                              getToolChain().GetFilePath("crt0.o")));
3493      CmdArgs.push_back(Args.MakeArgString(
3494                              getToolChain().GetFilePath("crti.o")));
3495      CmdArgs.push_back(Args.MakeArgString(
3496                              getToolChain().GetFilePath("crtbegin.o")));
3497    } else {
3498      CmdArgs.push_back(Args.MakeArgString(
3499                              getToolChain().GetFilePath("crti.o")));
3500      CmdArgs.push_back(Args.MakeArgString(
3501                              getToolChain().GetFilePath("crtbeginS.o")));
3502    }
3503  }
3504
3505  Args.AddAllArgs(CmdArgs, options::OPT_L);
3506  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3507  Args.AddAllArgs(CmdArgs, options::OPT_e);
3508  Args.AddAllArgs(CmdArgs, options::OPT_s);
3509  Args.AddAllArgs(CmdArgs, options::OPT_t);
3510  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
3511  Args.AddAllArgs(CmdArgs, options::OPT_r);
3512
3513  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3514
3515  if (!Args.hasArg(options::OPT_nostdlib) &&
3516      !Args.hasArg(options::OPT_nodefaultlibs)) {
3517    if (D.CCCIsCXX) {
3518      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3519      CmdArgs.push_back("-lm");
3520    }
3521    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
3522    // the default system libraries. Just mimic this for now.
3523    CmdArgs.push_back("-lgcc");
3524    if (Args.hasArg(options::OPT_static)) {
3525      CmdArgs.push_back("-lgcc_eh");
3526    } else {
3527      CmdArgs.push_back("--as-needed");
3528      CmdArgs.push_back("-lgcc_s");
3529      CmdArgs.push_back("--no-as-needed");
3530    }
3531
3532    if (Args.hasArg(options::OPT_pthread))
3533      CmdArgs.push_back("-lpthread");
3534    CmdArgs.push_back("-lc");
3535
3536    CmdArgs.push_back("-lgcc");
3537    if (Args.hasArg(options::OPT_static)) {
3538      CmdArgs.push_back("-lgcc_eh");
3539    } else {
3540      CmdArgs.push_back("--as-needed");
3541      CmdArgs.push_back("-lgcc_s");
3542      CmdArgs.push_back("--no-as-needed");
3543    }
3544  }
3545
3546  if (!Args.hasArg(options::OPT_nostdlib) &&
3547      !Args.hasArg(options::OPT_nostartfiles)) {
3548    if (!Args.hasArg(options::OPT_shared))
3549      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3550                                                                  "crtend.o")));
3551    else
3552      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3553                                                                 "crtendS.o")));
3554    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3555                                                                    "crtn.o")));
3556  }
3557
3558  const char *Exec = Args.MakeArgString(FindTargetProgramPath(getToolChain(),
3559                                                              "ld"));
3560  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3561}
3562
3563void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3564                                        const InputInfo &Output,
3565                                        const InputInfoList &Inputs,
3566                                        const ArgList &Args,
3567                                        const char *LinkingOutput) const {
3568  ArgStringList CmdArgs;
3569
3570  // Add --32/--64 to make sure we get the format we want.
3571  // This is incomplete
3572  if (getToolChain().getArch() == llvm::Triple::x86) {
3573    CmdArgs.push_back("--32");
3574  } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
3575    CmdArgs.push_back("--64");
3576  } else if (getToolChain().getArch() == llvm::Triple::arm) {
3577    llvm::StringRef MArch = getToolChain().getArchName();
3578    if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
3579      CmdArgs.push_back("-mfpu=neon");
3580  }
3581
3582  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3583                       options::OPT_Xassembler);
3584
3585  CmdArgs.push_back("-o");
3586  CmdArgs.push_back(Output.getFilename());
3587
3588  for (InputInfoList::const_iterator
3589         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3590    const InputInfo &II = *it;
3591    CmdArgs.push_back(II.getFilename());
3592  }
3593
3594  const char *Exec =
3595    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3596  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3597}
3598
3599void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
3600                                    const InputInfo &Output,
3601                                    const InputInfoList &Inputs,
3602                                    const ArgList &Args,
3603                                    const char *LinkingOutput) const {
3604  const toolchains::Linux& ToolChain =
3605    static_cast<const toolchains::Linux&>(getToolChain());
3606  const Driver &D = ToolChain.getDriver();
3607  ArgStringList CmdArgs;
3608
3609  // Silence warning for "clang -g foo.o -o foo"
3610  Args.ClaimAllArgs(options::OPT_g_Group);
3611  // and "clang -emit-llvm foo.o -o foo"
3612  Args.ClaimAllArgs(options::OPT_emit_llvm);
3613  // and for "clang -g foo.o -o foo". Other warning options are already
3614  // handled somewhere else.
3615  Args.ClaimAllArgs(options::OPT_w);
3616
3617  if (!D.SysRoot.empty())
3618    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3619
3620  if (Args.hasArg(options::OPT_pie))
3621    CmdArgs.push_back("-pie");
3622
3623  if (Args.hasArg(options::OPT_rdynamic))
3624    CmdArgs.push_back("-export-dynamic");
3625
3626  if (Args.hasArg(options::OPT_s))
3627    CmdArgs.push_back("-s");
3628
3629  for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
3630         e = ToolChain.ExtraOpts.end();
3631       i != e; ++i)
3632    CmdArgs.push_back(i->c_str());
3633
3634  if (!Args.hasArg(options::OPT_static)) {
3635    CmdArgs.push_back("--eh-frame-hdr");
3636  }
3637
3638  CmdArgs.push_back("-m");
3639  if (ToolChain.getArch() == llvm::Triple::x86)
3640    CmdArgs.push_back("elf_i386");
3641  else if (ToolChain.getArch() == llvm::Triple::arm
3642           ||  ToolChain.getArch() == llvm::Triple::thumb)
3643    CmdArgs.push_back("armelf_linux_eabi");
3644  else
3645    CmdArgs.push_back("elf_x86_64");
3646
3647  if (Args.hasArg(options::OPT_static)) {
3648    if (ToolChain.getArch() == llvm::Triple::arm
3649        || ToolChain.getArch() == llvm::Triple::thumb)
3650      CmdArgs.push_back("-Bstatic");
3651    else
3652      CmdArgs.push_back("-static");
3653  } else if (Args.hasArg(options::OPT_shared)) {
3654    CmdArgs.push_back("-shared");
3655  }
3656
3657  if (ToolChain.getArch() == llvm::Triple::arm ||
3658      ToolChain.getArch() == llvm::Triple::thumb ||
3659      (!Args.hasArg(options::OPT_static) &&
3660       !Args.hasArg(options::OPT_shared))) {
3661    CmdArgs.push_back("-dynamic-linker");
3662    if (ToolChain.getArch() == llvm::Triple::x86)
3663      CmdArgs.push_back("/lib/ld-linux.so.2");
3664    else if (ToolChain.getArch() == llvm::Triple::arm ||
3665             ToolChain.getArch() == llvm::Triple::thumb)
3666      CmdArgs.push_back("/lib/ld-linux.so.3");
3667    else
3668      CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
3669  }
3670
3671  CmdArgs.push_back("-o");
3672  CmdArgs.push_back(Output.getFilename());
3673
3674  if (!Args.hasArg(options::OPT_nostdlib) &&
3675      !Args.hasArg(options::OPT_nostartfiles)) {
3676    const char *crt1 = NULL;
3677    if (!Args.hasArg(options::OPT_shared)){
3678      if (Args.hasArg(options::OPT_pie))
3679        crt1 = "Scrt1.o";
3680      else
3681        crt1 = "crt1.o";
3682    }
3683    if (crt1)
3684      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
3685
3686    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
3687
3688    const char *crtbegin;
3689    if (Args.hasArg(options::OPT_static))
3690      crtbegin = "crtbeginT.o";
3691    else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
3692      crtbegin = "crtbeginS.o";
3693    else
3694      crtbegin = "crtbegin.o";
3695    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
3696  }
3697
3698  Args.AddAllArgs(CmdArgs, options::OPT_L);
3699
3700  const ToolChain::path_list Paths = ToolChain.getFilePaths();
3701
3702  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
3703       i != e; ++i)
3704    CmdArgs.push_back(Args.MakeArgString(llvm::StringRef("-L") + *i));
3705
3706  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
3707
3708  if (D.CCCIsCXX && !Args.hasArg(options::OPT_nostdlib)) {
3709    ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
3710    CmdArgs.push_back("-lm");
3711  }
3712
3713  if (Args.hasArg(options::OPT_static))
3714    CmdArgs.push_back("--start-group");
3715
3716  if (!Args.hasArg(options::OPT_nostdlib)) {
3717    if (!D.CCCIsCXX)
3718      CmdArgs.push_back("-lgcc");
3719
3720    if (Args.hasArg(options::OPT_static)) {
3721      if (D.CCCIsCXX)
3722        CmdArgs.push_back("-lgcc");
3723    } else {
3724      if (!D.CCCIsCXX)
3725        CmdArgs.push_back("--as-needed");
3726      CmdArgs.push_back("-lgcc_s");
3727      if (!D.CCCIsCXX)
3728        CmdArgs.push_back("--no-as-needed");
3729    }
3730
3731    if (Args.hasArg(options::OPT_static))
3732      CmdArgs.push_back("-lgcc_eh");
3733    else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
3734      CmdArgs.push_back("-lgcc");
3735
3736    if (Args.hasArg(options::OPT_pthread) ||
3737        Args.hasArg(options::OPT_pthreads))
3738      CmdArgs.push_back("-lpthread");
3739
3740    CmdArgs.push_back("-lc");
3741
3742    if (Args.hasArg(options::OPT_static))
3743      CmdArgs.push_back("--end-group");
3744    else {
3745      if (!D.CCCIsCXX)
3746        CmdArgs.push_back("-lgcc");
3747
3748      if (!D.CCCIsCXX)
3749        CmdArgs.push_back("--as-needed");
3750      CmdArgs.push_back("-lgcc_s");
3751      if (!D.CCCIsCXX)
3752        CmdArgs.push_back("--no-as-needed");
3753
3754      if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
3755        CmdArgs.push_back("-lgcc");
3756    }
3757
3758
3759    if (!Args.hasArg(options::OPT_nostartfiles)) {
3760      const char *crtend;
3761      if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
3762        crtend = "crtendS.o";
3763      else
3764        crtend = "crtend.o";
3765
3766      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
3767      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
3768    }
3769  }
3770
3771  if (Args.hasArg(options::OPT_use_gold_plugin)) {
3772    CmdArgs.push_back("-plugin");
3773    std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
3774    CmdArgs.push_back(Args.MakeArgString(Plugin));
3775  }
3776
3777  C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
3778}
3779
3780void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3781                                   const InputInfo &Output,
3782                                   const InputInfoList &Inputs,
3783                                   const ArgList &Args,
3784                                   const char *LinkingOutput) const {
3785  ArgStringList CmdArgs;
3786
3787  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3788                       options::OPT_Xassembler);
3789
3790  CmdArgs.push_back("-o");
3791  CmdArgs.push_back(Output.getFilename());
3792
3793  for (InputInfoList::const_iterator
3794         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3795    const InputInfo &II = *it;
3796    CmdArgs.push_back(II.getFilename());
3797  }
3798
3799  const char *Exec =
3800    Args.MakeArgString(getToolChain().GetProgramPath("gas"));
3801  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3802}
3803
3804void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
3805                               const InputInfo &Output,
3806                               const InputInfoList &Inputs,
3807                               const ArgList &Args,
3808                               const char *LinkingOutput) const {
3809  const Driver &D = getToolChain().getDriver();
3810  ArgStringList CmdArgs;
3811
3812  if (Output.isFilename()) {
3813    CmdArgs.push_back("-o");
3814    CmdArgs.push_back(Output.getFilename());
3815  } else {
3816    assert(Output.isNothing() && "Invalid output.");
3817  }
3818
3819  if (!Args.hasArg(options::OPT_nostdlib) &&
3820      !Args.hasArg(options::OPT_nostartfiles))
3821    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3822                                                      "/usr/gnu/lib/crtso.o")));
3823
3824  Args.AddAllArgs(CmdArgs, options::OPT_L);
3825  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3826  Args.AddAllArgs(CmdArgs, options::OPT_e);
3827
3828  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3829
3830  if (!Args.hasArg(options::OPT_nostdlib) &&
3831      !Args.hasArg(options::OPT_nodefaultlibs)) {
3832    if (D.CCCIsCXX) {
3833      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3834      CmdArgs.push_back("-lm");
3835    }
3836
3837    if (Args.hasArg(options::OPT_pthread))
3838      CmdArgs.push_back("-lpthread");
3839    CmdArgs.push_back("-lc");
3840    CmdArgs.push_back("-lgcc");
3841    CmdArgs.push_back("-L/usr/gnu/lib");
3842    // FIXME: fill in the correct search path for the final
3843    // support libraries.
3844    CmdArgs.push_back("-L/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
3845  }
3846
3847  if (!Args.hasArg(options::OPT_nostdlib) &&
3848      !Args.hasArg(options::OPT_nostartfiles)) {
3849    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
3850                                              "/usr/gnu/lib/libend.a")));
3851  }
3852
3853  const char *Exec =
3854    Args.MakeArgString(getToolChain().GetProgramPath("/usr/gnu/bin/gld"));
3855  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3856}
3857
3858/// DragonFly Tools
3859
3860// For now, DragonFly Assemble does just about the same as for
3861// FreeBSD, but this may change soon.
3862void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3863                                       const InputInfo &Output,
3864                                       const InputInfoList &Inputs,
3865                                       const ArgList &Args,
3866                                       const char *LinkingOutput) const {
3867  ArgStringList CmdArgs;
3868
3869  // When building 32-bit code on DragonFly/pc64, we have to explicitly
3870  // instruct as in the base system to assemble 32-bit code.
3871  if (getToolChain().getArchName() == "i386")
3872    CmdArgs.push_back("--32");
3873
3874  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3875                       options::OPT_Xassembler);
3876
3877  CmdArgs.push_back("-o");
3878  CmdArgs.push_back(Output.getFilename());
3879
3880  for (InputInfoList::const_iterator
3881         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3882    const InputInfo &II = *it;
3883    CmdArgs.push_back(II.getFilename());
3884  }
3885
3886  const char *Exec =
3887    Args.MakeArgString(getToolChain().GetProgramPath("as"));
3888  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3889}
3890
3891void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
3892                                   const InputInfo &Output,
3893                                   const InputInfoList &Inputs,
3894                                   const ArgList &Args,
3895                                   const char *LinkingOutput) const {
3896  const Driver &D = getToolChain().getDriver();
3897  ArgStringList CmdArgs;
3898
3899  if (!D.SysRoot.empty())
3900    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
3901
3902  if (Args.hasArg(options::OPT_static)) {
3903    CmdArgs.push_back("-Bstatic");
3904  } else {
3905    if (Args.hasArg(options::OPT_shared))
3906      CmdArgs.push_back("-Bshareable");
3907    else {
3908      CmdArgs.push_back("-dynamic-linker");
3909      CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
3910    }
3911  }
3912
3913  // When building 32-bit code on DragonFly/pc64, we have to explicitly
3914  // instruct ld in the base system to link 32-bit code.
3915  if (getToolChain().getArchName() == "i386") {
3916    CmdArgs.push_back("-m");
3917    CmdArgs.push_back("elf_i386");
3918  }
3919
3920  if (Output.isFilename()) {
3921    CmdArgs.push_back("-o");
3922    CmdArgs.push_back(Output.getFilename());
3923  } else {
3924    assert(Output.isNothing() && "Invalid output.");
3925  }
3926
3927  if (!Args.hasArg(options::OPT_nostdlib) &&
3928      !Args.hasArg(options::OPT_nostartfiles)) {
3929    if (!Args.hasArg(options::OPT_shared)) {
3930      CmdArgs.push_back(
3931            Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
3932      CmdArgs.push_back(
3933            Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
3934      CmdArgs.push_back(
3935            Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
3936    } else {
3937      CmdArgs.push_back(
3938            Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
3939      CmdArgs.push_back(
3940            Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
3941    }
3942  }
3943
3944  Args.AddAllArgs(CmdArgs, options::OPT_L);
3945  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
3946  Args.AddAllArgs(CmdArgs, options::OPT_e);
3947
3948  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
3949
3950  if (!Args.hasArg(options::OPT_nostdlib) &&
3951      !Args.hasArg(options::OPT_nodefaultlibs)) {
3952    // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
3953    //         rpaths
3954    CmdArgs.push_back("-L/usr/lib/gcc41");
3955
3956    if (!Args.hasArg(options::OPT_static)) {
3957      CmdArgs.push_back("-rpath");
3958      CmdArgs.push_back("/usr/lib/gcc41");
3959
3960      CmdArgs.push_back("-rpath-link");
3961      CmdArgs.push_back("/usr/lib/gcc41");
3962
3963      CmdArgs.push_back("-rpath");
3964      CmdArgs.push_back("/usr/lib");
3965
3966      CmdArgs.push_back("-rpath-link");
3967      CmdArgs.push_back("/usr/lib");
3968    }
3969
3970    if (D.CCCIsCXX) {
3971      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
3972      CmdArgs.push_back("-lm");
3973    }
3974
3975    if (Args.hasArg(options::OPT_shared)) {
3976      CmdArgs.push_back("-lgcc_pic");
3977    } else {
3978      CmdArgs.push_back("-lgcc");
3979    }
3980
3981
3982    if (Args.hasArg(options::OPT_pthread))
3983      CmdArgs.push_back("-lpthread");
3984
3985    if (!Args.hasArg(options::OPT_nolibc)) {
3986      CmdArgs.push_back("-lc");
3987    }
3988
3989    if (Args.hasArg(options::OPT_shared)) {
3990      CmdArgs.push_back("-lgcc_pic");
3991    } else {
3992      CmdArgs.push_back("-lgcc");
3993    }
3994  }
3995
3996  if (!Args.hasArg(options::OPT_nostdlib) &&
3997      !Args.hasArg(options::OPT_nostartfiles)) {
3998    if (!Args.hasArg(options::OPT_shared))
3999      CmdArgs.push_back(Args.MakeArgString(
4000                              getToolChain().GetFilePath("crtend.o")));
4001    else
4002      CmdArgs.push_back(Args.MakeArgString(
4003                              getToolChain().GetFilePath("crtendS.o")));
4004    CmdArgs.push_back(Args.MakeArgString(
4005                              getToolChain().GetFilePath("crtn.o")));
4006  }
4007
4008  const char *Exec =
4009    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4010  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4011}
4012
4013void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
4014                                      const InputInfo &Output,
4015                                      const InputInfoList &Inputs,
4016                                      const ArgList &Args,
4017                                      const char *LinkingOutput) const {
4018  ArgStringList CmdArgs;
4019
4020  if (Output.isFilename()) {
4021    CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
4022                                         Output.getFilename()));
4023  } else {
4024    assert(Output.isNothing() && "Invalid output.");
4025  }
4026
4027  if (!Args.hasArg(options::OPT_nostdlib) &&
4028    !Args.hasArg(options::OPT_nostartfiles)) {
4029    CmdArgs.push_back("-defaultlib:libcmt");
4030  }
4031
4032  CmdArgs.push_back("-nologo");
4033
4034  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4035
4036  const char *Exec =
4037    Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
4038  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4039}
4040