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