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