clang API Documentation

Tools.cpp
Go to the documentation of this file.
00001 //===--- Tools.cpp - Tools Implementations --------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "Tools.h"
00011 #include "InputInfo.h"
00012 #include "ToolChains.h"
00013 #include "clang/Basic/LangOptions.h"
00014 #include "clang/Basic/ObjCRuntime.h"
00015 #include "clang/Basic/Version.h"
00016 #include "clang/Driver/Action.h"
00017 #include "clang/Driver/Compilation.h"
00018 #include "clang/Driver/Driver.h"
00019 #include "clang/Driver/DriverDiagnostic.h"
00020 #include "clang/Driver/Job.h"
00021 #include "clang/Driver/Options.h"
00022 #include "clang/Driver/SanitizerArgs.h"
00023 #include "clang/Driver/ToolChain.h"
00024 #include "clang/Driver/Util.h"
00025 #include "llvm/ADT/SmallString.h"
00026 #include "llvm/ADT/StringExtras.h"
00027 #include "llvm/ADT/StringSwitch.h"
00028 #include "llvm/ADT/Twine.h"
00029 #include "llvm/Option/Arg.h"
00030 #include "llvm/Option/ArgList.h"
00031 #include "llvm/Option/Option.h"
00032 #include "llvm/Support/Compression.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/FileSystem.h"
00035 #include "llvm/Support/Format.h"
00036 #include "llvm/Support/Host.h"
00037 #include "llvm/Support/Path.h"
00038 #include "llvm/Support/Process.h"
00039 #include "llvm/Support/Program.h"
00040 #include "llvm/Support/raw_ostream.h"
00041 
00042 using namespace clang::driver;
00043 using namespace clang::driver::tools;
00044 using namespace clang;
00045 using namespace llvm::opt;
00046 
00047 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
00048   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
00049                                     options::OPT_fpic, options::OPT_fno_pic,
00050                                     options::OPT_fPIE, options::OPT_fno_PIE,
00051                                     options::OPT_fpie, options::OPT_fno_pie);
00052   if (!LastPICArg)
00053     return;
00054   if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
00055       LastPICArg->getOption().matches(options::OPT_fpic) ||
00056       LastPICArg->getOption().matches(options::OPT_fPIE) ||
00057       LastPICArg->getOption().matches(options::OPT_fpie)) {
00058     CmdArgs.push_back("-KPIC");
00059   }
00060 }
00061 
00062 /// CheckPreprocessingOptions - Perform some validation of preprocessing
00063 /// arguments that is shared with gcc.
00064 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
00065   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
00066     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
00067         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
00068       D.Diag(diag::err_drv_argument_only_allowed_with)
00069           << A->getBaseArg().getAsString(Args)
00070           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
00071     }
00072   }
00073 }
00074 
00075 /// CheckCodeGenerationOptions - Perform some validation of code generation
00076 /// arguments that is shared with gcc.
00077 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
00078   // In gcc, only ARM checks this, but it seems reasonable to check universally.
00079   if (Args.hasArg(options::OPT_static))
00080     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
00081                                        options::OPT_mdynamic_no_pic))
00082       D.Diag(diag::err_drv_argument_not_allowed_with)
00083         << A->getAsString(Args) << "-static";
00084 }
00085 
00086 // Add backslashes to escape spaces and other backslashes.
00087 // This is used for the space-separated argument list specified with
00088 // the -dwarf-debug-flags option.
00089 static void EscapeSpacesAndBackslashes(const char *Arg,
00090                                        SmallVectorImpl<char> &Res) {
00091   for ( ; *Arg; ++Arg) {
00092     switch (*Arg) {
00093     default: break;
00094     case ' ':
00095     case '\\':
00096       Res.push_back('\\');
00097       break;
00098     }
00099     Res.push_back(*Arg);
00100   }
00101 }
00102 
00103 // Quote target names for inclusion in GNU Make dependency files.
00104 // Only the characters '$', '#', ' ', '\t' are quoted.
00105 static void QuoteTarget(StringRef Target,
00106                         SmallVectorImpl<char> &Res) {
00107   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
00108     switch (Target[i]) {
00109     case ' ':
00110     case '\t':
00111       // Escape the preceding backslashes
00112       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
00113         Res.push_back('\\');
00114 
00115       // Escape the space/tab
00116       Res.push_back('\\');
00117       break;
00118     case '$':
00119       Res.push_back('$');
00120       break;
00121     case '#':
00122       Res.push_back('\\');
00123       break;
00124     default:
00125       break;
00126     }
00127 
00128     Res.push_back(Target[i]);
00129   }
00130 }
00131 
00132 static void addDirectoryList(const ArgList &Args,
00133                              ArgStringList &CmdArgs,
00134                              const char *ArgName,
00135                              const char *EnvVar) {
00136   const char *DirList = ::getenv(EnvVar);
00137   bool CombinedArg = false;
00138 
00139   if (!DirList)
00140     return; // Nothing to do.
00141 
00142   StringRef Name(ArgName);
00143   if (Name.equals("-I") || Name.equals("-L"))
00144     CombinedArg = true;
00145 
00146   StringRef Dirs(DirList);
00147   if (Dirs.empty()) // Empty string should not add '.'.
00148     return;
00149 
00150   StringRef::size_type Delim;
00151   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
00152     if (Delim == 0) { // Leading colon.
00153       if (CombinedArg) {
00154         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
00155       } else {
00156         CmdArgs.push_back(ArgName);
00157         CmdArgs.push_back(".");
00158       }
00159     } else {
00160       if (CombinedArg) {
00161         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
00162       } else {
00163         CmdArgs.push_back(ArgName);
00164         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
00165       }
00166     }
00167     Dirs = Dirs.substr(Delim + 1);
00168   }
00169 
00170   if (Dirs.empty()) { // Trailing colon.
00171     if (CombinedArg) {
00172       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
00173     } else {
00174       CmdArgs.push_back(ArgName);
00175       CmdArgs.push_back(".");
00176     }
00177   } else { // Add the last path.
00178     if (CombinedArg) {
00179       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
00180     } else {
00181       CmdArgs.push_back(ArgName);
00182       CmdArgs.push_back(Args.MakeArgString(Dirs));
00183     }
00184   }
00185 }
00186 
00187 static void AddLinkerInputs(const ToolChain &TC,
00188                             const InputInfoList &Inputs, const ArgList &Args,
00189                             ArgStringList &CmdArgs) {
00190   const Driver &D = TC.getDriver();
00191 
00192   // Add extra linker input arguments which are not treated as inputs
00193   // (constructed via -Xarch_).
00194   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
00195 
00196   for (const auto &II : Inputs) {
00197     if (!TC.HasNativeLLVMSupport()) {
00198       // Don't try to pass LLVM inputs unless we have native support.
00199       if (II.getType() == types::TY_LLVM_IR ||
00200           II.getType() == types::TY_LTO_IR ||
00201           II.getType() == types::TY_LLVM_BC ||
00202           II.getType() == types::TY_LTO_BC)
00203         D.Diag(diag::err_drv_no_linker_llvm_support)
00204           << TC.getTripleString();
00205     }
00206 
00207     // Add filenames immediately.
00208     if (II.isFilename()) {
00209       CmdArgs.push_back(II.getFilename());
00210       continue;
00211     }
00212 
00213     // Otherwise, this is a linker input argument.
00214     const Arg &A = II.getInputArg();
00215 
00216     // Handle reserved library options.
00217     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
00218       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
00219     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
00220       TC.AddCCKextLibArgs(Args, CmdArgs);
00221     else if (A.getOption().matches(options::OPT_z)) {
00222       // Pass -z prefix for gcc linker compatibility.
00223       A.claim();
00224       A.render(Args, CmdArgs);
00225     } else {
00226        A.renderAsInput(Args, CmdArgs);
00227     }
00228   }
00229 
00230   // LIBRARY_PATH - included following the user specified library paths.
00231   //                and only supported on native toolchains.
00232   if (!TC.isCrossCompiling())
00233     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
00234 }
00235 
00236 /// \brief Determine whether Objective-C automated reference counting is
00237 /// enabled.
00238 static bool isObjCAutoRefCount(const ArgList &Args) {
00239   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
00240 }
00241 
00242 /// \brief Determine whether we are linking the ObjC runtime.
00243 static bool isObjCRuntimeLinked(const ArgList &Args) {
00244   if (isObjCAutoRefCount(Args)) {
00245     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
00246     return true;
00247   }
00248   return Args.hasArg(options::OPT_fobjc_link_runtime);
00249 }
00250 
00251 static bool forwardToGCC(const Option &O) {
00252   // Don't forward inputs from the original command line.  They are added from
00253   // InputInfoList.
00254   return O.getKind() != Option::InputClass &&
00255          !O.hasFlag(options::DriverOption) &&
00256          !O.hasFlag(options::LinkerInput);
00257 }
00258 
00259 void Clang::AddPreprocessingOptions(Compilation &C,
00260                                     const JobAction &JA,
00261                                     const Driver &D,
00262                                     const ArgList &Args,
00263                                     ArgStringList &CmdArgs,
00264                                     const InputInfo &Output,
00265                                     const InputInfoList &Inputs) const {
00266   Arg *A;
00267 
00268   CheckPreprocessingOptions(D, Args);
00269 
00270   Args.AddLastArg(CmdArgs, options::OPT_C);
00271   Args.AddLastArg(CmdArgs, options::OPT_CC);
00272 
00273   // Handle dependency file generation.
00274   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
00275       (A = Args.getLastArg(options::OPT_MD)) ||
00276       (A = Args.getLastArg(options::OPT_MMD))) {
00277     // Determine the output location.
00278     const char *DepFile;
00279     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
00280       DepFile = MF->getValue();
00281       C.addFailureResultFile(DepFile, &JA);
00282     } else if (Output.getType() == types::TY_Dependencies) {
00283       DepFile = Output.getFilename();
00284     } else if (A->getOption().matches(options::OPT_M) ||
00285                A->getOption().matches(options::OPT_MM)) {
00286       DepFile = "-";
00287     } else {
00288       DepFile = getDependencyFileName(Args, Inputs);
00289       C.addFailureResultFile(DepFile, &JA);
00290     }
00291     CmdArgs.push_back("-dependency-file");
00292     CmdArgs.push_back(DepFile);
00293 
00294     // Add a default target if one wasn't specified.
00295     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
00296       const char *DepTarget;
00297 
00298       // If user provided -o, that is the dependency target, except
00299       // when we are only generating a dependency file.
00300       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
00301       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
00302         DepTarget = OutputOpt->getValue();
00303       } else {
00304         // Otherwise derive from the base input.
00305         //
00306         // FIXME: This should use the computed output file location.
00307         SmallString<128> P(Inputs[0].getBaseInput());
00308         llvm::sys::path::replace_extension(P, "o");
00309         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
00310       }
00311 
00312       CmdArgs.push_back("-MT");
00313       SmallString<128> Quoted;
00314       QuoteTarget(DepTarget, Quoted);
00315       CmdArgs.push_back(Args.MakeArgString(Quoted));
00316     }
00317 
00318     if (A->getOption().matches(options::OPT_M) ||
00319         A->getOption().matches(options::OPT_MD))
00320       CmdArgs.push_back("-sys-header-deps");
00321 
00322     if (isa<PrecompileJobAction>(JA))
00323       CmdArgs.push_back("-module-file-deps");
00324   }
00325 
00326   if (Args.hasArg(options::OPT_MG)) {
00327     if (!A || A->getOption().matches(options::OPT_MD) ||
00328               A->getOption().matches(options::OPT_MMD))
00329       D.Diag(diag::err_drv_mg_requires_m_or_mm);
00330     CmdArgs.push_back("-MG");
00331   }
00332 
00333   Args.AddLastArg(CmdArgs, options::OPT_MP);
00334 
00335   // Convert all -MQ <target> args to -MT <quoted target>
00336   for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
00337                                              options::OPT_MQ),
00338          ie = Args.filtered_end(); it != ie; ++it) {
00339     const Arg *A = *it;
00340     A->claim();
00341 
00342     if (A->getOption().matches(options::OPT_MQ)) {
00343       CmdArgs.push_back("-MT");
00344       SmallString<128> Quoted;
00345       QuoteTarget(A->getValue(), Quoted);
00346       CmdArgs.push_back(Args.MakeArgString(Quoted));
00347 
00348     // -MT flag - no change
00349     } else {
00350       A->render(Args, CmdArgs);
00351     }
00352   }
00353 
00354   // Add -i* options, and automatically translate to
00355   // -include-pch/-include-pth for transparent PCH support. It's
00356   // wonky, but we include looking for .gch so we can support seamless
00357   // replacement into a build system already set up to be generating
00358   // .gch files.
00359   bool RenderedImplicitInclude = false;
00360   for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
00361          ie = Args.filtered_end(); it != ie; ++it) {
00362     const Arg *A = it;
00363 
00364     if (A->getOption().matches(options::OPT_include)) {
00365       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
00366       RenderedImplicitInclude = true;
00367 
00368       // Use PCH if the user requested it.
00369       bool UsePCH = D.CCCUsePCH;
00370 
00371       bool FoundPTH = false;
00372       bool FoundPCH = false;
00373       SmallString<128> P(A->getValue());
00374       // We want the files to have a name like foo.h.pch. Add a dummy extension
00375       // so that replace_extension does the right thing.
00376       P += ".dummy";
00377       if (UsePCH) {
00378         llvm::sys::path::replace_extension(P, "pch");
00379         if (llvm::sys::fs::exists(P.str()))
00380           FoundPCH = true;
00381       }
00382 
00383       if (!FoundPCH) {
00384         llvm::sys::path::replace_extension(P, "pth");
00385         if (llvm::sys::fs::exists(P.str()))
00386           FoundPTH = true;
00387       }
00388 
00389       if (!FoundPCH && !FoundPTH) {
00390         llvm::sys::path::replace_extension(P, "gch");
00391         if (llvm::sys::fs::exists(P.str())) {
00392           FoundPCH = UsePCH;
00393           FoundPTH = !UsePCH;
00394         }
00395       }
00396 
00397       if (FoundPCH || FoundPTH) {
00398         if (IsFirstImplicitInclude) {
00399           A->claim();
00400           if (UsePCH)
00401             CmdArgs.push_back("-include-pch");
00402           else
00403             CmdArgs.push_back("-include-pth");
00404           CmdArgs.push_back(Args.MakeArgString(P.str()));
00405           continue;
00406         } else {
00407           // Ignore the PCH if not first on command line and emit warning.
00408           D.Diag(diag::warn_drv_pch_not_first_include)
00409               << P.str() << A->getAsString(Args);
00410         }
00411       }
00412     }
00413 
00414     // Not translated, render as usual.
00415     A->claim();
00416     A->render(Args, CmdArgs);
00417   }
00418 
00419   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
00420   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
00421                   options::OPT_index_header_map);
00422 
00423   // Add -Wp, and -Xassembler if using the preprocessor.
00424 
00425   // FIXME: There is a very unfortunate problem here, some troubled
00426   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
00427   // really support that we would have to parse and then translate
00428   // those options. :(
00429   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
00430                        options::OPT_Xpreprocessor);
00431 
00432   // -I- is a deprecated GCC feature, reject it.
00433   if (Arg *A = Args.getLastArg(options::OPT_I_))
00434     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
00435 
00436   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
00437   // -isysroot to the CC1 invocation.
00438   StringRef sysroot = C.getSysRoot();
00439   if (sysroot != "") {
00440     if (!Args.hasArg(options::OPT_isysroot)) {
00441       CmdArgs.push_back("-isysroot");
00442       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
00443     }
00444   }
00445 
00446   // Parse additional include paths from environment variables.
00447   // FIXME: We should probably sink the logic for handling these from the
00448   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
00449   // CPATH - included following the user specified includes (but prior to
00450   // builtin and standard includes).
00451   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
00452   // C_INCLUDE_PATH - system includes enabled when compiling C.
00453   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
00454   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
00455   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
00456   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
00457   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
00458   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
00459   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
00460 
00461   // Add C++ include arguments, if needed.
00462   if (types::isCXX(Inputs[0].getType()))
00463     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
00464 
00465   // Add system include arguments.
00466   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
00467 }
00468 
00469 // FIXME: Move to target hook.
00470 static bool isSignedCharDefault(const llvm::Triple &Triple) {
00471   switch (Triple.getArch()) {
00472   default:
00473     return true;
00474 
00475   case llvm::Triple::aarch64:
00476   case llvm::Triple::aarch64_be:
00477   case llvm::Triple::arm:
00478   case llvm::Triple::armeb:
00479   case llvm::Triple::thumb:
00480   case llvm::Triple::thumbeb:
00481     if (Triple.isOSDarwin() || Triple.isOSWindows())
00482       return true;
00483     return false;
00484 
00485   case llvm::Triple::ppc:
00486   case llvm::Triple::ppc64:
00487     if (Triple.isOSDarwin())
00488       return true;
00489     return false;
00490 
00491   case llvm::Triple::ppc64le:
00492   case llvm::Triple::systemz:
00493   case llvm::Triple::xcore:
00494     return false;
00495   }
00496 }
00497 
00498 static bool isNoCommonDefault(const llvm::Triple &Triple) {
00499   switch (Triple.getArch()) {
00500   default:
00501     return false;
00502 
00503   case llvm::Triple::xcore:
00504     return true;
00505   }
00506 }
00507 
00508 // Handle -mhwdiv=.
00509 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
00510                               const ArgList &Args,
00511                               std::vector<const char *> &Features) {
00512   StringRef HWDiv = A->getValue();
00513   if (HWDiv == "arm") {
00514     Features.push_back("+hwdiv-arm");
00515     Features.push_back("-hwdiv");
00516   } else if (HWDiv == "thumb") {
00517     Features.push_back("-hwdiv-arm");
00518     Features.push_back("+hwdiv");
00519   } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
00520     Features.push_back("+hwdiv-arm");
00521     Features.push_back("+hwdiv");
00522   } else if (HWDiv == "none") {
00523     Features.push_back("-hwdiv-arm");
00524     Features.push_back("-hwdiv");
00525   } else
00526     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
00527 }
00528 
00529 // Handle -mfpu=.
00530 //
00531 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
00532 // frontend target.
00533 static void getARMFPUFeatures(const Driver &D, const Arg *A,
00534                               const ArgList &Args,
00535                               std::vector<const char *> &Features) {
00536   StringRef FPU = A->getValue();
00537 
00538   // Set the target features based on the FPU.
00539   if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
00540     // Disable any default FPU support.
00541     Features.push_back("-vfp2");
00542     Features.push_back("-vfp3");
00543     Features.push_back("-neon");
00544   } else if (FPU == "vfp") {
00545     Features.push_back("+vfp2");
00546     Features.push_back("-neon");
00547   } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
00548     Features.push_back("+vfp3");
00549     Features.push_back("+d16");
00550     Features.push_back("-neon");
00551   } else if (FPU == "vfp3" || FPU == "vfpv3") {
00552     Features.push_back("+vfp3");
00553     Features.push_back("-neon");
00554   } else if (FPU == "vfp4-d16" || FPU == "vfpv4-d16") {
00555     Features.push_back("+vfp4");
00556     Features.push_back("+d16");
00557     Features.push_back("-neon");
00558   } else if (FPU == "vfp4" || FPU == "vfpv4") {
00559     Features.push_back("+vfp4");
00560     Features.push_back("-neon");
00561   } else if (FPU == "fp4-sp-d16" || FPU == "fpv4-sp-d16") {
00562     Features.push_back("+vfp4");
00563     Features.push_back("+d16");
00564     Features.push_back("+fp-only-sp");
00565     Features.push_back("-neon");
00566   } else if (FPU == "fp5-sp-d16" || FPU == "fpv5-sp-d16") {
00567     Features.push_back("+fp-armv8");
00568     Features.push_back("+fp-only-sp");
00569     Features.push_back("+d16");
00570     Features.push_back("-neon");
00571     Features.push_back("-crypto");
00572   } else if (FPU == "fp5-dp-d16" || FPU == "fpv5-dp-d16" ||
00573              FPU == "fp5-d16" || FPU == "fpv5-d16") {
00574     Features.push_back("+fp-armv8");
00575     Features.push_back("+d16");
00576     Features.push_back("-neon");
00577     Features.push_back("-crypto");
00578   } else if (FPU == "fp-armv8") {
00579     Features.push_back("+fp-armv8");
00580     Features.push_back("-neon");
00581     Features.push_back("-crypto");
00582   } else if (FPU == "neon-fp-armv8") {
00583     Features.push_back("+fp-armv8");
00584     Features.push_back("+neon");
00585     Features.push_back("-crypto");
00586   } else if (FPU == "crypto-neon-fp-armv8") {
00587     Features.push_back("+fp-armv8");
00588     Features.push_back("+neon");
00589     Features.push_back("+crypto");
00590   } else if (FPU == "neon") {
00591     Features.push_back("+neon");
00592   } else if (FPU == "none") {
00593     Features.push_back("-vfp2");
00594     Features.push_back("-vfp3");
00595     Features.push_back("-vfp4");
00596     Features.push_back("-fp-armv8");
00597     Features.push_back("-crypto");
00598     Features.push_back("-neon");
00599   } else
00600     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
00601 }
00602 
00603 // Select the float ABI as determined by -msoft-float, -mhard-float, and
00604 // -mfloat-abi=.
00605 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
00606                                      const llvm::Triple &Triple) {
00607   StringRef FloatABI;
00608   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
00609                                options::OPT_mhard_float,
00610                                options::OPT_mfloat_abi_EQ)) {
00611     if (A->getOption().matches(options::OPT_msoft_float))
00612       FloatABI = "soft";
00613     else if (A->getOption().matches(options::OPT_mhard_float))
00614       FloatABI = "hard";
00615     else {
00616       FloatABI = A->getValue();
00617       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
00618         D.Diag(diag::err_drv_invalid_mfloat_abi)
00619           << A->getAsString(Args);
00620         FloatABI = "soft";
00621       }
00622     }
00623   }
00624 
00625   // If unspecified, choose the default based on the platform.
00626   if (FloatABI.empty()) {
00627     switch (Triple.getOS()) {
00628     case llvm::Triple::Darwin:
00629     case llvm::Triple::MacOSX:
00630     case llvm::Triple::IOS: {
00631       // Darwin defaults to "softfp" for v6 and v7.
00632       //
00633       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
00634       std::string ArchName =
00635         arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
00636       if (StringRef(ArchName).startswith("v6") ||
00637           StringRef(ArchName).startswith("v7"))
00638         FloatABI = "softfp";
00639       else
00640         FloatABI = "soft";
00641       break;
00642     }
00643 
00644     // FIXME: this is invalid for WindowsCE
00645     case llvm::Triple::Win32:
00646       FloatABI = "hard";
00647       break;
00648 
00649     case llvm::Triple::FreeBSD:
00650       switch(Triple.getEnvironment()) {
00651       case llvm::Triple::GNUEABIHF:
00652         FloatABI = "hard";
00653         break;
00654       default:
00655         // FreeBSD defaults to soft float
00656         FloatABI = "soft";
00657         break;
00658       }
00659       break;
00660 
00661     default:
00662       switch(Triple.getEnvironment()) {
00663       case llvm::Triple::GNUEABIHF:
00664         FloatABI = "hard";
00665         break;
00666       case llvm::Triple::GNUEABI:
00667         FloatABI = "softfp";
00668         break;
00669       case llvm::Triple::EABIHF:
00670         FloatABI = "hard";
00671         break;
00672       case llvm::Triple::EABI:
00673         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
00674         FloatABI = "softfp";
00675         break;
00676       case llvm::Triple::Android: {
00677         std::string ArchName =
00678           arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
00679         if (StringRef(ArchName).startswith("v7"))
00680           FloatABI = "softfp";
00681         else
00682           FloatABI = "soft";
00683         break;
00684       }
00685       default:
00686         // Assume "soft", but warn the user we are guessing.
00687         FloatABI = "soft";
00688         if (Triple.getOS() != llvm::Triple::UnknownOS ||
00689             !Triple.isOSBinFormatMachO())
00690           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
00691         break;
00692       }
00693     }
00694   }
00695 
00696   return FloatABI;
00697 }
00698 
00699 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
00700                                  const ArgList &Args,
00701                                  std::vector<const char *> &Features,
00702                                  bool ForAS) {
00703   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
00704   if (!ForAS) {
00705     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
00706     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
00707     // stripped out by the ARM target. We should probably pass this a new
00708     // -target-option, which is handled by the -cc1/-cc1as invocation.
00709     //
00710     // FIXME2:  For consistency, it would be ideal if we set up the target
00711     // machine state the same when using the frontend or the assembler. We don't
00712     // currently do that for the assembler, we pass the options directly to the
00713     // backend and never even instantiate the frontend TargetInfo. If we did,
00714     // and used its handleTargetFeatures hook, then we could ensure the
00715     // assembler and the frontend behave the same.
00716 
00717     // Use software floating point operations?
00718     if (FloatABI == "soft")
00719       Features.push_back("+soft-float");
00720 
00721     // Use software floating point argument passing?
00722     if (FloatABI != "hard")
00723       Features.push_back("+soft-float-abi");
00724   }
00725 
00726   // Honor -mfpu=.
00727   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
00728     getARMFPUFeatures(D, A, Args, Features);
00729   if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
00730     getARMHWDivFeatures(D, A, Args, Features);
00731 
00732   // Setting -msoft-float effectively disables NEON because of the GCC
00733   // implementation, although the same isn't true of VFP or VFP3.
00734   if (FloatABI == "soft") {
00735     Features.push_back("-neon");
00736     // Also need to explicitly disable features which imply NEON.
00737     Features.push_back("-crypto");
00738   }
00739 
00740   // En/disable crc
00741   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
00742                                options::OPT_mnocrc)) {
00743     if (A->getOption().matches(options::OPT_mcrc))
00744       Features.push_back("+crc");
00745     else
00746       Features.push_back("-crc");
00747   }
00748 }
00749 
00750 void Clang::AddARMTargetArgs(const ArgList &Args,
00751                              ArgStringList &CmdArgs,
00752                              bool KernelOrKext) const {
00753   const Driver &D = getToolChain().getDriver();
00754   // Get the effective triple, which takes into account the deployment target.
00755   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
00756   llvm::Triple Triple(TripleStr);
00757   std::string CPUName = arm::getARMTargetCPU(Args, Triple);
00758 
00759   // Select the ABI to use.
00760   //
00761   // FIXME: Support -meabi.
00762   const char *ABIName = nullptr;
00763   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
00764     ABIName = A->getValue();
00765   } else if (Triple.isOSBinFormatMachO()) {
00766     // The backend is hardwired to assume AAPCS for M-class processors, ensure
00767     // the frontend matches that.
00768     if (Triple.getEnvironment() == llvm::Triple::EABI ||
00769         (Triple.getOS() == llvm::Triple::UnknownOS &&
00770          Triple.getObjectFormat() == llvm::Triple::MachO) ||
00771         StringRef(CPUName).startswith("cortex-m")) {
00772       ABIName = "aapcs";
00773     } else {
00774       ABIName = "apcs-gnu";
00775     }
00776   } else if (Triple.isOSWindows()) {
00777     // FIXME: this is invalid for WindowsCE
00778     ABIName = "aapcs";
00779   } else {
00780     // Select the default based on the platform.
00781     switch(Triple.getEnvironment()) {
00782     case llvm::Triple::Android:
00783     case llvm::Triple::GNUEABI:
00784     case llvm::Triple::GNUEABIHF:
00785       ABIName = "aapcs-linux";
00786       break;
00787     case llvm::Triple::EABIHF:
00788     case llvm::Triple::EABI:
00789       ABIName = "aapcs";
00790       break;
00791     default:
00792       if (Triple.getOS() == llvm::Triple::NetBSD)
00793         ABIName = "apcs-gnu";
00794       else
00795         ABIName = "aapcs";
00796       break;
00797     }
00798   }
00799   CmdArgs.push_back("-target-abi");
00800   CmdArgs.push_back(ABIName);
00801 
00802   // Determine floating point ABI from the options & target defaults.
00803   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
00804   if (FloatABI == "soft") {
00805     // Floating point operations and argument passing are soft.
00806     //
00807     // FIXME: This changes CPP defines, we need -target-soft-float.
00808     CmdArgs.push_back("-msoft-float");
00809     CmdArgs.push_back("-mfloat-abi");
00810     CmdArgs.push_back("soft");
00811   } else if (FloatABI == "softfp") {
00812     // Floating point operations are hard, but argument passing is soft.
00813     CmdArgs.push_back("-mfloat-abi");
00814     CmdArgs.push_back("soft");
00815   } else {
00816     // Floating point operations and argument passing are hard.
00817     assert(FloatABI == "hard" && "Invalid float abi!");
00818     CmdArgs.push_back("-mfloat-abi");
00819     CmdArgs.push_back("hard");
00820   }
00821 
00822   // Kernel code has more strict alignment requirements.
00823   if (KernelOrKext) {
00824     if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
00825       CmdArgs.push_back("-backend-option");
00826       CmdArgs.push_back("-arm-long-calls");
00827     }
00828 
00829     CmdArgs.push_back("-backend-option");
00830     CmdArgs.push_back("-arm-strict-align");
00831 
00832     // The kext linker doesn't know how to deal with movw/movt.
00833     CmdArgs.push_back("-backend-option");
00834     CmdArgs.push_back("-arm-use-movt=0");
00835   }
00836 
00837   // -mkernel implies -mstrict-align; don't add the redundant option.
00838   if (!KernelOrKext) {
00839     if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
00840                                  options::OPT_munaligned_access)) {
00841       CmdArgs.push_back("-backend-option");
00842       if (A->getOption().matches(options::OPT_mno_unaligned_access))
00843         CmdArgs.push_back("-arm-strict-align");
00844       else {
00845         if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
00846           D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
00847         CmdArgs.push_back("-arm-no-strict-align");
00848       }
00849     }
00850   }
00851 
00852   // Setting -mno-global-merge disables the codegen global merge pass. Setting 
00853   // -mglobal-merge has no effect as the pass is enabled by default.
00854   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
00855                                options::OPT_mno_global_merge)) {
00856     if (A->getOption().matches(options::OPT_mno_global_merge))
00857       CmdArgs.push_back("-mno-global-merge");
00858   }
00859 
00860   if (!Args.hasFlag(options::OPT_mimplicit_float,
00861                     options::OPT_mno_implicit_float,
00862                     true))
00863     CmdArgs.push_back("-no-implicit-float");
00864 
00865   // llvm does not support reserving registers in general. There is support
00866   // for reserving r9 on ARM though (defined as a platform-specific register
00867   // in ARM EABI).
00868   if (Args.hasArg(options::OPT_ffixed_r9)) {
00869     CmdArgs.push_back("-backend-option");
00870     CmdArgs.push_back("-arm-reserve-r9");
00871   }
00872 }
00873 
00874 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
00875 /// targeting.
00876 static std::string getAArch64TargetCPU(const ArgList &Args) {
00877   Arg *A;
00878   std::string CPU;
00879   // If we have -mtune or -mcpu, use that.
00880   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
00881     CPU = A->getValue();
00882   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
00883     StringRef Mcpu = A->getValue();
00884     CPU = Mcpu.split("+").first;
00885   }
00886 
00887   // Handle CPU name is 'native'.
00888   if (CPU == "native")
00889     return llvm::sys::getHostCPUName();
00890   else if (CPU.size())
00891     return CPU;
00892 
00893   // Make sure we pick "cyclone" if -arch is used.
00894   // FIXME: Should this be picked by checking the target triple instead?
00895   if (Args.getLastArg(options::OPT_arch))
00896     return "cyclone";
00897 
00898   return "generic";
00899 }
00900 
00901 void Clang::AddAArch64TargetArgs(const ArgList &Args,
00902                                  ArgStringList &CmdArgs) const {
00903   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
00904   llvm::Triple Triple(TripleStr);
00905 
00906   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
00907       Args.hasArg(options::OPT_mkernel) ||
00908       Args.hasArg(options::OPT_fapple_kext))
00909     CmdArgs.push_back("-disable-red-zone");
00910 
00911   if (!Args.hasFlag(options::OPT_mimplicit_float,
00912                     options::OPT_mno_implicit_float, true))
00913     CmdArgs.push_back("-no-implicit-float");
00914 
00915   const char *ABIName = nullptr;
00916   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
00917     ABIName = A->getValue();
00918   else if (Triple.isOSDarwin())
00919     ABIName = "darwinpcs";
00920   else
00921     ABIName = "aapcs";
00922 
00923   CmdArgs.push_back("-target-abi");
00924   CmdArgs.push_back(ABIName);
00925 
00926   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
00927                                options::OPT_munaligned_access)) {
00928     CmdArgs.push_back("-backend-option");
00929     if (A->getOption().matches(options::OPT_mno_unaligned_access))
00930       CmdArgs.push_back("-aarch64-strict-align");
00931     else
00932       CmdArgs.push_back("-aarch64-no-strict-align");
00933   }
00934 
00935   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
00936                                options::OPT_mno_fix_cortex_a53_835769)) {
00937     CmdArgs.push_back("-backend-option");
00938     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
00939       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
00940     else
00941       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
00942   } else if (Triple.getEnvironment() == llvm::Triple::Android) {
00943     // Enabled A53 errata (835769) workaround by default on android
00944     CmdArgs.push_back("-backend-option");
00945     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
00946   }
00947 
00948   // Setting -mno-global-merge disables the codegen global merge pass. Setting
00949   // -mglobal-merge has no effect as the pass is enabled by default.
00950   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
00951                                options::OPT_mno_global_merge)) {
00952     if (A->getOption().matches(options::OPT_mno_global_merge))
00953       CmdArgs.push_back("-mno-global-merge");
00954   }
00955 }
00956 
00957 // Get CPU and ABI names. They are not independent
00958 // so we have to calculate them together.
00959 void mips::getMipsCPUAndABI(const ArgList &Args,
00960                             const llvm::Triple &Triple,
00961                             StringRef &CPUName,
00962                             StringRef &ABIName) {
00963   const char *DefMips32CPU = "mips32r2";
00964   const char *DefMips64CPU = "mips64r2";
00965 
00966   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
00967   // default for mips64(el)?-img-linux-gnu.
00968   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
00969       Triple.getEnvironment() == llvm::Triple::GNU) {
00970     DefMips32CPU = "mips32r6";
00971     DefMips64CPU = "mips64r6";
00972   }
00973 
00974   if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
00975                                options::OPT_mcpu_EQ))
00976     CPUName = A->getValue();
00977 
00978   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
00979     ABIName = A->getValue();
00980     // Convert a GNU style Mips ABI name to the name
00981     // accepted by LLVM Mips backend.
00982     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
00983       .Case("32", "o32")
00984       .Case("64", "n64")
00985       .Default(ABIName);
00986   }
00987 
00988   // Setup default CPU and ABI names.
00989   if (CPUName.empty() && ABIName.empty()) {
00990     switch (Triple.getArch()) {
00991     default:
00992       llvm_unreachable("Unexpected triple arch name");
00993     case llvm::Triple::mips:
00994     case llvm::Triple::mipsel:
00995       CPUName = DefMips32CPU;
00996       break;
00997     case llvm::Triple::mips64:
00998     case llvm::Triple::mips64el:
00999       CPUName = DefMips64CPU;
01000       break;
01001     }
01002   }
01003 
01004   if (ABIName.empty()) {
01005     // Deduce ABI name from the target triple.
01006     if (Triple.getArch() == llvm::Triple::mips ||
01007         Triple.getArch() == llvm::Triple::mipsel)
01008       ABIName = "o32";
01009     else
01010       ABIName = "n64";
01011   }
01012 
01013   if (CPUName.empty()) {
01014     // Deduce CPU name from ABI name.
01015     CPUName = llvm::StringSwitch<const char *>(ABIName)
01016       .Cases("o32", "eabi", DefMips32CPU)
01017       .Cases("n32", "n64", DefMips64CPU)
01018       .Default("");
01019   }
01020 
01021   // FIXME: Warn on inconsistent use of -march and -mabi.
01022 }
01023 
01024 // Convert ABI name to the GNU tools acceptable variant.
01025 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
01026   return llvm::StringSwitch<llvm::StringRef>(ABI)
01027     .Case("o32", "32")
01028     .Case("n64", "64")
01029     .Default(ABI);
01030 }
01031 
01032 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
01033 // and -mfloat-abi=.
01034 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
01035   StringRef FloatABI;
01036   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
01037                                options::OPT_mhard_float,
01038                                options::OPT_mfloat_abi_EQ)) {
01039     if (A->getOption().matches(options::OPT_msoft_float))
01040       FloatABI = "soft";
01041     else if (A->getOption().matches(options::OPT_mhard_float))
01042       FloatABI = "hard";
01043     else {
01044       FloatABI = A->getValue();
01045       if (FloatABI != "soft" && FloatABI != "hard") {
01046         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
01047         FloatABI = "hard";
01048       }
01049     }
01050   }
01051 
01052   // If unspecified, choose the default based on the platform.
01053   if (FloatABI.empty()) {
01054     // Assume "hard", because it's a default value used by gcc.
01055     // When we start to recognize specific target MIPS processors,
01056     // we will be able to select the default more correctly.
01057     FloatABI = "hard";
01058   }
01059 
01060   return FloatABI;
01061 }
01062 
01063 static void AddTargetFeature(const ArgList &Args,
01064                              std::vector<const char *> &Features,
01065                              OptSpecifier OnOpt, OptSpecifier OffOpt,
01066                              StringRef FeatureName) {
01067   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
01068     if (A->getOption().matches(OnOpt))
01069       Features.push_back(Args.MakeArgString("+" + FeatureName));
01070     else
01071       Features.push_back(Args.MakeArgString("-" + FeatureName));
01072   }
01073 }
01074 
01075 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
01076                                   const ArgList &Args,
01077                                   std::vector<const char *> &Features) {
01078   StringRef CPUName;
01079   StringRef ABIName;
01080   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
01081   ABIName = getGnuCompatibleMipsABIName(ABIName);
01082 
01083   // Always override the backend's default ABI.
01084   std::string ABIFeature = llvm::StringSwitch<StringRef>(ABIName)
01085                                .Case("32", "+o32")
01086                                .Case("n32", "+n32")
01087                                .Case("64", "+n64")
01088                                .Case("eabi", "+eabi")
01089                                .Default(("+" + ABIName).str());
01090   Features.push_back("-o32");
01091   Features.push_back("-n64");
01092   Features.push_back(Args.MakeArgString(ABIFeature));
01093 
01094   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
01095                    options::OPT_mabicalls, "noabicalls");
01096 
01097   StringRef FloatABI = getMipsFloatABI(D, Args);
01098   if (FloatABI == "soft") {
01099     // FIXME: Note, this is a hack. We need to pass the selected float
01100     // mode to the MipsTargetInfoBase to define appropriate macros there.
01101     // Now it is the only method.
01102     Features.push_back("+soft-float");
01103   }
01104 
01105   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
01106     StringRef Val = StringRef(A->getValue());
01107     if (Val == "2008")
01108       Features.push_back("+nan2008");
01109     else if (Val == "legacy")
01110       Features.push_back("-nan2008");
01111     else
01112       D.Diag(diag::err_drv_unsupported_option_argument)
01113           << A->getOption().getName() << Val;
01114   }
01115 
01116   AddTargetFeature(Args, Features, options::OPT_msingle_float,
01117                    options::OPT_mdouble_float, "single-float");
01118   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
01119                    "mips16");
01120   AddTargetFeature(Args, Features, options::OPT_mmicromips,
01121                    options::OPT_mno_micromips, "micromips");
01122   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
01123                    "dsp");
01124   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
01125                    "dspr2");
01126   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
01127                    "msa");
01128 
01129   // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
01130   // pass -mfpxx
01131   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
01132                                options::OPT_mfp64)) {
01133     if (A->getOption().matches(options::OPT_mfp32))
01134       Features.push_back(Args.MakeArgString("-fp64"));
01135     else if (A->getOption().matches(options::OPT_mfpxx)) {
01136       Features.push_back(Args.MakeArgString("+fpxx"));
01137       Features.push_back(Args.MakeArgString("+nooddspreg"));
01138     } else
01139       Features.push_back(Args.MakeArgString("+fp64"));
01140   } else if (mips::isFPXXDefault(Triple, CPUName, ABIName)) {
01141     Features.push_back(Args.MakeArgString("+fpxx"));
01142     Features.push_back(Args.MakeArgString("+nooddspreg"));
01143   }
01144 
01145   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
01146                    options::OPT_modd_spreg, "nooddspreg");
01147 }
01148 
01149 void Clang::AddMIPSTargetArgs(const ArgList &Args,
01150                               ArgStringList &CmdArgs) const {
01151   const Driver &D = getToolChain().getDriver();
01152   StringRef CPUName;
01153   StringRef ABIName;
01154   const llvm::Triple &Triple = getToolChain().getTriple();
01155   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
01156 
01157   CmdArgs.push_back("-target-abi");
01158   CmdArgs.push_back(ABIName.data());
01159 
01160   StringRef FloatABI = getMipsFloatABI(D, Args);
01161 
01162   if (FloatABI == "soft") {
01163     // Floating point operations and argument passing are soft.
01164     CmdArgs.push_back("-msoft-float");
01165     CmdArgs.push_back("-mfloat-abi");
01166     CmdArgs.push_back("soft");
01167   }
01168   else {
01169     // Floating point operations and argument passing are hard.
01170     assert(FloatABI == "hard" && "Invalid float abi!");
01171     CmdArgs.push_back("-mfloat-abi");
01172     CmdArgs.push_back("hard");
01173   }
01174 
01175   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
01176     if (A->getOption().matches(options::OPT_mxgot)) {
01177       CmdArgs.push_back("-mllvm");
01178       CmdArgs.push_back("-mxgot");
01179     }
01180   }
01181 
01182   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
01183                                options::OPT_mno_ldc1_sdc1)) {
01184     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
01185       CmdArgs.push_back("-mllvm");
01186       CmdArgs.push_back("-mno-ldc1-sdc1");
01187     }
01188   }
01189 
01190   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
01191                                options::OPT_mno_check_zero_division)) {
01192     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
01193       CmdArgs.push_back("-mllvm");
01194       CmdArgs.push_back("-mno-check-zero-division");
01195     }
01196   }
01197 
01198   if (Arg *A = Args.getLastArg(options::OPT_G)) {
01199     StringRef v = A->getValue();
01200     CmdArgs.push_back("-mllvm");
01201     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
01202     A->claim();
01203   }
01204 }
01205 
01206 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
01207 static std::string getPPCTargetCPU(const ArgList &Args) {
01208   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
01209     StringRef CPUName = A->getValue();
01210 
01211     if (CPUName == "native") {
01212       std::string CPU = llvm::sys::getHostCPUName();
01213       if (!CPU.empty() && CPU != "generic")
01214         return CPU;
01215       else
01216         return "";
01217     }
01218 
01219     return llvm::StringSwitch<const char *>(CPUName)
01220       .Case("common", "generic")
01221       .Case("440", "440")
01222       .Case("440fp", "440")
01223       .Case("450", "450")
01224       .Case("601", "601")
01225       .Case("602", "602")
01226       .Case("603", "603")
01227       .Case("603e", "603e")
01228       .Case("603ev", "603ev")
01229       .Case("604", "604")
01230       .Case("604e", "604e")
01231       .Case("620", "620")
01232       .Case("630", "pwr3")
01233       .Case("G3", "g3")
01234       .Case("7400", "7400")
01235       .Case("G4", "g4")
01236       .Case("7450", "7450")
01237       .Case("G4+", "g4+")
01238       .Case("750", "750")
01239       .Case("970", "970")
01240       .Case("G5", "g5")
01241       .Case("a2", "a2")
01242       .Case("a2q", "a2q")
01243       .Case("e500mc", "e500mc")
01244       .Case("e5500", "e5500")
01245       .Case("power3", "pwr3")
01246       .Case("power4", "pwr4")
01247       .Case("power5", "pwr5")
01248       .Case("power5x", "pwr5x")
01249       .Case("power6", "pwr6")
01250       .Case("power6x", "pwr6x")
01251       .Case("power7", "pwr7")
01252       .Case("power8", "pwr8")
01253       .Case("pwr3", "pwr3")
01254       .Case("pwr4", "pwr4")
01255       .Case("pwr5", "pwr5")
01256       .Case("pwr5x", "pwr5x")
01257       .Case("pwr6", "pwr6")
01258       .Case("pwr6x", "pwr6x")
01259       .Case("pwr7", "pwr7")
01260       .Case("pwr8", "pwr8")
01261       .Case("powerpc", "ppc")
01262       .Case("powerpc64", "ppc64")
01263       .Case("powerpc64le", "ppc64le")
01264       .Default("");
01265   }
01266 
01267   return "";
01268 }
01269 
01270 static void getPPCTargetFeatures(const ArgList &Args,
01271                                  std::vector<const char *> &Features) {
01272   for (arg_iterator it = Args.filtered_begin(options::OPT_m_ppc_Features_Group),
01273                     ie = Args.filtered_end();
01274        it != ie; ++it) {
01275     StringRef Name = (*it)->getOption().getName();
01276     (*it)->claim();
01277 
01278     // Skip over "-m".
01279     assert(Name.startswith("m") && "Invalid feature name.");
01280     Name = Name.substr(1);
01281 
01282     bool IsNegative = Name.startswith("no-");
01283     if (IsNegative)
01284       Name = Name.substr(3);
01285 
01286     // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
01287     // pass the correct option to the backend while calling the frontend
01288     // option the same.
01289     // TODO: Change the LLVM backend option maybe?
01290     if (Name == "mfcrf")
01291       Name = "mfocrf";
01292 
01293     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
01294   }
01295 
01296   // Altivec is a bit weird, allow overriding of the Altivec feature here.
01297   AddTargetFeature(Args, Features, options::OPT_faltivec,
01298                    options::OPT_fno_altivec, "altivec");
01299 }
01300 
01301 void Clang::AddPPCTargetArgs(const ArgList &Args,
01302                              ArgStringList &CmdArgs) const {
01303   // Select the ABI to use.
01304   const char *ABIName = nullptr;
01305   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
01306     ABIName = A->getValue();
01307   } else if (getToolChain().getTriple().isOSLinux())
01308     switch(getToolChain().getArch()) {
01309     case llvm::Triple::ppc64:
01310       ABIName = "elfv1";
01311       break;
01312     case llvm::Triple::ppc64le:
01313       ABIName = "elfv2";
01314       break;
01315     default:
01316       break;
01317   }
01318 
01319   if (ABIName) {
01320     CmdArgs.push_back("-target-abi");
01321     CmdArgs.push_back(ABIName);
01322   }
01323 }
01324 
01325 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
01326   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
01327   return A && (A->getValue() == StringRef(Value));
01328 }
01329 
01330 /// Get the (LLVM) name of the R600 gpu we are targeting.
01331 static std::string getR600TargetGPU(const ArgList &Args) {
01332   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
01333     const char *GPUName = A->getValue();
01334     return llvm::StringSwitch<const char *>(GPUName)
01335       .Cases("rv630", "rv635", "r600")
01336       .Cases("rv610", "rv620", "rs780", "rs880")
01337       .Case("rv740", "rv770")
01338       .Case("palm", "cedar")
01339       .Cases("sumo", "sumo2", "sumo")
01340       .Case("hemlock", "cypress")
01341       .Case("aruba", "cayman")
01342       .Default(GPUName);
01343   }
01344   return "";
01345 }
01346 
01347 static void getSparcTargetFeatures(const ArgList &Args,
01348                                    std::vector<const char *> &Features) {
01349   bool SoftFloatABI = true;
01350   if (Arg *A =
01351           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
01352     if (A->getOption().matches(options::OPT_mhard_float))
01353       SoftFloatABI = false;
01354   }
01355   if (SoftFloatABI)
01356     Features.push_back("+soft-float");
01357 }
01358 
01359 void Clang::AddSparcTargetArgs(const ArgList &Args,
01360                              ArgStringList &CmdArgs) const {
01361   const Driver &D = getToolChain().getDriver();
01362 
01363   // Select the float ABI as determined by -msoft-float and -mhard-float.
01364   StringRef FloatABI;
01365   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
01366                                options::OPT_mhard_float)) {
01367     if (A->getOption().matches(options::OPT_msoft_float))
01368       FloatABI = "soft";
01369     else if (A->getOption().matches(options::OPT_mhard_float))
01370       FloatABI = "hard";
01371   }
01372 
01373   // If unspecified, choose the default based on the platform.
01374   if (FloatABI.empty()) {
01375     // Assume "soft", but warn the user we are guessing.
01376     FloatABI = "soft";
01377     D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
01378   }
01379 
01380   if (FloatABI == "soft") {
01381     // Floating point operations and argument passing are soft.
01382     //
01383     // FIXME: This changes CPP defines, we need -target-soft-float.
01384     CmdArgs.push_back("-msoft-float");
01385   } else {
01386     assert(FloatABI == "hard" && "Invalid float abi!");
01387     CmdArgs.push_back("-mhard-float");
01388   }
01389 }
01390 
01391 static const char *getSystemZTargetCPU(const ArgList &Args) {
01392   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
01393     return A->getValue();
01394   return "z10";
01395 }
01396 
01397 static const char *getX86TargetCPU(const ArgList &Args,
01398                                    const llvm::Triple &Triple) {
01399   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
01400     if (StringRef(A->getValue()) != "native") {
01401       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
01402         return "core-avx2";
01403 
01404       return A->getValue();
01405     }
01406 
01407     // FIXME: Reject attempts to use -march=native unless the target matches
01408     // the host.
01409     //
01410     // FIXME: We should also incorporate the detected target features for use
01411     // with -native.
01412     std::string CPU = llvm::sys::getHostCPUName();
01413     if (!CPU.empty() && CPU != "generic")
01414       return Args.MakeArgString(CPU);
01415   }
01416 
01417   // Select the default CPU if none was given (or detection failed).
01418 
01419   if (Triple.getArch() != llvm::Triple::x86_64 &&
01420       Triple.getArch() != llvm::Triple::x86)
01421     return nullptr; // This routine is only handling x86 targets.
01422 
01423   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
01424 
01425   // FIXME: Need target hooks.
01426   if (Triple.isOSDarwin()) {
01427     if (Triple.getArchName() == "x86_64h")
01428       return "core-avx2";
01429     return Is64Bit ? "core2" : "yonah";
01430   }
01431 
01432   // On Android use targets compatible with gcc
01433   if (Triple.getEnvironment() == llvm::Triple::Android)
01434     return Is64Bit ? "x86-64" : "i686";
01435 
01436   // Everything else goes to x86-64 in 64-bit mode.
01437   if (Is64Bit)
01438     return "x86-64";
01439 
01440   switch (Triple.getOS()) {
01441   case llvm::Triple::FreeBSD:
01442   case llvm::Triple::NetBSD:
01443   case llvm::Triple::OpenBSD:
01444     return "i486";
01445   case llvm::Triple::Haiku:
01446     return "i586";
01447   case llvm::Triple::Bitrig:
01448     return "i686";
01449   default:
01450     // Fallback to p4.
01451     return "pentium4";
01452   }
01453 }
01454 
01455 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
01456   switch(T.getArch()) {
01457   default:
01458     return "";
01459 
01460   case llvm::Triple::aarch64:
01461   case llvm::Triple::aarch64_be:
01462     return getAArch64TargetCPU(Args);
01463 
01464   case llvm::Triple::arm:
01465   case llvm::Triple::armeb:
01466   case llvm::Triple::thumb:
01467   case llvm::Triple::thumbeb:
01468     return arm::getARMTargetCPU(Args, T);
01469 
01470   case llvm::Triple::mips:
01471   case llvm::Triple::mipsel:
01472   case llvm::Triple::mips64:
01473   case llvm::Triple::mips64el: {
01474     StringRef CPUName;
01475     StringRef ABIName;
01476     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
01477     return CPUName;
01478   }
01479 
01480   case llvm::Triple::ppc:
01481   case llvm::Triple::ppc64:
01482   case llvm::Triple::ppc64le: {
01483     std::string TargetCPUName = getPPCTargetCPU(Args);
01484     // LLVM may default to generating code for the native CPU,
01485     // but, like gcc, we default to a more generic option for
01486     // each architecture. (except on Darwin)
01487     if (TargetCPUName.empty() && !T.isOSDarwin()) {
01488       if (T.getArch() == llvm::Triple::ppc64)
01489         TargetCPUName = "ppc64";
01490       else if (T.getArch() == llvm::Triple::ppc64le)
01491         TargetCPUName = "ppc64le";
01492       else
01493         TargetCPUName = "ppc";
01494     }
01495     return TargetCPUName;
01496   }
01497 
01498   case llvm::Triple::sparc:
01499   case llvm::Triple::sparcv9:
01500     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
01501       return A->getValue();
01502     return "";
01503 
01504   case llvm::Triple::x86:
01505   case llvm::Triple::x86_64:
01506     return getX86TargetCPU(Args, T);
01507 
01508   case llvm::Triple::hexagon:
01509     return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
01510 
01511   case llvm::Triple::systemz:
01512     return getSystemZTargetCPU(Args);
01513 
01514   case llvm::Triple::r600:
01515     return getR600TargetGPU(Args);
01516   }
01517 }
01518 
01519 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
01520                           ArgStringList &CmdArgs) {
01521   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
01522   // as gold requires -plugin to come before any -plugin-opt that -Wl might
01523   // forward.
01524   CmdArgs.push_back("-plugin");
01525   std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
01526   CmdArgs.push_back(Args.MakeArgString(Plugin));
01527 
01528   // Try to pass driver level flags relevant to LTO code generation down to
01529   // the plugin.
01530 
01531   // Handle flags for selecting CPU variants.
01532   std::string CPU = getCPUName(Args, ToolChain.getTriple());
01533   if (!CPU.empty())
01534     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
01535 }
01536 
01537 static void getX86TargetFeatures(const Driver & D,
01538                                  const llvm::Triple &Triple,
01539                                  const ArgList &Args,
01540                                  std::vector<const char *> &Features) {
01541   if (Triple.getArchName() == "x86_64h") {
01542     // x86_64h implies quite a few of the more modern subtarget features
01543     // for Haswell class CPUs, but not all of them. Opt-out of a few.
01544     Features.push_back("-rdrnd");
01545     Features.push_back("-aes");
01546     Features.push_back("-pclmul");
01547     Features.push_back("-rtm");
01548     Features.push_back("-hle");
01549     Features.push_back("-fsgsbase");
01550   }
01551 
01552   // Add features to comply with gcc on Android
01553   if (Triple.getEnvironment() == llvm::Triple::Android) {
01554     if (Triple.getArch() == llvm::Triple::x86_64) {
01555       Features.push_back("+sse4.2");
01556       Features.push_back("+popcnt");
01557     } else
01558       Features.push_back("+ssse3");
01559   }
01560 
01561   // Set features according to the -arch flag on MSVC
01562   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
01563     StringRef Arch = A->getValue();
01564     bool ArchUsed = false;
01565     // First, look for flags that are shared in x86 and x86-64.
01566     if (Triple.getArch() == llvm::Triple::x86_64 ||
01567         Triple.getArch() == llvm::Triple::x86) {
01568       if (Arch == "AVX" || Arch == "AVX2") {
01569         ArchUsed = true;
01570         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
01571       }
01572     }
01573     // Then, look for x86-specific flags.
01574     if (Triple.getArch() == llvm::Triple::x86) {
01575       if (Arch == "IA32") {
01576         ArchUsed = true;
01577       } else if (Arch == "SSE" || Arch == "SSE2") {
01578         ArchUsed = true;
01579         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
01580       }
01581     }
01582     if (!ArchUsed)
01583       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
01584   }
01585 
01586   // Now add any that the user explicitly requested on the command line,
01587   // which may override the defaults.
01588   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
01589                     ie = Args.filtered_end();
01590        it != ie; ++it) {
01591     StringRef Name = (*it)->getOption().getName();
01592     (*it)->claim();
01593 
01594     // Skip over "-m".
01595     assert(Name.startswith("m") && "Invalid feature name.");
01596     Name = Name.substr(1);
01597 
01598     bool IsNegative = Name.startswith("no-");
01599     if (IsNegative)
01600       Name = Name.substr(3);
01601 
01602     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
01603   }
01604 }
01605 
01606 void Clang::AddX86TargetArgs(const ArgList &Args,
01607                              ArgStringList &CmdArgs) const {
01608   if (!Args.hasFlag(options::OPT_mred_zone,
01609                     options::OPT_mno_red_zone,
01610                     true) ||
01611       Args.hasArg(options::OPT_mkernel) ||
01612       Args.hasArg(options::OPT_fapple_kext))
01613     CmdArgs.push_back("-disable-red-zone");
01614 
01615   // Default to avoid implicit floating-point for kernel/kext code, but allow
01616   // that to be overridden with -mno-soft-float.
01617   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
01618                           Args.hasArg(options::OPT_fapple_kext));
01619   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
01620                                options::OPT_mno_soft_float,
01621                                options::OPT_mimplicit_float,
01622                                options::OPT_mno_implicit_float)) {
01623     const Option &O = A->getOption();
01624     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
01625                        O.matches(options::OPT_msoft_float));
01626   }
01627   if (NoImplicitFloat)
01628     CmdArgs.push_back("-no-implicit-float");
01629 
01630   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
01631     StringRef Value = A->getValue();
01632     if (Value == "intel" || Value == "att") {
01633       CmdArgs.push_back("-mllvm");
01634       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
01635     } else {
01636       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
01637           << A->getOption().getName() << Value;
01638     }
01639   }
01640 }
01641 
01642 static inline bool HasPICArg(const ArgList &Args) {
01643   return Args.hasArg(options::OPT_fPIC)
01644     || Args.hasArg(options::OPT_fpic);
01645 }
01646 
01647 static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) {
01648   return Args.getLastArg(options::OPT_G,
01649                          options::OPT_G_EQ,
01650                          options::OPT_msmall_data_threshold_EQ);
01651 }
01652 
01653 static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) {
01654   std::string value;
01655   if (HasPICArg(Args))
01656     value = "0";
01657   else if (Arg *A = GetLastSmallDataThresholdArg(Args)) {
01658     value = A->getValue();
01659     A->claim();
01660   }
01661   return value;
01662 }
01663 
01664 void Clang::AddHexagonTargetArgs(const ArgList &Args,
01665                                  ArgStringList &CmdArgs) const {
01666   CmdArgs.push_back("-fno-signed-char");
01667   CmdArgs.push_back("-mqdsp6-compat");
01668   CmdArgs.push_back("-Wreturn-type");
01669 
01670   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
01671   if (!SmallDataThreshold.empty()) {
01672     CmdArgs.push_back ("-mllvm");
01673     CmdArgs.push_back(Args.MakeArgString(
01674                         "-hexagon-small-data-threshold=" + SmallDataThreshold));
01675   }
01676 
01677   if (!Args.hasArg(options::OPT_fno_short_enums))
01678     CmdArgs.push_back("-fshort-enums");
01679   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
01680     CmdArgs.push_back ("-mllvm");
01681     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
01682   }
01683   CmdArgs.push_back ("-mllvm");
01684   CmdArgs.push_back ("-machine-sink-split=0");
01685 }
01686 
01687 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
01688 static bool DecodeAArch64Features(const Driver &D, StringRef text,
01689                                   std::vector<const char *> &Features) {
01690   SmallVector<StringRef, 8> Split;
01691   text.split(Split, StringRef("+"), -1, false);
01692 
01693   for (unsigned I = 0, E = Split.size(); I != E; ++I) {
01694     const char *result = llvm::StringSwitch<const char *>(Split[I])
01695                              .Case("fp", "+fp-armv8")
01696                              .Case("simd", "+neon")
01697                              .Case("crc", "+crc")
01698                              .Case("crypto", "+crypto")
01699                              .Case("nofp", "-fp-armv8")
01700                              .Case("nosimd", "-neon")
01701                              .Case("nocrc", "-crc")
01702                              .Case("nocrypto", "-crypto")
01703                              .Default(nullptr);
01704     if (result)
01705       Features.push_back(result);
01706     else if (Split[I] == "neon" || Split[I] == "noneon")
01707       D.Diag(diag::err_drv_no_neon_modifier);
01708     else
01709       return false;
01710   }
01711   return true;
01712 }
01713 
01714 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
01715 // decode CPU and feature.
01716 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
01717                               std::vector<const char *> &Features) {
01718   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
01719   CPU = Split.first;
01720   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57") {
01721     Features.push_back("+neon");
01722     Features.push_back("+crc");
01723     Features.push_back("+crypto");
01724   } else if (CPU == "generic") {
01725     Features.push_back("+neon");
01726   } else {
01727     return false;
01728   }
01729 
01730   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
01731     return false;
01732 
01733   return true;
01734 }
01735 
01736 static bool
01737 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
01738                                 const ArgList &Args,
01739                                 std::vector<const char *> &Features) {
01740   std::pair<StringRef, StringRef> Split = March.split("+");
01741   if (Split.first != "armv8-a")
01742     return false;
01743 
01744   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
01745     return false;
01746 
01747   return true;
01748 }
01749 
01750 static bool
01751 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
01752                                const ArgList &Args,
01753                                std::vector<const char *> &Features) {
01754   StringRef CPU;
01755   if (!DecodeAArch64Mcpu(D, Mcpu, CPU, Features))
01756     return false;
01757 
01758   return true;
01759 }
01760 
01761 static bool
01762 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
01763                                      const ArgList &Args,
01764                                      std::vector<const char *> &Features) {
01765   // Handle CPU name is 'native'.
01766   if (Mtune == "native")
01767     Mtune = llvm::sys::getHostCPUName();
01768   if (Mtune == "cyclone") {
01769     Features.push_back("+zcm");
01770     Features.push_back("+zcz");
01771   }
01772   return true;
01773 }
01774 
01775 static bool
01776 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
01777                                     const ArgList &Args,
01778                                     std::vector<const char *> &Features) {
01779   StringRef CPU;
01780   std::vector<const char *> DecodedFeature;
01781   if (!DecodeAArch64Mcpu(D, Mcpu, CPU, DecodedFeature))
01782     return false;
01783 
01784   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
01785 }
01786 
01787 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
01788                                      std::vector<const char *> &Features) {
01789   Arg *A;
01790   bool success = true;
01791   // Enable NEON by default.
01792   Features.push_back("+neon");
01793   if ((A = Args.getLastArg(options::OPT_march_EQ)))
01794     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
01795   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
01796     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
01797   else if (Args.hasArg(options::OPT_arch))
01798     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
01799                                              Features);
01800 
01801   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
01802     success =
01803         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
01804   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
01805     success =
01806         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
01807   else if (Args.hasArg(options::OPT_arch))
01808     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
01809                                                   Args, Features);
01810 
01811   if (!success)
01812     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
01813 
01814   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
01815     Features.push_back("-fp-armv8");
01816     Features.push_back("-crypto");
01817     Features.push_back("-neon");
01818   }
01819 
01820   // En/disable crc
01821   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
01822                                options::OPT_mnocrc)) {
01823     if (A->getOption().matches(options::OPT_mcrc))
01824       Features.push_back("+crc");
01825     else
01826       Features.push_back("-crc");
01827   }
01828 }
01829 
01830 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
01831                               const ArgList &Args, ArgStringList &CmdArgs,
01832                               bool ForAS) {
01833   std::vector<const char *> Features;
01834   switch (Triple.getArch()) {
01835   default:
01836     break;
01837   case llvm::Triple::mips:
01838   case llvm::Triple::mipsel:
01839   case llvm::Triple::mips64:
01840   case llvm::Triple::mips64el:
01841     getMIPSTargetFeatures(D, Triple, Args, Features);
01842     break;
01843 
01844   case llvm::Triple::arm:
01845   case llvm::Triple::armeb:
01846   case llvm::Triple::thumb:
01847   case llvm::Triple::thumbeb:
01848     getARMTargetFeatures(D, Triple, Args, Features, ForAS);
01849     break;
01850 
01851   case llvm::Triple::ppc:
01852   case llvm::Triple::ppc64:
01853   case llvm::Triple::ppc64le:
01854     getPPCTargetFeatures(Args, Features);
01855     break;
01856   case llvm::Triple::sparc:
01857   case llvm::Triple::sparcv9:
01858     getSparcTargetFeatures(Args, Features);
01859     break;
01860   case llvm::Triple::aarch64:
01861   case llvm::Triple::aarch64_be:
01862     getAArch64TargetFeatures(D, Args, Features);
01863     break;
01864   case llvm::Triple::x86:
01865   case llvm::Triple::x86_64:
01866     getX86TargetFeatures(D, Triple, Args, Features);
01867     break;
01868   }
01869 
01870   // Find the last of each feature.
01871   llvm::StringMap<unsigned> LastOpt;
01872   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
01873     const char *Name = Features[I];
01874     assert(Name[0] == '-' || Name[0] == '+');
01875     LastOpt[Name + 1] = I;
01876   }
01877 
01878   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
01879     // If this feature was overridden, ignore it.
01880     const char *Name = Features[I];
01881     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
01882     assert(LastI != LastOpt.end());
01883     unsigned Last = LastI->second;
01884     if (Last != I)
01885       continue;
01886 
01887     CmdArgs.push_back("-target-feature");
01888     CmdArgs.push_back(Name);
01889   }
01890 }
01891 
01892 static bool
01893 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
01894                                           const llvm::Triple &Triple) {
01895   // We use the zero-cost exception tables for Objective-C if the non-fragile
01896   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
01897   // later.
01898   if (runtime.isNonFragile())
01899     return true;
01900 
01901   if (!Triple.isMacOSX())
01902     return false;
01903 
01904   return (!Triple.isMacOSXVersionLT(10,5) &&
01905           (Triple.getArch() == llvm::Triple::x86_64 ||
01906            Triple.getArch() == llvm::Triple::arm));
01907 }
01908 
01909 namespace {
01910   struct ExceptionSettings {
01911     bool ExceptionsEnabled;
01912     bool ShouldUseExceptionTables;
01913     ExceptionSettings() : ExceptionsEnabled(false),
01914                           ShouldUseExceptionTables(false) {}
01915   };
01916 } // end anonymous namespace.
01917 
01918 // exceptionSettings() exists to share the logic between -cc1 and linker
01919 // invocations.
01920 static ExceptionSettings exceptionSettings(const ArgList &Args,
01921                                            const llvm::Triple &Triple) {
01922   ExceptionSettings ES;
01923 
01924   // Are exceptions enabled by default?
01925   ES.ExceptionsEnabled = (Triple.getArch() != llvm::Triple::xcore);
01926 
01927   // This keeps track of whether exceptions were explicitly turned on or off.
01928   bool DidHaveExplicitExceptionFlag = false;
01929 
01930   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
01931                                options::OPT_fno_exceptions)) {
01932     if (A->getOption().matches(options::OPT_fexceptions))
01933       ES.ExceptionsEnabled = true;
01934     else
01935       ES.ExceptionsEnabled = false;
01936 
01937     DidHaveExplicitExceptionFlag = true;
01938   }
01939 
01940   // Exception tables and cleanups can be enabled with -fexceptions even if the
01941   // language itself doesn't support exceptions.
01942   if (ES.ExceptionsEnabled && DidHaveExplicitExceptionFlag)
01943     ES.ShouldUseExceptionTables = true;
01944 
01945   return ES;
01946 }
01947 
01948 /// addExceptionArgs - Adds exception related arguments to the driver command
01949 /// arguments. There's a master flag, -fexceptions and also language specific
01950 /// flags to enable/disable C++ and Objective-C exceptions.
01951 /// This makes it possible to for example disable C++ exceptions but enable
01952 /// Objective-C exceptions.
01953 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
01954                              const llvm::Triple &Triple,
01955                              bool KernelOrKext,
01956                              const ObjCRuntime &objcRuntime,
01957                              ArgStringList &CmdArgs) {
01958   if (KernelOrKext) {
01959     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
01960     // arguments now to avoid warnings about unused arguments.
01961     Args.ClaimAllArgs(options::OPT_fexceptions);
01962     Args.ClaimAllArgs(options::OPT_fno_exceptions);
01963     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
01964     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
01965     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
01966     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
01967     return;
01968   }
01969 
01970    // Gather the exception settings from the command line arguments.
01971    ExceptionSettings ES = exceptionSettings(Args, Triple);
01972 
01973   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
01974   // is not necessarily sensible, but follows GCC.
01975   if (types::isObjC(InputType) &&
01976       Args.hasFlag(options::OPT_fobjc_exceptions,
01977                    options::OPT_fno_objc_exceptions,
01978                    true)) {
01979     CmdArgs.push_back("-fobjc-exceptions");
01980 
01981     ES.ShouldUseExceptionTables |=
01982       shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
01983   }
01984 
01985   if (types::isCXX(InputType)) {
01986     bool CXXExceptionsEnabled = ES.ExceptionsEnabled;
01987 
01988     if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
01989                                  options::OPT_fno_cxx_exceptions,
01990                                  options::OPT_fexceptions,
01991                                  options::OPT_fno_exceptions)) {
01992       if (A->getOption().matches(options::OPT_fcxx_exceptions))
01993         CXXExceptionsEnabled = true;
01994       else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
01995         CXXExceptionsEnabled = false;
01996     }
01997 
01998     if (CXXExceptionsEnabled) {
01999       CmdArgs.push_back("-fcxx-exceptions");
02000 
02001       ES.ShouldUseExceptionTables = true;
02002     }
02003   }
02004 
02005   if (ES.ShouldUseExceptionTables)
02006     CmdArgs.push_back("-fexceptions");
02007 }
02008 
02009 static bool ShouldDisableAutolink(const ArgList &Args,
02010                              const ToolChain &TC) {
02011   bool Default = true;
02012   if (TC.getTriple().isOSDarwin()) {
02013     // The native darwin assembler doesn't support the linker_option directives,
02014     // so we disable them if we think the .s file will be passed to it.
02015     Default = TC.useIntegratedAs();
02016   }
02017   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
02018                        Default);
02019 }
02020 
02021 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
02022                                         const ToolChain &TC) {
02023   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
02024                                         options::OPT_fno_dwarf_directory_asm,
02025                                         TC.useIntegratedAs());
02026   return !UseDwarfDirectory;
02027 }
02028 
02029 /// \brief Check whether the given input tree contains any compilation actions.
02030 static bool ContainsCompileAction(const Action *A) {
02031   if (isa<CompileJobAction>(A))
02032     return true;
02033 
02034   for (const auto &Act : *A)
02035     if (ContainsCompileAction(Act))
02036       return true;
02037 
02038   return false;
02039 }
02040 
02041 /// \brief Check if -relax-all should be passed to the internal assembler.
02042 /// This is done by default when compiling non-assembler source with -O0.
02043 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
02044   bool RelaxDefault = true;
02045 
02046   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
02047     RelaxDefault = A->getOption().matches(options::OPT_O0);
02048 
02049   if (RelaxDefault) {
02050     RelaxDefault = false;
02051     for (const auto &Act : C.getActions()) {
02052       if (ContainsCompileAction(Act)) {
02053         RelaxDefault = true;
02054         break;
02055       }
02056     }
02057   }
02058 
02059   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
02060     RelaxDefault);
02061 }
02062 
02063 static void CollectArgsForIntegratedAssembler(Compilation &C,
02064                                               const ArgList &Args,
02065                                               ArgStringList &CmdArgs,
02066                                               const Driver &D) {
02067     if (UseRelaxAll(C, Args))
02068       CmdArgs.push_back("-mrelax-all");
02069 
02070     // When passing -I arguments to the assembler we sometimes need to
02071     // unconditionally take the next argument.  For example, when parsing
02072     // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
02073     // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
02074     // arg after parsing the '-I' arg.
02075     bool TakeNextArg = false;
02076 
02077     // When using an integrated assembler, translate -Wa, and -Xassembler
02078     // options.
02079     bool CompressDebugSections = false;
02080     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
02081                                                options::OPT_Xassembler),
02082            ie = Args.filtered_end(); it != ie; ++it) {
02083       const Arg *A = *it;
02084       A->claim();
02085 
02086       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
02087         StringRef Value = A->getValue(i);
02088         if (TakeNextArg) {
02089           CmdArgs.push_back(Value.data());
02090           TakeNextArg = false;
02091           continue;
02092         }
02093 
02094         if (Value == "-force_cpusubtype_ALL") {
02095           // Do nothing, this is the default and we don't support anything else.
02096         } else if (Value == "-L") {
02097           CmdArgs.push_back("-msave-temp-labels");
02098         } else if (Value == "--fatal-warnings") {
02099           CmdArgs.push_back("-massembler-fatal-warnings");
02100         } else if (Value == "--noexecstack") {
02101           CmdArgs.push_back("-mnoexecstack");
02102         } else if (Value == "-compress-debug-sections" ||
02103                    Value == "--compress-debug-sections") {
02104           CompressDebugSections = true;
02105         } else if (Value == "-nocompress-debug-sections" ||
02106                    Value == "--nocompress-debug-sections") {
02107           CompressDebugSections = false;
02108         } else if (Value.startswith("-I")) {
02109           CmdArgs.push_back(Value.data());
02110           // We need to consume the next argument if the current arg is a plain
02111           // -I. The next arg will be the include directory.
02112           if (Value == "-I")
02113             TakeNextArg = true;
02114         } else if (Value.startswith("-gdwarf-")) {
02115           CmdArgs.push_back(Value.data());
02116         } else {
02117           D.Diag(diag::err_drv_unsupported_option_argument)
02118             << A->getOption().getName() << Value;
02119         }
02120       }
02121     }
02122     if (CompressDebugSections) {
02123       if (llvm::zlib::isAvailable())
02124         CmdArgs.push_back("-compress-debug-sections");
02125       else
02126         D.Diag(diag::warn_debug_compression_unavailable);
02127     }
02128 }
02129 
02130 // Until ARM libraries are build separately, we have them all in one library
02131 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
02132   if (TC.getArch() == llvm::Triple::arm ||
02133       TC.getArch() == llvm::Triple::armeb)
02134     return "arm";
02135   else
02136     return TC.getArchName();
02137 }
02138 
02139 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
02140   // The runtimes are located in the OS-specific resource directory.
02141   SmallString<128> Res(TC.getDriver().ResourceDir);
02142   const llvm::Triple &Triple = TC.getTriple();
02143   // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
02144   StringRef OSLibName = (Triple.getOS() == llvm::Triple::FreeBSD) ?
02145     "freebsd" : TC.getOS();
02146   llvm::sys::path::append(Res, "lib", OSLibName);
02147   return Res;
02148 }
02149 
02150 // This adds the static libclang_rt.builtins-arch.a directly to the command line
02151 // FIXME: Make sure we can also emit shared objects if they're requested
02152 // and available, check for possible errors, etc.
02153 static void addClangRTLinux(
02154     const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
02155   SmallString<128> LibClangRT = getCompilerRTLibDir(TC);
02156   llvm::sys::path::append(LibClangRT, Twine("libclang_rt.builtins-") +
02157                                           getArchNameForCompilerRTLib(TC) +
02158                                           ".a");
02159 
02160   CmdArgs.push_back(Args.MakeArgString(LibClangRT));
02161   CmdArgs.push_back("-lgcc_s");
02162   if (TC.getDriver().CCCIsCXX())
02163     CmdArgs.push_back("-lgcc_eh");
02164 }
02165 
02166 static void addClangRTWindows(const ToolChain &TC, const ArgList &Args,
02167                               ArgStringList &CmdArgs) {
02168   SmallString<128> LibClangRT = getCompilerRTLibDir(TC);
02169   llvm::sys::path::append(LibClangRT, Twine("libclang_rt.builtins-") +
02170                           getArchNameForCompilerRTLib(TC) + ".lib");
02171   CmdArgs.push_back(Args.MakeArgString(LibClangRT));
02172 }
02173 
02174 static void addProfileRT(
02175     const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
02176   if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
02177                      false) ||
02178         Args.hasArg(options::OPT_fprofile_generate) ||
02179         Args.hasArg(options::OPT_fprofile_instr_generate) ||
02180         Args.hasArg(options::OPT_fcreate_profile) ||
02181         Args.hasArg(options::OPT_coverage)))
02182     return;
02183 
02184   SmallString<128> LibProfile = getCompilerRTLibDir(TC);
02185   llvm::sys::path::append(LibProfile, Twine("libclang_rt.profile-") +
02186                                           getArchNameForCompilerRTLib(TC) +
02187                                           ".a");
02188 
02189   CmdArgs.push_back(Args.MakeArgString(LibProfile));
02190 }
02191 
02192 static SmallString<128> getSanitizerRTLibName(const ToolChain &TC,
02193                                               StringRef Sanitizer,
02194                                               bool Shared) {
02195   // Sanitizer runtime has name "libclang_rt.<Sanitizer>-<ArchName>.{a,so}"
02196   // (or "libclang_rt.<Sanitizer>-<ArchName>-android.so for Android)
02197   const char *EnvSuffix =
02198     TC.getTriple().getEnvironment() == llvm::Triple::Android ?  "-android" : "";
02199   SmallString<128> LibSanitizer = getCompilerRTLibDir(TC);
02200   llvm::sys::path::append(LibSanitizer,
02201                           Twine("libclang_rt.") + Sanitizer + "-" +
02202                               getArchNameForCompilerRTLib(TC) + EnvSuffix +
02203                               (Shared ? ".so" : ".a"));
02204   return LibSanitizer;
02205 }
02206 
02207 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
02208                                 ArgStringList &CmdArgs, StringRef Sanitizer,
02209                                 bool IsShared) {
02210   SmallString<128> LibSanitizer = getSanitizerRTLibName(TC, Sanitizer, IsShared);
02211   // Static runtimes must be forced into executable, so we wrap them in
02212   // whole-archive.
02213   if (!IsShared)
02214     CmdArgs.push_back("-whole-archive");
02215   CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
02216   if (!IsShared)
02217     CmdArgs.push_back("-no-whole-archive");
02218 }
02219 
02220 // Tries to use a file with the list of dynamic symbols that need to be exported
02221 // from the runtime library. Returns true if the file was found.
02222 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
02223                                     ArgStringList &CmdArgs,
02224                                     StringRef Sanitizer) {
02225   SmallString<128> LibSanitizer = getSanitizerRTLibName(TC, Sanitizer, false);
02226   if (llvm::sys::fs::exists(LibSanitizer + ".syms")) {
02227     CmdArgs.push_back(
02228         Args.MakeArgString("--dynamic-list=" + LibSanitizer + ".syms"));
02229     return true;
02230   }
02231   return false;
02232 }
02233 
02234 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
02235                                      ArgStringList &CmdArgs) {
02236   // Force linking against the system libraries sanitizers depends on
02237   // (see PR15823 why this is necessary).
02238   CmdArgs.push_back("--no-as-needed");
02239   CmdArgs.push_back("-lpthread");
02240   CmdArgs.push_back("-lrt");
02241   CmdArgs.push_back("-lm");
02242   // There's no libdl on FreeBSD.
02243   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
02244     CmdArgs.push_back("-ldl");
02245 }
02246 
02247 static void
02248 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
02249                          SmallVectorImpl<StringRef> &SharedRuntimes,
02250                          SmallVectorImpl<StringRef> &StaticRuntimes,
02251                          SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
02252   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
02253   // Collect shared runtimes.
02254   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
02255     SharedRuntimes.push_back("asan");
02256   }
02257 
02258   // Collect static runtimes.
02259   if (Args.hasArg(options::OPT_shared) ||
02260       (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
02261     // Don't link static runtimes into DSOs or if compiling for Android.
02262     return;
02263   }
02264   if (SanArgs.needsAsanRt()) {
02265     if (SanArgs.needsSharedAsanRt()) {
02266       HelperStaticRuntimes.push_back("asan-preinit");
02267     } else {
02268       StaticRuntimes.push_back("asan");
02269       if (SanArgs.linkCXXRuntimes())
02270         StaticRuntimes.push_back("asan_cxx");
02271     }
02272   }
02273   if (SanArgs.needsDfsanRt())
02274     StaticRuntimes.push_back("dfsan");
02275   if (SanArgs.needsLsanRt())
02276     StaticRuntimes.push_back("lsan");
02277   if (SanArgs.needsMsanRt())
02278     StaticRuntimes.push_back("msan");
02279   if (SanArgs.needsTsanRt())
02280     StaticRuntimes.push_back("tsan");
02281   // WARNING: UBSan should always go last.
02282   if (SanArgs.needsUbsanRt()) {
02283     // If UBSan is not combined with another sanitizer, we need to pull in
02284     // sanitizer_common explicitly.
02285     if (StaticRuntimes.empty())
02286       HelperStaticRuntimes.push_back("san");
02287     StaticRuntimes.push_back("ubsan");
02288     if (SanArgs.linkCXXRuntimes())
02289       StaticRuntimes.push_back("ubsan_cxx");
02290   }
02291 }
02292 
02293 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
02294 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
02295 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
02296                                  ArgStringList &CmdArgs) {
02297   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
02298       HelperStaticRuntimes;
02299   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
02300                            HelperStaticRuntimes);
02301   for (auto RT : SharedRuntimes)
02302     addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
02303   for (auto RT : HelperStaticRuntimes)
02304     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
02305   bool AddExportDynamic = false;
02306   for (auto RT : StaticRuntimes) {
02307     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
02308     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
02309   }
02310   // If there is a static runtime with no dynamic list, force all the symbols
02311   // to be dynamic to be sure we export sanitizer interface functions.
02312   if (AddExportDynamic)
02313     CmdArgs.push_back("-export-dynamic");
02314   return !StaticRuntimes.empty();
02315 }
02316 
02317 static bool shouldUseFramePointerForTarget(const ArgList &Args,
02318                                            const llvm::Triple &Triple) {
02319   switch (Triple.getArch()) {
02320   // Don't use a frame pointer on linux if optimizing for certain targets.
02321   case llvm::Triple::mips64:
02322   case llvm::Triple::mips64el:
02323   case llvm::Triple::mips:
02324   case llvm::Triple::mipsel:
02325   case llvm::Triple::systemz:
02326   case llvm::Triple::x86:
02327   case llvm::Triple::x86_64:
02328     if (Triple.isOSLinux())
02329       if (Arg *A = Args.getLastArg(options::OPT_O_Group))
02330         if (!A->getOption().matches(options::OPT_O0))
02331           return false;
02332     return true;
02333   case llvm::Triple::xcore:
02334     return false;
02335   default:
02336     return true;
02337   }
02338 }
02339 
02340 static bool shouldUseFramePointer(const ArgList &Args,
02341                                   const llvm::Triple &Triple) {
02342   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
02343                                options::OPT_fomit_frame_pointer))
02344     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
02345 
02346   return shouldUseFramePointerForTarget(Args, Triple);
02347 }
02348 
02349 static bool shouldUseLeafFramePointer(const ArgList &Args,
02350                                       const llvm::Triple &Triple) {
02351   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
02352                                options::OPT_momit_leaf_frame_pointer))
02353     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
02354 
02355   return shouldUseFramePointerForTarget(Args, Triple);
02356 }
02357 
02358 /// Add a CC1 option to specify the debug compilation directory.
02359 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
02360   SmallString<128> cwd;
02361   if (!llvm::sys::fs::current_path(cwd)) {
02362     CmdArgs.push_back("-fdebug-compilation-dir");
02363     CmdArgs.push_back(Args.MakeArgString(cwd));
02364   }
02365 }
02366 
02367 static const char *SplitDebugName(const ArgList &Args,
02368                                   const InputInfoList &Inputs) {
02369   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
02370   if (FinalOutput && Args.hasArg(options::OPT_c)) {
02371     SmallString<128> T(FinalOutput->getValue());
02372     llvm::sys::path::replace_extension(T, "dwo");
02373     return Args.MakeArgString(T);
02374   } else {
02375     // Use the compilation dir.
02376     SmallString<128> T(
02377         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
02378     SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput()));
02379     llvm::sys::path::replace_extension(F, "dwo");
02380     T += F;
02381     return Args.MakeArgString(F);
02382   }
02383 }
02384 
02385 static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
02386                            const Tool &T, const JobAction &JA,
02387                            const ArgList &Args, const InputInfo &Output,
02388                            const char *OutFile) {
02389   ArgStringList ExtractArgs;
02390   ExtractArgs.push_back("--extract-dwo");
02391 
02392   ArgStringList StripArgs;
02393   StripArgs.push_back("--strip-dwo");
02394 
02395   // Grabbing the output of the earlier compile step.
02396   StripArgs.push_back(Output.getFilename());
02397   ExtractArgs.push_back(Output.getFilename());
02398   ExtractArgs.push_back(OutFile);
02399 
02400   const char *Exec =
02401     Args.MakeArgString(TC.GetProgramPath("objcopy"));
02402 
02403   // First extract the dwo sections.
02404   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
02405 
02406   // Then remove them from the original .o file.
02407   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
02408 }
02409 
02410 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
02411 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
02412 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
02413   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
02414     if (A->getOption().matches(options::OPT_O4) ||
02415         A->getOption().matches(options::OPT_Ofast))
02416       return true;
02417 
02418     if (A->getOption().matches(options::OPT_O0))
02419       return false;
02420 
02421     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
02422 
02423     // Vectorize -Os.
02424     StringRef S(A->getValue());
02425     if (S == "s")
02426       return true;
02427 
02428     // Don't vectorize -Oz, unless it's the slp vectorizer.
02429     if (S == "z")
02430       return isSlpVec;
02431 
02432     unsigned OptLevel = 0;
02433     if (S.getAsInteger(10, OptLevel))
02434       return false;
02435 
02436     return OptLevel > 1;
02437   }
02438 
02439   return false;
02440 }
02441 
02442 /// Add -x lang to \p CmdArgs for \p Input.
02443 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
02444                              ArgStringList &CmdArgs) {
02445   // When using -verify-pch, we don't want to provide the type
02446   // 'precompiled-header' if it was inferred from the file extension
02447   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
02448     return;
02449 
02450   CmdArgs.push_back("-x");
02451   if (Args.hasArg(options::OPT_rewrite_objc))
02452     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
02453   else
02454     CmdArgs.push_back(types::getTypeName(Input.getType()));
02455 }
02456 
02457 static std::string getMSCompatibilityVersion(const char *VersionStr) {
02458   unsigned Version;
02459   if (StringRef(VersionStr).getAsInteger(10, Version))
02460     return "0";
02461 
02462   if (Version < 100)
02463     return llvm::utostr_32(Version) + ".0";
02464 
02465   if (Version < 10000)
02466     return llvm::utostr_32(Version / 100) + "." +
02467         llvm::utostr_32(Version % 100);
02468 
02469   unsigned Build = 0, Factor = 1;
02470   for ( ; Version > 10000; Version = Version / 10, Factor = Factor * 10)
02471     Build = Build + (Version % 10) * Factor;
02472   return llvm::utostr_32(Version / 100) + "." +
02473       llvm::utostr_32(Version % 100) + "." +
02474       llvm::utostr_32(Build);
02475 }
02476 
02477 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
02478                          const InputInfo &Output,
02479                          const InputInfoList &Inputs,
02480                          const ArgList &Args,
02481                          const char *LinkingOutput) const {
02482   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
02483                                   options::OPT_fapple_kext);
02484   const Driver &D = getToolChain().getDriver();
02485   ArgStringList CmdArgs;
02486 
02487   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
02488   bool IsWindowsCygnus =
02489       getToolChain().getTriple().isWindowsCygwinEnvironment();
02490   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
02491 
02492   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
02493 
02494   // Invoke ourselves in -cc1 mode.
02495   //
02496   // FIXME: Implement custom jobs for internal actions.
02497   CmdArgs.push_back("-cc1");
02498 
02499   // Add the "effective" target triple.
02500   CmdArgs.push_back("-triple");
02501   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
02502   CmdArgs.push_back(Args.MakeArgString(TripleStr));
02503 
02504   const llvm::Triple TT(TripleStr);
02505   if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
02506                            TT.getArch() == llvm::Triple::thumb)) {
02507     unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
02508     unsigned Version;
02509     TT.getArchName().substr(Offset).getAsInteger(10, Version);
02510     if (Version < 7)
02511       D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
02512                                                 << TripleStr;
02513   }
02514 
02515   // Push all default warning arguments that are specific to
02516   // the given target.  These come before user provided warning options
02517   // are provided.
02518   getToolChain().addClangWarningOptions(CmdArgs);
02519 
02520   // Select the appropriate action.
02521   RewriteKind rewriteKind = RK_None;
02522   
02523   if (isa<AnalyzeJobAction>(JA)) {
02524     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
02525     CmdArgs.push_back("-analyze");
02526   } else if (isa<MigrateJobAction>(JA)) {
02527     CmdArgs.push_back("-migrate");
02528   } else if (isa<PreprocessJobAction>(JA)) {
02529     if (Output.getType() == types::TY_Dependencies)
02530       CmdArgs.push_back("-Eonly");
02531     else {
02532       CmdArgs.push_back("-E");
02533       if (Args.hasArg(options::OPT_rewrite_objc) &&
02534           !Args.hasArg(options::OPT_g_Group))
02535         CmdArgs.push_back("-P");
02536     }
02537   } else if (isa<AssembleJobAction>(JA)) {
02538     CmdArgs.push_back("-emit-obj");
02539 
02540     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
02541 
02542     // Also ignore explicit -force_cpusubtype_ALL option.
02543     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
02544   } else if (isa<PrecompileJobAction>(JA)) {
02545     // Use PCH if the user requested it.
02546     bool UsePCH = D.CCCUsePCH;
02547 
02548     if (JA.getType() == types::TY_Nothing)
02549       CmdArgs.push_back("-fsyntax-only");
02550     else if (UsePCH)
02551       CmdArgs.push_back("-emit-pch");
02552     else
02553       CmdArgs.push_back("-emit-pth");
02554   } else if (isa<VerifyPCHJobAction>(JA)) {
02555     CmdArgs.push_back("-verify-pch");
02556   } else {
02557     assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
02558 
02559     if (JA.getType() == types::TY_Nothing) {
02560       CmdArgs.push_back("-fsyntax-only");
02561     } else if (JA.getType() == types::TY_LLVM_IR ||
02562                JA.getType() == types::TY_LTO_IR) {
02563       CmdArgs.push_back("-emit-llvm");
02564     } else if (JA.getType() == types::TY_LLVM_BC ||
02565                JA.getType() == types::TY_LTO_BC) {
02566       CmdArgs.push_back("-emit-llvm-bc");
02567     } else if (JA.getType() == types::TY_PP_Asm) {
02568       CmdArgs.push_back("-S");
02569     } else if (JA.getType() == types::TY_AST) {
02570       CmdArgs.push_back("-emit-pch");
02571     } else if (JA.getType() == types::TY_ModuleFile) {
02572       CmdArgs.push_back("-module-file-info");
02573     } else if (JA.getType() == types::TY_RewrittenObjC) {
02574       CmdArgs.push_back("-rewrite-objc");
02575       rewriteKind = RK_NonFragile;
02576     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
02577       CmdArgs.push_back("-rewrite-objc");
02578       rewriteKind = RK_Fragile;
02579     } else {
02580       assert(JA.getType() == types::TY_PP_Asm &&
02581              "Unexpected output type!");
02582     }
02583   }
02584 
02585   // We normally speed up the clang process a bit by skipping destructors at
02586   // exit, but when we're generating diagnostics we can rely on some of the
02587   // cleanup.
02588   if (!C.isForDiagnostics())
02589     CmdArgs.push_back("-disable-free");
02590 
02591   // Disable the verification pass in -asserts builds.
02592 #ifdef NDEBUG
02593   CmdArgs.push_back("-disable-llvm-verifier");
02594 #endif
02595 
02596   // Set the main file name, so that debug info works even with
02597   // -save-temps.
02598   CmdArgs.push_back("-main-file-name");
02599   CmdArgs.push_back(getBaseInputName(Args, Inputs));
02600 
02601   // Some flags which affect the language (via preprocessor
02602   // defines).
02603   if (Args.hasArg(options::OPT_static))
02604     CmdArgs.push_back("-static-define");
02605 
02606   if (isa<AnalyzeJobAction>(JA)) {
02607     // Enable region store model by default.
02608     CmdArgs.push_back("-analyzer-store=region");
02609 
02610     // Treat blocks as analysis entry points.
02611     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
02612 
02613     CmdArgs.push_back("-analyzer-eagerly-assume");
02614 
02615     // Add default argument set.
02616     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
02617       CmdArgs.push_back("-analyzer-checker=core");
02618 
02619       if (!IsWindowsMSVC)
02620         CmdArgs.push_back("-analyzer-checker=unix");
02621 
02622       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
02623         CmdArgs.push_back("-analyzer-checker=osx");
02624       
02625       CmdArgs.push_back("-analyzer-checker=deadcode");
02626       
02627       if (types::isCXX(Inputs[0].getType()))
02628         CmdArgs.push_back("-analyzer-checker=cplusplus");
02629 
02630       // Enable the following experimental checkers for testing.
02631       CmdArgs.push_back(
02632           "-analyzer-checker=security.insecureAPI.UncheckedReturn");
02633       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
02634       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
02635       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");      
02636       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
02637       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
02638     }
02639 
02640     // Set the output format. The default is plist, for (lame) historical
02641     // reasons.
02642     CmdArgs.push_back("-analyzer-output");
02643     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
02644       CmdArgs.push_back(A->getValue());
02645     else
02646       CmdArgs.push_back("plist");
02647 
02648     // Disable the presentation of standard compiler warnings when
02649     // using --analyze.  We only want to show static analyzer diagnostics
02650     // or frontend errors.
02651     CmdArgs.push_back("-w");
02652 
02653     // Add -Xanalyzer arguments when running as analyzer.
02654     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
02655   }
02656 
02657   CheckCodeGenerationOptions(D, Args);
02658 
02659   bool PIE = getToolChain().isPIEDefault();
02660   bool PIC = PIE || getToolChain().isPICDefault();
02661   bool IsPICLevelTwo = PIC;
02662 
02663   // Android-specific defaults for PIC/PIE
02664   if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
02665     switch (getToolChain().getTriple().getArch()) {
02666     case llvm::Triple::arm:
02667     case llvm::Triple::armeb:
02668     case llvm::Triple::thumb:
02669     case llvm::Triple::thumbeb:
02670     case llvm::Triple::aarch64:
02671     case llvm::Triple::mips:
02672     case llvm::Triple::mipsel:
02673     case llvm::Triple::mips64:
02674     case llvm::Triple::mips64el:
02675       PIC = true; // "-fpic"
02676       break;
02677 
02678     case llvm::Triple::x86:
02679     case llvm::Triple::x86_64:
02680       PIC = true; // "-fPIC"
02681       IsPICLevelTwo = true;
02682       break;
02683 
02684     default:
02685       break;
02686     }
02687   }
02688 
02689   // OpenBSD-specific defaults for PIE
02690   if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
02691     switch (getToolChain().getTriple().getArch()) {
02692     case llvm::Triple::mips64:
02693     case llvm::Triple::mips64el:
02694     case llvm::Triple::sparc:
02695     case llvm::Triple::x86:
02696     case llvm::Triple::x86_64:
02697       IsPICLevelTwo = false; // "-fpie"
02698       break;
02699 
02700     case llvm::Triple::ppc:
02701     case llvm::Triple::sparcv9:
02702       IsPICLevelTwo = true; // "-fPIE"
02703       break;
02704 
02705     default:
02706       break;
02707     }
02708   }
02709 
02710   // For the PIC and PIE flag options, this logic is different from the
02711   // legacy logic in very old versions of GCC, as that logic was just
02712   // a bug no one had ever fixed. This logic is both more rational and
02713   // consistent with GCC's new logic now that the bugs are fixed. The last
02714   // argument relating to either PIC or PIE wins, and no other argument is
02715   // used. If the last argument is any flavor of the '-fno-...' arguments,
02716   // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
02717   // at the same level.
02718   Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
02719                                  options::OPT_fpic, options::OPT_fno_pic,
02720                                  options::OPT_fPIE, options::OPT_fno_PIE,
02721                                  options::OPT_fpie, options::OPT_fno_pie);
02722   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
02723   // is forced, then neither PIC nor PIE flags will have no effect.
02724   if (!getToolChain().isPICDefaultForced()) {
02725     if (LastPICArg) {
02726       Option O = LastPICArg->getOption();
02727       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
02728           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
02729         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
02730         PIC = PIE || O.matches(options::OPT_fPIC) ||
02731               O.matches(options::OPT_fpic);
02732         IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
02733                         O.matches(options::OPT_fPIC);
02734       } else {
02735         PIE = PIC = false;
02736       }
02737     }
02738   }
02739 
02740   // Introduce a Darwin-specific hack. If the default is PIC but the flags
02741   // specified while enabling PIC enabled level 1 PIC, just force it back to
02742   // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
02743   // informal testing).
02744   if (PIC && getToolChain().getTriple().isOSDarwin())
02745     IsPICLevelTwo |= getToolChain().isPICDefault();
02746 
02747   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
02748   // PIC or PIE options above, if these show up, PIC is disabled.
02749   llvm::Triple Triple(TripleStr);
02750   if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6) ||
02751                        Triple.getArch() == llvm::Triple::aarch64))
02752     PIC = PIE = false;
02753   if (Args.hasArg(options::OPT_static))
02754     PIC = PIE = false;
02755 
02756   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
02757     // This is a very special mode. It trumps the other modes, almost no one
02758     // uses it, and it isn't even valid on any OS but Darwin.
02759     if (!getToolChain().getTriple().isOSDarwin())
02760       D.Diag(diag::err_drv_unsupported_opt_for_target)
02761         << A->getSpelling() << getToolChain().getTriple().str();
02762 
02763     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
02764 
02765     CmdArgs.push_back("-mrelocation-model");
02766     CmdArgs.push_back("dynamic-no-pic");
02767 
02768     // Only a forced PIC mode can cause the actual compile to have PIC defines
02769     // etc., no flags are sufficient. This behavior was selected to closely
02770     // match that of llvm-gcc and Apple GCC before that.
02771     if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
02772       CmdArgs.push_back("-pic-level");
02773       CmdArgs.push_back("2");
02774     }
02775   } else {
02776     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
02777     // handled in Clang's IRGen by the -pie-level flag.
02778     CmdArgs.push_back("-mrelocation-model");
02779     CmdArgs.push_back(PIC ? "pic" : "static");
02780 
02781     if (PIC) {
02782       CmdArgs.push_back("-pic-level");
02783       CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
02784       if (PIE) {
02785         CmdArgs.push_back("-pie-level");
02786         CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
02787       }
02788     }
02789   }
02790 
02791   CmdArgs.push_back("-mthread-model");
02792   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
02793     CmdArgs.push_back(A->getValue());
02794   else
02795     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
02796 
02797   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
02798                     options::OPT_fno_merge_all_constants))
02799     CmdArgs.push_back("-fno-merge-all-constants");
02800 
02801   // LLVM Code Generator Options.
02802 
02803   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
02804     StringRef v = A->getValue();
02805     CmdArgs.push_back("-mllvm");
02806     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
02807     A->claim();
02808   }
02809 
02810   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
02811     CmdArgs.push_back("-mregparm");
02812     CmdArgs.push_back(A->getValue());
02813   }
02814 
02815   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
02816                                options::OPT_freg_struct_return)) {
02817     if (getToolChain().getArch() != llvm::Triple::x86) {
02818       D.Diag(diag::err_drv_unsupported_opt_for_target)
02819         << A->getSpelling() << getToolChain().getTriple().str();
02820     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
02821       CmdArgs.push_back("-fpcc-struct-return");
02822     } else {
02823       assert(A->getOption().matches(options::OPT_freg_struct_return));
02824       CmdArgs.push_back("-freg-struct-return");
02825     }
02826   }
02827 
02828   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
02829     CmdArgs.push_back("-mrtd");
02830 
02831   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
02832     CmdArgs.push_back("-mdisable-fp-elim");
02833   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
02834                     options::OPT_fno_zero_initialized_in_bss))
02835     CmdArgs.push_back("-mno-zero-initialized-in-bss");
02836 
02837   bool OFastEnabled = isOptimizationLevelFast(Args);
02838   // If -Ofast is the optimization level, then -fstrict-aliasing should be
02839   // enabled.  This alias option is being used to simplify the hasFlag logic.
02840   OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
02841     options::OPT_fstrict_aliasing;
02842   // We turn strict aliasing off by default if we're in CL mode, since MSVC
02843   // doesn't do any TBAA.
02844   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
02845   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
02846                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
02847     CmdArgs.push_back("-relaxed-aliasing");
02848   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
02849                     options::OPT_fno_struct_path_tbaa))
02850     CmdArgs.push_back("-no-struct-path-tbaa");
02851   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
02852                    false))
02853     CmdArgs.push_back("-fstrict-enums");
02854   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
02855                     options::OPT_fno_optimize_sibling_calls))
02856     CmdArgs.push_back("-mdisable-tail-calls");
02857 
02858   // Handle segmented stacks.
02859   if (Args.hasArg(options::OPT_fsplit_stack))
02860     CmdArgs.push_back("-split-stacks");
02861 
02862   // If -Ofast is the optimization level, then -ffast-math should be enabled.
02863   // This alias option is being used to simplify the getLastArg logic.
02864   OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
02865     options::OPT_ffast_math;
02866   
02867   // Handle various floating point optimization flags, mapping them to the
02868   // appropriate LLVM code generation flags. The pattern for all of these is to
02869   // default off the codegen optimizations, and if any flag enables them and no
02870   // flag disables them after the flag enabling them, enable the codegen
02871   // optimization. This is complicated by several "umbrella" flags.
02872   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02873                                options::OPT_fno_fast_math,
02874                                options::OPT_ffinite_math_only,
02875                                options::OPT_fno_finite_math_only,
02876                                options::OPT_fhonor_infinities,
02877                                options::OPT_fno_honor_infinities))
02878     if (A->getOption().getID() != options::OPT_fno_fast_math &&
02879         A->getOption().getID() != options::OPT_fno_finite_math_only &&
02880         A->getOption().getID() != options::OPT_fhonor_infinities)
02881       CmdArgs.push_back("-menable-no-infs");
02882   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02883                                options::OPT_fno_fast_math,
02884                                options::OPT_ffinite_math_only,
02885                                options::OPT_fno_finite_math_only,
02886                                options::OPT_fhonor_nans,
02887                                options::OPT_fno_honor_nans))
02888     if (A->getOption().getID() != options::OPT_fno_fast_math &&
02889         A->getOption().getID() != options::OPT_fno_finite_math_only &&
02890         A->getOption().getID() != options::OPT_fhonor_nans)
02891       CmdArgs.push_back("-menable-no-nans");
02892 
02893   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
02894   bool MathErrno = getToolChain().IsMathErrnoDefault();
02895   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02896                                options::OPT_fno_fast_math,
02897                                options::OPT_fmath_errno,
02898                                options::OPT_fno_math_errno)) {
02899     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
02900     // However, turning *off* -ffast_math merely restores the toolchain default
02901     // (which may be false).
02902     if (A->getOption().getID() == options::OPT_fno_math_errno ||
02903         A->getOption().getID() == options::OPT_ffast_math ||
02904         A->getOption().getID() == options::OPT_Ofast)
02905       MathErrno = false;
02906     else if (A->getOption().getID() == options::OPT_fmath_errno)
02907       MathErrno = true;
02908   }
02909   if (MathErrno)
02910     CmdArgs.push_back("-fmath-errno");
02911 
02912   // There are several flags which require disabling very specific
02913   // optimizations. Any of these being disabled forces us to turn off the
02914   // entire set of LLVM optimizations, so collect them through all the flag
02915   // madness.
02916   bool AssociativeMath = false;
02917   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02918                                options::OPT_fno_fast_math,
02919                                options::OPT_funsafe_math_optimizations,
02920                                options::OPT_fno_unsafe_math_optimizations,
02921                                options::OPT_fassociative_math,
02922                                options::OPT_fno_associative_math))
02923     if (A->getOption().getID() != options::OPT_fno_fast_math &&
02924         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
02925         A->getOption().getID() != options::OPT_fno_associative_math)
02926       AssociativeMath = true;
02927   bool ReciprocalMath = false;
02928   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02929                                options::OPT_fno_fast_math,
02930                                options::OPT_funsafe_math_optimizations,
02931                                options::OPT_fno_unsafe_math_optimizations,
02932                                options::OPT_freciprocal_math,
02933                                options::OPT_fno_reciprocal_math))
02934     if (A->getOption().getID() != options::OPT_fno_fast_math &&
02935         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
02936         A->getOption().getID() != options::OPT_fno_reciprocal_math)
02937       ReciprocalMath = true;
02938   bool SignedZeros = true;
02939   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02940                                options::OPT_fno_fast_math,
02941                                options::OPT_funsafe_math_optimizations,
02942                                options::OPT_fno_unsafe_math_optimizations,
02943                                options::OPT_fsigned_zeros,
02944                                options::OPT_fno_signed_zeros))
02945     if (A->getOption().getID() != options::OPT_fno_fast_math &&
02946         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
02947         A->getOption().getID() != options::OPT_fsigned_zeros)
02948       SignedZeros = false;
02949   bool TrappingMath = true;
02950   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02951                                options::OPT_fno_fast_math,
02952                                options::OPT_funsafe_math_optimizations,
02953                                options::OPT_fno_unsafe_math_optimizations,
02954                                options::OPT_ftrapping_math,
02955                                options::OPT_fno_trapping_math))
02956     if (A->getOption().getID() != options::OPT_fno_fast_math &&
02957         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
02958         A->getOption().getID() != options::OPT_ftrapping_math)
02959       TrappingMath = false;
02960   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
02961       !TrappingMath)
02962     CmdArgs.push_back("-menable-unsafe-fp-math");
02963 
02964 
02965   // Validate and pass through -fp-contract option. 
02966   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02967                                options::OPT_fno_fast_math,
02968                                options::OPT_ffp_contract)) {
02969     if (A->getOption().getID() == options::OPT_ffp_contract) {
02970       StringRef Val = A->getValue();
02971       if (Val == "fast" || Val == "on" || Val == "off") {
02972         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
02973       } else {
02974         D.Diag(diag::err_drv_unsupported_option_argument)
02975           << A->getOption().getName() << Val;
02976       }
02977     } else if (A->getOption().matches(options::OPT_ffast_math) ||
02978                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
02979       // If fast-math is set then set the fp-contract mode to fast.
02980       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
02981     }
02982   }
02983 
02984   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
02985   // and if we find them, tell the frontend to provide the appropriate
02986   // preprocessor macros. This is distinct from enabling any optimizations as
02987   // these options induce language changes which must survive serialization
02988   // and deserialization, etc.
02989   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
02990                                options::OPT_fno_fast_math))
02991       if (!A->getOption().matches(options::OPT_fno_fast_math))
02992         CmdArgs.push_back("-ffast-math");
02993   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
02994                                options::OPT_fno_fast_math))
02995     if (A->getOption().matches(options::OPT_ffinite_math_only))
02996       CmdArgs.push_back("-ffinite-math-only");
02997 
02998   // Decide whether to use verbose asm. Verbose assembly is the default on
02999   // toolchains which have the integrated assembler on by default.
03000   bool IsIntegratedAssemblerDefault =
03001       getToolChain().IsIntegratedAssemblerDefault();
03002   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
03003                    IsIntegratedAssemblerDefault) ||
03004       Args.hasArg(options::OPT_dA))
03005     CmdArgs.push_back("-masm-verbose");
03006 
03007   if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
03008                     IsIntegratedAssemblerDefault))
03009     CmdArgs.push_back("-no-integrated-as");
03010 
03011   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
03012     CmdArgs.push_back("-mdebug-pass");
03013     CmdArgs.push_back("Structure");
03014   }
03015   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
03016     CmdArgs.push_back("-mdebug-pass");
03017     CmdArgs.push_back("Arguments");
03018   }
03019 
03020   // Enable -mconstructor-aliases except on darwin, where we have to
03021   // work around a linker bug;  see <rdar://problem/7651567>.
03022   if (!getToolChain().getTriple().isOSDarwin())
03023     CmdArgs.push_back("-mconstructor-aliases");
03024 
03025   // Darwin's kernel doesn't support guard variables; just die if we
03026   // try to use them.
03027   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
03028     CmdArgs.push_back("-fforbid-guard-variables");
03029 
03030   if (Args.hasArg(options::OPT_mms_bitfields)) {
03031     CmdArgs.push_back("-mms-bitfields");
03032   }
03033 
03034   // This is a coarse approximation of what llvm-gcc actually does, both
03035   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
03036   // complicated ways.
03037   bool AsynchronousUnwindTables =
03038       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
03039                    options::OPT_fno_asynchronous_unwind_tables,
03040                    (getToolChain().IsUnwindTablesDefault() ||
03041                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
03042                        !KernelOrKext);
03043   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
03044                    AsynchronousUnwindTables))
03045     CmdArgs.push_back("-munwind-tables");
03046 
03047   getToolChain().addClangTargetOptions(Args, CmdArgs);
03048 
03049   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
03050     CmdArgs.push_back("-mlimit-float-precision");
03051     CmdArgs.push_back(A->getValue());
03052   }
03053 
03054   // FIXME: Handle -mtune=.
03055   (void) Args.hasArg(options::OPT_mtune_EQ);
03056 
03057   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
03058     CmdArgs.push_back("-mcode-model");
03059     CmdArgs.push_back(A->getValue());
03060   }
03061 
03062   // Add the target cpu
03063   std::string ETripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
03064   llvm::Triple ETriple(ETripleStr);
03065   std::string CPU = getCPUName(Args, ETriple);
03066   if (!CPU.empty()) {
03067     CmdArgs.push_back("-target-cpu");
03068     CmdArgs.push_back(Args.MakeArgString(CPU));
03069   }
03070 
03071   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
03072     CmdArgs.push_back("-mfpmath");
03073     CmdArgs.push_back(A->getValue());
03074   }
03075 
03076   // Add the target features
03077   getTargetFeatures(D, ETriple, Args, CmdArgs, false);
03078 
03079   // Add target specific flags.
03080   switch(getToolChain().getArch()) {
03081   default:
03082     break;
03083 
03084   case llvm::Triple::arm:
03085   case llvm::Triple::armeb:
03086   case llvm::Triple::thumb:
03087   case llvm::Triple::thumbeb:
03088     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
03089     break;
03090 
03091   case llvm::Triple::aarch64:
03092   case llvm::Triple::aarch64_be:
03093     AddAArch64TargetArgs(Args, CmdArgs);
03094     break;
03095 
03096   case llvm::Triple::mips:
03097   case llvm::Triple::mipsel:
03098   case llvm::Triple::mips64:
03099   case llvm::Triple::mips64el:
03100     AddMIPSTargetArgs(Args, CmdArgs);
03101     break;
03102 
03103   case llvm::Triple::ppc:
03104   case llvm::Triple::ppc64:
03105   case llvm::Triple::ppc64le:
03106     AddPPCTargetArgs(Args, CmdArgs);
03107     break;
03108 
03109   case llvm::Triple::sparc:
03110   case llvm::Triple::sparcv9:
03111     AddSparcTargetArgs(Args, CmdArgs);
03112     break;
03113 
03114   case llvm::Triple::x86:
03115   case llvm::Triple::x86_64:
03116     AddX86TargetArgs(Args, CmdArgs);
03117     break;
03118 
03119   case llvm::Triple::hexagon:
03120     AddHexagonTargetArgs(Args, CmdArgs);
03121     break;
03122   }
03123 
03124   // Add clang-cl arguments.
03125   if (getToolChain().getDriver().IsCLMode())
03126     AddClangCLArgs(Args, CmdArgs);
03127 
03128   // Pass the linker version in use.
03129   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
03130     CmdArgs.push_back("-target-linker-version");
03131     CmdArgs.push_back(A->getValue());
03132   }
03133 
03134   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
03135     CmdArgs.push_back("-momit-leaf-frame-pointer");
03136 
03137   // Explicitly error on some things we know we don't support and can't just
03138   // ignore.
03139   types::ID InputType = Inputs[0].getType();
03140   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
03141     Arg *Unsupported;
03142     if (types::isCXX(InputType) &&
03143         getToolChain().getTriple().isOSDarwin() &&
03144         getToolChain().getArch() == llvm::Triple::x86) {
03145       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
03146           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
03147         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
03148           << Unsupported->getOption().getName();
03149     }
03150   }
03151 
03152   Args.AddAllArgs(CmdArgs, options::OPT_v);
03153   Args.AddLastArg(CmdArgs, options::OPT_H);
03154   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
03155     CmdArgs.push_back("-header-include-file");
03156     CmdArgs.push_back(D.CCPrintHeadersFilename ?
03157                       D.CCPrintHeadersFilename : "-");
03158   }
03159   Args.AddLastArg(CmdArgs, options::OPT_P);
03160   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
03161 
03162   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
03163     CmdArgs.push_back("-diagnostic-log-file");
03164     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
03165                       D.CCLogDiagnosticsFilename : "-");
03166   }
03167 
03168   // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
03169   // are preserved, all other debug options are substituted with "-g".
03170   Args.ClaimAllArgs(options::OPT_g_Group);
03171   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
03172     if (A->getOption().matches(options::OPT_gline_tables_only) ||
03173         A->getOption().matches(options::OPT_g1)) {
03174       // FIXME: we should support specifying dwarf version with
03175       // -gline-tables-only.
03176       CmdArgs.push_back("-gline-tables-only");
03177       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
03178       const llvm::Triple &Triple = getToolChain().getTriple();
03179       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
03180           Triple.getOS() == llvm::Triple::FreeBSD ||
03181           Triple.getOS() == llvm::Triple::Solaris)
03182         CmdArgs.push_back("-gdwarf-2");
03183     } else if (A->getOption().matches(options::OPT_gdwarf_2))
03184       CmdArgs.push_back("-gdwarf-2");
03185     else if (A->getOption().matches(options::OPT_gdwarf_3))
03186       CmdArgs.push_back("-gdwarf-3");
03187     else if (A->getOption().matches(options::OPT_gdwarf_4))
03188       CmdArgs.push_back("-gdwarf-4");
03189     else if (!A->getOption().matches(options::OPT_g0) &&
03190              !A->getOption().matches(options::OPT_ggdb0)) {
03191       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
03192       const llvm::Triple &Triple = getToolChain().getTriple();
03193       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
03194           Triple.getOS() == llvm::Triple::FreeBSD ||
03195           Triple.getOS() == llvm::Triple::Solaris)
03196         CmdArgs.push_back("-gdwarf-2");
03197       else
03198         CmdArgs.push_back("-g");
03199     }
03200   }
03201 
03202   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
03203   Args.ClaimAllArgs(options::OPT_g_flags_Group);
03204   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
03205                    /*Default*/ true))
03206     CmdArgs.push_back("-dwarf-column-info");
03207 
03208   // FIXME: Move backend command line options to the module.
03209   // -gsplit-dwarf should turn on -g and enable the backend dwarf
03210   // splitting and extraction.
03211   // FIXME: Currently only works on Linux.
03212   if (getToolChain().getTriple().isOSLinux() &&
03213       Args.hasArg(options::OPT_gsplit_dwarf)) {
03214     CmdArgs.push_back("-g");
03215     CmdArgs.push_back("-backend-option");
03216     CmdArgs.push_back("-split-dwarf=Enable");
03217   }
03218 
03219   // -ggnu-pubnames turns on gnu style pubnames in the backend.
03220   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
03221     CmdArgs.push_back("-backend-option");
03222     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
03223   }
03224 
03225   // -gdwarf-aranges turns on the emission of the aranges section in the
03226   // backend.
03227   if (Args.hasArg(options::OPT_gdwarf_aranges)) {
03228     CmdArgs.push_back("-backend-option");
03229     CmdArgs.push_back("-generate-arange-section");
03230   }
03231 
03232   if (Args.hasFlag(options::OPT_fdebug_types_section,
03233                    options::OPT_fno_debug_types_section, false)) {
03234     CmdArgs.push_back("-backend-option");
03235     CmdArgs.push_back("-generate-type-units");
03236   }
03237 
03238   if (Args.hasFlag(options::OPT_ffunction_sections,
03239                    options::OPT_fno_function_sections, false)) {
03240     CmdArgs.push_back("-ffunction-sections");
03241   }
03242 
03243   if (Args.hasFlag(options::OPT_fdata_sections,
03244                    options::OPT_fno_data_sections, false)) {
03245     CmdArgs.push_back("-fdata-sections");
03246   }
03247 
03248   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
03249 
03250   if (Args.hasArg(options::OPT_fprofile_instr_generate) &&
03251       (Args.hasArg(options::OPT_fprofile_instr_use) ||
03252        Args.hasArg(options::OPT_fprofile_instr_use_EQ)))
03253     D.Diag(diag::err_drv_argument_not_allowed_with)
03254       << "-fprofile-instr-generate" << "-fprofile-instr-use";
03255 
03256   Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
03257 
03258   if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_use_EQ))
03259     A->render(Args, CmdArgs);
03260   else if (Args.hasArg(options::OPT_fprofile_instr_use))
03261     CmdArgs.push_back("-fprofile-instr-use=pgo-data");
03262 
03263   if (Args.hasArg(options::OPT_ftest_coverage) ||
03264       Args.hasArg(options::OPT_coverage))
03265     CmdArgs.push_back("-femit-coverage-notes");
03266   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
03267                    false) ||
03268       Args.hasArg(options::OPT_coverage))
03269     CmdArgs.push_back("-femit-coverage-data");
03270 
03271   if (Args.hasArg(options::OPT_fcoverage_mapping) &&
03272       !Args.hasArg(options::OPT_fprofile_instr_generate))
03273     D.Diag(diag::err_drv_argument_only_allowed_with)
03274       << "-fcoverage-mapping" << "-fprofile-instr-generate";
03275 
03276   if (Args.hasArg(options::OPT_fcoverage_mapping))
03277     CmdArgs.push_back("-fcoverage-mapping");
03278 
03279   if (C.getArgs().hasArg(options::OPT_c) ||
03280       C.getArgs().hasArg(options::OPT_S)) {
03281     if (Output.isFilename()) {
03282       CmdArgs.push_back("-coverage-file");
03283       SmallString<128> CoverageFilename;
03284       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
03285         CoverageFilename = FinalOutput->getValue();
03286       } else {
03287         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
03288       }
03289       if (llvm::sys::path::is_relative(CoverageFilename.str())) {
03290         SmallString<128> Pwd;
03291         if (!llvm::sys::fs::current_path(Pwd)) {
03292           llvm::sys::path::append(Pwd, CoverageFilename.str());
03293           CoverageFilename.swap(Pwd);
03294         }
03295       }
03296       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
03297     }
03298   }
03299 
03300   // Pass options for controlling the default header search paths.
03301   if (Args.hasArg(options::OPT_nostdinc)) {
03302     CmdArgs.push_back("-nostdsysteminc");
03303     CmdArgs.push_back("-nobuiltininc");
03304   } else {
03305     if (Args.hasArg(options::OPT_nostdlibinc))
03306         CmdArgs.push_back("-nostdsysteminc");
03307     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
03308     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
03309   }
03310 
03311   // Pass the path to compiler resource files.
03312   CmdArgs.push_back("-resource-dir");
03313   CmdArgs.push_back(D.ResourceDir.c_str());
03314 
03315   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
03316 
03317   bool ARCMTEnabled = false;
03318   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
03319     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
03320                                        options::OPT_ccc_arcmt_modify,
03321                                        options::OPT_ccc_arcmt_migrate)) {
03322       ARCMTEnabled = true;
03323       switch (A->getOption().getID()) {
03324       default:
03325         llvm_unreachable("missed a case");
03326       case options::OPT_ccc_arcmt_check:
03327         CmdArgs.push_back("-arcmt-check");
03328         break;
03329       case options::OPT_ccc_arcmt_modify:
03330         CmdArgs.push_back("-arcmt-modify");
03331         break;
03332       case options::OPT_ccc_arcmt_migrate:
03333         CmdArgs.push_back("-arcmt-migrate");
03334         CmdArgs.push_back("-mt-migrate-directory");
03335         CmdArgs.push_back(A->getValue());
03336 
03337         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
03338         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
03339         break;
03340       }
03341     }
03342   } else {
03343     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
03344     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
03345     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
03346   }
03347 
03348   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
03349     if (ARCMTEnabled) {
03350       D.Diag(diag::err_drv_argument_not_allowed_with)
03351         << A->getAsString(Args) << "-ccc-arcmt-migrate";
03352     }
03353     CmdArgs.push_back("-mt-migrate-directory");
03354     CmdArgs.push_back(A->getValue());
03355 
03356     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
03357                      options::OPT_objcmt_migrate_subscripting,
03358                      options::OPT_objcmt_migrate_property)) {
03359       // None specified, means enable them all.
03360       CmdArgs.push_back("-objcmt-migrate-literals");
03361       CmdArgs.push_back("-objcmt-migrate-subscripting");
03362       CmdArgs.push_back("-objcmt-migrate-property");
03363     } else {
03364       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
03365       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
03366       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
03367     }
03368   } else {
03369     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
03370     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
03371     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
03372     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
03373     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
03374     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
03375     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
03376     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
03377     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
03378     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
03379     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
03380     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
03381     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
03382     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
03383     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
03384   }
03385 
03386   // Add preprocessing options like -I, -D, etc. if we are using the
03387   // preprocessor.
03388   //
03389   // FIXME: Support -fpreprocessed
03390   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
03391     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
03392 
03393   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
03394   // that "The compiler can only warn and ignore the option if not recognized".
03395   // When building with ccache, it will pass -D options to clang even on
03396   // preprocessed inputs and configure concludes that -fPIC is not supported.
03397   Args.ClaimAllArgs(options::OPT_D);
03398 
03399   // Manually translate -O4 to -O3; let clang reject others.
03400   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
03401     if (A->getOption().matches(options::OPT_O4)) {
03402       CmdArgs.push_back("-O3");
03403       D.Diag(diag::warn_O4_is_O3);
03404     } else {
03405       A->render(Args, CmdArgs);
03406     }
03407   }
03408 
03409   // Warn about ignored options to clang.
03410   for (arg_iterator it = Args.filtered_begin(
03411        options::OPT_clang_ignored_gcc_optimization_f_Group),
03412        ie = Args.filtered_end(); it != ie; ++it) {
03413     D.Diag(diag::warn_ignored_gcc_optimization) << (*it)->getAsString(Args);
03414   }
03415 
03416   // Don't warn about unused -flto.  This can happen when we're preprocessing or
03417   // precompiling.
03418   Args.ClaimAllArgs(options::OPT_flto);
03419 
03420   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
03421   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
03422   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
03423     CmdArgs.push_back("-pedantic");
03424   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
03425   Args.AddLastArg(CmdArgs, options::OPT_w);
03426 
03427   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
03428   // (-ansi is equivalent to -std=c89 or -std=c++98).
03429   //
03430   // If a std is supplied, only add -trigraphs if it follows the
03431   // option.
03432   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
03433     if (Std->getOption().matches(options::OPT_ansi))
03434       if (types::isCXX(InputType))
03435         CmdArgs.push_back("-std=c++98");
03436       else
03437         CmdArgs.push_back("-std=c89");
03438     else
03439       Std->render(Args, CmdArgs);
03440 
03441     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
03442                                  options::OPT_trigraphs))
03443       if (A != Std)
03444         A->render(Args, CmdArgs);
03445   } else {
03446     // Honor -std-default.
03447     //
03448     // FIXME: Clang doesn't correctly handle -std= when the input language
03449     // doesn't match. For the time being just ignore this for C++ inputs;
03450     // eventually we want to do all the standard defaulting here instead of
03451     // splitting it between the driver and clang -cc1.
03452     if (!types::isCXX(InputType))
03453       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
03454                                 "-std=", /*Joined=*/true);
03455     else if (IsWindowsMSVC)
03456       CmdArgs.push_back("-std=c++11");
03457 
03458     Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
03459   }
03460 
03461   // GCC's behavior for -Wwrite-strings is a bit strange:
03462   //  * In C, this "warning flag" changes the types of string literals from
03463   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
03464   //    for the discarded qualifier.
03465   //  * In C++, this is just a normal warning flag.
03466   //
03467   // Implementing this warning correctly in C is hard, so we follow GCC's
03468   // behavior for now. FIXME: Directly diagnose uses of a string literal as
03469   // a non-const char* in C, rather than using this crude hack.
03470   if (!types::isCXX(InputType)) {
03471     // FIXME: This should behave just like a warning flag, and thus should also
03472     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
03473     Arg *WriteStrings =
03474         Args.getLastArg(options::OPT_Wwrite_strings,
03475                         options::OPT_Wno_write_strings, options::OPT_w);
03476     if (WriteStrings &&
03477         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
03478       CmdArgs.push_back("-fconst-strings");
03479   }
03480 
03481   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
03482   // during C++ compilation, which it is by default. GCC keeps this define even
03483   // in the presence of '-w', match this behavior bug-for-bug.
03484   if (types::isCXX(InputType) &&
03485       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
03486                    true)) {
03487     CmdArgs.push_back("-fdeprecated-macro");
03488   }
03489 
03490   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
03491   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
03492     if (Asm->getOption().matches(options::OPT_fasm))
03493       CmdArgs.push_back("-fgnu-keywords");
03494     else
03495       CmdArgs.push_back("-fno-gnu-keywords");
03496   }
03497 
03498   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
03499     CmdArgs.push_back("-fno-dwarf-directory-asm");
03500 
03501   if (ShouldDisableAutolink(Args, getToolChain()))
03502     CmdArgs.push_back("-fno-autolink");
03503 
03504   // Add in -fdebug-compilation-dir if necessary.
03505   addDebugCompDirArg(Args, CmdArgs);
03506 
03507   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
03508                                options::OPT_ftemplate_depth_EQ)) {
03509     CmdArgs.push_back("-ftemplate-depth");
03510     CmdArgs.push_back(A->getValue());
03511   }
03512 
03513   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
03514     CmdArgs.push_back("-foperator-arrow-depth");
03515     CmdArgs.push_back(A->getValue());
03516   }
03517 
03518   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
03519     CmdArgs.push_back("-fconstexpr-depth");
03520     CmdArgs.push_back(A->getValue());
03521   }
03522 
03523   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
03524     CmdArgs.push_back("-fconstexpr-steps");
03525     CmdArgs.push_back(A->getValue());
03526   }
03527 
03528   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
03529     CmdArgs.push_back("-fbracket-depth");
03530     CmdArgs.push_back(A->getValue());
03531   }
03532 
03533   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
03534                                options::OPT_Wlarge_by_value_copy_def)) {
03535     if (A->getNumValues()) {
03536       StringRef bytes = A->getValue();
03537       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
03538     } else
03539       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
03540   }
03541 
03542 
03543   if (Args.hasArg(options::OPT_relocatable_pch))
03544     CmdArgs.push_back("-relocatable-pch");
03545 
03546   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
03547     CmdArgs.push_back("-fconstant-string-class");
03548     CmdArgs.push_back(A->getValue());
03549   }
03550 
03551   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
03552     CmdArgs.push_back("-ftabstop");
03553     CmdArgs.push_back(A->getValue());
03554   }
03555 
03556   CmdArgs.push_back("-ferror-limit");
03557   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
03558     CmdArgs.push_back(A->getValue());
03559   else
03560     CmdArgs.push_back("19");
03561 
03562   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
03563     CmdArgs.push_back("-fmacro-backtrace-limit");
03564     CmdArgs.push_back(A->getValue());
03565   }
03566 
03567   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
03568     CmdArgs.push_back("-ftemplate-backtrace-limit");
03569     CmdArgs.push_back(A->getValue());
03570   }
03571 
03572   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
03573     CmdArgs.push_back("-fconstexpr-backtrace-limit");
03574     CmdArgs.push_back(A->getValue());
03575   }
03576 
03577   // Pass -fmessage-length=.
03578   CmdArgs.push_back("-fmessage-length");
03579   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
03580     CmdArgs.push_back(A->getValue());
03581   } else {
03582     // If -fmessage-length=N was not specified, determine whether this is a
03583     // terminal and, if so, implicitly define -fmessage-length appropriately.
03584     unsigned N = llvm::sys::Process::StandardErrColumns();
03585     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
03586   }
03587 
03588   // -fvisibility= and -fvisibility-ms-compat are of a piece.
03589   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
03590                                      options::OPT_fvisibility_ms_compat)) {
03591     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
03592       CmdArgs.push_back("-fvisibility");
03593       CmdArgs.push_back(A->getValue());
03594     } else {
03595       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
03596       CmdArgs.push_back("-fvisibility");
03597       CmdArgs.push_back("hidden");
03598       CmdArgs.push_back("-ftype-visibility");
03599       CmdArgs.push_back("default");
03600     }
03601   }
03602 
03603   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
03604 
03605   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
03606 
03607   // -fhosted is default.
03608   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
03609       KernelOrKext)
03610     CmdArgs.push_back("-ffreestanding");
03611 
03612   // Forward -f (flag) options which we can pass directly.
03613   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
03614   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
03615   Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
03616   Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
03617   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
03618   // AltiVec language extensions aren't relevant for assembling.
03619   if (!isa<PreprocessJobAction>(JA) || 
03620       Output.getType() != types::TY_PP_Asm)
03621     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
03622   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
03623   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
03624 
03625   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
03626   Sanitize.addArgs(Args, CmdArgs);
03627 
03628   // Report an error for -faltivec on anything other than PowerPC.
03629   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
03630     if (!(getToolChain().getArch() == llvm::Triple::ppc ||
03631           getToolChain().getArch() == llvm::Triple::ppc64 ||
03632           getToolChain().getArch() == llvm::Triple::ppc64le))
03633       D.Diag(diag::err_drv_argument_only_allowed_with)
03634         << A->getAsString(Args) << "ppc/ppc64/ppc64le";
03635 
03636   if (getToolChain().SupportsProfiling())
03637     Args.AddLastArg(CmdArgs, options::OPT_pg);
03638 
03639   // -flax-vector-conversions is default.
03640   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
03641                     options::OPT_fno_lax_vector_conversions))
03642     CmdArgs.push_back("-fno-lax-vector-conversions");
03643 
03644   if (Args.getLastArg(options::OPT_fapple_kext))
03645     CmdArgs.push_back("-fapple-kext");
03646 
03647   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
03648   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
03649   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
03650   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
03651   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
03652 
03653   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
03654     CmdArgs.push_back("-ftrapv-handler");
03655     CmdArgs.push_back(A->getValue());
03656   }
03657 
03658   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
03659 
03660   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
03661   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
03662   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
03663                                options::OPT_fno_wrapv)) {
03664     if (A->getOption().matches(options::OPT_fwrapv))
03665       CmdArgs.push_back("-fwrapv");
03666   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
03667                                       options::OPT_fno_strict_overflow)) {
03668     if (A->getOption().matches(options::OPT_fno_strict_overflow))
03669       CmdArgs.push_back("-fwrapv");
03670   }
03671 
03672   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
03673                                options::OPT_fno_reroll_loops))
03674     if (A->getOption().matches(options::OPT_freroll_loops))
03675       CmdArgs.push_back("-freroll-loops");
03676 
03677   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
03678   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
03679                   options::OPT_fno_unroll_loops);
03680 
03681   Args.AddLastArg(CmdArgs, options::OPT_pthread);
03682 
03683 
03684   // -stack-protector=0 is default.
03685   unsigned StackProtectorLevel = 0;
03686   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
03687                                options::OPT_fstack_protector_all,
03688                                options::OPT_fstack_protector_strong,
03689                                options::OPT_fstack_protector)) {
03690     if (A->getOption().matches(options::OPT_fstack_protector)) {
03691       StackProtectorLevel = std::max<unsigned>(LangOptions::SSPOn,
03692         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
03693     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
03694       StackProtectorLevel = LangOptions::SSPStrong;
03695     else if (A->getOption().matches(options::OPT_fstack_protector_all))
03696       StackProtectorLevel = LangOptions::SSPReq;
03697   } else {
03698     StackProtectorLevel =
03699       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
03700   }
03701   if (StackProtectorLevel) {
03702     CmdArgs.push_back("-stack-protector");
03703     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
03704   }
03705 
03706   // --param ssp-buffer-size=
03707   for (arg_iterator it = Args.filtered_begin(options::OPT__param),
03708        ie = Args.filtered_end(); it != ie; ++it) {
03709     StringRef Str((*it)->getValue());
03710     if (Str.startswith("ssp-buffer-size=")) {
03711       if (StackProtectorLevel) {
03712         CmdArgs.push_back("-stack-protector-buffer-size");
03713         // FIXME: Verify the argument is a valid integer.
03714         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
03715       }
03716       (*it)->claim();
03717     }
03718   }
03719 
03720   // Translate -mstackrealign
03721   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
03722                    false)) {
03723     CmdArgs.push_back("-backend-option");
03724     CmdArgs.push_back("-force-align-stack");
03725   }
03726   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
03727                    false)) {
03728     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
03729   }
03730 
03731   if (Args.hasArg(options::OPT_mstack_alignment)) {
03732     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
03733     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
03734   }
03735 
03736   if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
03737       getToolChain().getTriple().getArch() == llvm::Triple::aarch64_be)
03738     CmdArgs.push_back("-fallow-half-arguments-and-returns");
03739 
03740   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
03741                                options::OPT_mno_restrict_it)) {
03742     if (A->getOption().matches(options::OPT_mrestrict_it)) {
03743       CmdArgs.push_back("-backend-option");
03744       CmdArgs.push_back("-arm-restrict-it");
03745     } else {
03746       CmdArgs.push_back("-backend-option");
03747       CmdArgs.push_back("-arm-no-restrict-it");
03748     }
03749   } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
03750                                   TT.getArch() == llvm::Triple::thumb)) {
03751     // Windows on ARM expects restricted IT blocks
03752     CmdArgs.push_back("-backend-option");
03753     CmdArgs.push_back("-arm-restrict-it");
03754   }
03755 
03756   if (TT.getArch() == llvm::Triple::arm ||
03757       TT.getArch() == llvm::Triple::thumb) {
03758     if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
03759                                  options::OPT_mno_long_calls)) {
03760       if (A->getOption().matches(options::OPT_mlong_calls)) {
03761         CmdArgs.push_back("-backend-option");
03762         CmdArgs.push_back("-arm-long-calls");
03763       }
03764     }
03765   }
03766 
03767   // Forward -f options with positive and negative forms; we translate
03768   // these by hand.
03769   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
03770     StringRef fname = A->getValue();
03771     if (!llvm::sys::fs::exists(fname))
03772       D.Diag(diag::err_drv_no_such_file) << fname;
03773     else
03774       A->render(Args, CmdArgs);
03775   }
03776 
03777   if (Args.hasArg(options::OPT_mkernel)) {
03778     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
03779       CmdArgs.push_back("-fapple-kext");
03780     if (!Args.hasArg(options::OPT_fbuiltin))
03781       CmdArgs.push_back("-fno-builtin");
03782     Args.ClaimAllArgs(options::OPT_fno_builtin);
03783   }
03784   // -fbuiltin is default.
03785   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
03786     CmdArgs.push_back("-fno-builtin");
03787 
03788   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
03789                     options::OPT_fno_assume_sane_operator_new))
03790     CmdArgs.push_back("-fno-assume-sane-operator-new");
03791 
03792   // -fblocks=0 is default.
03793   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
03794                    getToolChain().IsBlocksDefault()) ||
03795         (Args.hasArg(options::OPT_fgnu_runtime) &&
03796          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
03797          !Args.hasArg(options::OPT_fno_blocks))) {
03798     CmdArgs.push_back("-fblocks");
03799 
03800     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
03801         !getToolChain().hasBlocksRuntime())
03802       CmdArgs.push_back("-fblocks-runtime-optional");
03803   }
03804 
03805   // -fmodules enables modules (off by default).
03806   // Users can pass -fno-cxx-modules to turn off modules support for
03807   // C++/Objective-C++ programs, which is a little less mature.
03808   bool HaveModules = false;
03809   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
03810     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
03811                                      options::OPT_fno_cxx_modules, 
03812                                      true);
03813     if (AllowedInCXX || !types::isCXX(InputType)) {
03814       CmdArgs.push_back("-fmodules");
03815       HaveModules = true;
03816     }
03817   }
03818 
03819   // -fmodule-maps enables module map processing (off by default) for header
03820   // checking.  It is implied by -fmodules.
03821   if (Args.hasFlag(options::OPT_fmodule_maps, options::OPT_fno_module_maps,
03822                    false)) {
03823     CmdArgs.push_back("-fmodule-maps");
03824   }
03825 
03826   // -fmodules-decluse checks that modules used are declared so (off by
03827   // default).
03828   if (Args.hasFlag(options::OPT_fmodules_decluse,
03829                    options::OPT_fno_modules_decluse,
03830                    false)) {
03831     CmdArgs.push_back("-fmodules-decluse");
03832   }
03833 
03834   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
03835   // all #included headers are part of modules.
03836   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
03837                    options::OPT_fno_modules_strict_decluse,
03838                    false)) {
03839     CmdArgs.push_back("-fmodules-strict-decluse");
03840   }
03841 
03842   // -fmodule-name specifies the module that is currently being built (or
03843   // used for header checking by -fmodule-maps).
03844   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
03845 
03846   // -fmodule-map-file can be used to specify files containing module
03847   // definitions.
03848   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
03849 
03850   // -fmodule-file can be used to specify files containing precompiled modules.
03851   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
03852 
03853   // -fmodule-cache-path specifies where our implicitly-built module files
03854   // should be written.
03855   SmallString<128> ModuleCachePath;
03856   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
03857     ModuleCachePath = A->getValue();
03858   if (HaveModules) {
03859     if (C.isForDiagnostics()) {
03860       // When generating crash reports, we want to emit the modules along with
03861       // the reproduction sources, so we ignore any provided module path.
03862       ModuleCachePath = Output.getFilename();
03863       llvm::sys::path::replace_extension(ModuleCachePath, ".cache");
03864       llvm::sys::path::append(ModuleCachePath, "modules");
03865     } else if (ModuleCachePath.empty()) {
03866       // No module path was provided: use the default.
03867       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
03868                                              ModuleCachePath);
03869       llvm::sys::path::append(ModuleCachePath, "org.llvm.clang");
03870       llvm::sys::path::append(ModuleCachePath, "ModuleCache");
03871     }
03872     const char Arg[] = "-fmodules-cache-path=";
03873     ModuleCachePath.insert(ModuleCachePath.begin(), Arg, Arg + strlen(Arg));
03874     CmdArgs.push_back(Args.MakeArgString(ModuleCachePath));
03875   }
03876 
03877   // When building modules and generating crashdumps, we need to dump a module
03878   // dependency VFS alongside the output.
03879   if (HaveModules && C.isForDiagnostics()) {
03880     SmallString<128> VFSDir(Output.getFilename());
03881     llvm::sys::path::replace_extension(VFSDir, ".cache");
03882     // Add the cache directory as a temp so the crash diagnostics pick it up.
03883     C.addTempFile(Args.MakeArgString(VFSDir));
03884 
03885     llvm::sys::path::append(VFSDir, "vfs");
03886     CmdArgs.push_back("-module-dependency-dir");
03887     CmdArgs.push_back(Args.MakeArgString(VFSDir));
03888   }
03889 
03890   if (HaveModules)
03891     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
03892 
03893   // Pass through all -fmodules-ignore-macro arguments.
03894   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
03895   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
03896   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
03897 
03898   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
03899 
03900   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
03901     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
03902       D.Diag(diag::err_drv_argument_not_allowed_with)
03903           << A->getAsString(Args) << "-fbuild-session-timestamp";
03904 
03905     llvm::sys::fs::file_status Status;
03906     if (llvm::sys::fs::status(A->getValue(), Status))
03907       D.Diag(diag::err_drv_no_such_file) << A->getValue();
03908     char TimeStamp[48];
03909     snprintf(TimeStamp, sizeof(TimeStamp), "-fbuild-session-timestamp=%" PRIu64,
03910              (uint64_t)Status.getLastModificationTime().toEpochTime());
03911     CmdArgs.push_back(Args.MakeArgString(TimeStamp));
03912   }
03913 
03914   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
03915     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
03916                          options::OPT_fbuild_session_file))
03917       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
03918 
03919     Args.AddLastArg(CmdArgs,
03920                     options::OPT_fmodules_validate_once_per_build_session);
03921   }
03922 
03923   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
03924 
03925   // -faccess-control is default.
03926   if (Args.hasFlag(options::OPT_fno_access_control,
03927                    options::OPT_faccess_control,
03928                    false))
03929     CmdArgs.push_back("-fno-access-control");
03930 
03931   // -felide-constructors is the default.
03932   if (Args.hasFlag(options::OPT_fno_elide_constructors,
03933                    options::OPT_felide_constructors,
03934                    false))
03935     CmdArgs.push_back("-fno-elide-constructors");
03936 
03937   // -frtti is default.
03938   if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
03939       KernelOrKext) {
03940     CmdArgs.push_back("-fno-rtti");
03941 
03942     // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
03943     if (Sanitize.sanitizesVptr()) {
03944       std::string NoRttiArg =
03945         Args.getLastArg(options::OPT_mkernel,
03946                         options::OPT_fapple_kext,
03947                         options::OPT_fno_rtti)->getAsString(Args);
03948       D.Diag(diag::err_drv_argument_not_allowed_with)
03949         << "-fsanitize=vptr" << NoRttiArg;
03950     }
03951   }
03952 
03953   // -fshort-enums=0 is default for all architectures except Hexagon.
03954   if (Args.hasFlag(options::OPT_fshort_enums,
03955                    options::OPT_fno_short_enums,
03956                    getToolChain().getArch() ==
03957                    llvm::Triple::hexagon))
03958     CmdArgs.push_back("-fshort-enums");
03959 
03960   // -fsigned-char is default.
03961   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
03962                     isSignedCharDefault(getToolChain().getTriple())))
03963     CmdArgs.push_back("-fno-signed-char");
03964 
03965   // -fthreadsafe-static is default.
03966   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
03967                     options::OPT_fno_threadsafe_statics))
03968     CmdArgs.push_back("-fno-threadsafe-statics");
03969 
03970   // -fuse-cxa-atexit is default.
03971   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
03972                     options::OPT_fno_use_cxa_atexit,
03973                     !IsWindowsCygnus && !IsWindowsGNU &&
03974                     getToolChain().getArch() != llvm::Triple::hexagon &&
03975                     getToolChain().getArch() != llvm::Triple::xcore) ||
03976       KernelOrKext)
03977     CmdArgs.push_back("-fno-use-cxa-atexit");
03978 
03979   // -fms-extensions=0 is default.
03980   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
03981                    IsWindowsMSVC))
03982     CmdArgs.push_back("-fms-extensions");
03983 
03984   // -fms-compatibility=0 is default.
03985   if (Args.hasFlag(options::OPT_fms_compatibility, 
03986                    options::OPT_fno_ms_compatibility,
03987                    (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
03988                                                   options::OPT_fno_ms_extensions,
03989                                                   true))))
03990     CmdArgs.push_back("-fms-compatibility");
03991 
03992   // -fms-compatibility-version=17.00 is default.
03993   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
03994                    IsWindowsMSVC) || Args.hasArg(options::OPT_fmsc_version) ||
03995       Args.hasArg(options::OPT_fms_compatibility_version)) {
03996     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
03997     const Arg *MSCompatibilityVersion =
03998       Args.getLastArg(options::OPT_fms_compatibility_version);
03999 
04000     if (MSCVersion && MSCompatibilityVersion)
04001       D.Diag(diag::err_drv_argument_not_allowed_with)
04002           << MSCVersion->getAsString(Args)
04003           << MSCompatibilityVersion->getAsString(Args);
04004 
04005     std::string Ver;
04006     if (MSCompatibilityVersion)
04007       Ver = Args.getLastArgValue(options::OPT_fms_compatibility_version);
04008     else if (MSCVersion)
04009       Ver = getMSCompatibilityVersion(MSCVersion->getValue());
04010 
04011     if (Ver.empty())
04012       CmdArgs.push_back("-fms-compatibility-version=17.00");
04013     else
04014       CmdArgs.push_back(Args.MakeArgString("-fms-compatibility-version=" + Ver));
04015   }
04016 
04017   // -fno-borland-extensions is default.
04018   if (Args.hasFlag(options::OPT_fborland_extensions,
04019                    options::OPT_fno_borland_extensions, false))
04020     CmdArgs.push_back("-fborland-extensions");
04021 
04022   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
04023   // needs it.
04024   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
04025                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
04026     CmdArgs.push_back("-fdelayed-template-parsing");
04027 
04028   // -fgnu-keywords default varies depending on language; only pass if
04029   // specified.
04030   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
04031                                options::OPT_fno_gnu_keywords))
04032     A->render(Args, CmdArgs);
04033 
04034   if (Args.hasFlag(options::OPT_fgnu89_inline,
04035                    options::OPT_fno_gnu89_inline,
04036                    false))
04037     CmdArgs.push_back("-fgnu89-inline");
04038 
04039   if (Args.hasArg(options::OPT_fno_inline))
04040     CmdArgs.push_back("-fno-inline");
04041 
04042   if (Args.hasArg(options::OPT_fno_inline_functions))
04043     CmdArgs.push_back("-fno-inline-functions");
04044 
04045   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
04046 
04047   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
04048   // legacy is the default. Except for deployment taget of 10.5,
04049   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
04050   // gets ignored silently.
04051   if (objcRuntime.isNonFragile()) {
04052     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
04053                       options::OPT_fno_objc_legacy_dispatch,
04054                       objcRuntime.isLegacyDispatchDefaultForArch(
04055                         getToolChain().getArch()))) {
04056       if (getToolChain().UseObjCMixedDispatch())
04057         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
04058       else
04059         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
04060     }
04061   }
04062 
04063   // When ObjectiveC legacy runtime is in effect on MacOSX,
04064   // turn on the option to do Array/Dictionary subscripting
04065   // by default.
04066   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 &&
04067       getToolChain().getTriple().isMacOSX() &&
04068       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
04069       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
04070       objcRuntime.isNeXTFamily())
04071     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
04072   
04073   // -fencode-extended-block-signature=1 is default.
04074   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
04075     CmdArgs.push_back("-fencode-extended-block-signature");
04076   }
04077   
04078   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
04079   // NOTE: This logic is duplicated in ToolChains.cpp.
04080   bool ARC = isObjCAutoRefCount(Args);
04081   if (ARC) {
04082     getToolChain().CheckObjCARC();
04083 
04084     CmdArgs.push_back("-fobjc-arc");
04085 
04086     // FIXME: It seems like this entire block, and several around it should be
04087     // wrapped in isObjC, but for now we just use it here as this is where it
04088     // was being used previously.
04089     if (types::isCXX(InputType) && types::isObjC(InputType)) {
04090       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
04091         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
04092       else
04093         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
04094     }
04095 
04096     // Allow the user to enable full exceptions code emission.
04097     // We define off for Objective-CC, on for Objective-C++.
04098     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
04099                      options::OPT_fno_objc_arc_exceptions,
04100                      /*default*/ types::isCXX(InputType)))
04101       CmdArgs.push_back("-fobjc-arc-exceptions");
04102   }
04103 
04104   // -fobjc-infer-related-result-type is the default, except in the Objective-C
04105   // rewriter.
04106   if (rewriteKind != RK_None)
04107     CmdArgs.push_back("-fno-objc-infer-related-result-type");
04108 
04109   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
04110   // takes precedence.
04111   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
04112   if (!GCArg)
04113     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
04114   if (GCArg) {
04115     if (ARC) {
04116       D.Diag(diag::err_drv_objc_gc_arr)
04117         << GCArg->getAsString(Args);
04118     } else if (getToolChain().SupportsObjCGC()) {
04119       GCArg->render(Args, CmdArgs);
04120     } else {
04121       // FIXME: We should move this to a hard error.
04122       D.Diag(diag::warn_drv_objc_gc_unsupported)
04123         << GCArg->getAsString(Args);
04124     }
04125   }
04126 
04127   // Handle GCC-style exception args.
04128   if (!C.getDriver().IsCLMode())
04129     addExceptionArgs(Args, InputType, getToolChain().getTriple(), KernelOrKext,
04130                      objcRuntime, CmdArgs);
04131 
04132   if (getToolChain().UseSjLjExceptions())
04133     CmdArgs.push_back("-fsjlj-exceptions");
04134 
04135   // C++ "sane" operator new.
04136   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
04137                     options::OPT_fno_assume_sane_operator_new))
04138     CmdArgs.push_back("-fno-assume-sane-operator-new");
04139 
04140   // -fconstant-cfstrings is default, and may be subject to argument translation
04141   // on Darwin.
04142   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
04143                     options::OPT_fno_constant_cfstrings) ||
04144       !Args.hasFlag(options::OPT_mconstant_cfstrings,
04145                     options::OPT_mno_constant_cfstrings))
04146     CmdArgs.push_back("-fno-constant-cfstrings");
04147 
04148   // -fshort-wchar default varies depending on platform; only
04149   // pass if specified.
04150   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
04151                                options::OPT_fno_short_wchar))
04152     A->render(Args, CmdArgs);
04153 
04154   // -fno-pascal-strings is default, only pass non-default.
04155   if (Args.hasFlag(options::OPT_fpascal_strings,
04156                    options::OPT_fno_pascal_strings,
04157                    false))
04158     CmdArgs.push_back("-fpascal-strings");
04159 
04160   // Honor -fpack-struct= and -fpack-struct, if given. Note that
04161   // -fno-pack-struct doesn't apply to -fpack-struct=.
04162   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
04163     std::string PackStructStr = "-fpack-struct=";
04164     PackStructStr += A->getValue();
04165     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
04166   } else if (Args.hasFlag(options::OPT_fpack_struct,
04167                           options::OPT_fno_pack_struct, false)) {
04168     CmdArgs.push_back("-fpack-struct=1");
04169   }
04170 
04171   // Handle -fmax-type-align=N and -fno-type-align
04172   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
04173   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
04174     if (!SkipMaxTypeAlign) {
04175       std::string MaxTypeAlignStr = "-fmax-type-align=";
04176       MaxTypeAlignStr += A->getValue();
04177       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
04178     }
04179   } else if (getToolChain().getTriple().isOSDarwin()) {
04180     if (!SkipMaxTypeAlign) {
04181       std::string MaxTypeAlignStr = "-fmax-type-align=16";
04182       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
04183     }
04184   }
04185 
04186   if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
04187     if (!Args.hasArg(options::OPT_fcommon))
04188       CmdArgs.push_back("-fno-common");
04189     Args.ClaimAllArgs(options::OPT_fno_common);
04190   }
04191 
04192   // -fcommon is default, only pass non-default.
04193   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
04194     CmdArgs.push_back("-fno-common");
04195 
04196   // -fsigned-bitfields is default, and clang doesn't yet support
04197   // -funsigned-bitfields.
04198   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
04199                     options::OPT_funsigned_bitfields))
04200     D.Diag(diag::warn_drv_clang_unsupported)
04201       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
04202 
04203   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
04204   if (!Args.hasFlag(options::OPT_ffor_scope,
04205                     options::OPT_fno_for_scope))
04206     D.Diag(diag::err_drv_clang_unsupported)
04207       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
04208 
04209   // -finput_charset=UTF-8 is default. Reject others
04210   if (Arg *inputCharset = Args.getLastArg(
04211           options::OPT_finput_charset_EQ)) {
04212       StringRef value = inputCharset->getValue();
04213       if (value != "UTF-8")
04214           D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) << value;
04215   }
04216 
04217   // -fexec_charset=UTF-8 is default. Reject others
04218   if (Arg *execCharset = Args.getLastArg(
04219           options::OPT_fexec_charset_EQ)) {
04220       StringRef value = execCharset->getValue();
04221       if (value != "UTF-8")
04222           D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) << value;
04223   }
04224 
04225   // -fcaret-diagnostics is default.
04226   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
04227                     options::OPT_fno_caret_diagnostics, true))
04228     CmdArgs.push_back("-fno-caret-diagnostics");
04229 
04230   // -fdiagnostics-fixit-info is default, only pass non-default.
04231   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
04232                     options::OPT_fno_diagnostics_fixit_info))
04233     CmdArgs.push_back("-fno-diagnostics-fixit-info");
04234 
04235   // Enable -fdiagnostics-show-option by default.
04236   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
04237                    options::OPT_fno_diagnostics_show_option))
04238     CmdArgs.push_back("-fdiagnostics-show-option");
04239 
04240   if (const Arg *A =
04241         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
04242     CmdArgs.push_back("-fdiagnostics-show-category");
04243     CmdArgs.push_back(A->getValue());
04244   }
04245 
04246   if (const Arg *A =
04247         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
04248     CmdArgs.push_back("-fdiagnostics-format");
04249     CmdArgs.push_back(A->getValue());
04250   }
04251 
04252   if (Arg *A = Args.getLastArg(
04253       options::OPT_fdiagnostics_show_note_include_stack,
04254       options::OPT_fno_diagnostics_show_note_include_stack)) {
04255     if (A->getOption().matches(
04256         options::OPT_fdiagnostics_show_note_include_stack))
04257       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
04258     else
04259       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
04260   }
04261 
04262   // Color diagnostics are the default, unless the terminal doesn't support
04263   // them.
04264   // Support both clang's -f[no-]color-diagnostics and gcc's
04265   // -f[no-]diagnostics-colors[=never|always|auto].
04266   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
04267   for (const auto &Arg : Args) {
04268     const Option &O = Arg->getOption();
04269     if (!O.matches(options::OPT_fcolor_diagnostics) &&
04270         !O.matches(options::OPT_fdiagnostics_color) &&
04271         !O.matches(options::OPT_fno_color_diagnostics) &&
04272         !O.matches(options::OPT_fno_diagnostics_color) &&
04273         !O.matches(options::OPT_fdiagnostics_color_EQ))
04274       continue;
04275 
04276     Arg->claim();
04277     if (O.matches(options::OPT_fcolor_diagnostics) ||
04278         O.matches(options::OPT_fdiagnostics_color)) {
04279       ShowColors = Colors_On;
04280     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
04281                O.matches(options::OPT_fno_diagnostics_color)) {
04282       ShowColors = Colors_Off;
04283     } else {
04284       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
04285       StringRef value(Arg->getValue());
04286       if (value == "always")
04287         ShowColors = Colors_On;
04288       else if (value == "never")
04289         ShowColors = Colors_Off;
04290       else if (value == "auto")
04291         ShowColors = Colors_Auto;
04292       else
04293         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
04294           << ("-fdiagnostics-color=" + value).str();
04295     }
04296   }
04297   if (ShowColors == Colors_On ||
04298       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
04299     CmdArgs.push_back("-fcolor-diagnostics");
04300 
04301   if (Args.hasArg(options::OPT_fansi_escape_codes))
04302     CmdArgs.push_back("-fansi-escape-codes");
04303 
04304   if (!Args.hasFlag(options::OPT_fshow_source_location,
04305                     options::OPT_fno_show_source_location))
04306     CmdArgs.push_back("-fno-show-source-location");
04307 
04308   if (!Args.hasFlag(options::OPT_fshow_column,
04309                     options::OPT_fno_show_column,
04310                     true))
04311     CmdArgs.push_back("-fno-show-column");
04312 
04313   if (!Args.hasFlag(options::OPT_fspell_checking,
04314                     options::OPT_fno_spell_checking))
04315     CmdArgs.push_back("-fno-spell-checking");
04316 
04317 
04318   // -fno-asm-blocks is default.
04319   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
04320                    false))
04321     CmdArgs.push_back("-fasm-blocks");
04322 
04323   // Enable vectorization per default according to the optimization level
04324   // selected. For optimization levels that want vectorization we use the alias
04325   // option to simplify the hasFlag logic.
04326   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
04327   OptSpecifier VectorizeAliasOption = EnableVec ? options::OPT_O_Group :
04328     options::OPT_fvectorize;
04329   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
04330                    options::OPT_fno_vectorize, EnableVec))
04331     CmdArgs.push_back("-vectorize-loops");
04332 
04333   // -fslp-vectorize is enabled based on the optimization level selected.
04334   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
04335   OptSpecifier SLPVectAliasOption = EnableSLPVec ? options::OPT_O_Group :
04336     options::OPT_fslp_vectorize;
04337   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
04338                    options::OPT_fno_slp_vectorize, EnableSLPVec))
04339     CmdArgs.push_back("-vectorize-slp");
04340 
04341   // -fno-slp-vectorize-aggressive is default.
04342   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
04343                    options::OPT_fno_slp_vectorize_aggressive, false))
04344     CmdArgs.push_back("-vectorize-slp-aggressive");
04345 
04346   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
04347     A->render(Args, CmdArgs);
04348 
04349   // -fdollars-in-identifiers default varies depending on platform and
04350   // language; only pass if specified.
04351   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
04352                                options::OPT_fno_dollars_in_identifiers)) {
04353     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
04354       CmdArgs.push_back("-fdollars-in-identifiers");
04355     else
04356       CmdArgs.push_back("-fno-dollars-in-identifiers");
04357   }
04358 
04359   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
04360   // practical purposes.
04361   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
04362                                options::OPT_fno_unit_at_a_time)) {
04363     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
04364       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
04365   }
04366 
04367   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
04368                    options::OPT_fno_apple_pragma_pack, false))
04369     CmdArgs.push_back("-fapple-pragma-pack");
04370 
04371   // le32-specific flags: 
04372   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
04373   //                     by default.
04374   if (getToolChain().getArch() == llvm::Triple::le32) {
04375     CmdArgs.push_back("-fno-math-builtin");
04376   }
04377 
04378   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
04379   //
04380   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
04381 #if 0
04382   if (getToolChain().getTriple().isOSDarwin() &&
04383       (getToolChain().getArch() == llvm::Triple::arm ||
04384        getToolChain().getArch() == llvm::Triple::thumb)) {
04385     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
04386       CmdArgs.push_back("-fno-builtin-strcat");
04387     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
04388       CmdArgs.push_back("-fno-builtin-strcpy");
04389   }
04390 #endif
04391 
04392   // Enable rewrite includes if the user's asked for it or if we're generating
04393   // diagnostics.
04394   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
04395   // nice to enable this when doing a crashdump for modules as well.
04396   if (Args.hasFlag(options::OPT_frewrite_includes,
04397                    options::OPT_fno_rewrite_includes, false) ||
04398       (C.isForDiagnostics() && !HaveModules))
04399     CmdArgs.push_back("-frewrite-includes");
04400 
04401   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
04402   if (Arg *A = Args.getLastArg(options::OPT_traditional,
04403                                options::OPT_traditional_cpp)) {
04404     if (isa<PreprocessJobAction>(JA))
04405       CmdArgs.push_back("-traditional-cpp");
04406     else
04407       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
04408   }
04409 
04410   Args.AddLastArg(CmdArgs, options::OPT_dM);
04411   Args.AddLastArg(CmdArgs, options::OPT_dD);
04412   
04413   // Handle serialized diagnostics.
04414   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
04415     CmdArgs.push_back("-serialize-diagnostic-file");
04416     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
04417   }
04418 
04419   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
04420     CmdArgs.push_back("-fretain-comments-from-system-headers");
04421 
04422   // Forward -fcomment-block-commands to -cc1.
04423   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
04424   // Forward -fparse-all-comments to -cc1.
04425   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
04426 
04427   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
04428   // parser.
04429   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
04430   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
04431          ie = Args.filtered_end(); it != ie; ++it) {
04432     (*it)->claim();
04433 
04434     // We translate this by hand to the -cc1 argument, since nightly test uses
04435     // it and developers have been trained to spell it with -mllvm.
04436     if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns")
04437       CmdArgs.push_back("-disable-llvm-optzns");
04438     else
04439       (*it)->render(Args, CmdArgs);
04440   }
04441 
04442   if (Output.getType() == types::TY_Dependencies) {
04443     // Handled with other dependency code.
04444   } else if (Output.isFilename()) {
04445     CmdArgs.push_back("-o");
04446     CmdArgs.push_back(Output.getFilename());
04447   } else {
04448     assert(Output.isNothing() && "Invalid output.");
04449   }
04450 
04451   for (const auto &II : Inputs) {
04452     addDashXForInput(Args, II, CmdArgs);
04453 
04454     if (II.isFilename())
04455       CmdArgs.push_back(II.getFilename());
04456     else
04457       II.getInputArg().renderAsInput(Args, CmdArgs);
04458   }
04459 
04460   Args.AddAllArgs(CmdArgs, options::OPT_undef);
04461 
04462   const char *Exec = getToolChain().getDriver().getClangProgramPath();
04463 
04464   // Optionally embed the -cc1 level arguments into the debug info, for build
04465   // analysis.
04466   if (getToolChain().UseDwarfDebugFlags()) {
04467     ArgStringList OriginalArgs;
04468     for (const auto &Arg : Args)
04469       Arg->render(Args, OriginalArgs);
04470 
04471     SmallString<256> Flags;
04472     Flags += Exec;
04473     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
04474       SmallString<128> EscapedArg;
04475       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
04476       Flags += " ";
04477       Flags += EscapedArg;
04478     }
04479     CmdArgs.push_back("-dwarf-debug-flags");
04480     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
04481   }
04482 
04483   // Add the split debug info name to the command lines here so we
04484   // can propagate it to the backend.
04485   bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
04486     getToolChain().getTriple().isOSLinux() &&
04487     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA));
04488   const char *SplitDwarfOut;
04489   if (SplitDwarf) {
04490     CmdArgs.push_back("-split-dwarf-file");
04491     SplitDwarfOut = SplitDebugName(Args, Inputs);
04492     CmdArgs.push_back(SplitDwarfOut);
04493   }
04494 
04495   // Finally add the compile command to the compilation.
04496   if (Args.hasArg(options::OPT__SLASH_fallback) &&
04497       Output.getType() == types::TY_Object &&
04498       (InputType == types::TY_C || InputType == types::TY_CXX)) {
04499     auto CLCommand =
04500         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
04501     C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
04502                                                     std::move(CLCommand)));
04503   } else {
04504     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
04505   }
04506 
04507 
04508   // Handle the debug info splitting at object creation time if we're
04509   // creating an object.
04510   // TODO: Currently only works on linux with newer objcopy.
04511   if (SplitDwarf && !isa<CompileJobAction>(JA))
04512     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
04513 
04514   if (Arg *A = Args.getLastArg(options::OPT_pg))
04515     if (Args.hasArg(options::OPT_fomit_frame_pointer))
04516       D.Diag(diag::err_drv_argument_not_allowed_with)
04517         << "-fomit-frame-pointer" << A->getAsString(Args);
04518 
04519   // Claim some arguments which clang supports automatically.
04520 
04521   // -fpch-preprocess is used with gcc to add a special marker in the output to
04522   // include the PCH file. Clang's PTH solution is completely transparent, so we
04523   // do not need to deal with it at all.
04524   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
04525 
04526   // Claim some arguments which clang doesn't support, but we don't
04527   // care to warn the user about.
04528   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
04529   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
04530 
04531   // Disable warnings for clang -E -emit-llvm foo.c
04532   Args.ClaimAllArgs(options::OPT_emit_llvm);
04533 }
04534 
04535 /// Add options related to the Objective-C runtime/ABI.
04536 ///
04537 /// Returns true if the runtime is non-fragile.
04538 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
04539                                       ArgStringList &cmdArgs,
04540                                       RewriteKind rewriteKind) const {
04541   // Look for the controlling runtime option.
04542   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
04543                                     options::OPT_fgnu_runtime,
04544                                     options::OPT_fobjc_runtime_EQ);
04545 
04546   // Just forward -fobjc-runtime= to the frontend.  This supercedes
04547   // options about fragility.
04548   if (runtimeArg &&
04549       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
04550     ObjCRuntime runtime;
04551     StringRef value = runtimeArg->getValue();
04552     if (runtime.tryParse(value)) {
04553       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
04554         << value;
04555     }
04556 
04557     runtimeArg->render(args, cmdArgs);
04558     return runtime;
04559   }
04560 
04561   // Otherwise, we'll need the ABI "version".  Version numbers are
04562   // slightly confusing for historical reasons:
04563   //   1 - Traditional "fragile" ABI
04564   //   2 - Non-fragile ABI, version 1
04565   //   3 - Non-fragile ABI, version 2
04566   unsigned objcABIVersion = 1;
04567   // If -fobjc-abi-version= is present, use that to set the version.
04568   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
04569     StringRef value = abiArg->getValue();
04570     if (value == "1")
04571       objcABIVersion = 1;
04572     else if (value == "2")
04573       objcABIVersion = 2;
04574     else if (value == "3")
04575       objcABIVersion = 3;
04576     else
04577       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
04578         << value;
04579   } else {
04580     // Otherwise, determine if we are using the non-fragile ABI.
04581     bool nonFragileABIIsDefault = 
04582       (rewriteKind == RK_NonFragile || 
04583        (rewriteKind == RK_None &&
04584         getToolChain().IsObjCNonFragileABIDefault()));
04585     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
04586                      options::OPT_fno_objc_nonfragile_abi,
04587                      nonFragileABIIsDefault)) {
04588       // Determine the non-fragile ABI version to use.
04589 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
04590       unsigned nonFragileABIVersion = 1;
04591 #else
04592       unsigned nonFragileABIVersion = 2;
04593 #endif
04594 
04595       if (Arg *abiArg = args.getLastArg(
04596             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
04597         StringRef value = abiArg->getValue();
04598         if (value == "1")
04599           nonFragileABIVersion = 1;
04600         else if (value == "2")
04601           nonFragileABIVersion = 2;
04602         else
04603           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
04604             << value;
04605       }
04606 
04607       objcABIVersion = 1 + nonFragileABIVersion;
04608     } else {
04609       objcABIVersion = 1;
04610     }
04611   }
04612 
04613   // We don't actually care about the ABI version other than whether
04614   // it's non-fragile.
04615   bool isNonFragile = objcABIVersion != 1;
04616 
04617   // If we have no runtime argument, ask the toolchain for its default runtime.
04618   // However, the rewriter only really supports the Mac runtime, so assume that.
04619   ObjCRuntime runtime;
04620   if (!runtimeArg) {
04621     switch (rewriteKind) {
04622     case RK_None:
04623       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
04624       break;
04625     case RK_Fragile:
04626       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
04627       break;
04628     case RK_NonFragile:
04629       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
04630       break;
04631     }
04632 
04633   // -fnext-runtime
04634   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
04635     // On Darwin, make this use the default behavior for the toolchain.
04636     if (getToolChain().getTriple().isOSDarwin()) {
04637       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
04638 
04639     // Otherwise, build for a generic macosx port.
04640     } else {
04641       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
04642     }
04643 
04644   // -fgnu-runtime
04645   } else {
04646     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
04647     // Legacy behaviour is to target the gnustep runtime if we are i
04648     // non-fragile mode or the GCC runtime in fragile mode.
04649     if (isNonFragile)
04650       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
04651     else
04652       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
04653   }
04654 
04655   cmdArgs.push_back(args.MakeArgString(
04656                                  "-fobjc-runtime=" + runtime.getAsString()));
04657   return runtime;
04658 }
04659 
04660 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
04661   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
04662   I += HaveDash;
04663   return !HaveDash;
04664 }
04665 
04666 struct EHFlags {
04667   EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
04668   bool Synch;
04669   bool Asynch;
04670   bool NoExceptC;
04671 };
04672 
04673 /// /EH controls whether to run destructor cleanups when exceptions are
04674 /// thrown.  There are three modifiers:
04675 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
04676 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
04677 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
04678 /// - c: Assume that extern "C" functions are implicitly noexcept.  This
04679 ///      modifier is an optimization, so we ignore it for now.
04680 /// The default is /EHs-c-, meaning cleanups are disabled.
04681 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
04682   EHFlags EH;
04683   std::vector<std::string> EHArgs = Args.getAllArgValues(options::OPT__SLASH_EH);
04684   for (auto EHVal : EHArgs) {
04685     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
04686       switch (EHVal[I]) {
04687       case 'a': EH.Asynch = maybeConsumeDash(EHVal, I); continue;
04688       case 'c': EH.NoExceptC = maybeConsumeDash(EHVal, I); continue;
04689       case 's': EH.Synch = maybeConsumeDash(EHVal, I); continue;
04690       default: break;
04691       }
04692       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
04693       break;
04694     }
04695   }
04696   return EH;
04697 }
04698 
04699 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
04700   unsigned RTOptionID = options::OPT__SLASH_MT;
04701 
04702   if (Args.hasArg(options::OPT__SLASH_LDd))
04703     // The /LDd option implies /MTd. The dependent lib part can be overridden,
04704     // but defining _DEBUG is sticky.
04705     RTOptionID = options::OPT__SLASH_MTd;
04706 
04707   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
04708     RTOptionID = A->getOption().getID();
04709 
04710   switch(RTOptionID) {
04711     case options::OPT__SLASH_MD:
04712       if (Args.hasArg(options::OPT__SLASH_LDd))
04713         CmdArgs.push_back("-D_DEBUG");
04714       CmdArgs.push_back("-D_MT");
04715       CmdArgs.push_back("-D_DLL");
04716       CmdArgs.push_back("--dependent-lib=msvcrt");
04717       break;
04718     case options::OPT__SLASH_MDd:
04719       CmdArgs.push_back("-D_DEBUG");
04720       CmdArgs.push_back("-D_MT");
04721       CmdArgs.push_back("-D_DLL");
04722       CmdArgs.push_back("--dependent-lib=msvcrtd");
04723       break;
04724     case options::OPT__SLASH_MT:
04725       if (Args.hasArg(options::OPT__SLASH_LDd))
04726         CmdArgs.push_back("-D_DEBUG");
04727       CmdArgs.push_back("-D_MT");
04728       CmdArgs.push_back("--dependent-lib=libcmt");
04729       break;
04730     case options::OPT__SLASH_MTd:
04731       CmdArgs.push_back("-D_DEBUG");
04732       CmdArgs.push_back("-D_MT");
04733       CmdArgs.push_back("--dependent-lib=libcmtd");
04734       break;
04735     default:
04736       llvm_unreachable("Unexpected option ID.");
04737   }
04738 
04739   // This provides POSIX compatibility (maps 'open' to '_open'), which most
04740   // users want.  The /Za flag to cl.exe turns this off, but it's not
04741   // implemented in clang.
04742   CmdArgs.push_back("--dependent-lib=oldnames");
04743 
04744   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
04745   // would produce interleaved output, so ignore /showIncludes in such cases.
04746   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
04747     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
04748       A->render(Args, CmdArgs);
04749 
04750   // This controls whether or not we emit RTTI data for polymorphic types.
04751   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
04752                    /*default=*/false))
04753     CmdArgs.push_back("-fno-rtti-data");
04754 
04755   const Driver &D = getToolChain().getDriver();
04756   EHFlags EH = parseClangCLEHFlags(D, Args);
04757   // FIXME: Do something with NoExceptC.
04758   if (EH.Synch || EH.Asynch) {
04759     CmdArgs.push_back("-fexceptions");
04760     CmdArgs.push_back("-fcxx-exceptions");
04761   }
04762 
04763   // /EP should expand to -E -P.
04764   if (Args.hasArg(options::OPT__SLASH_EP)) {
04765     CmdArgs.push_back("-E");
04766     CmdArgs.push_back("-P");
04767   }
04768 
04769   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
04770   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
04771   if (MostGeneralArg && BestCaseArg)
04772     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
04773         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
04774 
04775   if (MostGeneralArg) {
04776     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
04777     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
04778     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
04779 
04780     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
04781     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
04782     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
04783       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
04784           << FirstConflict->getAsString(Args)
04785           << SecondConflict->getAsString(Args);
04786 
04787     if (SingleArg)
04788       CmdArgs.push_back("-fms-memptr-rep=single");
04789     else if (MultipleArg)
04790       CmdArgs.push_back("-fms-memptr-rep=multiple");
04791     else
04792       CmdArgs.push_back("-fms-memptr-rep=virtual");
04793   }
04794 
04795   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
04796     A->render(Args, CmdArgs);
04797 
04798   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
04799     CmdArgs.push_back("-fdiagnostics-format");
04800     if (Args.hasArg(options::OPT__SLASH_fallback))
04801       CmdArgs.push_back("msvc-fallback");
04802     else
04803       CmdArgs.push_back("msvc");
04804   }
04805 }
04806 
04807 visualstudio::Compile *Clang::getCLFallback() const {
04808   if (!CLFallback)
04809     CLFallback.reset(new visualstudio::Compile(getToolChain()));
04810   return CLFallback.get();
04811 }
04812 
04813 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
04814                            const InputInfo &Output,
04815                            const InputInfoList &Inputs,
04816                            const ArgList &Args,
04817                            const char *LinkingOutput) const {
04818   ArgStringList CmdArgs;
04819 
04820   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
04821   const InputInfo &Input = Inputs[0];
04822 
04823   // Don't warn about "clang -w -c foo.s"
04824   Args.ClaimAllArgs(options::OPT_w);
04825   // and "clang -emit-llvm -c foo.s"
04826   Args.ClaimAllArgs(options::OPT_emit_llvm);
04827 
04828   // Invoke ourselves in -cc1as mode.
04829   //
04830   // FIXME: Implement custom jobs for internal actions.
04831   CmdArgs.push_back("-cc1as");
04832 
04833   // Add the "effective" target triple.
04834   CmdArgs.push_back("-triple");
04835   std::string TripleStr = 
04836     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
04837   CmdArgs.push_back(Args.MakeArgString(TripleStr));
04838 
04839   // Set the output mode, we currently only expect to be used as a real
04840   // assembler.
04841   CmdArgs.push_back("-filetype");
04842   CmdArgs.push_back("obj");
04843 
04844   // Set the main file name, so that debug info works even with
04845   // -save-temps or preprocessed assembly.
04846   CmdArgs.push_back("-main-file-name");
04847   CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs));
04848 
04849   // Add the target cpu
04850   const llvm::Triple &Triple = getToolChain().getTriple();
04851   std::string CPU = getCPUName(Args, Triple);
04852   if (!CPU.empty()) {
04853     CmdArgs.push_back("-target-cpu");
04854     CmdArgs.push_back(Args.MakeArgString(CPU));
04855   }
04856 
04857   // Add the target features
04858   const Driver &D = getToolChain().getDriver();
04859   getTargetFeatures(D, Triple, Args, CmdArgs, true);
04860 
04861   // Ignore explicit -force_cpusubtype_ALL option.
04862   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
04863 
04864   // Determine the original source input.
04865   const Action *SourceAction = &JA;
04866   while (SourceAction->getKind() != Action::InputClass) {
04867     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
04868     SourceAction = SourceAction->getInputs()[0];
04869   }
04870 
04871   // Forward -g and handle debug info related flags, assuming we are dealing
04872   // with an actual assembly file.
04873   if (SourceAction->getType() == types::TY_Asm ||
04874       SourceAction->getType() == types::TY_PP_Asm) {
04875     Args.ClaimAllArgs(options::OPT_g_Group);
04876     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
04877       if (!A->getOption().matches(options::OPT_g0))
04878         CmdArgs.push_back("-g");
04879 
04880     if (Args.hasArg(options::OPT_gdwarf_2))
04881       CmdArgs.push_back("-gdwarf-2");
04882     if (Args.hasArg(options::OPT_gdwarf_3))
04883       CmdArgs.push_back("-gdwarf-3");
04884     if (Args.hasArg(options::OPT_gdwarf_4))
04885       CmdArgs.push_back("-gdwarf-4");
04886 
04887     // Add the -fdebug-compilation-dir flag if needed.
04888     addDebugCompDirArg(Args, CmdArgs);
04889 
04890     // Set the AT_producer to the clang version when using the integrated
04891     // assembler on assembly source files.
04892     CmdArgs.push_back("-dwarf-debug-producer");
04893     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
04894   }
04895 
04896   // Optionally embed the -cc1as level arguments into the debug info, for build
04897   // analysis.
04898   if (getToolChain().UseDwarfDebugFlags()) {
04899     ArgStringList OriginalArgs;
04900     for (const auto &Arg : Args)
04901       Arg->render(Args, OriginalArgs);
04902 
04903     SmallString<256> Flags;
04904     const char *Exec = getToolChain().getDriver().getClangProgramPath();
04905     Flags += Exec;
04906     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
04907       SmallString<128> EscapedArg;
04908       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
04909       Flags += " ";
04910       Flags += EscapedArg;
04911     }
04912     CmdArgs.push_back("-dwarf-debug-flags");
04913     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
04914   }
04915 
04916   // FIXME: Add -static support, once we have it.
04917 
04918   // Consume all the warning flags. Usually this would be handled more
04919   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
04920   // doesn't handle that so rather than warning about unused flags that are
04921   // actually used, we'll lie by omission instead.
04922   // FIXME: Stop lying and consume only the appropriate driver flags
04923   for (arg_iterator it = Args.filtered_begin(options::OPT_W_Group),
04924                     ie = Args.filtered_end();
04925        it != ie; ++it)
04926     (*it)->claim();
04927 
04928   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
04929                                     getToolChain().getDriver());
04930 
04931   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
04932 
04933   assert(Output.isFilename() && "Unexpected lipo output.");
04934   CmdArgs.push_back("-o");
04935   CmdArgs.push_back(Output.getFilename());
04936 
04937   assert(Input.isFilename() && "Invalid input.");
04938   CmdArgs.push_back(Input.getFilename());
04939 
04940   const char *Exec = getToolChain().getDriver().getClangProgramPath();
04941   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
04942 
04943   // Handle the debug info splitting at object creation time if we're
04944   // creating an object.
04945   // TODO: Currently only works on linux with newer objcopy.
04946   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
04947       getToolChain().getTriple().isOSLinux())
04948     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
04949                    SplitDebugName(Args, Inputs));
04950 }
04951 
04952 void GnuTool::anchor() {}
04953 
04954 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
04955                                const InputInfo &Output,
04956                                const InputInfoList &Inputs,
04957                                const ArgList &Args,
04958                                const char *LinkingOutput) const {
04959   const Driver &D = getToolChain().getDriver();
04960   ArgStringList CmdArgs;
04961 
04962   for (const auto &A : Args) {
04963     if (forwardToGCC(A->getOption())) {
04964       // Don't forward any -g arguments to assembly steps.
04965       if (isa<AssembleJobAction>(JA) &&
04966           A->getOption().matches(options::OPT_g_Group))
04967         continue;
04968 
04969       // Don't forward any -W arguments to assembly and link steps.
04970       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
04971           A->getOption().matches(options::OPT_W_Group))
04972         continue;
04973 
04974       // It is unfortunate that we have to claim here, as this means
04975       // we will basically never report anything interesting for
04976       // platforms using a generic gcc, even if we are just using gcc
04977       // to get to the assembler.
04978       A->claim();
04979       A->render(Args, CmdArgs);
04980     }
04981   }
04982 
04983   RenderExtraToolArgs(JA, CmdArgs);
04984 
04985   // If using a driver driver, force the arch.
04986   if (getToolChain().getTriple().isOSDarwin()) {
04987     CmdArgs.push_back("-arch");
04988     CmdArgs.push_back(
04989       Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
04990   }
04991 
04992   // Try to force gcc to match the tool chain we want, if we recognize
04993   // the arch.
04994   //
04995   // FIXME: The triple class should directly provide the information we want
04996   // here.
04997   llvm::Triple::ArchType Arch = getToolChain().getArch();
04998   if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
04999     CmdArgs.push_back("-m32");
05000   else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
05001            Arch == llvm::Triple::ppc64le)
05002     CmdArgs.push_back("-m64");
05003 
05004   if (Output.isFilename()) {
05005     CmdArgs.push_back("-o");
05006     CmdArgs.push_back(Output.getFilename());
05007   } else {
05008     assert(Output.isNothing() && "Unexpected output");
05009     CmdArgs.push_back("-fsyntax-only");
05010   }
05011 
05012   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
05013                        options::OPT_Xassembler);
05014 
05015   // Only pass -x if gcc will understand it; otherwise hope gcc
05016   // understands the suffix correctly. The main use case this would go
05017   // wrong in is for linker inputs if they happened to have an odd
05018   // suffix; really the only way to get this to happen is a command
05019   // like '-x foobar a.c' which will treat a.c like a linker input.
05020   //
05021   // FIXME: For the linker case specifically, can we safely convert
05022   // inputs into '-Wl,' options?
05023   for (const auto &II : Inputs) {
05024     // Don't try to pass LLVM or AST inputs to a generic gcc.
05025     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
05026         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
05027       D.Diag(diag::err_drv_no_linker_llvm_support)
05028         << getToolChain().getTripleString();
05029     else if (II.getType() == types::TY_AST)
05030       D.Diag(diag::err_drv_no_ast_support)
05031         << getToolChain().getTripleString();
05032     else if (II.getType() == types::TY_ModuleFile)
05033       D.Diag(diag::err_drv_no_module_support)
05034         << getToolChain().getTripleString();
05035 
05036     if (types::canTypeBeUserSpecified(II.getType())) {
05037       CmdArgs.push_back("-x");
05038       CmdArgs.push_back(types::getTypeName(II.getType()));
05039     }
05040 
05041     if (II.isFilename())
05042       CmdArgs.push_back(II.getFilename());
05043     else {
05044       const Arg &A = II.getInputArg();
05045 
05046       // Reverse translate some rewritten options.
05047       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
05048         CmdArgs.push_back("-lstdc++");
05049         continue;
05050       }
05051 
05052       // Don't render as input, we need gcc to do the translations.
05053       A.render(Args, CmdArgs);
05054     }
05055   }
05056 
05057   const std::string customGCCName = D.getCCCGenericGCCName();
05058   const char *GCCName;
05059   if (!customGCCName.empty())
05060     GCCName = customGCCName.c_str();
05061   else if (D.CCCIsCXX()) {
05062     GCCName = "g++";
05063   } else
05064     GCCName = "gcc";
05065 
05066   const char *Exec =
05067     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
05068   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
05069 }
05070 
05071 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
05072                                           ArgStringList &CmdArgs) const {
05073   CmdArgs.push_back("-E");
05074 }
05075 
05076 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
05077                                        ArgStringList &CmdArgs) const {
05078   const Driver &D = getToolChain().getDriver();
05079 
05080   // If -flto, etc. are present then make sure not to force assembly output.
05081   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
05082       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
05083     CmdArgs.push_back("-c");
05084   else {
05085     if (JA.getType() != types::TY_PP_Asm)
05086       D.Diag(diag::err_drv_invalid_gcc_output_type)
05087         << getTypeName(JA.getType());
05088 
05089     CmdArgs.push_back("-S");
05090   }
05091 }
05092 
05093 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
05094                                     ArgStringList &CmdArgs) const {
05095   // The types are (hopefully) good enough.
05096 }
05097 
05098 // Hexagon tools start.
05099 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
05100                                         ArgStringList &CmdArgs) const {
05101 
05102 }
05103 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
05104                                const InputInfo &Output,
05105                                const InputInfoList &Inputs,
05106                                const ArgList &Args,
05107                                const char *LinkingOutput) const {
05108 
05109   const Driver &D = getToolChain().getDriver();
05110   ArgStringList CmdArgs;
05111 
05112   std::string MarchString = "-march=";
05113   MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
05114   CmdArgs.push_back(Args.MakeArgString(MarchString));
05115 
05116   RenderExtraToolArgs(JA, CmdArgs);
05117 
05118   if (Output.isFilename()) {
05119     CmdArgs.push_back("-o");
05120     CmdArgs.push_back(Output.getFilename());
05121   } else {
05122     assert(Output.isNothing() && "Unexpected output");
05123     CmdArgs.push_back("-fsyntax-only");
05124   }
05125 
05126   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
05127   if (!SmallDataThreshold.empty())
05128     CmdArgs.push_back(
05129       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
05130 
05131   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
05132                        options::OPT_Xassembler);
05133 
05134   // Only pass -x if gcc will understand it; otherwise hope gcc
05135   // understands the suffix correctly. The main use case this would go
05136   // wrong in is for linker inputs if they happened to have an odd
05137   // suffix; really the only way to get this to happen is a command
05138   // like '-x foobar a.c' which will treat a.c like a linker input.
05139   //
05140   // FIXME: For the linker case specifically, can we safely convert
05141   // inputs into '-Wl,' options?
05142   for (const auto &II : Inputs) {
05143     // Don't try to pass LLVM or AST inputs to a generic gcc.
05144     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
05145         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
05146       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
05147         << getToolChain().getTripleString();
05148     else if (II.getType() == types::TY_AST)
05149       D.Diag(clang::diag::err_drv_no_ast_support)
05150         << getToolChain().getTripleString();
05151     else if (II.getType() == types::TY_ModuleFile)
05152       D.Diag(diag::err_drv_no_module_support)
05153       << getToolChain().getTripleString();
05154 
05155     if (II.isFilename())
05156       CmdArgs.push_back(II.getFilename());
05157     else
05158       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
05159       II.getInputArg().render(Args, CmdArgs);
05160   }
05161 
05162   const char *GCCName = "hexagon-as";
05163   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
05164   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
05165 }
05166 
05167 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
05168                                     ArgStringList &CmdArgs) const {
05169   // The types are (hopefully) good enough.
05170 }
05171 
05172 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
05173                                const InputInfo &Output,
05174                                const InputInfoList &Inputs,
05175                                const ArgList &Args,
05176                                const char *LinkingOutput) const {
05177 
05178   const toolchains::Hexagon_TC& ToolChain =
05179     static_cast<const toolchains::Hexagon_TC&>(getToolChain());
05180   const Driver &D = ToolChain.getDriver();
05181 
05182   ArgStringList CmdArgs;
05183 
05184   //----------------------------------------------------------------------------
05185   //
05186   //----------------------------------------------------------------------------
05187   bool hasStaticArg = Args.hasArg(options::OPT_static);
05188   bool buildingLib = Args.hasArg(options::OPT_shared);
05189   bool buildPIE = Args.hasArg(options::OPT_pie);
05190   bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
05191   bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
05192   bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
05193   bool useShared = buildingLib && !hasStaticArg;
05194 
05195   //----------------------------------------------------------------------------
05196   // Silence warnings for various options
05197   //----------------------------------------------------------------------------
05198 
05199   Args.ClaimAllArgs(options::OPT_g_Group);
05200   Args.ClaimAllArgs(options::OPT_emit_llvm);
05201   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
05202                                      // handled somewhere else.
05203   Args.ClaimAllArgs(options::OPT_static_libgcc);
05204 
05205   //----------------------------------------------------------------------------
05206   //
05207   //----------------------------------------------------------------------------
05208   for (const auto &Opt : ToolChain.ExtraOpts)
05209     CmdArgs.push_back(Opt.c_str());
05210 
05211   std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
05212   CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
05213 
05214   if (buildingLib) {
05215     CmdArgs.push_back("-shared");
05216     CmdArgs.push_back("-call_shared"); // should be the default, but doing as
05217                                        // hexagon-gcc does
05218   }
05219 
05220   if (hasStaticArg)
05221     CmdArgs.push_back("-static");
05222 
05223   if (buildPIE && !buildingLib)
05224     CmdArgs.push_back("-pie");
05225 
05226   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
05227   if (!SmallDataThreshold.empty()) {
05228     CmdArgs.push_back(
05229       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
05230   }
05231 
05232   //----------------------------------------------------------------------------
05233   //
05234   //----------------------------------------------------------------------------
05235   CmdArgs.push_back("-o");
05236   CmdArgs.push_back(Output.getFilename());
05237 
05238   const std::string MarchSuffix = "/" + MarchString;
05239   const std::string G0Suffix = "/G0";
05240   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
05241   const std::string RootDir =
05242       toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
05243   const std::string StartFilesDir = RootDir
05244                                     + "hexagon/lib"
05245                                     + (buildingLib
05246                                        ? MarchG0Suffix : MarchSuffix);
05247 
05248   //----------------------------------------------------------------------------
05249   // moslib
05250   //----------------------------------------------------------------------------
05251   std::vector<std::string> oslibs;
05252   bool hasStandalone= false;
05253 
05254   for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ),
05255          ie = Args.filtered_end(); it != ie; ++it) {
05256     (*it)->claim();
05257     oslibs.push_back((*it)->getValue());
05258     hasStandalone = hasStandalone || (oslibs.back() == "standalone");
05259   }
05260   if (oslibs.empty()) {
05261     oslibs.push_back("standalone");
05262     hasStandalone = true;
05263   }
05264 
05265   //----------------------------------------------------------------------------
05266   // Start Files
05267   //----------------------------------------------------------------------------
05268   if (incStdLib && incStartFiles) {
05269 
05270     if (!buildingLib) {
05271       if (hasStandalone) {
05272         CmdArgs.push_back(
05273           Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
05274       }
05275       CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
05276     }
05277     std::string initObj = useShared ? "/initS.o" : "/init.o";
05278     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
05279   }
05280 
05281   //----------------------------------------------------------------------------
05282   // Library Search Paths
05283   //----------------------------------------------------------------------------
05284   const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
05285   for (const auto &LibPath : LibPaths)
05286     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
05287 
05288   //----------------------------------------------------------------------------
05289   //
05290   //----------------------------------------------------------------------------
05291   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
05292   Args.AddAllArgs(CmdArgs, options::OPT_e);
05293   Args.AddAllArgs(CmdArgs, options::OPT_s);
05294   Args.AddAllArgs(CmdArgs, options::OPT_t);
05295   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
05296 
05297   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
05298 
05299   //----------------------------------------------------------------------------
05300   // Libraries
05301   //----------------------------------------------------------------------------
05302   if (incStdLib && incDefLibs) {
05303     if (D.CCCIsCXX()) {
05304       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
05305       CmdArgs.push_back("-lm");
05306     }
05307 
05308     CmdArgs.push_back("--start-group");
05309 
05310     if (!buildingLib) {
05311       for(std::vector<std::string>::iterator i = oslibs.begin(),
05312             e = oslibs.end(); i != e; ++i)
05313         CmdArgs.push_back(Args.MakeArgString("-l" + *i));
05314       CmdArgs.push_back("-lc");
05315     }
05316     CmdArgs.push_back("-lgcc");
05317 
05318     CmdArgs.push_back("--end-group");
05319   }
05320 
05321   //----------------------------------------------------------------------------
05322   // End files
05323   //----------------------------------------------------------------------------
05324   if (incStdLib && incStartFiles) {
05325     std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
05326     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
05327   }
05328 
05329   std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
05330   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
05331                                           CmdArgs));
05332 }
05333 // Hexagon tools end.
05334 
05335 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
05336 const char *arm::getARMCPUForMArch(const ArgList &Args,
05337                                    const llvm::Triple &Triple) {
05338   StringRef MArch;
05339   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
05340     // Otherwise, if we have -march= choose the base CPU for that arch.
05341     MArch = A->getValue();
05342   } else {
05343     // Otherwise, use the Arch from the triple.
05344     MArch = Triple.getArchName();
05345   }
05346 
05347   // Handle -march=native.
05348   if (MArch == "native") {
05349     std::string CPU = llvm::sys::getHostCPUName();
05350     if (CPU != "generic") {
05351       // Translate the native cpu into the architecture. The switch below will
05352       // then chose the minimum cpu for that arch.
05353       MArch = std::string("arm") + arm::getLLVMArchSuffixForARM(CPU);
05354     }
05355   }
05356 
05357   return Triple.getARMCPUForArch(MArch);
05358 }
05359 
05360 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
05361 StringRef arm::getARMTargetCPU(const ArgList &Args,
05362                                const llvm::Triple &Triple) {
05363   // FIXME: Warn on inconsistent use of -mcpu and -march.
05364   // If we have -mcpu=, use that.
05365   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
05366     StringRef MCPU = A->getValue();
05367     // Handle -mcpu=native.
05368     if (MCPU == "native")
05369       return llvm::sys::getHostCPUName();
05370     else
05371       return MCPU;
05372   }
05373 
05374   return getARMCPUForMArch(Args, Triple);
05375 }
05376 
05377 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
05378 /// CPU.
05379 //
05380 // FIXME: This is redundant with -mcpu, why does LLVM use this.
05381 // FIXME: tblgen this, or kill it!
05382 const char *arm::getLLVMArchSuffixForARM(StringRef CPU) {
05383   return llvm::StringSwitch<const char *>(CPU)
05384     .Case("strongarm", "v4")
05385     .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
05386     .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
05387     .Cases("arm920", "arm920t", "arm922t", "v4t")
05388     .Cases("arm940t", "ep9312","v4t")
05389     .Cases("arm10tdmi",  "arm1020t", "v5")
05390     .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
05391     .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
05392     .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
05393     .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
05394     .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
05395     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
05396     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
05397     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "v7")
05398     .Cases("cortex-r4", "cortex-r5", "v7r")
05399     .Case("cortex-m0", "v6m")
05400     .Case("cortex-m3", "v7m")
05401     .Cases("cortex-m4", "cortex-m7", "v7em")
05402     .Case("swift", "v7s")
05403     .Case("cyclone", "v8")
05404     .Cases("cortex-a53", "cortex-a57", "v8")
05405     .Default("");
05406 }
05407 
05408 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
05409   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
05410   return A && (A->getValue() == StringRef(Value));
05411 }
05412 
05413 bool mips::isUCLibc(const ArgList &Args) {
05414   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
05415   return A && A->getOption().matches(options::OPT_muclibc);
05416 }
05417 
05418 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
05419   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
05420     return llvm::StringSwitch<bool>(NaNArg->getValue())
05421                .Case("2008", true)
05422                .Case("legacy", false)
05423                .Default(false);
05424 
05425   // NaN2008 is the default for MIPS32r6/MIPS64r6.
05426   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
05427              .Cases("mips32r6", "mips64r6", true)
05428              .Default(false);
05429 
05430   return false;
05431 }
05432 
05433 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
05434                          StringRef ABIName) {
05435   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
05436       Triple.getVendor() != llvm::Triple::MipsTechnologies)
05437     return false;
05438 
05439   if (ABIName != "32")
05440     return false;
05441 
05442   return llvm::StringSwitch<bool>(CPUName)
05443              .Cases("mips2", "mips3", "mips4", "mips5", true)
05444              .Cases("mips32", "mips32r2", true)
05445              .Cases("mips64", "mips64r2", true)
05446              .Default(false);
05447 }
05448 
05449 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
05450   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
05451   // archs which Darwin doesn't use.
05452 
05453   // The matching this routine does is fairly pointless, since it is neither the
05454   // complete architecture list, nor a reasonable subset. The problem is that
05455   // historically the driver driver accepts this and also ties its -march=
05456   // handling to the architecture name, so we need to be careful before removing
05457   // support for it.
05458 
05459   // This code must be kept in sync with Clang's Darwin specific argument
05460   // translation.
05461 
05462   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
05463     .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
05464     .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
05465     .Case("ppc64", llvm::Triple::ppc64)
05466     .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
05467     .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
05468            llvm::Triple::x86)
05469     .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
05470     // This is derived from the driver driver.
05471     .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
05472     .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
05473     .Cases("armv7s", "xscale", llvm::Triple::arm)
05474     .Case("arm64", llvm::Triple::aarch64)
05475     .Case("r600", llvm::Triple::r600)
05476     .Case("nvptx", llvm::Triple::nvptx)
05477     .Case("nvptx64", llvm::Triple::nvptx64)
05478     .Case("amdil", llvm::Triple::amdil)
05479     .Case("spir", llvm::Triple::spir)
05480     .Default(llvm::Triple::UnknownArch);
05481 }
05482 
05483 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
05484   llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
05485   T.setArch(Arch);
05486 
05487   if (Str == "x86_64h")
05488     T.setArchName(Str);
05489   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
05490     T.setOS(llvm::Triple::UnknownOS);
05491     T.setObjectFormat(llvm::Triple::MachO);
05492   }
05493 }
05494 
05495 const char *Clang::getBaseInputName(const ArgList &Args,
05496                                     const InputInfoList &Inputs) {
05497   return Args.MakeArgString(
05498     llvm::sys::path::filename(Inputs[0].getBaseInput()));
05499 }
05500 
05501 const char *Clang::getBaseInputStem(const ArgList &Args,
05502                                     const InputInfoList &Inputs) {
05503   const char *Str = getBaseInputName(Args, Inputs);
05504 
05505   if (const char *End = strrchr(Str, '.'))
05506     return Args.MakeArgString(std::string(Str, End));
05507 
05508   return Str;
05509 }
05510 
05511 const char *Clang::getDependencyFileName(const ArgList &Args,
05512                                          const InputInfoList &Inputs) {
05513   // FIXME: Think about this more.
05514   std::string Res;
05515 
05516   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
05517     std::string Str(OutputOpt->getValue());
05518     Res = Str.substr(0, Str.rfind('.'));
05519   } else {
05520     Res = getBaseInputStem(Args, Inputs);
05521   }
05522   return Args.MakeArgString(Res + ".d");
05523 }
05524 
05525 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
05526                                     const InputInfo &Output,
05527                                     const InputInfoList &Inputs,
05528                                     const ArgList &Args,
05529                                     const char *LinkingOutput) const {
05530   ArgStringList CmdArgs;
05531 
05532   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
05533   const InputInfo &Input = Inputs[0];
05534 
05535   // Determine the original source input.
05536   const Action *SourceAction = &JA;
05537   while (SourceAction->getKind() != Action::InputClass) {
05538     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
05539     SourceAction = SourceAction->getInputs()[0];
05540   }
05541 
05542   // If -fno_integrated_as is used add -Q to the darwin assember driver to make
05543   // sure it runs its system assembler not clang's integrated assembler.
05544   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
05545   // FIXME: at run-time detect assembler capabilities or rely on version
05546   // information forwarded by -target-assembler-version (future)
05547   if (Args.hasArg(options::OPT_fno_integrated_as)) {
05548     const llvm::Triple &T(getToolChain().getTriple());
05549     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
05550       CmdArgs.push_back("-Q");
05551   }
05552 
05553   // Forward -g, assuming we are dealing with an actual assembly file.
05554   if (SourceAction->getType() == types::TY_Asm ||
05555       SourceAction->getType() == types::TY_PP_Asm) {
05556     if (Args.hasArg(options::OPT_gstabs))
05557       CmdArgs.push_back("--gstabs");
05558     else if (Args.hasArg(options::OPT_g_Group))
05559       CmdArgs.push_back("-g");
05560   }
05561 
05562   // Derived from asm spec.
05563   AddMachOArch(Args, CmdArgs);
05564 
05565   // Use -force_cpusubtype_ALL on x86 by default.
05566   if (getToolChain().getArch() == llvm::Triple::x86 ||
05567       getToolChain().getArch() == llvm::Triple::x86_64 ||
05568       Args.hasArg(options::OPT_force__cpusubtype__ALL))
05569     CmdArgs.push_back("-force_cpusubtype_ALL");
05570 
05571   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
05572       (((Args.hasArg(options::OPT_mkernel) ||
05573          Args.hasArg(options::OPT_fapple_kext)) &&
05574         getMachOToolChain().isKernelStatic()) ||
05575        Args.hasArg(options::OPT_static)))
05576     CmdArgs.push_back("-static");
05577 
05578   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
05579                        options::OPT_Xassembler);
05580 
05581   assert(Output.isFilename() && "Unexpected lipo output.");
05582   CmdArgs.push_back("-o");
05583   CmdArgs.push_back(Output.getFilename());
05584 
05585   assert(Input.isFilename() && "Invalid input.");
05586   CmdArgs.push_back(Input.getFilename());
05587 
05588   // asm_final spec is empty.
05589 
05590   const char *Exec =
05591     Args.MakeArgString(getToolChain().GetProgramPath("as"));
05592   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
05593 }
05594 
05595 void darwin::MachOTool::anchor() {}
05596 
05597 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
05598                                      ArgStringList &CmdArgs) const {
05599   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
05600 
05601   // Derived from darwin_arch spec.
05602   CmdArgs.push_back("-arch");
05603   CmdArgs.push_back(Args.MakeArgString(ArchName));
05604 
05605   // FIXME: Is this needed anymore?
05606   if (ArchName == "arm")
05607     CmdArgs.push_back("-force_cpusubtype_ALL");
05608 }
05609 
05610 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
05611   // We only need to generate a temp path for LTO if we aren't compiling object
05612   // files. When compiling source files, we run 'dsymutil' after linking. We
05613   // don't run 'dsymutil' when compiling object files.
05614   for (const auto &Input : Inputs)
05615     if (Input.getType() != types::TY_Object)
05616       return true;
05617 
05618   return false;
05619 }
05620 
05621 void darwin::Link::AddLinkArgs(Compilation &C,
05622                                const ArgList &Args,
05623                                ArgStringList &CmdArgs,
05624                                const InputInfoList &Inputs) const {
05625   const Driver &D = getToolChain().getDriver();
05626   const toolchains::MachO &MachOTC = getMachOToolChain();
05627 
05628   unsigned Version[3] = { 0, 0, 0 };
05629   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
05630     bool HadExtra;
05631     if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
05632                                    Version[1], Version[2], HadExtra) ||
05633         HadExtra)
05634       D.Diag(diag::err_drv_invalid_version_number)
05635         << A->getAsString(Args);
05636   }
05637 
05638   // Newer linkers support -demangle. Pass it if supported and not disabled by
05639   // the user.
05640   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
05641     CmdArgs.push_back("-demangle");
05642 
05643   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
05644     CmdArgs.push_back("-export_dynamic");
05645 
05646   // If we are using LTO, then automatically create a temporary file path for
05647   // the linker to use, so that it's lifetime will extend past a possible
05648   // dsymutil step.
05649   if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
05650     const char *TmpPath = C.getArgs().MakeArgString(
05651       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
05652     C.addTempFile(TmpPath);
05653     CmdArgs.push_back("-object_path_lto");
05654     CmdArgs.push_back(TmpPath);
05655   }
05656 
05657   // Derived from the "link" spec.
05658   Args.AddAllArgs(CmdArgs, options::OPT_static);
05659   if (!Args.hasArg(options::OPT_static))
05660     CmdArgs.push_back("-dynamic");
05661   if (Args.hasArg(options::OPT_fgnu_runtime)) {
05662     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
05663     // here. How do we wish to handle such things?
05664   }
05665 
05666   if (!Args.hasArg(options::OPT_dynamiclib)) {
05667     AddMachOArch(Args, CmdArgs);
05668     // FIXME: Why do this only on this path?
05669     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
05670 
05671     Args.AddLastArg(CmdArgs, options::OPT_bundle);
05672     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
05673     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
05674 
05675     Arg *A;
05676     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
05677         (A = Args.getLastArg(options::OPT_current__version)) ||
05678         (A = Args.getLastArg(options::OPT_install__name)))
05679       D.Diag(diag::err_drv_argument_only_allowed_with)
05680         << A->getAsString(Args) << "-dynamiclib";
05681 
05682     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
05683     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
05684     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
05685   } else {
05686     CmdArgs.push_back("-dylib");
05687 
05688     Arg *A;
05689     if ((A = Args.getLastArg(options::OPT_bundle)) ||
05690         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
05691         (A = Args.getLastArg(options::OPT_client__name)) ||
05692         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
05693         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
05694         (A = Args.getLastArg(options::OPT_private__bundle)))
05695       D.Diag(diag::err_drv_argument_not_allowed_with)
05696         << A->getAsString(Args) << "-dynamiclib";
05697 
05698     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
05699                               "-dylib_compatibility_version");
05700     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
05701                               "-dylib_current_version");
05702 
05703     AddMachOArch(Args, CmdArgs);
05704 
05705     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
05706                               "-dylib_install_name");
05707   }
05708 
05709   Args.AddLastArg(CmdArgs, options::OPT_all__load);
05710   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
05711   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
05712   if (MachOTC.isTargetIOSBased())
05713     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
05714   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
05715   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
05716   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
05717   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
05718   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
05719   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
05720   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
05721   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
05722   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
05723   Args.AddAllArgs(CmdArgs, options::OPT_init);
05724 
05725   // Add the deployment target.
05726   MachOTC.addMinVersionArgs(Args, CmdArgs);
05727 
05728   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
05729   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
05730   Args.AddLastArg(CmdArgs, options::OPT_single__module);
05731   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
05732   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
05733 
05734   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
05735                                      options::OPT_fno_pie,
05736                                      options::OPT_fno_PIE)) {
05737     if (A->getOption().matches(options::OPT_fpie) ||
05738         A->getOption().matches(options::OPT_fPIE))
05739       CmdArgs.push_back("-pie");
05740     else
05741       CmdArgs.push_back("-no_pie");
05742   }
05743 
05744   Args.AddLastArg(CmdArgs, options::OPT_prebind);
05745   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
05746   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
05747   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
05748   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
05749   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
05750   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
05751   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
05752   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
05753   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
05754   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
05755   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
05756   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
05757   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
05758   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
05759   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
05760 
05761   // Give --sysroot= preference, over the Apple specific behavior to also use
05762   // --isysroot as the syslibroot.
05763   StringRef sysroot = C.getSysRoot();
05764   if (sysroot != "") {
05765     CmdArgs.push_back("-syslibroot");
05766     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
05767   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
05768     CmdArgs.push_back("-syslibroot");
05769     CmdArgs.push_back(A->getValue());
05770   }
05771 
05772   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
05773   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
05774   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
05775   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
05776   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
05777   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
05778   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
05779   Args.AddAllArgs(CmdArgs, options::OPT_y);
05780   Args.AddLastArg(CmdArgs, options::OPT_w);
05781   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
05782   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
05783   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
05784   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
05785   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
05786   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
05787   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
05788   Args.AddLastArg(CmdArgs, options::OPT_whyload);
05789   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
05790   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
05791   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
05792   Args.AddLastArg(CmdArgs, options::OPT_Mach);
05793 }
05794 
05795 enum LibOpenMP {
05796   LibUnknown,
05797   LibGOMP,
05798   LibIOMP5
05799 };
05800 
05801 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
05802                                 const InputInfo &Output,
05803                                 const InputInfoList &Inputs,
05804                                 const ArgList &Args,
05805                                 const char *LinkingOutput) const {
05806   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
05807 
05808   // If the number of arguments surpasses the system limits, we will encode the
05809   // input files in a separate file, shortening the command line. To this end,
05810   // build a list of input file names that can be passed via a file with the
05811   // -filelist linker option.
05812   llvm::opt::ArgStringList InputFileList;
05813 
05814   // The logic here is derived from gcc's behavior; most of which
05815   // comes from specs (starting with link_command). Consult gcc for
05816   // more information.
05817   ArgStringList CmdArgs;
05818 
05819   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
05820   if (Args.hasArg(options::OPT_ccc_arcmt_check,
05821                   options::OPT_ccc_arcmt_migrate)) {
05822     for (const auto &Arg : Args)
05823       Arg->claim();
05824     const char *Exec =
05825       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
05826     CmdArgs.push_back(Output.getFilename());
05827     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
05828     return;
05829   }
05830 
05831   // I'm not sure why this particular decomposition exists in gcc, but
05832   // we follow suite for ease of comparison.
05833   AddLinkArgs(C, Args, CmdArgs, Inputs);
05834 
05835   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
05836   Args.AddAllArgs(CmdArgs, options::OPT_s);
05837   Args.AddAllArgs(CmdArgs, options::OPT_t);
05838   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
05839   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
05840   Args.AddLastArg(CmdArgs, options::OPT_e);
05841   Args.AddAllArgs(CmdArgs, options::OPT_r);
05842 
05843   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
05844   // members of static archive libraries which implement Objective-C classes or
05845   // categories.
05846   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
05847     CmdArgs.push_back("-ObjC");
05848 
05849   CmdArgs.push_back("-o");
05850   CmdArgs.push_back(Output.getFilename());
05851 
05852   if (!Args.hasArg(options::OPT_nostdlib) &&
05853       !Args.hasArg(options::OPT_nostartfiles))
05854     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
05855 
05856   Args.AddAllArgs(CmdArgs, options::OPT_L);
05857 
05858   LibOpenMP UsedOpenMPLib = LibUnknown;
05859   if (Args.hasArg(options::OPT_fopenmp)) {
05860     UsedOpenMPLib = LibGOMP;
05861   } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
05862     UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
05863         .Case("libgomp",  LibGOMP)
05864         .Case("libiomp5", LibIOMP5)
05865         .Default(LibUnknown);
05866     if (UsedOpenMPLib == LibUnknown)
05867       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
05868         << A->getOption().getName() << A->getValue();
05869   }
05870   switch (UsedOpenMPLib) {
05871   case LibGOMP:
05872     CmdArgs.push_back("-lgomp");
05873     break;
05874   case LibIOMP5:
05875     CmdArgs.push_back("-liomp5");
05876     break;
05877   case LibUnknown:
05878     break;
05879   }
05880 
05881   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
05882   // Build the input file for -filelist (list of linker input files) in case we
05883   // need it later
05884   for (const auto &II : Inputs) {
05885     if (!II.isFilename()) {
05886       // This is a linker input argument.
05887       // We cannot mix input arguments and file names in a -filelist input, thus
05888       // we prematurely stop our list (remaining files shall be passed as
05889       // arguments).
05890       if (InputFileList.size() > 0)
05891         break;
05892 
05893       continue;
05894     }
05895 
05896     InputFileList.push_back(II.getFilename());
05897   }
05898 
05899   if (isObjCRuntimeLinked(Args) &&
05900       !Args.hasArg(options::OPT_nostdlib) &&
05901       !Args.hasArg(options::OPT_nodefaultlibs)) {
05902     // We use arclite library for both ARC and subscripting support.
05903     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
05904 
05905     CmdArgs.push_back("-framework");
05906     CmdArgs.push_back("Foundation");
05907     // Link libobj.
05908     CmdArgs.push_back("-lobjc");
05909   }
05910 
05911   if (LinkingOutput) {
05912     CmdArgs.push_back("-arch_multiple");
05913     CmdArgs.push_back("-final_output");
05914     CmdArgs.push_back(LinkingOutput);
05915   }
05916 
05917   if (Args.hasArg(options::OPT_fnested_functions))
05918     CmdArgs.push_back("-allow_stack_execute");
05919 
05920   if (!Args.hasArg(options::OPT_nostdlib) &&
05921       !Args.hasArg(options::OPT_nodefaultlibs)) {
05922     if (getToolChain().getDriver().CCCIsCXX())
05923       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
05924 
05925     // link_ssp spec is empty.
05926 
05927     // Let the tool chain choose which runtime library to link.
05928     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
05929   }
05930 
05931   if (!Args.hasArg(options::OPT_nostdlib) &&
05932       !Args.hasArg(options::OPT_nostartfiles)) {
05933     // endfile_spec is empty.
05934   }
05935 
05936   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
05937   Args.AddAllArgs(CmdArgs, options::OPT_F);
05938 
05939   const char *Exec =
05940     Args.MakeArgString(getToolChain().GetLinkerPath());
05941   std::unique_ptr<Command> Cmd =
05942     llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
05943   Cmd->setInputFileList(std::move(InputFileList));
05944   C.addCommand(std::move(Cmd));
05945 }
05946 
05947 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
05948                                 const InputInfo &Output,
05949                                 const InputInfoList &Inputs,
05950                                 const ArgList &Args,
05951                                 const char *LinkingOutput) const {
05952   ArgStringList CmdArgs;
05953 
05954   CmdArgs.push_back("-create");
05955   assert(Output.isFilename() && "Unexpected lipo output.");
05956 
05957   CmdArgs.push_back("-output");
05958   CmdArgs.push_back(Output.getFilename());
05959 
05960   for (const auto &II : Inputs) {
05961     assert(II.isFilename() && "Unexpected lipo input.");
05962     CmdArgs.push_back(II.getFilename());
05963   }
05964 
05965   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
05966   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
05967 }
05968 
05969 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
05970                                     const InputInfo &Output,
05971                                     const InputInfoList &Inputs,
05972                                     const ArgList &Args,
05973                                     const char *LinkingOutput) const {
05974   ArgStringList CmdArgs;
05975 
05976   CmdArgs.push_back("-o");
05977   CmdArgs.push_back(Output.getFilename());
05978 
05979   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
05980   const InputInfo &Input = Inputs[0];
05981   assert(Input.isFilename() && "Unexpected dsymutil input.");
05982   CmdArgs.push_back(Input.getFilename());
05983 
05984   const char *Exec =
05985     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
05986   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
05987 }
05988 
05989 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
05990                                        const InputInfo &Output,
05991                                        const InputInfoList &Inputs,
05992                                        const ArgList &Args,
05993                                        const char *LinkingOutput) const {
05994   ArgStringList CmdArgs;
05995   CmdArgs.push_back("--verify");
05996   CmdArgs.push_back("--debug-info");
05997   CmdArgs.push_back("--eh-frame");
05998   CmdArgs.push_back("--quiet");
05999 
06000   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
06001   const InputInfo &Input = Inputs[0];
06002   assert(Input.isFilename() && "Unexpected verify input");
06003 
06004   // Grabbing the output of the earlier dsymutil run.
06005   CmdArgs.push_back(Input.getFilename());
06006 
06007   const char *Exec =
06008     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
06009   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06010 }
06011 
06012 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
06013                                       const InputInfo &Output,
06014                                       const InputInfoList &Inputs,
06015                                       const ArgList &Args,
06016                                       const char *LinkingOutput) const {
06017   ArgStringList CmdArgs;
06018 
06019   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
06020                        options::OPT_Xassembler);
06021 
06022   CmdArgs.push_back("-o");
06023   CmdArgs.push_back(Output.getFilename());
06024 
06025   for (const auto &II : Inputs)
06026     CmdArgs.push_back(II.getFilename());
06027 
06028   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
06029   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06030 }
06031 
06032 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
06033                                   const InputInfo &Output,
06034                                   const InputInfoList &Inputs,
06035                                   const ArgList &Args,
06036                                   const char *LinkingOutput) const {
06037   // FIXME: Find a real GCC, don't hard-code versions here
06038   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
06039   const llvm::Triple &T = getToolChain().getTriple();
06040   std::string LibPath = "/usr/lib/";
06041   llvm::Triple::ArchType Arch = T.getArch();
06042   switch (Arch) {
06043   case llvm::Triple::x86:
06044     GCCLibPath +=
06045         ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
06046     break;
06047   case llvm::Triple::x86_64:
06048     GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
06049     GCCLibPath += "/4.5.2/amd64/";
06050     LibPath += "amd64/";
06051     break;
06052   default:
06053     llvm_unreachable("Unsupported architecture");
06054   }
06055 
06056   ArgStringList CmdArgs;
06057 
06058   // Demangle C++ names in errors
06059   CmdArgs.push_back("-C");
06060 
06061   if ((!Args.hasArg(options::OPT_nostdlib)) &&
06062       (!Args.hasArg(options::OPT_shared))) {
06063     CmdArgs.push_back("-e");
06064     CmdArgs.push_back("_start");
06065   }
06066 
06067   if (Args.hasArg(options::OPT_static)) {
06068     CmdArgs.push_back("-Bstatic");
06069     CmdArgs.push_back("-dn");
06070   } else {
06071     CmdArgs.push_back("-Bdynamic");
06072     if (Args.hasArg(options::OPT_shared)) {
06073       CmdArgs.push_back("-shared");
06074     } else {
06075       CmdArgs.push_back("--dynamic-linker");
06076       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
06077     }
06078   }
06079 
06080   if (Output.isFilename()) {
06081     CmdArgs.push_back("-o");
06082     CmdArgs.push_back(Output.getFilename());
06083   } else {
06084     assert(Output.isNothing() && "Invalid output.");
06085   }
06086 
06087   if (!Args.hasArg(options::OPT_nostdlib) &&
06088       !Args.hasArg(options::OPT_nostartfiles)) {
06089     if (!Args.hasArg(options::OPT_shared)) {
06090       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
06091       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
06092       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
06093       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
06094     } else {
06095       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
06096       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
06097       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
06098     }
06099     if (getToolChain().getDriver().CCCIsCXX())
06100       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
06101   }
06102 
06103   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
06104 
06105   Args.AddAllArgs(CmdArgs, options::OPT_L);
06106   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
06107   Args.AddAllArgs(CmdArgs, options::OPT_e);
06108   Args.AddAllArgs(CmdArgs, options::OPT_r);
06109 
06110   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
06111 
06112   if (!Args.hasArg(options::OPT_nostdlib) &&
06113       !Args.hasArg(options::OPT_nodefaultlibs)) {
06114     if (getToolChain().getDriver().CCCIsCXX())
06115       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
06116     CmdArgs.push_back("-lgcc_s");
06117     if (!Args.hasArg(options::OPT_shared)) {
06118       CmdArgs.push_back("-lgcc");
06119       CmdArgs.push_back("-lc");
06120       CmdArgs.push_back("-lm");
06121     }
06122   }
06123 
06124   if (!Args.hasArg(options::OPT_nostdlib) &&
06125       !Args.hasArg(options::OPT_nostartfiles)) {
06126     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
06127   }
06128   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
06129 
06130   addProfileRT(getToolChain(), Args, CmdArgs);
06131 
06132   const char *Exec =
06133     Args.MakeArgString(getToolChain().GetLinkerPath());
06134   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06135 }
06136 
06137 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
06138                                      const InputInfo &Output,
06139                                      const InputInfoList &Inputs,
06140                                      const ArgList &Args,
06141                                      const char *LinkingOutput) const {
06142   ArgStringList CmdArgs;
06143   bool NeedsKPIC = false;
06144 
06145   switch (getToolChain().getArch()) {
06146   case llvm::Triple::x86:
06147     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
06148     // instruct as in the base system to assemble 32-bit code.
06149     CmdArgs.push_back("--32");
06150     break;
06151 
06152   case llvm::Triple::ppc:
06153     CmdArgs.push_back("-mppc");
06154     CmdArgs.push_back("-many");
06155     break;
06156 
06157   case llvm::Triple::sparc:
06158     CmdArgs.push_back("-32");
06159     NeedsKPIC = true;
06160     break;
06161 
06162   case llvm::Triple::sparcv9:
06163     CmdArgs.push_back("-64");
06164     CmdArgs.push_back("-Av9a");
06165     NeedsKPIC = true;
06166     break;
06167 
06168   case llvm::Triple::mips64:
06169   case llvm::Triple::mips64el: {
06170     StringRef CPUName;
06171     StringRef ABIName;
06172     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
06173 
06174     CmdArgs.push_back("-mabi");
06175     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
06176 
06177     if (getToolChain().getArch() == llvm::Triple::mips64)
06178       CmdArgs.push_back("-EB");
06179     else
06180       CmdArgs.push_back("-EL");
06181 
06182     NeedsKPIC = true;
06183     break;
06184   }
06185 
06186   default:
06187     break;
06188   }
06189 
06190   if (NeedsKPIC)
06191     addAssemblerKPIC(Args, CmdArgs);
06192 
06193   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
06194                        options::OPT_Xassembler);
06195 
06196   CmdArgs.push_back("-o");
06197   CmdArgs.push_back(Output.getFilename());
06198 
06199   for (const auto &II : Inputs)
06200     CmdArgs.push_back(II.getFilename());
06201 
06202   const char *Exec =
06203     Args.MakeArgString(getToolChain().GetProgramPath("as"));
06204   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06205 }
06206 
06207 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
06208                                  const InputInfo &Output,
06209                                  const InputInfoList &Inputs,
06210                                  const ArgList &Args,
06211                                  const char *LinkingOutput) const {
06212   const Driver &D = getToolChain().getDriver();
06213   ArgStringList CmdArgs;
06214 
06215   // Silence warning for "clang -g foo.o -o foo"
06216   Args.ClaimAllArgs(options::OPT_g_Group);
06217   // and "clang -emit-llvm foo.o -o foo"
06218   Args.ClaimAllArgs(options::OPT_emit_llvm);
06219   // and for "clang -w foo.o -o foo". Other warning options are already
06220   // handled somewhere else.
06221   Args.ClaimAllArgs(options::OPT_w);
06222 
06223   if (getToolChain().getArch() == llvm::Triple::mips64)
06224     CmdArgs.push_back("-EB");
06225   else if (getToolChain().getArch() == llvm::Triple::mips64el)
06226     CmdArgs.push_back("-EL");
06227 
06228   if ((!Args.hasArg(options::OPT_nostdlib)) &&
06229       (!Args.hasArg(options::OPT_shared))) {
06230     CmdArgs.push_back("-e");
06231     CmdArgs.push_back("__start");
06232   }
06233 
06234   if (Args.hasArg(options::OPT_static)) {
06235     CmdArgs.push_back("-Bstatic");
06236   } else {
06237     if (Args.hasArg(options::OPT_rdynamic))
06238       CmdArgs.push_back("-export-dynamic");
06239     CmdArgs.push_back("--eh-frame-hdr");
06240     CmdArgs.push_back("-Bdynamic");
06241     if (Args.hasArg(options::OPT_shared)) {
06242       CmdArgs.push_back("-shared");
06243     } else {
06244       CmdArgs.push_back("-dynamic-linker");
06245       CmdArgs.push_back("/usr/libexec/ld.so");
06246     }
06247   }
06248 
06249   if (Args.hasArg(options::OPT_nopie))
06250     CmdArgs.push_back("-nopie");
06251 
06252   if (Output.isFilename()) {
06253     CmdArgs.push_back("-o");
06254     CmdArgs.push_back(Output.getFilename());
06255   } else {
06256     assert(Output.isNothing() && "Invalid output.");
06257   }
06258 
06259   if (!Args.hasArg(options::OPT_nostdlib) &&
06260       !Args.hasArg(options::OPT_nostartfiles)) {
06261     if (!Args.hasArg(options::OPT_shared)) {
06262       if (Args.hasArg(options::OPT_pg))  
06263         CmdArgs.push_back(Args.MakeArgString(
06264                                 getToolChain().GetFilePath("gcrt0.o")));
06265       else
06266         CmdArgs.push_back(Args.MakeArgString(
06267                                 getToolChain().GetFilePath("crt0.o")));
06268       CmdArgs.push_back(Args.MakeArgString(
06269                               getToolChain().GetFilePath("crtbegin.o")));
06270     } else {
06271       CmdArgs.push_back(Args.MakeArgString(
06272                               getToolChain().GetFilePath("crtbeginS.o")));
06273     }
06274   }
06275 
06276   std::string Triple = getToolChain().getTripleString();
06277   if (Triple.substr(0, 6) == "x86_64")
06278     Triple.replace(0, 6, "amd64");
06279   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
06280                                        "/4.2.1"));
06281 
06282   Args.AddAllArgs(CmdArgs, options::OPT_L);
06283   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
06284   Args.AddAllArgs(CmdArgs, options::OPT_e);
06285   Args.AddAllArgs(CmdArgs, options::OPT_s);
06286   Args.AddAllArgs(CmdArgs, options::OPT_t);
06287   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
06288   Args.AddAllArgs(CmdArgs, options::OPT_r);
06289 
06290   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
06291 
06292   if (!Args.hasArg(options::OPT_nostdlib) &&
06293       !Args.hasArg(options::OPT_nodefaultlibs)) {
06294     if (D.CCCIsCXX()) {
06295       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
06296       if (Args.hasArg(options::OPT_pg)) 
06297         CmdArgs.push_back("-lm_p");
06298       else
06299         CmdArgs.push_back("-lm");
06300     }
06301 
06302     // FIXME: For some reason GCC passes -lgcc before adding
06303     // the default system libraries. Just mimic this for now.
06304     CmdArgs.push_back("-lgcc");
06305 
06306     if (Args.hasArg(options::OPT_pthread)) {
06307       if (!Args.hasArg(options::OPT_shared) &&
06308           Args.hasArg(options::OPT_pg))
06309          CmdArgs.push_back("-lpthread_p");
06310       else
06311          CmdArgs.push_back("-lpthread");
06312     }
06313 
06314     if (!Args.hasArg(options::OPT_shared)) {
06315       if (Args.hasArg(options::OPT_pg))
06316          CmdArgs.push_back("-lc_p");
06317       else
06318          CmdArgs.push_back("-lc");
06319     }
06320 
06321     CmdArgs.push_back("-lgcc");
06322   }
06323 
06324   if (!Args.hasArg(options::OPT_nostdlib) &&
06325       !Args.hasArg(options::OPT_nostartfiles)) {
06326     if (!Args.hasArg(options::OPT_shared))
06327       CmdArgs.push_back(Args.MakeArgString(
06328                               getToolChain().GetFilePath("crtend.o")));
06329     else
06330       CmdArgs.push_back(Args.MakeArgString(
06331                               getToolChain().GetFilePath("crtendS.o")));
06332   }
06333 
06334   const char *Exec =
06335     Args.MakeArgString(getToolChain().GetLinkerPath());
06336   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06337 }
06338 
06339 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
06340                                     const InputInfo &Output,
06341                                     const InputInfoList &Inputs,
06342                                     const ArgList &Args,
06343                                     const char *LinkingOutput) const {
06344   ArgStringList CmdArgs;
06345 
06346   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
06347                        options::OPT_Xassembler);
06348 
06349   CmdArgs.push_back("-o");
06350   CmdArgs.push_back(Output.getFilename());
06351 
06352   for (const auto &II : Inputs)
06353     CmdArgs.push_back(II.getFilename());
06354 
06355   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
06356   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06357 }
06358 
06359 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
06360                                 const InputInfo &Output,
06361                                 const InputInfoList &Inputs,
06362                                 const ArgList &Args,
06363                                 const char *LinkingOutput) const {
06364   const Driver &D = getToolChain().getDriver();
06365   ArgStringList CmdArgs;
06366 
06367   if ((!Args.hasArg(options::OPT_nostdlib)) &&
06368       (!Args.hasArg(options::OPT_shared))) {
06369     CmdArgs.push_back("-e");
06370     CmdArgs.push_back("__start");
06371   }
06372 
06373   if (Args.hasArg(options::OPT_static)) {
06374     CmdArgs.push_back("-Bstatic");
06375   } else {
06376     if (Args.hasArg(options::OPT_rdynamic))
06377       CmdArgs.push_back("-export-dynamic");
06378     CmdArgs.push_back("--eh-frame-hdr");
06379     CmdArgs.push_back("-Bdynamic");
06380     if (Args.hasArg(options::OPT_shared)) {
06381       CmdArgs.push_back("-shared");
06382     } else {
06383       CmdArgs.push_back("-dynamic-linker");
06384       CmdArgs.push_back("/usr/libexec/ld.so");
06385     }
06386   }
06387 
06388   if (Output.isFilename()) {
06389     CmdArgs.push_back("-o");
06390     CmdArgs.push_back(Output.getFilename());
06391   } else {
06392     assert(Output.isNothing() && "Invalid output.");
06393   }
06394 
06395   if (!Args.hasArg(options::OPT_nostdlib) &&
06396       !Args.hasArg(options::OPT_nostartfiles)) {
06397     if (!Args.hasArg(options::OPT_shared)) {
06398       if (Args.hasArg(options::OPT_pg))
06399         CmdArgs.push_back(Args.MakeArgString(
06400                                 getToolChain().GetFilePath("gcrt0.o")));
06401       else
06402         CmdArgs.push_back(Args.MakeArgString(
06403                                 getToolChain().GetFilePath("crt0.o")));
06404       CmdArgs.push_back(Args.MakeArgString(
06405                               getToolChain().GetFilePath("crtbegin.o")));
06406     } else {
06407       CmdArgs.push_back(Args.MakeArgString(
06408                               getToolChain().GetFilePath("crtbeginS.o")));
06409     }
06410   }
06411 
06412   Args.AddAllArgs(CmdArgs, options::OPT_L);
06413   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
06414   Args.AddAllArgs(CmdArgs, options::OPT_e);
06415 
06416   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
06417 
06418   if (!Args.hasArg(options::OPT_nostdlib) &&
06419       !Args.hasArg(options::OPT_nodefaultlibs)) {
06420     if (D.CCCIsCXX()) {
06421       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
06422       if (Args.hasArg(options::OPT_pg))
06423         CmdArgs.push_back("-lm_p");
06424       else
06425         CmdArgs.push_back("-lm");
06426     }
06427 
06428     if (Args.hasArg(options::OPT_pthread)) {
06429       if (!Args.hasArg(options::OPT_shared) &&
06430           Args.hasArg(options::OPT_pg))
06431         CmdArgs.push_back("-lpthread_p");
06432       else
06433         CmdArgs.push_back("-lpthread");
06434     }
06435 
06436     if (!Args.hasArg(options::OPT_shared)) {
06437       if (Args.hasArg(options::OPT_pg))
06438         CmdArgs.push_back("-lc_p");
06439       else
06440         CmdArgs.push_back("-lc");
06441     }
06442 
06443     StringRef MyArch;
06444     switch (getToolChain().getTriple().getArch()) {
06445     case llvm::Triple::arm:
06446       MyArch = "arm";
06447       break;
06448     case llvm::Triple::x86:
06449       MyArch = "i386";
06450       break;
06451     case llvm::Triple::x86_64:
06452       MyArch = "amd64";
06453       break;
06454     default:
06455       llvm_unreachable("Unsupported architecture");
06456     }
06457     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
06458   }
06459 
06460   if (!Args.hasArg(options::OPT_nostdlib) &&
06461       !Args.hasArg(options::OPT_nostartfiles)) {
06462     if (!Args.hasArg(options::OPT_shared))
06463       CmdArgs.push_back(Args.MakeArgString(
06464                               getToolChain().GetFilePath("crtend.o")));
06465     else
06466       CmdArgs.push_back(Args.MakeArgString(
06467                               getToolChain().GetFilePath("crtendS.o")));
06468   }
06469 
06470   const char *Exec =
06471     Args.MakeArgString(getToolChain().GetLinkerPath());
06472   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06473 }
06474 
06475 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
06476                                      const InputInfo &Output,
06477                                      const InputInfoList &Inputs,
06478                                      const ArgList &Args,
06479                                      const char *LinkingOutput) const {
06480   ArgStringList CmdArgs;
06481 
06482   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
06483   // instruct as in the base system to assemble 32-bit code.
06484   if (getToolChain().getArch() == llvm::Triple::x86)
06485     CmdArgs.push_back("--32");
06486   else if (getToolChain().getArch() == llvm::Triple::ppc)
06487     CmdArgs.push_back("-a32");
06488   else if (getToolChain().getArch() == llvm::Triple::mips ||
06489            getToolChain().getArch() == llvm::Triple::mipsel ||
06490            getToolChain().getArch() == llvm::Triple::mips64 ||
06491            getToolChain().getArch() == llvm::Triple::mips64el) {
06492     StringRef CPUName;
06493     StringRef ABIName;
06494     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
06495 
06496     CmdArgs.push_back("-march");
06497     CmdArgs.push_back(CPUName.data());
06498 
06499     CmdArgs.push_back("-mabi");
06500     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
06501 
06502     if (getToolChain().getArch() == llvm::Triple::mips ||
06503         getToolChain().getArch() == llvm::Triple::mips64)
06504       CmdArgs.push_back("-EB");
06505     else
06506       CmdArgs.push_back("-EL");
06507 
06508     addAssemblerKPIC(Args, CmdArgs);
06509   } else if (getToolChain().getArch() == llvm::Triple::arm ||
06510              getToolChain().getArch() == llvm::Triple::armeb ||
06511              getToolChain().getArch() == llvm::Triple::thumb ||
06512              getToolChain().getArch() == llvm::Triple::thumbeb) {
06513     const Driver &D = getToolChain().getDriver();
06514     const llvm::Triple &Triple = getToolChain().getTriple();
06515     StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
06516 
06517     if (FloatABI == "hard") {
06518       CmdArgs.push_back("-mfpu=vfp");
06519     } else {
06520       CmdArgs.push_back("-mfpu=softvfp");
06521     }
06522 
06523     switch(getToolChain().getTriple().getEnvironment()) {
06524     case llvm::Triple::GNUEABIHF:
06525     case llvm::Triple::GNUEABI:
06526     case llvm::Triple::EABI:
06527       CmdArgs.push_back("-meabi=5");
06528       break;
06529 
06530     default:
06531       CmdArgs.push_back("-matpcs");
06532     }
06533   } else if (getToolChain().getArch() == llvm::Triple::sparc ||
06534              getToolChain().getArch() == llvm::Triple::sparcv9) {
06535     if (getToolChain().getArch() == llvm::Triple::sparc)
06536       CmdArgs.push_back("-Av8plusa");
06537     else
06538       CmdArgs.push_back("-Av9a");
06539 
06540     addAssemblerKPIC(Args, CmdArgs);
06541   }
06542 
06543   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
06544                        options::OPT_Xassembler);
06545 
06546   CmdArgs.push_back("-o");
06547   CmdArgs.push_back(Output.getFilename());
06548 
06549   for (const auto &II : Inputs)
06550     CmdArgs.push_back(II.getFilename());
06551 
06552   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
06553   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06554 }
06555 
06556 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
06557                                  const InputInfo &Output,
06558                                  const InputInfoList &Inputs,
06559                                  const ArgList &Args,
06560                                  const char *LinkingOutput) const {
06561   const toolchains::FreeBSD& ToolChain = 
06562     static_cast<const toolchains::FreeBSD&>(getToolChain());
06563   const Driver &D = ToolChain.getDriver();
06564   const bool IsPIE =
06565     !Args.hasArg(options::OPT_shared) &&
06566     (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
06567   ArgStringList CmdArgs;
06568 
06569   // Silence warning for "clang -g foo.o -o foo"
06570   Args.ClaimAllArgs(options::OPT_g_Group);
06571   // and "clang -emit-llvm foo.o -o foo"
06572   Args.ClaimAllArgs(options::OPT_emit_llvm);
06573   // and for "clang -w foo.o -o foo". Other warning options are already
06574   // handled somewhere else.
06575   Args.ClaimAllArgs(options::OPT_w);
06576 
06577   if (!D.SysRoot.empty())
06578     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
06579 
06580   if (IsPIE)
06581     CmdArgs.push_back("-pie");
06582 
06583   if (Args.hasArg(options::OPT_static)) {
06584     CmdArgs.push_back("-Bstatic");
06585   } else {
06586     if (Args.hasArg(options::OPT_rdynamic))
06587       CmdArgs.push_back("-export-dynamic");
06588     CmdArgs.push_back("--eh-frame-hdr");
06589     if (Args.hasArg(options::OPT_shared)) {
06590       CmdArgs.push_back("-Bshareable");
06591     } else {
06592       CmdArgs.push_back("-dynamic-linker");
06593       CmdArgs.push_back("/libexec/ld-elf.so.1");
06594     }
06595     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
06596       llvm::Triple::ArchType Arch = ToolChain.getArch();
06597       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
06598           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
06599         CmdArgs.push_back("--hash-style=both");
06600       }
06601     }
06602     CmdArgs.push_back("--enable-new-dtags");
06603   }
06604 
06605   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
06606   // instruct ld in the base system to link 32-bit code.
06607   if (ToolChain.getArch() == llvm::Triple::x86) {
06608     CmdArgs.push_back("-m");
06609     CmdArgs.push_back("elf_i386_fbsd");
06610   }
06611 
06612   if (ToolChain.getArch() == llvm::Triple::ppc) {
06613     CmdArgs.push_back("-m");
06614     CmdArgs.push_back("elf32ppc_fbsd");
06615   }
06616 
06617   if (Output.isFilename()) {
06618     CmdArgs.push_back("-o");
06619     CmdArgs.push_back(Output.getFilename());
06620   } else {
06621     assert(Output.isNothing() && "Invalid output.");
06622   }
06623 
06624   if (!Args.hasArg(options::OPT_nostdlib) &&
06625       !Args.hasArg(options::OPT_nostartfiles)) {
06626     const char *crt1 = nullptr;
06627     if (!Args.hasArg(options::OPT_shared)) {
06628       if (Args.hasArg(options::OPT_pg))
06629         crt1 = "gcrt1.o";
06630       else if (IsPIE)
06631         crt1 = "Scrt1.o";
06632       else
06633         crt1 = "crt1.o";
06634     }
06635     if (crt1)
06636       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
06637 
06638     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
06639 
06640     const char *crtbegin = nullptr;
06641     if (Args.hasArg(options::OPT_static))
06642       crtbegin = "crtbeginT.o";
06643     else if (Args.hasArg(options::OPT_shared) || IsPIE)
06644       crtbegin = "crtbeginS.o";
06645     else
06646       crtbegin = "crtbegin.o";
06647 
06648     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
06649   }
06650 
06651   Args.AddAllArgs(CmdArgs, options::OPT_L);
06652   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
06653   for (const auto &Path : Paths)
06654     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
06655   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
06656   Args.AddAllArgs(CmdArgs, options::OPT_e);
06657   Args.AddAllArgs(CmdArgs, options::OPT_s);
06658   Args.AddAllArgs(CmdArgs, options::OPT_t);
06659   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
06660   Args.AddAllArgs(CmdArgs, options::OPT_r);
06661 
06662   if (D.IsUsingLTO(Args))
06663     AddGoldPlugin(ToolChain, Args, CmdArgs);
06664 
06665   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
06666   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
06667 
06668   if (!Args.hasArg(options::OPT_nostdlib) &&
06669       !Args.hasArg(options::OPT_nodefaultlibs)) {
06670     if (D.CCCIsCXX()) {
06671       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
06672       if (Args.hasArg(options::OPT_pg))
06673         CmdArgs.push_back("-lm_p");
06674       else
06675         CmdArgs.push_back("-lm");
06676     }
06677     if (NeedsSanitizerDeps)
06678       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
06679     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
06680     // the default system libraries. Just mimic this for now.
06681     if (Args.hasArg(options::OPT_pg))
06682       CmdArgs.push_back("-lgcc_p");
06683     else
06684       CmdArgs.push_back("-lgcc");
06685     if (Args.hasArg(options::OPT_static)) {
06686       CmdArgs.push_back("-lgcc_eh");
06687     } else if (Args.hasArg(options::OPT_pg)) {
06688       CmdArgs.push_back("-lgcc_eh_p");
06689     } else {
06690       CmdArgs.push_back("--as-needed");
06691       CmdArgs.push_back("-lgcc_s");
06692       CmdArgs.push_back("--no-as-needed");
06693     }
06694 
06695     if (Args.hasArg(options::OPT_pthread)) {
06696       if (Args.hasArg(options::OPT_pg))
06697         CmdArgs.push_back("-lpthread_p");
06698       else
06699         CmdArgs.push_back("-lpthread");
06700     }
06701 
06702     if (Args.hasArg(options::OPT_pg)) {
06703       if (Args.hasArg(options::OPT_shared))
06704         CmdArgs.push_back("-lc");
06705       else
06706         CmdArgs.push_back("-lc_p");
06707       CmdArgs.push_back("-lgcc_p");
06708     } else {
06709       CmdArgs.push_back("-lc");
06710       CmdArgs.push_back("-lgcc");
06711     }
06712 
06713     if (Args.hasArg(options::OPT_static)) {
06714       CmdArgs.push_back("-lgcc_eh");
06715     } else if (Args.hasArg(options::OPT_pg)) {
06716       CmdArgs.push_back("-lgcc_eh_p");
06717     } else {
06718       CmdArgs.push_back("--as-needed");
06719       CmdArgs.push_back("-lgcc_s");
06720       CmdArgs.push_back("--no-as-needed");
06721     }
06722   }
06723 
06724   if (!Args.hasArg(options::OPT_nostdlib) &&
06725       !Args.hasArg(options::OPT_nostartfiles)) {
06726     if (Args.hasArg(options::OPT_shared) || IsPIE)
06727       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
06728     else
06729       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
06730     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
06731   }
06732 
06733   addProfileRT(ToolChain, Args, CmdArgs);
06734 
06735   const char *Exec =
06736     Args.MakeArgString(getToolChain().GetLinkerPath());
06737   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06738 }
06739 
06740 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
06741                                      const InputInfo &Output,
06742                                      const InputInfoList &Inputs,
06743                                      const ArgList &Args,
06744                                      const char *LinkingOutput) const {
06745   ArgStringList CmdArgs;
06746 
06747   // GNU as needs different flags for creating the correct output format
06748   // on architectures with different ABIs or optional feature sets.
06749   switch (getToolChain().getArch()) {
06750   case llvm::Triple::x86:
06751     CmdArgs.push_back("--32");
06752     break;
06753   case llvm::Triple::arm:
06754   case llvm::Triple::armeb:
06755   case llvm::Triple::thumb:
06756   case llvm::Triple::thumbeb: {
06757     std::string MArch(arm::getARMTargetCPU(Args, getToolChain().getTriple()));
06758     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
06759     break;
06760   }
06761 
06762   case llvm::Triple::mips:
06763   case llvm::Triple::mipsel:
06764   case llvm::Triple::mips64:
06765   case llvm::Triple::mips64el: {
06766     StringRef CPUName;
06767     StringRef ABIName;
06768     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
06769 
06770     CmdArgs.push_back("-march");
06771     CmdArgs.push_back(CPUName.data());
06772 
06773     CmdArgs.push_back("-mabi");
06774     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
06775 
06776     if (getToolChain().getArch() == llvm::Triple::mips ||
06777         getToolChain().getArch() == llvm::Triple::mips64)
06778       CmdArgs.push_back("-EB");
06779     else
06780       CmdArgs.push_back("-EL");
06781 
06782     addAssemblerKPIC(Args, CmdArgs);
06783     break;
06784   }
06785 
06786   case llvm::Triple::sparc:
06787     CmdArgs.push_back("-32");
06788     addAssemblerKPIC(Args, CmdArgs);
06789     break;
06790 
06791   case llvm::Triple::sparcv9:
06792     CmdArgs.push_back("-64");
06793     CmdArgs.push_back("-Av9");
06794     addAssemblerKPIC(Args, CmdArgs);
06795     break;
06796 
06797   default:
06798     break;  
06799   }
06800 
06801   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
06802                        options::OPT_Xassembler);
06803 
06804   CmdArgs.push_back("-o");
06805   CmdArgs.push_back(Output.getFilename());
06806 
06807   for (const auto &II : Inputs)
06808     CmdArgs.push_back(II.getFilename());
06809 
06810   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
06811   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
06812 }
06813 
06814 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
06815                                  const InputInfo &Output,
06816                                  const InputInfoList &Inputs,
06817                                  const ArgList &Args,
06818                                  const char *LinkingOutput) const {
06819   const Driver &D = getToolChain().getDriver();
06820   ArgStringList CmdArgs;
06821 
06822   if (!D.SysRoot.empty())
06823     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
06824 
06825   CmdArgs.push_back("--eh-frame-hdr");
06826   if (Args.hasArg(options::OPT_static)) {
06827     CmdArgs.push_back("-Bstatic");
06828   } else {
06829     if (Args.hasArg(options::OPT_rdynamic))
06830       CmdArgs.push_back("-export-dynamic");
06831     if (Args.hasArg(options::OPT_shared)) {
06832       CmdArgs.push_back("-Bshareable");
06833     } else {
06834       CmdArgs.push_back("-dynamic-linker");
06835       CmdArgs.push_back("/libexec/ld.elf_so");
06836     }
06837   }
06838 
06839   // Many NetBSD architectures support more than one ABI.
06840   // Determine the correct emulation for ld.
06841   switch (getToolChain().getArch()) {
06842   case llvm::Triple::x86:
06843     CmdArgs.push_back("-m");
06844     CmdArgs.push_back("elf_i386");
06845     break;
06846   case llvm::Triple::arm:
06847   case llvm::Triple::thumb:
06848     CmdArgs.push_back("-m");
06849     switch (getToolChain().getTriple().getEnvironment()) {
06850     case llvm::Triple::EABI:
06851     case llvm::Triple::GNUEABI:
06852       CmdArgs.push_back("armelf_nbsd_eabi");
06853       break;
06854     case llvm::Triple::EABIHF:
06855     case llvm::Triple::GNUEABIHF:
06856       CmdArgs.push_back("armelf_nbsd_eabihf");
06857       break;
06858     default:
06859       CmdArgs.push_back("armelf_nbsd");
06860       break;
06861     }
06862     break;
06863   case llvm::Triple::armeb:
06864   case llvm::Triple::thumbeb:
06865     CmdArgs.push_back("-m");
06866     switch (getToolChain().getTriple().getEnvironment()) {
06867     case llvm::Triple::EABI:
06868     case llvm::Triple::GNUEABI:
06869       CmdArgs.push_back("armelfb_nbsd_eabi");
06870       break;
06871     case llvm::Triple::EABIHF:
06872     case llvm::Triple::GNUEABIHF:
06873       CmdArgs.push_back("armelfb_nbsd_eabihf");
06874       break;
06875     default:
06876       CmdArgs.push_back("armelfb_nbsd");
06877       break;
06878     }
06879     break;
06880   case llvm::Triple::mips64:
06881   case llvm::Triple::mips64el:
06882     if (mips::hasMipsAbiArg(Args, "32")) {
06883       CmdArgs.push_back("-m");
06884       if (getToolChain().getArch() == llvm::Triple::mips64)
06885         CmdArgs.push_back("elf32btsmip");
06886       else
06887         CmdArgs.push_back("elf32ltsmip");
06888    } else if (mips::hasMipsAbiArg(Args, "64")) {
06889      CmdArgs.push_back("-m");
06890      if (getToolChain().getArch() == llvm::Triple::mips64)
06891        CmdArgs.push_back("elf64btsmip");
06892      else
06893        CmdArgs.push_back("elf64ltsmip");
06894    }
06895    break;
06896   case llvm::Triple::ppc:
06897     CmdArgs.push_back("-m");
06898     CmdArgs.push_back("elf32ppc_nbsd");
06899     break;
06900 
06901   case llvm::Triple::ppc64:
06902   case llvm::Triple::ppc64le:
06903     CmdArgs.push_back("-m");
06904     CmdArgs.push_back("elf64ppc");
06905     break;
06906 
06907   case llvm::Triple::sparc:
06908     CmdArgs.push_back("-m");
06909     CmdArgs.push_back("elf32_sparc");
06910     break;
06911 
06912   case llvm::Triple::sparcv9:
06913     CmdArgs.push_back("-m");
06914     CmdArgs.push_back("elf64_sparc");
06915     break;
06916 
06917   default:
06918     break;
06919   }
06920 
06921   if (Output.isFilename()) {
06922     CmdArgs.push_back("-o");
06923     CmdArgs.push_back(Output.getFilename());
06924   } else {
06925     assert(Output.isNothing() && "Invalid output.");
06926   }
06927 
06928   if (!Args.hasArg(options::OPT_nostdlib) &&
06929       !Args.hasArg(options::OPT_nostartfiles)) {
06930     if (!Args.hasArg(options::OPT_shared)) {
06931       CmdArgs.push_back(Args.MakeArgString(
06932                               getToolChain().GetFilePath("crt0.o")));
06933       CmdArgs.push_back(Args.MakeArgString(
06934                               getToolChain().GetFilePath("crti.o")));
06935       CmdArgs.push_back(Args.MakeArgString(
06936                               getToolChain().GetFilePath("crtbegin.o")));
06937     } else {
06938       CmdArgs.push_back(Args.MakeArgString(
06939                               getToolChain().GetFilePath("crti.o")));
06940       CmdArgs.push_back(Args.MakeArgString(
06941                               getToolChain().GetFilePath("crtbeginS.o")));
06942     }
06943   }
06944 
06945   Args.AddAllArgs(CmdArgs, options::OPT_L);
06946   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
06947   Args.AddAllArgs(CmdArgs, options::OPT_e);
06948   Args.AddAllArgs(CmdArgs, options::OPT_s);
06949   Args.AddAllArgs(CmdArgs, options::OPT_t);
06950   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
06951   Args.AddAllArgs(CmdArgs, options::OPT_r);
06952 
06953   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
06954 
06955   unsigned Major, Minor, Micro;
06956   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
06957   bool useLibgcc = true;
06958   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
06959     switch(getToolChain().getArch()) {
06960     case llvm::Triple::aarch64:
06961     case llvm::Triple::arm:
06962     case llvm::Triple::armeb:
06963     case llvm::Triple::thumb:
06964     case llvm::Triple::thumbeb:
06965     case llvm::Triple::ppc:
06966     case llvm::Triple::ppc64:
06967     case llvm::Triple::ppc64le:
06968     case llvm::Triple::x86:
06969     case llvm::Triple::x86_64:
06970       useLibgcc = false;
06971       break;
06972     default:
06973       break;
06974     }
06975   }
06976 
06977   if (!Args.hasArg(options::OPT_nostdlib) &&
06978       !Args.hasArg(options::OPT_nodefaultlibs)) {
06979     if (D.CCCIsCXX()) {
06980       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
06981       CmdArgs.push_back("-lm");
06982     }
06983     if (Args.hasArg(options::OPT_pthread))
06984       CmdArgs.push_back("-lpthread");
06985     CmdArgs.push_back("-lc");
06986 
06987     if (useLibgcc) {
06988       if (Args.hasArg(options::OPT_static)) {
06989         // libgcc_eh depends on libc, so resolve as much as possible,
06990         // pull in any new requirements from libc and then get the rest
06991         // of libgcc.
06992         CmdArgs.push_back("-lgcc_eh");
06993         CmdArgs.push_back("-lc");
06994         CmdArgs.push_back("-lgcc");
06995       } else {
06996         CmdArgs.push_back("-lgcc");
06997         CmdArgs.push_back("--as-needed");
06998         CmdArgs.push_back("-lgcc_s");
06999         CmdArgs.push_back("--no-as-needed");
07000       }
07001     }
07002   }
07003 
07004   if (!Args.hasArg(options::OPT_nostdlib) &&
07005       !Args.hasArg(options::OPT_nostartfiles)) {
07006     if (!Args.hasArg(options::OPT_shared))
07007       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
07008                                                                   "crtend.o")));
07009     else
07010       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
07011                                                                  "crtendS.o")));
07012     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
07013                                                                     "crtn.o")));
07014   }
07015 
07016   addProfileRT(getToolChain(), Args, CmdArgs);
07017 
07018   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
07019   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
07020 }
07021 
07022 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
07023                                       const InputInfo &Output,
07024                                       const InputInfoList &Inputs,
07025                                       const ArgList &Args,
07026                                       const char *LinkingOutput) const {
07027   ArgStringList CmdArgs;
07028   bool NeedsKPIC = false;
07029 
07030   // Add --32/--64 to make sure we get the format we want.
07031   // This is incomplete
07032   if (getToolChain().getArch() == llvm::Triple::x86) {
07033     CmdArgs.push_back("--32");
07034   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
07035     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
07036       CmdArgs.push_back("--x32");
07037     else
07038       CmdArgs.push_back("--64");
07039   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
07040     CmdArgs.push_back("-a32");
07041     CmdArgs.push_back("-mppc");
07042     CmdArgs.push_back("-many");
07043   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
07044     CmdArgs.push_back("-a64");
07045     CmdArgs.push_back("-mppc64");
07046     CmdArgs.push_back("-many");
07047   } else if (getToolChain().getArch() == llvm::Triple::ppc64le) {
07048     CmdArgs.push_back("-a64");
07049     CmdArgs.push_back("-mppc64");
07050     CmdArgs.push_back("-many");
07051     CmdArgs.push_back("-mlittle-endian");
07052   } else if (getToolChain().getArch() == llvm::Triple::sparc) {
07053     CmdArgs.push_back("-32");
07054     CmdArgs.push_back("-Av8plusa");
07055     NeedsKPIC = true;
07056   } else if (getToolChain().getArch() == llvm::Triple::sparcv9) {
07057     CmdArgs.push_back("-64");
07058     CmdArgs.push_back("-Av9a");
07059     NeedsKPIC = true;
07060   } else if (getToolChain().getArch() == llvm::Triple::arm ||
07061              getToolChain().getArch() == llvm::Triple::armeb) {
07062     StringRef MArch = getToolChain().getArchName();
07063     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
07064       CmdArgs.push_back("-mfpu=neon");
07065     if (MArch == "armv8" || MArch == "armv8a" || MArch == "armv8-a" ||
07066         MArch == "armebv8" || MArch == "armebv8a" || MArch == "armebv8-a")
07067       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
07068 
07069     StringRef ARMFloatABI = tools::arm::getARMFloatABI(
07070         getToolChain().getDriver(), Args, getToolChain().getTriple());
07071     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
07072 
07073     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
07074 
07075     // FIXME: remove krait check when GNU tools support krait cpu
07076     // for now replace it with -march=armv7-a  to avoid a lower
07077     // march from being picked in the absence of a cpu flag.
07078     Arg *A;
07079     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
07080       StringRef(A->getValue()) == "krait")
07081         CmdArgs.push_back("-march=armv7-a");
07082     else
07083       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
07084     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
07085   } else if (getToolChain().getArch() == llvm::Triple::mips ||
07086              getToolChain().getArch() == llvm::Triple::mipsel ||
07087              getToolChain().getArch() == llvm::Triple::mips64 ||
07088              getToolChain().getArch() == llvm::Triple::mips64el) {
07089     StringRef CPUName;
07090     StringRef ABIName;
07091     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
07092     ABIName = getGnuCompatibleMipsABIName(ABIName);
07093 
07094     CmdArgs.push_back("-march");
07095     CmdArgs.push_back(CPUName.data());
07096 
07097     CmdArgs.push_back("-mabi");
07098     CmdArgs.push_back(ABIName.data());
07099 
07100     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
07101     // or -mshared (not implemented) is in effect.
07102     bool IsPicOrPie = false;
07103     if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
07104                                  options::OPT_fpic, options::OPT_fno_pic,
07105                                  options::OPT_fPIE, options::OPT_fno_PIE,
07106                                  options::OPT_fpie, options::OPT_fno_pie)) {
07107       if (A->getOption().matches(options::OPT_fPIC) ||
07108           A->getOption().matches(options::OPT_fpic) ||
07109           A->getOption().matches(options::OPT_fPIE) ||
07110           A->getOption().matches(options::OPT_fpie))
07111         IsPicOrPie = true;
07112     }
07113     if (!IsPicOrPie)
07114       CmdArgs.push_back("-mno-shared");
07115 
07116     // LLVM doesn't support -mplt yet and acts as if it is always given.
07117     // However, -mplt has no effect with the N64 ABI.
07118     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
07119 
07120     if (getToolChain().getArch() == llvm::Triple::mips ||
07121         getToolChain().getArch() == llvm::Triple::mips64)
07122       CmdArgs.push_back("-EB");
07123     else
07124       CmdArgs.push_back("-EL");
07125 
07126     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
07127       if (StringRef(A->getValue()) == "2008")
07128         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
07129     }
07130 
07131     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
07132     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
07133                                  options::OPT_mfp64)) {
07134       A->claim();
07135       A->render(Args, CmdArgs);
07136     } else if (mips::isFPXXDefault(getToolChain().getTriple(), CPUName,
07137                                    ABIName))
07138       CmdArgs.push_back("-mfpxx");
07139 
07140     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
07141     // -mno-mips16 is actually -no-mips16.
07142     if (Arg *A = Args.getLastArg(options::OPT_mips16,
07143                                  options::OPT_mno_mips16)) {
07144       if (A->getOption().matches(options::OPT_mips16)) {
07145         A->claim();
07146         A->render(Args, CmdArgs);
07147       } else {
07148         A->claim();
07149         CmdArgs.push_back("-no-mips16");
07150       }
07151     }
07152 
07153     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
07154                     options::OPT_mno_micromips);
07155     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
07156     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
07157 
07158     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
07159       // Do not use AddLastArg because not all versions of MIPS assembler
07160       // support -mmsa / -mno-msa options.
07161       if (A->getOption().matches(options::OPT_mmsa))
07162         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
07163     }
07164 
07165     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
07166                     options::OPT_msoft_float);
07167 
07168     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
07169                     options::OPT_mno_odd_spreg);
07170 
07171     NeedsKPIC = true;
07172   } else if (getToolChain().getArch() == llvm::Triple::systemz) {
07173     // Always pass an -march option, since our default of z10 is later
07174     // than the GNU assembler's default.
07175     StringRef CPUName = getSystemZTargetCPU(Args);
07176     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
07177   }
07178 
07179   if (NeedsKPIC)
07180     addAssemblerKPIC(Args, CmdArgs);
07181 
07182   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
07183                        options::OPT_Xassembler);
07184 
07185   CmdArgs.push_back("-o");
07186   CmdArgs.push_back(Output.getFilename());
07187 
07188   for (const auto &II : Inputs)
07189     CmdArgs.push_back(II.getFilename());
07190 
07191   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
07192   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
07193 
07194   // Handle the debug info splitting at object creation time if we're
07195   // creating an object.
07196   // TODO: Currently only works on linux with newer objcopy.
07197   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
07198       getToolChain().getTriple().isOSLinux())
07199     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
07200                    SplitDebugName(Args, Inputs));
07201 }
07202 
07203 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
07204                       ArgStringList &CmdArgs, const ArgList &Args) {
07205   bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
07206   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
07207                       Args.hasArg(options::OPT_static);
07208   if (!D.CCCIsCXX())
07209     CmdArgs.push_back("-lgcc");
07210 
07211   if (StaticLibgcc || isAndroid) {
07212     if (D.CCCIsCXX())
07213       CmdArgs.push_back("-lgcc");
07214   } else {
07215     if (!D.CCCIsCXX())
07216       CmdArgs.push_back("--as-needed");
07217     CmdArgs.push_back("-lgcc_s");
07218     if (!D.CCCIsCXX())
07219       CmdArgs.push_back("--no-as-needed");
07220   }
07221 
07222   if (StaticLibgcc && !isAndroid)
07223     CmdArgs.push_back("-lgcc_eh");
07224   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
07225     CmdArgs.push_back("-lgcc");
07226 
07227   // According to Android ABI, we have to link with libdl if we are
07228   // linking with non-static libgcc.
07229   //
07230   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
07231   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
07232   if (isAndroid && !StaticLibgcc)
07233     CmdArgs.push_back("-ldl");
07234 }
07235 
07236 static std::string getLinuxDynamicLinker(const ArgList &Args,
07237                                          const toolchains::Linux &ToolChain) {
07238   if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
07239     if (ToolChain.getTriple().isArch64Bit())
07240       return "/system/bin/linker64";
07241     else
07242       return "/system/bin/linker";
07243   } else if (ToolChain.getArch() == llvm::Triple::x86 ||
07244              ToolChain.getArch() == llvm::Triple::sparc)
07245     return "/lib/ld-linux.so.2";
07246   else if (ToolChain.getArch() == llvm::Triple::aarch64)
07247     return "/lib/ld-linux-aarch64.so.1";
07248   else if (ToolChain.getArch() == llvm::Triple::aarch64_be)
07249     return "/lib/ld-linux-aarch64_be.so.1";
07250   else if (ToolChain.getArch() == llvm::Triple::arm ||
07251            ToolChain.getArch() == llvm::Triple::thumb) {
07252     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
07253       return "/lib/ld-linux-armhf.so.3";
07254     else
07255       return "/lib/ld-linux.so.3";
07256   } else if (ToolChain.getArch() == llvm::Triple::armeb ||
07257              ToolChain.getArch() == llvm::Triple::thumbeb) {
07258     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
07259       return "/lib/ld-linux-armhf.so.3";        /* TODO: check which dynamic linker name.  */
07260     else
07261       return "/lib/ld-linux.so.3";              /* TODO: check which dynamic linker name.  */
07262   } else if (ToolChain.getArch() == llvm::Triple::mips ||
07263              ToolChain.getArch() == llvm::Triple::mipsel ||
07264              ToolChain.getArch() == llvm::Triple::mips64 ||
07265              ToolChain.getArch() == llvm::Triple::mips64el) {
07266     StringRef CPUName;
07267     StringRef ABIName;
07268     mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
07269     bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
07270 
07271     StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
07272                            .Case("o32", "/lib")
07273                            .Case("n32", "/lib32")
07274                            .Case("n64", "/lib64")
07275                            .Default("/lib");
07276     StringRef LibName;
07277     if (mips::isUCLibc(Args))
07278       LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
07279     else
07280       LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
07281 
07282     return (LibDir + "/" + LibName).str();
07283   } else if (ToolChain.getArch() == llvm::Triple::ppc)
07284     return "/lib/ld.so.1";
07285   else if (ToolChain.getArch() == llvm::Triple::ppc64) {
07286     if (ppc::hasPPCAbiArg(Args, "elfv2"))
07287       return "/lib64/ld64.so.2";
07288     return "/lib64/ld64.so.1";
07289   } else if (ToolChain.getArch() == llvm::Triple::ppc64le) {
07290     if (ppc::hasPPCAbiArg(Args, "elfv1"))
07291       return "/lib64/ld64.so.1";
07292     return "/lib64/ld64.so.2";
07293   } else if (ToolChain.getArch() == llvm::Triple::systemz)
07294     return "/lib64/ld64.so.1";
07295   else if (ToolChain.getArch() == llvm::Triple::sparcv9)
07296     return "/lib64/ld-linux.so.2";
07297   else if (ToolChain.getArch() == llvm::Triple::x86_64 &&
07298            ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
07299     return "/libx32/ld-linux-x32.so.2";
07300   else
07301     return "/lib64/ld-linux-x86-64.so.2";
07302 }
07303 
07304 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
07305                       ArgStringList &CmdArgs, const ArgList &Args) {
07306   // Make use of compiler-rt if --rtlib option is used
07307   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
07308 
07309   switch(RLT) {
07310   case ToolChain::RLT_CompilerRT:
07311     switch (TC.getTriple().getOS()) {
07312     default: llvm_unreachable("unsupported OS");
07313     case llvm::Triple::Win32:
07314       addClangRTWindows(TC, Args, CmdArgs);
07315       break;
07316     case llvm::Triple::Linux:
07317       addClangRTLinux(TC, Args, CmdArgs);
07318       break;
07319     }
07320     break;
07321   case ToolChain::RLT_Libgcc:
07322     AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
07323     break;
07324   }
07325 }
07326 
07327 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
07328   switch (T.getArch()) {
07329   case llvm::Triple::x86:
07330     return "elf_i386";
07331   case llvm::Triple::aarch64:
07332     return "aarch64linux";
07333   case llvm::Triple::aarch64_be:
07334     return "aarch64_be_linux";
07335   case llvm::Triple::arm:
07336   case llvm::Triple::thumb:
07337     return "armelf_linux_eabi";
07338   case llvm::Triple::armeb:
07339   case llvm::Triple::thumbeb:
07340     return "armebelf_linux_eabi"; /* TODO: check which NAME.  */
07341   case llvm::Triple::ppc:
07342     return "elf32ppclinux";
07343   case llvm::Triple::ppc64:
07344     return "elf64ppc";
07345   case llvm::Triple::ppc64le:
07346     return "elf64lppc";
07347   case llvm::Triple::sparc:
07348     return "elf32_sparc";
07349   case llvm::Triple::sparcv9:
07350     return "elf64_sparc";
07351   case llvm::Triple::mips:
07352     return "elf32btsmip";
07353   case llvm::Triple::mipsel:
07354     return "elf32ltsmip";
07355   case llvm::Triple::mips64:
07356     if (mips::hasMipsAbiArg(Args, "n32"))
07357       return "elf32btsmipn32";
07358     return "elf64btsmip";
07359   case llvm::Triple::mips64el:
07360     if (mips::hasMipsAbiArg(Args, "n32"))
07361       return "elf32ltsmipn32";
07362     return "elf64ltsmip";
07363   case llvm::Triple::systemz:
07364     return "elf64_s390";
07365   case llvm::Triple::x86_64:
07366     if (T.getEnvironment() == llvm::Triple::GNUX32)
07367       return "elf32_x86_64";
07368     return "elf_x86_64";
07369   default:
07370     llvm_unreachable("Unexpected arch");
07371   }
07372 }
07373 
07374 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
07375                                   const InputInfo &Output,
07376                                   const InputInfoList &Inputs,
07377                                   const ArgList &Args,
07378                                   const char *LinkingOutput) const {
07379   const toolchains::Linux& ToolChain =
07380     static_cast<const toolchains::Linux&>(getToolChain());
07381   const Driver &D = ToolChain.getDriver();
07382   const bool isAndroid =
07383     ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
07384   const bool IsPIE =
07385     !Args.hasArg(options::OPT_shared) &&
07386     !Args.hasArg(options::OPT_static) &&
07387     (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault() ||
07388      // On Android every code is PIC so every executable is PIE
07389      // Cannot use isPIEDefault here since otherwise
07390      // PIE only logic will be enabled during compilation
07391      isAndroid);
07392 
07393   ArgStringList CmdArgs;
07394 
07395   // Silence warning for "clang -g foo.o -o foo"
07396   Args.ClaimAllArgs(options::OPT_g_Group);
07397   // and "clang -emit-llvm foo.o -o foo"
07398   Args.ClaimAllArgs(options::OPT_emit_llvm);
07399   // and for "clang -w foo.o -o foo". Other warning options are already
07400   // handled somewhere else.
07401   Args.ClaimAllArgs(options::OPT_w);
07402 
07403   if (!D.SysRoot.empty())
07404     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
07405 
07406   if (IsPIE)
07407     CmdArgs.push_back("-pie");
07408 
07409   if (Args.hasArg(options::OPT_rdynamic))
07410     CmdArgs.push_back("-export-dynamic");
07411 
07412   if (Args.hasArg(options::OPT_s))
07413     CmdArgs.push_back("-s");
07414 
07415   for (const auto &Opt : ToolChain.ExtraOpts)
07416     CmdArgs.push_back(Opt.c_str());
07417 
07418   if (!Args.hasArg(options::OPT_static)) {
07419     CmdArgs.push_back("--eh-frame-hdr");
07420   }
07421 
07422   CmdArgs.push_back("-m");
07423   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
07424 
07425   if (Args.hasArg(options::OPT_static)) {
07426     if (ToolChain.getArch() == llvm::Triple::arm ||
07427         ToolChain.getArch() == llvm::Triple::armeb ||
07428         ToolChain.getArch() == llvm::Triple::thumb ||
07429         ToolChain.getArch() == llvm::Triple::thumbeb)
07430       CmdArgs.push_back("-Bstatic");
07431     else
07432       CmdArgs.push_back("-static");
07433   } else if (Args.hasArg(options::OPT_shared)) {
07434     CmdArgs.push_back("-shared");
07435   }
07436 
07437   if (ToolChain.getArch() == llvm::Triple::arm ||
07438       ToolChain.getArch() == llvm::Triple::armeb ||
07439       ToolChain.getArch() == llvm::Triple::thumb ||
07440       ToolChain.getArch() == llvm::Triple::thumbeb ||
07441       (!Args.hasArg(options::OPT_static) &&
07442        !Args.hasArg(options::OPT_shared))) {
07443     CmdArgs.push_back("-dynamic-linker");
07444     CmdArgs.push_back(Args.MakeArgString(
07445         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
07446   }
07447 
07448   CmdArgs.push_back("-o");
07449   CmdArgs.push_back(Output.getFilename());
07450 
07451   if (!Args.hasArg(options::OPT_nostdlib) &&
07452       !Args.hasArg(options::OPT_nostartfiles)) {
07453     if (!isAndroid) {
07454       const char *crt1 = nullptr;
07455       if (!Args.hasArg(options::OPT_shared)){
07456         if (Args.hasArg(options::OPT_pg))
07457           crt1 = "gcrt1.o";
07458         else if (IsPIE)
07459           crt1 = "Scrt1.o";
07460         else
07461           crt1 = "crt1.o";
07462       }
07463       if (crt1)
07464         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
07465 
07466       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
07467     }
07468 
07469     const char *crtbegin;
07470     if (Args.hasArg(options::OPT_static))
07471       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
07472     else if (Args.hasArg(options::OPT_shared))
07473       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
07474     else if (IsPIE)
07475       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
07476     else
07477       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
07478     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
07479 
07480     // Add crtfastmath.o if available and fast math is enabled.
07481     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
07482   }
07483 
07484   Args.AddAllArgs(CmdArgs, options::OPT_L);
07485   Args.AddAllArgs(CmdArgs, options::OPT_u);
07486 
07487   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
07488 
07489   for (const auto &Path : Paths)
07490     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
07491 
07492   if (D.IsUsingLTO(Args))
07493     AddGoldPlugin(ToolChain, Args, CmdArgs);
07494 
07495   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
07496     CmdArgs.push_back("--no-demangle");
07497 
07498   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
07499   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
07500   // The profile runtime also needs access to system libraries.
07501   addProfileRT(getToolChain(), Args, CmdArgs);
07502 
07503   if (D.CCCIsCXX() &&
07504       !Args.hasArg(options::OPT_nostdlib) &&
07505       !Args.hasArg(options::OPT_nodefaultlibs)) {
07506     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
07507       !Args.hasArg(options::OPT_static);
07508     if (OnlyLibstdcxxStatic)
07509       CmdArgs.push_back("-Bstatic");
07510     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
07511     if (OnlyLibstdcxxStatic)
07512       CmdArgs.push_back("-Bdynamic");
07513     CmdArgs.push_back("-lm");
07514   }
07515 
07516   if (!Args.hasArg(options::OPT_nostdlib)) {
07517     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
07518       if (Args.hasArg(options::OPT_static))
07519         CmdArgs.push_back("--start-group");
07520 
07521       if (NeedsSanitizerDeps)
07522         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
07523 
07524       LibOpenMP UsedOpenMPLib = LibUnknown;
07525       if (Args.hasArg(options::OPT_fopenmp)) {
07526         UsedOpenMPLib = LibGOMP;
07527       } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
07528         UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
07529             .Case("libgomp",  LibGOMP)
07530             .Case("libiomp5", LibIOMP5)
07531             .Default(LibUnknown);
07532         if (UsedOpenMPLib == LibUnknown)
07533           D.Diag(diag::err_drv_unsupported_option_argument)
07534             << A->getOption().getName() << A->getValue();
07535       }
07536       switch (UsedOpenMPLib) {
07537       case LibGOMP:
07538         CmdArgs.push_back("-lgomp");
07539 
07540         // FIXME: Exclude this for platforms with libgomp that don't require
07541         // librt. Most modern Linux platforms require it, but some may not.
07542         CmdArgs.push_back("-lrt");
07543         break;
07544       case LibIOMP5:
07545         CmdArgs.push_back("-liomp5");
07546         break;
07547       case LibUnknown:
07548         break;
07549       }
07550       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
07551 
07552       if ((Args.hasArg(options::OPT_pthread) ||
07553            Args.hasArg(options::OPT_pthreads) || UsedOpenMPLib != LibUnknown) &&
07554           !isAndroid)
07555         CmdArgs.push_back("-lpthread");
07556 
07557       CmdArgs.push_back("-lc");
07558 
07559       if (Args.hasArg(options::OPT_static))
07560         CmdArgs.push_back("--end-group");
07561       else
07562         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
07563     }
07564 
07565     if (!Args.hasArg(options::OPT_nostartfiles)) {
07566       const char *crtend;
07567       if (Args.hasArg(options::OPT_shared))
07568         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
07569       else if (IsPIE)
07570         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
07571       else
07572         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
07573 
07574       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
07575       if (!isAndroid)
07576         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
07577     }
07578   }
07579 
07580   C.addCommand(
07581       llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
07582 }
07583 
07584 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
07585                                    const InputInfo &Output,
07586                                    const InputInfoList &Inputs,
07587                                    const ArgList &Args,
07588                                    const char *LinkingOutput) const {
07589   ArgStringList CmdArgs;
07590 
07591   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
07592 
07593   CmdArgs.push_back("-o");
07594   CmdArgs.push_back(Output.getFilename());
07595 
07596   for (const auto &II : Inputs)
07597     CmdArgs.push_back(II.getFilename());
07598 
07599   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
07600   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
07601 }
07602 
07603 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
07604                                const InputInfo &Output,
07605                                const InputInfoList &Inputs,
07606                                const ArgList &Args,
07607                                const char *LinkingOutput) const {
07608   const Driver &D = getToolChain().getDriver();
07609   ArgStringList CmdArgs;
07610 
07611   if (Output.isFilename()) {
07612     CmdArgs.push_back("-o");
07613     CmdArgs.push_back(Output.getFilename());
07614   } else {
07615     assert(Output.isNothing() && "Invalid output.");
07616   }
07617 
07618   if (!Args.hasArg(options::OPT_nostdlib) &&
07619       !Args.hasArg(options::OPT_nostartfiles)) {
07620       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
07621       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
07622       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
07623       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
07624   }
07625 
07626   Args.AddAllArgs(CmdArgs, options::OPT_L);
07627   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
07628   Args.AddAllArgs(CmdArgs, options::OPT_e);
07629 
07630   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
07631 
07632   addProfileRT(getToolChain(), Args, CmdArgs);
07633 
07634   if (!Args.hasArg(options::OPT_nostdlib) &&
07635       !Args.hasArg(options::OPT_nodefaultlibs)) {
07636     if (D.CCCIsCXX()) {
07637       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
07638       CmdArgs.push_back("-lm");
07639     }
07640   }
07641 
07642   if (!Args.hasArg(options::OPT_nostdlib) &&
07643       !Args.hasArg(options::OPT_nostartfiles)) {
07644     if (Args.hasArg(options::OPT_pthread))
07645       CmdArgs.push_back("-lpthread");
07646     CmdArgs.push_back("-lc");
07647     CmdArgs.push_back("-lCompilerRT-Generic");
07648     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
07649     CmdArgs.push_back(
07650          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
07651   }
07652 
07653   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
07654   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
07655 }
07656 
07657 /// DragonFly Tools
07658 
07659 // For now, DragonFly Assemble does just about the same as for
07660 // FreeBSD, but this may change soon.
07661 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
07662                                        const InputInfo &Output,
07663                                        const InputInfoList &Inputs,
07664                                        const ArgList &Args,
07665                                        const char *LinkingOutput) const {
07666   ArgStringList CmdArgs;
07667 
07668   // When building 32-bit code on DragonFly/pc64, we have to explicitly
07669   // instruct as in the base system to assemble 32-bit code.
07670   if (getToolChain().getArch() == llvm::Triple::x86)
07671     CmdArgs.push_back("--32");
07672 
07673   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
07674 
07675   CmdArgs.push_back("-o");
07676   CmdArgs.push_back(Output.getFilename());
07677 
07678   for (const auto &II : Inputs)
07679     CmdArgs.push_back(II.getFilename());
07680 
07681   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
07682   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
07683 }
07684 
07685 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
07686                                    const InputInfo &Output,
07687                                    const InputInfoList &Inputs,
07688                                    const ArgList &Args,
07689                                    const char *LinkingOutput) const {
07690   const Driver &D = getToolChain().getDriver();
07691   ArgStringList CmdArgs;
07692   bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
07693 
07694   if (!D.SysRoot.empty())
07695     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
07696 
07697   CmdArgs.push_back("--eh-frame-hdr");
07698   if (Args.hasArg(options::OPT_static)) {
07699     CmdArgs.push_back("-Bstatic");
07700   } else {
07701     if (Args.hasArg(options::OPT_rdynamic))
07702       CmdArgs.push_back("-export-dynamic");
07703     if (Args.hasArg(options::OPT_shared))
07704       CmdArgs.push_back("-Bshareable");
07705     else {
07706       CmdArgs.push_back("-dynamic-linker");
07707       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
07708     }
07709     CmdArgs.push_back("--hash-style=both");
07710   }
07711 
07712   // When building 32-bit code on DragonFly/pc64, we have to explicitly
07713   // instruct ld in the base system to link 32-bit code.
07714   if (getToolChain().getArch() == llvm::Triple::x86) {
07715     CmdArgs.push_back("-m");
07716     CmdArgs.push_back("elf_i386");
07717   }
07718 
07719   if (Output.isFilename()) {
07720     CmdArgs.push_back("-o");
07721     CmdArgs.push_back(Output.getFilename());
07722   } else {
07723     assert(Output.isNothing() && "Invalid output.");
07724   }
07725 
07726   if (!Args.hasArg(options::OPT_nostdlib) &&
07727       !Args.hasArg(options::OPT_nostartfiles)) {
07728     if (!Args.hasArg(options::OPT_shared)) {
07729       if (Args.hasArg(options::OPT_pg))
07730         CmdArgs.push_back(Args.MakeArgString(
07731                                 getToolChain().GetFilePath("gcrt1.o")));
07732       else {
07733         if (Args.hasArg(options::OPT_pie))
07734           CmdArgs.push_back(Args.MakeArgString(
07735                                   getToolChain().GetFilePath("Scrt1.o")));
07736         else
07737           CmdArgs.push_back(Args.MakeArgString(
07738                                   getToolChain().GetFilePath("crt1.o")));
07739       }
07740     }
07741     CmdArgs.push_back(Args.MakeArgString(
07742                             getToolChain().GetFilePath("crti.o")));
07743     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
07744       CmdArgs.push_back(Args.MakeArgString(
07745                               getToolChain().GetFilePath("crtbeginS.o")));
07746     else
07747       CmdArgs.push_back(Args.MakeArgString(
07748                               getToolChain().GetFilePath("crtbegin.o")));
07749   }
07750 
07751   Args.AddAllArgs(CmdArgs, options::OPT_L);
07752   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
07753   Args.AddAllArgs(CmdArgs, options::OPT_e);
07754 
07755   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
07756 
07757   if (!Args.hasArg(options::OPT_nostdlib) &&
07758       !Args.hasArg(options::OPT_nodefaultlibs)) {
07759     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
07760     //         rpaths
07761     if (UseGCC47)
07762       CmdArgs.push_back("-L/usr/lib/gcc47");
07763     else
07764       CmdArgs.push_back("-L/usr/lib/gcc44");
07765 
07766     if (!Args.hasArg(options::OPT_static)) {
07767       if (UseGCC47) {
07768         CmdArgs.push_back("-rpath");
07769         CmdArgs.push_back("/usr/lib/gcc47");
07770       } else {
07771         CmdArgs.push_back("-rpath");
07772         CmdArgs.push_back("/usr/lib/gcc44");
07773       }
07774     }
07775 
07776     if (D.CCCIsCXX()) {
07777       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
07778       CmdArgs.push_back("-lm");
07779     }
07780 
07781     if (Args.hasArg(options::OPT_pthread))
07782       CmdArgs.push_back("-lpthread");
07783 
07784     if (!Args.hasArg(options::OPT_nolibc)) {
07785       CmdArgs.push_back("-lc");
07786     }
07787 
07788     if (UseGCC47) {
07789       if (Args.hasArg(options::OPT_static) ||
07790           Args.hasArg(options::OPT_static_libgcc)) {
07791         CmdArgs.push_back("-lgcc");
07792         CmdArgs.push_back("-lgcc_eh");
07793       } else {
07794         if (Args.hasArg(options::OPT_shared_libgcc)) {
07795           CmdArgs.push_back("-lgcc_pic");
07796           if (!Args.hasArg(options::OPT_shared))
07797             CmdArgs.push_back("-lgcc");
07798         } else {
07799           CmdArgs.push_back("-lgcc");
07800           CmdArgs.push_back("--as-needed");
07801           CmdArgs.push_back("-lgcc_pic");
07802           CmdArgs.push_back("--no-as-needed");
07803         }
07804       }
07805     } else {
07806       if (Args.hasArg(options::OPT_shared)) {
07807         CmdArgs.push_back("-lgcc_pic");
07808       } else {
07809         CmdArgs.push_back("-lgcc");
07810       }
07811     }
07812   }
07813 
07814   if (!Args.hasArg(options::OPT_nostdlib) &&
07815       !Args.hasArg(options::OPT_nostartfiles)) {
07816     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
07817       CmdArgs.push_back(Args.MakeArgString(
07818                               getToolChain().GetFilePath("crtendS.o")));
07819     else
07820       CmdArgs.push_back(Args.MakeArgString(
07821                               getToolChain().GetFilePath("crtend.o")));
07822     CmdArgs.push_back(Args.MakeArgString(
07823                             getToolChain().GetFilePath("crtn.o")));
07824   }
07825 
07826   addProfileRT(getToolChain(), Args, CmdArgs);
07827 
07828   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
07829   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
07830 }
07831 
07832 static void addSanitizerRTWindows(const ToolChain &TC, const ArgList &Args,
07833                                   ArgStringList &CmdArgs,
07834                                   StringRef RTName) {
07835   SmallString<128> LibSanitizer(getCompilerRTLibDir(TC));
07836   llvm::sys::path::append(LibSanitizer,
07837                           Twine("clang_rt.") + RTName + ".lib");
07838   CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
07839 }
07840 
07841 // Try to find Exe from a Visual Studio distribution.  This first tries to find
07842 // an installed copy of Visual Studio and, failing that, looks in the PATH,
07843 // making sure that whatever executable that's found is not a same-named exe
07844 // from clang itself to prevent clang from falling back to itself.
07845 static std::string FindVisualStudioExecutable(const ToolChain &TC,
07846                                               const char *Exe,
07847                                               const char *ClangProgramPath) {
07848   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
07849   std::string visualStudioBinDir;
07850   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
07851                                          visualStudioBinDir)) {
07852     SmallString<128> FilePath(visualStudioBinDir);
07853     llvm::sys::path::append(FilePath, Exe);
07854     if (llvm::sys::fs::can_execute(FilePath.c_str()))
07855       return FilePath.str();
07856   }
07857 
07858   return Exe;
07859 }
07860 
07861 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
07862                                       const InputInfo &Output,
07863                                       const InputInfoList &Inputs,
07864                                       const ArgList &Args,
07865                                       const char *LinkingOutput) const {
07866   ArgStringList CmdArgs;
07867 
07868   if (Output.isFilename()) {
07869     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
07870                                          Output.getFilename()));
07871   } else {
07872     assert(Output.isNothing() && "Invalid output.");
07873   }
07874 
07875   if (!Args.hasArg(options::OPT_nostdlib) &&
07876       !Args.hasArg(options::OPT_nostartfiles) &&
07877       !C.getDriver().IsCLMode()) {
07878     CmdArgs.push_back("-defaultlib:libcmt");
07879   }
07880 
07881   if (!llvm::sys::Process::GetEnv("LIB")) {
07882     // If the VC environment hasn't been configured (perhaps because the user
07883     // did not run vcvarsall), try to build a consistent link environment.  If
07884     // the environment variable is set however, assume the user knows what he's
07885     // doing.
07886     std::string VisualStudioDir;
07887     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(getToolChain());
07888     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
07889       SmallString<128> LibDir(VisualStudioDir);
07890       llvm::sys::path::append(LibDir, "VC", "lib");
07891       switch (MSVC.getArch()) {
07892       case llvm::Triple::x86:
07893         // x86 just puts the libraries directly in lib
07894         break;
07895       case llvm::Triple::x86_64:
07896         llvm::sys::path::append(LibDir, "amd64");
07897         break;
07898       case llvm::Triple::arm:
07899         llvm::sys::path::append(LibDir, "arm");
07900         break;
07901       default:
07902         break;
07903       }
07904       CmdArgs.push_back(
07905           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
07906     }
07907 
07908     std::string WindowsSdkLibPath;
07909     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
07910       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
07911                                            WindowsSdkLibPath.c_str()));
07912   }
07913 
07914   CmdArgs.push_back("-nologo");
07915 
07916   if (Args.hasArg(options::OPT_g_Group)) {
07917     CmdArgs.push_back("-debug");
07918   }
07919 
07920   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd);
07921 
07922   if (DLL) {
07923     CmdArgs.push_back(Args.MakeArgString("-dll"));
07924 
07925     SmallString<128> ImplibName(Output.getFilename());
07926     llvm::sys::path::replace_extension(ImplibName, "lib");
07927     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
07928                                          ImplibName.str()));
07929   }
07930 
07931   if (getToolChain().getSanitizerArgs().needsAsanRt()) {
07932     CmdArgs.push_back(Args.MakeArgString("-debug"));
07933     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
07934     // FIXME: Handle 64-bit.
07935     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
07936       addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan_dynamic-i386");
07937       addSanitizerRTWindows(getToolChain(), Args, CmdArgs,
07938                             "asan_dynamic_runtime_thunk-i386");
07939       // Make sure the dynamic runtime thunk is not optimized out at link time
07940       // to ensure proper SEH handling.
07941       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
07942     } else if (DLL) {
07943       addSanitizerRTWindows(getToolChain(), Args, CmdArgs,
07944                             "asan_dll_thunk-i386");
07945     } else {
07946       addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan-i386");
07947       addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan_cxx-i386");
07948     }
07949   }
07950 
07951   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
07952 
07953   // Add filenames, libraries, and other linker inputs.
07954   for (const auto &Input : Inputs) {
07955     if (Input.isFilename()) {
07956       CmdArgs.push_back(Input.getFilename());
07957       continue;
07958     }
07959 
07960     const Arg &A = Input.getInputArg();
07961 
07962     // Render -l options differently for the MSVC linker.
07963     if (A.getOption().matches(options::OPT_l)) {
07964       StringRef Lib = A.getValue();
07965       const char *LinkLibArg;
07966       if (Lib.endswith(".lib"))
07967         LinkLibArg = Args.MakeArgString(Lib);
07968       else
07969         LinkLibArg = Args.MakeArgString(Lib + ".lib");
07970       CmdArgs.push_back(LinkLibArg);
07971       continue;
07972     }
07973 
07974     // Otherwise, this is some other kind of linker input option like -Wl, -z,
07975     // or -L. Render it, even if MSVC doesn't understand it.
07976     A.renderAsInput(Args, CmdArgs);
07977   }
07978 
07979   // It's not sufficient to just use link from the program PATH, because other
07980   // environments like GnuWin32 install their own link.exe which may come first.
07981   llvm::SmallString<128> linkPath(FindVisualStudioExecutable(
07982       getToolChain(), "link.exe", C.getDriver().getClangProgramPath()));
07983   const char *Exec = Args.MakeArgString(linkPath);
07984   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
07985 }
07986 
07987 void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
07988                                          const InputInfo &Output,
07989                                          const InputInfoList &Inputs,
07990                                          const ArgList &Args,
07991                                          const char *LinkingOutput) const {
07992   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
07993 }
07994 
07995 std::unique_ptr<Command> visualstudio::Compile::GetCommand(
07996     Compilation &C, const JobAction &JA, const InputInfo &Output,
07997     const InputInfoList &Inputs, const ArgList &Args,
07998     const char *LinkingOutput) const {
07999   ArgStringList CmdArgs;
08000   CmdArgs.push_back("/nologo");
08001   CmdArgs.push_back("/c"); // Compile only.
08002   CmdArgs.push_back("/W0"); // No warnings.
08003 
08004   // The goal is to be able to invoke this tool correctly based on
08005   // any flag accepted by clang-cl.
08006 
08007   // These are spelled the same way in clang and cl.exe,.
08008   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
08009   Args.AddAllArgs(CmdArgs, options::OPT_I);
08010 
08011   // Optimization level.
08012   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
08013     if (A->getOption().getID() == options::OPT_O0) {
08014       CmdArgs.push_back("/Od");
08015     } else {
08016       StringRef OptLevel = A->getValue();
08017       if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
08018         A->render(Args, CmdArgs);
08019       else if (OptLevel == "3")
08020         CmdArgs.push_back("/Ox");
08021     }
08022   }
08023 
08024   // Flags for which clang-cl have an alias.
08025   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
08026 
08027   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
08028                    /*default=*/false))
08029     CmdArgs.push_back("/GR-");
08030   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
08031                                options::OPT_fno_function_sections))
08032     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
08033                           ? "/Gy"
08034                           : "/Gy-");
08035   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
08036                                options::OPT_fno_data_sections))
08037     CmdArgs.push_back(
08038         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
08039   if (Args.hasArg(options::OPT_fsyntax_only))
08040     CmdArgs.push_back("/Zs");
08041   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
08042     CmdArgs.push_back("/Z7");
08043 
08044   std::vector<std::string> Includes = Args.getAllArgValues(options::OPT_include);
08045   for (const auto &Include : Includes)
08046     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
08047 
08048   // Flags that can simply be passed through.
08049   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
08050   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
08051   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
08052 
08053   // The order of these flags is relevant, so pick the last one.
08054   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
08055                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
08056     A->render(Args, CmdArgs);
08057 
08058 
08059   // Input filename.
08060   assert(Inputs.size() == 1);
08061   const InputInfo &II = Inputs[0];
08062   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
08063   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
08064   if (II.isFilename())
08065     CmdArgs.push_back(II.getFilename());
08066   else
08067     II.getInputArg().renderAsInput(Args, CmdArgs);
08068 
08069   // Output filename.
08070   assert(Output.getType() == types::TY_Object);
08071   const char *Fo = Args.MakeArgString(std::string("/Fo") +
08072                                       Output.getFilename());
08073   CmdArgs.push_back(Fo);
08074 
08075   const Driver &D = getToolChain().getDriver();
08076   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
08077                                                 D.getClangProgramPath());
08078   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
08079                                     CmdArgs);
08080 }
08081 
08082 
08083 /// XCore Tools
08084 // We pass assemble and link construction to the xcc tool.
08085 
08086 void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
08087                                        const InputInfo &Output,
08088                                        const InputInfoList &Inputs,
08089                                        const ArgList &Args,
08090                                        const char *LinkingOutput) const {
08091   ArgStringList CmdArgs;
08092 
08093   CmdArgs.push_back("-o");
08094   CmdArgs.push_back(Output.getFilename());
08095 
08096   CmdArgs.push_back("-c");
08097 
08098   if (Args.hasArg(options::OPT_v))
08099     CmdArgs.push_back("-v");
08100 
08101   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
08102     if (!A->getOption().matches(options::OPT_g0))
08103       CmdArgs.push_back("-g");
08104 
08105   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
08106                    false))
08107     CmdArgs.push_back("-fverbose-asm");
08108 
08109   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
08110                        options::OPT_Xassembler);
08111 
08112   for (const auto &II : Inputs)
08113     CmdArgs.push_back(II.getFilename());
08114 
08115   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
08116   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
08117 }
08118 
08119 void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
08120                                    const InputInfo &Output,
08121                                    const InputInfoList &Inputs,
08122                                    const ArgList &Args,
08123                                    const char *LinkingOutput) const {
08124   ArgStringList CmdArgs;
08125 
08126   if (Output.isFilename()) {
08127     CmdArgs.push_back("-o");
08128     CmdArgs.push_back(Output.getFilename());
08129   } else {
08130     assert(Output.isNothing() && "Invalid output.");
08131   }
08132 
08133   if (Args.hasArg(options::OPT_v))
08134     CmdArgs.push_back("-v");
08135 
08136   ExceptionSettings EH = exceptionSettings(Args, getToolChain().getTriple());
08137   if (EH.ShouldUseExceptionTables)
08138     CmdArgs.push_back("-fexceptions");
08139 
08140   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
08141 
08142   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
08143   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
08144 }
08145 
08146 void CrossWindows::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
08147                                           const InputInfo &Output,
08148                                           const InputInfoList &Inputs,
08149                                           const ArgList &Args,
08150                                           const char *LinkingOutput) const {
08151   const auto &TC =
08152       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
08153   ArgStringList CmdArgs;
08154   const char *Exec;
08155 
08156   switch (TC.getArch()) {
08157   default: llvm_unreachable("unsupported architecture");
08158   case llvm::Triple::arm:
08159   case llvm::Triple::thumb:
08160     break;
08161   case llvm::Triple::x86:
08162     CmdArgs.push_back("--32");
08163     break;
08164   case llvm::Triple::x86_64:
08165     CmdArgs.push_back("--64");
08166     break;
08167   }
08168 
08169   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
08170 
08171   CmdArgs.push_back("-o");
08172   CmdArgs.push_back(Output.getFilename());
08173 
08174   for (const auto &Input : Inputs)
08175     CmdArgs.push_back(Input.getFilename());
08176 
08177   const std::string Assembler = TC.GetProgramPath("as");
08178   Exec = Args.MakeArgString(Assembler);
08179 
08180   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
08181 }
08182 
08183 void CrossWindows::Link::ConstructJob(Compilation &C, const JobAction &JA,
08184                                       const InputInfo &Output,
08185                                       const InputInfoList &Inputs,
08186                                       const ArgList &Args,
08187                                       const char *LinkingOutput) const {
08188   const auto &TC =
08189       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
08190   const llvm::Triple &T = TC.getTriple();
08191   const Driver &D = TC.getDriver();
08192   SmallString<128> EntryPoint;
08193   ArgStringList CmdArgs;
08194   const char *Exec;
08195 
08196   // Silence warning for "clang -g foo.o -o foo"
08197   Args.ClaimAllArgs(options::OPT_g_Group);
08198   // and "clang -emit-llvm foo.o -o foo"
08199   Args.ClaimAllArgs(options::OPT_emit_llvm);
08200   // and for "clang -w foo.o -o foo"
08201   Args.ClaimAllArgs(options::OPT_w);
08202   // Other warning options are already handled somewhere else.
08203 
08204   if (!D.SysRoot.empty())
08205     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
08206 
08207   if (Args.hasArg(options::OPT_pie))
08208     CmdArgs.push_back("-pie");
08209   if (Args.hasArg(options::OPT_rdynamic))
08210     CmdArgs.push_back("-export-dynamic");
08211   if (Args.hasArg(options::OPT_s))
08212     CmdArgs.push_back("--strip-all");
08213 
08214   CmdArgs.push_back("-m");
08215   switch (TC.getArch()) {
08216   default: llvm_unreachable("unsupported architecture");
08217   case llvm::Triple::arm:
08218   case llvm::Triple::thumb:
08219     // FIXME: this is incorrect for WinCE
08220     CmdArgs.push_back("thumb2pe");
08221     break;
08222   case llvm::Triple::x86:
08223     CmdArgs.push_back("i386pe");
08224     EntryPoint.append("_");
08225     break;
08226   case llvm::Triple::x86_64:
08227     CmdArgs.push_back("i386pep");
08228     break;
08229   }
08230 
08231   if (Args.hasArg(options::OPT_shared)) {
08232     switch (T.getArch()) {
08233     default: llvm_unreachable("unsupported architecture");
08234     case llvm::Triple::arm:
08235     case llvm::Triple::thumb:
08236     case llvm::Triple::x86_64:
08237       EntryPoint.append("_DllMainCRTStartup");
08238       break;
08239     case llvm::Triple::x86:
08240       EntryPoint.append("_DllMainCRTStartup@12");
08241       break;
08242     }
08243 
08244     CmdArgs.push_back("-shared");
08245     CmdArgs.push_back("-Bdynamic");
08246 
08247     CmdArgs.push_back("--enable-auto-image-base");
08248 
08249     CmdArgs.push_back("--entry");
08250     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
08251   } else {
08252     EntryPoint.append("mainCRTStartup");
08253 
08254     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
08255                                                        : "-Bdynamic");
08256 
08257     if (!Args.hasArg(options::OPT_nostdlib) &&
08258         !Args.hasArg(options::OPT_nostartfiles)) {
08259       CmdArgs.push_back("--entry");
08260       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
08261     }
08262 
08263     // FIXME: handle subsystem
08264   }
08265 
08266   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
08267   CmdArgs.push_back("--allow-multiple-definition");
08268 
08269   CmdArgs.push_back("-o");
08270   CmdArgs.push_back(Output.getFilename());
08271 
08272   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
08273     SmallString<261> ImpLib(Output.getFilename());
08274     llvm::sys::path::replace_extension(ImpLib, ".lib");
08275 
08276     CmdArgs.push_back("--out-implib");
08277     CmdArgs.push_back(Args.MakeArgString(ImpLib));
08278   }
08279 
08280   if (!Args.hasArg(options::OPT_nostdlib) &&
08281       !Args.hasArg(options::OPT_nostartfiles)) {
08282     const std::string CRTPath(D.SysRoot + "/usr/lib/");
08283     const char *CRTBegin;
08284 
08285     CRTBegin =
08286         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
08287     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
08288   }
08289 
08290   Args.AddAllArgs(CmdArgs, options::OPT_L);
08291 
08292   const auto &Paths = TC.getFilePaths();
08293   for (const auto &Path : Paths)
08294     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
08295 
08296   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
08297 
08298   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
08299       !Args.hasArg(options::OPT_nodefaultlibs)) {
08300     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
08301                      !Args.hasArg(options::OPT_static);
08302     if (StaticCXX)
08303       CmdArgs.push_back("-Bstatic");
08304     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
08305     if (StaticCXX)
08306       CmdArgs.push_back("-Bdynamic");
08307   }
08308 
08309   if (!Args.hasArg(options::OPT_nostdlib)) {
08310     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
08311       // TODO handle /MT[d] /MD[d]
08312       CmdArgs.push_back("-lmsvcrt");
08313       AddRunTimeLibs(TC, D, CmdArgs, Args);
08314     }
08315   }
08316 
08317   const std::string Linker = TC.GetProgramPath("ld");
08318   Exec = Args.MakeArgString(Linker);
08319 
08320   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
08321 }
08322