Tools.cpp revision 243830
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  // For the PIC and PIE flag options, this logic is different from the legacy
1773  // logic in very old versions of GCC, as that logic was just a bug no one had
1774  // ever fixed. This logic is both more rational and consistent with GCC's new
1775  // logic now that the bugs are fixed. The last argument relating to either
1776  // PIC or PIE wins, and no other argument is used. If the last argument is
1777  // any flavor of the '-fno-...' arguments, both PIC and PIE are disabled. Any
1778  // PIE option implicitly enables PIC at the same level.
1779  bool PIE = false;
1780  bool PIC = getToolChain().isPICDefault();
1781  bool IsPICLevelTwo = PIC;
1782  if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1783                               options::OPT_fpic, options::OPT_fno_pic,
1784                               options::OPT_fPIE, options::OPT_fno_PIE,
1785                               options::OPT_fpie, options::OPT_fno_pie)) {
1786    Option O = A->getOption();
1787    if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1788        O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1789      PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1790      PIC = PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1791      IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
1792                      O.matches(options::OPT_fPIC);
1793    } else {
1794      PIE = PIC = false;
1795    }
1796  }
1797  // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1798  // is forced, then neither PIC nor PIE flags will have no effect.
1799  if (getToolChain().isPICDefaultForced()) {
1800    PIE = false;
1801    PIC = getToolChain().isPICDefault();
1802    IsPICLevelTwo = PIC;
1803  }
1804
1805  // Inroduce a Darwin-specific hack. If the default is PIC but the flags
1806  // specified while enabling PIC enabled level 1 PIC, just force it back to
1807  // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
1808  // informal testing).
1809  if (PIC && getToolChain().getTriple().isOSDarwin())
1810    IsPICLevelTwo |= getToolChain().isPICDefault();
1811
1812  // Note that these flags are trump-cards. Regardless of the order w.r.t. the
1813  // PIC or PIE options above, if these show up, PIC is disabled.
1814  llvm::Triple Triple(TripleStr);
1815  if ((Args.hasArg(options::OPT_mkernel) ||
1816       Args.hasArg(options::OPT_fapple_kext)) &&
1817      (Triple.getOS() != llvm::Triple::IOS ||
1818       Triple.isOSVersionLT(6)))
1819    PIC = PIE = false;
1820  if (Args.hasArg(options::OPT_static))
1821    PIC = PIE = false;
1822
1823  if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1824    // This is a very special mode. It trumps the other modes, almost no one
1825    // uses it, and it isn't even valid on any OS but Darwin.
1826    if (!getToolChain().getTriple().isOSDarwin())
1827      D.Diag(diag::err_drv_unsupported_opt_for_target)
1828        << A->getSpelling() << getToolChain().getTriple().str();
1829
1830    // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1831
1832    CmdArgs.push_back("-mrelocation-model");
1833    CmdArgs.push_back("dynamic-no-pic");
1834
1835    // Only a forced PIC mode can cause the actual compile to have PIC defines
1836    // etc., no flags are sufficient. This behavior was selected to closely
1837    // match that of llvm-gcc and Apple GCC before that.
1838    if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
1839      CmdArgs.push_back("-pic-level");
1840      CmdArgs.push_back("2");
1841    }
1842  } else {
1843    // Currently, LLVM only knows about PIC vs. static; the PIE differences are
1844    // handled in Clang's IRGen by the -pie-level flag.
1845    CmdArgs.push_back("-mrelocation-model");
1846    CmdArgs.push_back(PIC ? "pic" : "static");
1847
1848    if (PIC) {
1849      CmdArgs.push_back("-pic-level");
1850      CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
1851      if (PIE) {
1852        CmdArgs.push_back("-pie-level");
1853        CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
1854      }
1855    }
1856  }
1857
1858  if (!Args.hasFlag(options::OPT_fmerge_all_constants,
1859                    options::OPT_fno_merge_all_constants))
1860    CmdArgs.push_back("-fno-merge-all-constants");
1861
1862  // LLVM Code Generator Options.
1863
1864  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1865    CmdArgs.push_back("-mregparm");
1866    CmdArgs.push_back(A->getValue());
1867  }
1868
1869  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
1870    CmdArgs.push_back("-mrtd");
1871
1872  if (shouldUseFramePointer(Args, getToolChain().getTriple()))
1873    CmdArgs.push_back("-mdisable-fp-elim");
1874  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
1875                    options::OPT_fno_zero_initialized_in_bss))
1876    CmdArgs.push_back("-mno-zero-initialized-in-bss");
1877  if (!Args.hasFlag(options::OPT_fstrict_aliasing,
1878                    options::OPT_fno_strict_aliasing,
1879                    getToolChain().IsStrictAliasingDefault()))
1880    CmdArgs.push_back("-relaxed-aliasing");
1881  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
1882                   false))
1883    CmdArgs.push_back("-fstrict-enums");
1884  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
1885                    options::OPT_fno_optimize_sibling_calls))
1886    CmdArgs.push_back("-mdisable-tail-calls");
1887
1888  // Handle various floating point optimization flags, mapping them to the
1889  // appropriate LLVM code generation flags. The pattern for all of these is to
1890  // default off the codegen optimizations, and if any flag enables them and no
1891  // flag disables them after the flag enabling them, enable the codegen
1892  // optimization. This is complicated by several "umbrella" flags.
1893  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1894                               options::OPT_fno_fast_math,
1895                               options::OPT_ffinite_math_only,
1896                               options::OPT_fno_finite_math_only,
1897                               options::OPT_fhonor_infinities,
1898                               options::OPT_fno_honor_infinities))
1899    if (A->getOption().getID() != options::OPT_fno_fast_math &&
1900        A->getOption().getID() != options::OPT_fno_finite_math_only &&
1901        A->getOption().getID() != options::OPT_fhonor_infinities)
1902      CmdArgs.push_back("-menable-no-infs");
1903  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1904                               options::OPT_fno_fast_math,
1905                               options::OPT_ffinite_math_only,
1906                               options::OPT_fno_finite_math_only,
1907                               options::OPT_fhonor_nans,
1908                               options::OPT_fno_honor_nans))
1909    if (A->getOption().getID() != options::OPT_fno_fast_math &&
1910        A->getOption().getID() != options::OPT_fno_finite_math_only &&
1911        A->getOption().getID() != options::OPT_fhonor_nans)
1912      CmdArgs.push_back("-menable-no-nans");
1913
1914  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
1915  bool MathErrno = getToolChain().IsMathErrnoDefault();
1916  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1917                               options::OPT_fno_fast_math,
1918                               options::OPT_fmath_errno,
1919                               options::OPT_fno_math_errno))
1920    MathErrno = A->getOption().getID() == options::OPT_fmath_errno;
1921  if (MathErrno)
1922    CmdArgs.push_back("-fmath-errno");
1923
1924  // There are several flags which require disabling very specific
1925  // optimizations. Any of these being disabled forces us to turn off the
1926  // entire set of LLVM optimizations, so collect them through all the flag
1927  // madness.
1928  bool AssociativeMath = false;
1929  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1930                               options::OPT_fno_fast_math,
1931                               options::OPT_funsafe_math_optimizations,
1932                               options::OPT_fno_unsafe_math_optimizations,
1933                               options::OPT_fassociative_math,
1934                               options::OPT_fno_associative_math))
1935    if (A->getOption().getID() != options::OPT_fno_fast_math &&
1936        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1937        A->getOption().getID() != options::OPT_fno_associative_math)
1938      AssociativeMath = true;
1939  bool ReciprocalMath = false;
1940  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1941                               options::OPT_fno_fast_math,
1942                               options::OPT_funsafe_math_optimizations,
1943                               options::OPT_fno_unsafe_math_optimizations,
1944                               options::OPT_freciprocal_math,
1945                               options::OPT_fno_reciprocal_math))
1946    if (A->getOption().getID() != options::OPT_fno_fast_math &&
1947        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1948        A->getOption().getID() != options::OPT_fno_reciprocal_math)
1949      ReciprocalMath = true;
1950  bool SignedZeros = true;
1951  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1952                               options::OPT_fno_fast_math,
1953                               options::OPT_funsafe_math_optimizations,
1954                               options::OPT_fno_unsafe_math_optimizations,
1955                               options::OPT_fsigned_zeros,
1956                               options::OPT_fno_signed_zeros))
1957    if (A->getOption().getID() != options::OPT_fno_fast_math &&
1958        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1959        A->getOption().getID() != options::OPT_fsigned_zeros)
1960      SignedZeros = false;
1961  bool TrappingMath = true;
1962  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1963                               options::OPT_fno_fast_math,
1964                               options::OPT_funsafe_math_optimizations,
1965                               options::OPT_fno_unsafe_math_optimizations,
1966                               options::OPT_ftrapping_math,
1967                               options::OPT_fno_trapping_math))
1968    if (A->getOption().getID() != options::OPT_fno_fast_math &&
1969        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
1970        A->getOption().getID() != options::OPT_ftrapping_math)
1971      TrappingMath = false;
1972  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
1973      !TrappingMath)
1974    CmdArgs.push_back("-menable-unsafe-fp-math");
1975
1976
1977  // Validate and pass through -fp-contract option.
1978  if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
1979                               options::OPT_fno_fast_math,
1980                               options::OPT_ffp_contract)) {
1981    if (A->getOption().getID() == options::OPT_ffp_contract) {
1982      StringRef Val = A->getValue();
1983      if (Val == "fast" || Val == "on" || Val == "off") {
1984        CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
1985      } else {
1986        D.Diag(diag::err_drv_unsupported_option_argument)
1987          << A->getOption().getName() << Val;
1988      }
1989    } else if (A->getOption().getID() == options::OPT_ffast_math) {
1990      // If fast-math is set then set the fp-contract mode to fast.
1991      CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
1992    }
1993  }
1994
1995  // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
1996  // and if we find them, tell the frontend to provide the appropriate
1997  // preprocessor macros. This is distinct from enabling any optimizations as
1998  // these options induce language changes which must survive serialization
1999  // and deserialization, etc.
2000  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math))
2001    if (A->getOption().matches(options::OPT_ffast_math))
2002      CmdArgs.push_back("-ffast-math");
2003  if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only, options::OPT_fno_fast_math))
2004    if (A->getOption().matches(options::OPT_ffinite_math_only))
2005      CmdArgs.push_back("-ffinite-math-only");
2006
2007  // Decide whether to use verbose asm. Verbose assembly is the default on
2008  // toolchains which have the integrated assembler on by default.
2009  bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
2010  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2011                   IsVerboseAsmDefault) ||
2012      Args.hasArg(options::OPT_dA))
2013    CmdArgs.push_back("-masm-verbose");
2014
2015  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2016    CmdArgs.push_back("-mdebug-pass");
2017    CmdArgs.push_back("Structure");
2018  }
2019  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2020    CmdArgs.push_back("-mdebug-pass");
2021    CmdArgs.push_back("Arguments");
2022  }
2023
2024  // Enable -mconstructor-aliases except on darwin, where we have to
2025  // work around a linker bug;  see <rdar://problem/7651567>.
2026  if (!getToolChain().getTriple().isOSDarwin())
2027    CmdArgs.push_back("-mconstructor-aliases");
2028
2029  // Darwin's kernel doesn't support guard variables; just die if we
2030  // try to use them.
2031  if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2032    CmdArgs.push_back("-fforbid-guard-variables");
2033
2034  if (Args.hasArg(options::OPT_mms_bitfields)) {
2035    CmdArgs.push_back("-mms-bitfields");
2036  }
2037
2038  // This is a coarse approximation of what llvm-gcc actually does, both
2039  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2040  // complicated ways.
2041  bool AsynchronousUnwindTables =
2042    Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2043                 options::OPT_fno_asynchronous_unwind_tables,
2044                 getToolChain().IsUnwindTablesDefault() &&
2045                 !KernelOrKext);
2046  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2047                   AsynchronousUnwindTables))
2048    CmdArgs.push_back("-munwind-tables");
2049
2050  getToolChain().addClangTargetOptions(CmdArgs);
2051
2052  if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2053    CmdArgs.push_back("-mlimit-float-precision");
2054    CmdArgs.push_back(A->getValue());
2055  }
2056
2057  // FIXME: Handle -mtune=.
2058  (void) Args.hasArg(options::OPT_mtune_EQ);
2059
2060  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2061    CmdArgs.push_back("-mcode-model");
2062    CmdArgs.push_back(A->getValue());
2063  }
2064
2065  // Add target specific cpu and features flags.
2066  switch(getToolChain().getTriple().getArch()) {
2067  default:
2068    break;
2069
2070  case llvm::Triple::arm:
2071  case llvm::Triple::thumb:
2072    AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
2073    break;
2074
2075  case llvm::Triple::mips:
2076  case llvm::Triple::mipsel:
2077  case llvm::Triple::mips64:
2078  case llvm::Triple::mips64el:
2079    AddMIPSTargetArgs(Args, CmdArgs);
2080    break;
2081
2082  case llvm::Triple::ppc:
2083  case llvm::Triple::ppc64:
2084    AddPPCTargetArgs(Args, CmdArgs);
2085    break;
2086
2087  case llvm::Triple::sparc:
2088    AddSparcTargetArgs(Args, CmdArgs);
2089    break;
2090
2091  case llvm::Triple::x86:
2092  case llvm::Triple::x86_64:
2093    AddX86TargetArgs(Args, CmdArgs);
2094    break;
2095
2096  case llvm::Triple::hexagon:
2097    AddHexagonTargetArgs(Args, CmdArgs);
2098    break;
2099  }
2100
2101
2102
2103  // Pass the linker version in use.
2104  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2105    CmdArgs.push_back("-target-linker-version");
2106    CmdArgs.push_back(A->getValue());
2107  }
2108
2109  // -mno-omit-leaf-frame-pointer is the default on Darwin.
2110  if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
2111                   options::OPT_mno_omit_leaf_frame_pointer,
2112                   !getToolChain().getTriple().isOSDarwin()))
2113    CmdArgs.push_back("-momit-leaf-frame-pointer");
2114
2115  // Explicitly error on some things we know we don't support and can't just
2116  // ignore.
2117  types::ID InputType = Inputs[0].getType();
2118  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2119    Arg *Unsupported;
2120    if (types::isCXX(InputType) &&
2121        getToolChain().getTriple().isOSDarwin() &&
2122        getToolChain().getTriple().getArch() == llvm::Triple::x86) {
2123      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2124          (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2125        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2126          << Unsupported->getOption().getName();
2127    }
2128  }
2129
2130  Args.AddAllArgs(CmdArgs, options::OPT_v);
2131  Args.AddLastArg(CmdArgs, options::OPT_H);
2132  if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2133    CmdArgs.push_back("-header-include-file");
2134    CmdArgs.push_back(D.CCPrintHeadersFilename ?
2135                      D.CCPrintHeadersFilename : "-");
2136  }
2137  Args.AddLastArg(CmdArgs, options::OPT_P);
2138  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2139
2140  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2141    CmdArgs.push_back("-diagnostic-log-file");
2142    CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
2143                      D.CCLogDiagnosticsFilename : "-");
2144  }
2145
2146  // Use the last option from "-g" group. "-gline-tables-only" is
2147  // preserved, all other debug options are substituted with "-g".
2148  Args.ClaimAllArgs(options::OPT_g_Group);
2149  if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2150    if (A->getOption().matches(options::OPT_gline_tables_only)) {
2151      CmdArgs.push_back("-gline-tables-only");
2152    } else if (!A->getOption().matches(options::OPT_g0) &&
2153               !A->getOption().matches(options::OPT_ggdb0)) {
2154      CmdArgs.push_back("-g");
2155    }
2156  }
2157
2158  // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
2159  Args.ClaimAllArgs(options::OPT_g_flags_Group);
2160  if (Args.hasArg(options::OPT_gcolumn_info))
2161    CmdArgs.push_back("-dwarf-column-info");
2162
2163  Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
2164  Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
2165
2166  Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2167
2168  if (Args.hasArg(options::OPT_ftest_coverage) ||
2169      Args.hasArg(options::OPT_coverage))
2170    CmdArgs.push_back("-femit-coverage-notes");
2171  if (Args.hasArg(options::OPT_fprofile_arcs) ||
2172      Args.hasArg(options::OPT_coverage))
2173    CmdArgs.push_back("-femit-coverage-data");
2174
2175  if (C.getArgs().hasArg(options::OPT_c) ||
2176      C.getArgs().hasArg(options::OPT_S)) {
2177    if (Output.isFilename()) {
2178      CmdArgs.push_back("-coverage-file");
2179      SmallString<128> absFilename(Output.getFilename());
2180      llvm::sys::fs::make_absolute(absFilename);
2181      CmdArgs.push_back(Args.MakeArgString(absFilename));
2182    }
2183  }
2184
2185  // Pass options for controlling the default header search paths.
2186  if (Args.hasArg(options::OPT_nostdinc)) {
2187    CmdArgs.push_back("-nostdsysteminc");
2188    CmdArgs.push_back("-nobuiltininc");
2189  } else {
2190    if (Args.hasArg(options::OPT_nostdlibinc))
2191        CmdArgs.push_back("-nostdsysteminc");
2192    Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2193    Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2194  }
2195
2196  // Pass the path to compiler resource files.
2197  CmdArgs.push_back("-resource-dir");
2198  CmdArgs.push_back(D.ResourceDir.c_str());
2199
2200  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2201
2202  bool ARCMTEnabled = false;
2203  if (!Args.hasArg(options::OPT_fno_objc_arc)) {
2204    if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2205                                       options::OPT_ccc_arcmt_modify,
2206                                       options::OPT_ccc_arcmt_migrate)) {
2207      ARCMTEnabled = true;
2208      switch (A->getOption().getID()) {
2209      default:
2210        llvm_unreachable("missed a case");
2211      case options::OPT_ccc_arcmt_check:
2212        CmdArgs.push_back("-arcmt-check");
2213        break;
2214      case options::OPT_ccc_arcmt_modify:
2215        CmdArgs.push_back("-arcmt-modify");
2216        break;
2217      case options::OPT_ccc_arcmt_migrate:
2218        CmdArgs.push_back("-arcmt-migrate");
2219        CmdArgs.push_back("-mt-migrate-directory");
2220        CmdArgs.push_back(A->getValue());
2221
2222        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2223        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2224        break;
2225      }
2226    }
2227  }
2228
2229  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2230    if (ARCMTEnabled) {
2231      D.Diag(diag::err_drv_argument_not_allowed_with)
2232        << A->getAsString(Args) << "-ccc-arcmt-migrate";
2233    }
2234    CmdArgs.push_back("-mt-migrate-directory");
2235    CmdArgs.push_back(A->getValue());
2236
2237    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2238                     options::OPT_objcmt_migrate_subscripting)) {
2239      // None specified, means enable them all.
2240      CmdArgs.push_back("-objcmt-migrate-literals");
2241      CmdArgs.push_back("-objcmt-migrate-subscripting");
2242    } else {
2243      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2244      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2245    }
2246  }
2247
2248  // Add preprocessing options like -I, -D, etc. if we are using the
2249  // preprocessor.
2250  //
2251  // FIXME: Support -fpreprocessed
2252  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2253    AddPreprocessingOptions(C, D, Args, CmdArgs, Output, Inputs);
2254
2255  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2256  // that "The compiler can only warn and ignore the option if not recognized".
2257  // When building with ccache, it will pass -D options to clang even on
2258  // preprocessed inputs and configure concludes that -fPIC is not supported.
2259  Args.ClaimAllArgs(options::OPT_D);
2260
2261  // Manually translate -O to -O2 and -O4 to -O3; let clang reject
2262  // others.
2263  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2264    if (A->getOption().matches(options::OPT_O4))
2265      CmdArgs.push_back("-O3");
2266    else if (A->getOption().matches(options::OPT_O) &&
2267             A->getValue()[0] == '\0')
2268      CmdArgs.push_back("-O2");
2269    else
2270      A->render(Args, CmdArgs);
2271  }
2272
2273  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2274  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2275    CmdArgs.push_back("-pedantic");
2276  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2277  Args.AddLastArg(CmdArgs, options::OPT_w);
2278
2279  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2280  // (-ansi is equivalent to -std=c89).
2281  //
2282  // If a std is supplied, only add -trigraphs if it follows the
2283  // option.
2284  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2285    if (Std->getOption().matches(options::OPT_ansi))
2286      if (types::isCXX(InputType))
2287        CmdArgs.push_back("-std=c++98");
2288      else
2289        CmdArgs.push_back("-std=c89");
2290    else
2291      Std->render(Args, CmdArgs);
2292
2293    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
2294                                 options::OPT_trigraphs))
2295      if (A != Std)
2296        A->render(Args, CmdArgs);
2297  } else {
2298    // Honor -std-default.
2299    //
2300    // FIXME: Clang doesn't correctly handle -std= when the input language
2301    // doesn't match. For the time being just ignore this for C++ inputs;
2302    // eventually we want to do all the standard defaulting here instead of
2303    // splitting it between the driver and clang -cc1.
2304    if (!types::isCXX(InputType))
2305      Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2306                                "-std=", /*Joined=*/true);
2307    else if (getToolChain().getTriple().getOS() == llvm::Triple::Win32)
2308      CmdArgs.push_back("-std=c++11");
2309
2310    Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
2311  }
2312
2313  // Map the bizarre '-Wwrite-strings' flag to a more sensible
2314  // '-fconst-strings'; this better indicates its actual behavior.
2315  if (Args.hasFlag(options::OPT_Wwrite_strings, options::OPT_Wno_write_strings,
2316                   false)) {
2317    // For perfect compatibility with GCC, we do this even in the presence of
2318    // '-w'. This flag names something other than a warning for GCC.
2319    CmdArgs.push_back("-fconst-strings");
2320  }
2321
2322  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
2323  // during C++ compilation, which it is by default. GCC keeps this define even
2324  // in the presence of '-w', match this behavior bug-for-bug.
2325  if (types::isCXX(InputType) &&
2326      Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
2327                   true)) {
2328    CmdArgs.push_back("-fdeprecated-macro");
2329  }
2330
2331  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
2332  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
2333    if (Asm->getOption().matches(options::OPT_fasm))
2334      CmdArgs.push_back("-fgnu-keywords");
2335    else
2336      CmdArgs.push_back("-fno-gnu-keywords");
2337  }
2338
2339  if (ShouldDisableCFI(Args, getToolChain()))
2340    CmdArgs.push_back("-fno-dwarf2-cfi-asm");
2341
2342  if (ShouldDisableDwarfDirectory(Args, getToolChain()))
2343    CmdArgs.push_back("-fno-dwarf-directory-asm");
2344
2345  if (const char *pwd = ::getenv("PWD")) {
2346    // GCC also verifies that stat(pwd) and stat(".") have the same inode
2347    // number. Not doing those because stats are slow, but we could.
2348    if (llvm::sys::path::is_absolute(pwd)) {
2349      std::string CompDir = pwd;
2350      CmdArgs.push_back("-fdebug-compilation-dir");
2351      CmdArgs.push_back(Args.MakeArgString(CompDir));
2352    }
2353  }
2354
2355  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
2356                               options::OPT_ftemplate_depth_EQ)) {
2357    CmdArgs.push_back("-ftemplate-depth");
2358    CmdArgs.push_back(A->getValue());
2359  }
2360
2361  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
2362    CmdArgs.push_back("-fconstexpr-depth");
2363    CmdArgs.push_back(A->getValue());
2364  }
2365
2366  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
2367                               options::OPT_Wlarge_by_value_copy_def)) {
2368    if (A->getNumValues()) {
2369      StringRef bytes = A->getValue();
2370      CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
2371    } else
2372      CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
2373  }
2374
2375  if (Arg *A = Args.getLastArg(options::OPT_fbounds_checking,
2376                               options::OPT_fbounds_checking_EQ)) {
2377    if (A->getNumValues()) {
2378      StringRef val = A->getValue();
2379      CmdArgs.push_back(Args.MakeArgString("-fbounds-checking=" + val));
2380    } else
2381      CmdArgs.push_back("-fbounds-checking=1");
2382  }
2383
2384  if (Args.hasArg(options::OPT_relocatable_pch))
2385    CmdArgs.push_back("-relocatable-pch");
2386
2387  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
2388    CmdArgs.push_back("-fconstant-string-class");
2389    CmdArgs.push_back(A->getValue());
2390  }
2391
2392  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
2393    CmdArgs.push_back("-ftabstop");
2394    CmdArgs.push_back(A->getValue());
2395  }
2396
2397  CmdArgs.push_back("-ferror-limit");
2398  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
2399    CmdArgs.push_back(A->getValue());
2400  else
2401    CmdArgs.push_back("19");
2402
2403  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
2404    CmdArgs.push_back("-fmacro-backtrace-limit");
2405    CmdArgs.push_back(A->getValue());
2406  }
2407
2408  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
2409    CmdArgs.push_back("-ftemplate-backtrace-limit");
2410    CmdArgs.push_back(A->getValue());
2411  }
2412
2413  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
2414    CmdArgs.push_back("-fconstexpr-backtrace-limit");
2415    CmdArgs.push_back(A->getValue());
2416  }
2417
2418  // Pass -fmessage-length=.
2419  CmdArgs.push_back("-fmessage-length");
2420  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
2421    CmdArgs.push_back(A->getValue());
2422  } else {
2423    // If -fmessage-length=N was not specified, determine whether this is a
2424    // terminal and, if so, implicitly define -fmessage-length appropriately.
2425    unsigned N = llvm::sys::Process::StandardErrColumns();
2426    CmdArgs.push_back(Args.MakeArgString(Twine(N)));
2427  }
2428
2429  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) {
2430    CmdArgs.push_back("-fvisibility");
2431    CmdArgs.push_back(A->getValue());
2432  }
2433
2434  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
2435
2436  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
2437
2438  // -fhosted is default.
2439  if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
2440      KernelOrKext)
2441    CmdArgs.push_back("-ffreestanding");
2442
2443  // Forward -f (flag) options which we can pass directly.
2444  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
2445  Args.AddLastArg(CmdArgs, options::OPT_fformat_extensions);
2446  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
2447  Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
2448  Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
2449  Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
2450  Args.AddLastArg(CmdArgs, options::OPT_faltivec);
2451  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
2452  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
2453
2454  SanitizerArgs Sanitize(D, Args);
2455  Sanitize.addArgs(Args, CmdArgs);
2456
2457  // Report and error for -faltivec on anything other then PowerPC.
2458  if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
2459    if (!(getToolChain().getTriple().getArch() == llvm::Triple::ppc ||
2460          getToolChain().getTriple().getArch() == llvm::Triple::ppc64))
2461      D.Diag(diag::err_drv_argument_only_allowed_with)
2462        << A->getAsString(Args) << "ppc/ppc64";
2463
2464  if (getToolChain().SupportsProfiling())
2465    Args.AddLastArg(CmdArgs, options::OPT_pg);
2466
2467  // -flax-vector-conversions is default.
2468  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
2469                    options::OPT_fno_lax_vector_conversions))
2470    CmdArgs.push_back("-fno-lax-vector-conversions");
2471
2472  if (Args.getLastArg(options::OPT_fapple_kext))
2473    CmdArgs.push_back("-fapple-kext");
2474
2475  if (Args.hasFlag(options::OPT_frewrite_includes,
2476                   options::OPT_fno_rewrite_includes, false))
2477    CmdArgs.push_back("-frewrite-includes");
2478
2479  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
2480  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
2481  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
2482  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
2483  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
2484
2485  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
2486    CmdArgs.push_back("-ftrapv-handler");
2487    CmdArgs.push_back(A->getValue());
2488  }
2489
2490  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
2491
2492  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
2493  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
2494  if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
2495                               options::OPT_fno_wrapv)) {
2496    if (A->getOption().matches(options::OPT_fwrapv))
2497      CmdArgs.push_back("-fwrapv");
2498  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
2499                                      options::OPT_fno_strict_overflow)) {
2500    if (A->getOption().matches(options::OPT_fno_strict_overflow))
2501      CmdArgs.push_back("-fwrapv");
2502  }
2503  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
2504  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
2505
2506  Args.AddLastArg(CmdArgs, options::OPT_pthread);
2507
2508
2509  // -stack-protector=0 is default.
2510  unsigned StackProtectorLevel = 0;
2511  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2512                               options::OPT_fstack_protector_all,
2513                               options::OPT_fstack_protector)) {
2514    if (A->getOption().matches(options::OPT_fstack_protector))
2515      StackProtectorLevel = 1;
2516    else if (A->getOption().matches(options::OPT_fstack_protector_all))
2517      StackProtectorLevel = 2;
2518  } else {
2519    StackProtectorLevel =
2520      getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
2521  }
2522  if (StackProtectorLevel) {
2523    CmdArgs.push_back("-stack-protector");
2524    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2525  }
2526
2527  // --param ssp-buffer-size=
2528  for (arg_iterator it = Args.filtered_begin(options::OPT__param),
2529       ie = Args.filtered_end(); it != ie; ++it) {
2530    StringRef Str((*it)->getValue());
2531    if (Str.startswith("ssp-buffer-size=")) {
2532      if (StackProtectorLevel) {
2533        CmdArgs.push_back("-stack-protector-buffer-size");
2534        // FIXME: Verify the argument is a valid integer.
2535        CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2536      }
2537      (*it)->claim();
2538    }
2539  }
2540
2541  // Translate -mstackrealign
2542  if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
2543                   false)) {
2544    CmdArgs.push_back("-backend-option");
2545    CmdArgs.push_back("-force-align-stack");
2546  }
2547  if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
2548                   false)) {
2549    CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
2550  }
2551
2552  if (Args.hasArg(options::OPT_mstack_alignment)) {
2553    StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
2554    CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
2555  }
2556  if (Args.hasArg(options::OPT_mstrict_align)) {
2557    CmdArgs.push_back("-backend-option");
2558    CmdArgs.push_back("-arm-strict-align");
2559  }
2560
2561  // Forward -f options with positive and negative forms; we translate
2562  // these by hand.
2563
2564  if (Args.hasArg(options::OPT_mkernel)) {
2565    if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
2566      CmdArgs.push_back("-fapple-kext");
2567    if (!Args.hasArg(options::OPT_fbuiltin))
2568      CmdArgs.push_back("-fno-builtin");
2569    Args.ClaimAllArgs(options::OPT_fno_builtin);
2570  }
2571  // -fbuiltin is default.
2572  else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
2573    CmdArgs.push_back("-fno-builtin");
2574
2575  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
2576                    options::OPT_fno_assume_sane_operator_new))
2577    CmdArgs.push_back("-fno-assume-sane-operator-new");
2578
2579  // -fblocks=0 is default.
2580  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
2581                   getToolChain().IsBlocksDefault()) ||
2582        (Args.hasArg(options::OPT_fgnu_runtime) &&
2583         Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
2584         !Args.hasArg(options::OPT_fno_blocks))) {
2585    CmdArgs.push_back("-fblocks");
2586
2587    if (!Args.hasArg(options::OPT_fgnu_runtime) &&
2588        !getToolChain().hasBlocksRuntime())
2589      CmdArgs.push_back("-fblocks-runtime-optional");
2590  }
2591
2592  // -fmodules enables modules (off by default). However, for C++/Objective-C++,
2593  // users must also pass -fcxx-modules. The latter flag will disappear once the
2594  // modules implementation is solid for C++/Objective-C++ programs as well.
2595  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2596    bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2597                                     options::OPT_fno_cxx_modules,
2598                                     false);
2599    if (AllowedInCXX || !types::isCXX(InputType))
2600      CmdArgs.push_back("-fmodules");
2601  }
2602
2603  // -faccess-control is default.
2604  if (Args.hasFlag(options::OPT_fno_access_control,
2605                   options::OPT_faccess_control,
2606                   false))
2607    CmdArgs.push_back("-fno-access-control");
2608
2609  // -felide-constructors is the default.
2610  if (Args.hasFlag(options::OPT_fno_elide_constructors,
2611                   options::OPT_felide_constructors,
2612                   false))
2613    CmdArgs.push_back("-fno-elide-constructors");
2614
2615  // -frtti is default.
2616  if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
2617      KernelOrKext) {
2618    CmdArgs.push_back("-fno-rtti");
2619
2620    // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
2621    if (Sanitize.sanitizesVptr()) {
2622      std::string NoRttiArg =
2623        Args.getLastArg(options::OPT_mkernel,
2624                        options::OPT_fapple_kext,
2625                        options::OPT_fno_rtti)->getAsString(Args);
2626      D.Diag(diag::err_drv_argument_not_allowed_with)
2627        << "-fsanitize=vptr" << NoRttiArg;
2628    }
2629  }
2630
2631  // -fshort-enums=0 is default for all architectures except Hexagon.
2632  if (Args.hasFlag(options::OPT_fshort_enums,
2633                   options::OPT_fno_short_enums,
2634                   getToolChain().getTriple().getArch() ==
2635                   llvm::Triple::hexagon))
2636    CmdArgs.push_back("-fshort-enums");
2637
2638  // -fsigned-char is default.
2639  if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
2640                    isSignedCharDefault(getToolChain().getTriple())))
2641    CmdArgs.push_back("-fno-signed-char");
2642
2643  // -fthreadsafe-static is default.
2644  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
2645                    options::OPT_fno_threadsafe_statics))
2646    CmdArgs.push_back("-fno-threadsafe-statics");
2647
2648  // -fuse-cxa-atexit is default.
2649  if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
2650                    options::OPT_fno_use_cxa_atexit,
2651                   getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
2652                  getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 &&
2653              getToolChain().getTriple().getArch() != llvm::Triple::hexagon) ||
2654      KernelOrKext)
2655    CmdArgs.push_back("-fno-use-cxa-atexit");
2656
2657  // -fms-extensions=0 is default.
2658  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2659                   getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2660    CmdArgs.push_back("-fms-extensions");
2661
2662  // -fms-inline-asm.
2663  if (Args.hasArg(options::OPT_fenable_experimental_ms_inline_asm))
2664    CmdArgs.push_back("-fenable-experimental-ms-inline-asm");
2665
2666  // -fms-compatibility=0 is default.
2667  if (Args.hasFlag(options::OPT_fms_compatibility,
2668                   options::OPT_fno_ms_compatibility,
2669                   (getToolChain().getTriple().getOS() == llvm::Triple::Win32 &&
2670                    Args.hasFlag(options::OPT_fms_extensions,
2671                                 options::OPT_fno_ms_extensions,
2672                                 true))))
2673    CmdArgs.push_back("-fms-compatibility");
2674
2675  // -fmsc-version=1300 is default.
2676  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2677                   getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
2678      Args.hasArg(options::OPT_fmsc_version)) {
2679    StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
2680    if (msc_ver.empty())
2681      CmdArgs.push_back("-fmsc-version=1300");
2682    else
2683      CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
2684  }
2685
2686
2687  // -fborland-extensions=0 is default.
2688  if (Args.hasFlag(options::OPT_fborland_extensions,
2689                   options::OPT_fno_borland_extensions, false))
2690    CmdArgs.push_back("-fborland-extensions");
2691
2692  // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
2693  // needs it.
2694  if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
2695                   options::OPT_fno_delayed_template_parsing,
2696                   getToolChain().getTriple().getOS() == llvm::Triple::Win32))
2697    CmdArgs.push_back("-fdelayed-template-parsing");
2698
2699  // -fgnu-keywords default varies depending on language; only pass if
2700  // specified.
2701  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
2702                               options::OPT_fno_gnu_keywords))
2703    A->render(Args, CmdArgs);
2704
2705  if (Args.hasFlag(options::OPT_fgnu89_inline,
2706                   options::OPT_fno_gnu89_inline,
2707                   false))
2708    CmdArgs.push_back("-fgnu89-inline");
2709
2710  if (Args.hasArg(options::OPT_fno_inline))
2711    CmdArgs.push_back("-fno-inline");
2712
2713  if (Args.hasArg(options::OPT_fno_inline_functions))
2714    CmdArgs.push_back("-fno-inline-functions");
2715
2716  ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
2717
2718  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
2719  // legacy is the default.
2720  if (objcRuntime.isNonFragile()) {
2721    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2722                      options::OPT_fno_objc_legacy_dispatch,
2723                      objcRuntime.isLegacyDispatchDefaultForArch(
2724                        getToolChain().getTriple().getArch()))) {
2725      if (getToolChain().UseObjCMixedDispatch())
2726        CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2727      else
2728        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2729    }
2730  }
2731
2732  // -fobjc-default-synthesize-properties=1 is default. This only has an effect
2733  // if the nonfragile objc abi is used.
2734  if (getToolChain().IsObjCDefaultSynthPropertiesDefault()) {
2735    CmdArgs.push_back("-fobjc-default-synthesize-properties");
2736  }
2737
2738  // -fencode-extended-block-signature=1 is default.
2739  if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
2740    CmdArgs.push_back("-fencode-extended-block-signature");
2741  }
2742
2743  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2744  // NOTE: This logic is duplicated in ToolChains.cpp.
2745  bool ARC = isObjCAutoRefCount(Args);
2746  if (ARC) {
2747    getToolChain().CheckObjCARC();
2748
2749    CmdArgs.push_back("-fobjc-arc");
2750
2751    // FIXME: It seems like this entire block, and several around it should be
2752    // wrapped in isObjC, but for now we just use it here as this is where it
2753    // was being used previously.
2754    if (types::isCXX(InputType) && types::isObjC(InputType)) {
2755      if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2756        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2757      else
2758        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2759    }
2760
2761    // Allow the user to enable full exceptions code emission.
2762    // We define off for Objective-CC, on for Objective-C++.
2763    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2764                     options::OPT_fno_objc_arc_exceptions,
2765                     /*default*/ types::isCXX(InputType)))
2766      CmdArgs.push_back("-fobjc-arc-exceptions");
2767  }
2768
2769  // -fobjc-infer-related-result-type is the default, except in the Objective-C
2770  // rewriter.
2771  if (rewriteKind != RK_None)
2772    CmdArgs.push_back("-fno-objc-infer-related-result-type");
2773
2774  // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
2775  // takes precedence.
2776  const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
2777  if (!GCArg)
2778    GCArg = Args.getLastArg(options::OPT_fobjc_gc);
2779  if (GCArg) {
2780    if (ARC) {
2781      D.Diag(diag::err_drv_objc_gc_arr)
2782        << GCArg->getAsString(Args);
2783    } else if (getToolChain().SupportsObjCGC()) {
2784      GCArg->render(Args, CmdArgs);
2785    } else {
2786      // FIXME: We should move this to a hard error.
2787      D.Diag(diag::warn_drv_objc_gc_unsupported)
2788        << GCArg->getAsString(Args);
2789    }
2790  }
2791
2792  // Add exception args.
2793  addExceptionArgs(Args, InputType, getToolChain().getTriple(),
2794                   KernelOrKext, objcRuntime, CmdArgs);
2795
2796  if (getToolChain().UseSjLjExceptions())
2797    CmdArgs.push_back("-fsjlj-exceptions");
2798
2799  // C++ "sane" operator new.
2800  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
2801                    options::OPT_fno_assume_sane_operator_new))
2802    CmdArgs.push_back("-fno-assume-sane-operator-new");
2803
2804  // -fconstant-cfstrings is default, and may be subject to argument translation
2805  // on Darwin.
2806  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
2807                    options::OPT_fno_constant_cfstrings) ||
2808      !Args.hasFlag(options::OPT_mconstant_cfstrings,
2809                    options::OPT_mno_constant_cfstrings))
2810    CmdArgs.push_back("-fno-constant-cfstrings");
2811
2812  // -fshort-wchar default varies depending on platform; only
2813  // pass if specified.
2814  if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
2815    A->render(Args, CmdArgs);
2816
2817  // -fno-pascal-strings is default, only pass non-default. If the tool chain
2818  // happened to translate to -mpascal-strings, we want to back translate here.
2819  //
2820  // FIXME: This is gross; that translation should be pulled from the
2821  // tool chain.
2822  if (Args.hasFlag(options::OPT_fpascal_strings,
2823                   options::OPT_fno_pascal_strings,
2824                   false) ||
2825      Args.hasFlag(options::OPT_mpascal_strings,
2826                   options::OPT_mno_pascal_strings,
2827                   false))
2828    CmdArgs.push_back("-fpascal-strings");
2829
2830  // Honor -fpack-struct= and -fpack-struct, if given. Note that
2831  // -fno-pack-struct doesn't apply to -fpack-struct=.
2832  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
2833    std::string PackStructStr = "-fpack-struct=";
2834    PackStructStr += A->getValue();
2835    CmdArgs.push_back(Args.MakeArgString(PackStructStr));
2836  } else if (Args.hasFlag(options::OPT_fpack_struct,
2837                          options::OPT_fno_pack_struct, false)) {
2838    CmdArgs.push_back("-fpack-struct=1");
2839  }
2840
2841  if (Args.hasArg(options::OPT_mkernel) ||
2842      Args.hasArg(options::OPT_fapple_kext)) {
2843    if (!Args.hasArg(options::OPT_fcommon))
2844      CmdArgs.push_back("-fno-common");
2845    Args.ClaimAllArgs(options::OPT_fno_common);
2846  }
2847
2848  // -fcommon is default, only pass non-default.
2849  else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
2850    CmdArgs.push_back("-fno-common");
2851
2852  // -fsigned-bitfields is default, and clang doesn't yet support
2853  // -funsigned-bitfields.
2854  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
2855                    options::OPT_funsigned_bitfields))
2856    D.Diag(diag::warn_drv_clang_unsupported)
2857      << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
2858
2859  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
2860  if (!Args.hasFlag(options::OPT_ffor_scope,
2861                    options::OPT_fno_for_scope))
2862    D.Diag(diag::err_drv_clang_unsupported)
2863      << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
2864
2865  // -fcaret-diagnostics is default.
2866  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2867                    options::OPT_fno_caret_diagnostics, true))
2868    CmdArgs.push_back("-fno-caret-diagnostics");
2869
2870  // -fdiagnostics-fixit-info is default, only pass non-default.
2871  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2872                    options::OPT_fno_diagnostics_fixit_info))
2873    CmdArgs.push_back("-fno-diagnostics-fixit-info");
2874
2875  // Enable -fdiagnostics-show-option by default.
2876  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2877                   options::OPT_fno_diagnostics_show_option))
2878    CmdArgs.push_back("-fdiagnostics-show-option");
2879
2880  if (const Arg *A =
2881        Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2882    CmdArgs.push_back("-fdiagnostics-show-category");
2883    CmdArgs.push_back(A->getValue());
2884  }
2885
2886  if (const Arg *A =
2887        Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2888    CmdArgs.push_back("-fdiagnostics-format");
2889    CmdArgs.push_back(A->getValue());
2890  }
2891
2892  if (Arg *A = Args.getLastArg(
2893      options::OPT_fdiagnostics_show_note_include_stack,
2894      options::OPT_fno_diagnostics_show_note_include_stack)) {
2895    if (A->getOption().matches(
2896        options::OPT_fdiagnostics_show_note_include_stack))
2897      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2898    else
2899      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2900  }
2901
2902  // Color diagnostics are the default, unless the terminal doesn't support
2903  // them.
2904  if (Args.hasFlag(options::OPT_fcolor_diagnostics,
2905                   options::OPT_fno_color_diagnostics,
2906                   llvm::sys::Process::StandardErrHasColors()))
2907    CmdArgs.push_back("-fcolor-diagnostics");
2908
2909  if (!Args.hasFlag(options::OPT_fshow_source_location,
2910                    options::OPT_fno_show_source_location))
2911    CmdArgs.push_back("-fno-show-source-location");
2912
2913  if (!Args.hasFlag(options::OPT_fshow_column,
2914                    options::OPT_fno_show_column,
2915                    true))
2916    CmdArgs.push_back("-fno-show-column");
2917
2918  if (!Args.hasFlag(options::OPT_fspell_checking,
2919                    options::OPT_fno_spell_checking))
2920    CmdArgs.push_back("-fno-spell-checking");
2921
2922
2923  // Silently ignore -fasm-blocks for now.
2924  (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
2925                      false);
2926
2927  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
2928    A->render(Args, CmdArgs);
2929
2930  // -fdollars-in-identifiers default varies depending on platform and
2931  // language; only pass if specified.
2932  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
2933                               options::OPT_fno_dollars_in_identifiers)) {
2934    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
2935      CmdArgs.push_back("-fdollars-in-identifiers");
2936    else
2937      CmdArgs.push_back("-fno-dollars-in-identifiers");
2938  }
2939
2940  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
2941  // practical purposes.
2942  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
2943                               options::OPT_fno_unit_at_a_time)) {
2944    if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
2945      D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
2946  }
2947
2948  if (Args.hasFlag(options::OPT_fapple_pragma_pack,
2949                   options::OPT_fno_apple_pragma_pack, false))
2950    CmdArgs.push_back("-fapple-pragma-pack");
2951
2952  // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
2953  //
2954  // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
2955#if 0
2956  if (getToolChain().getTriple().isOSDarwin() &&
2957      (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
2958       getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
2959    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
2960      CmdArgs.push_back("-fno-builtin-strcat");
2961    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
2962      CmdArgs.push_back("-fno-builtin-strcpy");
2963  }
2964#endif
2965
2966  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
2967  if (Arg *A = Args.getLastArg(options::OPT_traditional,
2968                               options::OPT_traditional_cpp)) {
2969    if (isa<PreprocessJobAction>(JA))
2970      CmdArgs.push_back("-traditional-cpp");
2971    else
2972      D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2973  }
2974
2975  Args.AddLastArg(CmdArgs, options::OPT_dM);
2976  Args.AddLastArg(CmdArgs, options::OPT_dD);
2977
2978  // Handle serialized diagnostics.
2979  if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
2980    CmdArgs.push_back("-serialize-diagnostic-file");
2981    CmdArgs.push_back(Args.MakeArgString(A->getValue()));
2982  }
2983
2984  if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
2985    CmdArgs.push_back("-fretain-comments-from-system-headers");
2986
2987  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
2988  // parser.
2989  Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
2990  for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
2991         ie = Args.filtered_end(); it != ie; ++it) {
2992    (*it)->claim();
2993
2994    // We translate this by hand to the -cc1 argument, since nightly test uses
2995    // it and developers have been trained to spell it with -mllvm.
2996    if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns")
2997      CmdArgs.push_back("-disable-llvm-optzns");
2998    else
2999      (*it)->render(Args, CmdArgs);
3000  }
3001
3002  if (Output.getType() == types::TY_Dependencies) {
3003    // Handled with other dependency code.
3004  } else if (Output.isFilename()) {
3005    CmdArgs.push_back("-o");
3006    CmdArgs.push_back(Output.getFilename());
3007  } else {
3008    assert(Output.isNothing() && "Invalid output.");
3009  }
3010
3011  for (InputInfoList::const_iterator
3012         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3013    const InputInfo &II = *it;
3014    CmdArgs.push_back("-x");
3015    if (Args.hasArg(options::OPT_rewrite_objc))
3016      CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3017    else
3018      CmdArgs.push_back(types::getTypeName(II.getType()));
3019    if (II.isFilename())
3020      CmdArgs.push_back(II.getFilename());
3021    else
3022      II.getInputArg().renderAsInput(Args, CmdArgs);
3023  }
3024
3025  Args.AddAllArgs(CmdArgs, options::OPT_undef);
3026
3027  const char *Exec = getToolChain().getDriver().getClangProgramPath();
3028
3029  // Optionally embed the -cc1 level arguments into the debug info, for build
3030  // analysis.
3031  if (getToolChain().UseDwarfDebugFlags()) {
3032    ArgStringList OriginalArgs;
3033    for (ArgList::const_iterator it = Args.begin(),
3034           ie = Args.end(); it != ie; ++it)
3035      (*it)->render(Args, OriginalArgs);
3036
3037    SmallString<256> Flags;
3038    Flags += Exec;
3039    for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3040      Flags += " ";
3041      Flags += OriginalArgs[i];
3042    }
3043    CmdArgs.push_back("-dwarf-debug-flags");
3044    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3045  }
3046
3047  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3048
3049  if (Arg *A = Args.getLastArg(options::OPT_pg))
3050    if (Args.hasArg(options::OPT_fomit_frame_pointer))
3051      D.Diag(diag::err_drv_argument_not_allowed_with)
3052        << "-fomit-frame-pointer" << A->getAsString(Args);
3053
3054  // Claim some arguments which clang supports automatically.
3055
3056  // -fpch-preprocess is used with gcc to add a special marker in the output to
3057  // include the PCH file. Clang's PTH solution is completely transparent, so we
3058  // do not need to deal with it at all.
3059  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
3060
3061  // Claim some arguments which clang doesn't support, but we don't
3062  // care to warn the user about.
3063  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
3064  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
3065
3066  // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
3067  Args.ClaimAllArgs(options::OPT_use_gold_plugin);
3068  Args.ClaimAllArgs(options::OPT_emit_llvm);
3069}
3070
3071void ClangAs::AddARMTargetArgs(const ArgList &Args,
3072                               ArgStringList &CmdArgs) const {
3073  const Driver &D = getToolChain().getDriver();
3074  llvm::Triple Triple = getToolChain().getTriple();
3075
3076  // Set the CPU based on -march= and -mcpu=.
3077  CmdArgs.push_back("-target-cpu");
3078  CmdArgs.push_back(Args.MakeArgString(getARMTargetCPU(Args, Triple)));
3079
3080  // Honor -mfpu=.
3081  if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
3082    addFPUArgs(D, A, Args, CmdArgs);
3083
3084  // Honor -mfpmath=.
3085  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ))
3086    addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
3087}
3088
3089/// Add options related to the Objective-C runtime/ABI.
3090///
3091/// Returns true if the runtime is non-fragile.
3092ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
3093                                      ArgStringList &cmdArgs,
3094                                      RewriteKind rewriteKind) const {
3095  // Look for the controlling runtime option.
3096  Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
3097                                    options::OPT_fgnu_runtime,
3098                                    options::OPT_fobjc_runtime_EQ);
3099
3100  // Just forward -fobjc-runtime= to the frontend.  This supercedes
3101  // options about fragility.
3102  if (runtimeArg &&
3103      runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
3104    ObjCRuntime runtime;
3105    StringRef value = runtimeArg->getValue();
3106    if (runtime.tryParse(value)) {
3107      getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
3108        << value;
3109    }
3110
3111    runtimeArg->render(args, cmdArgs);
3112    return runtime;
3113  }
3114
3115  // Otherwise, we'll need the ABI "version".  Version numbers are
3116  // slightly confusing for historical reasons:
3117  //   1 - Traditional "fragile" ABI
3118  //   2 - Non-fragile ABI, version 1
3119  //   3 - Non-fragile ABI, version 2
3120  unsigned objcABIVersion = 1;
3121  // If -fobjc-abi-version= is present, use that to set the version.
3122  if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
3123    StringRef value = abiArg->getValue();
3124    if (value == "1")
3125      objcABIVersion = 1;
3126    else if (value == "2")
3127      objcABIVersion = 2;
3128    else if (value == "3")
3129      objcABIVersion = 3;
3130    else
3131      getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3132        << value;
3133  } else {
3134    // Otherwise, determine if we are using the non-fragile ABI.
3135    bool nonFragileABIIsDefault =
3136      (rewriteKind == RK_NonFragile ||
3137       (rewriteKind == RK_None &&
3138        getToolChain().IsObjCNonFragileABIDefault()));
3139    if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
3140                     options::OPT_fno_objc_nonfragile_abi,
3141                     nonFragileABIIsDefault)) {
3142      // Determine the non-fragile ABI version to use.
3143#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
3144      unsigned nonFragileABIVersion = 1;
3145#else
3146      unsigned nonFragileABIVersion = 2;
3147#endif
3148
3149      if (Arg *abiArg = args.getLastArg(
3150            options::OPT_fobjc_nonfragile_abi_version_EQ)) {
3151        StringRef value = abiArg->getValue();
3152        if (value == "1")
3153          nonFragileABIVersion = 1;
3154        else if (value == "2")
3155          nonFragileABIVersion = 2;
3156        else
3157          getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3158            << value;
3159      }
3160
3161      objcABIVersion = 1 + nonFragileABIVersion;
3162    } else {
3163      objcABIVersion = 1;
3164    }
3165  }
3166
3167  // We don't actually care about the ABI version other than whether
3168  // it's non-fragile.
3169  bool isNonFragile = objcABIVersion != 1;
3170
3171  // If we have no runtime argument, ask the toolchain for its default runtime.
3172  // However, the rewriter only really supports the Mac runtime, so assume that.
3173  ObjCRuntime runtime;
3174  if (!runtimeArg) {
3175    switch (rewriteKind) {
3176    case RK_None:
3177      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3178      break;
3179    case RK_Fragile:
3180      runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
3181      break;
3182    case RK_NonFragile:
3183      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3184      break;
3185    }
3186
3187  // -fnext-runtime
3188  } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
3189    // On Darwin, make this use the default behavior for the toolchain.
3190    if (getToolChain().getTriple().isOSDarwin()) {
3191      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3192
3193    // Otherwise, build for a generic macosx port.
3194    } else {
3195      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3196    }
3197
3198  // -fgnu-runtime
3199  } else {
3200    assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
3201    // Legacy behaviour is to target the gnustep runtime if we are i
3202    // non-fragile mode or the GCC runtime in fragile mode.
3203    if (isNonFragile)
3204      runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
3205    else
3206      runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
3207  }
3208
3209  cmdArgs.push_back(args.MakeArgString(
3210                                 "-fobjc-runtime=" + runtime.getAsString()));
3211  return runtime;
3212}
3213
3214void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
3215                           const InputInfo &Output,
3216                           const InputInfoList &Inputs,
3217                           const ArgList &Args,
3218                           const char *LinkingOutput) const {
3219  ArgStringList CmdArgs;
3220
3221  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
3222  const InputInfo &Input = Inputs[0];
3223
3224  // Don't warn about "clang -w -c foo.s"
3225  Args.ClaimAllArgs(options::OPT_w);
3226  // and "clang -emit-llvm -c foo.s"
3227  Args.ClaimAllArgs(options::OPT_emit_llvm);
3228  // and "clang -use-gold-plugin -c foo.s"
3229  Args.ClaimAllArgs(options::OPT_use_gold_plugin);
3230
3231  // Invoke ourselves in -cc1as mode.
3232  //
3233  // FIXME: Implement custom jobs for internal actions.
3234  CmdArgs.push_back("-cc1as");
3235
3236  // Add the "effective" target triple.
3237  CmdArgs.push_back("-triple");
3238  std::string TripleStr =
3239    getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
3240  CmdArgs.push_back(Args.MakeArgString(TripleStr));
3241
3242  // Set the output mode, we currently only expect to be used as a real
3243  // assembler.
3244  CmdArgs.push_back("-filetype");
3245  CmdArgs.push_back("obj");
3246
3247  if (UseRelaxAll(C, Args))
3248    CmdArgs.push_back("-relax-all");
3249
3250  // Add target specific cpu and features flags.
3251  switch(getToolChain().getTriple().getArch()) {
3252  default:
3253    break;
3254
3255  case llvm::Triple::arm:
3256  case llvm::Triple::thumb:
3257    AddARMTargetArgs(Args, CmdArgs);
3258    break;
3259  }
3260
3261  // Ignore explicit -force_cpusubtype_ALL option.
3262  (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
3263
3264  // Determine the original source input.
3265  const Action *SourceAction = &JA;
3266  while (SourceAction->getKind() != Action::InputClass) {
3267    assert(!SourceAction->getInputs().empty() && "unexpected root action!");
3268    SourceAction = SourceAction->getInputs()[0];
3269  }
3270
3271  // Forward -g, assuming we are dealing with an actual assembly file.
3272  if (SourceAction->getType() == types::TY_Asm ||
3273      SourceAction->getType() == types::TY_PP_Asm) {
3274    Args.ClaimAllArgs(options::OPT_g_Group);
3275    if (Arg *A = Args.getLastArg(options::OPT_g_Group))
3276      if (!A->getOption().matches(options::OPT_g0))
3277        CmdArgs.push_back("-g");
3278  }
3279
3280  // Optionally embed the -cc1as level arguments into the debug info, for build
3281  // analysis.
3282  if (getToolChain().UseDwarfDebugFlags()) {
3283    ArgStringList OriginalArgs;
3284    for (ArgList::const_iterator it = Args.begin(),
3285           ie = Args.end(); it != ie; ++it)
3286      (*it)->render(Args, OriginalArgs);
3287
3288    SmallString<256> Flags;
3289    const char *Exec = getToolChain().getDriver().getClangProgramPath();
3290    Flags += Exec;
3291    for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3292      Flags += " ";
3293      Flags += OriginalArgs[i];
3294    }
3295    CmdArgs.push_back("-dwarf-debug-flags");
3296    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3297  }
3298
3299  // FIXME: Add -static support, once we have it.
3300
3301  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3302                       options::OPT_Xassembler);
3303  Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
3304
3305  assert(Output.isFilename() && "Unexpected lipo output.");
3306  CmdArgs.push_back("-o");
3307  CmdArgs.push_back(Output.getFilename());
3308
3309  assert(Input.isFilename() && "Invalid input.");
3310  CmdArgs.push_back(Input.getFilename());
3311
3312  const char *Exec = getToolChain().getDriver().getClangProgramPath();
3313  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3314}
3315
3316void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
3317                               const InputInfo &Output,
3318                               const InputInfoList &Inputs,
3319                               const ArgList &Args,
3320                               const char *LinkingOutput) const {
3321  const Driver &D = getToolChain().getDriver();
3322  ArgStringList CmdArgs;
3323
3324  for (ArgList::const_iterator
3325         it = Args.begin(), ie = Args.end(); it != ie; ++it) {
3326    Arg *A = *it;
3327    if (forwardToGCC(A->getOption())) {
3328      // Don't forward any -g arguments to assembly steps.
3329      if (isa<AssembleJobAction>(JA) &&
3330          A->getOption().matches(options::OPT_g_Group))
3331        continue;
3332
3333      // It is unfortunate that we have to claim here, as this means
3334      // we will basically never report anything interesting for
3335      // platforms using a generic gcc, even if we are just using gcc
3336      // to get to the assembler.
3337      A->claim();
3338      A->render(Args, CmdArgs);
3339    }
3340  }
3341
3342  RenderExtraToolArgs(JA, CmdArgs);
3343
3344  // If using a driver driver, force the arch.
3345  llvm::Triple::ArchType Arch = getToolChain().getArch();
3346  if (getToolChain().getTriple().isOSDarwin()) {
3347    CmdArgs.push_back("-arch");
3348
3349    // FIXME: Remove these special cases.
3350    if (Arch == llvm::Triple::ppc)
3351      CmdArgs.push_back("ppc");
3352    else if (Arch == llvm::Triple::ppc64)
3353      CmdArgs.push_back("ppc64");
3354    else
3355      CmdArgs.push_back(Args.MakeArgString(getToolChain().getArchName()));
3356  }
3357
3358  // Try to force gcc to match the tool chain we want, if we recognize
3359  // the arch.
3360  //
3361  // FIXME: The triple class should directly provide the information we want
3362  // here.
3363  if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
3364    CmdArgs.push_back("-m32");
3365  else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::x86_64)
3366    CmdArgs.push_back("-m64");
3367
3368  if (Output.isFilename()) {
3369    CmdArgs.push_back("-o");
3370    CmdArgs.push_back(Output.getFilename());
3371  } else {
3372    assert(Output.isNothing() && "Unexpected output");
3373    CmdArgs.push_back("-fsyntax-only");
3374  }
3375
3376  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
3377                       options::OPT_Xassembler);
3378
3379  // Only pass -x if gcc will understand it; otherwise hope gcc
3380  // understands the suffix correctly. The main use case this would go
3381  // wrong in is for linker inputs if they happened to have an odd
3382  // suffix; really the only way to get this to happen is a command
3383  // like '-x foobar a.c' which will treat a.c like a linker input.
3384  //
3385  // FIXME: For the linker case specifically, can we safely convert
3386  // inputs into '-Wl,' options?
3387  for (InputInfoList::const_iterator
3388         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3389    const InputInfo &II = *it;
3390
3391    // Don't try to pass LLVM or AST inputs to a generic gcc.
3392    if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3393        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3394      D.Diag(diag::err_drv_no_linker_llvm_support)
3395        << getToolChain().getTripleString();
3396    else if (II.getType() == types::TY_AST)
3397      D.Diag(diag::err_drv_no_ast_support)
3398        << getToolChain().getTripleString();
3399
3400    if (types::canTypeBeUserSpecified(II.getType())) {
3401      CmdArgs.push_back("-x");
3402      CmdArgs.push_back(types::getTypeName(II.getType()));
3403    }
3404
3405    if (II.isFilename())
3406      CmdArgs.push_back(II.getFilename());
3407    else {
3408      const Arg &A = II.getInputArg();
3409
3410      // Reverse translate some rewritten options.
3411      if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
3412        CmdArgs.push_back("-lstdc++");
3413        continue;
3414      }
3415
3416      // Don't render as input, we need gcc to do the translations.
3417      A.render(Args, CmdArgs);
3418    }
3419  }
3420
3421  const std::string customGCCName = D.getCCCGenericGCCName();
3422  const char *GCCName;
3423  if (!customGCCName.empty())
3424    GCCName = customGCCName.c_str();
3425  else if (D.CCCIsCXX) {
3426    GCCName = "g++";
3427  } else
3428    GCCName = "gcc";
3429
3430  const char *Exec =
3431    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3432  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3433}
3434
3435void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
3436                                          ArgStringList &CmdArgs) const {
3437  CmdArgs.push_back("-E");
3438}
3439
3440void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
3441                                          ArgStringList &CmdArgs) const {
3442  // The type is good enough.
3443}
3444
3445void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
3446                                       ArgStringList &CmdArgs) const {
3447  const Driver &D = getToolChain().getDriver();
3448
3449  // If -flto, etc. are present then make sure not to force assembly output.
3450  if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
3451      JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
3452    CmdArgs.push_back("-c");
3453  else {
3454    if (JA.getType() != types::TY_PP_Asm)
3455      D.Diag(diag::err_drv_invalid_gcc_output_type)
3456        << getTypeName(JA.getType());
3457
3458    CmdArgs.push_back("-S");
3459  }
3460}
3461
3462void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
3463                                        ArgStringList &CmdArgs) const {
3464  CmdArgs.push_back("-c");
3465}
3466
3467void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
3468                                    ArgStringList &CmdArgs) const {
3469  // The types are (hopefully) good enough.
3470}
3471
3472// Hexagon tools start.
3473void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
3474                                        ArgStringList &CmdArgs) const {
3475
3476}
3477void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
3478                               const InputInfo &Output,
3479                               const InputInfoList &Inputs,
3480                               const ArgList &Args,
3481                               const char *LinkingOutput) const {
3482
3483  const Driver &D = getToolChain().getDriver();
3484  ArgStringList CmdArgs;
3485
3486  std::string MarchString = "-march=";
3487  MarchString += getHexagonTargetCPU(Args);
3488  CmdArgs.push_back(Args.MakeArgString(MarchString));
3489
3490  RenderExtraToolArgs(JA, CmdArgs);
3491
3492  if (Output.isFilename()) {
3493    CmdArgs.push_back("-o");
3494    CmdArgs.push_back(Output.getFilename());
3495  } else {
3496    assert(Output.isNothing() && "Unexpected output");
3497    CmdArgs.push_back("-fsyntax-only");
3498  }
3499
3500
3501  // Only pass -x if gcc will understand it; otherwise hope gcc
3502  // understands the suffix correctly. The main use case this would go
3503  // wrong in is for linker inputs if they happened to have an odd
3504  // suffix; really the only way to get this to happen is a command
3505  // like '-x foobar a.c' which will treat a.c like a linker input.
3506  //
3507  // FIXME: For the linker case specifically, can we safely convert
3508  // inputs into '-Wl,' options?
3509  for (InputInfoList::const_iterator
3510         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3511    const InputInfo &II = *it;
3512
3513    // Don't try to pass LLVM or AST inputs to a generic gcc.
3514    if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3515        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3516      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3517        << getToolChain().getTripleString();
3518    else if (II.getType() == types::TY_AST)
3519      D.Diag(clang::diag::err_drv_no_ast_support)
3520        << getToolChain().getTripleString();
3521
3522    if (II.isFilename())
3523      CmdArgs.push_back(II.getFilename());
3524    else
3525      // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
3526      II.getInputArg().render(Args, CmdArgs);
3527  }
3528
3529  const char *GCCName = "hexagon-as";
3530  const char *Exec =
3531    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3532  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3533
3534}
3535void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
3536                                    ArgStringList &CmdArgs) const {
3537  // The types are (hopefully) good enough.
3538}
3539
3540void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
3541                               const InputInfo &Output,
3542                               const InputInfoList &Inputs,
3543                               const ArgList &Args,
3544                               const char *LinkingOutput) const {
3545
3546  const Driver &D = getToolChain().getDriver();
3547  ArgStringList CmdArgs;
3548
3549  for (ArgList::const_iterator
3550         it = Args.begin(), ie = Args.end(); it != ie; ++it) {
3551    Arg *A = *it;
3552    if (forwardToGCC(A->getOption())) {
3553      // Don't forward any -g arguments to assembly steps.
3554      if (isa<AssembleJobAction>(JA) &&
3555          A->getOption().matches(options::OPT_g_Group))
3556        continue;
3557
3558      // It is unfortunate that we have to claim here, as this means
3559      // we will basically never report anything interesting for
3560      // platforms using a generic gcc, even if we are just using gcc
3561      // to get to the assembler.
3562      A->claim();
3563      A->render(Args, CmdArgs);
3564    }
3565  }
3566
3567  RenderExtraToolArgs(JA, CmdArgs);
3568
3569  // Add Arch Information
3570  Arg *A;
3571  if ((A = getLastHexagonArchArg(Args))) {
3572    if (A->getOption().matches(options::OPT_m_Joined))
3573      A->render(Args, CmdArgs);
3574    else
3575      CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
3576  }
3577  else {
3578    CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
3579  }
3580
3581  CmdArgs.push_back("-mqdsp6-compat");
3582
3583  const char *GCCName;
3584  if (C.getDriver().CCCIsCXX)
3585    GCCName = "hexagon-g++";
3586  else
3587    GCCName = "hexagon-gcc";
3588  const char *Exec =
3589    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
3590
3591  if (Output.isFilename()) {
3592    CmdArgs.push_back("-o");
3593    CmdArgs.push_back(Output.getFilename());
3594  }
3595
3596  for (InputInfoList::const_iterator
3597         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3598    const InputInfo &II = *it;
3599
3600    // Don't try to pass LLVM or AST inputs to a generic gcc.
3601    if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
3602        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
3603      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
3604        << getToolChain().getTripleString();
3605    else if (II.getType() == types::TY_AST)
3606      D.Diag(clang::diag::err_drv_no_ast_support)
3607        << getToolChain().getTripleString();
3608
3609    if (II.isFilename())
3610      CmdArgs.push_back(II.getFilename());
3611    else
3612      // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
3613      II.getInputArg().render(Args, CmdArgs);
3614  }
3615  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3616
3617}
3618// Hexagon tools end.
3619
3620llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Str) {
3621  // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
3622  // archs which Darwin doesn't use.
3623
3624  // The matching this routine does is fairly pointless, since it is neither the
3625  // complete architecture list, nor a reasonable subset. The problem is that
3626  // historically the driver driver accepts this and also ties its -march=
3627  // handling to the architecture name, so we need to be careful before removing
3628  // support for it.
3629
3630  // This code must be kept in sync with Clang's Darwin specific argument
3631  // translation.
3632
3633  return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
3634    .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
3635    .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
3636    .Case("ppc64", llvm::Triple::ppc64)
3637    .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
3638    .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
3639           llvm::Triple::x86)
3640    .Case("x86_64", llvm::Triple::x86_64)
3641    // This is derived from the driver driver.
3642    .Cases("arm", "armv4t", "armv5", "armv6", llvm::Triple::arm)
3643    .Cases("armv7", "armv7f", "armv7k", "armv7s", "xscale", llvm::Triple::arm)
3644    .Case("r600", llvm::Triple::r600)
3645    .Case("nvptx", llvm::Triple::nvptx)
3646    .Case("nvptx64", llvm::Triple::nvptx64)
3647    .Case("amdil", llvm::Triple::amdil)
3648    .Case("spir", llvm::Triple::spir)
3649    .Default(llvm::Triple::UnknownArch);
3650}
3651
3652const char *darwin::CC1::getCC1Name(types::ID Type) const {
3653  switch (Type) {
3654  default:
3655    llvm_unreachable("Unexpected type for Darwin CC1 tool.");
3656  case types::TY_Asm:
3657  case types::TY_C: case types::TY_CHeader:
3658  case types::TY_PP_C: case types::TY_PP_CHeader:
3659    return "cc1";
3660  case types::TY_ObjC: case types::TY_ObjCHeader:
3661  case types::TY_PP_ObjC: case types::TY_PP_ObjC_Alias:
3662  case types::TY_PP_ObjCHeader:
3663    return "cc1obj";
3664  case types::TY_CXX: case types::TY_CXXHeader:
3665  case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
3666    return "cc1plus";
3667  case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
3668  case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXX_Alias:
3669  case types::TY_PP_ObjCXXHeader:
3670    return "cc1objplus";
3671  }
3672}
3673
3674void darwin::CC1::anchor() {}
3675
3676const char *darwin::CC1::getBaseInputName(const ArgList &Args,
3677                                          const InputInfoList &Inputs) {
3678  return Args.MakeArgString(
3679    llvm::sys::path::filename(Inputs[0].getBaseInput()));
3680}
3681
3682const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
3683                                          const InputInfoList &Inputs) {
3684  const char *Str = getBaseInputName(Args, Inputs);
3685
3686  if (const char *End = strrchr(Str, '.'))
3687    return Args.MakeArgString(std::string(Str, End));
3688
3689  return Str;
3690}
3691
3692const char *
3693darwin::CC1::getDependencyFileName(const ArgList &Args,
3694                                   const InputInfoList &Inputs) {
3695  // FIXME: Think about this more.
3696  std::string Res;
3697
3698  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
3699    std::string Str(OutputOpt->getValue());
3700    Res = Str.substr(0, Str.rfind('.'));
3701  } else {
3702    Res = darwin::CC1::getBaseInputStem(Args, Inputs);
3703  }
3704  return Args.MakeArgString(Res + ".d");
3705}
3706
3707void darwin::CC1::RemoveCC1UnsupportedArgs(ArgStringList &CmdArgs) const {
3708  for (ArgStringList::iterator it = CmdArgs.begin(), ie = CmdArgs.end();
3709       it != ie;) {
3710
3711    StringRef Option = *it;
3712    bool RemoveOption = false;
3713
3714    // Erase both -fmodule-cache-path and its argument.
3715    if (Option.equals("-fmodule-cache-path") && it+2 != ie) {
3716      it = CmdArgs.erase(it, it+2);
3717      ie = CmdArgs.end();
3718      continue;
3719    }
3720
3721    // Remove unsupported -f options.
3722    if (Option.startswith("-f")) {
3723      // Remove -f/-fno- to reduce the number of cases.
3724      if (Option.startswith("-fno-"))
3725        Option = Option.substr(5);
3726      else
3727        Option = Option.substr(2);
3728      RemoveOption = llvm::StringSwitch<bool>(Option)
3729        .Case("altivec", true)
3730        .Case("modules", true)
3731        .Case("diagnostics-show-note-include-stack", true)
3732        .Default(false);
3733    }
3734
3735    // Handle machine specific options.
3736    if (Option.startswith("-m")) {
3737      RemoveOption = llvm::StringSwitch<bool>(Option)
3738        .Case("-mthumb", true)
3739        .Case("-mno-thumb", true)
3740        .Case("-mno-fused-madd", true)
3741        .Case("-mlong-branch", true)
3742        .Case("-mlongcall", true)
3743        .Case("-mcpu=G4", true)
3744        .Case("-mcpu=G5", true)
3745        .Default(false);
3746    }
3747
3748    // Handle warning options.
3749    if (Option.startswith("-W")) {
3750      // Remove -W/-Wno- to reduce the number of cases.
3751      if (Option.startswith("-Wno-"))
3752        Option = Option.substr(5);
3753      else
3754        Option = Option.substr(2);
3755
3756      RemoveOption = llvm::StringSwitch<bool>(Option)
3757        .Case("address-of-temporary", true)
3758        .Case("ambiguous-member-template", true)
3759        .Case("analyzer-incompatible-plugin", true)
3760        .Case("array-bounds", true)
3761        .Case("array-bounds-pointer-arithmetic", true)
3762        .Case("bind-to-temporary-copy", true)
3763        .Case("bitwise-op-parentheses", true)
3764        .Case("bool-conversions", true)
3765        .Case("builtin-macro-redefined", true)
3766        .Case("c++-hex-floats", true)
3767        .Case("c++0x-compat", true)
3768        .Case("c++0x-extensions", true)
3769        .Case("c++0x-narrowing", true)
3770        .Case("c++11-compat", true)
3771        .Case("c++11-extensions", true)
3772        .Case("c++11-narrowing", true)
3773        .Case("conditional-uninitialized", true)
3774        .Case("constant-conversion", true)
3775        .Case("conversion-null", true)
3776        .Case("CFString-literal", true)
3777        .Case("constant-logical-operand", true)
3778        .Case("custom-atomic-properties", true)
3779        .Case("default-arg-special-member", true)
3780        .Case("delegating-ctor-cycles", true)
3781        .Case("delete-non-virtual-dtor", true)
3782        .Case("deprecated-implementations", true)
3783        .Case("deprecated-writable-strings", true)
3784        .Case("distributed-object-modifiers", true)
3785        .Case("duplicate-method-arg", true)
3786        .Case("dynamic-class-memaccess", true)
3787        .Case("enum-compare", true)
3788        .Case("enum-conversion", true)
3789        .Case("exit-time-destructors", true)
3790        .Case("gnu", true)
3791        .Case("gnu-designator", true)
3792        .Case("header-hygiene", true)
3793        .Case("idiomatic-parentheses", true)
3794        .Case("ignored-qualifiers", true)
3795        .Case("implicit-atomic-properties", true)
3796        .Case("incompatible-pointer-types", true)
3797        .Case("incomplete-implementation", true)
3798        .Case("int-conversion", true)
3799        .Case("initializer-overrides", true)
3800        .Case("invalid-noreturn", true)
3801        .Case("invalid-token-paste", true)
3802        .Case("language-extension-token", true)
3803        .Case("literal-conversion", true)
3804        .Case("literal-range", true)
3805        .Case("local-type-template-args", true)
3806        .Case("logical-op-parentheses", true)
3807        .Case("method-signatures", true)
3808        .Case("microsoft", true)
3809        .Case("mismatched-tags", true)
3810        .Case("missing-method-return-type", true)
3811        .Case("non-pod-varargs", true)
3812        .Case("nonfragile-abi2", true)
3813        .Case("null-arithmetic", true)
3814        .Case("null-dereference", true)
3815        .Case("out-of-line-declaration", true)
3816        .Case("overriding-method-mismatch", true)
3817        .Case("readonly-setter-attrs", true)
3818        .Case("return-stack-address", true)
3819        .Case("self-assign", true)
3820        .Case("semicolon-before-method-body", true)
3821        .Case("sentinel", true)
3822        .Case("shift-overflow", true)
3823        .Case("shift-sign-overflow", true)
3824        .Case("sign-conversion", true)
3825        .Case("sizeof-array-argument", true)
3826        .Case("sizeof-pointer-memaccess", true)
3827        .Case("string-compare", true)
3828        .Case("super-class-method-mismatch", true)
3829        .Case("tautological-compare", true)
3830        .Case("typedef-redefinition", true)
3831        .Case("typename-missing", true)
3832        .Case("undefined-reinterpret-cast", true)
3833        .Case("unknown-warning-option", true)
3834        .Case("unnamed-type-template-args", true)
3835        .Case("unneeded-internal-declaration", true)
3836        .Case("unneeded-member-function", true)
3837        .Case("unused-comparison", true)
3838        .Case("unused-exception-parameter", true)
3839        .Case("unused-member-function", true)
3840        .Case("unused-result", true)
3841        .Case("vector-conversions", true)
3842        .Case("vla", true)
3843        .Case("used-but-marked-unused", true)
3844        .Case("weak-vtables", true)
3845        .Default(false);
3846    } // if (Option.startswith("-W"))
3847    if (RemoveOption) {
3848      it = CmdArgs.erase(it);
3849      ie = CmdArgs.end();
3850    } else {
3851      ++it;
3852    }
3853  }
3854}
3855
3856void darwin::CC1::AddCC1Args(const ArgList &Args,
3857                             ArgStringList &CmdArgs) const {
3858  const Driver &D = getToolChain().getDriver();
3859
3860  CheckCodeGenerationOptions(D, Args);
3861
3862  // Derived from cc1 spec.
3863  if ((!Args.hasArg(options::OPT_mkernel) ||
3864       (getDarwinToolChain().isTargetIPhoneOS() &&
3865        !getDarwinToolChain().isIPhoneOSVersionLT(6, 0))) &&
3866      !Args.hasArg(options::OPT_static) &&
3867      !Args.hasArg(options::OPT_mdynamic_no_pic))
3868    CmdArgs.push_back("-fPIC");
3869
3870  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
3871      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
3872    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
3873      CmdArgs.push_back("-fno-builtin-strcat");
3874    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
3875      CmdArgs.push_back("-fno-builtin-strcpy");
3876  }
3877
3878  if (Args.hasArg(options::OPT_g_Flag) &&
3879      !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
3880    CmdArgs.push_back("-feliminate-unused-debug-symbols");
3881}
3882
3883void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
3884                                    const InputInfoList &Inputs,
3885                                    const ArgStringList &OutputArgs) const {
3886  const Driver &D = getToolChain().getDriver();
3887
3888  // Derived from cc1_options spec.
3889  if (Args.hasArg(options::OPT_fast) ||
3890      Args.hasArg(options::OPT_fastf) ||
3891      Args.hasArg(options::OPT_fastcp))
3892    CmdArgs.push_back("-O3");
3893
3894  if (Arg *A = Args.getLastArg(options::OPT_pg))
3895    if (Args.hasArg(options::OPT_fomit_frame_pointer))
3896      D.Diag(diag::err_drv_argument_not_allowed_with)
3897        << A->getAsString(Args) << "-fomit-frame-pointer";
3898
3899  AddCC1Args(Args, CmdArgs);
3900
3901  if (!Args.hasArg(options::OPT_Q))
3902    CmdArgs.push_back("-quiet");
3903
3904  CmdArgs.push_back("-dumpbase");
3905  CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
3906
3907  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
3908
3909  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
3910  Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
3911
3912  // FIXME: The goal is to use the user provided -o if that is our
3913  // final output, otherwise to drive from the original input
3914  // name. Find a clean way to go about this.
3915  if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
3916      Args.hasArg(options::OPT_o)) {
3917    Arg *OutputOpt = Args.getLastArg(options::OPT_o);
3918    CmdArgs.push_back("-auxbase-strip");
3919    CmdArgs.push_back(OutputOpt->getValue());
3920  } else {
3921    CmdArgs.push_back("-auxbase");
3922    CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
3923  }
3924
3925  Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
3926
3927  Args.AddAllArgs(CmdArgs, options::OPT_O);
3928  // FIXME: -Wall is getting some special treatment. Investigate.
3929  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
3930  Args.AddLastArg(CmdArgs, options::OPT_w);
3931  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
3932                  options::OPT_trigraphs);
3933  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3934    // Honor -std-default.
3935    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3936                              "-std=", /*Joined=*/true);
3937  }
3938
3939  if (Args.hasArg(options::OPT_v))
3940    CmdArgs.push_back("-version");
3941  if (Args.hasArg(options::OPT_pg) &&
3942      getToolChain().SupportsProfiling())
3943    CmdArgs.push_back("-p");
3944  Args.AddLastArg(CmdArgs, options::OPT_p);
3945
3946  // The driver treats -fsyntax-only specially.
3947  if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
3948      getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
3949    // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
3950    // used to inhibit the default -fno-builtin-str{cat,cpy}.
3951    //
3952    // FIXME: Should we grow a better way to deal with "removing" args?
3953    for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
3954                                               options::OPT_fsyntax_only),
3955           ie = Args.filtered_end(); it != ie; ++it) {
3956      if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) &&
3957          !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) {
3958        (*it)->claim();
3959        (*it)->render(Args, CmdArgs);
3960      }
3961    }
3962  } else
3963    Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
3964
3965  // Claim Clang only -f options, they aren't worth warning about.
3966  Args.ClaimAllArgs(options::OPT_f_clang_Group);
3967
3968  Args.AddAllArgs(CmdArgs, options::OPT_undef);
3969  if (Args.hasArg(options::OPT_Qn))
3970    CmdArgs.push_back("-fno-ident");
3971
3972  // FIXME: This isn't correct.
3973  //Args.AddLastArg(CmdArgs, options::OPT__help)
3974  //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
3975
3976  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
3977
3978  // FIXME: Still don't get what is happening here. Investigate.
3979  Args.AddAllArgs(CmdArgs, options::OPT__param);
3980
3981  if (Args.hasArg(options::OPT_fmudflap) ||
3982      Args.hasArg(options::OPT_fmudflapth)) {
3983    CmdArgs.push_back("-fno-builtin");
3984    CmdArgs.push_back("-fno-merge-constants");
3985  }
3986
3987  if (Args.hasArg(options::OPT_coverage)) {
3988    CmdArgs.push_back("-fprofile-arcs");
3989    CmdArgs.push_back("-ftest-coverage");
3990  }
3991
3992  if (types::isCXX(Inputs[0].getType()))
3993    CmdArgs.push_back("-D__private_extern__=extern");
3994}
3995
3996void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
3997                                    const InputInfoList &Inputs,
3998                                    const ArgStringList &OutputArgs) const {
3999  // Derived from cpp_options
4000  AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
4001
4002  CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
4003
4004  AddCC1Args(Args, CmdArgs);
4005
4006  // NOTE: The code below has some commonality with cpp_options, but
4007  // in classic gcc style ends up sending things in different
4008  // orders. This may be a good merge candidate once we drop pedantic
4009  // compatibility.
4010
4011  Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
4012  Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
4013                  options::OPT_trigraphs);
4014  if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4015    // Honor -std-default.
4016    Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
4017                              "-std=", /*Joined=*/true);
4018  }
4019  Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
4020  Args.AddLastArg(CmdArgs, options::OPT_w);
4021
4022  // The driver treats -fsyntax-only specially.
4023  Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
4024
4025  // Claim Clang only -f options, they aren't worth warning about.
4026  Args.ClaimAllArgs(options::OPT_f_clang_Group);
4027
4028  if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
4029      !Args.hasArg(options::OPT_fno_working_directory))
4030    CmdArgs.push_back("-fworking-directory");
4031
4032  Args.AddAllArgs(CmdArgs, options::OPT_O);
4033  Args.AddAllArgs(CmdArgs, options::OPT_undef);
4034  if (Args.hasArg(options::OPT_save_temps))
4035    CmdArgs.push_back("-fpch-preprocess");
4036}
4037
4038void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
4039                                          ArgStringList &CmdArgs,
4040                                          const InputInfoList &Inputs) const {
4041  const Driver &D = getToolChain().getDriver();
4042
4043  CheckPreprocessingOptions(D, Args);
4044
4045  // Derived from cpp_unique_options.
4046  // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
4047  Args.AddLastArg(CmdArgs, options::OPT_C);
4048  Args.AddLastArg(CmdArgs, options::OPT_CC);
4049  if (!Args.hasArg(options::OPT_Q))
4050    CmdArgs.push_back("-quiet");
4051  Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
4052  Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
4053  Args.AddLastArg(CmdArgs, options::OPT_v);
4054  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
4055  Args.AddLastArg(CmdArgs, options::OPT_P);
4056
4057  // FIXME: Handle %I properly.
4058  if (getToolChain().getArch() == llvm::Triple::x86_64) {
4059    CmdArgs.push_back("-imultilib");
4060    CmdArgs.push_back("x86_64");
4061  }
4062
4063  if (Args.hasArg(options::OPT_MD)) {
4064    CmdArgs.push_back("-MD");
4065    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
4066  }
4067
4068  if (Args.hasArg(options::OPT_MMD)) {
4069    CmdArgs.push_back("-MMD");
4070    CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
4071  }
4072
4073  Args.AddLastArg(CmdArgs, options::OPT_M);
4074  Args.AddLastArg(CmdArgs, options::OPT_MM);
4075  Args.AddAllArgs(CmdArgs, options::OPT_MF);
4076  Args.AddLastArg(CmdArgs, options::OPT_MG);
4077  Args.AddLastArg(CmdArgs, options::OPT_MP);
4078  Args.AddAllArgs(CmdArgs, options::OPT_MQ);
4079  Args.AddAllArgs(CmdArgs, options::OPT_MT);
4080  if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
4081      (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
4082    if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4083      CmdArgs.push_back("-MQ");
4084      CmdArgs.push_back(OutputOpt->getValue());
4085    }
4086  }
4087
4088  Args.AddLastArg(CmdArgs, options::OPT_remap);
4089  if (Args.hasArg(options::OPT_g3))
4090    CmdArgs.push_back("-dD");
4091  Args.AddLastArg(CmdArgs, options::OPT_H);
4092
4093  AddCPPArgs(Args, CmdArgs);
4094
4095  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
4096  Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
4097
4098  for (InputInfoList::const_iterator
4099         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4100    const InputInfo &II = *it;
4101
4102    CmdArgs.push_back(II.getFilename());
4103  }
4104
4105  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
4106                       options::OPT_Xpreprocessor);
4107
4108  if (Args.hasArg(options::OPT_fmudflap)) {
4109    CmdArgs.push_back("-D_MUDFLAP");
4110    CmdArgs.push_back("-include");
4111    CmdArgs.push_back("mf-runtime.h");
4112  }
4113
4114  if (Args.hasArg(options::OPT_fmudflapth)) {
4115    CmdArgs.push_back("-D_MUDFLAP");
4116    CmdArgs.push_back("-D_MUDFLAPTH");
4117    CmdArgs.push_back("-include");
4118    CmdArgs.push_back("mf-runtime.h");
4119  }
4120}
4121
4122void darwin::CC1::AddCPPArgs(const ArgList &Args,
4123                             ArgStringList &CmdArgs) const {
4124  // Derived from cpp spec.
4125
4126  if (Args.hasArg(options::OPT_static)) {
4127    // The gcc spec is broken here, it refers to dynamic but
4128    // that has been translated. Start by being bug compatible.
4129
4130    // if (!Args.hasArg(arglist.parser.dynamicOption))
4131    CmdArgs.push_back("-D__STATIC__");
4132  } else
4133    CmdArgs.push_back("-D__DYNAMIC__");
4134
4135  if (Args.hasArg(options::OPT_pthread))
4136    CmdArgs.push_back("-D_REENTRANT");
4137}
4138
4139void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
4140                                      const InputInfo &Output,
4141                                      const InputInfoList &Inputs,
4142                                      const ArgList &Args,
4143                                      const char *LinkingOutput) const {
4144  ArgStringList CmdArgs;
4145
4146  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
4147
4148  CmdArgs.push_back("-E");
4149
4150  if (Args.hasArg(options::OPT_traditional) ||
4151      Args.hasArg(options::OPT_traditional_cpp))
4152    CmdArgs.push_back("-traditional-cpp");
4153
4154  ArgStringList OutputArgs;
4155  assert(Output.isFilename() && "Unexpected CC1 output.");
4156  OutputArgs.push_back("-o");
4157  OutputArgs.push_back(Output.getFilename());
4158
4159  if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) {
4160    AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
4161  } else {
4162    AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
4163    CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
4164  }
4165
4166  Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
4167
4168  RemoveCC1UnsupportedArgs(CmdArgs);
4169
4170  const char *CC1Name = getCC1Name(Inputs[0].getType());
4171  const char *Exec =
4172    Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
4173  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4174}
4175
4176void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
4177                                   const InputInfo &Output,
4178                                   const InputInfoList &Inputs,
4179                                   const ArgList &Args,
4180                                   const char *LinkingOutput) const {
4181  const Driver &D = getToolChain().getDriver();
4182  ArgStringList CmdArgs;
4183
4184  assert(Inputs.size() == 1 && "Unexpected number of inputs!");
4185
4186  // Silence warning about unused --serialize-diagnostics
4187  Args.ClaimAllArgs(options::OPT__serialize_diags);
4188
4189  types::ID InputType = Inputs[0].getType();
4190  if (const Arg *A = Args.getLastArg(options::OPT_traditional))
4191    D.Diag(diag::err_drv_argument_only_allowed_with)
4192      << A->getAsString(Args) << "-E";
4193
4194  if (JA.getType() == types::TY_LLVM_IR ||
4195      JA.getType() == types::TY_LTO_IR)
4196    CmdArgs.push_back("-emit-llvm");
4197  else if (JA.getType() == types::TY_LLVM_BC ||
4198           JA.getType() == types::TY_LTO_BC)
4199    CmdArgs.push_back("-emit-llvm-bc");
4200  else if (Output.getType() == types::TY_AST)
4201    D.Diag(diag::err_drv_no_ast_support)
4202      << getToolChain().getTripleString();
4203  else if (JA.getType() != types::TY_PP_Asm &&
4204           JA.getType() != types::TY_PCH)
4205    D.Diag(diag::err_drv_invalid_gcc_output_type)
4206      << getTypeName(JA.getType());
4207
4208  ArgStringList OutputArgs;
4209  if (Output.getType() != types::TY_PCH) {
4210    OutputArgs.push_back("-o");
4211    if (Output.isNothing())
4212      OutputArgs.push_back("/dev/null");
4213    else
4214      OutputArgs.push_back(Output.getFilename());
4215  }
4216
4217  // There is no need for this level of compatibility, but it makes
4218  // diffing easier.
4219  bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
4220                          Args.hasArg(options::OPT_S));
4221
4222  if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
4223    AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
4224    if (OutputArgsEarly) {
4225      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
4226    } else {
4227      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
4228      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
4229    }
4230  } else {
4231    CmdArgs.push_back("-fpreprocessed");
4232
4233    for (InputInfoList::const_iterator
4234           it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4235      const InputInfo &II = *it;
4236
4237      // Reject AST inputs.
4238      if (II.getType() == types::TY_AST) {
4239        D.Diag(diag::err_drv_no_ast_support)
4240          << getToolChain().getTripleString();
4241        return;
4242      }
4243
4244      CmdArgs.push_back(II.getFilename());
4245    }
4246
4247    if (OutputArgsEarly) {
4248      AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
4249    } else {
4250      AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
4251      CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
4252    }
4253  }
4254
4255  if (Output.getType() == types::TY_PCH) {
4256    assert(Output.isFilename() && "Invalid PCH output.");
4257
4258    CmdArgs.push_back("-o");
4259    // NOTE: gcc uses a temp .s file for this, but there doesn't seem
4260    // to be a good reason.
4261    const char *TmpPath = C.getArgs().MakeArgString(
4262      D.GetTemporaryPath("cc", "s"));
4263    C.addTempFile(TmpPath);
4264    CmdArgs.push_back(TmpPath);
4265
4266    // If we're emitting a pch file with the last 4 characters of ".pth"
4267    // and falling back to llvm-gcc we want to use ".gch" instead.
4268    std::string OutputFile(Output.getFilename());
4269    size_t loc = OutputFile.rfind(".pth");
4270    if (loc != std::string::npos)
4271      OutputFile.replace(loc, 4, ".gch");
4272    const char *Tmp = C.getArgs().MakeArgString("--output-pch="+OutputFile);
4273    CmdArgs.push_back(Tmp);
4274  }
4275
4276  RemoveCC1UnsupportedArgs(CmdArgs);
4277
4278  const char *CC1Name = getCC1Name(Inputs[0].getType());
4279  const char *Exec =
4280    Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
4281  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4282}
4283
4284void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4285                                    const InputInfo &Output,
4286                                    const InputInfoList &Inputs,
4287                                    const ArgList &Args,
4288                                    const char *LinkingOutput) const {
4289  ArgStringList CmdArgs;
4290
4291  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4292  const InputInfo &Input = Inputs[0];
4293
4294  // Determine the original source input.
4295  const Action *SourceAction = &JA;
4296  while (SourceAction->getKind() != Action::InputClass) {
4297    assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4298    SourceAction = SourceAction->getInputs()[0];
4299  }
4300
4301  // Forward -g, assuming we are dealing with an actual assembly file.
4302  if (SourceAction->getType() == types::TY_Asm ||
4303      SourceAction->getType() == types::TY_PP_Asm) {
4304    if (Args.hasArg(options::OPT_gstabs))
4305      CmdArgs.push_back("--gstabs");
4306    else if (Args.hasArg(options::OPT_g_Group))
4307      CmdArgs.push_back("-g");
4308  }
4309
4310  // Derived from asm spec.
4311  AddDarwinArch(Args, CmdArgs);
4312
4313  // Use -force_cpusubtype_ALL on x86 by default.
4314  if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
4315      getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
4316      Args.hasArg(options::OPT_force__cpusubtype__ALL))
4317    CmdArgs.push_back("-force_cpusubtype_ALL");
4318
4319  if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
4320      (((Args.hasArg(options::OPT_mkernel) ||
4321         Args.hasArg(options::OPT_fapple_kext)) &&
4322        (!getDarwinToolChain().isTargetIPhoneOS() ||
4323         getDarwinToolChain().isIPhoneOSVersionLT(6, 0))) ||
4324       Args.hasArg(options::OPT_static)))
4325    CmdArgs.push_back("-static");
4326
4327  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4328                       options::OPT_Xassembler);
4329
4330  assert(Output.isFilename() && "Unexpected lipo output.");
4331  CmdArgs.push_back("-o");
4332  CmdArgs.push_back(Output.getFilename());
4333
4334  assert(Input.isFilename() && "Invalid input.");
4335  CmdArgs.push_back(Input.getFilename());
4336
4337  // asm_final spec is empty.
4338
4339  const char *Exec =
4340    Args.MakeArgString(getToolChain().GetProgramPath("as"));
4341  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4342}
4343
4344void darwin::DarwinTool::anchor() {}
4345
4346void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
4347                                       ArgStringList &CmdArgs) const {
4348  StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
4349
4350  // Derived from darwin_arch spec.
4351  CmdArgs.push_back("-arch");
4352  CmdArgs.push_back(Args.MakeArgString(ArchName));
4353
4354  // FIXME: Is this needed anymore?
4355  if (ArchName == "arm")
4356    CmdArgs.push_back("-force_cpusubtype_ALL");
4357}
4358
4359bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
4360  // We only need to generate a temp path for LTO if we aren't compiling object
4361  // files. When compiling source files, we run 'dsymutil' after linking. We
4362  // don't run 'dsymutil' when compiling object files.
4363  for (InputInfoList::const_iterator
4364         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it)
4365    if (it->getType() != types::TY_Object)
4366      return true;
4367
4368  return false;
4369}
4370
4371void darwin::Link::AddLinkArgs(Compilation &C,
4372                               const ArgList &Args,
4373                               ArgStringList &CmdArgs,
4374                               const InputInfoList &Inputs) const {
4375  const Driver &D = getToolChain().getDriver();
4376  const toolchains::Darwin &DarwinTC = getDarwinToolChain();
4377
4378  unsigned Version[3] = { 0, 0, 0 };
4379  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4380    bool HadExtra;
4381    if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
4382                                   Version[1], Version[2], HadExtra) ||
4383        HadExtra)
4384      D.Diag(diag::err_drv_invalid_version_number)
4385        << A->getAsString(Args);
4386  }
4387
4388  // Newer linkers support -demangle, pass it if supported and not disabled by
4389  // the user.
4390  if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
4391    // Don't pass -demangle to ld_classic.
4392    //
4393    // FIXME: This is a temporary workaround, ld should be handling this.
4394    bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
4395                          Args.hasArg(options::OPT_static));
4396    if (getToolChain().getArch() == llvm::Triple::x86) {
4397      for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
4398                                                 options::OPT_Wl_COMMA),
4399             ie = Args.filtered_end(); it != ie; ++it) {
4400        const Arg *A = *it;
4401        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
4402          if (StringRef(A->getValue(i)) == "-kext")
4403            UsesLdClassic = true;
4404      }
4405    }
4406    if (!UsesLdClassic)
4407      CmdArgs.push_back("-demangle");
4408  }
4409
4410  // If we are using LTO, then automatically create a temporary file path for
4411  // the linker to use, so that it's lifetime will extend past a possible
4412  // dsymutil step.
4413  if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
4414    const char *TmpPath = C.getArgs().MakeArgString(
4415      D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
4416    C.addTempFile(TmpPath);
4417    CmdArgs.push_back("-object_path_lto");
4418    CmdArgs.push_back(TmpPath);
4419  }
4420
4421  // Derived from the "link" spec.
4422  Args.AddAllArgs(CmdArgs, options::OPT_static);
4423  if (!Args.hasArg(options::OPT_static))
4424    CmdArgs.push_back("-dynamic");
4425  if (Args.hasArg(options::OPT_fgnu_runtime)) {
4426    // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
4427    // here. How do we wish to handle such things?
4428  }
4429
4430  if (!Args.hasArg(options::OPT_dynamiclib)) {
4431    AddDarwinArch(Args, CmdArgs);
4432    // FIXME: Why do this only on this path?
4433    Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
4434
4435    Args.AddLastArg(CmdArgs, options::OPT_bundle);
4436    Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
4437    Args.AddAllArgs(CmdArgs, options::OPT_client__name);
4438
4439    Arg *A;
4440    if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
4441        (A = Args.getLastArg(options::OPT_current__version)) ||
4442        (A = Args.getLastArg(options::OPT_install__name)))
4443      D.Diag(diag::err_drv_argument_only_allowed_with)
4444        << A->getAsString(Args) << "-dynamiclib";
4445
4446    Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
4447    Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
4448    Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
4449  } else {
4450    CmdArgs.push_back("-dylib");
4451
4452    Arg *A;
4453    if ((A = Args.getLastArg(options::OPT_bundle)) ||
4454        (A = Args.getLastArg(options::OPT_bundle__loader)) ||
4455        (A = Args.getLastArg(options::OPT_client__name)) ||
4456        (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
4457        (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
4458        (A = Args.getLastArg(options::OPT_private__bundle)))
4459      D.Diag(diag::err_drv_argument_not_allowed_with)
4460        << A->getAsString(Args) << "-dynamiclib";
4461
4462    Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
4463                              "-dylib_compatibility_version");
4464    Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
4465                              "-dylib_current_version");
4466
4467    AddDarwinArch(Args, CmdArgs);
4468
4469    Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
4470                              "-dylib_install_name");
4471  }
4472
4473  Args.AddLastArg(CmdArgs, options::OPT_all__load);
4474  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
4475  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
4476  if (DarwinTC.isTargetIPhoneOS())
4477    Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
4478  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
4479  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
4480  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
4481  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
4482  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
4483  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
4484  Args.AddAllArgs(CmdArgs, options::OPT_force__load);
4485  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
4486  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
4487  Args.AddAllArgs(CmdArgs, options::OPT_init);
4488
4489  // Add the deployment target.
4490  VersionTuple TargetVersion = DarwinTC.getTargetVersion();
4491
4492  // If we had an explicit -mios-simulator-version-min argument, honor that,
4493  // otherwise use the traditional deployment targets. We can't just check the
4494  // is-sim attribute because existing code follows this path, and the linker
4495  // may not handle the argument.
4496  //
4497  // FIXME: We may be able to remove this, once we can verify no one depends on
4498  // it.
4499  if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
4500    CmdArgs.push_back("-ios_simulator_version_min");
4501  else if (DarwinTC.isTargetIPhoneOS())
4502    CmdArgs.push_back("-iphoneos_version_min");
4503  else
4504    CmdArgs.push_back("-macosx_version_min");
4505  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
4506
4507  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
4508  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
4509  Args.AddLastArg(CmdArgs, options::OPT_single__module);
4510  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
4511  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
4512
4513  if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
4514                                     options::OPT_fno_pie,
4515                                     options::OPT_fno_PIE)) {
4516    if (A->getOption().matches(options::OPT_fpie) ||
4517        A->getOption().matches(options::OPT_fPIE))
4518      CmdArgs.push_back("-pie");
4519    else
4520      CmdArgs.push_back("-no_pie");
4521  }
4522
4523  Args.AddLastArg(CmdArgs, options::OPT_prebind);
4524  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
4525  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
4526  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
4527  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
4528  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
4529  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
4530  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
4531  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
4532  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
4533  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
4534  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
4535  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
4536  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
4537  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
4538  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
4539
4540  // Give --sysroot= preference, over the Apple specific behavior to also use
4541  // --isysroot as the syslibroot.
4542  StringRef sysroot = C.getSysRoot();
4543  if (sysroot != "") {
4544    CmdArgs.push_back("-syslibroot");
4545    CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
4546  } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4547    CmdArgs.push_back("-syslibroot");
4548    CmdArgs.push_back(A->getValue());
4549  }
4550
4551  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
4552  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
4553  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
4554  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
4555  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
4556  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
4557  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
4558  Args.AddAllArgs(CmdArgs, options::OPT_y);
4559  Args.AddLastArg(CmdArgs, options::OPT_w);
4560  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
4561  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
4562  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
4563  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
4564  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
4565  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
4566  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
4567  Args.AddLastArg(CmdArgs, options::OPT_whyload);
4568  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
4569  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
4570  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
4571  Args.AddLastArg(CmdArgs, options::OPT_Mach);
4572}
4573
4574void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
4575                                const InputInfo &Output,
4576                                const InputInfoList &Inputs,
4577                                const ArgList &Args,
4578                                const char *LinkingOutput) const {
4579  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
4580
4581  // The logic here is derived from gcc's behavior; most of which
4582  // comes from specs (starting with link_command). Consult gcc for
4583  // more information.
4584  ArgStringList CmdArgs;
4585
4586  /// Hack(tm) to ignore linking errors when we are doing ARC migration.
4587  if (Args.hasArg(options::OPT_ccc_arcmt_check,
4588                  options::OPT_ccc_arcmt_migrate)) {
4589    for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
4590      (*I)->claim();
4591    const char *Exec =
4592      Args.MakeArgString(getToolChain().GetProgramPath("touch"));
4593    CmdArgs.push_back(Output.getFilename());
4594    C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4595    return;
4596  }
4597
4598  // I'm not sure why this particular decomposition exists in gcc, but
4599  // we follow suite for ease of comparison.
4600  AddLinkArgs(C, Args, CmdArgs, Inputs);
4601
4602  Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
4603  Args.AddAllArgs(CmdArgs, options::OPT_s);
4604  Args.AddAllArgs(CmdArgs, options::OPT_t);
4605  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
4606  Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4607  Args.AddLastArg(CmdArgs, options::OPT_e);
4608  Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
4609  Args.AddAllArgs(CmdArgs, options::OPT_r);
4610
4611  // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
4612  // members of static archive libraries which implement Objective-C classes or
4613  // categories.
4614  if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
4615    CmdArgs.push_back("-ObjC");
4616
4617  CmdArgs.push_back("-o");
4618  CmdArgs.push_back(Output.getFilename());
4619
4620  if (!Args.hasArg(options::OPT_nostdlib) &&
4621      !Args.hasArg(options::OPT_nostartfiles)) {
4622    // Derived from startfile spec.
4623    if (Args.hasArg(options::OPT_dynamiclib)) {
4624      // Derived from darwin_dylib1 spec.
4625      if (getDarwinToolChain().isTargetIOSSimulator()) {
4626        // The simulator doesn't have a versioned crt1 file.
4627        CmdArgs.push_back("-ldylib1.o");
4628      } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4629        if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4630          CmdArgs.push_back("-ldylib1.o");
4631      } else {
4632        if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4633          CmdArgs.push_back("-ldylib1.o");
4634        else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4635          CmdArgs.push_back("-ldylib1.10.5.o");
4636      }
4637    } else {
4638      if (Args.hasArg(options::OPT_bundle)) {
4639        if (!Args.hasArg(options::OPT_static)) {
4640          // Derived from darwin_bundle1 spec.
4641          if (getDarwinToolChain().isTargetIOSSimulator()) {
4642            // The simulator doesn't have a versioned crt1 file.
4643            CmdArgs.push_back("-lbundle1.o");
4644          } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4645            if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4646              CmdArgs.push_back("-lbundle1.o");
4647          } else {
4648            if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4649              CmdArgs.push_back("-lbundle1.o");
4650          }
4651        }
4652      } else {
4653        if (Args.hasArg(options::OPT_pg) &&
4654            getToolChain().SupportsProfiling()) {
4655          if (Args.hasArg(options::OPT_static) ||
4656              Args.hasArg(options::OPT_object) ||
4657              Args.hasArg(options::OPT_preload)) {
4658            CmdArgs.push_back("-lgcrt0.o");
4659          } else {
4660            CmdArgs.push_back("-lgcrt1.o");
4661
4662            // darwin_crt2 spec is empty.
4663          }
4664          // By default on OS X 10.8 and later, we don't link with a crt1.o
4665          // file and the linker knows to use _main as the entry point.  But,
4666          // when compiling with -pg, we need to link with the gcrt1.o file,
4667          // so pass the -no_new_main option to tell the linker to use the
4668          // "start" symbol as the entry point.
4669          if (getDarwinToolChain().isTargetMacOS() &&
4670              !getDarwinToolChain().isMacosxVersionLT(10, 8))
4671            CmdArgs.push_back("-no_new_main");
4672        } else {
4673          if (Args.hasArg(options::OPT_static) ||
4674              Args.hasArg(options::OPT_object) ||
4675              Args.hasArg(options::OPT_preload)) {
4676            CmdArgs.push_back("-lcrt0.o");
4677          } else {
4678            // Derived from darwin_crt1 spec.
4679            if (getDarwinToolChain().isTargetIOSSimulator()) {
4680              // The simulator doesn't have a versioned crt1 file.
4681              CmdArgs.push_back("-lcrt1.o");
4682            } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4683              if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4684                CmdArgs.push_back("-lcrt1.o");
4685              else if (getDarwinToolChain().isIPhoneOSVersionLT(6, 0))
4686                CmdArgs.push_back("-lcrt1.3.1.o");
4687            } else {
4688              if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4689                CmdArgs.push_back("-lcrt1.o");
4690              else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4691                CmdArgs.push_back("-lcrt1.10.5.o");
4692              else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
4693                CmdArgs.push_back("-lcrt1.10.6.o");
4694
4695              // darwin_crt2 spec is empty.
4696            }
4697          }
4698        }
4699      }
4700    }
4701
4702    if (!getDarwinToolChain().isTargetIPhoneOS() &&
4703        Args.hasArg(options::OPT_shared_libgcc) &&
4704        getDarwinToolChain().isMacosxVersionLT(10, 5)) {
4705      const char *Str =
4706        Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
4707      CmdArgs.push_back(Str);
4708    }
4709  }
4710
4711  Args.AddAllArgs(CmdArgs, options::OPT_L);
4712
4713  SanitizerArgs Sanitize(getToolChain().getDriver(), Args);
4714  // If we're building a dynamic lib with -fsanitize=address, or
4715  // -fsanitize=undefined, unresolved symbols may appear. Mark all
4716  // of them as dynamic_lookup. Linking executables is handled in
4717  // lib/Driver/ToolChains.cpp.
4718  if (Sanitize.needsAsanRt() || Sanitize.needsUbsanRt()) {
4719    if (Args.hasArg(options::OPT_dynamiclib) ||
4720        Args.hasArg(options::OPT_bundle)) {
4721      CmdArgs.push_back("-undefined");
4722      CmdArgs.push_back("dynamic_lookup");
4723    }
4724  }
4725
4726  if (Args.hasArg(options::OPT_fopenmp))
4727    // This is more complicated in gcc...
4728    CmdArgs.push_back("-lgomp");
4729
4730  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4731
4732  if (isObjCRuntimeLinked(Args) &&
4733      !Args.hasArg(options::OPT_nostdlib) &&
4734      !Args.hasArg(options::OPT_nodefaultlibs)) {
4735    // Avoid linking compatibility stubs on i386 mac.
4736    if (!getDarwinToolChain().isTargetMacOS() ||
4737        getDarwinToolChain().getArch() != llvm::Triple::x86) {
4738      // If we don't have ARC or subscripting runtime support, link in the
4739      // runtime stubs.  We have to do this *before* adding any of the normal
4740      // linker inputs so that its initializer gets run first.
4741      ObjCRuntime runtime =
4742        getDarwinToolChain().getDefaultObjCRuntime(/*nonfragile*/ true);
4743      // We use arclite library for both ARC and subscripting support.
4744      if ((!runtime.hasNativeARC() && isObjCAutoRefCount(Args)) ||
4745          !runtime.hasSubscripting())
4746        getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
4747    }
4748    CmdArgs.push_back("-framework");
4749    CmdArgs.push_back("Foundation");
4750    // Link libobj.
4751    CmdArgs.push_back("-lobjc");
4752  }
4753
4754  if (LinkingOutput) {
4755    CmdArgs.push_back("-arch_multiple");
4756    CmdArgs.push_back("-final_output");
4757    CmdArgs.push_back(LinkingOutput);
4758  }
4759
4760  if (Args.hasArg(options::OPT_fnested_functions))
4761    CmdArgs.push_back("-allow_stack_execute");
4762
4763  if (!Args.hasArg(options::OPT_nostdlib) &&
4764      !Args.hasArg(options::OPT_nodefaultlibs)) {
4765    if (getToolChain().getDriver().CCCIsCXX)
4766      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4767
4768    // link_ssp spec is empty.
4769
4770    // Let the tool chain choose which runtime library to link.
4771    getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
4772  }
4773
4774  if (!Args.hasArg(options::OPT_nostdlib) &&
4775      !Args.hasArg(options::OPT_nostartfiles)) {
4776    // endfile_spec is empty.
4777  }
4778
4779  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4780  Args.AddAllArgs(CmdArgs, options::OPT_F);
4781
4782  const char *Exec =
4783    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4784  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4785}
4786
4787void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
4788                                const InputInfo &Output,
4789                                const InputInfoList &Inputs,
4790                                const ArgList &Args,
4791                                const char *LinkingOutput) const {
4792  ArgStringList CmdArgs;
4793
4794  CmdArgs.push_back("-create");
4795  assert(Output.isFilename() && "Unexpected lipo output.");
4796
4797  CmdArgs.push_back("-output");
4798  CmdArgs.push_back(Output.getFilename());
4799
4800  for (InputInfoList::const_iterator
4801         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4802    const InputInfo &II = *it;
4803    assert(II.isFilename() && "Unexpected lipo input.");
4804    CmdArgs.push_back(II.getFilename());
4805  }
4806  const char *Exec =
4807    Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
4808  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4809}
4810
4811void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
4812                                    const InputInfo &Output,
4813                                    const InputInfoList &Inputs,
4814                                    const ArgList &Args,
4815                                    const char *LinkingOutput) const {
4816  ArgStringList CmdArgs;
4817
4818  CmdArgs.push_back("-o");
4819  CmdArgs.push_back(Output.getFilename());
4820
4821  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4822  const InputInfo &Input = Inputs[0];
4823  assert(Input.isFilename() && "Unexpected dsymutil input.");
4824  CmdArgs.push_back(Input.getFilename());
4825
4826  const char *Exec =
4827    Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
4828  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4829}
4830
4831void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
4832				       const InputInfo &Output,
4833				       const InputInfoList &Inputs,
4834				       const ArgList &Args,
4835				       const char *LinkingOutput) const {
4836  ArgStringList CmdArgs;
4837  CmdArgs.push_back("--verify");
4838  CmdArgs.push_back("--debug-info");
4839  CmdArgs.push_back("--eh-frame");
4840  CmdArgs.push_back("--quiet");
4841
4842  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
4843  const InputInfo &Input = Inputs[0];
4844  assert(Input.isFilename() && "Unexpected verify input");
4845
4846  // Grabbing the output of the earlier dsymutil run.
4847  CmdArgs.push_back(Input.getFilename());
4848
4849  const char *Exec =
4850    Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
4851  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4852}
4853
4854void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4855                                      const InputInfo &Output,
4856                                      const InputInfoList &Inputs,
4857                                      const ArgList &Args,
4858                                      const char *LinkingOutput) const {
4859  ArgStringList CmdArgs;
4860
4861  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4862                       options::OPT_Xassembler);
4863
4864  CmdArgs.push_back("-o");
4865  CmdArgs.push_back(Output.getFilename());
4866
4867  for (InputInfoList::const_iterator
4868         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4869    const InputInfo &II = *it;
4870    CmdArgs.push_back(II.getFilename());
4871  }
4872
4873  const char *Exec =
4874    Args.MakeArgString(getToolChain().GetProgramPath("as"));
4875  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4876}
4877
4878
4879void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
4880                                  const InputInfo &Output,
4881                                  const InputInfoList &Inputs,
4882                                  const ArgList &Args,
4883                                  const char *LinkingOutput) const {
4884  // FIXME: Find a real GCC, don't hard-code versions here
4885  std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
4886  const llvm::Triple &T = getToolChain().getTriple();
4887  std::string LibPath = "/usr/lib/";
4888  llvm::Triple::ArchType Arch = T.getArch();
4889  switch (Arch) {
4890        case llvm::Triple::x86:
4891          GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4892              T.getOSName()).str() + "/4.5.2/";
4893          break;
4894        case llvm::Triple::x86_64:
4895          GCCLibPath += ("i386-" + T.getVendorName() + "-" +
4896              T.getOSName()).str();
4897          GCCLibPath += "/4.5.2/amd64/";
4898          LibPath += "amd64/";
4899          break;
4900        default:
4901          assert(0 && "Unsupported architecture");
4902  }
4903
4904  ArgStringList CmdArgs;
4905
4906  // Demangle C++ names in errors
4907  CmdArgs.push_back("-C");
4908
4909  if ((!Args.hasArg(options::OPT_nostdlib)) &&
4910      (!Args.hasArg(options::OPT_shared))) {
4911    CmdArgs.push_back("-e");
4912    CmdArgs.push_back("_start");
4913  }
4914
4915  if (Args.hasArg(options::OPT_static)) {
4916    CmdArgs.push_back("-Bstatic");
4917    CmdArgs.push_back("-dn");
4918  } else {
4919    CmdArgs.push_back("-Bdynamic");
4920    if (Args.hasArg(options::OPT_shared)) {
4921      CmdArgs.push_back("-shared");
4922    } else {
4923      CmdArgs.push_back("--dynamic-linker");
4924      CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
4925    }
4926  }
4927
4928  if (Output.isFilename()) {
4929    CmdArgs.push_back("-o");
4930    CmdArgs.push_back(Output.getFilename());
4931  } else {
4932    assert(Output.isNothing() && "Invalid output.");
4933  }
4934
4935  if (!Args.hasArg(options::OPT_nostdlib) &&
4936      !Args.hasArg(options::OPT_nostartfiles)) {
4937    if (!Args.hasArg(options::OPT_shared)) {
4938      CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
4939      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4940      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4941      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4942    } else {
4943      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
4944      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
4945      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
4946    }
4947    if (getToolChain().getDriver().CCCIsCXX)
4948      CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
4949  }
4950
4951  CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
4952
4953  Args.AddAllArgs(CmdArgs, options::OPT_L);
4954  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4955  Args.AddAllArgs(CmdArgs, options::OPT_e);
4956  Args.AddAllArgs(CmdArgs, options::OPT_r);
4957
4958  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
4959
4960  if (!Args.hasArg(options::OPT_nostdlib) &&
4961      !Args.hasArg(options::OPT_nodefaultlibs)) {
4962    if (getToolChain().getDriver().CCCIsCXX)
4963      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
4964    CmdArgs.push_back("-lgcc_s");
4965    if (!Args.hasArg(options::OPT_shared)) {
4966      CmdArgs.push_back("-lgcc");
4967      CmdArgs.push_back("-lc");
4968      CmdArgs.push_back("-lm");
4969    }
4970  }
4971
4972  if (!Args.hasArg(options::OPT_nostdlib) &&
4973      !Args.hasArg(options::OPT_nostartfiles)) {
4974    CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
4975  }
4976  CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
4977
4978  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
4979
4980  const char *Exec =
4981    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
4982  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4983}
4984
4985void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4986                                      const InputInfo &Output,
4987                                      const InputInfoList &Inputs,
4988                                      const ArgList &Args,
4989                                      const char *LinkingOutput) const {
4990  ArgStringList CmdArgs;
4991
4992  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4993                       options::OPT_Xassembler);
4994
4995  CmdArgs.push_back("-o");
4996  CmdArgs.push_back(Output.getFilename());
4997
4998  for (InputInfoList::const_iterator
4999         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5000    const InputInfo &II = *it;
5001    CmdArgs.push_back(II.getFilename());
5002  }
5003
5004  const char *Exec =
5005    Args.MakeArgString(getToolChain().GetProgramPath("gas"));
5006  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5007}
5008
5009void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
5010                                  const InputInfo &Output,
5011                                  const InputInfoList &Inputs,
5012                                  const ArgList &Args,
5013                                  const char *LinkingOutput) const {
5014  ArgStringList CmdArgs;
5015
5016  if ((!Args.hasArg(options::OPT_nostdlib)) &&
5017      (!Args.hasArg(options::OPT_shared))) {
5018    CmdArgs.push_back("-e");
5019    CmdArgs.push_back("_start");
5020  }
5021
5022  if (Args.hasArg(options::OPT_static)) {
5023    CmdArgs.push_back("-Bstatic");
5024    CmdArgs.push_back("-dn");
5025  } else {
5026//    CmdArgs.push_back("--eh-frame-hdr");
5027    CmdArgs.push_back("-Bdynamic");
5028    if (Args.hasArg(options::OPT_shared)) {
5029      CmdArgs.push_back("-shared");
5030    } else {
5031      CmdArgs.push_back("--dynamic-linker");
5032      CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
5033    }
5034  }
5035
5036  if (Output.isFilename()) {
5037    CmdArgs.push_back("-o");
5038    CmdArgs.push_back(Output.getFilename());
5039  } else {
5040    assert(Output.isNothing() && "Invalid output.");
5041  }
5042
5043  if (!Args.hasArg(options::OPT_nostdlib) &&
5044      !Args.hasArg(options::OPT_nostartfiles)) {
5045    if (!Args.hasArg(options::OPT_shared)) {
5046      CmdArgs.push_back(Args.MakeArgString(
5047                                getToolChain().GetFilePath("crt1.o")));
5048      CmdArgs.push_back(Args.MakeArgString(
5049                                getToolChain().GetFilePath("crti.o")));
5050      CmdArgs.push_back(Args.MakeArgString(
5051                                getToolChain().GetFilePath("crtbegin.o")));
5052    } else {
5053      CmdArgs.push_back(Args.MakeArgString(
5054                                getToolChain().GetFilePath("crti.o")));
5055    }
5056    CmdArgs.push_back(Args.MakeArgString(
5057                                getToolChain().GetFilePath("crtn.o")));
5058  }
5059
5060  CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
5061                                       + getToolChain().getTripleString()
5062                                       + "/4.2.4"));
5063
5064  Args.AddAllArgs(CmdArgs, options::OPT_L);
5065  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5066  Args.AddAllArgs(CmdArgs, options::OPT_e);
5067
5068  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5069
5070  if (!Args.hasArg(options::OPT_nostdlib) &&
5071      !Args.hasArg(options::OPT_nodefaultlibs)) {
5072    // FIXME: For some reason GCC passes -lgcc before adding
5073    // the default system libraries. Just mimic this for now.
5074    CmdArgs.push_back("-lgcc");
5075
5076    if (Args.hasArg(options::OPT_pthread))
5077      CmdArgs.push_back("-pthread");
5078    if (!Args.hasArg(options::OPT_shared))
5079      CmdArgs.push_back("-lc");
5080    CmdArgs.push_back("-lgcc");
5081  }
5082
5083  if (!Args.hasArg(options::OPT_nostdlib) &&
5084      !Args.hasArg(options::OPT_nostartfiles)) {
5085    if (!Args.hasArg(options::OPT_shared))
5086      CmdArgs.push_back(Args.MakeArgString(
5087                                getToolChain().GetFilePath("crtend.o")));
5088  }
5089
5090  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5091
5092  const char *Exec =
5093    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5094  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5095}
5096
5097void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5098                                     const InputInfo &Output,
5099                                     const InputInfoList &Inputs,
5100                                     const ArgList &Args,
5101                                     const char *LinkingOutput) const {
5102  ArgStringList CmdArgs;
5103
5104  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5105                       options::OPT_Xassembler);
5106
5107  CmdArgs.push_back("-o");
5108  CmdArgs.push_back(Output.getFilename());
5109
5110  for (InputInfoList::const_iterator
5111         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5112    const InputInfo &II = *it;
5113    CmdArgs.push_back(II.getFilename());
5114  }
5115
5116  const char *Exec =
5117    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5118  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5119}
5120
5121void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5122                                 const InputInfo &Output,
5123                                 const InputInfoList &Inputs,
5124                                 const ArgList &Args,
5125                                 const char *LinkingOutput) const {
5126  const Driver &D = getToolChain().getDriver();
5127  ArgStringList CmdArgs;
5128
5129  if ((!Args.hasArg(options::OPT_nostdlib)) &&
5130      (!Args.hasArg(options::OPT_shared))) {
5131    CmdArgs.push_back("-e");
5132    CmdArgs.push_back("__start");
5133  }
5134
5135  if (Args.hasArg(options::OPT_static)) {
5136    CmdArgs.push_back("-Bstatic");
5137  } else {
5138    if (Args.hasArg(options::OPT_rdynamic))
5139      CmdArgs.push_back("-export-dynamic");
5140    CmdArgs.push_back("--eh-frame-hdr");
5141    CmdArgs.push_back("-Bdynamic");
5142    if (Args.hasArg(options::OPT_shared)) {
5143      CmdArgs.push_back("-shared");
5144    } else {
5145      CmdArgs.push_back("-dynamic-linker");
5146      CmdArgs.push_back("/usr/libexec/ld.so");
5147    }
5148  }
5149
5150  if (Output.isFilename()) {
5151    CmdArgs.push_back("-o");
5152    CmdArgs.push_back(Output.getFilename());
5153  } else {
5154    assert(Output.isNothing() && "Invalid output.");
5155  }
5156
5157  if (!Args.hasArg(options::OPT_nostdlib) &&
5158      !Args.hasArg(options::OPT_nostartfiles)) {
5159    if (!Args.hasArg(options::OPT_shared)) {
5160      if (Args.hasArg(options::OPT_pg))
5161        CmdArgs.push_back(Args.MakeArgString(
5162                                getToolChain().GetFilePath("gcrt0.o")));
5163      else
5164        CmdArgs.push_back(Args.MakeArgString(
5165                                getToolChain().GetFilePath("crt0.o")));
5166      CmdArgs.push_back(Args.MakeArgString(
5167                              getToolChain().GetFilePath("crtbegin.o")));
5168    } else {
5169      CmdArgs.push_back(Args.MakeArgString(
5170                              getToolChain().GetFilePath("crtbeginS.o")));
5171    }
5172  }
5173
5174  std::string Triple = getToolChain().getTripleString();
5175  if (Triple.substr(0, 6) == "x86_64")
5176    Triple.replace(0, 6, "amd64");
5177  CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
5178                                       "/4.2.1"));
5179
5180  Args.AddAllArgs(CmdArgs, options::OPT_L);
5181  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5182  Args.AddAllArgs(CmdArgs, options::OPT_e);
5183
5184  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5185
5186  if (!Args.hasArg(options::OPT_nostdlib) &&
5187      !Args.hasArg(options::OPT_nodefaultlibs)) {
5188    if (D.CCCIsCXX) {
5189      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5190      if (Args.hasArg(options::OPT_pg))
5191        CmdArgs.push_back("-lm_p");
5192      else
5193        CmdArgs.push_back("-lm");
5194    }
5195
5196    // FIXME: For some reason GCC passes -lgcc before adding
5197    // the default system libraries. Just mimic this for now.
5198    CmdArgs.push_back("-lgcc");
5199
5200    if (Args.hasArg(options::OPT_pthread)) {
5201      if (!Args.hasArg(options::OPT_shared) &&
5202          Args.hasArg(options::OPT_pg))
5203         CmdArgs.push_back("-lpthread_p");
5204      else
5205         CmdArgs.push_back("-lpthread");
5206    }
5207
5208    if (!Args.hasArg(options::OPT_shared)) {
5209      if (Args.hasArg(options::OPT_pg))
5210         CmdArgs.push_back("-lc_p");
5211      else
5212         CmdArgs.push_back("-lc");
5213    }
5214
5215    CmdArgs.push_back("-lgcc");
5216  }
5217
5218  if (!Args.hasArg(options::OPT_nostdlib) &&
5219      !Args.hasArg(options::OPT_nostartfiles)) {
5220    if (!Args.hasArg(options::OPT_shared))
5221      CmdArgs.push_back(Args.MakeArgString(
5222                              getToolChain().GetFilePath("crtend.o")));
5223    else
5224      CmdArgs.push_back(Args.MakeArgString(
5225                              getToolChain().GetFilePath("crtendS.o")));
5226  }
5227
5228  const char *Exec =
5229    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5230  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5231}
5232
5233void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5234                                    const InputInfo &Output,
5235                                    const InputInfoList &Inputs,
5236                                    const ArgList &Args,
5237                                    const char *LinkingOutput) const {
5238  ArgStringList CmdArgs;
5239
5240  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5241                       options::OPT_Xassembler);
5242
5243  CmdArgs.push_back("-o");
5244  CmdArgs.push_back(Output.getFilename());
5245
5246  for (InputInfoList::const_iterator
5247         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5248    const InputInfo &II = *it;
5249    CmdArgs.push_back(II.getFilename());
5250  }
5251
5252  const char *Exec =
5253    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5254  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5255}
5256
5257void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
5258                                const InputInfo &Output,
5259                                const InputInfoList &Inputs,
5260                                const ArgList &Args,
5261                                const char *LinkingOutput) const {
5262  const Driver &D = getToolChain().getDriver();
5263  ArgStringList CmdArgs;
5264
5265  if ((!Args.hasArg(options::OPT_nostdlib)) &&
5266      (!Args.hasArg(options::OPT_shared))) {
5267    CmdArgs.push_back("-e");
5268    CmdArgs.push_back("__start");
5269  }
5270
5271  if (Args.hasArg(options::OPT_static)) {
5272    CmdArgs.push_back("-Bstatic");
5273  } else {
5274    if (Args.hasArg(options::OPT_rdynamic))
5275      CmdArgs.push_back("-export-dynamic");
5276    CmdArgs.push_back("--eh-frame-hdr");
5277    CmdArgs.push_back("-Bdynamic");
5278    if (Args.hasArg(options::OPT_shared)) {
5279      CmdArgs.push_back("-shared");
5280    } else {
5281      CmdArgs.push_back("-dynamic-linker");
5282      CmdArgs.push_back("/usr/libexec/ld.so");
5283    }
5284  }
5285
5286  if (Output.isFilename()) {
5287    CmdArgs.push_back("-o");
5288    CmdArgs.push_back(Output.getFilename());
5289  } else {
5290    assert(Output.isNothing() && "Invalid output.");
5291  }
5292
5293  if (!Args.hasArg(options::OPT_nostdlib) &&
5294      !Args.hasArg(options::OPT_nostartfiles)) {
5295    if (!Args.hasArg(options::OPT_shared)) {
5296      if (Args.hasArg(options::OPT_pg))
5297        CmdArgs.push_back(Args.MakeArgString(
5298                                getToolChain().GetFilePath("gcrt0.o")));
5299      else
5300        CmdArgs.push_back(Args.MakeArgString(
5301                                getToolChain().GetFilePath("crt0.o")));
5302      CmdArgs.push_back(Args.MakeArgString(
5303                              getToolChain().GetFilePath("crtbegin.o")));
5304    } else {
5305      CmdArgs.push_back(Args.MakeArgString(
5306                              getToolChain().GetFilePath("crtbeginS.o")));
5307    }
5308  }
5309
5310  Args.AddAllArgs(CmdArgs, options::OPT_L);
5311  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5312  Args.AddAllArgs(CmdArgs, options::OPT_e);
5313
5314  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5315
5316  if (!Args.hasArg(options::OPT_nostdlib) &&
5317      !Args.hasArg(options::OPT_nodefaultlibs)) {
5318    if (D.CCCIsCXX) {
5319      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5320      if (Args.hasArg(options::OPT_pg))
5321        CmdArgs.push_back("-lm_p");
5322      else
5323        CmdArgs.push_back("-lm");
5324    }
5325
5326    if (Args.hasArg(options::OPT_pthread)) {
5327      if (!Args.hasArg(options::OPT_shared) &&
5328          Args.hasArg(options::OPT_pg))
5329        CmdArgs.push_back("-lpthread_p");
5330      else
5331        CmdArgs.push_back("-lpthread");
5332    }
5333
5334    if (!Args.hasArg(options::OPT_shared)) {
5335      if (Args.hasArg(options::OPT_pg))
5336        CmdArgs.push_back("-lc_p");
5337      else
5338        CmdArgs.push_back("-lc");
5339    }
5340
5341    std::string myarch = "-lclang_rt.";
5342    const llvm::Triple &T = getToolChain().getTriple();
5343    llvm::Triple::ArchType Arch = T.getArch();
5344    switch (Arch) {
5345          case llvm::Triple::arm:
5346            myarch += ("arm");
5347            break;
5348          case llvm::Triple::x86:
5349            myarch += ("i386");
5350            break;
5351          case llvm::Triple::x86_64:
5352            myarch += ("amd64");
5353            break;
5354          default:
5355            assert(0 && "Unsupported architecture");
5356     }
5357     CmdArgs.push_back(Args.MakeArgString(myarch));
5358  }
5359
5360  if (!Args.hasArg(options::OPT_nostdlib) &&
5361      !Args.hasArg(options::OPT_nostartfiles)) {
5362    if (!Args.hasArg(options::OPT_shared))
5363      CmdArgs.push_back(Args.MakeArgString(
5364                              getToolChain().GetFilePath("crtend.o")));
5365    else
5366      CmdArgs.push_back(Args.MakeArgString(
5367                              getToolChain().GetFilePath("crtendS.o")));
5368  }
5369
5370  const char *Exec =
5371    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5372  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5373}
5374
5375void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5376                                     const InputInfo &Output,
5377                                     const InputInfoList &Inputs,
5378                                     const ArgList &Args,
5379                                     const char *LinkingOutput) const {
5380  ArgStringList CmdArgs;
5381
5382  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5383  // instruct as in the base system to assemble 32-bit code.
5384  if (getToolChain().getArch() == llvm::Triple::x86)
5385    CmdArgs.push_back("--32");
5386  else if (getToolChain().getArch() == llvm::Triple::ppc)
5387    CmdArgs.push_back("-a32");
5388  else if (getToolChain().getArch() == llvm::Triple::mips ||
5389           getToolChain().getArch() == llvm::Triple::mipsel ||
5390           getToolChain().getArch() == llvm::Triple::mips64 ||
5391           getToolChain().getArch() == llvm::Triple::mips64el) {
5392    StringRef CPUName;
5393    StringRef ABIName;
5394    getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
5395
5396    CmdArgs.push_back("-march");
5397    CmdArgs.push_back(CPUName.data());
5398
5399    // Convert ABI name to the GNU tools acceptable variant.
5400    if (ABIName == "o32")
5401      ABIName = "32";
5402    else if (ABIName == "n64")
5403      ABIName = "64";
5404
5405    CmdArgs.push_back("-mabi");
5406    CmdArgs.push_back(ABIName.data());
5407
5408    if (getToolChain().getArch() == llvm::Triple::mips ||
5409        getToolChain().getArch() == llvm::Triple::mips64)
5410      CmdArgs.push_back("-EB");
5411    else
5412      CmdArgs.push_back("-EL");
5413
5414    Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5415                                      options::OPT_fpic, options::OPT_fno_pic,
5416                                      options::OPT_fPIE, options::OPT_fno_PIE,
5417                                      options::OPT_fpie, options::OPT_fno_pie);
5418    if (LastPICArg &&
5419        (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5420         LastPICArg->getOption().matches(options::OPT_fpic) ||
5421         LastPICArg->getOption().matches(options::OPT_fPIE) ||
5422         LastPICArg->getOption().matches(options::OPT_fpie))) {
5423      CmdArgs.push_back("-KPIC");
5424    }
5425  }
5426
5427  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5428                       options::OPT_Xassembler);
5429
5430  CmdArgs.push_back("-o");
5431  CmdArgs.push_back(Output.getFilename());
5432
5433  for (InputInfoList::const_iterator
5434         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5435    const InputInfo &II = *it;
5436    CmdArgs.push_back(II.getFilename());
5437  }
5438
5439  const char *Exec =
5440    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5441  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5442}
5443
5444void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5445                                 const InputInfo &Output,
5446                                 const InputInfoList &Inputs,
5447                                 const ArgList &Args,
5448                                 const char *LinkingOutput) const {
5449  const toolchains::FreeBSD& ToolChain =
5450    static_cast<const toolchains::FreeBSD&>(getToolChain());
5451  const Driver &D = ToolChain.getDriver();
5452  ArgStringList CmdArgs;
5453
5454  // Silence warning for "clang -g foo.o -o foo"
5455  Args.ClaimAllArgs(options::OPT_g_Group);
5456  // and "clang -emit-llvm foo.o -o foo"
5457  Args.ClaimAllArgs(options::OPT_emit_llvm);
5458  // and for "clang -w foo.o -o foo". Other warning options are already
5459  // handled somewhere else.
5460  Args.ClaimAllArgs(options::OPT_w);
5461
5462  if (!D.SysRoot.empty())
5463    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5464
5465  if (Args.hasArg(options::OPT_pie))
5466    CmdArgs.push_back("-pie");
5467
5468  if (Args.hasArg(options::OPT_static)) {
5469    CmdArgs.push_back("-Bstatic");
5470  } else {
5471    if (Args.hasArg(options::OPT_rdynamic))
5472      CmdArgs.push_back("-export-dynamic");
5473    CmdArgs.push_back("--eh-frame-hdr");
5474    if (Args.hasArg(options::OPT_shared)) {
5475      CmdArgs.push_back("-Bshareable");
5476    } else {
5477      CmdArgs.push_back("-dynamic-linker");
5478      CmdArgs.push_back("/libexec/ld-elf.so.1");
5479    }
5480    if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
5481      llvm::Triple::ArchType Arch = ToolChain.getArch();
5482      if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
5483          Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5484        CmdArgs.push_back("--hash-style=both");
5485      }
5486    }
5487    CmdArgs.push_back("--enable-new-dtags");
5488  }
5489
5490  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5491  // instruct ld in the base system to link 32-bit code.
5492  if (ToolChain.getArch() == llvm::Triple::x86) {
5493    CmdArgs.push_back("-m");
5494    CmdArgs.push_back("elf_i386_fbsd");
5495  }
5496
5497  if (ToolChain.getArch() == llvm::Triple::ppc) {
5498    CmdArgs.push_back("-m");
5499    CmdArgs.push_back("elf32ppc_fbsd");
5500  }
5501
5502  if (Output.isFilename()) {
5503    CmdArgs.push_back("-o");
5504    CmdArgs.push_back(Output.getFilename());
5505  } else {
5506    assert(Output.isNothing() && "Invalid output.");
5507  }
5508
5509  if (!Args.hasArg(options::OPT_nostdlib) &&
5510      !Args.hasArg(options::OPT_nostartfiles)) {
5511    const char *crt1 = NULL;
5512    if (!Args.hasArg(options::OPT_shared)) {
5513      if (Args.hasArg(options::OPT_pg))
5514        crt1 = "gcrt1.o";
5515      else if (Args.hasArg(options::OPT_pie))
5516        crt1 = "Scrt1.o";
5517      else
5518        crt1 = "crt1.o";
5519    }
5520    if (crt1)
5521      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5522
5523    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5524
5525    const char *crtbegin = NULL;
5526    if (Args.hasArg(options::OPT_static))
5527      crtbegin = "crtbeginT.o";
5528    else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5529      crtbegin = "crtbeginS.o";
5530    else
5531      crtbegin = "crtbegin.o";
5532
5533    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5534  }
5535
5536  Args.AddAllArgs(CmdArgs, options::OPT_L);
5537  const ToolChain::path_list Paths = ToolChain.getFilePaths();
5538  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5539       i != e; ++i)
5540    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5541  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5542  Args.AddAllArgs(CmdArgs, options::OPT_e);
5543  Args.AddAllArgs(CmdArgs, options::OPT_s);
5544  Args.AddAllArgs(CmdArgs, options::OPT_t);
5545  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5546  Args.AddAllArgs(CmdArgs, options::OPT_r);
5547
5548  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5549
5550  if (!Args.hasArg(options::OPT_nostdlib) &&
5551      !Args.hasArg(options::OPT_nodefaultlibs)) {
5552    if (D.CCCIsCXX) {
5553      ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5554      if (Args.hasArg(options::OPT_pg))
5555        CmdArgs.push_back("-lm_p");
5556      else
5557        CmdArgs.push_back("-lm");
5558    }
5559    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5560    // the default system libraries. Just mimic this for now.
5561    if (Args.hasArg(options::OPT_pg))
5562      CmdArgs.push_back("-lgcc_p");
5563    else
5564      CmdArgs.push_back("-lgcc");
5565    if (Args.hasArg(options::OPT_static)) {
5566      CmdArgs.push_back("-lgcc_eh");
5567    } else if (Args.hasArg(options::OPT_pg)) {
5568      CmdArgs.push_back("-lgcc_eh_p");
5569    } else {
5570      CmdArgs.push_back("--as-needed");
5571      CmdArgs.push_back("-lgcc_s");
5572      CmdArgs.push_back("--no-as-needed");
5573    }
5574
5575    if (Args.hasArg(options::OPT_pthread)) {
5576      if (Args.hasArg(options::OPT_pg))
5577        CmdArgs.push_back("-lpthread_p");
5578      else
5579        CmdArgs.push_back("-lpthread");
5580    }
5581
5582    if (Args.hasArg(options::OPT_pg)) {
5583      if (Args.hasArg(options::OPT_shared))
5584        CmdArgs.push_back("-lc");
5585      else
5586        CmdArgs.push_back("-lc_p");
5587      CmdArgs.push_back("-lgcc_p");
5588    } else {
5589      CmdArgs.push_back("-lc");
5590      CmdArgs.push_back("-lgcc");
5591    }
5592
5593    if (Args.hasArg(options::OPT_static)) {
5594      CmdArgs.push_back("-lgcc_eh");
5595    } else if (Args.hasArg(options::OPT_pg)) {
5596      CmdArgs.push_back("-lgcc_eh_p");
5597    } else {
5598      CmdArgs.push_back("--as-needed");
5599      CmdArgs.push_back("-lgcc_s");
5600      CmdArgs.push_back("--no-as-needed");
5601    }
5602  }
5603
5604  if (!Args.hasArg(options::OPT_nostdlib) &&
5605      !Args.hasArg(options::OPT_nostartfiles)) {
5606    if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5607      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
5608    else
5609      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
5610    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
5611  }
5612
5613  addProfileRT(ToolChain, Args, CmdArgs, ToolChain.getTriple());
5614
5615  const char *Exec =
5616    Args.MakeArgString(ToolChain.GetProgramPath("ld"));
5617  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5618}
5619
5620void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5621                                     const InputInfo &Output,
5622                                     const InputInfoList &Inputs,
5623                                     const ArgList &Args,
5624                                     const char *LinkingOutput) const {
5625  ArgStringList CmdArgs;
5626
5627  // When building 32-bit code on NetBSD/amd64, we have to explicitly
5628  // instruct as in the base system to assemble 32-bit code.
5629  if (getToolChain().getArch() == llvm::Triple::x86)
5630    CmdArgs.push_back("--32");
5631
5632  // Set byte order explicitly
5633  if (getToolChain().getArch() == llvm::Triple::mips)
5634    CmdArgs.push_back("-EB");
5635  else if (getToolChain().getArch() == llvm::Triple::mipsel)
5636    CmdArgs.push_back("-EL");
5637
5638  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5639                       options::OPT_Xassembler);
5640
5641  CmdArgs.push_back("-o");
5642  CmdArgs.push_back(Output.getFilename());
5643
5644  for (InputInfoList::const_iterator
5645         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5646    const InputInfo &II = *it;
5647    CmdArgs.push_back(II.getFilename());
5648  }
5649
5650  const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
5651  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5652}
5653
5654void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5655                                 const InputInfo &Output,
5656                                 const InputInfoList &Inputs,
5657                                 const ArgList &Args,
5658                                 const char *LinkingOutput) const {
5659  const Driver &D = getToolChain().getDriver();
5660  ArgStringList CmdArgs;
5661
5662  if (!D.SysRoot.empty())
5663    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5664
5665  if (Args.hasArg(options::OPT_static)) {
5666    CmdArgs.push_back("-Bstatic");
5667  } else {
5668    if (Args.hasArg(options::OPT_rdynamic))
5669      CmdArgs.push_back("-export-dynamic");
5670    CmdArgs.push_back("--eh-frame-hdr");
5671    if (Args.hasArg(options::OPT_shared)) {
5672      CmdArgs.push_back("-Bshareable");
5673    } else {
5674      CmdArgs.push_back("-dynamic-linker");
5675      CmdArgs.push_back("/libexec/ld.elf_so");
5676    }
5677  }
5678
5679  // When building 32-bit code on NetBSD/amd64, we have to explicitly
5680  // instruct ld in the base system to link 32-bit code.
5681  if (getToolChain().getArch() == llvm::Triple::x86) {
5682    CmdArgs.push_back("-m");
5683    CmdArgs.push_back("elf_i386");
5684  }
5685
5686  if (Output.isFilename()) {
5687    CmdArgs.push_back("-o");
5688    CmdArgs.push_back(Output.getFilename());
5689  } else {
5690    assert(Output.isNothing() && "Invalid output.");
5691  }
5692
5693  if (!Args.hasArg(options::OPT_nostdlib) &&
5694      !Args.hasArg(options::OPT_nostartfiles)) {
5695    if (!Args.hasArg(options::OPT_shared)) {
5696      CmdArgs.push_back(Args.MakeArgString(
5697                              getToolChain().GetFilePath("crt0.o")));
5698      CmdArgs.push_back(Args.MakeArgString(
5699                              getToolChain().GetFilePath("crti.o")));
5700      CmdArgs.push_back(Args.MakeArgString(
5701                              getToolChain().GetFilePath("crtbegin.o")));
5702    } else {
5703      CmdArgs.push_back(Args.MakeArgString(
5704                              getToolChain().GetFilePath("crti.o")));
5705      CmdArgs.push_back(Args.MakeArgString(
5706                              getToolChain().GetFilePath("crtbeginS.o")));
5707    }
5708  }
5709
5710  Args.AddAllArgs(CmdArgs, options::OPT_L);
5711  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5712  Args.AddAllArgs(CmdArgs, options::OPT_e);
5713  Args.AddAllArgs(CmdArgs, options::OPT_s);
5714  Args.AddAllArgs(CmdArgs, options::OPT_t);
5715  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5716  Args.AddAllArgs(CmdArgs, options::OPT_r);
5717
5718  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5719
5720  if (!Args.hasArg(options::OPT_nostdlib) &&
5721      !Args.hasArg(options::OPT_nodefaultlibs)) {
5722    if (D.CCCIsCXX) {
5723      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5724      CmdArgs.push_back("-lm");
5725    }
5726    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5727    // the default system libraries. Just mimic this for now.
5728    if (Args.hasArg(options::OPT_static)) {
5729      CmdArgs.push_back("-lgcc_eh");
5730    } else {
5731      CmdArgs.push_back("--as-needed");
5732      CmdArgs.push_back("-lgcc_s");
5733      CmdArgs.push_back("--no-as-needed");
5734    }
5735    CmdArgs.push_back("-lgcc");
5736
5737    if (Args.hasArg(options::OPT_pthread))
5738      CmdArgs.push_back("-lpthread");
5739    CmdArgs.push_back("-lc");
5740
5741    CmdArgs.push_back("-lgcc");
5742    if (Args.hasArg(options::OPT_static)) {
5743      CmdArgs.push_back("-lgcc_eh");
5744    } else {
5745      CmdArgs.push_back("--as-needed");
5746      CmdArgs.push_back("-lgcc_s");
5747      CmdArgs.push_back("--no-as-needed");
5748    }
5749  }
5750
5751  if (!Args.hasArg(options::OPT_nostdlib) &&
5752      !Args.hasArg(options::OPT_nostartfiles)) {
5753    if (!Args.hasArg(options::OPT_shared))
5754      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5755                                                                  "crtend.o")));
5756    else
5757      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5758                                                                 "crtendS.o")));
5759    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
5760                                                                    "crtn.o")));
5761  }
5762
5763  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5764
5765  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5766  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5767}
5768
5769void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5770                                        const InputInfo &Output,
5771                                        const InputInfoList &Inputs,
5772                                        const ArgList &Args,
5773                                        const char *LinkingOutput) const {
5774  ArgStringList CmdArgs;
5775
5776  // Add --32/--64 to make sure we get the format we want.
5777  // This is incomplete
5778  if (getToolChain().getArch() == llvm::Triple::x86) {
5779    CmdArgs.push_back("--32");
5780  } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
5781    CmdArgs.push_back("--64");
5782  } else if (getToolChain().getArch() == llvm::Triple::ppc) {
5783    CmdArgs.push_back("-a32");
5784    CmdArgs.push_back("-mppc");
5785    CmdArgs.push_back("-many");
5786  } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
5787    CmdArgs.push_back("-a64");
5788    CmdArgs.push_back("-mppc64");
5789    CmdArgs.push_back("-many");
5790  } else if (getToolChain().getArch() == llvm::Triple::arm) {
5791    StringRef MArch = getToolChain().getArchName();
5792    if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
5793      CmdArgs.push_back("-mfpu=neon");
5794
5795    StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
5796                                           getToolChain().getTriple());
5797    CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
5798
5799    Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
5800    Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
5801    Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
5802  } else if (getToolChain().getArch() == llvm::Triple::mips ||
5803             getToolChain().getArch() == llvm::Triple::mipsel ||
5804             getToolChain().getArch() == llvm::Triple::mips64 ||
5805             getToolChain().getArch() == llvm::Triple::mips64el) {
5806    StringRef CPUName;
5807    StringRef ABIName;
5808    getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
5809
5810    CmdArgs.push_back("-march");
5811    CmdArgs.push_back(CPUName.data());
5812
5813    // Convert ABI name to the GNU tools acceptable variant.
5814    if (ABIName == "o32")
5815      ABIName = "32";
5816    else if (ABIName == "n64")
5817      ABIName = "64";
5818
5819    CmdArgs.push_back("-mabi");
5820    CmdArgs.push_back(ABIName.data());
5821
5822    if (getToolChain().getArch() == llvm::Triple::mips ||
5823        getToolChain().getArch() == llvm::Triple::mips64)
5824      CmdArgs.push_back("-EB");
5825    else
5826      CmdArgs.push_back("-EL");
5827
5828    Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5829                                      options::OPT_fpic, options::OPT_fno_pic,
5830                                      options::OPT_fPIE, options::OPT_fno_PIE,
5831                                      options::OPT_fpie, options::OPT_fno_pie);
5832    if (LastPICArg &&
5833        (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5834         LastPICArg->getOption().matches(options::OPT_fpic) ||
5835         LastPICArg->getOption().matches(options::OPT_fPIE) ||
5836         LastPICArg->getOption().matches(options::OPT_fpie))) {
5837      CmdArgs.push_back("-KPIC");
5838    }
5839  }
5840
5841  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5842                       options::OPT_Xassembler);
5843
5844  CmdArgs.push_back("-o");
5845  CmdArgs.push_back(Output.getFilename());
5846
5847  for (InputInfoList::const_iterator
5848         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5849    const InputInfo &II = *it;
5850    CmdArgs.push_back(II.getFilename());
5851  }
5852
5853  const char *Exec =
5854    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5855  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5856}
5857
5858static void AddLibgcc(llvm::Triple Triple, const Driver &D,
5859                      ArgStringList &CmdArgs, const ArgList &Args) {
5860  bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
5861  bool StaticLibgcc = isAndroid || Args.hasArg(options::OPT_static) ||
5862    Args.hasArg(options::OPT_static_libgcc);
5863  if (!D.CCCIsCXX)
5864    CmdArgs.push_back("-lgcc");
5865
5866  if (StaticLibgcc) {
5867    if (D.CCCIsCXX)
5868      CmdArgs.push_back("-lgcc");
5869  } else {
5870    if (!D.CCCIsCXX)
5871      CmdArgs.push_back("--as-needed");
5872    CmdArgs.push_back("-lgcc_s");
5873    if (!D.CCCIsCXX)
5874      CmdArgs.push_back("--no-as-needed");
5875  }
5876
5877  if (StaticLibgcc && !isAndroid)
5878    CmdArgs.push_back("-lgcc_eh");
5879  else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
5880    CmdArgs.push_back("-lgcc");
5881}
5882
5883static bool hasMipsN32ABIArg(const ArgList &Args) {
5884  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5885  return A && (A->getValue() == StringRef("n32"));
5886}
5887
5888void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
5889                                    const InputInfo &Output,
5890                                    const InputInfoList &Inputs,
5891                                    const ArgList &Args,
5892                                    const char *LinkingOutput) const {
5893  const toolchains::Linux& ToolChain =
5894    static_cast<const toolchains::Linux&>(getToolChain());
5895  const Driver &D = ToolChain.getDriver();
5896  const bool isAndroid =
5897    ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
5898
5899  ArgStringList CmdArgs;
5900
5901  // Silence warning for "clang -g foo.o -o foo"
5902  Args.ClaimAllArgs(options::OPT_g_Group);
5903  // and "clang -emit-llvm foo.o -o foo"
5904  Args.ClaimAllArgs(options::OPT_emit_llvm);
5905  // and for "clang -w foo.o -o foo". Other warning options are already
5906  // handled somewhere else.
5907  Args.ClaimAllArgs(options::OPT_w);
5908
5909  if (!D.SysRoot.empty())
5910    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5911
5912  if (Args.hasArg(options::OPT_pie))
5913    CmdArgs.push_back("-pie");
5914
5915  if (Args.hasArg(options::OPT_rdynamic))
5916    CmdArgs.push_back("-export-dynamic");
5917
5918  if (Args.hasArg(options::OPT_s))
5919    CmdArgs.push_back("-s");
5920
5921  for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
5922         e = ToolChain.ExtraOpts.end();
5923       i != e; ++i)
5924    CmdArgs.push_back(i->c_str());
5925
5926  if (!Args.hasArg(options::OPT_static)) {
5927    CmdArgs.push_back("--eh-frame-hdr");
5928  }
5929
5930  CmdArgs.push_back("-m");
5931  if (ToolChain.getArch() == llvm::Triple::x86)
5932    CmdArgs.push_back("elf_i386");
5933  else if (ToolChain.getArch() == llvm::Triple::arm
5934           ||  ToolChain.getArch() == llvm::Triple::thumb)
5935    CmdArgs.push_back("armelf_linux_eabi");
5936  else if (ToolChain.getArch() == llvm::Triple::ppc)
5937    CmdArgs.push_back("elf32ppclinux");
5938  else if (ToolChain.getArch() == llvm::Triple::ppc64)
5939    CmdArgs.push_back("elf64ppc");
5940  else if (ToolChain.getArch() == llvm::Triple::mips)
5941    CmdArgs.push_back("elf32btsmip");
5942  else if (ToolChain.getArch() == llvm::Triple::mipsel)
5943    CmdArgs.push_back("elf32ltsmip");
5944  else if (ToolChain.getArch() == llvm::Triple::mips64) {
5945    if (hasMipsN32ABIArg(Args))
5946      CmdArgs.push_back("elf32btsmipn32");
5947    else
5948      CmdArgs.push_back("elf64btsmip");
5949  }
5950  else if (ToolChain.getArch() == llvm::Triple::mips64el) {
5951    if (hasMipsN32ABIArg(Args))
5952      CmdArgs.push_back("elf32ltsmipn32");
5953    else
5954      CmdArgs.push_back("elf64ltsmip");
5955  }
5956  else
5957    CmdArgs.push_back("elf_x86_64");
5958
5959  if (Args.hasArg(options::OPT_static)) {
5960    if (ToolChain.getArch() == llvm::Triple::arm
5961        || ToolChain.getArch() == llvm::Triple::thumb)
5962      CmdArgs.push_back("-Bstatic");
5963    else
5964      CmdArgs.push_back("-static");
5965  } else if (Args.hasArg(options::OPT_shared)) {
5966    CmdArgs.push_back("-shared");
5967    if (isAndroid) {
5968      CmdArgs.push_back("-Bsymbolic");
5969    }
5970  }
5971
5972  if (ToolChain.getArch() == llvm::Triple::arm ||
5973      ToolChain.getArch() == llvm::Triple::thumb ||
5974      (!Args.hasArg(options::OPT_static) &&
5975       !Args.hasArg(options::OPT_shared))) {
5976    CmdArgs.push_back("-dynamic-linker");
5977    if (isAndroid)
5978      CmdArgs.push_back("/system/bin/linker");
5979    else if (ToolChain.getArch() == llvm::Triple::x86)
5980      CmdArgs.push_back("/lib/ld-linux.so.2");
5981    else if (ToolChain.getArch() == llvm::Triple::arm ||
5982             ToolChain.getArch() == llvm::Triple::thumb) {
5983      if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
5984        CmdArgs.push_back("/lib/ld-linux-armhf.so.3");
5985      else
5986        CmdArgs.push_back("/lib/ld-linux.so.3");
5987    }
5988    else if (ToolChain.getArch() == llvm::Triple::mips ||
5989             ToolChain.getArch() == llvm::Triple::mipsel)
5990      CmdArgs.push_back("/lib/ld.so.1");
5991    else if (ToolChain.getArch() == llvm::Triple::mips64 ||
5992             ToolChain.getArch() == llvm::Triple::mips64el) {
5993      if (hasMipsN32ABIArg(Args))
5994        CmdArgs.push_back("/lib32/ld.so.1");
5995      else
5996        CmdArgs.push_back("/lib64/ld.so.1");
5997    }
5998    else if (ToolChain.getArch() == llvm::Triple::ppc)
5999      CmdArgs.push_back("/lib/ld.so.1");
6000    else if (ToolChain.getArch() == llvm::Triple::ppc64)
6001      CmdArgs.push_back("/lib64/ld64.so.1");
6002    else
6003      CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
6004  }
6005
6006  CmdArgs.push_back("-o");
6007  CmdArgs.push_back(Output.getFilename());
6008
6009  if (!Args.hasArg(options::OPT_nostdlib) &&
6010      !Args.hasArg(options::OPT_nostartfiles)) {
6011    if (!isAndroid) {
6012      const char *crt1 = NULL;
6013      if (!Args.hasArg(options::OPT_shared)){
6014        if (Args.hasArg(options::OPT_pie))
6015          crt1 = "Scrt1.o";
6016        else
6017          crt1 = "crt1.o";
6018      }
6019      if (crt1)
6020        CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
6021
6022      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
6023    }
6024
6025    const char *crtbegin;
6026    if (Args.hasArg(options::OPT_static))
6027      crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
6028    else if (Args.hasArg(options::OPT_shared))
6029      crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
6030    else if (Args.hasArg(options::OPT_pie))
6031      crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
6032    else
6033      crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
6034    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
6035
6036    // Add crtfastmath.o if available and fast math is enabled.
6037    ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
6038  }
6039
6040  Args.AddAllArgs(CmdArgs, options::OPT_L);
6041
6042  const ToolChain::path_list Paths = ToolChain.getFilePaths();
6043
6044  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
6045       i != e; ++i)
6046    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
6047
6048  // Tell the linker to load the plugin. This has to come before AddLinkerInputs
6049  // as gold requires -plugin to come before any -plugin-opt that -Wl might
6050  // forward.
6051  if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
6052    CmdArgs.push_back("-plugin");
6053    std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
6054    CmdArgs.push_back(Args.MakeArgString(Plugin));
6055  }
6056
6057  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6058    CmdArgs.push_back("--no-demangle");
6059
6060  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6061
6062  SanitizerArgs Sanitize(D, Args);
6063
6064  // Call this before we add the C++ ABI library.
6065  if (Sanitize.needsUbsanRt())
6066    addUbsanRTLinux(getToolChain(), Args, CmdArgs);
6067
6068  if (D.CCCIsCXX &&
6069      !Args.hasArg(options::OPT_nostdlib) &&
6070      !Args.hasArg(options::OPT_nodefaultlibs)) {
6071    bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
6072      !Args.hasArg(options::OPT_static);
6073    if (OnlyLibstdcxxStatic)
6074      CmdArgs.push_back("-Bstatic");
6075    ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6076    if (OnlyLibstdcxxStatic)
6077      CmdArgs.push_back("-Bdynamic");
6078    CmdArgs.push_back("-lm");
6079  }
6080
6081  // Call this before we add the C run-time.
6082  if (Sanitize.needsAsanRt())
6083    addAsanRTLinux(getToolChain(), Args, CmdArgs);
6084  if (Sanitize.needsTsanRt())
6085    addTsanRTLinux(getToolChain(), Args, CmdArgs);
6086
6087  if (!Args.hasArg(options::OPT_nostdlib)) {
6088    if (!Args.hasArg(options::OPT_nodefaultlibs)) {
6089      if (Args.hasArg(options::OPT_static))
6090        CmdArgs.push_back("--start-group");
6091
6092      AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6093
6094      if (Args.hasArg(options::OPT_pthread) ||
6095          Args.hasArg(options::OPT_pthreads))
6096        CmdArgs.push_back("-lpthread");
6097
6098      CmdArgs.push_back("-lc");
6099
6100      if (Args.hasArg(options::OPT_static))
6101        CmdArgs.push_back("--end-group");
6102      else
6103        AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6104    }
6105
6106    if (!Args.hasArg(options::OPT_nostartfiles)) {
6107      const char *crtend;
6108      if (Args.hasArg(options::OPT_shared))
6109        crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
6110      else if (Args.hasArg(options::OPT_pie))
6111        crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
6112      else
6113        crtend = isAndroid ? "crtend_android.o" : "crtend.o";
6114
6115      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
6116      if (!isAndroid)
6117        CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6118    }
6119  }
6120
6121  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6122
6123  C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
6124}
6125
6126void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6127                                   const InputInfo &Output,
6128                                   const InputInfoList &Inputs,
6129                                   const ArgList &Args,
6130                                   const char *LinkingOutput) const {
6131  ArgStringList CmdArgs;
6132
6133  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6134                       options::OPT_Xassembler);
6135
6136  CmdArgs.push_back("-o");
6137  CmdArgs.push_back(Output.getFilename());
6138
6139  for (InputInfoList::const_iterator
6140         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6141    const InputInfo &II = *it;
6142    CmdArgs.push_back(II.getFilename());
6143  }
6144
6145  const char *Exec =
6146    Args.MakeArgString(getToolChain().GetProgramPath("as"));
6147  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6148}
6149
6150void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
6151                               const InputInfo &Output,
6152                               const InputInfoList &Inputs,
6153                               const ArgList &Args,
6154                               const char *LinkingOutput) const {
6155  const Driver &D = getToolChain().getDriver();
6156  ArgStringList CmdArgs;
6157
6158  if (Output.isFilename()) {
6159    CmdArgs.push_back("-o");
6160    CmdArgs.push_back(Output.getFilename());
6161  } else {
6162    assert(Output.isNothing() && "Invalid output.");
6163  }
6164
6165  if (!Args.hasArg(options::OPT_nostdlib) &&
6166      !Args.hasArg(options::OPT_nostartfiles)) {
6167      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
6168      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6169      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6170      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
6171  }
6172
6173  Args.AddAllArgs(CmdArgs, options::OPT_L);
6174  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6175  Args.AddAllArgs(CmdArgs, options::OPT_e);
6176
6177  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6178
6179  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6180
6181  if (!Args.hasArg(options::OPT_nostdlib) &&
6182      !Args.hasArg(options::OPT_nodefaultlibs)) {
6183    if (D.CCCIsCXX) {
6184      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6185      CmdArgs.push_back("-lm");
6186    }
6187  }
6188
6189  if (!Args.hasArg(options::OPT_nostdlib) &&
6190      !Args.hasArg(options::OPT_nostartfiles)) {
6191    if (Args.hasArg(options::OPT_pthread))
6192      CmdArgs.push_back("-lpthread");
6193    CmdArgs.push_back("-lc");
6194    CmdArgs.push_back("-lCompilerRT-Generic");
6195    CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
6196    CmdArgs.push_back(
6197	 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
6198  }
6199
6200  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6201  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6202}
6203
6204/// DragonFly Tools
6205
6206// For now, DragonFly Assemble does just about the same as for
6207// FreeBSD, but this may change soon.
6208void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6209                                       const InputInfo &Output,
6210                                       const InputInfoList &Inputs,
6211                                       const ArgList &Args,
6212                                       const char *LinkingOutput) const {
6213  ArgStringList CmdArgs;
6214
6215  // When building 32-bit code on DragonFly/pc64, we have to explicitly
6216  // instruct as in the base system to assemble 32-bit code.
6217  if (getToolChain().getArch() == llvm::Triple::x86)
6218    CmdArgs.push_back("--32");
6219
6220  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6221                       options::OPT_Xassembler);
6222
6223  CmdArgs.push_back("-o");
6224  CmdArgs.push_back(Output.getFilename());
6225
6226  for (InputInfoList::const_iterator
6227         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6228    const InputInfo &II = *it;
6229    CmdArgs.push_back(II.getFilename());
6230  }
6231
6232  const char *Exec =
6233    Args.MakeArgString(getToolChain().GetProgramPath("as"));
6234  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6235}
6236
6237void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
6238                                   const InputInfo &Output,
6239                                   const InputInfoList &Inputs,
6240                                   const ArgList &Args,
6241                                   const char *LinkingOutput) const {
6242  const Driver &D = getToolChain().getDriver();
6243  ArgStringList CmdArgs;
6244
6245  if (!D.SysRoot.empty())
6246    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6247
6248  if (Args.hasArg(options::OPT_static)) {
6249    CmdArgs.push_back("-Bstatic");
6250  } else {
6251    if (Args.hasArg(options::OPT_shared))
6252      CmdArgs.push_back("-Bshareable");
6253    else {
6254      CmdArgs.push_back("-dynamic-linker");
6255      CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
6256    }
6257  }
6258
6259  // When building 32-bit code on DragonFly/pc64, we have to explicitly
6260  // instruct ld in the base system to link 32-bit code.
6261  if (getToolChain().getArch() == llvm::Triple::x86) {
6262    CmdArgs.push_back("-m");
6263    CmdArgs.push_back("elf_i386");
6264  }
6265
6266  if (Output.isFilename()) {
6267    CmdArgs.push_back("-o");
6268    CmdArgs.push_back(Output.getFilename());
6269  } else {
6270    assert(Output.isNothing() && "Invalid output.");
6271  }
6272
6273  if (!Args.hasArg(options::OPT_nostdlib) &&
6274      !Args.hasArg(options::OPT_nostartfiles)) {
6275    if (!Args.hasArg(options::OPT_shared)) {
6276      CmdArgs.push_back(
6277            Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
6278      CmdArgs.push_back(
6279            Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6280      CmdArgs.push_back(
6281            Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6282    } else {
6283      CmdArgs.push_back(
6284            Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6285      CmdArgs.push_back(
6286            Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6287    }
6288  }
6289
6290  Args.AddAllArgs(CmdArgs, options::OPT_L);
6291  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6292  Args.AddAllArgs(CmdArgs, options::OPT_e);
6293
6294  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6295
6296  if (!Args.hasArg(options::OPT_nostdlib) &&
6297      !Args.hasArg(options::OPT_nodefaultlibs)) {
6298    // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
6299    //         rpaths
6300    CmdArgs.push_back("-L/usr/lib/gcc41");
6301
6302    if (!Args.hasArg(options::OPT_static)) {
6303      CmdArgs.push_back("-rpath");
6304      CmdArgs.push_back("/usr/lib/gcc41");
6305
6306      CmdArgs.push_back("-rpath-link");
6307      CmdArgs.push_back("/usr/lib/gcc41");
6308
6309      CmdArgs.push_back("-rpath");
6310      CmdArgs.push_back("/usr/lib");
6311
6312      CmdArgs.push_back("-rpath-link");
6313      CmdArgs.push_back("/usr/lib");
6314    }
6315
6316    if (D.CCCIsCXX) {
6317      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6318      CmdArgs.push_back("-lm");
6319    }
6320
6321    if (Args.hasArg(options::OPT_shared)) {
6322      CmdArgs.push_back("-lgcc_pic");
6323    } else {
6324      CmdArgs.push_back("-lgcc");
6325    }
6326
6327
6328    if (Args.hasArg(options::OPT_pthread))
6329      CmdArgs.push_back("-lpthread");
6330
6331    if (!Args.hasArg(options::OPT_nolibc)) {
6332      CmdArgs.push_back("-lc");
6333    }
6334
6335    if (Args.hasArg(options::OPT_shared)) {
6336      CmdArgs.push_back("-lgcc_pic");
6337    } else {
6338      CmdArgs.push_back("-lgcc");
6339    }
6340  }
6341
6342  if (!Args.hasArg(options::OPT_nostdlib) &&
6343      !Args.hasArg(options::OPT_nostartfiles)) {
6344    if (!Args.hasArg(options::OPT_shared))
6345      CmdArgs.push_back(Args.MakeArgString(
6346                              getToolChain().GetFilePath("crtend.o")));
6347    else
6348      CmdArgs.push_back(Args.MakeArgString(
6349                              getToolChain().GetFilePath("crtendS.o")));
6350    CmdArgs.push_back(Args.MakeArgString(
6351                              getToolChain().GetFilePath("crtn.o")));
6352  }
6353
6354  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6355
6356  const char *Exec =
6357    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6358  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6359}
6360
6361void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
6362                                      const InputInfo &Output,
6363                                      const InputInfoList &Inputs,
6364                                      const ArgList &Args,
6365                                      const char *LinkingOutput) const {
6366  ArgStringList CmdArgs;
6367
6368  if (Output.isFilename()) {
6369    CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
6370                                         Output.getFilename()));
6371  } else {
6372    assert(Output.isNothing() && "Invalid output.");
6373  }
6374
6375  if (!Args.hasArg(options::OPT_nostdlib) &&
6376    !Args.hasArg(options::OPT_nostartfiles)) {
6377    CmdArgs.push_back("-defaultlib:libcmt");
6378  }
6379
6380  CmdArgs.push_back("-nologo");
6381
6382  Args.AddAllArgValues(CmdArgs, options::OPT_l);
6383
6384  // Add filenames immediately.
6385  for (InputInfoList::const_iterator
6386       it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6387    if (it->isFilename())
6388      CmdArgs.push_back(it->getFilename());
6389  }
6390
6391  const char *Exec =
6392    Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
6393  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6394}
6395