Home | History | Annotate | Download | only in Driver
      1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "Tools.h"
     11 #include "InputInfo.h"
     12 #include "ToolChains.h"
     13 #include "clang/Basic/CharInfo.h"
     14 #include "clang/Basic/LangOptions.h"
     15 #include "clang/Basic/ObjCRuntime.h"
     16 #include "clang/Basic/Version.h"
     17 #include "clang/Config/config.h"
     18 #include "clang/Driver/Action.h"
     19 #include "clang/Driver/Compilation.h"
     20 #include "clang/Driver/Driver.h"
     21 #include "clang/Driver/DriverDiagnostic.h"
     22 #include "clang/Driver/Job.h"
     23 #include "clang/Driver/Options.h"
     24 #include "clang/Driver/SanitizerArgs.h"
     25 #include "clang/Driver/ToolChain.h"
     26 #include "clang/Driver/Util.h"
     27 #include "llvm/ADT/STLExtras.h"
     28 #include "llvm/ADT/SmallString.h"
     29 #include "llvm/ADT/StringExtras.h"
     30 #include "llvm/ADT/StringSwitch.h"
     31 #include "llvm/ADT/Twine.h"
     32 #include "llvm/Option/Arg.h"
     33 #include "llvm/Option/ArgList.h"
     34 #include "llvm/Option/Option.h"
     35 #include "llvm/Support/CodeGen.h"
     36 #include "llvm/Support/Compression.h"
     37 #include "llvm/Support/ErrorHandling.h"
     38 #include "llvm/Support/FileSystem.h"
     39 #include "llvm/Support/Host.h"
     40 #include "llvm/Support/Path.h"
     41 #include "llvm/Support/Process.h"
     42 #include "llvm/Support/Program.h"
     43 #include "llvm/Support/raw_ostream.h"
     44 #include "llvm/Support/TargetParser.h"
     45 
     46 #ifdef LLVM_ON_UNIX
     47 #include <unistd.h> // For getuid().
     48 #endif
     49 
     50 using namespace clang::driver;
     51 using namespace clang::driver::tools;
     52 using namespace clang;
     53 using namespace llvm::opt;
     54 
     55 static const char *getSparcAsmModeForCPU(StringRef Name,
     56                                          const llvm::Triple &Triple) {
     57   if (Triple.getArch() == llvm::Triple::sparcv9) {
     58     return llvm::StringSwitch<const char *>(Name)
     59           .Case("niagara", "-Av9b")
     60           .Case("niagara2", "-Av9b")
     61           .Case("niagara3", "-Av9d")
     62           .Case("niagara4", "-Av9d")
     63           .Default("-Av9");
     64   } else {
     65     return llvm::StringSwitch<const char *>(Name)
     66           .Case("v8", "-Av8")
     67           .Case("supersparc", "-Av8")
     68           .Case("sparclite", "-Asparclite")
     69           .Case("f934", "-Asparclite")
     70           .Case("hypersparc", "-Av8")
     71           .Case("sparclite86x", "-Asparclite")
     72           .Case("sparclet", "-Asparclet")
     73           .Case("tsc701", "-Asparclet")
     74           .Case("v9", "-Av8plus")
     75           .Case("ultrasparc", "-Av8plus")
     76           .Case("ultrasparc3", "-Av8plus")
     77           .Case("niagara", "-Av8plusb")
     78           .Case("niagara2", "-Av8plusb")
     79           .Case("niagara3", "-Av8plusd")
     80           .Case("niagara4", "-Av8plusd")
     81           .Default("-Av8");
     82   }
     83 }
     84 
     85 /// CheckPreprocessingOptions - Perform some validation of preprocessing
     86 /// arguments that is shared with gcc.
     87 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
     88   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
     89     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
     90         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
     91       D.Diag(diag::err_drv_argument_only_allowed_with)
     92           << A->getBaseArg().getAsString(Args)
     93           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
     94     }
     95   }
     96 }
     97 
     98 /// CheckCodeGenerationOptions - Perform some validation of code generation
     99 /// arguments that is shared with gcc.
    100 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
    101   // In gcc, only ARM checks this, but it seems reasonable to check universally.
    102   if (Args.hasArg(options::OPT_static))
    103     if (const Arg *A =
    104             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
    105       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
    106                                                       << "-static";
    107 }
    108 
    109 // Add backslashes to escape spaces and other backslashes.
    110 // This is used for the space-separated argument list specified with
    111 // the -dwarf-debug-flags option.
    112 static void EscapeSpacesAndBackslashes(const char *Arg,
    113                                        SmallVectorImpl<char> &Res) {
    114   for (; *Arg; ++Arg) {
    115     switch (*Arg) {
    116     default:
    117       break;
    118     case ' ':
    119     case '\\':
    120       Res.push_back('\\');
    121       break;
    122     }
    123     Res.push_back(*Arg);
    124   }
    125 }
    126 
    127 // Quote target names for inclusion in GNU Make dependency files.
    128 // Only the characters '$', '#', ' ', '\t' are quoted.
    129 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
    130   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
    131     switch (Target[i]) {
    132     case ' ':
    133     case '\t':
    134       // Escape the preceding backslashes
    135       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
    136         Res.push_back('\\');
    137 
    138       // Escape the space/tab
    139       Res.push_back('\\');
    140       break;
    141     case '$':
    142       Res.push_back('$');
    143       break;
    144     case '#':
    145       Res.push_back('\\');
    146       break;
    147     default:
    148       break;
    149     }
    150 
    151     Res.push_back(Target[i]);
    152   }
    153 }
    154 
    155 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
    156                              const char *ArgName, const char *EnvVar) {
    157   const char *DirList = ::getenv(EnvVar);
    158   bool CombinedArg = false;
    159 
    160   if (!DirList)
    161     return; // Nothing to do.
    162 
    163   StringRef Name(ArgName);
    164   if (Name.equals("-I") || Name.equals("-L"))
    165     CombinedArg = true;
    166 
    167   StringRef Dirs(DirList);
    168   if (Dirs.empty()) // Empty string should not add '.'.
    169     return;
    170 
    171   StringRef::size_type Delim;
    172   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
    173     if (Delim == 0) { // Leading colon.
    174       if (CombinedArg) {
    175         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
    176       } else {
    177         CmdArgs.push_back(ArgName);
    178         CmdArgs.push_back(".");
    179       }
    180     } else {
    181       if (CombinedArg) {
    182         CmdArgs.push_back(
    183             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
    184       } else {
    185         CmdArgs.push_back(ArgName);
    186         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
    187       }
    188     }
    189     Dirs = Dirs.substr(Delim + 1);
    190   }
    191 
    192   if (Dirs.empty()) { // Trailing colon.
    193     if (CombinedArg) {
    194       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
    195     } else {
    196       CmdArgs.push_back(ArgName);
    197       CmdArgs.push_back(".");
    198     }
    199   } else { // Add the last path.
    200     if (CombinedArg) {
    201       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
    202     } else {
    203       CmdArgs.push_back(ArgName);
    204       CmdArgs.push_back(Args.MakeArgString(Dirs));
    205     }
    206   }
    207 }
    208 
    209 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
    210                             const ArgList &Args, ArgStringList &CmdArgs) {
    211   const Driver &D = TC.getDriver();
    212 
    213   // Add extra linker input arguments which are not treated as inputs
    214   // (constructed via -Xarch_).
    215   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
    216 
    217   for (const auto &II : Inputs) {
    218     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
    219       // Don't try to pass LLVM inputs unless we have native support.
    220       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
    221 
    222     // Add filenames immediately.
    223     if (II.isFilename()) {
    224       CmdArgs.push_back(II.getFilename());
    225       continue;
    226     }
    227 
    228     // Otherwise, this is a linker input argument.
    229     const Arg &A = II.getInputArg();
    230 
    231     // Handle reserved library options.
    232     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
    233       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
    234     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
    235       TC.AddCCKextLibArgs(Args, CmdArgs);
    236     else if (A.getOption().matches(options::OPT_z)) {
    237       // Pass -z prefix for gcc linker compatibility.
    238       A.claim();
    239       A.render(Args, CmdArgs);
    240     } else {
    241       A.renderAsInput(Args, CmdArgs);
    242     }
    243   }
    244 
    245   // LIBRARY_PATH - included following the user specified library paths.
    246   //                and only supported on native toolchains.
    247   if (!TC.isCrossCompiling())
    248     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
    249 }
    250 
    251 /// \brief Determine whether Objective-C automated reference counting is
    252 /// enabled.
    253 static bool isObjCAutoRefCount(const ArgList &Args) {
    254   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
    255 }
    256 
    257 /// \brief Determine whether we are linking the ObjC runtime.
    258 static bool isObjCRuntimeLinked(const ArgList &Args) {
    259   if (isObjCAutoRefCount(Args)) {
    260     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
    261     return true;
    262   }
    263   return Args.hasArg(options::OPT_fobjc_link_runtime);
    264 }
    265 
    266 static bool forwardToGCC(const Option &O) {
    267   // Don't forward inputs from the original command line.  They are added from
    268   // InputInfoList.
    269   return O.getKind() != Option::InputClass &&
    270          !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
    271 }
    272 
    273 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
    274                                     const Driver &D, const ArgList &Args,
    275                                     ArgStringList &CmdArgs,
    276                                     const InputInfo &Output,
    277                                     const InputInfoList &Inputs,
    278                                     const ToolChain *AuxToolChain) const {
    279   Arg *A;
    280 
    281   CheckPreprocessingOptions(D, Args);
    282 
    283   Args.AddLastArg(CmdArgs, options::OPT_C);
    284   Args.AddLastArg(CmdArgs, options::OPT_CC);
    285 
    286   // Handle dependency file generation.
    287   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
    288       (A = Args.getLastArg(options::OPT_MD)) ||
    289       (A = Args.getLastArg(options::OPT_MMD))) {
    290     // Determine the output location.
    291     const char *DepFile;
    292     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
    293       DepFile = MF->getValue();
    294       C.addFailureResultFile(DepFile, &JA);
    295     } else if (Output.getType() == types::TY_Dependencies) {
    296       DepFile = Output.getFilename();
    297     } else if (A->getOption().matches(options::OPT_M) ||
    298                A->getOption().matches(options::OPT_MM)) {
    299       DepFile = "-";
    300     } else {
    301       DepFile = getDependencyFileName(Args, Inputs);
    302       C.addFailureResultFile(DepFile, &JA);
    303     }
    304     CmdArgs.push_back("-dependency-file");
    305     CmdArgs.push_back(DepFile);
    306 
    307     // Add a default target if one wasn't specified.
    308     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
    309       const char *DepTarget;
    310 
    311       // If user provided -o, that is the dependency target, except
    312       // when we are only generating a dependency file.
    313       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
    314       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
    315         DepTarget = OutputOpt->getValue();
    316       } else {
    317         // Otherwise derive from the base input.
    318         //
    319         // FIXME: This should use the computed output file location.
    320         SmallString<128> P(Inputs[0].getBaseInput());
    321         llvm::sys::path::replace_extension(P, "o");
    322         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
    323       }
    324 
    325       CmdArgs.push_back("-MT");
    326       SmallString<128> Quoted;
    327       QuoteTarget(DepTarget, Quoted);
    328       CmdArgs.push_back(Args.MakeArgString(Quoted));
    329     }
    330 
    331     if (A->getOption().matches(options::OPT_M) ||
    332         A->getOption().matches(options::OPT_MD))
    333       CmdArgs.push_back("-sys-header-deps");
    334     if ((isa<PrecompileJobAction>(JA) &&
    335          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
    336         Args.hasArg(options::OPT_fmodule_file_deps))
    337       CmdArgs.push_back("-module-file-deps");
    338   }
    339 
    340   if (Args.hasArg(options::OPT_MG)) {
    341     if (!A || A->getOption().matches(options::OPT_MD) ||
    342         A->getOption().matches(options::OPT_MMD))
    343       D.Diag(diag::err_drv_mg_requires_m_or_mm);
    344     CmdArgs.push_back("-MG");
    345   }
    346 
    347   Args.AddLastArg(CmdArgs, options::OPT_MP);
    348   Args.AddLastArg(CmdArgs, options::OPT_MV);
    349 
    350   // Convert all -MQ <target> args to -MT <quoted target>
    351   for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
    352     A->claim();
    353 
    354     if (A->getOption().matches(options::OPT_MQ)) {
    355       CmdArgs.push_back("-MT");
    356       SmallString<128> Quoted;
    357       QuoteTarget(A->getValue(), Quoted);
    358       CmdArgs.push_back(Args.MakeArgString(Quoted));
    359 
    360       // -MT flag - no change
    361     } else {
    362       A->render(Args, CmdArgs);
    363     }
    364   }
    365 
    366   // Add -i* options, and automatically translate to
    367   // -include-pch/-include-pth for transparent PCH support. It's
    368   // wonky, but we include looking for .gch so we can support seamless
    369   // replacement into a build system already set up to be generating
    370   // .gch files.
    371   bool RenderedImplicitInclude = false;
    372   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
    373     if (A->getOption().matches(options::OPT_include)) {
    374       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
    375       RenderedImplicitInclude = true;
    376 
    377       // Use PCH if the user requested it.
    378       bool UsePCH = D.CCCUsePCH;
    379 
    380       bool FoundPTH = false;
    381       bool FoundPCH = false;
    382       SmallString<128> P(A->getValue());
    383       // We want the files to have a name like foo.h.pch. Add a dummy extension
    384       // so that replace_extension does the right thing.
    385       P += ".dummy";
    386       if (UsePCH) {
    387         llvm::sys::path::replace_extension(P, "pch");
    388         if (llvm::sys::fs::exists(P))
    389           FoundPCH = true;
    390       }
    391 
    392       if (!FoundPCH) {
    393         llvm::sys::path::replace_extension(P, "pth");
    394         if (llvm::sys::fs::exists(P))
    395           FoundPTH = true;
    396       }
    397 
    398       if (!FoundPCH && !FoundPTH) {
    399         llvm::sys::path::replace_extension(P, "gch");
    400         if (llvm::sys::fs::exists(P)) {
    401           FoundPCH = UsePCH;
    402           FoundPTH = !UsePCH;
    403         }
    404       }
    405 
    406       if (FoundPCH || FoundPTH) {
    407         if (IsFirstImplicitInclude) {
    408           A->claim();
    409           if (UsePCH)
    410             CmdArgs.push_back("-include-pch");
    411           else
    412             CmdArgs.push_back("-include-pth");
    413           CmdArgs.push_back(Args.MakeArgString(P));
    414           continue;
    415         } else {
    416           // Ignore the PCH if not first on command line and emit warning.
    417           D.Diag(diag::warn_drv_pch_not_first_include) << P
    418                                                        << A->getAsString(Args);
    419         }
    420       }
    421     }
    422 
    423     // Not translated, render as usual.
    424     A->claim();
    425     A->render(Args, CmdArgs);
    426   }
    427 
    428   Args.AddAllArgs(CmdArgs,
    429                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
    430                    options::OPT_F, options::OPT_index_header_map});
    431 
    432   // Add -Wp, and -Xpreprocessor if using the preprocessor.
    433 
    434   // FIXME: There is a very unfortunate problem here, some troubled
    435   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
    436   // really support that we would have to parse and then translate
    437   // those options. :(
    438   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
    439                        options::OPT_Xpreprocessor);
    440 
    441   // -I- is a deprecated GCC feature, reject it.
    442   if (Arg *A = Args.getLastArg(options::OPT_I_))
    443     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
    444 
    445   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
    446   // -isysroot to the CC1 invocation.
    447   StringRef sysroot = C.getSysRoot();
    448   if (sysroot != "") {
    449     if (!Args.hasArg(options::OPT_isysroot)) {
    450       CmdArgs.push_back("-isysroot");
    451       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
    452     }
    453   }
    454 
    455   // Parse additional include paths from environment variables.
    456   // FIXME: We should probably sink the logic for handling these from the
    457   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
    458   // CPATH - included following the user specified includes (but prior to
    459   // builtin and standard includes).
    460   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
    461   // C_INCLUDE_PATH - system includes enabled when compiling C.
    462   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
    463   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
    464   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
    465   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
    466   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
    467   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
    468   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
    469 
    470   // Optional AuxToolChain indicates that we need to include headers
    471   // for more than one target. If that's the case, add include paths
    472   // from AuxToolChain right after include paths of the same kind for
    473   // the current target.
    474 
    475   // Add C++ include arguments, if needed.
    476   if (types::isCXX(Inputs[0].getType())) {
    477     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
    478     if (AuxToolChain)
    479       AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
    480   }
    481 
    482   // Add system include arguments.
    483   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
    484   if (AuxToolChain)
    485       AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
    486 
    487   // Add CUDA include arguments, if needed.
    488   if (types::isCuda(Inputs[0].getType()))
    489     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
    490 }
    491 
    492 // FIXME: Move to target hook.
    493 static bool isSignedCharDefault(const llvm::Triple &Triple) {
    494   switch (Triple.getArch()) {
    495   default:
    496     return true;
    497 
    498   case llvm::Triple::aarch64:
    499   case llvm::Triple::aarch64_be:
    500   case llvm::Triple::arm:
    501   case llvm::Triple::armeb:
    502   case llvm::Triple::thumb:
    503   case llvm::Triple::thumbeb:
    504     if (Triple.isOSDarwin() || Triple.isOSWindows())
    505       return true;
    506     return false;
    507 
    508   case llvm::Triple::ppc:
    509   case llvm::Triple::ppc64:
    510     if (Triple.isOSDarwin())
    511       return true;
    512     return false;
    513 
    514   case llvm::Triple::hexagon:
    515   case llvm::Triple::ppc64le:
    516   case llvm::Triple::systemz:
    517   case llvm::Triple::xcore:
    518     return false;
    519   }
    520 }
    521 
    522 static bool isNoCommonDefault(const llvm::Triple &Triple) {
    523   switch (Triple.getArch()) {
    524   default:
    525     return false;
    526 
    527   case llvm::Triple::xcore:
    528   case llvm::Triple::wasm32:
    529   case llvm::Triple::wasm64:
    530     return true;
    531   }
    532 }
    533 
    534 // ARM tools start.
    535 
    536 // Get SubArch (vN).
    537 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
    538   llvm::StringRef Arch = Triple.getArchName();
    539   return llvm::ARM::parseArchVersion(Arch);
    540 }
    541 
    542 // True if M-profile.
    543 static bool isARMMProfile(const llvm::Triple &Triple) {
    544   llvm::StringRef Arch = Triple.getArchName();
    545   unsigned Profile = llvm::ARM::parseArchProfile(Arch);
    546   return Profile == llvm::ARM::PK_M;
    547 }
    548 
    549 // Get Arch/CPU from args.
    550 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
    551                                   llvm::StringRef &CPU, bool FromAs = false) {
    552   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
    553     CPU = A->getValue();
    554   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
    555     Arch = A->getValue();
    556   if (!FromAs)
    557     return;
    558 
    559   for (const Arg *A :
    560        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
    561     StringRef Value = A->getValue();
    562     if (Value.startswith("-mcpu="))
    563       CPU = Value.substr(6);
    564     if (Value.startswith("-march="))
    565       Arch = Value.substr(7);
    566   }
    567 }
    568 
    569 // Handle -mhwdiv=.
    570 // FIXME: Use ARMTargetParser.
    571 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
    572                                 const ArgList &Args, StringRef HWDiv,
    573                                 std::vector<const char *> &Features) {
    574   unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
    575   if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
    576     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
    577 }
    578 
    579 // Handle -mfpu=.
    580 static void getARMFPUFeatures(const Driver &D, const Arg *A,
    581                               const ArgList &Args, StringRef FPU,
    582                               std::vector<const char *> &Features) {
    583   unsigned FPUID = llvm::ARM::parseFPU(FPU);
    584   if (!llvm::ARM::getFPUFeatures(FPUID, Features))
    585     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
    586 }
    587 
    588 // Decode ARM features from string like +[no]featureA+[no]featureB+...
    589 static bool DecodeARMFeatures(const Driver &D, StringRef text,
    590                               std::vector<const char *> &Features) {
    591   SmallVector<StringRef, 8> Split;
    592   text.split(Split, StringRef("+"), -1, false);
    593 
    594   for (StringRef Feature : Split) {
    595     const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
    596     if (FeatureName)
    597       Features.push_back(FeatureName);
    598     else
    599       return false;
    600   }
    601   return true;
    602 }
    603 
    604 // Check if -march is valid by checking if it can be canonicalised and parsed.
    605 // getARMArch is used here instead of just checking the -march value in order
    606 // to handle -march=native correctly.
    607 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
    608                              llvm::StringRef ArchName,
    609                              std::vector<const char *> &Features,
    610                              const llvm::Triple &Triple) {
    611   std::pair<StringRef, StringRef> Split = ArchName.split("+");
    612 
    613   std::string MArch = arm::getARMArch(ArchName, Triple);
    614   if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
    615       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
    616     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
    617 }
    618 
    619 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
    620 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
    621                             llvm::StringRef CPUName, llvm::StringRef ArchName,
    622                             std::vector<const char *> &Features,
    623                             const llvm::Triple &Triple) {
    624   std::pair<StringRef, StringRef> Split = CPUName.split("+");
    625 
    626   std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
    627   if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
    628       (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
    629     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
    630 }
    631 
    632 static bool useAAPCSForMachO(const llvm::Triple &T) {
    633   // The backend is hardwired to assume AAPCS for M-class processors, ensure
    634   // the frontend matches that.
    635   return T.getEnvironment() == llvm::Triple::EABI ||
    636          T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
    637 }
    638 
    639 // Select the float ABI as determined by -msoft-float, -mhard-float, and
    640 // -mfloat-abi=.
    641 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
    642   const Driver &D = TC.getDriver();
    643   const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
    644   auto SubArch = getARMSubArchVersionNumber(Triple);
    645   arm::FloatABI ABI = FloatABI::Invalid;
    646   if (Arg *A =
    647           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
    648                           options::OPT_mfloat_abi_EQ)) {
    649     if (A->getOption().matches(options::OPT_msoft_float)) {
    650       ABI = FloatABI::Soft;
    651     } else if (A->getOption().matches(options::OPT_mhard_float)) {
    652       ABI = FloatABI::Hard;
    653     } else {
    654       ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
    655                 .Case("soft", FloatABI::Soft)
    656                 .Case("softfp", FloatABI::SoftFP)
    657                 .Case("hard", FloatABI::Hard)
    658                 .Default(FloatABI::Invalid);
    659       if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
    660         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
    661         ABI = FloatABI::Soft;
    662       }
    663     }
    664 
    665     // It is incorrect to select hard float ABI on MachO platforms if the ABI is
    666     // "apcs-gnu".
    667     if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
    668         ABI == FloatABI::Hard) {
    669       D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
    670                                                        << Triple.getArchName();
    671     }
    672   }
    673 
    674   // If unspecified, choose the default based on the platform.
    675   if (ABI == FloatABI::Invalid) {
    676     switch (Triple.getOS()) {
    677     case llvm::Triple::Darwin:
    678     case llvm::Triple::MacOSX:
    679     case llvm::Triple::IOS:
    680     case llvm::Triple::TvOS: {
    681       // Darwin defaults to "softfp" for v6 and v7.
    682       ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
    683       break;
    684     }
    685     case llvm::Triple::WatchOS:
    686       ABI = FloatABI::Hard;
    687       break;
    688 
    689     // FIXME: this is invalid for WindowsCE
    690     case llvm::Triple::Win32:
    691       ABI = FloatABI::Hard;
    692       break;
    693 
    694     case llvm::Triple::FreeBSD:
    695       switch (Triple.getEnvironment()) {
    696       case llvm::Triple::GNUEABIHF:
    697         ABI = FloatABI::Hard;
    698         break;
    699       default:
    700         // FreeBSD defaults to soft float
    701         ABI = FloatABI::Soft;
    702         break;
    703       }
    704       break;
    705 
    706     default:
    707       switch (Triple.getEnvironment()) {
    708       case llvm::Triple::GNUEABIHF:
    709       case llvm::Triple::EABIHF:
    710         ABI = FloatABI::Hard;
    711         break;
    712       case llvm::Triple::GNUEABI:
    713       case llvm::Triple::EABI:
    714         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
    715         ABI = FloatABI::SoftFP;
    716         break;
    717       case llvm::Triple::Android:
    718         ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
    719         break;
    720       default:
    721         // Assume "soft", but warn the user we are guessing.
    722         ABI = FloatABI::Soft;
    723         if (Triple.getOS() != llvm::Triple::UnknownOS ||
    724             !Triple.isOSBinFormatMachO())
    725           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
    726         break;
    727       }
    728     }
    729   }
    730 
    731   assert(ABI != FloatABI::Invalid && "must select an ABI");
    732   return ABI;
    733 }
    734 
    735 static void getARMTargetFeatures(const ToolChain &TC,
    736                                  const llvm::Triple &Triple,
    737                                  const ArgList &Args,
    738                                  std::vector<const char *> &Features,
    739                                  bool ForAS) {
    740   const Driver &D = TC.getDriver();
    741 
    742   bool KernelOrKext =
    743       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
    744   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
    745   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
    746   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
    747 
    748   if (!ForAS) {
    749     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
    750     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
    751     // stripped out by the ARM target. We should probably pass this a new
    752     // -target-option, which is handled by the -cc1/-cc1as invocation.
    753     //
    754     // FIXME2:  For consistency, it would be ideal if we set up the target
    755     // machine state the same when using the frontend or the assembler. We don't
    756     // currently do that for the assembler, we pass the options directly to the
    757     // backend and never even instantiate the frontend TargetInfo. If we did,
    758     // and used its handleTargetFeatures hook, then we could ensure the
    759     // assembler and the frontend behave the same.
    760 
    761     // Use software floating point operations?
    762     if (ABI == arm::FloatABI::Soft)
    763       Features.push_back("+soft-float");
    764 
    765     // Use software floating point argument passing?
    766     if (ABI != arm::FloatABI::Hard)
    767       Features.push_back("+soft-float-abi");
    768   } else {
    769     // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
    770     // to the assembler correctly.
    771     for (const Arg *A :
    772          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
    773       StringRef Value = A->getValue();
    774       if (Value.startswith("-mfpu=")) {
    775         WaFPU = A;
    776       } else if (Value.startswith("-mcpu=")) {
    777         WaCPU = A;
    778       } else if (Value.startswith("-mhwdiv=")) {
    779         WaHDiv = A;
    780       } else if (Value.startswith("-march=")) {
    781         WaArch = A;
    782       }
    783     }
    784   }
    785 
    786   // Check -march. ClangAs gives preference to -Wa,-march=.
    787   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
    788   StringRef ArchName;
    789   if (WaArch) {
    790     if (ArchArg)
    791       D.Diag(clang::diag::warn_drv_unused_argument)
    792           << ArchArg->getAsString(Args);
    793     ArchName = StringRef(WaArch->getValue()).substr(7);
    794     checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
    795     // FIXME: Set Arch.
    796     D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
    797   } else if (ArchArg) {
    798     ArchName = ArchArg->getValue();
    799     checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
    800   }
    801 
    802   // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
    803   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
    804   StringRef CPUName;
    805   if (WaCPU) {
    806     if (CPUArg)
    807       D.Diag(clang::diag::warn_drv_unused_argument)
    808           << CPUArg->getAsString(Args);
    809     CPUName = StringRef(WaCPU->getValue()).substr(6);
    810     checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
    811   } else if (CPUArg) {
    812     CPUName = CPUArg->getValue();
    813     checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
    814   }
    815 
    816   // Add CPU features for generic CPUs
    817   if (CPUName == "native") {
    818     llvm::StringMap<bool> HostFeatures;
    819     if (llvm::sys::getHostCPUFeatures(HostFeatures))
    820       for (auto &F : HostFeatures)
    821         Features.push_back(
    822             Args.MakeArgString((F.second ? "+" : "-") + F.first()));
    823   }
    824 
    825   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
    826   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
    827   if (WaFPU) {
    828     if (FPUArg)
    829       D.Diag(clang::diag::warn_drv_unused_argument)
    830           << FPUArg->getAsString(Args);
    831     getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
    832                       Features);
    833   } else if (FPUArg) {
    834     getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
    835   }
    836 
    837   // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
    838   const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
    839   if (WaHDiv) {
    840     if (HDivArg)
    841       D.Diag(clang::diag::warn_drv_unused_argument)
    842           << HDivArg->getAsString(Args);
    843     getARMHWDivFeatures(D, WaHDiv, Args,
    844                         StringRef(WaHDiv->getValue()).substr(8), Features);
    845   } else if (HDivArg)
    846     getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
    847 
    848   // Setting -msoft-float effectively disables NEON because of the GCC
    849   // implementation, although the same isn't true of VFP or VFP3.
    850   if (ABI == arm::FloatABI::Soft) {
    851     Features.push_back("-neon");
    852     // Also need to explicitly disable features which imply NEON.
    853     Features.push_back("-crypto");
    854   }
    855 
    856   // En/disable crc code generation.
    857   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
    858     if (A->getOption().matches(options::OPT_mcrc))
    859       Features.push_back("+crc");
    860     else
    861       Features.push_back("-crc");
    862   }
    863 
    864   if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
    865     Features.insert(Features.begin(), "+v8.1a");
    866   }
    867 
    868   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
    869   // neither options are specified, see if we are compiling for kernel/kext and
    870   // decide whether to pass "+long-calls" based on the OS and its version.
    871   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
    872                                options::OPT_mno_long_calls)) {
    873     if (A->getOption().matches(options::OPT_mlong_calls))
    874       Features.push_back("+long-calls");
    875   } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
    876              !Triple.isWatchOS()) {
    877       Features.push_back("+long-calls");
    878   }
    879 
    880   // Kernel code has more strict alignment requirements.
    881   if (KernelOrKext)
    882     Features.push_back("+strict-align");
    883   else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
    884                                     options::OPT_munaligned_access)) {
    885     if (A->getOption().matches(options::OPT_munaligned_access)) {
    886       // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
    887       if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
    888         D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
    889     } else
    890       Features.push_back("+strict-align");
    891   } else {
    892     // Assume pre-ARMv6 doesn't support unaligned accesses.
    893     //
    894     // ARMv6 may or may not support unaligned accesses depending on the
    895     // SCTLR.U bit, which is architecture-specific. We assume ARMv6
    896     // Darwin and NetBSD targets support unaligned accesses, and others don't.
    897     //
    898     // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
    899     // which raises an alignment fault on unaligned accesses. Linux
    900     // defaults this bit to 0 and handles it as a system-wide (not
    901     // per-process) setting. It is therefore safe to assume that ARMv7+
    902     // Linux targets support unaligned accesses. The same goes for NaCl.
    903     //
    904     // The above behavior is consistent with GCC.
    905     int VersionNum = getARMSubArchVersionNumber(Triple);
    906     if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
    907       if (VersionNum < 6 ||
    908           Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
    909         Features.push_back("+strict-align");
    910     } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
    911       if (VersionNum < 7)
    912         Features.push_back("+strict-align");
    913     } else
    914       Features.push_back("+strict-align");
    915   }
    916 
    917   // llvm does not support reserving registers in general. There is support
    918   // for reserving r9 on ARM though (defined as a platform-specific register
    919   // in ARM EABI).
    920   if (Args.hasArg(options::OPT_ffixed_r9))
    921     Features.push_back("+reserve-r9");
    922 
    923   // The kext linker doesn't know how to deal with movw/movt.
    924   if (KernelOrKext)
    925     Features.push_back("+no-movt");
    926 }
    927 
    928 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
    929                              ArgStringList &CmdArgs, bool KernelOrKext) const {
    930   // Select the ABI to use.
    931   // FIXME: Support -meabi.
    932   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
    933   const char *ABIName = nullptr;
    934   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
    935     ABIName = A->getValue();
    936   } else if (Triple.isOSBinFormatMachO()) {
    937     if (useAAPCSForMachO(Triple)) {
    938       ABIName = "aapcs";
    939     } else if (Triple.isWatchOS()) {
    940       ABIName = "aapcs16";
    941     } else {
    942       ABIName = "apcs-gnu";
    943     }
    944   } else if (Triple.isOSWindows()) {
    945     // FIXME: this is invalid for WindowsCE
    946     ABIName = "aapcs";
    947   } else {
    948     // Select the default based on the platform.
    949     switch (Triple.getEnvironment()) {
    950     case llvm::Triple::Android:
    951     case llvm::Triple::GNUEABI:
    952     case llvm::Triple::GNUEABIHF:
    953       ABIName = "aapcs-linux";
    954       break;
    955     case llvm::Triple::EABIHF:
    956     case llvm::Triple::EABI:
    957       ABIName = "aapcs";
    958       break;
    959     default:
    960       if (Triple.getOS() == llvm::Triple::NetBSD)
    961         ABIName = "apcs-gnu";
    962       else
    963         ABIName = "aapcs";
    964       break;
    965     }
    966   }
    967   CmdArgs.push_back("-target-abi");
    968   CmdArgs.push_back(ABIName);
    969 
    970   // Determine floating point ABI from the options & target defaults.
    971   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
    972   if (ABI == arm::FloatABI::Soft) {
    973     // Floating point operations and argument passing are soft.
    974     // FIXME: This changes CPP defines, we need -target-soft-float.
    975     CmdArgs.push_back("-msoft-float");
    976     CmdArgs.push_back("-mfloat-abi");
    977     CmdArgs.push_back("soft");
    978   } else if (ABI == arm::FloatABI::SoftFP) {
    979     // Floating point operations are hard, but argument passing is soft.
    980     CmdArgs.push_back("-mfloat-abi");
    981     CmdArgs.push_back("soft");
    982   } else {
    983     // Floating point operations and argument passing are hard.
    984     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
    985     CmdArgs.push_back("-mfloat-abi");
    986     CmdArgs.push_back("hard");
    987   }
    988 
    989   // Forward the -mglobal-merge option for explicit control over the pass.
    990   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
    991                                options::OPT_mno_global_merge)) {
    992     CmdArgs.push_back("-backend-option");
    993     if (A->getOption().matches(options::OPT_mno_global_merge))
    994       CmdArgs.push_back("-arm-global-merge=false");
    995     else
    996       CmdArgs.push_back("-arm-global-merge=true");
    997   }
    998 
    999   if (!Args.hasFlag(options::OPT_mimplicit_float,
   1000                     options::OPT_mno_implicit_float, true))
   1001     CmdArgs.push_back("-no-implicit-float");
   1002 }
   1003 // ARM tools end.
   1004 
   1005 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
   1006 /// targeting.
   1007 static std::string getAArch64TargetCPU(const ArgList &Args) {
   1008   Arg *A;
   1009   std::string CPU;
   1010   // If we have -mtune or -mcpu, use that.
   1011   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
   1012     CPU = StringRef(A->getValue()).lower();
   1013   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
   1014     StringRef Mcpu = A->getValue();
   1015     CPU = Mcpu.split("+").first.lower();
   1016   }
   1017 
   1018   // Handle CPU name is 'native'.
   1019   if (CPU == "native")
   1020     return llvm::sys::getHostCPUName();
   1021   else if (CPU.size())
   1022     return CPU;
   1023 
   1024   // Make sure we pick "cyclone" if -arch is used.
   1025   // FIXME: Should this be picked by checking the target triple instead?
   1026   if (Args.getLastArg(options::OPT_arch))
   1027     return "cyclone";
   1028 
   1029   return "generic";
   1030 }
   1031 
   1032 void Clang::AddAArch64TargetArgs(const ArgList &Args,
   1033                                  ArgStringList &CmdArgs) const {
   1034   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
   1035   llvm::Triple Triple(TripleStr);
   1036 
   1037   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
   1038       Args.hasArg(options::OPT_mkernel) ||
   1039       Args.hasArg(options::OPT_fapple_kext))
   1040     CmdArgs.push_back("-disable-red-zone");
   1041 
   1042   if (!Args.hasFlag(options::OPT_mimplicit_float,
   1043                     options::OPT_mno_implicit_float, true))
   1044     CmdArgs.push_back("-no-implicit-float");
   1045 
   1046   const char *ABIName = nullptr;
   1047   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
   1048     ABIName = A->getValue();
   1049   else if (Triple.isOSDarwin())
   1050     ABIName = "darwinpcs";
   1051   else
   1052     ABIName = "aapcs";
   1053 
   1054   CmdArgs.push_back("-target-abi");
   1055   CmdArgs.push_back(ABIName);
   1056 
   1057   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
   1058                                options::OPT_mno_fix_cortex_a53_835769)) {
   1059     CmdArgs.push_back("-backend-option");
   1060     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
   1061       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
   1062     else
   1063       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
   1064   } else if (Triple.isAndroid()) {
   1065     // Enabled A53 errata (835769) workaround by default on android
   1066     CmdArgs.push_back("-backend-option");
   1067     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
   1068   }
   1069 
   1070   // Forward the -mglobal-merge option for explicit control over the pass.
   1071   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
   1072                                options::OPT_mno_global_merge)) {
   1073     CmdArgs.push_back("-backend-option");
   1074     if (A->getOption().matches(options::OPT_mno_global_merge))
   1075       CmdArgs.push_back("-aarch64-global-merge=false");
   1076     else
   1077       CmdArgs.push_back("-aarch64-global-merge=true");
   1078   }
   1079 }
   1080 
   1081 // Get CPU and ABI names. They are not independent
   1082 // so we have to calculate them together.
   1083 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
   1084                             StringRef &CPUName, StringRef &ABIName) {
   1085   const char *DefMips32CPU = "mips32r2";
   1086   const char *DefMips64CPU = "mips64r2";
   1087 
   1088   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
   1089   // default for mips64(el)?-img-linux-gnu.
   1090   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
   1091       Triple.getEnvironment() == llvm::Triple::GNU) {
   1092     DefMips32CPU = "mips32r6";
   1093     DefMips64CPU = "mips64r6";
   1094   }
   1095 
   1096   // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
   1097   if (Triple.isAndroid())
   1098     DefMips64CPU = "mips64r6";
   1099 
   1100   // MIPS3 is the default for mips64*-unknown-openbsd.
   1101   if (Triple.getOS() == llvm::Triple::OpenBSD)
   1102     DefMips64CPU = "mips3";
   1103 
   1104   if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
   1105     CPUName = A->getValue();
   1106 
   1107   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
   1108     ABIName = A->getValue();
   1109     // Convert a GNU style Mips ABI name to the name
   1110     // accepted by LLVM Mips backend.
   1111     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
   1112                   .Case("32", "o32")
   1113                   .Case("64", "n64")
   1114                   .Default(ABIName);
   1115   }
   1116 
   1117   // Setup default CPU and ABI names.
   1118   if (CPUName.empty() && ABIName.empty()) {
   1119     switch (Triple.getArch()) {
   1120     default:
   1121       llvm_unreachable("Unexpected triple arch name");
   1122     case llvm::Triple::mips:
   1123     case llvm::Triple::mipsel:
   1124       CPUName = DefMips32CPU;
   1125       break;
   1126     case llvm::Triple::mips64:
   1127     case llvm::Triple::mips64el:
   1128       CPUName = DefMips64CPU;
   1129       break;
   1130     }
   1131   }
   1132 
   1133   if (ABIName.empty()) {
   1134     // Deduce ABI name from the target triple.
   1135     if (Triple.getArch() == llvm::Triple::mips ||
   1136         Triple.getArch() == llvm::Triple::mipsel)
   1137       ABIName = "o32";
   1138     else
   1139       ABIName = "n64";
   1140   }
   1141 
   1142   if (CPUName.empty()) {
   1143     // Deduce CPU name from ABI name.
   1144     CPUName = llvm::StringSwitch<const char *>(ABIName)
   1145                   .Cases("o32", "eabi", DefMips32CPU)
   1146                   .Cases("n32", "n64", DefMips64CPU)
   1147                   .Default("");
   1148   }
   1149 
   1150   // FIXME: Warn on inconsistent use of -march and -mabi.
   1151 }
   1152 
   1153 std::string mips::getMipsABILibSuffix(const ArgList &Args,
   1154                                       const llvm::Triple &Triple) {
   1155   StringRef CPUName, ABIName;
   1156   tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
   1157   return llvm::StringSwitch<std::string>(ABIName)
   1158       .Case("o32", "")
   1159       .Case("n32", "32")
   1160       .Case("n64", "64");
   1161 }
   1162 
   1163 // Convert ABI name to the GNU tools acceptable variant.
   1164 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
   1165   return llvm::StringSwitch<llvm::StringRef>(ABI)
   1166       .Case("o32", "32")
   1167       .Case("n64", "64")
   1168       .Default(ABI);
   1169 }
   1170 
   1171 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
   1172 // and -mfloat-abi=.
   1173 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
   1174   mips::FloatABI ABI = mips::FloatABI::Invalid;
   1175   if (Arg *A =
   1176           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
   1177                           options::OPT_mfloat_abi_EQ)) {
   1178     if (A->getOption().matches(options::OPT_msoft_float))
   1179       ABI = mips::FloatABI::Soft;
   1180     else if (A->getOption().matches(options::OPT_mhard_float))
   1181       ABI = mips::FloatABI::Hard;
   1182     else {
   1183       ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
   1184                 .Case("soft", mips::FloatABI::Soft)
   1185                 .Case("hard", mips::FloatABI::Hard)
   1186                 .Default(mips::FloatABI::Invalid);
   1187       if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
   1188         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
   1189         ABI = mips::FloatABI::Hard;
   1190       }
   1191     }
   1192   }
   1193 
   1194   // If unspecified, choose the default based on the platform.
   1195   if (ABI == mips::FloatABI::Invalid) {
   1196     // Assume "hard", because it's a default value used by gcc.
   1197     // When we start to recognize specific target MIPS processors,
   1198     // we will be able to select the default more correctly.
   1199     ABI = mips::FloatABI::Hard;
   1200   }
   1201 
   1202   assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
   1203   return ABI;
   1204 }
   1205 
   1206 static void AddTargetFeature(const ArgList &Args,
   1207                              std::vector<const char *> &Features,
   1208                              OptSpecifier OnOpt, OptSpecifier OffOpt,
   1209                              StringRef FeatureName) {
   1210   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
   1211     if (A->getOption().matches(OnOpt))
   1212       Features.push_back(Args.MakeArgString("+" + FeatureName));
   1213     else
   1214       Features.push_back(Args.MakeArgString("-" + FeatureName));
   1215   }
   1216 }
   1217 
   1218 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
   1219                                   const ArgList &Args,
   1220                                   std::vector<const char *> &Features) {
   1221   StringRef CPUName;
   1222   StringRef ABIName;
   1223   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
   1224   ABIName = getGnuCompatibleMipsABIName(ABIName);
   1225 
   1226   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
   1227                    options::OPT_mabicalls, "noabicalls");
   1228 
   1229   mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
   1230   if (FloatABI == mips::FloatABI::Soft) {
   1231     // FIXME: Note, this is a hack. We need to pass the selected float
   1232     // mode to the MipsTargetInfoBase to define appropriate macros there.
   1233     // Now it is the only method.
   1234     Features.push_back("+soft-float");
   1235   }
   1236 
   1237   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
   1238     StringRef Val = StringRef(A->getValue());
   1239     if (Val == "2008") {
   1240       if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
   1241         Features.push_back("+nan2008");
   1242       else {
   1243         Features.push_back("-nan2008");
   1244         D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
   1245       }
   1246     } else if (Val == "legacy") {
   1247       if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
   1248         Features.push_back("-nan2008");
   1249       else {
   1250         Features.push_back("+nan2008");
   1251         D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
   1252       }
   1253     } else
   1254       D.Diag(diag::err_drv_unsupported_option_argument)
   1255           << A->getOption().getName() << Val;
   1256   }
   1257 
   1258   AddTargetFeature(Args, Features, options::OPT_msingle_float,
   1259                    options::OPT_mdouble_float, "single-float");
   1260   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
   1261                    "mips16");
   1262   AddTargetFeature(Args, Features, options::OPT_mmicromips,
   1263                    options::OPT_mno_micromips, "micromips");
   1264   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
   1265                    "dsp");
   1266   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
   1267                    "dspr2");
   1268   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
   1269                    "msa");
   1270 
   1271   // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
   1272   // pass -mfpxx
   1273   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
   1274                                options::OPT_mfp64)) {
   1275     if (A->getOption().matches(options::OPT_mfp32))
   1276       Features.push_back(Args.MakeArgString("-fp64"));
   1277     else if (A->getOption().matches(options::OPT_mfpxx)) {
   1278       Features.push_back(Args.MakeArgString("+fpxx"));
   1279       Features.push_back(Args.MakeArgString("+nooddspreg"));
   1280     } else
   1281       Features.push_back(Args.MakeArgString("+fp64"));
   1282   } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
   1283     Features.push_back(Args.MakeArgString("+fpxx"));
   1284     Features.push_back(Args.MakeArgString("+nooddspreg"));
   1285   }
   1286 
   1287   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
   1288                    options::OPT_modd_spreg, "nooddspreg");
   1289 }
   1290 
   1291 void Clang::AddMIPSTargetArgs(const ArgList &Args,
   1292                               ArgStringList &CmdArgs) const {
   1293   const Driver &D = getToolChain().getDriver();
   1294   StringRef CPUName;
   1295   StringRef ABIName;
   1296   const llvm::Triple &Triple = getToolChain().getTriple();
   1297   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
   1298 
   1299   CmdArgs.push_back("-target-abi");
   1300   CmdArgs.push_back(ABIName.data());
   1301 
   1302   mips::FloatABI ABI = getMipsFloatABI(D, Args);
   1303   if (ABI == mips::FloatABI::Soft) {
   1304     // Floating point operations and argument passing are soft.
   1305     CmdArgs.push_back("-msoft-float");
   1306     CmdArgs.push_back("-mfloat-abi");
   1307     CmdArgs.push_back("soft");
   1308   } else {
   1309     // Floating point operations and argument passing are hard.
   1310     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
   1311     CmdArgs.push_back("-mfloat-abi");
   1312     CmdArgs.push_back("hard");
   1313   }
   1314 
   1315   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
   1316     if (A->getOption().matches(options::OPT_mxgot)) {
   1317       CmdArgs.push_back("-mllvm");
   1318       CmdArgs.push_back("-mxgot");
   1319     }
   1320   }
   1321 
   1322   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
   1323                                options::OPT_mno_ldc1_sdc1)) {
   1324     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
   1325       CmdArgs.push_back("-mllvm");
   1326       CmdArgs.push_back("-mno-ldc1-sdc1");
   1327     }
   1328   }
   1329 
   1330   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
   1331                                options::OPT_mno_check_zero_division)) {
   1332     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
   1333       CmdArgs.push_back("-mllvm");
   1334       CmdArgs.push_back("-mno-check-zero-division");
   1335     }
   1336   }
   1337 
   1338   if (Arg *A = Args.getLastArg(options::OPT_G)) {
   1339     StringRef v = A->getValue();
   1340     CmdArgs.push_back("-mllvm");
   1341     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
   1342     A->claim();
   1343   }
   1344 }
   1345 
   1346 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
   1347 static std::string getPPCTargetCPU(const ArgList &Args) {
   1348   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
   1349     StringRef CPUName = A->getValue();
   1350 
   1351     if (CPUName == "native") {
   1352       std::string CPU = llvm::sys::getHostCPUName();
   1353       if (!CPU.empty() && CPU != "generic")
   1354         return CPU;
   1355       else
   1356         return "";
   1357     }
   1358 
   1359     return llvm::StringSwitch<const char *>(CPUName)
   1360         .Case("common", "generic")
   1361         .Case("440", "440")
   1362         .Case("440fp", "440")
   1363         .Case("450", "450")
   1364         .Case("601", "601")
   1365         .Case("602", "602")
   1366         .Case("603", "603")
   1367         .Case("603e", "603e")
   1368         .Case("603ev", "603ev")
   1369         .Case("604", "604")
   1370         .Case("604e", "604e")
   1371         .Case("620", "620")
   1372         .Case("630", "pwr3")
   1373         .Case("G3", "g3")
   1374         .Case("7400", "7400")
   1375         .Case("G4", "g4")
   1376         .Case("7450", "7450")
   1377         .Case("G4+", "g4+")
   1378         .Case("750", "750")
   1379         .Case("970", "970")
   1380         .Case("G5", "g5")
   1381         .Case("a2", "a2")
   1382         .Case("a2q", "a2q")
   1383         .Case("e500mc", "e500mc")
   1384         .Case("e5500", "e5500")
   1385         .Case("power3", "pwr3")
   1386         .Case("power4", "pwr4")
   1387         .Case("power5", "pwr5")
   1388         .Case("power5x", "pwr5x")
   1389         .Case("power6", "pwr6")
   1390         .Case("power6x", "pwr6x")
   1391         .Case("power7", "pwr7")
   1392         .Case("power8", "pwr8")
   1393         .Case("pwr3", "pwr3")
   1394         .Case("pwr4", "pwr4")
   1395         .Case("pwr5", "pwr5")
   1396         .Case("pwr5x", "pwr5x")
   1397         .Case("pwr6", "pwr6")
   1398         .Case("pwr6x", "pwr6x")
   1399         .Case("pwr7", "pwr7")
   1400         .Case("pwr8", "pwr8")
   1401         .Case("powerpc", "ppc")
   1402         .Case("powerpc64", "ppc64")
   1403         .Case("powerpc64le", "ppc64le")
   1404         .Default("");
   1405   }
   1406 
   1407   return "";
   1408 }
   1409 
   1410 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
   1411                                  const ArgList &Args,
   1412                                  std::vector<const char *> &Features) {
   1413   for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
   1414     StringRef Name = A->getOption().getName();
   1415     A->claim();
   1416 
   1417     // Skip over "-m".
   1418     assert(Name.startswith("m") && "Invalid feature name.");
   1419     Name = Name.substr(1);
   1420 
   1421     bool IsNegative = Name.startswith("no-");
   1422     if (IsNegative)
   1423       Name = Name.substr(3);
   1424     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
   1425   }
   1426 
   1427   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
   1428   if (FloatABI == ppc::FloatABI::Soft &&
   1429       !(Triple.getArch() == llvm::Triple::ppc64 ||
   1430         Triple.getArch() == llvm::Triple::ppc64le))
   1431     Features.push_back("+soft-float");
   1432   else if (FloatABI == ppc::FloatABI::Soft &&
   1433            (Triple.getArch() == llvm::Triple::ppc64 ||
   1434             Triple.getArch() == llvm::Triple::ppc64le))
   1435     D.Diag(diag::err_drv_invalid_mfloat_abi)
   1436         << "soft float is not supported for ppc64";
   1437 
   1438   // Altivec is a bit weird, allow overriding of the Altivec feature here.
   1439   AddTargetFeature(Args, Features, options::OPT_faltivec,
   1440                    options::OPT_fno_altivec, "altivec");
   1441 }
   1442 
   1443 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
   1444   ppc::FloatABI ABI = ppc::FloatABI::Invalid;
   1445   if (Arg *A =
   1446           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
   1447                           options::OPT_mfloat_abi_EQ)) {
   1448     if (A->getOption().matches(options::OPT_msoft_float))
   1449       ABI = ppc::FloatABI::Soft;
   1450     else if (A->getOption().matches(options::OPT_mhard_float))
   1451       ABI = ppc::FloatABI::Hard;
   1452     else {
   1453       ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
   1454                 .Case("soft", ppc::FloatABI::Soft)
   1455                 .Case("hard", ppc::FloatABI::Hard)
   1456                 .Default(ppc::FloatABI::Invalid);
   1457       if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
   1458         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
   1459         ABI = ppc::FloatABI::Hard;
   1460       }
   1461     }
   1462   }
   1463 
   1464   // If unspecified, choose the default based on the platform.
   1465   if (ABI == ppc::FloatABI::Invalid) {
   1466     ABI = ppc::FloatABI::Hard;
   1467   }
   1468 
   1469   return ABI;
   1470 }
   1471 
   1472 void Clang::AddPPCTargetArgs(const ArgList &Args,
   1473                              ArgStringList &CmdArgs) const {
   1474   // Select the ABI to use.
   1475   const char *ABIName = nullptr;
   1476   if (getToolChain().getTriple().isOSLinux())
   1477     switch (getToolChain().getArch()) {
   1478     case llvm::Triple::ppc64: {
   1479       // When targeting a processor that supports QPX, or if QPX is
   1480       // specifically enabled, default to using the ABI that supports QPX (so
   1481       // long as it is not specifically disabled).
   1482       bool HasQPX = false;
   1483       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
   1484         HasQPX = A->getValue() == StringRef("a2q");
   1485       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
   1486       if (HasQPX) {
   1487         ABIName = "elfv1-qpx";
   1488         break;
   1489       }
   1490 
   1491       ABIName = "elfv1";
   1492       break;
   1493     }
   1494     case llvm::Triple::ppc64le:
   1495       ABIName = "elfv2";
   1496       break;
   1497     default:
   1498       break;
   1499     }
   1500 
   1501   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
   1502     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
   1503     // the option if given as we don't have backend support for any targets
   1504     // that don't use the altivec abi.
   1505     if (StringRef(A->getValue()) != "altivec")
   1506       ABIName = A->getValue();
   1507 
   1508   ppc::FloatABI FloatABI =
   1509       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
   1510 
   1511   if (FloatABI == ppc::FloatABI::Soft) {
   1512     // Floating point operations and argument passing are soft.
   1513     CmdArgs.push_back("-msoft-float");
   1514     CmdArgs.push_back("-mfloat-abi");
   1515     CmdArgs.push_back("soft");
   1516   } else {
   1517     // Floating point operations and argument passing are hard.
   1518     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
   1519     CmdArgs.push_back("-mfloat-abi");
   1520     CmdArgs.push_back("hard");
   1521   }
   1522 
   1523   if (ABIName) {
   1524     CmdArgs.push_back("-target-abi");
   1525     CmdArgs.push_back(ABIName);
   1526   }
   1527 }
   1528 
   1529 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
   1530   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
   1531   return A && (A->getValue() == StringRef(Value));
   1532 }
   1533 
   1534 /// Get the (LLVM) name of the R600 gpu we are targeting.
   1535 static std::string getR600TargetGPU(const ArgList &Args) {
   1536   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
   1537     const char *GPUName = A->getValue();
   1538     return llvm::StringSwitch<const char *>(GPUName)
   1539         .Cases("rv630", "rv635", "r600")
   1540         .Cases("rv610", "rv620", "rs780", "rs880")
   1541         .Case("rv740", "rv770")
   1542         .Case("palm", "cedar")
   1543         .Cases("sumo", "sumo2", "sumo")
   1544         .Case("hemlock", "cypress")
   1545         .Case("aruba", "cayman")
   1546         .Default(GPUName);
   1547   }
   1548   return "";
   1549 }
   1550 
   1551 void Clang::AddSparcTargetArgs(const ArgList &Args,
   1552                                ArgStringList &CmdArgs) const {
   1553   const Driver &D = getToolChain().getDriver();
   1554   std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
   1555 
   1556   bool SoftFloatABI = false;
   1557   if (Arg *A =
   1558           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
   1559     if (A->getOption().matches(options::OPT_msoft_float))
   1560       SoftFloatABI = true;
   1561   }
   1562 
   1563   // Only the hard-float ABI on Sparc is standardized, and it is the
   1564   // default. GCC also supports a nonstandard soft-float ABI mode, and
   1565   // perhaps LLVM should implement that, too. However, since llvm
   1566   // currently does not support Sparc soft-float, at all, display an
   1567   // error if it's requested.
   1568   if (SoftFloatABI) {
   1569     D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
   1570                                                      << Triple;
   1571   }
   1572 }
   1573 
   1574 static const char *getSystemZTargetCPU(const ArgList &Args) {
   1575   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
   1576     return A->getValue();
   1577   return "z10";
   1578 }
   1579 
   1580 static void getSystemZTargetFeatures(const ArgList &Args,
   1581                                      std::vector<const char *> &Features) {
   1582   // -m(no-)htm overrides use of the transactional-execution facility.
   1583   if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
   1584     if (A->getOption().matches(options::OPT_mhtm))
   1585       Features.push_back("+transactional-execution");
   1586     else
   1587       Features.push_back("-transactional-execution");
   1588   }
   1589   // -m(no-)vx overrides use of the vector facility.
   1590   if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
   1591     if (A->getOption().matches(options::OPT_mvx))
   1592       Features.push_back("+vector");
   1593     else
   1594       Features.push_back("-vector");
   1595   }
   1596 }
   1597 
   1598 static const char *getX86TargetCPU(const ArgList &Args,
   1599                                    const llvm::Triple &Triple) {
   1600   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
   1601     if (StringRef(A->getValue()) != "native") {
   1602       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
   1603         return "core-avx2";
   1604 
   1605       return A->getValue();
   1606     }
   1607 
   1608     // FIXME: Reject attempts to use -march=native unless the target matches
   1609     // the host.
   1610     //
   1611     // FIXME: We should also incorporate the detected target features for use
   1612     // with -native.
   1613     std::string CPU = llvm::sys::getHostCPUName();
   1614     if (!CPU.empty() && CPU != "generic")
   1615       return Args.MakeArgString(CPU);
   1616   }
   1617 
   1618   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
   1619     // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
   1620     StringRef Arch = A->getValue();
   1621     const char *CPU;
   1622     if (Triple.getArch() == llvm::Triple::x86) {
   1623       CPU = llvm::StringSwitch<const char *>(Arch)
   1624                 .Case("IA32", "i386")
   1625                 .Case("SSE", "pentium3")
   1626                 .Case("SSE2", "pentium4")
   1627                 .Case("AVX", "sandybridge")
   1628                 .Case("AVX2", "haswell")
   1629                 .Default(nullptr);
   1630     } else {
   1631       CPU = llvm::StringSwitch<const char *>(Arch)
   1632                 .Case("AVX", "sandybridge")
   1633                 .Case("AVX2", "haswell")
   1634                 .Default(nullptr);
   1635     }
   1636     if (CPU)
   1637       return CPU;
   1638   }
   1639 
   1640   // Select the default CPU if none was given (or detection failed).
   1641 
   1642   if (Triple.getArch() != llvm::Triple::x86_64 &&
   1643       Triple.getArch() != llvm::Triple::x86)
   1644     return nullptr; // This routine is only handling x86 targets.
   1645 
   1646   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
   1647 
   1648   // FIXME: Need target hooks.
   1649   if (Triple.isOSDarwin()) {
   1650     if (Triple.getArchName() == "x86_64h")
   1651       return "core-avx2";
   1652     return Is64Bit ? "core2" : "yonah";
   1653   }
   1654 
   1655   // Set up default CPU name for PS4 compilers.
   1656   if (Triple.isPS4CPU())
   1657     return "btver2";
   1658 
   1659   // On Android use targets compatible with gcc
   1660   if (Triple.isAndroid())
   1661     return Is64Bit ? "x86-64" : "i686";
   1662 
   1663   // Everything else goes to x86-64 in 64-bit mode.
   1664   if (Is64Bit)
   1665     return "x86-64";
   1666 
   1667   switch (Triple.getOS()) {
   1668   case llvm::Triple::FreeBSD:
   1669   case llvm::Triple::NetBSD:
   1670   case llvm::Triple::OpenBSD:
   1671     return "i486";
   1672   case llvm::Triple::Haiku:
   1673     return "i586";
   1674   case llvm::Triple::Bitrig:
   1675     return "i686";
   1676   default:
   1677     // Fallback to p4.
   1678     return "pentium4";
   1679   }
   1680 }
   1681 
   1682 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
   1683 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
   1684   // If we have -mcpu=, use that.
   1685   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
   1686     StringRef CPU = A->getValue();
   1687 
   1688 #ifdef __wasm__
   1689     // Handle "native" by examining the host. "native" isn't meaningful when
   1690     // cross compiling, so only support this when the host is also WebAssembly.
   1691     if (CPU == "native")
   1692       return llvm::sys::getHostCPUName();
   1693 #endif
   1694 
   1695     return CPU;
   1696   }
   1697 
   1698   return "generic";
   1699 }
   1700 
   1701 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
   1702                               bool FromAs = false) {
   1703   switch (T.getArch()) {
   1704   default:
   1705     return "";
   1706 
   1707   case llvm::Triple::aarch64:
   1708   case llvm::Triple::aarch64_be:
   1709     return getAArch64TargetCPU(Args);
   1710 
   1711   case llvm::Triple::arm:
   1712   case llvm::Triple::armeb:
   1713   case llvm::Triple::thumb:
   1714   case llvm::Triple::thumbeb: {
   1715     StringRef MArch, MCPU;
   1716     getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
   1717     return arm::getARMTargetCPU(MCPU, MArch, T);
   1718   }
   1719   case llvm::Triple::mips:
   1720   case llvm::Triple::mipsel:
   1721   case llvm::Triple::mips64:
   1722   case llvm::Triple::mips64el: {
   1723     StringRef CPUName;
   1724     StringRef ABIName;
   1725     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
   1726     return CPUName;
   1727   }
   1728 
   1729   case llvm::Triple::nvptx:
   1730   case llvm::Triple::nvptx64:
   1731     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
   1732       return A->getValue();
   1733     return "";
   1734 
   1735   case llvm::Triple::ppc:
   1736   case llvm::Triple::ppc64:
   1737   case llvm::Triple::ppc64le: {
   1738     std::string TargetCPUName = getPPCTargetCPU(Args);
   1739     // LLVM may default to generating code for the native CPU,
   1740     // but, like gcc, we default to a more generic option for
   1741     // each architecture. (except on Darwin)
   1742     if (TargetCPUName.empty() && !T.isOSDarwin()) {
   1743       if (T.getArch() == llvm::Triple::ppc64)
   1744         TargetCPUName = "ppc64";
   1745       else if (T.getArch() == llvm::Triple::ppc64le)
   1746         TargetCPUName = "ppc64le";
   1747       else
   1748         TargetCPUName = "ppc";
   1749     }
   1750     return TargetCPUName;
   1751   }
   1752 
   1753   case llvm::Triple::sparc:
   1754   case llvm::Triple::sparcel:
   1755   case llvm::Triple::sparcv9:
   1756     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
   1757       return A->getValue();
   1758     return "";
   1759 
   1760   case llvm::Triple::x86:
   1761   case llvm::Triple::x86_64:
   1762     return getX86TargetCPU(Args, T);
   1763 
   1764   case llvm::Triple::hexagon:
   1765     return "hexagon" +
   1766            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
   1767 
   1768   case llvm::Triple::systemz:
   1769     return getSystemZTargetCPU(Args);
   1770 
   1771   case llvm::Triple::r600:
   1772   case llvm::Triple::amdgcn:
   1773     return getR600TargetGPU(Args);
   1774 
   1775   case llvm::Triple::wasm32:
   1776   case llvm::Triple::wasm64:
   1777     return getWebAssemblyTargetCPU(Args);
   1778   }
   1779 }
   1780 
   1781 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
   1782                           ArgStringList &CmdArgs, bool IsThinLTO) {
   1783   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
   1784   // as gold requires -plugin to come before any -plugin-opt that -Wl might
   1785   // forward.
   1786   CmdArgs.push_back("-plugin");
   1787   std::string Plugin =
   1788       ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
   1789   CmdArgs.push_back(Args.MakeArgString(Plugin));
   1790 
   1791   // Try to pass driver level flags relevant to LTO code generation down to
   1792   // the plugin.
   1793 
   1794   // Handle flags for selecting CPU variants.
   1795   std::string CPU = getCPUName(Args, ToolChain.getTriple());
   1796   if (!CPU.empty())
   1797     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
   1798 
   1799   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
   1800     StringRef OOpt;
   1801     if (A->getOption().matches(options::OPT_O4) ||
   1802         A->getOption().matches(options::OPT_Ofast))
   1803       OOpt = "3";
   1804     else if (A->getOption().matches(options::OPT_O))
   1805       OOpt = A->getValue();
   1806     else if (A->getOption().matches(options::OPT_O0))
   1807       OOpt = "0";
   1808     if (!OOpt.empty())
   1809       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
   1810   }
   1811 
   1812   if (IsThinLTO)
   1813     CmdArgs.push_back("-plugin-opt=thinlto");
   1814 }
   1815 
   1816 /// This is a helper function for validating the optional refinement step
   1817 /// parameter in reciprocal argument strings. Return false if there is an error
   1818 /// parsing the refinement step. Otherwise, return true and set the Position
   1819 /// of the refinement step in the input string.
   1820 static bool getRefinementStep(StringRef In, const Driver &D,
   1821                               const Arg &A, size_t &Position) {
   1822   const char RefinementStepToken = ':';
   1823   Position = In.find(RefinementStepToken);
   1824   if (Position != StringRef::npos) {
   1825     StringRef Option = A.getOption().getName();
   1826     StringRef RefStep = In.substr(Position + 1);
   1827     // Allow exactly one numeric character for the additional refinement
   1828     // step parameter. This is reasonable for all currently-supported
   1829     // operations and architectures because we would expect that a larger value
   1830     // of refinement steps would cause the estimate "optimization" to
   1831     // under-perform the native operation. Also, if the estimate does not
   1832     // converge quickly, it probably will not ever converge, so further
   1833     // refinement steps will not produce a better answer.
   1834     if (RefStep.size() != 1) {
   1835       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
   1836       return false;
   1837     }
   1838     char RefStepChar = RefStep[0];
   1839     if (RefStepChar < '0' || RefStepChar > '9') {
   1840       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
   1841       return false;
   1842     }
   1843   }
   1844   return true;
   1845 }
   1846 
   1847 /// The -mrecip flag requires processing of many optional parameters.
   1848 static void ParseMRecip(const Driver &D, const ArgList &Args,
   1849                         ArgStringList &OutStrings) {
   1850   StringRef DisabledPrefixIn = "!";
   1851   StringRef DisabledPrefixOut = "!";
   1852   StringRef EnabledPrefixOut = "";
   1853   StringRef Out = "-mrecip=";
   1854 
   1855   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
   1856   if (!A)
   1857     return;
   1858 
   1859   unsigned NumOptions = A->getNumValues();
   1860   if (NumOptions == 0) {
   1861     // No option is the same as "all".
   1862     OutStrings.push_back(Args.MakeArgString(Out + "all"));
   1863     return;
   1864   }
   1865 
   1866   // Pass through "all", "none", or "default" with an optional refinement step.
   1867   if (NumOptions == 1) {
   1868     StringRef Val = A->getValue(0);
   1869     size_t RefStepLoc;
   1870     if (!getRefinementStep(Val, D, *A, RefStepLoc))
   1871       return;
   1872     StringRef ValBase = Val.slice(0, RefStepLoc);
   1873     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
   1874       OutStrings.push_back(Args.MakeArgString(Out + Val));
   1875       return;
   1876     }
   1877   }
   1878 
   1879   // Each reciprocal type may be enabled or disabled individually.
   1880   // Check each input value for validity, concatenate them all back together,
   1881   // and pass through.
   1882 
   1883   llvm::StringMap<bool> OptionStrings;
   1884   OptionStrings.insert(std::make_pair("divd", false));
   1885   OptionStrings.insert(std::make_pair("divf", false));
   1886   OptionStrings.insert(std::make_pair("vec-divd", false));
   1887   OptionStrings.insert(std::make_pair("vec-divf", false));
   1888   OptionStrings.insert(std::make_pair("sqrtd", false));
   1889   OptionStrings.insert(std::make_pair("sqrtf", false));
   1890   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
   1891   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
   1892 
   1893   for (unsigned i = 0; i != NumOptions; ++i) {
   1894     StringRef Val = A->getValue(i);
   1895 
   1896     bool IsDisabled = Val.startswith(DisabledPrefixIn);
   1897     // Ignore the disablement token for string matching.
   1898     if (IsDisabled)
   1899       Val = Val.substr(1);
   1900 
   1901     size_t RefStep;
   1902     if (!getRefinementStep(Val, D, *A, RefStep))
   1903       return;
   1904 
   1905     StringRef ValBase = Val.slice(0, RefStep);
   1906     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
   1907     if (OptionIter == OptionStrings.end()) {
   1908       // Try again specifying float suffix.
   1909       OptionIter = OptionStrings.find(ValBase.str() + 'f');
   1910       if (OptionIter == OptionStrings.end()) {
   1911         // The input name did not match any known option string.
   1912         D.Diag(diag::err_drv_unknown_argument) << Val;
   1913         return;
   1914       }
   1915       // The option was specified without a float or double suffix.
   1916       // Make sure that the double entry was not already specified.
   1917       // The float entry will be checked below.
   1918       if (OptionStrings[ValBase.str() + 'd']) {
   1919         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
   1920         return;
   1921       }
   1922     }
   1923 
   1924     if (OptionIter->second == true) {
   1925       // Duplicate option specified.
   1926       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
   1927       return;
   1928     }
   1929 
   1930     // Mark the matched option as found. Do not allow duplicate specifiers.
   1931     OptionIter->second = true;
   1932 
   1933     // If the precision was not specified, also mark the double entry as found.
   1934     if (ValBase.back() != 'f' && ValBase.back() != 'd')
   1935       OptionStrings[ValBase.str() + 'd'] = true;
   1936 
   1937     // Build the output string.
   1938     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
   1939     Out = Args.MakeArgString(Out + Prefix + Val);
   1940     if (i != NumOptions - 1)
   1941       Out = Args.MakeArgString(Out + ",");
   1942   }
   1943 
   1944   OutStrings.push_back(Args.MakeArgString(Out));
   1945 }
   1946 
   1947 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
   1948                                  const ArgList &Args,
   1949                                  std::vector<const char *> &Features) {
   1950   // If -march=native, autodetect the feature list.
   1951   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
   1952     if (StringRef(A->getValue()) == "native") {
   1953       llvm::StringMap<bool> HostFeatures;
   1954       if (llvm::sys::getHostCPUFeatures(HostFeatures))
   1955         for (auto &F : HostFeatures)
   1956           Features.push_back(
   1957               Args.MakeArgString((F.second ? "+" : "-") + F.first()));
   1958     }
   1959   }
   1960 
   1961   if (Triple.getArchName() == "x86_64h") {
   1962     // x86_64h implies quite a few of the more modern subtarget features
   1963     // for Haswell class CPUs, but not all of them. Opt-out of a few.
   1964     Features.push_back("-rdrnd");
   1965     Features.push_back("-aes");
   1966     Features.push_back("-pclmul");
   1967     Features.push_back("-rtm");
   1968     Features.push_back("-hle");
   1969     Features.push_back("-fsgsbase");
   1970   }
   1971 
   1972   const llvm::Triple::ArchType ArchType = Triple.getArch();
   1973   // Add features to be compatible with gcc for Android.
   1974   if (Triple.isAndroid()) {
   1975     if (ArchType == llvm::Triple::x86_64) {
   1976       Features.push_back("+sse4.2");
   1977       Features.push_back("+popcnt");
   1978     } else
   1979       Features.push_back("+ssse3");
   1980   }
   1981 
   1982   // Set features according to the -arch flag on MSVC.
   1983   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
   1984     StringRef Arch = A->getValue();
   1985     bool ArchUsed = false;
   1986     // First, look for flags that are shared in x86 and x86-64.
   1987     if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
   1988       if (Arch == "AVX" || Arch == "AVX2") {
   1989         ArchUsed = true;
   1990         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
   1991       }
   1992     }
   1993     // Then, look for x86-specific flags.
   1994     if (ArchType == llvm::Triple::x86) {
   1995       if (Arch == "IA32") {
   1996         ArchUsed = true;
   1997       } else if (Arch == "SSE" || Arch == "SSE2") {
   1998         ArchUsed = true;
   1999         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
   2000       }
   2001     }
   2002     if (!ArchUsed)
   2003       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
   2004   }
   2005 
   2006   // Now add any that the user explicitly requested on the command line,
   2007   // which may override the defaults.
   2008   for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
   2009     StringRef Name = A->getOption().getName();
   2010     A->claim();
   2011 
   2012     // Skip over "-m".
   2013     assert(Name.startswith("m") && "Invalid feature name.");
   2014     Name = Name.substr(1);
   2015 
   2016     bool IsNegative = Name.startswith("no-");
   2017     if (IsNegative)
   2018       Name = Name.substr(3);
   2019 
   2020     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
   2021   }
   2022 }
   2023 
   2024 void Clang::AddX86TargetArgs(const ArgList &Args,
   2025                              ArgStringList &CmdArgs) const {
   2026   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
   2027       Args.hasArg(options::OPT_mkernel) ||
   2028       Args.hasArg(options::OPT_fapple_kext))
   2029     CmdArgs.push_back("-disable-red-zone");
   2030 
   2031   // Default to avoid implicit floating-point for kernel/kext code, but allow
   2032   // that to be overridden with -mno-soft-float.
   2033   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
   2034                           Args.hasArg(options::OPT_fapple_kext));
   2035   if (Arg *A = Args.getLastArg(
   2036           options::OPT_msoft_float, options::OPT_mno_soft_float,
   2037           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
   2038     const Option &O = A->getOption();
   2039     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
   2040                        O.matches(options::OPT_msoft_float));
   2041   }
   2042   if (NoImplicitFloat)
   2043     CmdArgs.push_back("-no-implicit-float");
   2044 
   2045   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
   2046     StringRef Value = A->getValue();
   2047     if (Value == "intel" || Value == "att") {
   2048       CmdArgs.push_back("-mllvm");
   2049       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
   2050     } else {
   2051       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
   2052           << A->getOption().getName() << Value;
   2053     }
   2054   }
   2055 }
   2056 
   2057 void Clang::AddHexagonTargetArgs(const ArgList &Args,
   2058                                  ArgStringList &CmdArgs) const {
   2059   CmdArgs.push_back("-mqdsp6-compat");
   2060   CmdArgs.push_back("-Wreturn-type");
   2061 
   2062   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
   2063     std::string N = llvm::utostr(G.getValue());
   2064     std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
   2065     CmdArgs.push_back("-mllvm");
   2066     CmdArgs.push_back(Args.MakeArgString(Opt));
   2067   }
   2068 
   2069   if (!Args.hasArg(options::OPT_fno_short_enums))
   2070     CmdArgs.push_back("-fshort-enums");
   2071   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
   2072     CmdArgs.push_back("-mllvm");
   2073     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
   2074   }
   2075   CmdArgs.push_back("-mllvm");
   2076   CmdArgs.push_back("-machine-sink-split=0");
   2077 }
   2078 
   2079 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
   2080 static bool DecodeAArch64Features(const Driver &D, StringRef text,
   2081                                   std::vector<const char *> &Features) {
   2082   SmallVector<StringRef, 8> Split;
   2083   text.split(Split, StringRef("+"), -1, false);
   2084 
   2085   for (StringRef Feature : Split) {
   2086     const char *result = llvm::StringSwitch<const char *>(Feature)
   2087                              .Case("fp", "+fp-armv8")
   2088                              .Case("simd", "+neon")
   2089                              .Case("crc", "+crc")
   2090                              .Case("crypto", "+crypto")
   2091                              .Case("fp16", "+fullfp16")
   2092                              .Case("profile", "+spe")
   2093                              .Case("nofp", "-fp-armv8")
   2094                              .Case("nosimd", "-neon")
   2095                              .Case("nocrc", "-crc")
   2096                              .Case("nocrypto", "-crypto")
   2097                              .Case("nofp16", "-fullfp16")
   2098                              .Case("noprofile", "-spe")
   2099                              .Default(nullptr);
   2100     if (result)
   2101       Features.push_back(result);
   2102     else if (Feature == "neon" || Feature == "noneon")
   2103       D.Diag(diag::err_drv_no_neon_modifier);
   2104     else
   2105       return false;
   2106   }
   2107   return true;
   2108 }
   2109 
   2110 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
   2111 // decode CPU and feature.
   2112 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
   2113                               std::vector<const char *> &Features) {
   2114   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
   2115   CPU = Split.first;
   2116   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
   2117       CPU == "cortex-a72" || CPU == "cortex-a35") {
   2118     Features.push_back("+neon");
   2119     Features.push_back("+crc");
   2120     Features.push_back("+crypto");
   2121   } else if (CPU == "generic") {
   2122     Features.push_back("+neon");
   2123   } else {
   2124     return false;
   2125   }
   2126 
   2127   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
   2128     return false;
   2129 
   2130   return true;
   2131 }
   2132 
   2133 static bool
   2134 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
   2135                                 const ArgList &Args,
   2136                                 std::vector<const char *> &Features) {
   2137   std::string MarchLowerCase = March.lower();
   2138   std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
   2139 
   2140   if (Split.first == "armv8-a" || Split.first == "armv8a") {
   2141     // ok, no additional features.
   2142   } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
   2143     Features.push_back("+v8.1a");
   2144   } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
   2145     Features.push_back("+v8.2a");
   2146   } else {
   2147     return false;
   2148   }
   2149 
   2150   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
   2151     return false;
   2152 
   2153   return true;
   2154 }
   2155 
   2156 static bool
   2157 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
   2158                                const ArgList &Args,
   2159                                std::vector<const char *> &Features) {
   2160   StringRef CPU;
   2161   std::string McpuLowerCase = Mcpu.lower();
   2162   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
   2163     return false;
   2164 
   2165   return true;
   2166 }
   2167 
   2168 static bool
   2169 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
   2170                                      const ArgList &Args,
   2171                                      std::vector<const char *> &Features) {
   2172   std::string MtuneLowerCase = Mtune.lower();
   2173   // Handle CPU name is 'native'.
   2174   if (MtuneLowerCase == "native")
   2175     MtuneLowerCase = llvm::sys::getHostCPUName();
   2176   if (MtuneLowerCase == "cyclone") {
   2177     Features.push_back("+zcm");
   2178     Features.push_back("+zcz");
   2179   }
   2180   return true;
   2181 }
   2182 
   2183 static bool
   2184 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
   2185                                     const ArgList &Args,
   2186                                     std::vector<const char *> &Features) {
   2187   StringRef CPU;
   2188   std::vector<const char *> DecodedFeature;
   2189   std::string McpuLowerCase = Mcpu.lower();
   2190   if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
   2191     return false;
   2192 
   2193   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
   2194 }
   2195 
   2196 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
   2197                                      std::vector<const char *> &Features) {
   2198   Arg *A;
   2199   bool success = true;
   2200   // Enable NEON by default.
   2201   Features.push_back("+neon");
   2202   if ((A = Args.getLastArg(options::OPT_march_EQ)))
   2203     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
   2204   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
   2205     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
   2206   else if (Args.hasArg(options::OPT_arch))
   2207     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
   2208                                              Features);
   2209 
   2210   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
   2211     success =
   2212         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
   2213   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
   2214     success =
   2215         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
   2216   else if (Args.hasArg(options::OPT_arch))
   2217     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
   2218                                                   Args, Features);
   2219 
   2220   if (!success)
   2221     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
   2222 
   2223   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
   2224     Features.push_back("-fp-armv8");
   2225     Features.push_back("-crypto");
   2226     Features.push_back("-neon");
   2227   }
   2228 
   2229   // En/disable crc
   2230   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
   2231     if (A->getOption().matches(options::OPT_mcrc))
   2232       Features.push_back("+crc");
   2233     else
   2234       Features.push_back("-crc");
   2235   }
   2236 
   2237   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
   2238                                options::OPT_munaligned_access))
   2239     if (A->getOption().matches(options::OPT_mno_unaligned_access))
   2240       Features.push_back("+strict-align");
   2241 
   2242   if (Args.hasArg(options::OPT_ffixed_x18))
   2243     Features.push_back("+reserve-x18");
   2244 }
   2245 
   2246 static void getHexagonTargetFeatures(const ArgList &Args,
   2247                                      std::vector<const char *> &Features) {
   2248   bool HasHVX = false, HasHVXD = false;
   2249 
   2250   for (auto &A : Args) {
   2251     auto &Opt = A->getOption();
   2252     if (Opt.matches(options::OPT_mhexagon_hvx))
   2253       HasHVX = true;
   2254     else if (Opt.matches(options::OPT_mno_hexagon_hvx))
   2255       HasHVXD = HasHVX = false;
   2256     else if (Opt.matches(options::OPT_mhexagon_hvx_double))
   2257       HasHVXD = HasHVX = true;
   2258     else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
   2259       HasHVXD = false;
   2260     else
   2261       continue;
   2262     A->claim();
   2263   }
   2264 
   2265   Features.push_back(HasHVX  ? "+hvx" : "-hvx");
   2266   Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
   2267 }
   2268 
   2269 static void getWebAssemblyTargetFeatures(const ArgList &Args,
   2270                                          std::vector<const char *> &Features) {
   2271   for (const Arg *A : Args.filtered(options::OPT_m_wasm_Features_Group)) {
   2272     StringRef Name = A->getOption().getName();
   2273     A->claim();
   2274 
   2275     // Skip over "-m".
   2276     assert(Name.startswith("m") && "Invalid feature name.");
   2277     Name = Name.substr(1);
   2278 
   2279     bool IsNegative = Name.startswith("no-");
   2280     if (IsNegative)
   2281       Name = Name.substr(3);
   2282 
   2283     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
   2284   }
   2285 }
   2286 
   2287 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
   2288                               const ArgList &Args, ArgStringList &CmdArgs,
   2289                               bool ForAS) {
   2290   const Driver &D = TC.getDriver();
   2291   std::vector<const char *> Features;
   2292   switch (Triple.getArch()) {
   2293   default:
   2294     break;
   2295   case llvm::Triple::mips:
   2296   case llvm::Triple::mipsel:
   2297   case llvm::Triple::mips64:
   2298   case llvm::Triple::mips64el:
   2299     getMIPSTargetFeatures(D, Triple, Args, Features);
   2300     break;
   2301 
   2302   case llvm::Triple::arm:
   2303   case llvm::Triple::armeb:
   2304   case llvm::Triple::thumb:
   2305   case llvm::Triple::thumbeb:
   2306     getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
   2307     break;
   2308 
   2309   case llvm::Triple::ppc:
   2310   case llvm::Triple::ppc64:
   2311   case llvm::Triple::ppc64le:
   2312     getPPCTargetFeatures(D, Triple, Args, Features);
   2313     break;
   2314   case llvm::Triple::systemz:
   2315     getSystemZTargetFeatures(Args, Features);
   2316     break;
   2317   case llvm::Triple::aarch64:
   2318   case llvm::Triple::aarch64_be:
   2319     getAArch64TargetFeatures(D, Args, Features);
   2320     break;
   2321   case llvm::Triple::x86:
   2322   case llvm::Triple::x86_64:
   2323     getX86TargetFeatures(D, Triple, Args, Features);
   2324     break;
   2325   case llvm::Triple::hexagon:
   2326     getHexagonTargetFeatures(Args, Features);
   2327     break;
   2328   case llvm::Triple::wasm32:
   2329   case llvm::Triple::wasm64:
   2330     getWebAssemblyTargetFeatures(Args, Features);
   2331     break;
   2332   }
   2333 
   2334   // Find the last of each feature.
   2335   llvm::StringMap<unsigned> LastOpt;
   2336   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
   2337     const char *Name = Features[I];
   2338     assert(Name[0] == '-' || Name[0] == '+');
   2339     LastOpt[Name + 1] = I;
   2340   }
   2341 
   2342   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
   2343     // If this feature was overridden, ignore it.
   2344     const char *Name = Features[I];
   2345     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
   2346     assert(LastI != LastOpt.end());
   2347     unsigned Last = LastI->second;
   2348     if (Last != I)
   2349       continue;
   2350 
   2351     CmdArgs.push_back("-target-feature");
   2352     CmdArgs.push_back(Name);
   2353   }
   2354 }
   2355 
   2356 static bool
   2357 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
   2358                                           const llvm::Triple &Triple) {
   2359   // We use the zero-cost exception tables for Objective-C if the non-fragile
   2360   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
   2361   // later.
   2362   if (runtime.isNonFragile())
   2363     return true;
   2364 
   2365   if (!Triple.isMacOSX())
   2366     return false;
   2367 
   2368   return (!Triple.isMacOSXVersionLT(10, 5) &&
   2369           (Triple.getArch() == llvm::Triple::x86_64 ||
   2370            Triple.getArch() == llvm::Triple::arm));
   2371 }
   2372 
   2373 /// Adds exception related arguments to the driver command arguments. There's a
   2374 /// master flag, -fexceptions and also language specific flags to enable/disable
   2375 /// C++ and Objective-C exceptions. This makes it possible to for example
   2376 /// disable C++ exceptions but enable Objective-C exceptions.
   2377 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
   2378                              const ToolChain &TC, bool KernelOrKext,
   2379                              const ObjCRuntime &objcRuntime,
   2380                              ArgStringList &CmdArgs) {
   2381   const Driver &D = TC.getDriver();
   2382   const llvm::Triple &Triple = TC.getTriple();
   2383 
   2384   if (KernelOrKext) {
   2385     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
   2386     // arguments now to avoid warnings about unused arguments.
   2387     Args.ClaimAllArgs(options::OPT_fexceptions);
   2388     Args.ClaimAllArgs(options::OPT_fno_exceptions);
   2389     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
   2390     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
   2391     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
   2392     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
   2393     return;
   2394   }
   2395 
   2396   // See if the user explicitly enabled exceptions.
   2397   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
   2398                          false);
   2399 
   2400   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
   2401   // is not necessarily sensible, but follows GCC.
   2402   if (types::isObjC(InputType) &&
   2403       Args.hasFlag(options::OPT_fobjc_exceptions,
   2404                    options::OPT_fno_objc_exceptions, true)) {
   2405     CmdArgs.push_back("-fobjc-exceptions");
   2406 
   2407     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
   2408   }
   2409 
   2410   if (types::isCXX(InputType)) {
   2411     // Disable C++ EH by default on XCore, PS4, and MSVC.
   2412     // FIXME: Remove MSVC from this list once things work.
   2413     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
   2414                                 !Triple.isPS4CPU() &&
   2415                                 !Triple.isWindowsMSVCEnvironment();
   2416     Arg *ExceptionArg = Args.getLastArg(
   2417         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
   2418         options::OPT_fexceptions, options::OPT_fno_exceptions);
   2419     if (ExceptionArg)
   2420       CXXExceptionsEnabled =
   2421           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
   2422           ExceptionArg->getOption().matches(options::OPT_fexceptions);
   2423 
   2424     if (CXXExceptionsEnabled) {
   2425       if (Triple.isPS4CPU()) {
   2426         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
   2427         assert(ExceptionArg &&
   2428                "On the PS4 exceptions should only be enabled if passing "
   2429                "an argument");
   2430         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
   2431           const Arg *RTTIArg = TC.getRTTIArg();
   2432           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
   2433           D.Diag(diag::err_drv_argument_not_allowed_with)
   2434               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
   2435         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
   2436           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
   2437       } else
   2438         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
   2439 
   2440       CmdArgs.push_back("-fcxx-exceptions");
   2441 
   2442       EH = true;
   2443     }
   2444   }
   2445 
   2446   if (EH)
   2447     CmdArgs.push_back("-fexceptions");
   2448 }
   2449 
   2450 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
   2451   bool Default = true;
   2452   if (TC.getTriple().isOSDarwin()) {
   2453     // The native darwin assembler doesn't support the linker_option directives,
   2454     // so we disable them if we think the .s file will be passed to it.
   2455     Default = TC.useIntegratedAs();
   2456   }
   2457   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
   2458                        Default);
   2459 }
   2460 
   2461 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
   2462                                         const ToolChain &TC) {
   2463   bool UseDwarfDirectory =
   2464       Args.hasFlag(options::OPT_fdwarf_directory_asm,
   2465                    options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
   2466   return !UseDwarfDirectory;
   2467 }
   2468 
   2469 /// \brief Check whether the given input tree contains any compilation actions.
   2470 static bool ContainsCompileAction(const Action *A) {
   2471   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
   2472     return true;
   2473 
   2474   for (const auto &Act : *A)
   2475     if (ContainsCompileAction(Act))
   2476       return true;
   2477 
   2478   return false;
   2479 }
   2480 
   2481 /// \brief Check if -relax-all should be passed to the internal assembler.
   2482 /// This is done by default when compiling non-assembler source with -O0.
   2483 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
   2484   bool RelaxDefault = true;
   2485 
   2486   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
   2487     RelaxDefault = A->getOption().matches(options::OPT_O0);
   2488 
   2489   if (RelaxDefault) {
   2490     RelaxDefault = false;
   2491     for (const auto &Act : C.getActions()) {
   2492       if (ContainsCompileAction(Act)) {
   2493         RelaxDefault = true;
   2494         break;
   2495       }
   2496     }
   2497   }
   2498 
   2499   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
   2500                       RelaxDefault);
   2501 }
   2502 
   2503 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
   2504 // to the corresponding DebugInfoKind.
   2505 static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
   2506   assert(A.getOption().matches(options::OPT_gN_Group) &&
   2507          "Not a -g option that specifies a debug-info level");
   2508   if (A.getOption().matches(options::OPT_g0) ||
   2509       A.getOption().matches(options::OPT_ggdb0))
   2510     return CodeGenOptions::NoDebugInfo;
   2511   if (A.getOption().matches(options::OPT_gline_tables_only) ||
   2512       A.getOption().matches(options::OPT_ggdb1))
   2513     return CodeGenOptions::DebugLineTablesOnly;
   2514   return CodeGenOptions::LimitedDebugInfo;
   2515 }
   2516 
   2517 // Extract the integer N from a string spelled "-dwarf-N", returning 0
   2518 // on mismatch. The StringRef input (rather than an Arg) allows
   2519 // for use by the "-Xassembler" option parser.
   2520 static unsigned DwarfVersionNum(StringRef ArgValue) {
   2521   return llvm::StringSwitch<unsigned>(ArgValue)
   2522       .Case("-gdwarf-2", 2)
   2523       .Case("-gdwarf-3", 3)
   2524       .Case("-gdwarf-4", 4)
   2525       .Default(0);
   2526 }
   2527 
   2528 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
   2529                                     CodeGenOptions::DebugInfoKind DebugInfoKind,
   2530                                     unsigned DwarfVersion,
   2531                                     llvm::DebuggerKind DebuggerTuning) {
   2532   switch (DebugInfoKind) {
   2533   case CodeGenOptions::DebugLineTablesOnly:
   2534     CmdArgs.push_back("-debug-info-kind=line-tables-only");
   2535     break;
   2536   case CodeGenOptions::LimitedDebugInfo:
   2537     CmdArgs.push_back("-debug-info-kind=limited");
   2538     break;
   2539   case CodeGenOptions::FullDebugInfo:
   2540     CmdArgs.push_back("-debug-info-kind=standalone");
   2541     break;
   2542   default:
   2543     break;
   2544   }
   2545   if (DwarfVersion > 0)
   2546     CmdArgs.push_back(
   2547         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
   2548   switch (DebuggerTuning) {
   2549   case llvm::DebuggerKind::GDB:
   2550     CmdArgs.push_back("-debugger-tuning=gdb");
   2551     break;
   2552   case llvm::DebuggerKind::LLDB:
   2553     CmdArgs.push_back("-debugger-tuning=lldb");
   2554     break;
   2555   case llvm::DebuggerKind::SCE:
   2556     CmdArgs.push_back("-debugger-tuning=sce");
   2557     break;
   2558   default:
   2559     break;
   2560   }
   2561 }
   2562 
   2563 static void CollectArgsForIntegratedAssembler(Compilation &C,
   2564                                               const ArgList &Args,
   2565                                               ArgStringList &CmdArgs,
   2566                                               const Driver &D) {
   2567   if (UseRelaxAll(C, Args))
   2568     CmdArgs.push_back("-mrelax-all");
   2569 
   2570   // Only default to -mincremental-linker-compatible if we think we are
   2571   // targeting the MSVC linker.
   2572   bool DefaultIncrementalLinkerCompatible =
   2573       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
   2574   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
   2575                    options::OPT_mno_incremental_linker_compatible,
   2576                    DefaultIncrementalLinkerCompatible))
   2577     CmdArgs.push_back("-mincremental-linker-compatible");
   2578 
   2579   // When passing -I arguments to the assembler we sometimes need to
   2580   // unconditionally take the next argument.  For example, when parsing
   2581   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
   2582   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
   2583   // arg after parsing the '-I' arg.
   2584   bool TakeNextArg = false;
   2585 
   2586   // When using an integrated assembler, translate -Wa, and -Xassembler
   2587   // options.
   2588   bool CompressDebugSections = false;
   2589   for (const Arg *A :
   2590        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
   2591     A->claim();
   2592 
   2593     for (StringRef Value : A->getValues()) {
   2594       if (TakeNextArg) {
   2595         CmdArgs.push_back(Value.data());
   2596         TakeNextArg = false;
   2597         continue;
   2598       }
   2599 
   2600       switch (C.getDefaultToolChain().getArch()) {
   2601       default:
   2602         break;
   2603       case llvm::Triple::mips:
   2604       case llvm::Triple::mipsel:
   2605       case llvm::Triple::mips64:
   2606       case llvm::Triple::mips64el:
   2607         if (Value == "--trap") {
   2608           CmdArgs.push_back("-target-feature");
   2609           CmdArgs.push_back("+use-tcc-in-div");
   2610           continue;
   2611         }
   2612         if (Value == "--break") {
   2613           CmdArgs.push_back("-target-feature");
   2614           CmdArgs.push_back("-use-tcc-in-div");
   2615           continue;
   2616         }
   2617         if (Value.startswith("-msoft-float")) {
   2618           CmdArgs.push_back("-target-feature");
   2619           CmdArgs.push_back("+soft-float");
   2620           continue;
   2621         }
   2622         if (Value.startswith("-mhard-float")) {
   2623           CmdArgs.push_back("-target-feature");
   2624           CmdArgs.push_back("-soft-float");
   2625           continue;
   2626         }
   2627         break;
   2628       }
   2629 
   2630       if (Value == "-force_cpusubtype_ALL") {
   2631         // Do nothing, this is the default and we don't support anything else.
   2632       } else if (Value == "-L") {
   2633         CmdArgs.push_back("-msave-temp-labels");
   2634       } else if (Value == "--fatal-warnings") {
   2635         CmdArgs.push_back("-massembler-fatal-warnings");
   2636       } else if (Value == "--noexecstack") {
   2637         CmdArgs.push_back("-mnoexecstack");
   2638       } else if (Value == "-compress-debug-sections" ||
   2639                  Value == "--compress-debug-sections") {
   2640         CompressDebugSections = true;
   2641       } else if (Value == "-nocompress-debug-sections" ||
   2642                  Value == "--nocompress-debug-sections") {
   2643         CompressDebugSections = false;
   2644       } else if (Value.startswith("-I")) {
   2645         CmdArgs.push_back(Value.data());
   2646         // We need to consume the next argument if the current arg is a plain
   2647         // -I. The next arg will be the include directory.
   2648         if (Value == "-I")
   2649           TakeNextArg = true;
   2650       } else if (Value.startswith("-gdwarf-")) {
   2651         // "-gdwarf-N" options are not cc1as options.
   2652         unsigned DwarfVersion = DwarfVersionNum(Value);
   2653         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
   2654           CmdArgs.push_back(Value.data());
   2655         } else {
   2656           RenderDebugEnablingArgs(
   2657               Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
   2658               llvm::DebuggerKind::Default);
   2659         }
   2660       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
   2661                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
   2662         // Do nothing, we'll validate it later.
   2663       } else {
   2664         D.Diag(diag::err_drv_unsupported_option_argument)
   2665             << A->getOption().getName() << Value;
   2666       }
   2667     }
   2668   }
   2669   if (CompressDebugSections) {
   2670     if (llvm::zlib::isAvailable())
   2671       CmdArgs.push_back("-compress-debug-sections");
   2672     else
   2673       D.Diag(diag::warn_debug_compression_unavailable);
   2674   }
   2675 }
   2676 
   2677 // This adds the static libclang_rt.builtins-arch.a directly to the command line
   2678 // FIXME: Make sure we can also emit shared objects if they're requested
   2679 // and available, check for possible errors, etc.
   2680 static void addClangRT(const ToolChain &TC, const ArgList &Args,
   2681                        ArgStringList &CmdArgs) {
   2682   CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
   2683 }
   2684 
   2685 namespace {
   2686 enum OpenMPRuntimeKind {
   2687   /// An unknown OpenMP runtime. We can't generate effective OpenMP code
   2688   /// without knowing what runtime to target.
   2689   OMPRT_Unknown,
   2690 
   2691   /// The LLVM OpenMP runtime. When completed and integrated, this will become
   2692   /// the default for Clang.
   2693   OMPRT_OMP,
   2694 
   2695   /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
   2696   /// this runtime but can swallow the pragmas, and find and link against the
   2697   /// runtime library itself.
   2698   OMPRT_GOMP,
   2699 
   2700   /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
   2701   /// OpenMP runtime. We support this mode for users with existing dependencies
   2702   /// on this runtime library name.
   2703   OMPRT_IOMP5
   2704 };
   2705 }
   2706 
   2707 /// Compute the desired OpenMP runtime from the flag provided.
   2708 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
   2709                                           const ArgList &Args) {
   2710   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
   2711 
   2712   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
   2713   if (A)
   2714     RuntimeName = A->getValue();
   2715 
   2716   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
   2717                 .Case("libomp", OMPRT_OMP)
   2718                 .Case("libgomp", OMPRT_GOMP)
   2719                 .Case("libiomp5", OMPRT_IOMP5)
   2720                 .Default(OMPRT_Unknown);
   2721 
   2722   if (RT == OMPRT_Unknown) {
   2723     if (A)
   2724       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
   2725           << A->getOption().getName() << A->getValue();
   2726     else
   2727       // FIXME: We could use a nicer diagnostic here.
   2728       TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
   2729   }
   2730 
   2731   return RT;
   2732 }
   2733 
   2734 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
   2735                               const ArgList &Args) {
   2736   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
   2737                     options::OPT_fno_openmp, false))
   2738     return;
   2739 
   2740   switch (getOpenMPRuntime(TC, Args)) {
   2741   case OMPRT_OMP:
   2742     CmdArgs.push_back("-lomp");
   2743     break;
   2744   case OMPRT_GOMP:
   2745     CmdArgs.push_back("-lgomp");
   2746     break;
   2747   case OMPRT_IOMP5:
   2748     CmdArgs.push_back("-liomp5");
   2749     break;
   2750   case OMPRT_Unknown:
   2751     // Already diagnosed.
   2752     break;
   2753   }
   2754 }
   2755 
   2756 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
   2757                                 ArgStringList &CmdArgs, StringRef Sanitizer,
   2758                                 bool IsShared) {
   2759   // Static runtimes must be forced into executable, so we wrap them in
   2760   // whole-archive.
   2761   if (!IsShared) CmdArgs.push_back("-whole-archive");
   2762   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
   2763   if (!IsShared) CmdArgs.push_back("-no-whole-archive");
   2764 }
   2765 
   2766 // Tries to use a file with the list of dynamic symbols that need to be exported
   2767 // from the runtime library. Returns true if the file was found.
   2768 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
   2769                                     ArgStringList &CmdArgs,
   2770                                     StringRef Sanitizer) {
   2771   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
   2772   if (llvm::sys::fs::exists(SanRT + ".syms")) {
   2773     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
   2774     return true;
   2775   }
   2776   return false;
   2777 }
   2778 
   2779 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
   2780                                      ArgStringList &CmdArgs) {
   2781   // Force linking against the system libraries sanitizers depends on
   2782   // (see PR15823 why this is necessary).
   2783   CmdArgs.push_back("--no-as-needed");
   2784   CmdArgs.push_back("-lpthread");
   2785   CmdArgs.push_back("-lrt");
   2786   CmdArgs.push_back("-lm");
   2787   // There's no libdl on FreeBSD.
   2788   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
   2789     CmdArgs.push_back("-ldl");
   2790 }
   2791 
   2792 static void
   2793 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
   2794                          SmallVectorImpl<StringRef> &SharedRuntimes,
   2795                          SmallVectorImpl<StringRef> &StaticRuntimes,
   2796                          SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
   2797   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
   2798   // Collect shared runtimes.
   2799   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
   2800     SharedRuntimes.push_back("asan");
   2801   }
   2802 
   2803   // Collect static runtimes.
   2804   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
   2805     // Don't link static runtimes into DSOs or if compiling for Android.
   2806     return;
   2807   }
   2808   if (SanArgs.needsAsanRt()) {
   2809     if (SanArgs.needsSharedAsanRt()) {
   2810       HelperStaticRuntimes.push_back("asan-preinit");
   2811     } else {
   2812       StaticRuntimes.push_back("asan");
   2813       if (SanArgs.linkCXXRuntimes())
   2814         StaticRuntimes.push_back("asan_cxx");
   2815     }
   2816   }
   2817   if (SanArgs.needsDfsanRt())
   2818     StaticRuntimes.push_back("dfsan");
   2819   if (SanArgs.needsLsanRt())
   2820     StaticRuntimes.push_back("lsan");
   2821   if (SanArgs.needsMsanRt()) {
   2822     StaticRuntimes.push_back("msan");
   2823     if (SanArgs.linkCXXRuntimes())
   2824       StaticRuntimes.push_back("msan_cxx");
   2825   }
   2826   if (SanArgs.needsTsanRt()) {
   2827     StaticRuntimes.push_back("tsan");
   2828     if (SanArgs.linkCXXRuntimes())
   2829       StaticRuntimes.push_back("tsan_cxx");
   2830   }
   2831   if (SanArgs.needsUbsanRt()) {
   2832     StaticRuntimes.push_back("ubsan_standalone");
   2833     if (SanArgs.linkCXXRuntimes())
   2834       StaticRuntimes.push_back("ubsan_standalone_cxx");
   2835   }
   2836   if (SanArgs.needsSafeStackRt())
   2837     StaticRuntimes.push_back("safestack");
   2838   if (SanArgs.needsCfiRt())
   2839     StaticRuntimes.push_back("cfi");
   2840   if (SanArgs.needsCfiDiagRt())
   2841     StaticRuntimes.push_back("cfi_diag");
   2842 }
   2843 
   2844 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
   2845 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
   2846 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
   2847                                  ArgStringList &CmdArgs) {
   2848   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
   2849       HelperStaticRuntimes;
   2850   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
   2851                            HelperStaticRuntimes);
   2852   for (auto RT : SharedRuntimes)
   2853     addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
   2854   for (auto RT : HelperStaticRuntimes)
   2855     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
   2856   bool AddExportDynamic = false;
   2857   for (auto RT : StaticRuntimes) {
   2858     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
   2859     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
   2860   }
   2861   // If there is a static runtime with no dynamic list, force all the symbols
   2862   // to be dynamic to be sure we export sanitizer interface functions.
   2863   if (AddExportDynamic)
   2864     CmdArgs.push_back("-export-dynamic");
   2865   return !StaticRuntimes.empty();
   2866 }
   2867 
   2868 static bool areOptimizationsEnabled(const ArgList &Args) {
   2869   // Find the last -O arg and see if it is non-zero.
   2870   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
   2871     return !A->getOption().matches(options::OPT_O0);
   2872   // Defaults to -O0.
   2873   return false;
   2874 }
   2875 
   2876 static bool shouldUseFramePointerForTarget(const ArgList &Args,
   2877                                            const llvm::Triple &Triple) {
   2878   switch (Triple.getArch()) {
   2879   case llvm::Triple::xcore:
   2880   case llvm::Triple::wasm32:
   2881   case llvm::Triple::wasm64:
   2882     // XCore never wants frame pointers, regardless of OS.
   2883     // WebAssembly never wants frame pointers.
   2884     return false;
   2885   default:
   2886     break;
   2887   }
   2888 
   2889   if (Triple.isOSLinux()) {
   2890     switch (Triple.getArch()) {
   2891     // Don't use a frame pointer on linux if optimizing for certain targets.
   2892     case llvm::Triple::mips64:
   2893     case llvm::Triple::mips64el:
   2894     case llvm::Triple::mips:
   2895     case llvm::Triple::mipsel:
   2896     case llvm::Triple::systemz:
   2897     case llvm::Triple::x86:
   2898     case llvm::Triple::x86_64:
   2899       return !areOptimizationsEnabled(Args);
   2900     default:
   2901       return true;
   2902     }
   2903   }
   2904 
   2905   if (Triple.isOSWindows()) {
   2906     switch (Triple.getArch()) {
   2907     case llvm::Triple::x86:
   2908       return !areOptimizationsEnabled(Args);
   2909     case llvm::Triple::arm:
   2910     case llvm::Triple::thumb:
   2911       // Windows on ARM builds with FPO disabled to aid fast stack walking
   2912       return true;
   2913     default:
   2914       // All other supported Windows ISAs use xdata unwind information, so frame
   2915       // pointers are not generally useful.
   2916       return false;
   2917     }
   2918   }
   2919 
   2920   return true;
   2921 }
   2922 
   2923 static bool shouldUseFramePointer(const ArgList &Args,
   2924                                   const llvm::Triple &Triple) {
   2925   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
   2926                                options::OPT_fomit_frame_pointer))
   2927     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
   2928   if (Args.hasArg(options::OPT_pg))
   2929     return true;
   2930 
   2931   return shouldUseFramePointerForTarget(Args, Triple);
   2932 }
   2933 
   2934 static bool shouldUseLeafFramePointer(const ArgList &Args,
   2935                                       const llvm::Triple &Triple) {
   2936   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
   2937                                options::OPT_momit_leaf_frame_pointer))
   2938     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
   2939   if (Args.hasArg(options::OPT_pg))
   2940     return true;
   2941 
   2942   if (Triple.isPS4CPU())
   2943     return false;
   2944 
   2945   return shouldUseFramePointerForTarget(Args, Triple);
   2946 }
   2947 
   2948 /// Add a CC1 option to specify the debug compilation directory.
   2949 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
   2950   SmallString<128> cwd;
   2951   if (!llvm::sys::fs::current_path(cwd)) {
   2952     CmdArgs.push_back("-fdebug-compilation-dir");
   2953     CmdArgs.push_back(Args.MakeArgString(cwd));
   2954   }
   2955 }
   2956 
   2957 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
   2958   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
   2959   if (FinalOutput && Args.hasArg(options::OPT_c)) {
   2960     SmallString<128> T(FinalOutput->getValue());
   2961     llvm::sys::path::replace_extension(T, "dwo");
   2962     return Args.MakeArgString(T);
   2963   } else {
   2964     // Use the compilation dir.
   2965     SmallString<128> T(
   2966         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
   2967     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
   2968     llvm::sys::path::replace_extension(F, "dwo");
   2969     T += F;
   2970     return Args.MakeArgString(F);
   2971   }
   2972 }
   2973 
   2974 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
   2975                            const JobAction &JA, const ArgList &Args,
   2976                            const InputInfo &Output, const char *OutFile) {
   2977   ArgStringList ExtractArgs;
   2978   ExtractArgs.push_back("--extract-dwo");
   2979 
   2980   ArgStringList StripArgs;
   2981   StripArgs.push_back("--strip-dwo");
   2982 
   2983   // Grabbing the output of the earlier compile step.
   2984   StripArgs.push_back(Output.getFilename());
   2985   ExtractArgs.push_back(Output.getFilename());
   2986   ExtractArgs.push_back(OutFile);
   2987 
   2988   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
   2989   InputInfo II(Output.getFilename(), types::TY_Object, Output.getFilename());
   2990 
   2991   // First extract the dwo sections.
   2992   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
   2993 
   2994   // Then remove them from the original .o file.
   2995   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
   2996 }
   2997 
   2998 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
   2999 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
   3000 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
   3001   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
   3002     if (A->getOption().matches(options::OPT_O4) ||
   3003         A->getOption().matches(options::OPT_Ofast))
   3004       return true;
   3005 
   3006     if (A->getOption().matches(options::OPT_O0))
   3007       return false;
   3008 
   3009     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
   3010 
   3011     // Vectorize -Os.
   3012     StringRef S(A->getValue());
   3013     if (S == "s")
   3014       return true;
   3015 
   3016     // Don't vectorize -Oz, unless it's the slp vectorizer.
   3017     if (S == "z")
   3018       return isSlpVec;
   3019 
   3020     unsigned OptLevel = 0;
   3021     if (S.getAsInteger(10, OptLevel))
   3022       return false;
   3023 
   3024     return OptLevel > 1;
   3025   }
   3026 
   3027   return false;
   3028 }
   3029 
   3030 /// Add -x lang to \p CmdArgs for \p Input.
   3031 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
   3032                              ArgStringList &CmdArgs) {
   3033   // When using -verify-pch, we don't want to provide the type
   3034   // 'precompiled-header' if it was inferred from the file extension
   3035   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
   3036     return;
   3037 
   3038   CmdArgs.push_back("-x");
   3039   if (Args.hasArg(options::OPT_rewrite_objc))
   3040     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
   3041   else
   3042     CmdArgs.push_back(types::getTypeName(Input.getType()));
   3043 }
   3044 
   3045 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
   3046   if (Version < 100)
   3047     return VersionTuple(Version);
   3048 
   3049   if (Version < 10000)
   3050     return VersionTuple(Version / 100, Version % 100);
   3051 
   3052   unsigned Build = 0, Factor = 1;
   3053   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
   3054     Build = Build + (Version % 10) * Factor;
   3055   return VersionTuple(Version / 100, Version % 100, Build);
   3056 }
   3057 
   3058 // Claim options we don't want to warn if they are unused. We do this for
   3059 // options that build systems might add but are unused when assembling or only
   3060 // running the preprocessor for example.
   3061 static void claimNoWarnArgs(const ArgList &Args) {
   3062   // Don't warn about unused -f(no-)?lto.  This can happen when we're
   3063   // preprocessing, precompiling or assembling.
   3064   Args.ClaimAllArgs(options::OPT_flto_EQ);
   3065   Args.ClaimAllArgs(options::OPT_flto);
   3066   Args.ClaimAllArgs(options::OPT_fno_lto);
   3067 }
   3068 
   3069 static void appendUserToPath(SmallVectorImpl<char> &Result) {
   3070 #ifdef LLVM_ON_UNIX
   3071   const char *Username = getenv("LOGNAME");
   3072 #else
   3073   const char *Username = getenv("USERNAME");
   3074 #endif
   3075   if (Username) {
   3076     // Validate that LoginName can be used in a path, and get its length.
   3077     size_t Len = 0;
   3078     for (const char *P = Username; *P; ++P, ++Len) {
   3079       if (!isAlphanumeric(*P) && *P != '_') {
   3080         Username = nullptr;
   3081         break;
   3082       }
   3083     }
   3084 
   3085     if (Username && Len > 0) {
   3086       Result.append(Username, Username + Len);
   3087       return;
   3088     }
   3089   }
   3090 
   3091 // Fallback to user id.
   3092 #ifdef LLVM_ON_UNIX
   3093   std::string UID = llvm::utostr(getuid());
   3094 #else
   3095   // FIXME: Windows seems to have an 'SID' that might work.
   3096   std::string UID = "9999";
   3097 #endif
   3098   Result.append(UID.begin(), UID.end());
   3099 }
   3100 
   3101 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
   3102                                           const llvm::Triple &Triple,
   3103                                           const llvm::opt::ArgList &Args,
   3104                                           bool IsWindowsMSVC) {
   3105   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
   3106                    IsWindowsMSVC) ||
   3107       Args.hasArg(options::OPT_fmsc_version) ||
   3108       Args.hasArg(options::OPT_fms_compatibility_version)) {
   3109     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
   3110     const Arg *MSCompatibilityVersion =
   3111         Args.getLastArg(options::OPT_fms_compatibility_version);
   3112 
   3113     if (MSCVersion && MSCompatibilityVersion) {
   3114       if (D)
   3115         D->Diag(diag::err_drv_argument_not_allowed_with)
   3116             << MSCVersion->getAsString(Args)
   3117             << MSCompatibilityVersion->getAsString(Args);
   3118       return VersionTuple();
   3119     }
   3120 
   3121     if (MSCompatibilityVersion) {
   3122       VersionTuple MSVT;
   3123       if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
   3124         D->Diag(diag::err_drv_invalid_value)
   3125             << MSCompatibilityVersion->getAsString(Args)
   3126             << MSCompatibilityVersion->getValue();
   3127       return MSVT;
   3128     }
   3129 
   3130     if (MSCVersion) {
   3131       unsigned Version = 0;
   3132       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
   3133         D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
   3134                                              << MSCVersion->getValue();
   3135       return getMSCompatibilityVersion(Version);
   3136     }
   3137 
   3138     unsigned Major, Minor, Micro;
   3139     Triple.getEnvironmentVersion(Major, Minor, Micro);
   3140     if (Major || Minor || Micro)
   3141       return VersionTuple(Major, Minor, Micro);
   3142 
   3143     return VersionTuple(18);
   3144   }
   3145   return VersionTuple();
   3146 }
   3147 
   3148 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
   3149                                    const InputInfo &Output, const ArgList &Args,
   3150                                    ArgStringList &CmdArgs) {
   3151   auto *ProfileGenerateArg = Args.getLastArg(
   3152       options::OPT_fprofile_instr_generate,
   3153       options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
   3154       options::OPT_fprofile_generate_EQ,
   3155       options::OPT_fno_profile_instr_generate);
   3156   if (ProfileGenerateArg &&
   3157       ProfileGenerateArg->getOption().matches(
   3158           options::OPT_fno_profile_instr_generate))
   3159     ProfileGenerateArg = nullptr;
   3160 
   3161   auto *ProfileUseArg = Args.getLastArg(
   3162       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
   3163       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
   3164       options::OPT_fno_profile_instr_use);
   3165   if (ProfileUseArg &&
   3166       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
   3167     ProfileUseArg = nullptr;
   3168 
   3169   if (ProfileGenerateArg && ProfileUseArg)
   3170     D.Diag(diag::err_drv_argument_not_allowed_with)
   3171         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
   3172 
   3173   if (ProfileGenerateArg) {
   3174     if (ProfileGenerateArg->getOption().matches(
   3175             options::OPT_fprofile_instr_generate_EQ))
   3176       ProfileGenerateArg->render(Args, CmdArgs);
   3177     else if (ProfileGenerateArg->getOption().matches(
   3178                  options::OPT_fprofile_generate_EQ)) {
   3179       SmallString<128> Path(ProfileGenerateArg->getValue());
   3180       llvm::sys::path::append(Path, "default.profraw");
   3181       CmdArgs.push_back(
   3182           Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
   3183     } else
   3184       Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
   3185   }
   3186 
   3187   if (ProfileUseArg) {
   3188     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
   3189       ProfileUseArg->render(Args, CmdArgs);
   3190     else if ((ProfileUseArg->getOption().matches(
   3191                   options::OPT_fprofile_use_EQ) ||
   3192               ProfileUseArg->getOption().matches(
   3193                   options::OPT_fprofile_instr_use))) {
   3194       SmallString<128> Path(
   3195           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
   3196       if (Path.empty() || llvm::sys::fs::is_directory(Path))
   3197         llvm::sys::path::append(Path, "default.profdata");
   3198       CmdArgs.push_back(
   3199           Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
   3200     }
   3201   }
   3202 
   3203   if (Args.hasArg(options::OPT_ftest_coverage) ||
   3204       Args.hasArg(options::OPT_coverage))
   3205     CmdArgs.push_back("-femit-coverage-notes");
   3206   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
   3207                    false) ||
   3208       Args.hasArg(options::OPT_coverage))
   3209     CmdArgs.push_back("-femit-coverage-data");
   3210 
   3211   if (Args.hasFlag(options::OPT_fcoverage_mapping,
   3212                    options::OPT_fno_coverage_mapping, false) &&
   3213       !ProfileGenerateArg)
   3214     D.Diag(diag::err_drv_argument_only_allowed_with)
   3215         << "-fcoverage-mapping"
   3216         << "-fprofile-instr-generate";
   3217 
   3218   if (Args.hasFlag(options::OPT_fcoverage_mapping,
   3219                    options::OPT_fno_coverage_mapping, false))
   3220     CmdArgs.push_back("-fcoverage-mapping");
   3221 
   3222   if (C.getArgs().hasArg(options::OPT_c) ||
   3223       C.getArgs().hasArg(options::OPT_S)) {
   3224     if (Output.isFilename()) {
   3225       CmdArgs.push_back("-coverage-file");
   3226       SmallString<128> CoverageFilename;
   3227       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
   3228         CoverageFilename = FinalOutput->getValue();
   3229       } else {
   3230         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
   3231       }
   3232       if (llvm::sys::path::is_relative(CoverageFilename)) {
   3233         SmallString<128> Pwd;
   3234         if (!llvm::sys::fs::current_path(Pwd)) {
   3235           llvm::sys::path::append(Pwd, CoverageFilename);
   3236           CoverageFilename.swap(Pwd);
   3237         }
   3238       }
   3239       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
   3240     }
   3241   }
   3242 }
   3243 
   3244 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
   3245                                 ArgStringList &CmdArgs) {
   3246   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
   3247                     false) ||
   3248        Args.hasFlag(options::OPT_fprofile_generate,
   3249                     options::OPT_fno_profile_instr_generate, false) ||
   3250        Args.hasFlag(options::OPT_fprofile_generate_EQ,
   3251                     options::OPT_fno_profile_instr_generate, false) ||
   3252        Args.hasFlag(options::OPT_fprofile_instr_generate,
   3253                     options::OPT_fno_profile_instr_generate, false) ||
   3254        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
   3255                     options::OPT_fno_profile_instr_generate, false) ||
   3256        Args.hasArg(options::OPT_fcreate_profile) ||
   3257        Args.hasArg(options::OPT_coverage)))
   3258     CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
   3259 }
   3260 
   3261 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
   3262 /// smooshes them together with platform defaults, to decide whether
   3263 /// this compile should be using PIC mode or not. Returns a tuple of
   3264 /// (RelocationModel, PICLevel, IsPIE).
   3265 static std::tuple<llvm::Reloc::Model, unsigned, bool>
   3266 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
   3267              const ArgList &Args) {
   3268   // FIXME: why does this code...and so much everywhere else, use both
   3269   // ToolChain.getTriple() and Triple?
   3270   bool PIE = ToolChain.isPIEDefault();
   3271   bool PIC = PIE || ToolChain.isPICDefault();
   3272   // The Darwin default to use PIC does not apply when using -static.
   3273   if (ToolChain.getTriple().isOSDarwin() && Args.hasArg(options::OPT_static))
   3274     PIE = PIC = false;
   3275   bool IsPICLevelTwo = PIC;
   3276 
   3277   bool KernelOrKext =
   3278       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
   3279 
   3280   // Android-specific defaults for PIC/PIE
   3281   if (ToolChain.getTriple().isAndroid()) {
   3282     switch (ToolChain.getArch()) {
   3283     case llvm::Triple::arm:
   3284     case llvm::Triple::armeb:
   3285     case llvm::Triple::thumb:
   3286     case llvm::Triple::thumbeb:
   3287     case llvm::Triple::aarch64:
   3288     case llvm::Triple::mips:
   3289     case llvm::Triple::mipsel:
   3290     case llvm::Triple::mips64:
   3291     case llvm::Triple::mips64el:
   3292       PIC = true; // "-fpic"
   3293       break;
   3294 
   3295     case llvm::Triple::x86:
   3296     case llvm::Triple::x86_64:
   3297       PIC = true; // "-fPIC"
   3298       IsPICLevelTwo = true;
   3299       break;
   3300 
   3301     default:
   3302       break;
   3303     }
   3304   }
   3305 
   3306   // OpenBSD-specific defaults for PIE
   3307   if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
   3308     switch (ToolChain.getArch()) {
   3309     case llvm::Triple::mips64:
   3310     case llvm::Triple::mips64el:
   3311     case llvm::Triple::sparcel:
   3312     case llvm::Triple::x86:
   3313     case llvm::Triple::x86_64:
   3314       IsPICLevelTwo = false; // "-fpie"
   3315       break;
   3316 
   3317     case llvm::Triple::ppc:
   3318     case llvm::Triple::sparc:
   3319     case llvm::Triple::sparcv9:
   3320       IsPICLevelTwo = true; // "-fPIE"
   3321       break;
   3322 
   3323     default:
   3324       break;
   3325     }
   3326   }
   3327 
   3328   // The last argument relating to either PIC or PIE wins, and no
   3329   // other argument is used. If the last argument is any flavor of the
   3330   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
   3331   // option implicitly enables PIC at the same level.
   3332   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
   3333                                     options::OPT_fpic, options::OPT_fno_pic,
   3334                                     options::OPT_fPIE, options::OPT_fno_PIE,
   3335                                     options::OPT_fpie, options::OPT_fno_pie);
   3336   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
   3337   // is forced, then neither PIC nor PIE flags will have no effect.
   3338   if (!ToolChain.isPICDefaultForced()) {
   3339     if (LastPICArg) {
   3340       Option O = LastPICArg->getOption();
   3341       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
   3342           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
   3343         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
   3344         PIC =
   3345             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
   3346         IsPICLevelTwo =
   3347             O.matches(options::OPT_fPIE) || O.