Tools.cpp revision 207619
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/Format.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/System/Host.h"
31#include "llvm/System/Process.h"
32
33#include "InputInfo.h"
34#include "ToolChains.h"
35
36using namespace clang::driver;
37using namespace clang::driver::tools;
38
39/// CheckPreprocessingOptions - Perform some validation of preprocessing
40/// arguments that is shared with gcc.
41static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
42  if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
43    if (!Args.hasArg(options::OPT_E))
44      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
45        << A->getAsString(Args) << "-E";
46}
47
48/// CheckCodeGenerationOptions - Perform some validation of code generation
49/// arguments that is shared with gcc.
50static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
51  // In gcc, only ARM checks this, but it seems reasonable to check universally.
52  if (Args.hasArg(options::OPT_static))
53    if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
54                                       options::OPT_mdynamic_no_pic))
55      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
56        << A->getAsString(Args) << "-static";
57}
58
59// Quote target names for inclusion in GNU Make dependency files.
60// Only the characters '$', '#', ' ', '\t' are quoted.
61static void QuoteTarget(llvm::StringRef Target,
62                        llvm::SmallVectorImpl<char> &Res) {
63  for (unsigned i = 0, e = Target.size(); i != e; ++i) {
64    switch (Target[i]) {
65    case ' ':
66    case '\t':
67      // Escape the preceding backslashes
68      for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
69        Res.push_back('\\');
70
71      // Escape the space/tab
72      Res.push_back('\\');
73      break;
74    case '$':
75      Res.push_back('$');
76      break;
77    case '#':
78      Res.push_back('\\');
79      break;
80    default:
81      break;
82    }
83
84    Res.push_back(Target[i]);
85  }
86}
87
88void Clang::AddPreprocessingOptions(const Driver &D,
89                                    const ArgList &Args,
90                                    ArgStringList &CmdArgs,
91                                    const InputInfo &Output,
92                                    const InputInfoList &Inputs) const {
93  Arg *A;
94
95  CheckPreprocessingOptions(D, Args);
96
97  Args.AddLastArg(CmdArgs, options::OPT_C);
98  Args.AddLastArg(CmdArgs, options::OPT_CC);
99
100  // Handle dependency file generation.
101  if ((A = Args.getLastArg(options::OPT_M)) ||
102      (A = Args.getLastArg(options::OPT_MM)) ||
103      (A = Args.getLastArg(options::OPT_MD)) ||
104      (A = Args.getLastArg(options::OPT_MMD))) {
105    // Determine the output location.
106    const char *DepFile;
107    if (Output.getType() == types::TY_Dependencies) {
108      if (Output.isPipe())
109        DepFile = "-";
110      else
111        DepFile = Output.getFilename();
112    } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
113      DepFile = MF->getValue(Args);
114    } else if (A->getOption().matches(options::OPT_M) ||
115               A->getOption().matches(options::OPT_MM)) {
116      DepFile = "-";
117    } else {
118      DepFile = darwin::CC1::getDependencyFileName(Args, Inputs);
119    }
120    CmdArgs.push_back("-dependency-file");
121    CmdArgs.push_back(DepFile);
122
123    // Add a default target if one wasn't specified.
124    if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
125      const char *DepTarget;
126
127      // If user provided -o, that is the dependency target, except
128      // when we are only generating a dependency file.
129      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
130      if (OutputOpt && Output.getType() != types::TY_Dependencies) {
131        DepTarget = OutputOpt->getValue(Args);
132      } else {
133        // Otherwise derive from the base input.
134        //
135        // FIXME: This should use the computed output file location.
136        llvm::sys::Path P(Inputs[0].getBaseInput());
137
138        P.eraseSuffix();
139        P.appendSuffix("o");
140        DepTarget = Args.MakeArgString(P.getLast());
141      }
142
143      CmdArgs.push_back("-MT");
144      llvm::SmallString<128> Quoted;
145      QuoteTarget(DepTarget, Quoted);
146      CmdArgs.push_back(Args.MakeArgString(Quoted));
147    }
148
149    if (A->getOption().matches(options::OPT_M) ||
150        A->getOption().matches(options::OPT_MD))
151      CmdArgs.push_back("-sys-header-deps");
152  }
153
154  Args.AddLastArg(CmdArgs, options::OPT_MP);
155
156  // Convert all -MQ <target> args to -MT <quoted target>
157  for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
158                                             options::OPT_MQ),
159         ie = Args.filtered_end(); it != ie; ++it) {
160
161    it->claim();
162
163    if (it->getOption().matches(options::OPT_MQ)) {
164      CmdArgs.push_back("-MT");
165      llvm::SmallString<128> Quoted;
166      QuoteTarget(it->getValue(Args), Quoted);
167      CmdArgs.push_back(Args.MakeArgString(Quoted));
168
169    // -MT flag - no change
170    } else {
171      it->render(Args, CmdArgs);
172    }
173  }
174
175  // Add -i* options, and automatically translate to
176  // -include-pch/-include-pth for transparent PCH support. It's
177  // wonky, but we include looking for .gch so we can support seamless
178  // replacement into a build system already set up to be generating
179  // .gch files.
180  for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
181         ie = Args.filtered_end(); it != ie; ++it) {
182    const Arg *A = it;
183
184    if (A->getOption().matches(options::OPT_include)) {
185      // Use PCH if the user requested it, except for C++ (for now).
186      bool UsePCH = D.CCCUsePCH;
187      if (types::isCXX(Inputs[0].getType()))
188        UsePCH = false;
189
190      bool FoundPTH = false;
191      bool FoundPCH = false;
192      llvm::sys::Path P(A->getValue(Args));
193      if (UsePCH) {
194        P.appendSuffix("pch");
195        if (P.exists())
196          FoundPCH = true;
197        else
198          P.eraseSuffix();
199      }
200
201      if (!FoundPCH) {
202        P.appendSuffix("pth");
203        if (P.exists())
204          FoundPTH = true;
205        else
206          P.eraseSuffix();
207      }
208
209      if (!FoundPCH && !FoundPTH) {
210        P.appendSuffix("gch");
211        if (P.exists()) {
212          FoundPCH = UsePCH;
213          FoundPTH = !UsePCH;
214        }
215        else
216          P.eraseSuffix();
217      }
218
219      if (FoundPCH || FoundPTH) {
220        A->claim();
221        if (UsePCH)
222          CmdArgs.push_back("-include-pch");
223        else
224          CmdArgs.push_back("-include-pth");
225        CmdArgs.push_back(Args.MakeArgString(P.str()));
226        continue;
227      }
228    }
229
230    // Not translated, render as usual.
231    A->claim();
232    A->render(Args, CmdArgs);
233  }
234
235  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
236  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
237
238  // Add -Wp, and -Xassembler if using the preprocessor.
239
240  // FIXME: There is a very unfortunate problem here, some troubled
241  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
242  // really support that we would have to parse and then translate
243  // those options. :(
244  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
245                       options::OPT_Xpreprocessor);
246
247  // -I- is a deprecated GCC feature, reject it.
248  if (Arg *A = Args.getLastArg(options::OPT_I_))
249    D.Diag(clang::diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
250}
251
252/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targetting.
253//
254// FIXME: tblgen this.
255static const char *getARMTargetCPU(const ArgList &Args) {
256  // FIXME: Warn on inconsistent use of -mcpu and -march.
257
258  // If we have -mcpu=, use that.
259  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
260    return A->getValue(Args);
261
262  // Otherwise, if we have -march= choose the base CPU for that arch.
263  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
264    llvm::StringRef MArch = A->getValue(Args);
265
266    if (MArch == "armv2" || MArch == "armv2a")
267      return "arm2";
268    if (MArch == "armv3")
269      return "arm6";
270    if (MArch == "armv3m")
271      return "arm7m";
272    if (MArch == "armv4" || MArch == "armv4t")
273      return "arm7tdmi";
274    if (MArch == "armv5" || MArch == "armv5t")
275      return "arm10tdmi";
276    if (MArch == "armv5e" || MArch == "armv5te")
277      return "arm1026ejs";
278    if (MArch == "armv5tej")
279      return "arm926ej-s";
280    if (MArch == "armv6" || MArch == "armv6k")
281      return "arm1136jf-s";
282    if (MArch == "armv6j")
283      return "arm1136j-s";
284    if (MArch == "armv6z" || MArch == "armv6zk")
285      return "arm1176jzf-s";
286    if (MArch == "armv6t2")
287      return "arm1156t2-s";
288    if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
289      return "cortex-a8";
290    if (MArch == "armv7r" || MArch == "armv7-r")
291      return "cortex-r4";
292    if (MArch == "armv7m" || MArch == "armv7-m")
293      return "cortex-m3";
294    if (MArch == "ep9312")
295      return "ep9312";
296    if (MArch == "iwmmxt")
297      return "iwmmxt";
298    if (MArch == "xscale")
299      return "xscale";
300  }
301
302  // Otherwise return the most base CPU LLVM supports.
303  return "arm7tdmi";
304}
305
306/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
307/// CPU.
308//
309// FIXME: This is redundant with -mcpu, why does LLVM use this.
310// FIXME: tblgen this, or kill it!
311static const char *getLLVMArchSuffixForARM(llvm::StringRef CPU) {
312  if (CPU == "arm7tdmi" || CPU == "arm7tdmi-s" || CPU == "arm710t" ||
313      CPU == "arm720t" || CPU == "arm9" || CPU == "arm9tdmi" ||
314      CPU == "arm920" || CPU == "arm920t" || CPU == "arm922t" ||
315      CPU == "arm940t" || CPU == "ep9312")
316    return "v4t";
317
318  if (CPU == "arm10tdmi" || CPU == "arm1020t")
319    return "v5";
320
321  if (CPU == "arm9e" || CPU == "arm926ej-s" || CPU == "arm946e-s" ||
322      CPU == "arm966e-s" || CPU == "arm968e-s" || CPU == "arm10e" ||
323      CPU == "arm1020e" || CPU == "arm1022e" || CPU == "xscale" ||
324      CPU == "iwmmxt")
325    return "v5e";
326
327  if (CPU == "arm1136j-s" || CPU == "arm1136jf-s" || CPU == "arm1176jz-s" ||
328      CPU == "arm1176jzf-s" || CPU == "mpcorenovfp" || CPU == "mpcore")
329    return "v6";
330
331  if (CPU == "arm1156t2-s" || CPU == "arm1156t2f-s")
332    return "v6t2";
333
334  if (CPU == "cortex-a8" || CPU == "cortex-a9")
335    return "v7";
336
337  return "";
338}
339
340/// getLLVMTriple - Get the LLVM triple to use for a particular toolchain, which
341/// may depend on command line arguments.
342static std::string getLLVMTriple(const ToolChain &TC, const ArgList &Args) {
343  switch (TC.getTriple().getArch()) {
344  default:
345    return TC.getTripleString();
346
347  case llvm::Triple::arm:
348  case llvm::Triple::thumb: {
349    // FIXME: Factor into subclasses.
350    llvm::Triple Triple = TC.getTriple();
351
352    // Thumb2 is the default for V7 on Darwin.
353    //
354    // FIXME: Thumb should just be another -target-feaure, not in the triple.
355    llvm::StringRef Suffix = getLLVMArchSuffixForARM(getARMTargetCPU(Args));
356    bool ThumbDefault =
357      (Suffix == "v7" && TC.getTriple().getOS() == llvm::Triple::Darwin);
358    std::string ArchName = "arm";
359    if (Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
360      ArchName = "thumb";
361    Triple.setArchName(ArchName + Suffix.str());
362
363    return Triple.getTriple();
364  }
365  }
366}
367
368// FIXME: Move to target hook.
369static bool isSignedCharDefault(const llvm::Triple &Triple) {
370  switch (Triple.getArch()) {
371  default:
372    return true;
373
374  case llvm::Triple::ppc:
375  case llvm::Triple::ppc64:
376    if (Triple.getOS() == llvm::Triple::Darwin)
377      return true;
378    return false;
379
380  case llvm::Triple::systemz:
381    return false;
382  }
383}
384
385void Clang::AddARMTargetArgs(const ArgList &Args,
386                             ArgStringList &CmdArgs) const {
387  const Driver &D = getToolChain().getDriver();
388
389  // Select the ABI to use.
390  //
391  // FIXME: Support -meabi.
392  const char *ABIName = 0;
393  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
394    ABIName = A->getValue(Args);
395  } else {
396    // Select the default based on the platform.
397    switch (getToolChain().getTriple().getOS()) {
398      // FIXME: Is this right for non-Darwin and non-Linux?
399    default:
400      ABIName = "aapcs";
401      break;
402
403    case llvm::Triple::Darwin:
404      ABIName = "apcs-gnu";
405      break;
406
407    case llvm::Triple::Linux:
408      ABIName = "aapcs-linux";
409      break;
410    }
411  }
412  CmdArgs.push_back("-target-abi");
413  CmdArgs.push_back(ABIName);
414
415  // Set the CPU based on -march= and -mcpu=.
416  CmdArgs.push_back("-target-cpu");
417  CmdArgs.push_back(getARMTargetCPU(Args));
418
419  // Select the float ABI as determined by -msoft-float, -mhard-float, and
420  // -mfloat-abi=.
421  llvm::StringRef FloatABI;
422  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
423                               options::OPT_mhard_float,
424                               options::OPT_mfloat_abi_EQ)) {
425    if (A->getOption().matches(options::OPT_msoft_float))
426      FloatABI = "soft";
427    else if (A->getOption().matches(options::OPT_mhard_float))
428      FloatABI = "hard";
429    else {
430      FloatABI = A->getValue(Args);
431      if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
432        D.Diag(clang::diag::err_drv_invalid_mfloat_abi)
433          << A->getAsString(Args);
434        FloatABI = "soft";
435      }
436    }
437  }
438
439  // If unspecified, choose the default based on the platform.
440  if (FloatABI.empty()) {
441    // FIXME: This is wrong for non-Darwin, we don't have a mechanism yet for
442    // distinguishing things like linux-eabi vs linux-elf.
443    switch (getToolChain().getTriple().getOS()) {
444    case llvm::Triple::Darwin: {
445      // Darwin defaults to "softfp" for v6 and v7.
446      //
447      // FIXME: Factor out an ARM class so we can cache the arch somewhere.
448      llvm::StringRef ArchName = getLLVMArchSuffixForARM(getARMTargetCPU(Args));
449      if (ArchName.startswith("v6") || ArchName.startswith("v7"))
450        FloatABI = "softfp";
451      else
452        FloatABI = "soft";
453      break;
454    }
455
456    default:
457      // Assume "soft", but warn the user we are guessing.
458      FloatABI = "soft";
459      D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
460      break;
461    }
462  }
463
464  if (FloatABI == "soft") {
465    // Floating point operations and argument passing are soft.
466    //
467    // FIXME: This changes CPP defines, we need -target-soft-float.
468    CmdArgs.push_back("-msoft-float");
469    CmdArgs.push_back("-mfloat-abi");
470    CmdArgs.push_back("soft");
471  } else if (FloatABI == "softfp") {
472    // Floating point operations are hard, but argument passing is soft.
473    CmdArgs.push_back("-mfloat-abi");
474    CmdArgs.push_back("soft");
475  } else {
476    // Floating point operations and argument passing are hard.
477    assert(FloatABI == "hard" && "Invalid float abi!");
478    CmdArgs.push_back("-mfloat-abi");
479    CmdArgs.push_back("hard");
480  }
481
482  // Set appropriate target features for floating point mode.
483  //
484  // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
485  // yet (it uses the -mfloat-abi and -msoft-float options above), and it is
486  // stripped out by the ARM target.
487
488  // Use software floating point operations?
489  if (FloatABI == "soft") {
490    CmdArgs.push_back("-target-feature");
491    CmdArgs.push_back("+soft-float");
492  }
493
494  // Use software floating point argument passing?
495  if (FloatABI != "hard") {
496    CmdArgs.push_back("-target-feature");
497    CmdArgs.push_back("+soft-float-abi");
498  }
499
500  // Honor -mfpu=.
501  //
502  // FIXME: Centralize feature selection, defaulting shouldn't be also in the
503  // frontend target.
504  if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ)) {
505    llvm::StringRef FPU = A->getValue(Args);
506
507    // Set the target features based on the FPU.
508    if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
509      // Disable any default FPU support.
510      CmdArgs.push_back("-target-feature");
511      CmdArgs.push_back("-vfp2");
512      CmdArgs.push_back("-target-feature");
513      CmdArgs.push_back("-vfp3");
514      CmdArgs.push_back("-target-feature");
515      CmdArgs.push_back("-neon");
516    } else if (FPU == "vfp") {
517      CmdArgs.push_back("-target-feature");
518      CmdArgs.push_back("+vfp2");
519    } else if (FPU == "vfp3") {
520      CmdArgs.push_back("-target-feature");
521      CmdArgs.push_back("+vfp3");
522    } else if (FPU == "neon") {
523      CmdArgs.push_back("-target-feature");
524      CmdArgs.push_back("+neon");
525    } else
526      D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
527  }
528}
529
530void Clang::AddMIPSTargetArgs(const ArgList &Args,
531                             ArgStringList &CmdArgs) const {
532  const Driver &D = getToolChain().getDriver();
533
534  // Select the ABI to use.
535  const char *ABIName = 0;
536  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
537    ABIName = A->getValue(Args);
538  } else {
539    ABIName = "o32";
540  }
541
542  CmdArgs.push_back("-target-abi");
543  CmdArgs.push_back(ABIName);
544
545  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
546    llvm::StringRef MArch = A->getValue(Args);
547    CmdArgs.push_back("-target-cpu");
548
549    if ((MArch == "r2000") || (MArch == "r3000"))
550      CmdArgs.push_back("mips1");
551    else if (MArch == "r6000")
552      CmdArgs.push_back("mips2");
553    else
554      CmdArgs.push_back(MArch.str().c_str());
555  }
556
557  // Select the float ABI as determined by -msoft-float, -mhard-float, and
558  llvm::StringRef FloatABI;
559  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
560                               options::OPT_mhard_float)) {
561    if (A->getOption().matches(options::OPT_msoft_float))
562      FloatABI = "soft";
563    else if (A->getOption().matches(options::OPT_mhard_float))
564      FloatABI = "hard";
565  }
566
567  // If unspecified, choose the default based on the platform.
568  if (FloatABI.empty()) {
569    // Assume "soft", but warn the user we are guessing.
570    FloatABI = "soft";
571    D.Diag(clang::diag::warn_drv_assuming_mfloat_abi_is) << "soft";
572  }
573
574  if (FloatABI == "soft") {
575    // Floating point operations and argument passing are soft.
576    //
577    // FIXME: This changes CPP defines, we need -target-soft-float.
578    CmdArgs.push_back("-msoft-float");
579  } else {
580    assert(FloatABI == "hard" && "Invalid float abi!");
581    CmdArgs.push_back("-mhard-float");
582  }
583}
584
585void Clang::AddX86TargetArgs(const ArgList &Args,
586                             ArgStringList &CmdArgs) const {
587  if (!Args.hasFlag(options::OPT_mred_zone,
588                    options::OPT_mno_red_zone,
589                    true) ||
590      Args.hasArg(options::OPT_mkernel) ||
591      Args.hasArg(options::OPT_fapple_kext))
592    CmdArgs.push_back("-disable-red-zone");
593
594  if (Args.hasFlag(options::OPT_msoft_float,
595                   options::OPT_mno_soft_float,
596                   false))
597    CmdArgs.push_back("-no-implicit-float");
598
599  const char *CPUName = 0;
600  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
601    if (llvm::StringRef(A->getValue(Args)) == "native") {
602      // FIXME: Reject attempts to use -march=native unless the target matches
603      // the host.
604      //
605      // FIXME: We should also incorporate the detected target features for use
606      // with -native.
607      std::string CPU = llvm::sys::getHostCPUName();
608      if (!CPU.empty())
609        CPUName = Args.MakeArgString(CPU);
610    } else
611      CPUName = A->getValue(Args);
612  }
613
614  // Select the default CPU if none was given (or detection failed).
615  if (!CPUName) {
616    // FIXME: Need target hooks.
617    if (getToolChain().getOS().startswith("darwin")) {
618      if (getToolChain().getArchName() == "x86_64")
619        CPUName = "core2";
620      else if (getToolChain().getArchName() == "i386")
621        CPUName = "yonah";
622    } else if (getToolChain().getOS().startswith("haiku"))  {
623      if (getToolChain().getArchName() == "x86_64")
624        CPUName = "x86-64";
625      else if (getToolChain().getArchName() == "i386")
626        CPUName = "i586";
627    } else {
628      if (getToolChain().getArchName() == "x86_64")
629        CPUName = "x86-64";
630      else if (getToolChain().getArchName() == "i386")
631        CPUName = "pentium4";
632    }
633  }
634
635  if (CPUName) {
636    CmdArgs.push_back("-target-cpu");
637    CmdArgs.push_back(CPUName);
638  }
639
640  for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
641         ie = Args.filtered_end(); it != ie; ++it) {
642    llvm::StringRef Name = it->getOption().getName();
643    it->claim();
644
645    // Skip over "-m".
646    assert(Name.startswith("-m") && "Invalid feature name.");
647    Name = Name.substr(2);
648
649    bool IsNegative = Name.startswith("no-");
650    if (IsNegative)
651      Name = Name.substr(3);
652
653    CmdArgs.push_back("-target-feature");
654    CmdArgs.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
655  }
656}
657
658static bool needsExceptions(const ArgList &Args,  types::ID InputType,
659                            const llvm::Triple &Triple) {
660  if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
661                               options::OPT_fno_exceptions)) {
662    if (A->getOption().matches(options::OPT_fexceptions))
663      return true;
664    else
665      return false;
666  }
667  switch (InputType) {
668  case types::TY_CXX: case types::TY_CXXHeader:
669  case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
670  case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
671  case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXXHeader:
672    return true;
673
674  case types::TY_ObjC: case types::TY_ObjCHeader:
675  case types::TY_PP_ObjC: case types::TY_PP_ObjCHeader:
676    if (Args.hasArg(options::OPT_fobjc_nonfragile_abi))
677      return true;
678    if (Triple.getOS() != llvm::Triple::Darwin)
679      return false;
680    return (Triple.getDarwinMajorNumber() >= 9 &&
681            Triple.getArch() == llvm::Triple::x86_64);
682
683  default:
684    return false;
685  }
686}
687
688/// getEffectiveClangTriple - Get the "effective" target triple, which is the
689/// triple for the target but with the OS version potentially modified for
690/// Darwin's -mmacosx-version-min.
691static std::string getEffectiveClangTriple(const Driver &D,
692                                           const ToolChain &TC,
693                                           const ArgList &Args) {
694  llvm::Triple Triple(getLLVMTriple(TC, Args));
695
696  // Handle -mmacosx-version-min and -miphoneos-version-min.
697  if (Triple.getOS() != llvm::Triple::Darwin) {
698    // Diagnose use of -mmacosx-version-min and -miphoneos-version-min on
699    // non-Darwin.
700    if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ,
701                                 options::OPT_miphoneos_version_min_EQ))
702      D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
703  } else {
704    const toolchains::Darwin &DarwinTC(
705      reinterpret_cast<const toolchains::Darwin&>(TC));
706
707    // If the target isn't initialized (e.g., an unknown Darwin platform, return
708    // the default triple).
709    if (!DarwinTC.isTargetInitialized())
710      return Triple.getTriple();
711
712    unsigned Version[3];
713    DarwinTC.getTargetVersion(Version);
714
715    // Mangle the target version into the OS triple component.  For historical
716    // reasons that make little sense, the version passed here is the "darwin"
717    // version, which drops the 10 and offsets by 4. See inverse code when
718    // setting the OS version preprocessor define.
719    if (!DarwinTC.isTargetIPhoneOS()) {
720      Version[0] = Version[1] + 4;
721      Version[1] = Version[2];
722      Version[2] = 0;
723    } else {
724      // Use the environment to communicate that we are targetting iPhoneOS.
725      Triple.setEnvironmentName("iphoneos");
726    }
727
728    llvm::SmallString<16> Str;
729    llvm::raw_svector_ostream(Str) << "darwin" << Version[0]
730                                   << "." << Version[1] << "." << Version[2];
731    Triple.setOSName(Str.str());
732  }
733
734  return Triple.getTriple();
735}
736
737void Clang::ConstructJob(Compilation &C, const JobAction &JA,
738                         Job &Dest,
739                         const InputInfo &Output,
740                         const InputInfoList &Inputs,
741                         const ArgList &Args,
742                         const char *LinkingOutput) const {
743  bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
744                                  options::OPT_fapple_kext);
745  const Driver &D = getToolChain().getDriver();
746  ArgStringList CmdArgs;
747
748  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
749
750  // Invoke ourselves in -cc1 mode.
751  //
752  // FIXME: Implement custom jobs for internal actions.
753  CmdArgs.push_back("-cc1");
754
755  // Add the "effective" target triple.
756  CmdArgs.push_back("-triple");
757  std::string TripleStr = getEffectiveClangTriple(D, getToolChain(), Args);
758  CmdArgs.push_back(Args.MakeArgString(TripleStr));
759
760  // Select the appropriate action.
761  if (isa<AnalyzeJobAction>(JA)) {
762    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
763    CmdArgs.push_back("-analyze");
764  } else if (isa<PreprocessJobAction>(JA)) {
765    if (Output.getType() == types::TY_Dependencies)
766      CmdArgs.push_back("-Eonly");
767    else
768      CmdArgs.push_back("-E");
769  } else if (isa<AssembleJobAction>(JA)) {
770    CmdArgs.push_back("-emit-obj");
771  } else if (isa<PrecompileJobAction>(JA)) {
772    // Use PCH if the user requested it, except for C++ (for now).
773    bool UsePCH = D.CCCUsePCH;
774    if (types::isCXX(Inputs[0].getType()))
775      UsePCH = false;
776
777    if (UsePCH)
778      CmdArgs.push_back("-emit-pch");
779    else
780      CmdArgs.push_back("-emit-pth");
781  } else {
782    assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
783
784    if (JA.getType() == types::TY_Nothing) {
785      CmdArgs.push_back("-fsyntax-only");
786    } else if (JA.getType() == types::TY_LLVMAsm) {
787      CmdArgs.push_back("-emit-llvm");
788    } else if (JA.getType() == types::TY_LLVMBC) {
789      CmdArgs.push_back("-emit-llvm-bc");
790    } else if (JA.getType() == types::TY_PP_Asm) {
791      CmdArgs.push_back("-S");
792    } else if (JA.getType() == types::TY_AST) {
793      CmdArgs.push_back("-emit-pch");
794    } else if (JA.getType() == types::TY_RewrittenObjC) {
795      CmdArgs.push_back("-rewrite-objc");
796    } else {
797      assert(JA.getType() == types::TY_PP_Asm &&
798             "Unexpected output type!");
799    }
800  }
801
802  // The make clang go fast button.
803  CmdArgs.push_back("-disable-free");
804
805  // Disable the verification pass in -asserts builds.
806#ifdef NDEBUG
807  CmdArgs.push_back("-disable-llvm-verifier");
808#endif
809
810  // Set the main file name, so that debug info works even with
811  // -save-temps.
812  CmdArgs.push_back("-main-file-name");
813  CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
814
815  // Some flags which affect the language (via preprocessor
816  // defines). See darwin::CC1::AddCPPArgs.
817  if (Args.hasArg(options::OPT_static))
818    CmdArgs.push_back("-static-define");
819
820  if (isa<AnalyzeJobAction>(JA)) {
821    // Enable region store model by default.
822    CmdArgs.push_back("-analyzer-store=region");
823
824    // Treat blocks as analysis entry points.
825    CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
826
827    // Add default argument set.
828    if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
829      CmdArgs.push_back("-analyzer-check-dead-stores");
830      // Do not enable the security-syntatic check since it
831      // it needs to be refined (known issues).
832      // CmdArgs.push_back("-analyzer-check-security-syntactic");
833      CmdArgs.push_back("-analyzer-check-objc-mem");
834      CmdArgs.push_back("-analyzer-eagerly-assume");
835      CmdArgs.push_back("-analyzer-check-objc-methodsigs");
836      // Do not enable the missing -dealloc check.
837      // '-analyzer-check-objc-missing-dealloc',
838      CmdArgs.push_back("-analyzer-check-objc-unused-ivars");
839    }
840
841    // Set the output format. The default is plist, for (lame) historical
842    // reasons.
843    CmdArgs.push_back("-analyzer-output");
844    if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
845      CmdArgs.push_back(A->getValue(Args));
846    else
847      CmdArgs.push_back("plist");
848
849    // Disable the presentation of standard compiler warnings when
850    // using --analyze.  We only want to show static analyzer diagnostics
851    // or frontend errors.
852    CmdArgs.push_back("-w");
853
854    // Add -Xanalyzer arguments when running as analyzer.
855    Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
856  }
857
858  CheckCodeGenerationOptions(D, Args);
859
860  // Perform argument translation for LLVM backend. This
861  // takes some care in reconciling with llvm-gcc. The
862  // issue is that llvm-gcc translates these options based on
863  // the values in cc1, whereas we are processing based on
864  // the driver arguments.
865
866  // This comes from the default translation the driver + cc1
867  // would do to enable flag_pic.
868  //
869  // FIXME: Centralize this code.
870  bool PICEnabled = (Args.hasArg(options::OPT_fPIC) ||
871                     Args.hasArg(options::OPT_fpic) ||
872                     Args.hasArg(options::OPT_fPIE) ||
873                     Args.hasArg(options::OPT_fpie));
874  bool PICDisabled = (Args.hasArg(options::OPT_mkernel) ||
875                      Args.hasArg(options::OPT_static));
876  const char *Model = getToolChain().GetForcedPicModel();
877  if (!Model) {
878    if (Args.hasArg(options::OPT_mdynamic_no_pic))
879      Model = "dynamic-no-pic";
880    else if (PICDisabled)
881      Model = "static";
882    else if (PICEnabled)
883      Model = "pic";
884    else
885      Model = getToolChain().GetDefaultRelocationModel();
886  }
887  if (llvm::StringRef(Model) != "pic") {
888    CmdArgs.push_back("-mrelocation-model");
889    CmdArgs.push_back(Model);
890  }
891
892  // Infer the __PIC__ value.
893  //
894  // FIXME:  This isn't quite right on Darwin, which always sets
895  // __PIC__=2.
896  if (strcmp(Model, "pic") == 0 || strcmp(Model, "dynamic-no-pic") == 0) {
897    CmdArgs.push_back("-pic-level");
898    CmdArgs.push_back(Args.hasArg(options::OPT_fPIC) ? "2" : "1");
899  }
900  if (!Args.hasFlag(options::OPT_fmerge_all_constants,
901                    options::OPT_fno_merge_all_constants))
902    CmdArgs.push_back("-no-merge-all-constants");
903
904  // LLVM Code Generator Options.
905
906  // FIXME: Set --enable-unsafe-fp-math.
907  if (Args.hasFlag(options::OPT_fno_omit_frame_pointer,
908                   options::OPT_fomit_frame_pointer))
909    CmdArgs.push_back("-mdisable-fp-elim");
910  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
911                    options::OPT_fno_zero_initialized_in_bss))
912    CmdArgs.push_back("-mno-zero-initialized-in-bss");
913  if (Args.hasArg(options::OPT_dA) || Args.hasArg(options::OPT_fverbose_asm))
914    CmdArgs.push_back("-masm-verbose");
915  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
916    CmdArgs.push_back("-mdebug-pass");
917    CmdArgs.push_back("Structure");
918  }
919  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
920    CmdArgs.push_back("-mdebug-pass");
921    CmdArgs.push_back("Arguments");
922  }
923
924  // Enable -mconstructor-aliases except on darwin, where we have to
925  // work around a linker bug;  see <rdar://problem/7651567>.
926  if (getToolChain().getTriple().getOS() != llvm::Triple::Darwin)
927    CmdArgs.push_back("-mconstructor-aliases");
928
929  // This is a coarse approximation of what llvm-gcc actually does, both
930  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
931  // complicated ways.
932  bool AsynchronousUnwindTables =
933    Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
934                 options::OPT_fno_asynchronous_unwind_tables,
935                 getToolChain().IsUnwindTablesDefault() &&
936                 !KernelOrKext);
937  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
938                   AsynchronousUnwindTables))
939    CmdArgs.push_back("-munwind-tables");
940
941  if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
942    CmdArgs.push_back("-mlimit-float-precision");
943    CmdArgs.push_back(A->getValue(Args));
944  }
945
946  // FIXME: Handle -mtune=.
947  (void) Args.hasArg(options::OPT_mtune_EQ);
948
949  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
950    CmdArgs.push_back("-mcode-model");
951    CmdArgs.push_back(A->getValue(Args));
952  }
953
954  // Add target specific cpu and features flags.
955  switch(getToolChain().getTriple().getArch()) {
956  default:
957    break;
958
959  case llvm::Triple::arm:
960  case llvm::Triple::thumb:
961    AddARMTargetArgs(Args, CmdArgs);
962    break;
963
964  case llvm::Triple::mips:
965  case llvm::Triple::mipsel:
966    AddMIPSTargetArgs(Args, CmdArgs);
967    break;
968
969  case llvm::Triple::x86:
970  case llvm::Triple::x86_64:
971    AddX86TargetArgs(Args, CmdArgs);
972    break;
973  }
974
975  // -fno-math-errno is default.
976  if (Args.hasFlag(options::OPT_fmath_errno,
977                   options::OPT_fno_math_errno,
978                   false))
979    CmdArgs.push_back("-fmath-errno");
980
981  Arg *Unsupported;
982  if ((Unsupported = Args.getLastArg(options::OPT_MG)) ||
983      (Unsupported = Args.getLastArg(options::OPT_iframework)) ||
984      (Unsupported = Args.getLastArg(options::OPT_fshort_enums)))
985    D.Diag(clang::diag::err_drv_clang_unsupported)
986      << Unsupported->getOption().getName();
987
988  Args.AddAllArgs(CmdArgs, options::OPT_v);
989  Args.AddLastArg(CmdArgs, options::OPT_P);
990  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
991
992  // Special case debug options to only pass -g to clang. This is
993  // wrong.
994  Args.ClaimAllArgs(options::OPT_g_Group);
995  Arg *Garg = Args.getLastArg(options::OPT_g_Group);
996  if (Garg && Garg != Args.getLastArg(options::OPT_g0))
997    CmdArgs.push_back("-g");
998
999  Args.AddLastArg(CmdArgs, options::OPT_nostdinc);
1000  Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
1001  Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
1002
1003  // Pass the path to compiler resource files.
1004  CmdArgs.push_back("-resource-dir");
1005  CmdArgs.push_back(D.ResourceDir.c_str());
1006
1007  // Add preprocessing options like -I, -D, etc. if we are using the
1008  // preprocessor.
1009  //
1010  // FIXME: Support -fpreprocessed
1011  types::ID InputType = Inputs[0].getType();
1012  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
1013    AddPreprocessingOptions(D, Args, CmdArgs, Output, Inputs);
1014
1015  // Manually translate -O to -O2 and -O4 to -O3; let clang reject
1016  // others.
1017  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1018    if (A->getOption().matches(options::OPT_O4))
1019      CmdArgs.push_back("-O3");
1020    else if (A->getValue(Args)[0] == '\0')
1021      CmdArgs.push_back("-O2");
1022    else
1023      A->render(Args, CmdArgs);
1024  }
1025
1026  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
1027  Args.AddLastArg(CmdArgs, options::OPT_pedantic);
1028  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
1029  Args.AddLastArg(CmdArgs, options::OPT_w);
1030
1031  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
1032  // (-ansi is equivalent to -std=c89).
1033  //
1034  // If a std is supplied, only add -trigraphs if it follows the
1035  // option.
1036  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
1037    if (Std->getOption().matches(options::OPT_ansi))
1038      if (types::isCXX(InputType))
1039        CmdArgs.push_back("-std=c++98");
1040      else
1041        CmdArgs.push_back("-std=c89");
1042    else
1043      Std->render(Args, CmdArgs);
1044
1045    if (Arg *A = Args.getLastArg(options::OPT_trigraphs))
1046      if (A->getIndex() > Std->getIndex())
1047        A->render(Args, CmdArgs);
1048  } else {
1049    // Honor -std-default.
1050    //
1051    // FIXME: Clang doesn't correctly handle -std= when the input language
1052    // doesn't match. For the time being just ignore this for C++ inputs;
1053    // eventually we want to do all the standard defaulting here instead of
1054    // splitting it between the driver and clang -cc1.
1055    if (!types::isCXX(InputType))
1056        Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
1057                                  "-std=", /*Joined=*/true);
1058    Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
1059  }
1060
1061  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_)) {
1062    CmdArgs.push_back("-ftemplate-depth");
1063    CmdArgs.push_back(A->getValue(Args));
1064  }
1065
1066  if (Args.hasArg(options::OPT__relocatable_pch))
1067    CmdArgs.push_back("-relocatable-pch");
1068
1069  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
1070    CmdArgs.push_back("-fconstant-string-class");
1071    CmdArgs.push_back(A->getValue(Args));
1072  }
1073
1074  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
1075    CmdArgs.push_back("-ftabstop");
1076    CmdArgs.push_back(A->getValue(Args));
1077  }
1078
1079  CmdArgs.push_back("-ferror-limit");
1080  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
1081    CmdArgs.push_back(A->getValue(Args));
1082  else
1083    CmdArgs.push_back("19");
1084
1085  CmdArgs.push_back("-ftemplate-backtrace-limit");
1086  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ))
1087    CmdArgs.push_back(A->getValue(Args));
1088  else
1089    CmdArgs.push_back("10");
1090
1091  // Pass -fmessage-length=.
1092  CmdArgs.push_back("-fmessage-length");
1093  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
1094    CmdArgs.push_back(A->getValue(Args));
1095  } else {
1096    // If -fmessage-length=N was not specified, determine whether this is a
1097    // terminal and, if so, implicitly define -fmessage-length appropriately.
1098    unsigned N = llvm::sys::Process::StandardErrColumns();
1099    CmdArgs.push_back(Args.MakeArgString(llvm::Twine(N)));
1100  }
1101
1102  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) {
1103    CmdArgs.push_back("-fvisibility");
1104    CmdArgs.push_back(A->getValue(Args));
1105  }
1106
1107  // -fhosted is default.
1108  if (KernelOrKext || Args.hasFlag(options::OPT_ffreestanding,
1109                                   options::OPT_fhosted,
1110                                   false))
1111    CmdArgs.push_back("-ffreestanding");
1112
1113  // Forward -f (flag) options which we can pass directly.
1114  Args.AddLastArg(CmdArgs, options::OPT_fcatch_undefined_behavior);
1115  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
1116  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
1117
1118  // -flax-vector-conversions is default.
1119  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
1120                    options::OPT_fno_lax_vector_conversions))
1121    CmdArgs.push_back("-fno-lax-vector-conversions");
1122
1123  // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
1124  // takes precedence.
1125  const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
1126  if (!GCArg)
1127    GCArg = Args.getLastArg(options::OPT_fobjc_gc);
1128  if (GCArg) {
1129    if (getToolChain().SupportsObjCGC()) {
1130      GCArg->render(Args, CmdArgs);
1131    } else {
1132      // FIXME: We should move this to a hard error.
1133      D.Diag(clang::diag::warn_drv_objc_gc_unsupported)
1134        << GCArg->getAsString(Args);
1135    }
1136  }
1137
1138  Args.AddLastArg(CmdArgs, options::OPT_fno_caret_diagnostics);
1139  Args.AddLastArg(CmdArgs, options::OPT_fno_show_column);
1140  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
1141  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
1142  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
1143  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
1144  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
1145
1146  Args.AddLastArg(CmdArgs, options::OPT_pthread);
1147
1148  // -stack-protector=0 is default.
1149  unsigned StackProtectorLevel = 0;
1150  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
1151                               options::OPT_fstack_protector_all,
1152                               options::OPT_fstack_protector)) {
1153    if (A->getOption().matches(options::OPT_fstack_protector))
1154      StackProtectorLevel = 1;
1155    else if (A->getOption().matches(options::OPT_fstack_protector_all))
1156      StackProtectorLevel = 2;
1157  } else
1158    StackProtectorLevel = getToolChain().GetDefaultStackProtectorLevel();
1159  if (StackProtectorLevel) {
1160    CmdArgs.push_back("-stack-protector");
1161    CmdArgs.push_back(Args.MakeArgString(llvm::Twine(StackProtectorLevel)));
1162  }
1163
1164  // Forward -f options with positive and negative forms; we translate
1165  // these by hand.
1166
1167  // -fbuiltin is default.
1168  if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
1169    CmdArgs.push_back("-fno-builtin");
1170
1171  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1172                    options::OPT_fno_assume_sane_operator_new))
1173    CmdArgs.push_back("-fno-assume-sane-operator-new");
1174
1175  // -fblocks=0 is default.
1176  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
1177                   getToolChain().IsBlocksDefault())) {
1178    CmdArgs.push_back("-fblocks");
1179  }
1180
1181  // -faccess-control is default.
1182  if (Args.hasFlag(options::OPT_fno_access_control,
1183                   options::OPT_faccess_control,
1184                   false))
1185    CmdArgs.push_back("-fno-access-control");
1186
1187  // -fexceptions=0 is default.
1188  if (needsExceptions(Args, InputType, getToolChain().getTriple()))
1189    CmdArgs.push_back("-fexceptions");
1190
1191  if (getToolChain().UseSjLjExceptions())
1192    CmdArgs.push_back("-fsjlj-exceptions");
1193
1194  // -frtti is default.
1195  if (KernelOrKext ||
1196      !Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti))
1197    CmdArgs.push_back("-fno-rtti");
1198
1199  // -fsigned-char is default.
1200  if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
1201                    isSignedCharDefault(getToolChain().getTriple())))
1202    CmdArgs.push_back("-fno-signed-char");
1203
1204  // -fthreadsafe-static is default.
1205  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
1206                    options::OPT_fno_threadsafe_statics))
1207    CmdArgs.push_back("-fno-threadsafe-statics");
1208
1209  // -fuse-cxa-atexit is default.
1210  if (KernelOrKext || !Args.hasFlag(options::OPT_fuse_cxa_atexit,
1211                                    options::OPT_fno_use_cxa_atexit))
1212    CmdArgs.push_back("-fno-use-cxa-atexit");
1213
1214  // -fms-extensions=0 is default.
1215  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1216                   getToolChain().getTriple().getOS() == llvm::Triple::Win32))
1217    CmdArgs.push_back("-fms-extensions");
1218
1219  // -fgnu-keywords default varies depending on language; only pass if
1220  // specified.
1221  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
1222                               options::OPT_fno_gnu_keywords))
1223    A->render(Args, CmdArgs);
1224
1225  // -fnext-runtime is default.
1226  if (!Args.hasFlag(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
1227                    getToolChain().getTriple().getOS() == llvm::Triple::Darwin))
1228    CmdArgs.push_back("-fgnu-runtime");
1229
1230  // -fobjc-nonfragile-abi=0 is default.
1231  if (types::isObjC(InputType)) {
1232    unsigned Version = 1;
1233    if (Args.hasArg(options::OPT_fobjc_nonfragile_abi) ||
1234        getToolChain().IsObjCNonFragileABIDefault())
1235      Version = 2;
1236    if (Arg *A = Args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
1237      if (llvm::StringRef(A->getValue(Args)) == "1")
1238        Version = 1;
1239      else if (llvm::StringRef(A->getValue(Args)) == "2")
1240        Version = 2;
1241      else
1242        D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
1243    }
1244
1245    if (Version == 2) {
1246      CmdArgs.push_back("-fobjc-nonfragile-abi");
1247
1248      // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
1249      // legacy is the default.
1250      if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
1251                        options::OPT_fno_objc_legacy_dispatch,
1252                        getToolChain().IsObjCLegacyDispatchDefault())) {
1253        if (getToolChain().UseObjCMixedDispatch())
1254          CmdArgs.push_back("-fobjc-dispatch-method=mixed");
1255        else
1256          CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
1257      }
1258    }
1259  }
1260
1261  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
1262                    options::OPT_fno_assume_sane_operator_new))
1263    CmdArgs.push_back("-fno-assume-sane-operator-new");
1264
1265  // -fconstant-cfstrings is default, and may be subject to argument translation
1266  // on Darwin.
1267  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
1268                    options::OPT_fno_constant_cfstrings) ||
1269      !Args.hasFlag(options::OPT_mconstant_cfstrings,
1270                    options::OPT_mno_constant_cfstrings))
1271    CmdArgs.push_back("-fno-constant-cfstrings");
1272
1273  // -fshort-wchar default varies depending on platform; only
1274  // pass if specified.
1275  if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
1276    A->render(Args, CmdArgs);
1277
1278  // -fno-pascal-strings is default, only pass non-default. If the tool chain
1279  // happened to translate to -mpascal-strings, we want to back translate here.
1280  //
1281  // FIXME: This is gross; that translation should be pulled from the
1282  // tool chain.
1283  if (Args.hasFlag(options::OPT_fpascal_strings,
1284                   options::OPT_fno_pascal_strings,
1285                   false) ||
1286      Args.hasFlag(options::OPT_mpascal_strings,
1287                   options::OPT_mno_pascal_strings,
1288                   false))
1289    CmdArgs.push_back("-fpascal-strings");
1290
1291  // -fcommon is default, only pass non-default.
1292  if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
1293    CmdArgs.push_back("-fno-common");
1294
1295  // -fsigned-bitfields is default, and clang doesn't yet support
1296  // --funsigned-bitfields.
1297  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
1298                    options::OPT_funsigned_bitfields))
1299    D.Diag(clang::diag::warn_drv_clang_unsupported)
1300      << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
1301
1302  // -fdiagnostics-fixit-info is default, only pass non-default.
1303  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
1304                    options::OPT_fno_diagnostics_fixit_info))
1305    CmdArgs.push_back("-fno-diagnostics-fixit-info");
1306
1307  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_binary);
1308
1309  // Enable -fdiagnostics-show-option by default.
1310  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
1311                   options::OPT_fno_diagnostics_show_option))
1312    CmdArgs.push_back("-fdiagnostics-show-option");
1313
1314  // Color diagnostics are the default, unless the terminal doesn't support
1315  // them.
1316  if (Args.hasFlag(options::OPT_fcolor_diagnostics,
1317                   options::OPT_fno_color_diagnostics) &&
1318      llvm::sys::Process::StandardErrHasColors())
1319    CmdArgs.push_back("-fcolor-diagnostics");
1320
1321  if (!Args.hasFlag(options::OPT_fshow_source_location,
1322                    options::OPT_fno_show_source_location))
1323    CmdArgs.push_back("-fno-show-source-location");
1324
1325  // -fdollars-in-identifiers default varies depending on platform and
1326  // language; only pass if specified.
1327  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
1328                               options::OPT_fno_dollars_in_identifiers)) {
1329    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
1330      CmdArgs.push_back("-fdollars-in-identifiers");
1331    else
1332      CmdArgs.push_back("-fno-dollars-in-identifiers");
1333  }
1334
1335  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
1336  // practical purposes.
1337  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
1338                               options::OPT_fno_unit_at_a_time)) {
1339    if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
1340      D.Diag(clang::diag::warn_drv_clang_unsupported) << A->getAsString(Args);
1341  }
1342
1343  // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
1344  //
1345  // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
1346#if 0
1347  if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin &&
1348      (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
1349       getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
1350    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
1351      CmdArgs.push_back("-fno-builtin-strcat");
1352    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
1353      CmdArgs.push_back("-fno-builtin-strcpy");
1354  }
1355#endif
1356
1357  if (Arg *A = Args.getLastArg(options::OPT_traditional,
1358                               options::OPT_traditional_cpp))
1359    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
1360
1361  Args.AddLastArg(CmdArgs, options::OPT_dM);
1362  Args.AddLastArg(CmdArgs, options::OPT_dD);
1363
1364  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
1365  // parser.
1366  Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
1367  for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
1368         ie = Args.filtered_end(); it != ie; ++it) {
1369    it->claim();
1370
1371    // We translate this by hand to the -cc1 argument, since nightly test uses
1372    // it and developers have been trained to spell it with -mllvm.
1373    if (llvm::StringRef(it->getValue(Args, 0)) == "-disable-llvm-optzns")
1374      CmdArgs.push_back("-disable-llvm-optzns");
1375    else
1376      it->render(Args, CmdArgs);
1377  }
1378
1379  if (Output.getType() == types::TY_Dependencies) {
1380    // Handled with other dependency code.
1381  } else if (Output.isPipe()) {
1382    CmdArgs.push_back("-o");
1383    CmdArgs.push_back("-");
1384  } else if (Output.isFilename()) {
1385    CmdArgs.push_back("-o");
1386    CmdArgs.push_back(Output.getFilename());
1387  } else {
1388    assert(Output.isNothing() && "Invalid output.");
1389  }
1390
1391  for (InputInfoList::const_iterator
1392         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
1393    const InputInfo &II = *it;
1394    CmdArgs.push_back("-x");
1395    CmdArgs.push_back(types::getTypeName(II.getType()));
1396    if (II.isPipe())
1397      CmdArgs.push_back("-");
1398    else if (II.isFilename())
1399      CmdArgs.push_back(II.getFilename());
1400    else
1401      II.getInputArg().renderAsInput(Args, CmdArgs);
1402  }
1403
1404  Args.AddAllArgs(CmdArgs, options::OPT_undef);
1405
1406  const char *Exec =
1407    Args.MakeArgString(getToolChain().GetProgramPath(C, "clang"));
1408
1409  // Optionally embed the -cc1 level arguments into the debug info, for build
1410  // analysis.
1411  if (getToolChain().UseDwarfDebugFlags()) {
1412    llvm::SmallString<256> Flags;
1413    Flags += Exec;
1414    for (unsigned i = 0, e = CmdArgs.size(); i != e; ++i) {
1415      Flags += " ";
1416      Flags += CmdArgs[i];
1417    }
1418    CmdArgs.push_back("-dwarf-debug-flags");
1419    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
1420  }
1421
1422  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
1423
1424  // Explicitly warn that these options are unsupported, even though
1425  // we are allowing compilation to continue.
1426  for (arg_iterator it = Args.filtered_begin(options::OPT_pg),
1427         ie = Args.filtered_end(); it != ie; ++it) {
1428    it->claim();
1429    D.Diag(clang::diag::warn_drv_clang_unsupported) << it->getAsString(Args);
1430  }
1431
1432  // Claim some arguments which clang supports automatically.
1433
1434  // -fpch-preprocess is used with gcc to add a special marker in the output to
1435  // include the PCH file. Clang's PTH solution is completely transparent, so we
1436  // do not need to deal with it at all.
1437  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
1438
1439  // Claim some arguments which clang doesn't support, but we don't
1440  // care to warn the user about.
1441  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
1442  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
1443}
1444
1445void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
1446                               Job &Dest,
1447                               const InputInfo &Output,
1448                               const InputInfoList &Inputs,
1449                               const ArgList &Args,
1450                               const char *LinkingOutput) const {
1451  const Driver &D = getToolChain().getDriver();
1452  ArgStringList CmdArgs;
1453
1454  for (ArgList::const_iterator
1455         it = Args.begin(), ie = Args.end(); it != ie; ++it) {
1456    Arg *A = *it;
1457    if (A->getOption().hasForwardToGCC()) {
1458      // It is unfortunate that we have to claim here, as this means
1459      // we will basically never report anything interesting for
1460      // platforms using a generic gcc, even if we are just using gcc
1461      // to get to the assembler.
1462      A->claim();
1463      A->render(Args, CmdArgs);
1464    }
1465  }
1466
1467  RenderExtraToolArgs(JA, CmdArgs);
1468
1469  // If using a driver driver, force the arch.
1470  const std::string &Arch = getToolChain().getArchName();
1471  if (getToolChain().getTriple().getOS() == llvm::Triple::Darwin) {
1472    CmdArgs.push_back("-arch");
1473
1474    // FIXME: Remove these special cases.
1475    if (Arch == "powerpc")
1476      CmdArgs.push_back("ppc");
1477    else if (Arch == "powerpc64")
1478      CmdArgs.push_back("ppc64");
1479    else
1480      CmdArgs.push_back(Args.MakeArgString(Arch));
1481  }
1482
1483  // Try to force gcc to match the tool chain we want, if we recognize
1484  // the arch.
1485  //
1486  // FIXME: The triple class should directly provide the information we want
1487  // here.
1488  if (Arch == "i386" || Arch == "powerpc")
1489    CmdArgs.push_back("-m32");
1490  else if (Arch == "x86_64" || Arch == "powerpc64")
1491    CmdArgs.push_back("-m64");
1492
1493  if (Output.isPipe()) {
1494    CmdArgs.push_back("-o");
1495    CmdArgs.push_back("-");
1496  } else if (Output.isFilename()) {
1497    CmdArgs.push_back("-o");
1498    CmdArgs.push_back(Output.getFilename());
1499  } else {
1500    assert(Output.isNothing() && "Unexpected output");
1501    CmdArgs.push_back("-fsyntax-only");
1502  }
1503
1504
1505  // Only pass -x if gcc will understand it; otherwise hope gcc
1506  // understands the suffix correctly. The main use case this would go
1507  // wrong in is for linker inputs if they happened to have an odd
1508  // suffix; really the only way to get this to happen is a command
1509  // like '-x foobar a.c' which will treat a.c like a linker input.
1510  //
1511  // FIXME: For the linker case specifically, can we safely convert
1512  // inputs into '-Wl,' options?
1513  for (InputInfoList::const_iterator
1514         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
1515    const InputInfo &II = *it;
1516
1517    // Don't try to pass LLVM or AST inputs to a generic gcc.
1518    if (II.getType() == types::TY_LLVMBC)
1519      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
1520        << getToolChain().getTripleString();
1521    else if (II.getType() == types::TY_AST)
1522      D.Diag(clang::diag::err_drv_no_ast_support)
1523        << getToolChain().getTripleString();
1524
1525    if (types::canTypeBeUserSpecified(II.getType())) {
1526      CmdArgs.push_back("-x");
1527      CmdArgs.push_back(types::getTypeName(II.getType()));
1528    }
1529
1530    if (II.isPipe())
1531      CmdArgs.push_back("-");
1532    else if (II.isFilename())
1533      CmdArgs.push_back(II.getFilename());
1534    else
1535      // Don't render as input, we need gcc to do the translations.
1536      II.getInputArg().render(Args, CmdArgs);
1537  }
1538
1539  const char *GCCName = getToolChain().getDriver().CCCGenericGCCName.c_str();
1540  const char *Exec =
1541    Args.MakeArgString(getToolChain().GetProgramPath(C, GCCName));
1542  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
1543}
1544
1545void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
1546                                          ArgStringList &CmdArgs) const {
1547  CmdArgs.push_back("-E");
1548}
1549
1550void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
1551                                          ArgStringList &CmdArgs) const {
1552  // The type is good enough.
1553}
1554
1555void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
1556                                       ArgStringList &CmdArgs) const {
1557  const Driver &D = getToolChain().getDriver();
1558
1559  // If -flto, etc. are present then make sure not to force assembly output.
1560  if (JA.getType() == types::TY_LLVMBC)
1561    CmdArgs.push_back("-c");
1562  else {
1563    if (JA.getType() != types::TY_PP_Asm)
1564      D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
1565        << getTypeName(JA.getType());
1566
1567    CmdArgs.push_back("-S");
1568  }
1569}
1570
1571void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
1572                                        ArgStringList &CmdArgs) const {
1573  CmdArgs.push_back("-c");
1574}
1575
1576void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
1577                                    ArgStringList &CmdArgs) const {
1578  // The types are (hopefully) good enough.
1579}
1580
1581const char *darwin::CC1::getCC1Name(types::ID Type) const {
1582  switch (Type) {
1583  default:
1584    assert(0 && "Unexpected type for Darwin CC1 tool.");
1585  case types::TY_Asm:
1586  case types::TY_C: case types::TY_CHeader:
1587  case types::TY_PP_C: case types::TY_PP_CHeader:
1588    return "cc1";
1589  case types::TY_ObjC: case types::TY_ObjCHeader:
1590  case types::TY_PP_ObjC: case types::TY_PP_ObjCHeader:
1591    return "cc1obj";
1592  case types::TY_CXX: case types::TY_CXXHeader:
1593  case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
1594    return "cc1plus";
1595  case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
1596  case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXXHeader:
1597    return "cc1objplus";
1598  }
1599}
1600
1601const char *darwin::CC1::getBaseInputName(const ArgList &Args,
1602                                          const InputInfoList &Inputs) {
1603  llvm::sys::Path P(Inputs[0].getBaseInput());
1604  return Args.MakeArgString(P.getLast());
1605}
1606
1607const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
1608                                          const InputInfoList &Inputs) {
1609  const char *Str = getBaseInputName(Args, Inputs);
1610
1611  if (const char *End = strchr(Str, '.'))
1612    return Args.MakeArgString(std::string(Str, End));
1613
1614  return Str;
1615}
1616
1617const char *
1618darwin::CC1::getDependencyFileName(const ArgList &Args,
1619                                   const InputInfoList &Inputs) {
1620  // FIXME: Think about this more.
1621  std::string Res;
1622
1623  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
1624    std::string Str(OutputOpt->getValue(Args));
1625
1626    Res = Str.substr(0, Str.rfind('.'));
1627  } else
1628    Res = darwin::CC1::getBaseInputStem(Args, Inputs);
1629
1630  return Args.MakeArgString(Res + ".d");
1631}
1632
1633void darwin::CC1::AddCC1Args(const ArgList &Args,
1634                             ArgStringList &CmdArgs) const {
1635  const Driver &D = getToolChain().getDriver();
1636
1637  CheckCodeGenerationOptions(D, Args);
1638
1639  // Derived from cc1 spec.
1640  if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) &&
1641      !Args.hasArg(options::OPT_mdynamic_no_pic))
1642    CmdArgs.push_back("-fPIC");
1643
1644  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
1645      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
1646    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
1647      CmdArgs.push_back("-fno-builtin-strcat");
1648    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
1649      CmdArgs.push_back("-fno-builtin-strcpy");
1650  }
1651
1652  // gcc has some code here to deal with when no -mmacosx-version-min
1653  // and no -miphoneos-version-min is present, but this never happens
1654  // due to tool chain specific argument translation.
1655
1656  if (Args.hasArg(options::OPT_g_Flag) &&
1657      !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
1658    CmdArgs.push_back("-feliminate-unused-debug-symbols");
1659}
1660
1661void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
1662                                    const InputInfoList &Inputs,
1663                                    const ArgStringList &OutputArgs) const {
1664  const Driver &D = getToolChain().getDriver();
1665
1666  // Derived from cc1_options spec.
1667  if (Args.hasArg(options::OPT_fast) ||
1668      Args.hasArg(options::OPT_fastf) ||
1669      Args.hasArg(options::OPT_fastcp))
1670    CmdArgs.push_back("-O3");
1671
1672  if (Arg *A = Args.getLastArg(options::OPT_pg))
1673    if (Args.hasArg(options::OPT_fomit_frame_pointer))
1674      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
1675        << A->getAsString(Args) << "-fomit-frame-pointer";
1676
1677  AddCC1Args(Args, CmdArgs);
1678
1679  if (!Args.hasArg(options::OPT_Q))
1680    CmdArgs.push_back("-quiet");
1681
1682  CmdArgs.push_back("-dumpbase");
1683  CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
1684
1685  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
1686
1687  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
1688  Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
1689
1690  // FIXME: The goal is to use the user provided -o if that is our
1691  // final output, otherwise to drive from the original input
1692  // name. Find a clean way to go about this.
1693  if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
1694      Args.hasArg(options::OPT_o)) {
1695    Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1696    CmdArgs.push_back("-auxbase-strip");
1697    CmdArgs.push_back(OutputOpt->getValue(Args));
1698  } else {
1699    CmdArgs.push_back("-auxbase");
1700    CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
1701  }
1702
1703  Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
1704
1705  Args.AddAllArgs(CmdArgs, options::OPT_O);
1706  // FIXME: -Wall is getting some special treatment. Investigate.
1707  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
1708  Args.AddLastArg(CmdArgs, options::OPT_w);
1709  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
1710                  options::OPT_trigraphs);
1711  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
1712    // Honor -std-default.
1713    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
1714                              "-std=", /*Joined=*/true);
1715  }
1716
1717  if (Args.hasArg(options::OPT_v))
1718    CmdArgs.push_back("-version");
1719  if (Args.hasArg(options::OPT_pg))
1720    CmdArgs.push_back("-p");
1721  Args.AddLastArg(CmdArgs, options::OPT_p);
1722
1723  // The driver treats -fsyntax-only specially.
1724  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
1725      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
1726    // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
1727    // used to inhibit the default -fno-builtin-str{cat,cpy}.
1728    //
1729    // FIXME: Should we grow a better way to deal with "removing" args?
1730    for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
1731                                               options::OPT_fsyntax_only),
1732           ie = Args.filtered_end(); it != ie; ++it) {
1733      if (!it->getOption().matches(options::OPT_fbuiltin_strcat) &&
1734          !it->getOption().matches(options::OPT_fbuiltin_strcpy)) {
1735        it->claim();
1736        it->render(Args, CmdArgs);
1737      }
1738    }
1739  } else
1740    Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
1741
1742  Args.AddAllArgs(CmdArgs, options::OPT_undef);
1743  if (Args.hasArg(options::OPT_Qn))
1744    CmdArgs.push_back("-fno-ident");
1745
1746  // FIXME: This isn't correct.
1747  //Args.AddLastArg(CmdArgs, options::OPT__help)
1748  //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
1749
1750  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
1751
1752  // FIXME: Still don't get what is happening here. Investigate.
1753  Args.AddAllArgs(CmdArgs, options::OPT__param);
1754
1755  if (Args.hasArg(options::OPT_fmudflap) ||
1756      Args.hasArg(options::OPT_fmudflapth)) {
1757    CmdArgs.push_back("-fno-builtin");
1758    CmdArgs.push_back("-fno-merge-constants");
1759  }
1760
1761  if (Args.hasArg(options::OPT_coverage)) {
1762    CmdArgs.push_back("-fprofile-arcs");
1763    CmdArgs.push_back("-ftest-coverage");
1764  }
1765
1766  if (types::isCXX(Inputs[0].getType()))
1767    CmdArgs.push_back("-D__private_extern__=extern");
1768}
1769
1770void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
1771                                    const InputInfoList &Inputs,
1772                                    const ArgStringList &OutputArgs) const {
1773  // Derived from cpp_options
1774  AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
1775
1776  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
1777
1778  AddCC1Args(Args, CmdArgs);
1779
1780  // NOTE: The code below has some commonality with cpp_options, but
1781  // in classic gcc style ends up sending things in different
1782  // orders. This may be a good merge candidate once we drop pedantic
1783  // compatibility.
1784
1785  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
1786  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
1787                  options::OPT_trigraphs);
1788  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
1789    // Honor -std-default.
1790    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
1791                              "-std=", /*Joined=*/true);
1792  }
1793  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
1794  Args.AddLastArg(CmdArgs, options::OPT_w);
1795
1796  // The driver treats -fsyntax-only specially.
1797  Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
1798
1799  if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
1800      !Args.hasArg(options::OPT_fno_working_directory))
1801    CmdArgs.push_back("-fworking-directory");
1802
1803  Args.AddAllArgs(CmdArgs, options::OPT_O);
1804  Args.AddAllArgs(CmdArgs, options::OPT_undef);
1805  if (Args.hasArg(options::OPT_save_temps))
1806    CmdArgs.push_back("-fpch-preprocess");
1807}
1808
1809void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
1810                                          ArgStringList &CmdArgs,
1811                                          const InputInfoList &Inputs) const {
1812  const Driver &D = getToolChain().getDriver();
1813
1814  CheckPreprocessingOptions(D, Args);
1815
1816  // Derived from cpp_unique_options.
1817  // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
1818  Args.AddLastArg(CmdArgs, options::OPT_C);
1819  Args.AddLastArg(CmdArgs, options::OPT_CC);
1820  if (!Args.hasArg(options::OPT_Q))
1821    CmdArgs.push_back("-quiet");
1822  Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
1823  Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
1824  Args.AddLastArg(CmdArgs, options::OPT_v);
1825  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
1826  Args.AddLastArg(CmdArgs, options::OPT_P);
1827
1828  // FIXME: Handle %I properly.
1829  if (getToolChain().getArchName() == "x86_64") {
1830    CmdArgs.push_back("-imultilib");
1831    CmdArgs.push_back("x86_64");
1832  }
1833
1834  if (Args.hasArg(options::OPT_MD)) {
1835    CmdArgs.push_back("-MD");
1836    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
1837  }
1838
1839  if (Args.hasArg(options::OPT_MMD)) {
1840    CmdArgs.push_back("-MMD");
1841    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
1842  }
1843
1844  Args.AddLastArg(CmdArgs, options::OPT_M);
1845  Args.AddLastArg(CmdArgs, options::OPT_MM);
1846  Args.AddAllArgs(CmdArgs, options::OPT_MF);
1847  Args.AddLastArg(CmdArgs, options::OPT_MG);
1848  Args.AddLastArg(CmdArgs, options::OPT_MP);
1849  Args.AddAllArgs(CmdArgs, options::OPT_MQ);
1850  Args.AddAllArgs(CmdArgs, options::OPT_MT);
1851  if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
1852      (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
1853    if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
1854      CmdArgs.push_back("-MQ");
1855      CmdArgs.push_back(OutputOpt->getValue(Args));
1856    }
1857  }
1858
1859  Args.AddLastArg(CmdArgs, options::OPT_remap);
1860  if (Args.hasArg(options::OPT_g3))
1861    CmdArgs.push_back("-dD");
1862  Args.AddLastArg(CmdArgs, options::OPT_H);
1863
1864  AddCPPArgs(Args, CmdArgs);
1865
1866  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
1867  Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
1868
1869  for (InputInfoList::const_iterator
1870         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
1871    const InputInfo &II = *it;
1872
1873    if (II.isPipe())
1874      CmdArgs.push_back("-");
1875    else
1876      CmdArgs.push_back(II.getFilename());
1877  }
1878
1879  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1880                       options::OPT_Xpreprocessor);
1881
1882  if (Args.hasArg(options::OPT_fmudflap)) {
1883    CmdArgs.push_back("-D_MUDFLAP");
1884    CmdArgs.push_back("-include");
1885    CmdArgs.push_back("mf-runtime.h");
1886  }
1887
1888  if (Args.hasArg(options::OPT_fmudflapth)) {
1889    CmdArgs.push_back("-D_MUDFLAP");
1890    CmdArgs.push_back("-D_MUDFLAPTH");
1891    CmdArgs.push_back("-include");
1892    CmdArgs.push_back("mf-runtime.h");
1893  }
1894}
1895
1896void darwin::CC1::AddCPPArgs(const ArgList &Args,
1897                             ArgStringList &CmdArgs) const {
1898  // Derived from cpp spec.
1899
1900  if (Args.hasArg(options::OPT_static)) {
1901    // The gcc spec is broken here, it refers to dynamic but
1902    // that has been translated. Start by being bug compatible.
1903
1904    // if (!Args.hasArg(arglist.parser.dynamicOption))
1905    CmdArgs.push_back("-D__STATIC__");
1906  } else
1907    CmdArgs.push_back("-D__DYNAMIC__");
1908
1909  if (Args.hasArg(options::OPT_pthread))
1910    CmdArgs.push_back("-D_REENTRANT");
1911}
1912
1913void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
1914                                      Job &Dest, const InputInfo &Output,
1915                                      const InputInfoList &Inputs,
1916                                      const ArgList &Args,
1917                                      const char *LinkingOutput) const {
1918  ArgStringList CmdArgs;
1919
1920  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
1921
1922  CmdArgs.push_back("-E");
1923
1924  if (Args.hasArg(options::OPT_traditional) ||
1925      Args.hasArg(options::OPT_traditional_cpp))
1926    CmdArgs.push_back("-traditional-cpp");
1927
1928  ArgStringList OutputArgs;
1929  if (Output.isFilename()) {
1930    OutputArgs.push_back("-o");
1931    OutputArgs.push_back(Output.getFilename());
1932  } else {
1933    assert(Output.isPipe() && "Unexpected CC1 output.");
1934  }
1935
1936  if (Args.hasArg(options::OPT_E)) {
1937    AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
1938  } else {
1939    AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
1940    CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
1941  }
1942
1943  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
1944
1945  const char *CC1Name = getCC1Name(Inputs[0].getType());
1946  const char *Exec =
1947    Args.MakeArgString(getToolChain().GetProgramPath(C, CC1Name));
1948  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
1949}
1950
1951void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
1952                                   Job &Dest, const InputInfo &Output,
1953                                   const InputInfoList &Inputs,
1954                                   const ArgList &Args,
1955                                   const char *LinkingOutput) const {
1956  const Driver &D = getToolChain().getDriver();
1957  ArgStringList CmdArgs;
1958
1959  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
1960
1961  types::ID InputType = Inputs[0].getType();
1962  const Arg *A;
1963  if ((A = Args.getLastArg(options::OPT_traditional)))
1964    D.Diag(clang::diag::err_drv_argument_only_allowed_with)
1965      << A->getAsString(Args) << "-E";
1966
1967  if (Output.getType() == types::TY_LLVMAsm)
1968    CmdArgs.push_back("-emit-llvm");
1969  else if (Output.getType() == types::TY_LLVMBC)
1970    CmdArgs.push_back("-emit-llvm-bc");
1971  else if (Output.getType() == types::TY_AST)
1972    D.Diag(clang::diag::err_drv_no_ast_support)
1973      << getToolChain().getTripleString();
1974  else if (JA.getType() != types::TY_PP_Asm &&
1975           JA.getType() != types::TY_PCH)
1976    D.Diag(clang::diag::err_drv_invalid_gcc_output_type)
1977      << getTypeName(JA.getType());
1978
1979  ArgStringList OutputArgs;
1980  if (Output.getType() != types::TY_PCH) {
1981    OutputArgs.push_back("-o");
1982    if (Output.isPipe())
1983      OutputArgs.push_back("-");
1984    else if (Output.isNothing())
1985      OutputArgs.push_back("/dev/null");
1986    else
1987      OutputArgs.push_back(Output.getFilename());
1988  }
1989
1990  // There is no need for this level of compatibility, but it makes
1991  // diffing easier.
1992  bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
1993                          Args.hasArg(options::OPT_S));
1994
1995  if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
1996    AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
1997    if (OutputArgsEarly) {
1998      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
1999    } else {
2000      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2001      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2002    }
2003  } else {
2004    CmdArgs.push_back("-fpreprocessed");
2005
2006    for (InputInfoList::const_iterator
2007           it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2008      const InputInfo &II = *it;
2009
2010      // Reject AST inputs.
2011      if (II.getType() == types::TY_AST) {
2012        D.Diag(clang::diag::err_drv_no_ast_support)
2013          << getToolChain().getTripleString();
2014        return;
2015      }
2016
2017      if (II.isPipe())
2018        CmdArgs.push_back("-");
2019      else
2020        CmdArgs.push_back(II.getFilename());
2021    }
2022
2023    if (OutputArgsEarly) {
2024      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
2025    } else {
2026      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
2027      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
2028    }
2029  }
2030
2031  if (Output.getType() == types::TY_PCH) {
2032    assert(Output.isFilename() && "Invalid PCH output.");
2033
2034    CmdArgs.push_back("-o");
2035    // NOTE: gcc uses a temp .s file for this, but there doesn't seem
2036    // to be a good reason.
2037    CmdArgs.push_back("/dev/null");
2038
2039    CmdArgs.push_back("--output-pch=");
2040    CmdArgs.push_back(Output.getFilename());
2041  }
2042
2043  const char *CC1Name = getCC1Name(Inputs[0].getType());
2044  const char *Exec =
2045    Args.MakeArgString(getToolChain().GetProgramPath(C, CC1Name));
2046  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2047}
2048
2049void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2050                                    Job &Dest, const InputInfo &Output,
2051                                    const InputInfoList &Inputs,
2052                                    const ArgList &Args,
2053                                    const char *LinkingOutput) const {
2054  ArgStringList CmdArgs;
2055
2056  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
2057  const InputInfo &Input = Inputs[0];
2058
2059  // Bit of a hack, this is only used for original inputs.
2060  //
2061  // FIXME: This is broken for preprocessed .s inputs.
2062  if (Input.isFilename() &&
2063      strcmp(Input.getFilename(), Input.getBaseInput()) == 0) {
2064    if (Args.hasArg(options::OPT_gstabs))
2065      CmdArgs.push_back("--gstabs");
2066    else if (Args.hasArg(options::OPT_g_Group))
2067      CmdArgs.push_back("--gdwarf2");
2068  }
2069
2070  // Derived from asm spec.
2071  AddDarwinArch(Args, CmdArgs);
2072
2073  if (!getDarwinToolChain().isTargetIPhoneOS() ||
2074      Args.hasArg(options::OPT_force__cpusubtype__ALL))
2075    CmdArgs.push_back("-force_cpusubtype_ALL");
2076
2077  if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
2078      (Args.hasArg(options::OPT_mkernel) ||
2079       Args.hasArg(options::OPT_static) ||
2080       Args.hasArg(options::OPT_fapple_kext)))
2081    CmdArgs.push_back("-static");
2082
2083  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2084                       options::OPT_Xassembler);
2085
2086  assert(Output.isFilename() && "Unexpected lipo output.");
2087  CmdArgs.push_back("-o");
2088  CmdArgs.push_back(Output.getFilename());
2089
2090  if (Input.isPipe()) {
2091    CmdArgs.push_back("-");
2092  } else {
2093    assert(Input.isFilename() && "Invalid input.");
2094    CmdArgs.push_back(Input.getFilename());
2095  }
2096
2097  // asm_final spec is empty.
2098
2099  const char *Exec =
2100    Args.MakeArgString(getToolChain().GetProgramPath(C, "as"));
2101  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2102}
2103
2104/// Helper routine for seeing if we should use dsymutil; this is a
2105/// gcc compatible hack, we should remove it and use the input
2106/// type information.
2107static bool isSourceSuffix(const char *Str) {
2108  // match: 'C', 'CPP', 'c', 'cc', 'cp', 'c++', 'cpp', 'cxx', 'm',
2109  // 'mm'.
2110  return llvm::StringSwitch<bool>(Str)
2111           .Case("C", true)
2112           .Case("c", true)
2113           .Case("m", true)
2114           .Case("cc", true)
2115           .Case("cp", true)
2116           .Case("mm", true)
2117           .Case("CPP", true)
2118           .Case("c++", true)
2119           .Case("cpp", true)
2120           .Case("cxx", true)
2121           .Default(false);
2122}
2123
2124void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
2125                                       ArgStringList &CmdArgs) const {
2126  llvm::StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
2127
2128  // Derived from darwin_arch spec.
2129  CmdArgs.push_back("-arch");
2130  CmdArgs.push_back(Args.MakeArgString(ArchName));
2131
2132  // FIXME: Is this needed anymore?
2133  if (ArchName == "arm")
2134    CmdArgs.push_back("-force_cpusubtype_ALL");
2135}
2136
2137void darwin::Link::AddLinkArgs(const ArgList &Args,
2138                               ArgStringList &CmdArgs) const {
2139  const Driver &D = getToolChain().getDriver();
2140
2141  // Derived from the "link" spec.
2142  Args.AddAllArgs(CmdArgs, options::OPT_static);
2143  if (!Args.hasArg(options::OPT_static))
2144    CmdArgs.push_back("-dynamic");
2145  if (Args.hasArg(options::OPT_fgnu_runtime)) {
2146    // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
2147    // here. How do we wish to handle such things?
2148  }
2149
2150  if (!Args.hasArg(options::OPT_dynamiclib)) {
2151    AddDarwinArch(Args, CmdArgs);
2152    // FIXME: Why do this only on this path?
2153    Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
2154
2155    Args.AddLastArg(CmdArgs, options::OPT_bundle);
2156    Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
2157    Args.AddAllArgs(CmdArgs, options::OPT_client__name);
2158
2159    Arg *A;
2160    if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
2161        (A = Args.getLastArg(options::OPT_current__version)) ||
2162        (A = Args.getLastArg(options::OPT_install__name)))
2163      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
2164        << A->getAsString(Args) << "-dynamiclib";
2165
2166    Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
2167    Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
2168    Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
2169  } else {
2170    CmdArgs.push_back("-dylib");
2171
2172    Arg *A;
2173    if ((A = Args.getLastArg(options::OPT_bundle)) ||
2174        (A = Args.getLastArg(options::OPT_bundle__loader)) ||
2175        (A = Args.getLastArg(options::OPT_client__name)) ||
2176        (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
2177        (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
2178        (A = Args.getLastArg(options::OPT_private__bundle)))
2179      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
2180        << A->getAsString(Args) << "-dynamiclib";
2181
2182    Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
2183                              "-dylib_compatibility_version");
2184    Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
2185                              "-dylib_current_version");
2186
2187    AddDarwinArch(Args, CmdArgs);
2188
2189    Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
2190                              "-dylib_install_name");
2191  }
2192
2193  Args.AddLastArg(CmdArgs, options::OPT_all__load);
2194  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
2195  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
2196  if (getDarwinToolChain().isTargetIPhoneOS())
2197    Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
2198  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
2199  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
2200  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
2201  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
2202  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
2203  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
2204  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
2205  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
2206  Args.AddAllArgs(CmdArgs, options::OPT_init);
2207
2208  // Adding all arguments doesn't make sense here but this is what gcc does. One
2209  // of this should always be present thanks to argument translation.
2210  assert((Args.hasArg(options::OPT_mmacosx_version_min_EQ) ||
2211          Args.hasArg(options::OPT_miphoneos_version_min_EQ)) &&
2212         "Missing version argument (lost in translation)?");
2213  Args.AddAllArgsTranslated(CmdArgs, options::OPT_mmacosx_version_min_EQ,
2214                            "-macosx_version_min");
2215  Args.AddAllArgsTranslated(CmdArgs, options::OPT_miphoneos_version_min_EQ,
2216                            "-iphoneos_version_min");
2217  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
2218  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
2219  Args.AddLastArg(CmdArgs, options::OPT_single__module);
2220  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
2221  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
2222
2223  if (Args.hasArg(options::OPT_fpie))
2224    CmdArgs.push_back("-pie");
2225
2226  Args.AddLastArg(CmdArgs, options::OPT_prebind);
2227  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
2228  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
2229  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
2230  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
2231  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
2232  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
2233  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
2234  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
2235  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
2236  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
2237  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
2238  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
2239  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
2240  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
2241  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
2242
2243  Args.AddAllArgsTranslated(CmdArgs, options::OPT_isysroot, "-syslibroot");
2244  if (getDarwinToolChain().isTargetIPhoneOS()) {
2245    if (!Args.hasArg(options::OPT_isysroot)) {
2246      CmdArgs.push_back("-syslibroot");
2247      CmdArgs.push_back("/Developer/SDKs/Extra");
2248    }
2249  }
2250
2251  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
2252  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
2253  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
2254  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
2255  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
2256  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
2257  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
2258  Args.AddAllArgs(CmdArgs, options::OPT_y);
2259  Args.AddLastArg(CmdArgs, options::OPT_w);
2260  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
2261  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
2262  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
2263  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
2264  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
2265  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
2266  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
2267  Args.AddLastArg(CmdArgs, options::OPT_whyload);
2268  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
2269  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
2270  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
2271  Args.AddLastArg(CmdArgs, options::OPT_Mach);
2272}
2273
2274void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
2275                                Job &Dest, const InputInfo &Output,
2276                                const InputInfoList &Inputs,
2277                                const ArgList &Args,
2278                                const char *LinkingOutput) const {
2279  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
2280
2281  // The logic here is derived from gcc's behavior; most of which
2282  // comes from specs (starting with link_command). Consult gcc for
2283  // more information.
2284  ArgStringList CmdArgs;
2285
2286  // I'm not sure why this particular decomposition exists in gcc, but
2287  // we follow suite for ease of comparison.
2288  AddLinkArgs(Args, CmdArgs);
2289
2290  Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
2291  Args.AddAllArgs(CmdArgs, options::OPT_s);
2292  Args.AddAllArgs(CmdArgs, options::OPT_t);
2293  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
2294  Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
2295  Args.AddAllArgs(CmdArgs, options::OPT_A);
2296  Args.AddLastArg(CmdArgs, options::OPT_e);
2297  Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
2298  Args.AddAllArgs(CmdArgs, options::OPT_r);
2299
2300  CmdArgs.push_back("-o");
2301  CmdArgs.push_back(Output.getFilename());
2302
2303  if (!Args.hasArg(options::OPT_A) &&
2304      !Args.hasArg(options::OPT_nostdlib) &&
2305      !Args.hasArg(options::OPT_nostartfiles)) {
2306    // Derived from startfile spec.
2307    if (Args.hasArg(options::OPT_dynamiclib)) {
2308      // Derived from darwin_dylib1 spec.
2309      if (getDarwinToolChain().isTargetIPhoneOS()) {
2310        if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2311          CmdArgs.push_back("-ldylib1.o");
2312      } else {
2313        if (getDarwinToolChain().isMacosxVersionLT(10, 5))
2314          CmdArgs.push_back("-ldylib1.o");
2315        else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2316          CmdArgs.push_back("-ldylib1.10.5.o");
2317      }
2318    } else {
2319      if (Args.hasArg(options::OPT_bundle)) {
2320        if (!Args.hasArg(options::OPT_static)) {
2321          // Derived from darwin_bundle1 spec.
2322          if (getDarwinToolChain().isTargetIPhoneOS()) {
2323            if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2324              CmdArgs.push_back("-lbundle1.o");
2325          } else {
2326            if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2327              CmdArgs.push_back("-lbundle1.o");
2328          }
2329        }
2330      } else {
2331        if (Args.hasArg(options::OPT_pg)) {
2332          if (Args.hasArg(options::OPT_static) ||
2333              Args.hasArg(options::OPT_object) ||
2334              Args.hasArg(options::OPT_preload)) {
2335            CmdArgs.push_back("-lgcrt0.o");
2336          } else {
2337            CmdArgs.push_back("-lgcrt1.o");
2338
2339            // darwin_crt2 spec is empty.
2340          }
2341        } else {
2342          if (Args.hasArg(options::OPT_static) ||
2343              Args.hasArg(options::OPT_object) ||
2344              Args.hasArg(options::OPT_preload)) {
2345            CmdArgs.push_back("-lcrt0.o");
2346          } else {
2347            // Derived from darwin_crt1 spec.
2348            if (getDarwinToolChain().isTargetIPhoneOS()) {
2349              if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
2350                CmdArgs.push_back("-lcrt1.o");
2351              else
2352                CmdArgs.push_back("-lcrt1.3.1.o");
2353            } else {
2354              if (getDarwinToolChain().isMacosxVersionLT(10, 5))
2355                CmdArgs.push_back("-lcrt1.o");
2356              else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
2357                CmdArgs.push_back("-lcrt1.10.5.o");
2358              else
2359                CmdArgs.push_back("-lcrt1.10.6.o");
2360
2361              // darwin_crt2 spec is empty.
2362            }
2363          }
2364        }
2365      }
2366    }
2367
2368    if (!getDarwinToolChain().isTargetIPhoneOS() &&
2369        Args.hasArg(options::OPT_shared_libgcc) &&
2370        getDarwinToolChain().isMacosxVersionLT(10, 5)) {
2371      const char *Str =
2372        Args.MakeArgString(getToolChain().GetFilePath(C, "crt3.o"));
2373      CmdArgs.push_back(Str);
2374    }
2375  }
2376
2377  Args.AddAllArgs(CmdArgs, options::OPT_L);
2378
2379  if (Args.hasArg(options::OPT_fopenmp))
2380    // This is more complicated in gcc...
2381    CmdArgs.push_back("-lgomp");
2382
2383  getDarwinToolChain().AddLinkSearchPathArgs(Args, CmdArgs);
2384
2385  for (InputInfoList::const_iterator
2386         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2387    const InputInfo &II = *it;
2388    if (II.isFilename())
2389      CmdArgs.push_back(II.getFilename());
2390    else
2391      II.getInputArg().renderAsInput(Args, CmdArgs);
2392  }
2393
2394  if (LinkingOutput) {
2395    CmdArgs.push_back("-arch_multiple");
2396    CmdArgs.push_back("-final_output");
2397    CmdArgs.push_back(LinkingOutput);
2398  }
2399
2400  if (Args.hasArg(options::OPT_fprofile_arcs) ||
2401      Args.hasArg(options::OPT_fprofile_generate) ||
2402      Args.hasArg(options::OPT_fcreate_profile) ||
2403      Args.hasArg(options::OPT_coverage))
2404    CmdArgs.push_back("-lgcov");
2405
2406  if (Args.hasArg(options::OPT_fnested_functions))
2407    CmdArgs.push_back("-allow_stack_execute");
2408
2409  if (!Args.hasArg(options::OPT_nostdlib) &&
2410      !Args.hasArg(options::OPT_nodefaultlibs)) {
2411    // FIXME: g++ is more complicated here, it tries to put -lstdc++
2412    // before -lm, for example.
2413    if (getToolChain().getDriver().CCCIsCXX)
2414      CmdArgs.push_back("-lstdc++");
2415
2416    // link_ssp spec is empty.
2417
2418    // Let the tool chain choose which runtime library to link.
2419    getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
2420  }
2421
2422  if (!Args.hasArg(options::OPT_A) &&
2423      !Args.hasArg(options::OPT_nostdlib) &&
2424      !Args.hasArg(options::OPT_nostartfiles)) {
2425    // endfile_spec is empty.
2426  }
2427
2428  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
2429  Args.AddAllArgs(CmdArgs, options::OPT_F);
2430
2431  const char *Exec =
2432    Args.MakeArgString(getToolChain().GetProgramPath(C, "ld"));
2433  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2434
2435  // Find the first non-empty base input (we want to ignore linker
2436  // inputs).
2437  const char *BaseInput = "";
2438  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2439    if (Inputs[i].getBaseInput()[0] != '\0') {
2440      BaseInput = Inputs[i].getBaseInput();
2441      break;
2442    }
2443  }
2444
2445  // Run dsymutil if we are making an executable in a single step.
2446  //
2447  // FIXME: Currently we don't want to do this when we are part of a
2448  // universal build step, as this would end up creating stray temp
2449  // files.
2450  if (!LinkingOutput &&
2451      Args.getLastArg(options::OPT_g_Group) &&
2452      !Args.getLastArg(options::OPT_gstabs) &&
2453      !Args.getLastArg(options::OPT_g0)) {
2454    // FIXME: This is gross, but matches gcc. The test only considers
2455    // the suffix (not the -x type), and then only of the first
2456    // source input. Awesome.
2457    const char *Suffix = strrchr(BaseInput, '.');
2458    if (Suffix && isSourceSuffix(Suffix + 1)) {
2459      const char *Exec =
2460        Args.MakeArgString(getToolChain().GetProgramPath(C, "dsymutil"));
2461      ArgStringList CmdArgs;
2462      CmdArgs.push_back(Output.getFilename());
2463      C.getJobs().addCommand(new Command(JA, *this, Exec, CmdArgs));
2464    }
2465  }
2466}
2467
2468void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
2469                                Job &Dest, const InputInfo &Output,
2470                                const InputInfoList &Inputs,
2471                                const ArgList &Args,
2472                                const char *LinkingOutput) const {
2473  ArgStringList CmdArgs;
2474
2475  CmdArgs.push_back("-create");
2476  assert(Output.isFilename() && "Unexpected lipo output.");
2477
2478  CmdArgs.push_back("-output");
2479  CmdArgs.push_back(Output.getFilename());
2480
2481  for (InputInfoList::const_iterator
2482         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2483    const InputInfo &II = *it;
2484    assert(II.isFilename() && "Unexpected lipo input.");
2485    CmdArgs.push_back(II.getFilename());
2486  }
2487  const char *Exec =
2488    Args.MakeArgString(getToolChain().GetProgramPath(C, "lipo"));
2489  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2490}
2491
2492void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2493                                      Job &Dest, const InputInfo &Output,
2494                                      const InputInfoList &Inputs,
2495                                      const ArgList &Args,
2496                                      const char *LinkingOutput) const {
2497  ArgStringList CmdArgs;
2498
2499  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2500                       options::OPT_Xassembler);
2501
2502  CmdArgs.push_back("-o");
2503  if (Output.isPipe())
2504    CmdArgs.push_back("-");
2505  else
2506    CmdArgs.push_back(Output.getFilename());
2507
2508  for (InputInfoList::const_iterator
2509         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2510    const InputInfo &II = *it;
2511    if (II.isPipe())
2512      CmdArgs.push_back("-");
2513    else
2514      CmdArgs.push_back(II.getFilename());
2515  }
2516
2517  const char *Exec =
2518    Args.MakeArgString(getToolChain().GetProgramPath(C, "gas"));
2519  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2520}
2521
2522void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
2523                                  Job &Dest, const InputInfo &Output,
2524                                  const InputInfoList &Inputs,
2525                                  const ArgList &Args,
2526                                  const char *LinkingOutput) const {
2527  const Driver &D = getToolChain().getDriver();
2528  ArgStringList CmdArgs;
2529
2530  if ((!Args.hasArg(options::OPT_nostdlib)) &&
2531      (!Args.hasArg(options::OPT_shared))) {
2532    CmdArgs.push_back("-e");
2533    CmdArgs.push_back("_start");
2534  }
2535
2536  if (Args.hasArg(options::OPT_static)) {
2537    CmdArgs.push_back("-Bstatic");
2538    CmdArgs.push_back("-dn");
2539  } else {
2540//    CmdArgs.push_back("--eh-frame-hdr");
2541    CmdArgs.push_back("-Bdynamic");
2542    if (Args.hasArg(options::OPT_shared)) {
2543      CmdArgs.push_back("-shared");
2544    } else {
2545      CmdArgs.push_back("--dynamic-linker");
2546      CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
2547    }
2548  }
2549
2550  if (Output.isPipe()) {
2551    CmdArgs.push_back("-o");
2552    CmdArgs.push_back("-");
2553  } else if (Output.isFilename()) {
2554    CmdArgs.push_back("-o");
2555    CmdArgs.push_back(Output.getFilename());
2556  } else {
2557    assert(Output.isNothing() && "Invalid output.");
2558  }
2559
2560  if (!Args.hasArg(options::OPT_nostdlib) &&
2561      !Args.hasArg(options::OPT_nostartfiles)) {
2562    if (!Args.hasArg(options::OPT_shared)) {
2563      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crt1.o")));
2564      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o")));
2565      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbegin.o")));
2566    } else {
2567      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o")));
2568    }
2569    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtn.o")));
2570  }
2571
2572  CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
2573                                       + getToolChain().getTripleString()
2574                                       + "/4.2.4"));
2575
2576  Args.AddAllArgs(CmdArgs, options::OPT_L);
2577  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
2578  Args.AddAllArgs(CmdArgs, options::OPT_e);
2579
2580  for (InputInfoList::const_iterator
2581         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2582    const InputInfo &II = *it;
2583
2584    // Don't try to pass LLVM inputs to a generic gcc.
2585    if (II.getType() == types::TY_LLVMBC)
2586      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
2587        << getToolChain().getTripleString();
2588
2589    if (II.isPipe())
2590      CmdArgs.push_back("-");
2591    else if (II.isFilename())
2592      CmdArgs.push_back(II.getFilename());
2593    else
2594      II.getInputArg().renderAsInput(Args, CmdArgs);
2595  }
2596
2597  if (!Args.hasArg(options::OPT_nostdlib) &&
2598      !Args.hasArg(options::OPT_nodefaultlibs)) {
2599    // FIXME: For some reason GCC passes -lgcc before adding
2600    // the default system libraries. Just mimic this for now.
2601    CmdArgs.push_back("-lgcc");
2602
2603    if (Args.hasArg(options::OPT_pthread))
2604      CmdArgs.push_back("-pthread");
2605    if (!Args.hasArg(options::OPT_shared))
2606      CmdArgs.push_back("-lc");
2607    CmdArgs.push_back("-lgcc");
2608  }
2609
2610  if (!Args.hasArg(options::OPT_nostdlib) &&
2611      !Args.hasArg(options::OPT_nostartfiles)) {
2612    if (!Args.hasArg(options::OPT_shared))
2613      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtend.o")));
2614//    else
2615//      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtendS.o")));
2616  }
2617
2618  const char *Exec =
2619    Args.MakeArgString(getToolChain().GetProgramPath(C, "ld"));
2620  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2621}
2622
2623void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2624                                     Job &Dest, const InputInfo &Output,
2625                                     const InputInfoList &Inputs,
2626                                     const ArgList &Args,
2627                                     const char *LinkingOutput) const {
2628  ArgStringList CmdArgs;
2629
2630  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2631                       options::OPT_Xassembler);
2632
2633  CmdArgs.push_back("-o");
2634  if (Output.isPipe())
2635    CmdArgs.push_back("-");
2636  else
2637    CmdArgs.push_back(Output.getFilename());
2638
2639  for (InputInfoList::const_iterator
2640         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2641    const InputInfo &II = *it;
2642    if (II.isPipe())
2643      CmdArgs.push_back("-");
2644    else
2645      CmdArgs.push_back(II.getFilename());
2646  }
2647
2648  const char *Exec =
2649    Args.MakeArgString(getToolChain().GetProgramPath(C, "as"));
2650  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2651}
2652
2653void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
2654                                 Job &Dest, const InputInfo &Output,
2655                                 const InputInfoList &Inputs,
2656                                 const ArgList &Args,
2657                                 const char *LinkingOutput) const {
2658  const Driver &D = getToolChain().getDriver();
2659  ArgStringList CmdArgs;
2660
2661  if ((!Args.hasArg(options::OPT_nostdlib)) &&
2662      (!Args.hasArg(options::OPT_shared))) {
2663    CmdArgs.push_back("-e");
2664    CmdArgs.push_back("__start");
2665  }
2666
2667  if (Args.hasArg(options::OPT_static)) {
2668    CmdArgs.push_back("-Bstatic");
2669  } else {
2670    CmdArgs.push_back("--eh-frame-hdr");
2671    CmdArgs.push_back("-Bdynamic");
2672    if (Args.hasArg(options::OPT_shared)) {
2673      CmdArgs.push_back("-shared");
2674    } else {
2675      CmdArgs.push_back("-dynamic-linker");
2676      CmdArgs.push_back("/usr/libexec/ld.so");
2677    }
2678  }
2679
2680  if (Output.isPipe()) {
2681    CmdArgs.push_back("-o");
2682    CmdArgs.push_back("-");
2683  } else if (Output.isFilename()) {
2684    CmdArgs.push_back("-o");
2685    CmdArgs.push_back(Output.getFilename());
2686  } else {
2687    assert(Output.isNothing() && "Invalid output.");
2688  }
2689
2690  if (!Args.hasArg(options::OPT_nostdlib) &&
2691      !Args.hasArg(options::OPT_nostartfiles)) {
2692    if (!Args.hasArg(options::OPT_shared)) {
2693      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crt0.o")));
2694      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbegin.o")));
2695    } else {
2696      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbeginS.o")));
2697    }
2698  }
2699
2700  std::string Triple = getToolChain().getTripleString();
2701  if (Triple.substr(0, 6) == "x86_64")
2702    Triple.replace(0, 6, "amd64");
2703  CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
2704                                       "/3.3.5"));
2705
2706  Args.AddAllArgs(CmdArgs, options::OPT_L);
2707  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
2708  Args.AddAllArgs(CmdArgs, options::OPT_e);
2709
2710  for (InputInfoList::const_iterator
2711         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2712    const InputInfo &II = *it;
2713
2714    // Don't try to pass LLVM inputs to a generic gcc.
2715    if (II.getType() == types::TY_LLVMBC)
2716      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
2717        << getToolChain().getTripleString();
2718
2719    if (II.isPipe())
2720      CmdArgs.push_back("-");
2721    else if (II.isFilename())
2722      CmdArgs.push_back(II.getFilename());
2723    else
2724      II.getInputArg().renderAsInput(Args, CmdArgs);
2725  }
2726
2727  if (!Args.hasArg(options::OPT_nostdlib) &&
2728      !Args.hasArg(options::OPT_nodefaultlibs)) {
2729    // FIXME: For some reason GCC passes -lgcc before adding
2730    // the default system libraries. Just mimic this for now.
2731    CmdArgs.push_back("-lgcc");
2732
2733    if (Args.hasArg(options::OPT_pthread))
2734      CmdArgs.push_back("-pthread");
2735    if (!Args.hasArg(options::OPT_shared))
2736      CmdArgs.push_back("-lc");
2737    CmdArgs.push_back("-lgcc");
2738  }
2739
2740  if (!Args.hasArg(options::OPT_nostdlib) &&
2741      !Args.hasArg(options::OPT_nostartfiles)) {
2742    if (!Args.hasArg(options::OPT_shared))
2743      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtend.o")));
2744    else
2745      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtendS.o")));
2746  }
2747
2748  const char *Exec =
2749    Args.MakeArgString(getToolChain().GetProgramPath(C, "ld"));
2750  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2751}
2752
2753void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2754                                     Job &Dest, const InputInfo &Output,
2755                                     const InputInfoList &Inputs,
2756                                     const ArgList &Args,
2757                                     const char *LinkingOutput) const {
2758  ArgStringList CmdArgs;
2759
2760  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
2761  // instruct as in the base system to assemble 32-bit code.
2762  if (getToolChain().getArchName() == "i386")
2763    CmdArgs.push_back("--32");
2764
2765
2766  // Set byte order explicitly
2767  if (getToolChain().getArchName() == "mips")
2768    CmdArgs.push_back("-EB");
2769  else if (getToolChain().getArchName() == "mipsel")
2770    CmdArgs.push_back("-EL");
2771
2772  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2773                       options::OPT_Xassembler);
2774
2775  CmdArgs.push_back("-o");
2776  if (Output.isPipe())
2777    CmdArgs.push_back("-");
2778  else
2779    CmdArgs.push_back(Output.getFilename());
2780
2781  for (InputInfoList::const_iterator
2782         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2783    const InputInfo &II = *it;
2784    if (II.isPipe())
2785      CmdArgs.push_back("-");
2786    else
2787      CmdArgs.push_back(II.getFilename());
2788  }
2789
2790  const char *Exec =
2791    Args.MakeArgString(getToolChain().GetProgramPath(C, "as"));
2792  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2793}
2794
2795void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
2796                                 Job &Dest, const InputInfo &Output,
2797                                 const InputInfoList &Inputs,
2798                                 const ArgList &Args,
2799                                 const char *LinkingOutput) const {
2800  const Driver &D = getToolChain().getDriver();
2801  ArgStringList CmdArgs;
2802
2803  if (Args.hasArg(options::OPT_static)) {
2804    CmdArgs.push_back("-Bstatic");
2805  } else {
2806    CmdArgs.push_back("--eh-frame-hdr");
2807    if (Args.hasArg(options::OPT_shared)) {
2808      CmdArgs.push_back("-Bshareable");
2809    } else {
2810      CmdArgs.push_back("-dynamic-linker");
2811      CmdArgs.push_back("/libexec/ld-elf.so.1");
2812    }
2813  }
2814
2815  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
2816  // instruct ld in the base system to link 32-bit code.
2817  if (getToolChain().getArchName() == "i386") {
2818    CmdArgs.push_back("-m");
2819    CmdArgs.push_back("elf_i386_fbsd");
2820  }
2821
2822  if (Output.isPipe()) {
2823    CmdArgs.push_back("-o");
2824    CmdArgs.push_back("-");
2825  } else if (Output.isFilename()) {
2826    CmdArgs.push_back("-o");
2827    CmdArgs.push_back(Output.getFilename());
2828  } else {
2829    assert(Output.isNothing() && "Invalid output.");
2830  }
2831
2832  if (!Args.hasArg(options::OPT_nostdlib) &&
2833      !Args.hasArg(options::OPT_nostartfiles)) {
2834    if (!Args.hasArg(options::OPT_shared)) {
2835      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crt1.o")));
2836      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o")));
2837      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbegin.o")));
2838    } else {
2839      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o")));
2840      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbeginS.o")));
2841    }
2842  }
2843
2844  Args.AddAllArgs(CmdArgs, options::OPT_L);
2845  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
2846  Args.AddAllArgs(CmdArgs, options::OPT_e);
2847
2848  for (InputInfoList::const_iterator
2849         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2850    const InputInfo &II = *it;
2851
2852    // Don't try to pass LLVM inputs to a generic gcc.
2853    if (II.getType() == types::TY_LLVMBC)
2854      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
2855        << getToolChain().getTripleString();
2856
2857    if (II.isPipe())
2858      CmdArgs.push_back("-");
2859    else if (II.isFilename())
2860      CmdArgs.push_back(II.getFilename());
2861    else
2862      II.getInputArg().renderAsInput(Args, CmdArgs);
2863  }
2864
2865  if (!Args.hasArg(options::OPT_nostdlib) &&
2866      !Args.hasArg(options::OPT_nodefaultlibs)) {
2867    if (D.CCCIsCXX) {
2868      CmdArgs.push_back("-lstdc++");
2869      CmdArgs.push_back("-lm");
2870    }
2871    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
2872    // the default system libraries. Just mimic this for now.
2873    CmdArgs.push_back("-lgcc");
2874    if (Args.hasArg(options::OPT_static)) {
2875      CmdArgs.push_back("-lgcc_eh");
2876    } else {
2877      CmdArgs.push_back("--as-needed");
2878      CmdArgs.push_back("-lgcc_s");
2879      CmdArgs.push_back("--no-as-needed");
2880    }
2881
2882    if (Args.hasArg(options::OPT_pthread))
2883      CmdArgs.push_back("-lpthread");
2884    CmdArgs.push_back("-lc");
2885
2886    CmdArgs.push_back("-lgcc");
2887    if (Args.hasArg(options::OPT_static)) {
2888      CmdArgs.push_back("-lgcc_eh");
2889    } else {
2890      CmdArgs.push_back("--as-needed");
2891      CmdArgs.push_back("-lgcc_s");
2892      CmdArgs.push_back("--no-as-needed");
2893    }
2894  }
2895
2896  if (!Args.hasArg(options::OPT_nostdlib) &&
2897      !Args.hasArg(options::OPT_nostartfiles)) {
2898    if (!Args.hasArg(options::OPT_shared))
2899      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtend.o")));
2900    else
2901      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtendS.o")));
2902    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtn.o")));
2903  }
2904
2905  const char *Exec =
2906    Args.MakeArgString(getToolChain().GetProgramPath(C, "ld"));
2907  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2908}
2909
2910/// DragonFly Tools
2911
2912// For now, DragonFly Assemble does just about the same as for
2913// FreeBSD, but this may change soon.
2914void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
2915                                       Job &Dest, const InputInfo &Output,
2916                                       const InputInfoList &Inputs,
2917                                       const ArgList &Args,
2918                                       const char *LinkingOutput) const {
2919  ArgStringList CmdArgs;
2920
2921  // When building 32-bit code on DragonFly/pc64, we have to explicitly
2922  // instruct as in the base system to assemble 32-bit code.
2923  if (getToolChain().getArchName() == "i386")
2924    CmdArgs.push_back("--32");
2925
2926  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
2927                       options::OPT_Xassembler);
2928
2929  CmdArgs.push_back("-o");
2930  if (Output.isPipe())
2931    CmdArgs.push_back("-");
2932  else
2933    CmdArgs.push_back(Output.getFilename());
2934
2935  for (InputInfoList::const_iterator
2936         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
2937    const InputInfo &II = *it;
2938    if (II.isPipe())
2939      CmdArgs.push_back("-");
2940    else
2941      CmdArgs.push_back(II.getFilename());
2942  }
2943
2944  const char *Exec =
2945    Args.MakeArgString(getToolChain().GetProgramPath(C, "as"));
2946  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
2947}
2948
2949void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
2950                                 Job &Dest, const InputInfo &Output,
2951                                 const InputInfoList &Inputs,
2952                                 const ArgList &Args,
2953                                 const char *LinkingOutput) const {
2954  const Driver &D = getToolChain().getDriver();
2955  ArgStringList CmdArgs;
2956
2957  if (Args.hasArg(options::OPT_static)) {
2958    CmdArgs.push_back("-Bstatic");
2959  } else {
2960    if (Args.hasArg(options::OPT_shared))
2961      CmdArgs.push_back("-Bshareable");
2962    else {
2963      CmdArgs.push_back("-dynamic-linker");
2964      CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
2965    }
2966  }
2967
2968  // When building 32-bit code on DragonFly/pc64, we have to explicitly
2969  // instruct ld in the base system to link 32-bit code.
2970  if (getToolChain().getArchName() == "i386") {
2971    CmdArgs.push_back("-m");
2972    CmdArgs.push_back("elf_i386");
2973  }
2974
2975  if (Output.isPipe()) {
2976    CmdArgs.push_back("-o");
2977    CmdArgs.push_back("-");
2978  } else if (Output.isFilename()) {
2979    CmdArgs.push_back("-o");
2980    CmdArgs.push_back(Output.getFilename());
2981  } else {
2982    assert(Output.isNothing() && "Invalid output.");
2983  }
2984
2985  if (!Args.hasArg(options::OPT_nostdlib) &&
2986      !Args.hasArg(options::OPT_nostartfiles)) {
2987    if (!Args.hasArg(options::OPT_shared)) {
2988      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crt1.o")));
2989      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o")));
2990      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbegin.o")));
2991    } else {
2992      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o")));
2993      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbeginS.o")));
2994    }
2995  }
2996
2997  Args.AddAllArgs(CmdArgs, options::OPT_L);
2998  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
2999  Args.AddAllArgs(CmdArgs, options::OPT_e);
3000
3001  for (InputInfoList::const_iterator
3002         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3003    const InputInfo &II = *it;
3004
3005    // Don't try to pass LLVM inputs to a generic gcc.
3006    if (II.getType() == types::TY_LLVMBC)
3007      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3008        << getToolChain().getTripleString();
3009
3010    if (II.isPipe())
3011      CmdArgs.push_back("-");
3012    else if (II.isFilename())
3013      CmdArgs.push_back(II.getFilename());
3014    else
3015      II.getInputArg().renderAsInput(Args, CmdArgs);
3016  }
3017
3018  if (!Args.hasArg(options::OPT_nostdlib) &&
3019      !Args.hasArg(options::OPT_nodefaultlibs)) {
3020    // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
3021    //         rpaths
3022    CmdArgs.push_back("-L/usr/lib/gcc41");
3023
3024    if (!Args.hasArg(options::OPT_static)) {
3025      CmdArgs.push_back("-rpath");
3026      CmdArgs.push_back("/usr/lib/gcc41");
3027
3028      CmdArgs.push_back("-rpath-link");
3029      CmdArgs.push_back("/usr/lib/gcc41");
3030
3031      CmdArgs.push_back("-rpath");
3032      CmdArgs.push_back("/usr/lib");
3033
3034      CmdArgs.push_back("-rpath-link");
3035      CmdArgs.push_back("/usr/lib");
3036    }
3037
3038    if (Args.hasArg(options::OPT_shared)) {
3039      CmdArgs.push_back("-lgcc_pic");
3040    } else {
3041      CmdArgs.push_back("-lgcc");
3042    }
3043
3044
3045    if (Args.hasArg(options::OPT_pthread))
3046      CmdArgs.push_back("-lpthread");
3047
3048    if (!Args.hasArg(options::OPT_nolibc)) {
3049      CmdArgs.push_back("-lc");
3050    }
3051
3052    if (Args.hasArg(options::OPT_shared)) {
3053      CmdArgs.push_back("-lgcc_pic");
3054    } else {
3055      CmdArgs.push_back("-lgcc");
3056    }
3057  }
3058
3059  if (!Args.hasArg(options::OPT_nostdlib) &&
3060      !Args.hasArg(options::OPT_nostartfiles)) {
3061    if (!Args.hasArg(options::OPT_shared))
3062      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtend.o")));
3063    else
3064      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtendS.o")));
3065    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtn.o")));
3066  }
3067
3068  const char *Exec =
3069    Args.MakeArgString(getToolChain().GetProgramPath(C, "ld"));
3070  Dest.addCommand(new Command(JA, *this, Exec, CmdArgs));
3071}
3072