xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp (revision 647cbc5de815c5651677bf8582797f716ec7b48d)
10b57cec5SDimitry Andric //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "Clang.h"
105ffd83dbSDimitry Andric #include "AMDGPU.h"
110b57cec5SDimitry Andric #include "Arch/AArch64.h"
120b57cec5SDimitry Andric #include "Arch/ARM.h"
1381ad6265SDimitry Andric #include "Arch/CSKY.h"
14bdd1243dSDimitry Andric #include "Arch/LoongArch.h"
15fe6060f1SDimitry Andric #include "Arch/M68k.h"
160b57cec5SDimitry Andric #include "Arch/Mips.h"
170b57cec5SDimitry Andric #include "Arch/PPC.h"
180b57cec5SDimitry Andric #include "Arch/RISCV.h"
190b57cec5SDimitry Andric #include "Arch/Sparc.h"
200b57cec5SDimitry Andric #include "Arch/SystemZ.h"
215ffd83dbSDimitry Andric #include "Arch/VE.h"
220b57cec5SDimitry Andric #include "Arch/X86.h"
230b57cec5SDimitry Andric #include "CommonArgs.h"
240b57cec5SDimitry Andric #include "Hexagon.h"
255ffd83dbSDimitry Andric #include "MSP430.h"
260b57cec5SDimitry Andric #include "PS4CPU.h"
27349cc55cSDimitry Andric #include "clang/Basic/CLWarnings.h"
280b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
29a7dea167SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
30bdd1243dSDimitry Andric #include "clang/Basic/HeaderInclude.h"
310b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
32753f127fSDimitry Andric #include "clang/Basic/MakeSupport.h"
330b57cec5SDimitry Andric #include "clang/Basic/ObjCRuntime.h"
340b57cec5SDimitry Andric #include "clang/Basic/Version.h"
3581ad6265SDimitry Andric #include "clang/Config/config.h"
3681ad6265SDimitry Andric #include "clang/Driver/Action.h"
370b57cec5SDimitry Andric #include "clang/Driver/Distro.h"
380b57cec5SDimitry Andric #include "clang/Driver/DriverDiagnostic.h"
39fe6060f1SDimitry Andric #include "clang/Driver/InputInfo.h"
400b57cec5SDimitry Andric #include "clang/Driver/Options.h"
410b57cec5SDimitry Andric #include "clang/Driver/SanitizerArgs.h"
4204eeddc0SDimitry Andric #include "clang/Driver/Types.h"
430b57cec5SDimitry Andric #include "clang/Driver/XRayArgs.h"
4481ad6265SDimitry Andric #include "llvm/ADT/SmallSet.h"
450b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
460b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
470b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
480b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
495ffd83dbSDimitry Andric #include "llvm/Support/Compiler.h"
500b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
5106c3fb27SDimitry Andric #include "llvm/Support/Error.h"
520b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
530b57cec5SDimitry Andric #include "llvm/Support/Path.h"
540b57cec5SDimitry Andric #include "llvm/Support/Process.h"
5506c3fb27SDimitry Andric #include "llvm/Support/RISCVISAInfo.h"
560b57cec5SDimitry Andric #include "llvm/Support/YAMLParser.h"
5706c3fb27SDimitry Andric #include "llvm/TargetParser/ARMTargetParserCommon.h"
5806c3fb27SDimitry Andric #include "llvm/TargetParser/Host.h"
598a4dda33SDimitry Andric #include "llvm/TargetParser/LoongArchTargetParser.h"
6006c3fb27SDimitry Andric #include "llvm/TargetParser/RISCVTargetParser.h"
61753f127fSDimitry Andric #include <cctype>
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric using namespace clang::driver;
640b57cec5SDimitry Andric using namespace clang::driver::tools;
650b57cec5SDimitry Andric using namespace clang;
660b57cec5SDimitry Andric using namespace llvm::opt;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
69349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
70349cc55cSDimitry Andric                                options::OPT_fminimize_whitespace,
715f757f3fSDimitry Andric                                options::OPT_fno_minimize_whitespace,
725f757f3fSDimitry Andric                                options::OPT_fkeep_system_includes,
735f757f3fSDimitry Andric                                options::OPT_fno_keep_system_includes)) {
740b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
750b57cec5SDimitry Andric         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
760b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
770b57cec5SDimitry Andric           << A->getBaseArg().getAsString(Args)
780b57cec5SDimitry Andric           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
790b57cec5SDimitry Andric     }
800b57cec5SDimitry Andric   }
810b57cec5SDimitry Andric }
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
840b57cec5SDimitry Andric   // In gcc, only ARM checks this, but it seems reasonable to check universally.
850b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_static))
860b57cec5SDimitry Andric     if (const Arg *A =
870b57cec5SDimitry Andric             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
880b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
890b57cec5SDimitry Andric                                                       << "-static";
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric // Add backslashes to escape spaces and other backslashes.
930b57cec5SDimitry Andric // This is used for the space-separated argument list specified with
940b57cec5SDimitry Andric // the -dwarf-debug-flags option.
950b57cec5SDimitry Andric static void EscapeSpacesAndBackslashes(const char *Arg,
960b57cec5SDimitry Andric                                        SmallVectorImpl<char> &Res) {
970b57cec5SDimitry Andric   for (; *Arg; ++Arg) {
980b57cec5SDimitry Andric     switch (*Arg) {
990b57cec5SDimitry Andric     default:
1000b57cec5SDimitry Andric       break;
1010b57cec5SDimitry Andric     case ' ':
1020b57cec5SDimitry Andric     case '\\':
1030b57cec5SDimitry Andric       Res.push_back('\\');
1040b57cec5SDimitry Andric       break;
1050b57cec5SDimitry Andric     }
1060b57cec5SDimitry Andric     Res.push_back(*Arg);
1070b57cec5SDimitry Andric   }
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric /// Apply \a Work on the current tool chain \a RegularToolChain and any other
1110b57cec5SDimitry Andric /// offloading tool chain that is associated with the current action \a JA.
1120b57cec5SDimitry Andric static void
1130b57cec5SDimitry Andric forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
1140b57cec5SDimitry Andric                            const ToolChain &RegularToolChain,
1150b57cec5SDimitry Andric                            llvm::function_ref<void(const ToolChain &)> Work) {
1160b57cec5SDimitry Andric   // Apply Work on the current/regular tool chain.
1170b57cec5SDimitry Andric   Work(RegularToolChain);
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric   // Apply Work on all the offloading tool chains associated with the current
1200b57cec5SDimitry Andric   // action.
1210b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_Cuda))
1220b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1230b57cec5SDimitry Andric   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
1240b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1250b57cec5SDimitry Andric   else if (JA.isHostOffloading(Action::OFK_HIP))
1260b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
1270b57cec5SDimitry Andric   else if (JA.isDeviceOffloading(Action::OFK_HIP))
1280b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
1310b57cec5SDimitry Andric     auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
1320b57cec5SDimitry Andric     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
1330b57cec5SDimitry Andric       Work(*II->second);
1340b57cec5SDimitry Andric   } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
1350b57cec5SDimitry Andric     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   //
1380b57cec5SDimitry Andric   // TODO: Add support for other offloading programming models here.
1390b57cec5SDimitry Andric   //
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric /// This is a helper function for validating the optional refinement step
1430b57cec5SDimitry Andric /// parameter in reciprocal argument strings. Return false if there is an error
1440b57cec5SDimitry Andric /// parsing the refinement step. Otherwise, return true and set the Position
1450b57cec5SDimitry Andric /// of the refinement step in the input string.
1460b57cec5SDimitry Andric static bool getRefinementStep(StringRef In, const Driver &D,
1470b57cec5SDimitry Andric                               const Arg &A, size_t &Position) {
1480b57cec5SDimitry Andric   const char RefinementStepToken = ':';
1490b57cec5SDimitry Andric   Position = In.find(RefinementStepToken);
1500b57cec5SDimitry Andric   if (Position != StringRef::npos) {
1510b57cec5SDimitry Andric     StringRef Option = A.getOption().getName();
1520b57cec5SDimitry Andric     StringRef RefStep = In.substr(Position + 1);
1530b57cec5SDimitry Andric     // Allow exactly one numeric character for the additional refinement
1540b57cec5SDimitry Andric     // step parameter. This is reasonable for all currently-supported
1550b57cec5SDimitry Andric     // operations and architectures because we would expect that a larger value
1560b57cec5SDimitry Andric     // of refinement steps would cause the estimate "optimization" to
1570b57cec5SDimitry Andric     // under-perform the native operation. Also, if the estimate does not
1580b57cec5SDimitry Andric     // converge quickly, it probably will not ever converge, so further
1590b57cec5SDimitry Andric     // refinement steps will not produce a better answer.
1600b57cec5SDimitry Andric     if (RefStep.size() != 1) {
1610b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1620b57cec5SDimitry Andric       return false;
1630b57cec5SDimitry Andric     }
1640b57cec5SDimitry Andric     char RefStepChar = RefStep[0];
1650b57cec5SDimitry Andric     if (RefStepChar < '0' || RefStepChar > '9') {
1660b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1670b57cec5SDimitry Andric       return false;
1680b57cec5SDimitry Andric     }
1690b57cec5SDimitry Andric   }
1700b57cec5SDimitry Andric   return true;
1710b57cec5SDimitry Andric }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric /// The -mrecip flag requires processing of many optional parameters.
1740b57cec5SDimitry Andric static void ParseMRecip(const Driver &D, const ArgList &Args,
1750b57cec5SDimitry Andric                         ArgStringList &OutStrings) {
1760b57cec5SDimitry Andric   StringRef DisabledPrefixIn = "!";
1770b57cec5SDimitry Andric   StringRef DisabledPrefixOut = "!";
1780b57cec5SDimitry Andric   StringRef EnabledPrefixOut = "";
1790b57cec5SDimitry Andric   StringRef Out = "-mrecip=";
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1820b57cec5SDimitry Andric   if (!A)
1830b57cec5SDimitry Andric     return;
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   unsigned NumOptions = A->getNumValues();
1860b57cec5SDimitry Andric   if (NumOptions == 0) {
1870b57cec5SDimitry Andric     // No option is the same as "all".
1880b57cec5SDimitry Andric     OutStrings.push_back(Args.MakeArgString(Out + "all"));
1890b57cec5SDimitry Andric     return;
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // Pass through "all", "none", or "default" with an optional refinement step.
1930b57cec5SDimitry Andric   if (NumOptions == 1) {
1940b57cec5SDimitry Andric     StringRef Val = A->getValue(0);
1950b57cec5SDimitry Andric     size_t RefStepLoc;
1960b57cec5SDimitry Andric     if (!getRefinementStep(Val, D, *A, RefStepLoc))
1970b57cec5SDimitry Andric       return;
1980b57cec5SDimitry Andric     StringRef ValBase = Val.slice(0, RefStepLoc);
1990b57cec5SDimitry Andric     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2000b57cec5SDimitry Andric       OutStrings.push_back(Args.MakeArgString(Out + Val));
2010b57cec5SDimitry Andric       return;
2020b57cec5SDimitry Andric     }
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   // Each reciprocal type may be enabled or disabled individually.
2060b57cec5SDimitry Andric   // Check each input value for validity, concatenate them all back together,
2070b57cec5SDimitry Andric   // and pass through.
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   llvm::StringMap<bool> OptionStrings;
2100b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("divd", false));
2110b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("divf", false));
21281ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("divh", false));
2130b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divd", false));
2140b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divf", false));
21581ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("vec-divh", false));
2160b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("sqrtd", false));
2170b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("sqrtf", false));
21881ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("sqrth", false));
2190b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2200b57cec5SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
22181ad6265SDimitry Andric   OptionStrings.insert(std::make_pair("vec-sqrth", false));
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric   for (unsigned i = 0; i != NumOptions; ++i) {
2240b57cec5SDimitry Andric     StringRef Val = A->getValue(i);
2250b57cec5SDimitry Andric 
2265f757f3fSDimitry Andric     bool IsDisabled = Val.starts_with(DisabledPrefixIn);
2270b57cec5SDimitry Andric     // Ignore the disablement token for string matching.
2280b57cec5SDimitry Andric     if (IsDisabled)
2290b57cec5SDimitry Andric       Val = Val.substr(1);
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric     size_t RefStep;
2320b57cec5SDimitry Andric     if (!getRefinementStep(Val, D, *A, RefStep))
2330b57cec5SDimitry Andric       return;
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     StringRef ValBase = Val.slice(0, RefStep);
2360b57cec5SDimitry Andric     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2370b57cec5SDimitry Andric     if (OptionIter == OptionStrings.end()) {
2380b57cec5SDimitry Andric       // Try again specifying float suffix.
2390b57cec5SDimitry Andric       OptionIter = OptionStrings.find(ValBase.str() + 'f');
2400b57cec5SDimitry Andric       if (OptionIter == OptionStrings.end()) {
2410b57cec5SDimitry Andric         // The input name did not match any known option string.
2420b57cec5SDimitry Andric         D.Diag(diag::err_drv_unknown_argument) << Val;
2430b57cec5SDimitry Andric         return;
2440b57cec5SDimitry Andric       }
24581ad6265SDimitry Andric       // The option was specified without a half or float or double suffix.
24681ad6265SDimitry Andric       // Make sure that the double or half entry was not already specified.
2470b57cec5SDimitry Andric       // The float entry will be checked below.
24881ad6265SDimitry Andric       if (OptionStrings[ValBase.str() + 'd'] ||
24981ad6265SDimitry Andric           OptionStrings[ValBase.str() + 'h']) {
2500b57cec5SDimitry Andric         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2510b57cec5SDimitry Andric         return;
2520b57cec5SDimitry Andric       }
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric     if (OptionIter->second == true) {
2560b57cec5SDimitry Andric       // Duplicate option specified.
2570b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2580b57cec5SDimitry Andric       return;
2590b57cec5SDimitry Andric     }
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric     // Mark the matched option as found. Do not allow duplicate specifiers.
2620b57cec5SDimitry Andric     OptionIter->second = true;
2630b57cec5SDimitry Andric 
26481ad6265SDimitry Andric     // If the precision was not specified, also mark the double and half entry
26581ad6265SDimitry Andric     // as found.
26681ad6265SDimitry Andric     if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
2670b57cec5SDimitry Andric       OptionStrings[ValBase.str() + 'd'] = true;
26881ad6265SDimitry Andric       OptionStrings[ValBase.str() + 'h'] = true;
26981ad6265SDimitry Andric     }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric     // Build the output string.
2720b57cec5SDimitry Andric     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2730b57cec5SDimitry Andric     Out = Args.MakeArgString(Out + Prefix + Val);
2740b57cec5SDimitry Andric     if (i != NumOptions - 1)
2750b57cec5SDimitry Andric       Out = Args.MakeArgString(Out + ",");
2760b57cec5SDimitry Andric   }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   OutStrings.push_back(Args.MakeArgString(Out));
2790b57cec5SDimitry Andric }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric /// The -mprefer-vector-width option accepts either a positive integer
2820b57cec5SDimitry Andric /// or the string "none".
2830b57cec5SDimitry Andric static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
2840b57cec5SDimitry Andric                                     ArgStringList &CmdArgs) {
2850b57cec5SDimitry Andric   Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
2860b57cec5SDimitry Andric   if (!A)
2870b57cec5SDimitry Andric     return;
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   StringRef Value = A->getValue();
2900b57cec5SDimitry Andric   if (Value == "none") {
2910b57cec5SDimitry Andric     CmdArgs.push_back("-mprefer-vector-width=none");
2920b57cec5SDimitry Andric   } else {
2930b57cec5SDimitry Andric     unsigned Width;
2940b57cec5SDimitry Andric     if (Value.getAsInteger(10, Width)) {
2950b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
2960b57cec5SDimitry Andric       return;
2970b57cec5SDimitry Andric     }
2980b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
2990b57cec5SDimitry Andric   }
3000b57cec5SDimitry Andric }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric static bool
3030b57cec5SDimitry Andric shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
3040b57cec5SDimitry Andric                                           const llvm::Triple &Triple) {
3050b57cec5SDimitry Andric   // We use the zero-cost exception tables for Objective-C if the non-fragile
3060b57cec5SDimitry Andric   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
3070b57cec5SDimitry Andric   // later.
3080b57cec5SDimitry Andric   if (runtime.isNonFragile())
3090b57cec5SDimitry Andric     return true;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   if (!Triple.isMacOSX())
3120b57cec5SDimitry Andric     return false;
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   return (!Triple.isMacOSXVersionLT(10, 5) &&
3150b57cec5SDimitry Andric           (Triple.getArch() == llvm::Triple::x86_64 ||
3160b57cec5SDimitry Andric            Triple.getArch() == llvm::Triple::arm));
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric /// Adds exception related arguments to the driver command arguments. There's a
3204824e7fdSDimitry Andric /// main flag, -fexceptions and also language specific flags to enable/disable
3210b57cec5SDimitry Andric /// C++ and Objective-C exceptions. This makes it possible to for example
3220b57cec5SDimitry Andric /// disable C++ exceptions but enable Objective-C exceptions.
323fe6060f1SDimitry Andric static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
3240b57cec5SDimitry Andric                              const ToolChain &TC, bool KernelOrKext,
3250b57cec5SDimitry Andric                              const ObjCRuntime &objcRuntime,
3260b57cec5SDimitry Andric                              ArgStringList &CmdArgs) {
3270b57cec5SDimitry Andric   const llvm::Triple &Triple = TC.getTriple();
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   if (KernelOrKext) {
3300b57cec5SDimitry Andric     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
3310b57cec5SDimitry Andric     // arguments now to avoid warnings about unused arguments.
3320b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fexceptions);
3330b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_exceptions);
3340b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
3350b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
3360b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
3370b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
338fe6060f1SDimitry Andric     Args.ClaimAllArgs(options::OPT_fasync_exceptions);
339fe6060f1SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
340fe6060f1SDimitry Andric     return false;
3410b57cec5SDimitry Andric   }
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   // See if the user explicitly enabled exceptions.
3440b57cec5SDimitry Andric   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
3450b57cec5SDimitry Andric                          false);
3460b57cec5SDimitry Andric 
347fe6060f1SDimitry Andric   bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
348fe6060f1SDimitry Andric                           options::OPT_fno_async_exceptions, false);
349fe6060f1SDimitry Andric   if (EHa) {
350fe6060f1SDimitry Andric     CmdArgs.push_back("-fasync-exceptions");
351fe6060f1SDimitry Andric     EH = true;
352fe6060f1SDimitry Andric   }
353fe6060f1SDimitry Andric 
3540b57cec5SDimitry Andric   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
3550b57cec5SDimitry Andric   // is not necessarily sensible, but follows GCC.
3560b57cec5SDimitry Andric   if (types::isObjC(InputType) &&
3570b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fobjc_exceptions,
3580b57cec5SDimitry Andric                    options::OPT_fno_objc_exceptions, true)) {
3590b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-exceptions");
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   if (types::isCXX(InputType)) {
36581ad6265SDimitry Andric     // Disable C++ EH by default on XCore and PS4/PS5.
36681ad6265SDimitry Andric     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
36781ad6265SDimitry Andric                                 !Triple.isPS() && !Triple.isDriverKit();
3680b57cec5SDimitry Andric     Arg *ExceptionArg = Args.getLastArg(
3690b57cec5SDimitry Andric         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
3700b57cec5SDimitry Andric         options::OPT_fexceptions, options::OPT_fno_exceptions);
3710b57cec5SDimitry Andric     if (ExceptionArg)
3720b57cec5SDimitry Andric       CXXExceptionsEnabled =
3730b57cec5SDimitry Andric           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
3740b57cec5SDimitry Andric           ExceptionArg->getOption().matches(options::OPT_fexceptions);
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric     if (CXXExceptionsEnabled) {
3770b57cec5SDimitry Andric       CmdArgs.push_back("-fcxx-exceptions");
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric       EH = true;
3800b57cec5SDimitry Andric     }
3810b57cec5SDimitry Andric   }
3820b57cec5SDimitry Andric 
3835ffd83dbSDimitry Andric   // OPT_fignore_exceptions means exception could still be thrown,
3845ffd83dbSDimitry Andric   // but no clean up or catch would happen in current module.
3855ffd83dbSDimitry Andric   // So we do not set EH to false.
3865ffd83dbSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
3875ffd83dbSDimitry Andric 
3885f757f3fSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
3895f757f3fSDimitry Andric                     options::OPT_fno_assume_nothrow_exception_dtor);
3905f757f3fSDimitry Andric 
3910b57cec5SDimitry Andric   if (EH)
3920b57cec5SDimitry Andric     CmdArgs.push_back("-fexceptions");
393fe6060f1SDimitry Andric   return EH;
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
396480093f4SDimitry Andric static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
397480093f4SDimitry Andric                                  const JobAction &JA) {
3980b57cec5SDimitry Andric   bool Default = true;
3990b57cec5SDimitry Andric   if (TC.getTriple().isOSDarwin()) {
4000b57cec5SDimitry Andric     // The native darwin assembler doesn't support the linker_option directives,
4010b57cec5SDimitry Andric     // so we disable them if we think the .s file will be passed to it.
4020b57cec5SDimitry Andric     Default = TC.useIntegratedAs();
4030b57cec5SDimitry Andric   }
404480093f4SDimitry Andric   // The linker_option directives are intended for host compilation.
405480093f4SDimitry Andric   if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
406480093f4SDimitry Andric       JA.isDeviceOffloading(Action::OFK_HIP))
407480093f4SDimitry Andric     Default = false;
408480093f4SDimitry Andric   return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
4090b57cec5SDimitry Andric                       Default);
4100b57cec5SDimitry Andric }
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric /// Add a CC1 option to specify the debug compilation directory.
4130eae32dcSDimitry Andric static const char *addDebugCompDirArg(const ArgList &Args,
4140eae32dcSDimitry Andric                                       ArgStringList &CmdArgs,
415a7dea167SDimitry Andric                                       const llvm::vfs::FileSystem &VFS) {
416fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
417fe6060f1SDimitry Andric                                options::OPT_fdebug_compilation_dir_EQ)) {
418fe6060f1SDimitry Andric     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
419fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
420fe6060f1SDimitry Andric                                            A->getValue()));
421fe6060f1SDimitry Andric     else
422fe6060f1SDimitry Andric       A->render(Args, CmdArgs);
423a7dea167SDimitry Andric   } else if (llvm::ErrorOr<std::string> CWD =
424a7dea167SDimitry Andric                  VFS.getCurrentWorkingDirectory()) {
425fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
4260b57cec5SDimitry Andric   }
4270eae32dcSDimitry Andric   StringRef Path(CmdArgs.back());
4280eae32dcSDimitry Andric   return Path.substr(Path.find('=') + 1).data();
4290eae32dcSDimitry Andric }
4300eae32dcSDimitry Andric 
4310eae32dcSDimitry Andric static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
4320eae32dcSDimitry Andric                                const char *DebugCompilationDir,
4330eae32dcSDimitry Andric                                const char *OutputFileName) {
4340eae32dcSDimitry Andric   // No need to generate a value for -object-file-name if it was provided.
4350eae32dcSDimitry Andric   for (auto *Arg : Args.filtered(options::OPT_Xclang))
4365f757f3fSDimitry Andric     if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
4370eae32dcSDimitry Andric       return;
4380eae32dcSDimitry Andric 
4390eae32dcSDimitry Andric   if (Args.hasArg(options::OPT_object_file_name_EQ))
4400eae32dcSDimitry Andric     return;
4410eae32dcSDimitry Andric 
4420eae32dcSDimitry Andric   SmallString<128> ObjFileNameForDebug(OutputFileName);
4430eae32dcSDimitry Andric   if (ObjFileNameForDebug != "-" &&
4440eae32dcSDimitry Andric       !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
4450eae32dcSDimitry Andric       (!DebugCompilationDir ||
4460eae32dcSDimitry Andric        llvm::sys::path::is_absolute(DebugCompilationDir))) {
4470eae32dcSDimitry Andric     // Make the path absolute in the debug infos like MSVC does.
4480eae32dcSDimitry Andric     llvm::sys::fs::make_absolute(ObjFileNameForDebug);
4490eae32dcSDimitry Andric   }
45006c3fb27SDimitry Andric   // If the object file name is a relative path, then always use Windows
45106c3fb27SDimitry Andric   // backslash style as -object-file-name is used for embedding object file path
45206c3fb27SDimitry Andric   // in codeview and it can only be generated when targeting on Windows.
45306c3fb27SDimitry Andric   // Otherwise, just use native absolute path.
45406c3fb27SDimitry Andric   llvm::sys::path::Style Style =
45506c3fb27SDimitry Andric       llvm::sys::path::is_absolute(ObjFileNameForDebug)
45606c3fb27SDimitry Andric           ? llvm::sys::path::Style::native
45706c3fb27SDimitry Andric           : llvm::sys::path::Style::windows_backslash;
45806c3fb27SDimitry Andric   llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
45906c3fb27SDimitry Andric                                Style);
4600eae32dcSDimitry Andric   CmdArgs.push_back(
4610eae32dcSDimitry Andric       Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
46581ad6265SDimitry Andric static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
46681ad6265SDimitry Andric                                  const ArgList &Args, ArgStringList &CmdArgs) {
46781ad6265SDimitry Andric   auto AddOneArg = [&](StringRef Map, StringRef Name) {
468349cc55cSDimitry Andric     if (!Map.contains('='))
46981ad6265SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
4700b57cec5SDimitry Andric     else
4710b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
47281ad6265SDimitry Andric   };
47381ad6265SDimitry Andric 
47481ad6265SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
47581ad6265SDimitry Andric                                     options::OPT_fdebug_prefix_map_EQ)) {
47681ad6265SDimitry Andric     AddOneArg(A->getValue(), A->getOption().getName());
4770b57cec5SDimitry Andric     A->claim();
4780b57cec5SDimitry Andric   }
47981ad6265SDimitry Andric   std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
48081ad6265SDimitry Andric   if (GlobalRemapEntry.empty())
48181ad6265SDimitry Andric     return;
48281ad6265SDimitry Andric   AddOneArg(GlobalRemapEntry, "environment");
4830b57cec5SDimitry Andric }
4840b57cec5SDimitry Andric 
485480093f4SDimitry Andric /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
486480093f4SDimitry Andric static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
487480093f4SDimitry Andric                                  ArgStringList &CmdArgs) {
488480093f4SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
489480093f4SDimitry Andric                                     options::OPT_fmacro_prefix_map_EQ)) {
490480093f4SDimitry Andric     StringRef Map = A->getValue();
491349cc55cSDimitry Andric     if (!Map.contains('='))
492480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
493480093f4SDimitry Andric           << Map << A->getOption().getName();
494480093f4SDimitry Andric     else
495480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
496480093f4SDimitry Andric     A->claim();
497480093f4SDimitry Andric   }
498480093f4SDimitry Andric }
499480093f4SDimitry Andric 
500e8d8bef9SDimitry Andric /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
501fe6060f1SDimitry Andric static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
502e8d8bef9SDimitry Andric                                    ArgStringList &CmdArgs) {
503e8d8bef9SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
504fe6060f1SDimitry Andric                                     options::OPT_fcoverage_prefix_map_EQ)) {
505e8d8bef9SDimitry Andric     StringRef Map = A->getValue();
506349cc55cSDimitry Andric     if (!Map.contains('='))
507e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
508e8d8bef9SDimitry Andric           << Map << A->getOption().getName();
509e8d8bef9SDimitry Andric     else
510fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
511e8d8bef9SDimitry Andric     A->claim();
512e8d8bef9SDimitry Andric   }
513e8d8bef9SDimitry Andric }
514e8d8bef9SDimitry Andric 
5150b57cec5SDimitry Andric /// Vectorize at all optimization levels greater than 1 except for -Oz.
5160b57cec5SDimitry Andric /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
5170b57cec5SDimitry Andric /// enabled.
5180b57cec5SDimitry Andric static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
5190b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5200b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O4) ||
5210b57cec5SDimitry Andric         A->getOption().matches(options::OPT_Ofast))
5220b57cec5SDimitry Andric       return true;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O0))
5250b57cec5SDimitry Andric       return false;
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric     // Vectorize -Os.
5300b57cec5SDimitry Andric     StringRef S(A->getValue());
5310b57cec5SDimitry Andric     if (S == "s")
5320b57cec5SDimitry Andric       return true;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric     // Don't vectorize -Oz, unless it's the slp vectorizer.
5350b57cec5SDimitry Andric     if (S == "z")
5360b57cec5SDimitry Andric       return isSlpVec;
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric     unsigned OptLevel = 0;
5390b57cec5SDimitry Andric     if (S.getAsInteger(10, OptLevel))
5400b57cec5SDimitry Andric       return false;
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric     return OptLevel > 1;
5430b57cec5SDimitry Andric   }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   return false;
5460b57cec5SDimitry Andric }
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric /// Add -x lang to \p CmdArgs for \p Input.
5490b57cec5SDimitry Andric static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
5500b57cec5SDimitry Andric                              ArgStringList &CmdArgs) {
5510b57cec5SDimitry Andric   // When using -verify-pch, we don't want to provide the type
5520b57cec5SDimitry Andric   // 'precompiled-header' if it was inferred from the file extension
5530b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
5540b57cec5SDimitry Andric     return;
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric   CmdArgs.push_back("-x");
5570b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_rewrite_objc))
5580b57cec5SDimitry Andric     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
5590b57cec5SDimitry Andric   else {
5600b57cec5SDimitry Andric     // Map the driver type to the frontend type. This is mostly an identity
5610b57cec5SDimitry Andric     // mapping, except that the distinction between module interface units
5620b57cec5SDimitry Andric     // and other source files does not exist at the frontend layer.
5630b57cec5SDimitry Andric     const char *ClangType;
5640b57cec5SDimitry Andric     switch (Input.getType()) {
5650b57cec5SDimitry Andric     case types::TY_CXXModule:
5660b57cec5SDimitry Andric       ClangType = "c++";
5670b57cec5SDimitry Andric       break;
5680b57cec5SDimitry Andric     case types::TY_PP_CXXModule:
5690b57cec5SDimitry Andric       ClangType = "c++-cpp-output";
5700b57cec5SDimitry Andric       break;
5710b57cec5SDimitry Andric     default:
5720b57cec5SDimitry Andric       ClangType = types::getTypeName(Input.getType());
5730b57cec5SDimitry Andric       break;
5740b57cec5SDimitry Andric     }
5750b57cec5SDimitry Andric     CmdArgs.push_back(ClangType);
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric }
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
58006c3fb27SDimitry Andric                                    const JobAction &JA, const InputInfo &Output,
581349cc55cSDimitry Andric                                    const ArgList &Args, SanitizerArgs &SanArgs,
5820b57cec5SDimitry Andric                                    ArgStringList &CmdArgs) {
58306c3fb27SDimitry Andric   const Driver &D = TC.getDriver();
5840b57cec5SDimitry Andric   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
5850b57cec5SDimitry Andric                                          options::OPT_fprofile_generate_EQ,
5860b57cec5SDimitry Andric                                          options::OPT_fno_profile_generate);
5870b57cec5SDimitry Andric   if (PGOGenerateArg &&
5880b57cec5SDimitry Andric       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
5890b57cec5SDimitry Andric     PGOGenerateArg = nullptr;
5900b57cec5SDimitry Andric 
59106c3fb27SDimitry Andric   auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   auto *ProfileGenerateArg = Args.getLastArg(
5940b57cec5SDimitry Andric       options::OPT_fprofile_instr_generate,
5950b57cec5SDimitry Andric       options::OPT_fprofile_instr_generate_EQ,
5960b57cec5SDimitry Andric       options::OPT_fno_profile_instr_generate);
5970b57cec5SDimitry Andric   if (ProfileGenerateArg &&
5980b57cec5SDimitry Andric       ProfileGenerateArg->getOption().matches(
5990b57cec5SDimitry Andric           options::OPT_fno_profile_instr_generate))
6000b57cec5SDimitry Andric     ProfileGenerateArg = nullptr;
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   if (PGOGenerateArg && ProfileGenerateArg)
6030b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6040b57cec5SDimitry Andric         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   auto *ProfileUseArg = getLastProfileUseArg(Args);
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   if (PGOGenerateArg && ProfileUseArg)
6090b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6100b57cec5SDimitry Andric         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   if (ProfileGenerateArg && ProfileUseArg)
6130b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6140b57cec5SDimitry Andric         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
6150b57cec5SDimitry Andric 
616e8d8bef9SDimitry Andric   if (CSPGOGenerateArg && PGOGenerateArg) {
6170b57cec5SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
6180b57cec5SDimitry Andric         << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
619e8d8bef9SDimitry Andric     PGOGenerateArg = nullptr;
620e8d8bef9SDimitry Andric   }
6210b57cec5SDimitry Andric 
622fe6060f1SDimitry Andric   if (TC.getTriple().isOSAIX()) {
623fe6060f1SDimitry Andric     if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
624fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
625fe6060f1SDimitry Andric           << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
626fe6060f1SDimitry Andric   }
627fe6060f1SDimitry Andric 
6280b57cec5SDimitry Andric   if (ProfileGenerateArg) {
6290b57cec5SDimitry Andric     if (ProfileGenerateArg->getOption().matches(
6300b57cec5SDimitry Andric             options::OPT_fprofile_instr_generate_EQ))
6310b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
6320b57cec5SDimitry Andric                                            ProfileGenerateArg->getValue()));
6330b57cec5SDimitry Andric     // The default is to use Clang Instrumentation.
6340b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=clang");
6350b57cec5SDimitry Andric     if (TC.getTriple().isWindowsMSVCEnvironment()) {
6360b57cec5SDimitry Andric       // Add dependent lib for clang_rt.profile
6375ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6385ffd83dbSDimitry Andric           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
6390b57cec5SDimitry Andric     }
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   Arg *PGOGenArg = nullptr;
6430b57cec5SDimitry Andric   if (PGOGenerateArg) {
6440b57cec5SDimitry Andric     assert(!CSPGOGenerateArg);
6450b57cec5SDimitry Andric     PGOGenArg = PGOGenerateArg;
6460b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=llvm");
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric   if (CSPGOGenerateArg) {
6490b57cec5SDimitry Andric     assert(!PGOGenerateArg);
6500b57cec5SDimitry Andric     PGOGenArg = CSPGOGenerateArg;
6510b57cec5SDimitry Andric     CmdArgs.push_back("-fprofile-instrument=csllvm");
6520b57cec5SDimitry Andric   }
6530b57cec5SDimitry Andric   if (PGOGenArg) {
6540b57cec5SDimitry Andric     if (TC.getTriple().isWindowsMSVCEnvironment()) {
6555ffd83dbSDimitry Andric       // Add dependent lib for clang_rt.profile
6565ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6575ffd83dbSDimitry Andric           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
6580b57cec5SDimitry Andric     }
6590b57cec5SDimitry Andric     if (PGOGenArg->getOption().matches(
6600b57cec5SDimitry Andric             PGOGenerateArg ? options::OPT_fprofile_generate_EQ
6610b57cec5SDimitry Andric                            : options::OPT_fcs_profile_generate_EQ)) {
6620b57cec5SDimitry Andric       SmallString<128> Path(PGOGenArg->getValue());
6630b57cec5SDimitry Andric       llvm::sys::path::append(Path, "default_%m.profraw");
6640b57cec5SDimitry Andric       CmdArgs.push_back(
6650b57cec5SDimitry Andric           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
6660b57cec5SDimitry Andric     }
6670b57cec5SDimitry Andric   }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   if (ProfileUseArg) {
6700b57cec5SDimitry Andric     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
6710b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
6720b57cec5SDimitry Andric           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
6730b57cec5SDimitry Andric     else if ((ProfileUseArg->getOption().matches(
6740b57cec5SDimitry Andric                   options::OPT_fprofile_use_EQ) ||
6750b57cec5SDimitry Andric               ProfileUseArg->getOption().matches(
6760b57cec5SDimitry Andric                   options::OPT_fprofile_instr_use))) {
6770b57cec5SDimitry Andric       SmallString<128> Path(
6780b57cec5SDimitry Andric           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
6790b57cec5SDimitry Andric       if (Path.empty() || llvm::sys::fs::is_directory(Path))
6800b57cec5SDimitry Andric         llvm::sys::path::append(Path, "default.profdata");
6810b57cec5SDimitry Andric       CmdArgs.push_back(
6820b57cec5SDimitry Andric           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
6830b57cec5SDimitry Andric     }
6840b57cec5SDimitry Andric   }
6850b57cec5SDimitry Andric 
6865ffd83dbSDimitry Andric   bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
6875ffd83dbSDimitry Andric                                    options::OPT_fno_test_coverage, false) ||
688a7dea167SDimitry Andric                       Args.hasArg(options::OPT_coverage);
6895ffd83dbSDimitry Andric   bool EmitCovData = TC.needsGCovInstrumentation(Args);
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fcoverage_mapping,
6920b57cec5SDimitry Andric                    options::OPT_fno_coverage_mapping, false)) {
6930b57cec5SDimitry Andric     if (!ProfileGenerateArg)
6940b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
6950b57cec5SDimitry Andric           << "-fcoverage-mapping"
6960b57cec5SDimitry Andric           << "-fprofile-instr-generate";
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric     CmdArgs.push_back("-fcoverage-mapping");
6990b57cec5SDimitry Andric   }
7000b57cec5SDimitry Andric 
701fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
702fe6060f1SDimitry Andric                                options::OPT_fcoverage_compilation_dir_EQ)) {
703fe6060f1SDimitry Andric     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
704fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
705fe6060f1SDimitry Andric           Twine("-fcoverage-compilation-dir=") + A->getValue()));
706fe6060f1SDimitry Andric     else
707fe6060f1SDimitry Andric       A->render(Args, CmdArgs);
708fe6060f1SDimitry Andric   } else if (llvm::ErrorOr<std::string> CWD =
709fe6060f1SDimitry Andric                  D.getVFS().getCurrentWorkingDirectory()) {
710fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
711fe6060f1SDimitry Andric   }
712fe6060f1SDimitry Andric 
7130b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
7140b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
7150b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_coverage))
7160b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7170b57cec5SDimitry Andric           << "-fprofile-exclude-files="
7180b57cec5SDimitry Andric           << "--coverage";
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric     StringRef v = Arg->getValue();
7210b57cec5SDimitry Andric     CmdArgs.push_back(
7220b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
7230b57cec5SDimitry Andric   }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
7260b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
7270b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_coverage))
7280b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
7290b57cec5SDimitry Andric           << "-fprofile-filter-files="
7300b57cec5SDimitry Andric           << "--coverage";
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric     StringRef v = Arg->getValue();
7330b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric 
736e8d8bef9SDimitry Andric   if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
737e8d8bef9SDimitry Andric     StringRef Val = A->getValue();
738e8d8bef9SDimitry Andric     if (Val == "atomic" || Val == "prefer-atomic")
739e8d8bef9SDimitry Andric       CmdArgs.push_back("-fprofile-update=atomic");
740e8d8bef9SDimitry Andric     else if (Val != "single")
741e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
742bdd1243dSDimitry Andric           << A->getSpelling() << Val;
743e8d8bef9SDimitry Andric   }
744e8d8bef9SDimitry Andric 
745fcaf7f86SDimitry Andric   int FunctionGroups = 1;
746fcaf7f86SDimitry Andric   int SelectedFunctionGroup = 0;
747fcaf7f86SDimitry Andric   if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
748fcaf7f86SDimitry Andric     StringRef Val = A->getValue();
749fcaf7f86SDimitry Andric     if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
750fcaf7f86SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
751fcaf7f86SDimitry Andric   }
752fcaf7f86SDimitry Andric   if (const auto *A =
753fcaf7f86SDimitry Andric           Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
754fcaf7f86SDimitry Andric     StringRef Val = A->getValue();
755fcaf7f86SDimitry Andric     if (Val.getAsInteger(0, SelectedFunctionGroup) ||
756fcaf7f86SDimitry Andric         SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
757fcaf7f86SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
758fcaf7f86SDimitry Andric   }
759fcaf7f86SDimitry Andric   if (FunctionGroups != 1)
760fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
761fcaf7f86SDimitry Andric                                          Twine(FunctionGroups)));
762fcaf7f86SDimitry Andric   if (SelectedFunctionGroup != 0)
763fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
764fcaf7f86SDimitry Andric                                          Twine(SelectedFunctionGroup)));
765fcaf7f86SDimitry Andric 
766a7dea167SDimitry Andric   // Leave -fprofile-dir= an unused argument unless .gcda emission is
767a7dea167SDimitry Andric   // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
768a7dea167SDimitry Andric   // the flag used. There is no -fno-profile-dir, so the user has no
769a7dea167SDimitry Andric   // targeted way to suppress the warning.
770a7dea167SDimitry Andric   Arg *FProfileDir = nullptr;
771a7dea167SDimitry Andric   if (Args.hasArg(options::OPT_fprofile_arcs) ||
772a7dea167SDimitry Andric       Args.hasArg(options::OPT_coverage))
773a7dea167SDimitry Andric     FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
774a7dea167SDimitry Andric 
77506c3fb27SDimitry Andric   // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
77606c3fb27SDimitry Andric   // like we warn about -fsyntax-only -E.
77706c3fb27SDimitry Andric   (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
77806c3fb27SDimitry Andric 
77906c3fb27SDimitry Andric   // Put the .gcno and .gcda files (if needed) next to the primary output file,
78006c3fb27SDimitry Andric   // or fall back to a file in the current directory for `clang -c --coverage
78106c3fb27SDimitry Andric   // d/a.c` in the absence of -o.
78206c3fb27SDimitry Andric   if (EmitCovNotes || EmitCovData) {
78306c3fb27SDimitry Andric     SmallString<128> CoverageFilename;
78406c3fb27SDimitry Andric     if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
78506c3fb27SDimitry Andric       // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
78606c3fb27SDimitry Andric       // path separator.
78706c3fb27SDimitry Andric       CoverageFilename = DumpDir->getValue();
78806c3fb27SDimitry Andric       CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
78906c3fb27SDimitry Andric     } else if (Arg *FinalOutput =
79006c3fb27SDimitry Andric                    C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
79106c3fb27SDimitry Andric       CoverageFilename = FinalOutput->getValue();
79206c3fb27SDimitry Andric     } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
79306c3fb27SDimitry Andric       CoverageFilename = FinalOutput->getValue();
79406c3fb27SDimitry Andric     } else {
79506c3fb27SDimitry Andric       CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
79606c3fb27SDimitry Andric     }
797a7dea167SDimitry Andric     if (llvm::sys::path::is_relative(CoverageFilename))
798a7dea167SDimitry Andric       (void)D.getVFS().makeAbsolute(CoverageFilename);
7990b57cec5SDimitry Andric     llvm::sys::path::replace_extension(CoverageFilename, "gcno");
80006c3fb27SDimitry Andric     if (EmitCovNotes) {
8015f757f3fSDimitry Andric       CmdArgs.push_back(
8025f757f3fSDimitry Andric           Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
80306c3fb27SDimitry Andric     }
8040b57cec5SDimitry Andric 
805a7dea167SDimitry Andric     if (EmitCovData) {
806a7dea167SDimitry Andric       if (FProfileDir) {
80706c3fb27SDimitry Andric         SmallString<128> Gcno = std::move(CoverageFilename);
8080b57cec5SDimitry Andric         CoverageFilename = FProfileDir->getValue();
80906c3fb27SDimitry Andric         llvm::sys::path::append(CoverageFilename, Gcno);
8100b57cec5SDimitry Andric       }
8110b57cec5SDimitry Andric       llvm::sys::path::replace_extension(CoverageFilename, "gcda");
8125f757f3fSDimitry Andric       CmdArgs.push_back(
8135f757f3fSDimitry Andric           Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
8140b57cec5SDimitry Andric     }
8150b57cec5SDimitry Andric   }
8160b57cec5SDimitry Andric }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric /// Check whether the given input tree contains any compilation actions.
8190b57cec5SDimitry Andric static bool ContainsCompileAction(const Action *A) {
8200b57cec5SDimitry Andric   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
8210b57cec5SDimitry Andric     return true;
8220b57cec5SDimitry Andric 
8230eae32dcSDimitry Andric   return llvm::any_of(A->inputs(), ContainsCompileAction);
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric /// Check if -relax-all should be passed to the internal assembler.
8270b57cec5SDimitry Andric /// This is done by default when compiling non-assembler source with -O0.
8280b57cec5SDimitry Andric static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
8290b57cec5SDimitry Andric   bool RelaxDefault = true;
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
8320b57cec5SDimitry Andric     RelaxDefault = A->getOption().matches(options::OPT_O0);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   if (RelaxDefault) {
8350b57cec5SDimitry Andric     RelaxDefault = false;
8360b57cec5SDimitry Andric     for (const auto &Act : C.getActions()) {
8370b57cec5SDimitry Andric       if (ContainsCompileAction(Act)) {
8380b57cec5SDimitry Andric         RelaxDefault = true;
8390b57cec5SDimitry Andric         break;
8400b57cec5SDimitry Andric       }
8410b57cec5SDimitry Andric     }
8420b57cec5SDimitry Andric   }
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
8450b57cec5SDimitry Andric                       RelaxDefault);
8460b57cec5SDimitry Andric }
8470b57cec5SDimitry Andric 
84806c3fb27SDimitry Andric static void
84906c3fb27SDimitry Andric RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
85006c3fb27SDimitry Andric                         llvm::codegenoptions::DebugInfoKind DebugInfoKind,
8510b57cec5SDimitry Andric                         unsigned DwarfVersion,
8520b57cec5SDimitry Andric                         llvm::DebuggerKind DebuggerTuning) {
85306c3fb27SDimitry Andric   addDebugInfoKind(CmdArgs, DebugInfoKind);
8540b57cec5SDimitry Andric   if (DwarfVersion > 0)
8550b57cec5SDimitry Andric     CmdArgs.push_back(
8560b57cec5SDimitry Andric         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
8570b57cec5SDimitry Andric   switch (DebuggerTuning) {
8580b57cec5SDimitry Andric   case llvm::DebuggerKind::GDB:
8590b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=gdb");
8600b57cec5SDimitry Andric     break;
8610b57cec5SDimitry Andric   case llvm::DebuggerKind::LLDB:
8620b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=lldb");
8630b57cec5SDimitry Andric     break;
8640b57cec5SDimitry Andric   case llvm::DebuggerKind::SCE:
8650b57cec5SDimitry Andric     CmdArgs.push_back("-debugger-tuning=sce");
8660b57cec5SDimitry Andric     break;
867fe6060f1SDimitry Andric   case llvm::DebuggerKind::DBX:
868fe6060f1SDimitry Andric     CmdArgs.push_back("-debugger-tuning=dbx");
869fe6060f1SDimitry Andric     break;
8700b57cec5SDimitry Andric   default:
8710b57cec5SDimitry Andric     break;
8720b57cec5SDimitry Andric   }
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
8760b57cec5SDimitry Andric                                  const Driver &D, const ToolChain &TC) {
8770b57cec5SDimitry Andric   assert(A && "Expected non-nullptr argument.");
8780b57cec5SDimitry Andric   if (TC.supportsDebugInfoOption(A))
8790b57cec5SDimitry Andric     return true;
8800b57cec5SDimitry Andric   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
8810b57cec5SDimitry Andric       << A->getAsString(Args) << TC.getTripleString();
8820b57cec5SDimitry Andric   return false;
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric static void RenderDebugInfoCompressionArgs(const ArgList &Args,
8860b57cec5SDimitry Andric                                            ArgStringList &CmdArgs,
8870b57cec5SDimitry Andric                                            const Driver &D,
8880b57cec5SDimitry Andric                                            const ToolChain &TC) {
889e8d8bef9SDimitry Andric   const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
8900b57cec5SDimitry Andric   if (!A)
8910b57cec5SDimitry Andric     return;
8920b57cec5SDimitry Andric   if (checkDebugInfoOption(A, Args, D, TC)) {
8930b57cec5SDimitry Andric     StringRef Value = A->getValue();
8940b57cec5SDimitry Andric     if (Value == "none") {
8950b57cec5SDimitry Andric       CmdArgs.push_back("--compress-debug-sections=none");
89604eeddc0SDimitry Andric     } else if (Value == "zlib") {
897753f127fSDimitry Andric       if (llvm::compression::zlib::isAvailable()) {
8980b57cec5SDimitry Andric         CmdArgs.push_back(
8990b57cec5SDimitry Andric             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
9000b57cec5SDimitry Andric       } else {
901bdd1243dSDimitry Andric         D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
902bdd1243dSDimitry Andric       }
903bdd1243dSDimitry Andric     } else if (Value == "zstd") {
904bdd1243dSDimitry Andric       if (llvm::compression::zstd::isAvailable()) {
905bdd1243dSDimitry Andric         CmdArgs.push_back(
906bdd1243dSDimitry Andric             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
907bdd1243dSDimitry Andric       } else {
908bdd1243dSDimitry Andric         D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
9090b57cec5SDimitry Andric       }
9100b57cec5SDimitry Andric     } else {
9110b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
912bdd1243dSDimitry Andric           << A->getSpelling() << Value;
9130b57cec5SDimitry Andric     }
9140b57cec5SDimitry Andric   }
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric 
917e8d8bef9SDimitry Andric static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
918e8d8bef9SDimitry Andric                                                  const ArgList &Args,
91981ad6265SDimitry Andric                                                  ArgStringList &CmdArgs,
92081ad6265SDimitry Andric                                                  bool IsCC1As = false) {
921fe6060f1SDimitry Andric   // If no version was requested by the user, use the default value from the
922fe6060f1SDimitry Andric   // back end. This is consistent with the value returned from
923fe6060f1SDimitry Andric   // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
924fe6060f1SDimitry Andric   // requiring the corresponding llvm to have the AMDGPU target enabled,
925fe6060f1SDimitry Andric   // provided the user (e.g. front end tests) can use the default.
926fe6060f1SDimitry Andric   if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
927fe6060f1SDimitry Andric     unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
928e8d8bef9SDimitry Andric     CmdArgs.insert(CmdArgs.begin() + 1,
929e8d8bef9SDimitry Andric                    Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
930e8d8bef9SDimitry Andric                                       Twine(CodeObjVer)));
931e8d8bef9SDimitry Andric     CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
93281ad6265SDimitry Andric     // -cc1as does not accept -mcode-object-version option.
93381ad6265SDimitry Andric     if (!IsCC1As)
93481ad6265SDimitry Andric       CmdArgs.insert(CmdArgs.begin() + 1,
93581ad6265SDimitry Andric                      Args.MakeArgString(Twine("-mcode-object-version=") +
93681ad6265SDimitry Andric                                         Twine(CodeObjVer)));
937e8d8bef9SDimitry Andric   }
938fe6060f1SDimitry Andric }
9390b57cec5SDimitry Andric 
9405f757f3fSDimitry Andric static bool hasClangPchSignature(const Driver &D, StringRef Path) {
9415f757f3fSDimitry Andric   if (llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
9425f757f3fSDimitry Andric           D.getVFS().getBufferForFile(Path))
9435f757f3fSDimitry Andric     return (*MemBuf)->getBuffer().starts_with("CPCH");
9445f757f3fSDimitry Andric   return false;
9455f757f3fSDimitry Andric }
9465f757f3fSDimitry Andric 
9475f757f3fSDimitry Andric static bool gchProbe(const Driver &D, StringRef Path) {
9485f757f3fSDimitry Andric   llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
9495f757f3fSDimitry Andric   if (!Status)
9505f757f3fSDimitry Andric     return false;
9515f757f3fSDimitry Andric 
9525f757f3fSDimitry Andric   if (Status->isDirectory()) {
9535f757f3fSDimitry Andric     std::error_code EC;
9545f757f3fSDimitry Andric     for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
9555f757f3fSDimitry Andric          !EC && DI != DE; DI = DI.increment(EC)) {
9565f757f3fSDimitry Andric       if (hasClangPchSignature(D, DI->path()))
9575f757f3fSDimitry Andric         return true;
9585f757f3fSDimitry Andric     }
9595f757f3fSDimitry Andric     D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
9605f757f3fSDimitry Andric     return false;
9615f757f3fSDimitry Andric   }
9625f757f3fSDimitry Andric 
9635f757f3fSDimitry Andric   if (hasClangPchSignature(D, Path))
9645f757f3fSDimitry Andric     return true;
9655f757f3fSDimitry Andric   D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
9665f757f3fSDimitry Andric   return false;
9675f757f3fSDimitry Andric }
9685f757f3fSDimitry Andric 
9690b57cec5SDimitry Andric void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
9700b57cec5SDimitry Andric                                     const Driver &D, const ArgList &Args,
9710b57cec5SDimitry Andric                                     ArgStringList &CmdArgs,
9720b57cec5SDimitry Andric                                     const InputInfo &Output,
9730b57cec5SDimitry Andric                                     const InputInfoList &Inputs) const {
9740b57cec5SDimitry Andric   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   CheckPreprocessingOptions(D, Args);
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_C);
9790b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_CC);
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   // Handle dependency file generation.
982a7dea167SDimitry Andric   Arg *ArgM = Args.getLastArg(options::OPT_MM);
983a7dea167SDimitry Andric   if (!ArgM)
984a7dea167SDimitry Andric     ArgM = Args.getLastArg(options::OPT_M);
985a7dea167SDimitry Andric   Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
986a7dea167SDimitry Andric   if (!ArgMD)
987a7dea167SDimitry Andric     ArgMD = Args.getLastArg(options::OPT_MD);
988a7dea167SDimitry Andric 
989a7dea167SDimitry Andric   // -M and -MM imply -w.
990a7dea167SDimitry Andric   if (ArgM)
991a7dea167SDimitry Andric     CmdArgs.push_back("-w");
992a7dea167SDimitry Andric   else
993a7dea167SDimitry Andric     ArgM = ArgMD;
994a7dea167SDimitry Andric 
995a7dea167SDimitry Andric   if (ArgM) {
9960b57cec5SDimitry Andric     // Determine the output location.
9970b57cec5SDimitry Andric     const char *DepFile;
9980b57cec5SDimitry Andric     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
9990b57cec5SDimitry Andric       DepFile = MF->getValue();
10000b57cec5SDimitry Andric       C.addFailureResultFile(DepFile, &JA);
10010b57cec5SDimitry Andric     } else if (Output.getType() == types::TY_Dependencies) {
10020b57cec5SDimitry Andric       DepFile = Output.getFilename();
1003a7dea167SDimitry Andric     } else if (!ArgMD) {
10040b57cec5SDimitry Andric       DepFile = "-";
10050b57cec5SDimitry Andric     } else {
10060b57cec5SDimitry Andric       DepFile = getDependencyFileName(Args, Inputs);
10070b57cec5SDimitry Andric       C.addFailureResultFile(DepFile, &JA);
10080b57cec5SDimitry Andric     }
10090b57cec5SDimitry Andric     CmdArgs.push_back("-dependency-file");
10100b57cec5SDimitry Andric     CmdArgs.push_back(DepFile);
10110b57cec5SDimitry Andric 
1012a7dea167SDimitry Andric     bool HasTarget = false;
1013a7dea167SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1014a7dea167SDimitry Andric       HasTarget = true;
1015a7dea167SDimitry Andric       A->claim();
1016a7dea167SDimitry Andric       if (A->getOption().matches(options::OPT_MT)) {
1017a7dea167SDimitry Andric         A->render(Args, CmdArgs);
1018a7dea167SDimitry Andric       } else {
1019a7dea167SDimitry Andric         CmdArgs.push_back("-MT");
1020a7dea167SDimitry Andric         SmallString<128> Quoted;
1021753f127fSDimitry Andric         quoteMakeTarget(A->getValue(), Quoted);
1022a7dea167SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(Quoted));
1023a7dea167SDimitry Andric       }
1024a7dea167SDimitry Andric     }
1025a7dea167SDimitry Andric 
10260b57cec5SDimitry Andric     // Add a default target if one wasn't specified.
1027a7dea167SDimitry Andric     if (!HasTarget) {
10280b57cec5SDimitry Andric       const char *DepTarget;
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric       // If user provided -o, that is the dependency target, except
10310b57cec5SDimitry Andric       // when we are only generating a dependency file.
10320b57cec5SDimitry Andric       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
10330b57cec5SDimitry Andric       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
10340b57cec5SDimitry Andric         DepTarget = OutputOpt->getValue();
10350b57cec5SDimitry Andric       } else {
10360b57cec5SDimitry Andric         // Otherwise derive from the base input.
10370b57cec5SDimitry Andric         //
10380b57cec5SDimitry Andric         // FIXME: This should use the computed output file location.
10390b57cec5SDimitry Andric         SmallString<128> P(Inputs[0].getBaseInput());
10400b57cec5SDimitry Andric         llvm::sys::path::replace_extension(P, "o");
10410b57cec5SDimitry Andric         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
10420b57cec5SDimitry Andric       }
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric       CmdArgs.push_back("-MT");
10450b57cec5SDimitry Andric       SmallString<128> Quoted;
1046753f127fSDimitry Andric       quoteMakeTarget(DepTarget, Quoted);
10470b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Quoted));
10480b57cec5SDimitry Andric     }
10490b57cec5SDimitry Andric 
1050a7dea167SDimitry Andric     if (ArgM->getOption().matches(options::OPT_M) ||
1051a7dea167SDimitry Andric         ArgM->getOption().matches(options::OPT_MD))
10520b57cec5SDimitry Andric       CmdArgs.push_back("-sys-header-deps");
10530b57cec5SDimitry Andric     if ((isa<PrecompileJobAction>(JA) &&
10540b57cec5SDimitry Andric          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
10550b57cec5SDimitry Andric         Args.hasArg(options::OPT_fmodule_file_deps))
10560b57cec5SDimitry Andric       CmdArgs.push_back("-module-file-deps");
10570b57cec5SDimitry Andric   }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_MG)) {
1060a7dea167SDimitry Andric     if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1061a7dea167SDimitry Andric         ArgM->getOption().matches(options::OPT_MMD))
10620b57cec5SDimitry Andric       D.Diag(diag::err_drv_mg_requires_m_or_mm);
10630b57cec5SDimitry Andric     CmdArgs.push_back("-MG");
10640b57cec5SDimitry Andric   }
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_MP);
10670b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_MV);
10680b57cec5SDimitry Andric 
10695ffd83dbSDimitry Andric   // Add offload include arguments specific for CUDA/HIP.  This must happen
10705ffd83dbSDimitry Andric   // before we -I or -include anything else, because we must pick up the
10715ffd83dbSDimitry Andric   // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
10725ffd83dbSDimitry Andric   // from e.g. /usr/local/include.
10730b57cec5SDimitry Andric   if (JA.isOffloading(Action::OFK_Cuda))
10740b57cec5SDimitry Andric     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
10755ffd83dbSDimitry Andric   if (JA.isOffloading(Action::OFK_HIP))
10765ffd83dbSDimitry Andric     getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
10770b57cec5SDimitry Andric 
107806c3fb27SDimitry Andric   // If we are compiling for a GPU target we want to override the system headers
107906c3fb27SDimitry Andric   // with ones created by the 'libc' project if present.
108006c3fb27SDimitry Andric   if (!Args.hasArg(options::OPT_nostdinc) &&
108106c3fb27SDimitry Andric       !Args.hasArg(options::OPT_nogpuinc) &&
10825f757f3fSDimitry Andric       !Args.hasArg(options::OPT_nobuiltininc)) {
108306c3fb27SDimitry Andric     // Without an offloading language we will include these headers directly.
108406c3fb27SDimitry Andric     // Offloading languages will instead only use the declarations stored in
108506c3fb27SDimitry Andric     // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
10865f757f3fSDimitry Andric     if ((getToolChain().getTriple().isNVPTX() ||
10875f757f3fSDimitry Andric          getToolChain().getTriple().isAMDGCN()) &&
10885f757f3fSDimitry Andric         C.getActiveOffloadKinds() == Action::OFK_None) {
108906c3fb27SDimitry Andric       SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
109006c3fb27SDimitry Andric       llvm::sys::path::append(P, "include");
109106c3fb27SDimitry Andric       llvm::sys::path::append(P, "gpu-none-llvm");
109206c3fb27SDimitry Andric       CmdArgs.push_back("-c-isystem");
109306c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
109406c3fb27SDimitry Andric     } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
109506c3fb27SDimitry Andric       // TODO: CUDA / HIP include their own headers for some common functions
109606c3fb27SDimitry Andric       // implemented here. We'll need to clean those up so they do not conflict.
109706c3fb27SDimitry Andric       SmallString<128> P(D.ResourceDir);
109806c3fb27SDimitry Andric       llvm::sys::path::append(P, "include");
109906c3fb27SDimitry Andric       llvm::sys::path::append(P, "llvm_libc_wrappers");
110006c3fb27SDimitry Andric       CmdArgs.push_back("-internal-isystem");
110106c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
110206c3fb27SDimitry Andric     }
110306c3fb27SDimitry Andric   }
110406c3fb27SDimitry Andric 
11050b57cec5SDimitry Andric   // If we are offloading to a target via OpenMP we need to include the
11060b57cec5SDimitry Andric   // openmp_wrappers folder which contains alternative system headers.
11070b57cec5SDimitry Andric   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
110881ad6265SDimitry Andric       !Args.hasArg(options::OPT_nostdinc) &&
1109bdd1243dSDimitry Andric       !Args.hasArg(options::OPT_nogpuinc) &&
111069ade1e0SDimitry Andric       (getToolChain().getTriple().isNVPTX() ||
111169ade1e0SDimitry Andric        getToolChain().getTriple().isAMDGCN())) {
11120b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_nobuiltininc)) {
11130b57cec5SDimitry Andric       // Add openmp_wrappers/* to our system include path.  This lets us wrap
11140b57cec5SDimitry Andric       // standard library headers.
11150b57cec5SDimitry Andric       SmallString<128> P(D.ResourceDir);
11160b57cec5SDimitry Andric       llvm::sys::path::append(P, "include");
11170b57cec5SDimitry Andric       llvm::sys::path::append(P, "openmp_wrappers");
11180b57cec5SDimitry Andric       CmdArgs.push_back("-internal-isystem");
11190b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(P));
11200b57cec5SDimitry Andric     }
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric     CmdArgs.push_back("-include");
11235ffd83dbSDimitry Andric     CmdArgs.push_back("__clang_openmp_device_functions.h");
11240b57cec5SDimitry Andric   }
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric   // Add -i* options, and automatically translate to
11270b57cec5SDimitry Andric   // -include-pch/-include-pth for transparent PCH support. It's
11280b57cec5SDimitry Andric   // wonky, but we include looking for .gch so we can support seamless
11290b57cec5SDimitry Andric   // replacement into a build system already set up to be generating
11300b57cec5SDimitry Andric   // .gch files.
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   if (getToolChain().getDriver().IsCLMode()) {
11330b57cec5SDimitry Andric     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
11340b57cec5SDimitry Andric     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
11350b57cec5SDimitry Andric     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
11360b57cec5SDimitry Andric         JA.getKind() <= Action::AssembleJobClass) {
11370b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1138f91b0c1cSDimitry Andric       // -fpch-instantiate-templates is the default when creating
1139f91b0c1cSDimitry Andric       // precomp using /Yc
1140f91b0c1cSDimitry Andric       if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1141f91b0c1cSDimitry Andric                        options::OPT_fno_pch_instantiate_templates, true))
11425ffd83dbSDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
11430b57cec5SDimitry Andric     }
11440b57cec5SDimitry Andric     if (YcArg || YuArg) {
11450b57cec5SDimitry Andric       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
11460b57cec5SDimitry Andric       if (!isa<PrecompileJobAction>(JA)) {
11470b57cec5SDimitry Andric         CmdArgs.push_back("-include-pch");
11480b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
11490b57cec5SDimitry Andric             C, !ThroughHeader.empty()
11500b57cec5SDimitry Andric                    ? ThroughHeader
11510b57cec5SDimitry Andric                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
11520b57cec5SDimitry Andric       }
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric       if (ThroughHeader.empty()) {
11550b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
11560b57cec5SDimitry Andric             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
11570b57cec5SDimitry Andric       } else {
11580b57cec5SDimitry Andric         CmdArgs.push_back(
11590b57cec5SDimitry Andric             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
11600b57cec5SDimitry Andric       }
11610b57cec5SDimitry Andric     }
11620b57cec5SDimitry Andric   }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   bool RenderedImplicitInclude = false;
11650b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
116681ad6265SDimitry Andric     if (A->getOption().matches(options::OPT_include) &&
116781ad6265SDimitry Andric         D.getProbePrecompiled()) {
11680b57cec5SDimitry Andric       // Handling of gcc-style gch precompiled headers.
11690b57cec5SDimitry Andric       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
11700b57cec5SDimitry Andric       RenderedImplicitInclude = true;
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric       bool FoundPCH = false;
11730b57cec5SDimitry Andric       SmallString<128> P(A->getValue());
11740b57cec5SDimitry Andric       // We want the files to have a name like foo.h.pch. Add a dummy extension
11750b57cec5SDimitry Andric       // so that replace_extension does the right thing.
11760b57cec5SDimitry Andric       P += ".dummy";
11770b57cec5SDimitry Andric       llvm::sys::path::replace_extension(P, "pch");
117881ad6265SDimitry Andric       if (D.getVFS().exists(P))
11790b57cec5SDimitry Andric         FoundPCH = true;
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric       if (!FoundPCH) {
11825f757f3fSDimitry Andric         // For GCC compat, probe for a file or directory ending in .gch instead.
11830b57cec5SDimitry Andric         llvm::sys::path::replace_extension(P, "gch");
11845f757f3fSDimitry Andric         FoundPCH = gchProbe(D, P.str());
11850b57cec5SDimitry Andric       }
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric       if (FoundPCH) {
11880b57cec5SDimitry Andric         if (IsFirstImplicitInclude) {
11890b57cec5SDimitry Andric           A->claim();
11900b57cec5SDimitry Andric           CmdArgs.push_back("-include-pch");
11910b57cec5SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(P));
11920b57cec5SDimitry Andric           continue;
11930b57cec5SDimitry Andric         } else {
11940b57cec5SDimitry Andric           // Ignore the PCH if not first on command line and emit warning.
11950b57cec5SDimitry Andric           D.Diag(diag::warn_drv_pch_not_first_include) << P
11960b57cec5SDimitry Andric                                                        << A->getAsString(Args);
11970b57cec5SDimitry Andric         }
11980b57cec5SDimitry Andric       }
11990b57cec5SDimitry Andric     } else if (A->getOption().matches(options::OPT_isystem_after)) {
12000b57cec5SDimitry Andric       // Handling of paths which must come late.  These entries are handled by
12010b57cec5SDimitry Andric       // the toolchain itself after the resource dir is inserted in the right
12020b57cec5SDimitry Andric       // search order.
12030b57cec5SDimitry Andric       // Do not claim the argument so that the use of the argument does not
12040b57cec5SDimitry Andric       // silently go unnoticed on toolchains which do not honour the option.
12050b57cec5SDimitry Andric       continue;
1206a7dea167SDimitry Andric     } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1207a7dea167SDimitry Andric       // Translated to -internal-isystem by the driver, no need to pass to cc1.
1208a7dea167SDimitry Andric       continue;
120906c3fb27SDimitry Andric     } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
121006c3fb27SDimitry Andric       // This is used only by the driver. No need to pass to cc1.
121106c3fb27SDimitry Andric       continue;
12120b57cec5SDimitry Andric     }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric     // Not translated, render as usual.
12150b57cec5SDimitry Andric     A->claim();
12160b57cec5SDimitry Andric     A->render(Args, CmdArgs);
12170b57cec5SDimitry Andric   }
12180b57cec5SDimitry Andric 
12195f757f3fSDimitry Andric   Args.addAllArgs(CmdArgs,
12200b57cec5SDimitry Andric                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
12210b57cec5SDimitry Andric                    options::OPT_F, options::OPT_index_header_map});
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // Add -Wp, and -Xpreprocessor if using the preprocessor.
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   // FIXME: There is a very unfortunate problem here, some troubled
12260b57cec5SDimitry Andric   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
12270b57cec5SDimitry Andric   // really support that we would have to parse and then translate
12280b57cec5SDimitry Andric   // those options. :(
12290b57cec5SDimitry Andric   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
12300b57cec5SDimitry Andric                        options::OPT_Xpreprocessor);
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric   // -I- is a deprecated GCC feature, reject it.
12330b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_I_))
12340b57cec5SDimitry Andric     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
12370b57cec5SDimitry Andric   // -isysroot to the CC1 invocation.
12380b57cec5SDimitry Andric   StringRef sysroot = C.getSysRoot();
12390b57cec5SDimitry Andric   if (sysroot != "") {
12400b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_isysroot)) {
12410b57cec5SDimitry Andric       CmdArgs.push_back("-isysroot");
12420b57cec5SDimitry Andric       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
12430b57cec5SDimitry Andric     }
12440b57cec5SDimitry Andric   }
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric   // Parse additional include paths from environment variables.
12470b57cec5SDimitry Andric   // FIXME: We should probably sink the logic for handling these from the
12480b57cec5SDimitry Andric   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
12490b57cec5SDimitry Andric   // CPATH - included following the user specified includes (but prior to
12500b57cec5SDimitry Andric   // builtin and standard includes).
12510b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
12520b57cec5SDimitry Andric   // C_INCLUDE_PATH - system includes enabled when compiling C.
12530b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
12540b57cec5SDimitry Andric   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
12550b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
12560b57cec5SDimitry Andric   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
12570b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
12580b57cec5SDimitry Andric   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
12590b57cec5SDimitry Andric   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric   // While adding the include arguments, we also attempt to retrieve the
12620b57cec5SDimitry Andric   // arguments of related offloading toolchains or arguments that are specific
12630b57cec5SDimitry Andric   // of an offloading programming model.
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric   // Add C++ include arguments, if needed.
1266a7dea167SDimitry Andric   if (types::isCXX(Inputs[0].getType())) {
1267a7dea167SDimitry Andric     bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1268a7dea167SDimitry Andric     forAllAssociatedToolChains(
1269a7dea167SDimitry Andric         C, JA, getToolChain(),
1270a7dea167SDimitry Andric         [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1271a7dea167SDimitry Andric           HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1272a7dea167SDimitry Andric                              : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
12730b57cec5SDimitry Andric         });
1274a7dea167SDimitry Andric   }
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric   // Add system include arguments for all targets but IAMCU.
12770b57cec5SDimitry Andric   if (!IsIAMCU)
12780b57cec5SDimitry Andric     forAllAssociatedToolChains(C, JA, getToolChain(),
12790b57cec5SDimitry Andric                                [&Args, &CmdArgs](const ToolChain &TC) {
12800b57cec5SDimitry Andric                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
12810b57cec5SDimitry Andric                                });
12820b57cec5SDimitry Andric   else {
12830b57cec5SDimitry Andric     // For IAMCU add special include arguments.
12840b57cec5SDimitry Andric     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
12850b57cec5SDimitry Andric   }
1286480093f4SDimitry Andric 
1287480093f4SDimitry Andric   addMacroPrefixMapArg(D, Args, CmdArgs);
1288fe6060f1SDimitry Andric   addCoveragePrefixMapArg(D, Args, CmdArgs);
128981ad6265SDimitry Andric 
129081ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
129181ad6265SDimitry Andric                   options::OPT_fno_file_reproducible);
1292bdd1243dSDimitry Andric 
1293bdd1243dSDimitry Andric   if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1294bdd1243dSDimitry Andric     CmdArgs.push_back("-source-date-epoch");
1295bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Epoch));
1296bdd1243dSDimitry Andric   }
12975f757f3fSDimitry Andric 
12985f757f3fSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
12995f757f3fSDimitry Andric                     options::OPT_fno_define_target_os_macros);
13000b57cec5SDimitry Andric }
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric // FIXME: Move to target hook.
13030b57cec5SDimitry Andric static bool isSignedCharDefault(const llvm::Triple &Triple) {
13040b57cec5SDimitry Andric   switch (Triple.getArch()) {
13050b57cec5SDimitry Andric   default:
13060b57cec5SDimitry Andric     return true;
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   case llvm::Triple::aarch64:
1309480093f4SDimitry Andric   case llvm::Triple::aarch64_32:
13100b57cec5SDimitry Andric   case llvm::Triple::aarch64_be:
13110b57cec5SDimitry Andric   case llvm::Triple::arm:
13120b57cec5SDimitry Andric   case llvm::Triple::armeb:
13130b57cec5SDimitry Andric   case llvm::Triple::thumb:
13140b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
13150b57cec5SDimitry Andric     if (Triple.isOSDarwin() || Triple.isOSWindows())
13160b57cec5SDimitry Andric       return true;
13170b57cec5SDimitry Andric     return false;
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric   case llvm::Triple::ppc:
13200b57cec5SDimitry Andric   case llvm::Triple::ppc64:
13210b57cec5SDimitry Andric     if (Triple.isOSDarwin())
13220b57cec5SDimitry Andric       return true;
13230b57cec5SDimitry Andric     return false;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   case llvm::Triple::hexagon:
1326e8d8bef9SDimitry Andric   case llvm::Triple::ppcle:
13270b57cec5SDimitry Andric   case llvm::Triple::ppc64le:
13280b57cec5SDimitry Andric   case llvm::Triple::riscv32:
13290b57cec5SDimitry Andric   case llvm::Triple::riscv64:
13300b57cec5SDimitry Andric   case llvm::Triple::systemz:
13310b57cec5SDimitry Andric   case llvm::Triple::xcore:
13320b57cec5SDimitry Andric     return false;
13330b57cec5SDimitry Andric   }
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric 
1336480093f4SDimitry Andric static bool hasMultipleInvocations(const llvm::Triple &Triple,
1337480093f4SDimitry Andric                                    const ArgList &Args) {
1338480093f4SDimitry Andric   // Supported only on Darwin where we invoke the compiler multiple times
1339480093f4SDimitry Andric   // followed by an invocation to lipo.
1340480093f4SDimitry Andric   if (!Triple.isOSDarwin())
1341480093f4SDimitry Andric     return false;
1342480093f4SDimitry Andric   // If more than one "-arch <arch>" is specified, we're targeting multiple
1343480093f4SDimitry Andric   // architectures resulting in a fat binary.
1344480093f4SDimitry Andric   return Args.getAllArgValues(options::OPT_arch).size() > 1;
1345480093f4SDimitry Andric }
1346480093f4SDimitry Andric 
1347480093f4SDimitry Andric static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1348480093f4SDimitry Andric                                 const llvm::Triple &Triple) {
1349480093f4SDimitry Andric   // When enabling remarks, we need to error if:
1350480093f4SDimitry Andric   // * The remark file is specified but we're targeting multiple architectures,
1351480093f4SDimitry Andric   // which means more than one remark file is being generated.
1352480093f4SDimitry Andric   bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1353480093f4SDimitry Andric   bool hasExplicitOutputFile =
1354480093f4SDimitry Andric       Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1355480093f4SDimitry Andric   if (hasMultipleInvocations && hasExplicitOutputFile) {
1356480093f4SDimitry Andric     D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1357480093f4SDimitry Andric         << "-foptimization-record-file";
1358480093f4SDimitry Andric     return false;
1359480093f4SDimitry Andric   }
1360480093f4SDimitry Andric   return true;
1361480093f4SDimitry Andric }
1362480093f4SDimitry Andric 
1363480093f4SDimitry Andric static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1364480093f4SDimitry Andric                                  const llvm::Triple &Triple,
1365480093f4SDimitry Andric                                  const InputInfo &Input,
1366480093f4SDimitry Andric                                  const InputInfo &Output, const JobAction &JA) {
1367480093f4SDimitry Andric   StringRef Format = "yaml";
1368480093f4SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1369480093f4SDimitry Andric     Format = A->getValue();
1370480093f4SDimitry Andric 
1371480093f4SDimitry Andric   CmdArgs.push_back("-opt-record-file");
1372480093f4SDimitry Andric 
1373480093f4SDimitry Andric   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1374480093f4SDimitry Andric   if (A) {
1375480093f4SDimitry Andric     CmdArgs.push_back(A->getValue());
1376480093f4SDimitry Andric   } else {
1377480093f4SDimitry Andric     bool hasMultipleArchs =
1378480093f4SDimitry Andric         Triple.isOSDarwin() && // Only supported on Darwin platforms.
1379480093f4SDimitry Andric         Args.getAllArgValues(options::OPT_arch).size() > 1;
1380480093f4SDimitry Andric 
1381480093f4SDimitry Andric     SmallString<128> F;
1382480093f4SDimitry Andric 
1383480093f4SDimitry Andric     if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1384480093f4SDimitry Andric       if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1385480093f4SDimitry Andric         F = FinalOutput->getValue();
1386480093f4SDimitry Andric     } else {
1387480093f4SDimitry Andric       if (Format != "yaml" && // For YAML, keep the original behavior.
1388480093f4SDimitry Andric           Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1389480093f4SDimitry Andric           Output.isFilename())
1390480093f4SDimitry Andric         F = Output.getFilename();
1391480093f4SDimitry Andric     }
1392480093f4SDimitry Andric 
1393480093f4SDimitry Andric     if (F.empty()) {
1394480093f4SDimitry Andric       // Use the input filename.
1395480093f4SDimitry Andric       F = llvm::sys::path::stem(Input.getBaseInput());
1396480093f4SDimitry Andric 
1397480093f4SDimitry Andric       // If we're compiling for an offload architecture (i.e. a CUDA device),
1398480093f4SDimitry Andric       // we need to make the file name for the device compilation different
1399480093f4SDimitry Andric       // from the host compilation.
1400480093f4SDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_None) &&
1401480093f4SDimitry Andric           !JA.isDeviceOffloading(Action::OFK_Host)) {
1402480093f4SDimitry Andric         llvm::sys::path::replace_extension(F, "");
1403480093f4SDimitry Andric         F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1404480093f4SDimitry Andric                                                  Triple.normalize());
1405480093f4SDimitry Andric         F += "-";
1406480093f4SDimitry Andric         F += JA.getOffloadingArch();
1407480093f4SDimitry Andric       }
1408480093f4SDimitry Andric     }
1409480093f4SDimitry Andric 
1410480093f4SDimitry Andric     // If we're having more than one "-arch", we should name the files
1411480093f4SDimitry Andric     // differently so that every cc1 invocation writes to a different file.
1412480093f4SDimitry Andric     // We're doing that by appending "-<arch>" with "<arch>" being the arch
1413480093f4SDimitry Andric     // name from the triple.
1414480093f4SDimitry Andric     if (hasMultipleArchs) {
1415480093f4SDimitry Andric       // First, remember the extension.
1416480093f4SDimitry Andric       SmallString<64> OldExtension = llvm::sys::path::extension(F);
1417480093f4SDimitry Andric       // then, remove it.
1418480093f4SDimitry Andric       llvm::sys::path::replace_extension(F, "");
1419480093f4SDimitry Andric       // attach -<arch> to it.
1420480093f4SDimitry Andric       F += "-";
1421480093f4SDimitry Andric       F += Triple.getArchName();
1422480093f4SDimitry Andric       // put back the extension.
1423480093f4SDimitry Andric       llvm::sys::path::replace_extension(F, OldExtension);
1424480093f4SDimitry Andric     }
1425480093f4SDimitry Andric 
1426480093f4SDimitry Andric     SmallString<32> Extension;
1427480093f4SDimitry Andric     Extension += "opt.";
1428480093f4SDimitry Andric     Extension += Format;
1429480093f4SDimitry Andric 
1430480093f4SDimitry Andric     llvm::sys::path::replace_extension(F, Extension);
1431480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(F));
1432480093f4SDimitry Andric   }
1433480093f4SDimitry Andric 
1434480093f4SDimitry Andric   if (const Arg *A =
1435480093f4SDimitry Andric           Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1436480093f4SDimitry Andric     CmdArgs.push_back("-opt-record-passes");
1437480093f4SDimitry Andric     CmdArgs.push_back(A->getValue());
1438480093f4SDimitry Andric   }
1439480093f4SDimitry Andric 
1440480093f4SDimitry Andric   if (!Format.empty()) {
1441480093f4SDimitry Andric     CmdArgs.push_back("-opt-record-format");
1442480093f4SDimitry Andric     CmdArgs.push_back(Format.data());
1443480093f4SDimitry Andric   }
1444480093f4SDimitry Andric }
1445480093f4SDimitry Andric 
1446fe6060f1SDimitry Andric void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1447fe6060f1SDimitry Andric   if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1448fe6060f1SDimitry Andric                     options::OPT_fno_aapcs_bitfield_width, true))
1449fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-aapcs-bitfield-width");
1450fe6060f1SDimitry Andric 
1451fe6060f1SDimitry Andric   if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1452fe6060f1SDimitry Andric     CmdArgs.push_back("-faapcs-bitfield-load");
1453fe6060f1SDimitry Andric }
1454fe6060f1SDimitry Andric 
14550b57cec5SDimitry Andric namespace {
1456349cc55cSDimitry Andric void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1457349cc55cSDimitry Andric                   const ArgList &Args, ArgStringList &CmdArgs) {
14580b57cec5SDimitry Andric   // Select the ABI to use.
14590b57cec5SDimitry Andric   // FIXME: Support -meabi.
14600b57cec5SDimitry Andric   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
14610b57cec5SDimitry Andric   const char *ABIName = nullptr;
14620b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
14630b57cec5SDimitry Andric     ABIName = A->getValue();
14640b57cec5SDimitry Andric   } else {
1465349cc55cSDimitry Andric     std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
14660b57cec5SDimitry Andric     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
14670b57cec5SDimitry Andric   }
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
14700b57cec5SDimitry Andric   CmdArgs.push_back(ABIName);
14710b57cec5SDimitry Andric }
147281ad6265SDimitry Andric 
147381ad6265SDimitry Andric void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
147481ad6265SDimitry Andric   auto StrictAlignIter =
1475bdd1243dSDimitry Andric       llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
147681ad6265SDimitry Andric         return Arg == "+strict-align" || Arg == "-strict-align";
147781ad6265SDimitry Andric       });
147881ad6265SDimitry Andric   if (StrictAlignIter != CmdArgs.rend() &&
147981ad6265SDimitry Andric       StringRef(*StrictAlignIter) == "+strict-align")
148081ad6265SDimitry Andric     CmdArgs.push_back("-Wunaligned-access");
148181ad6265SDimitry Andric }
14820b57cec5SDimitry Andric }
14830b57cec5SDimitry Andric 
14841fd87a68SDimitry Andric static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
14854824e7fdSDimitry Andric                                     ArgStringList &CmdArgs, bool isAArch64) {
14864824e7fdSDimitry Andric   const Arg *A = isAArch64
14874824e7fdSDimitry Andric                      ? Args.getLastArg(options::OPT_msign_return_address_EQ,
14884824e7fdSDimitry Andric                                        options::OPT_mbranch_protection_EQ)
14894824e7fdSDimitry Andric                      : Args.getLastArg(options::OPT_mbranch_protection_EQ);
14904824e7fdSDimitry Andric   if (!A)
14914824e7fdSDimitry Andric     return;
14924824e7fdSDimitry Andric 
14931fd87a68SDimitry Andric   const Driver &D = TC.getDriver();
14941fd87a68SDimitry Andric   const llvm::Triple &Triple = TC.getEffectiveTriple();
14951fd87a68SDimitry Andric   if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1496d56accc7SDimitry Andric     D.Diag(diag::warn_incompatible_branch_protection_option)
14971fd87a68SDimitry Andric         << Triple.getArchName();
14981fd87a68SDimitry Andric 
14994824e7fdSDimitry Andric   StringRef Scope, Key;
1500cb14a3feSDimitry Andric   bool IndirectBranches, BranchProtectionPAuthLR;
15014824e7fdSDimitry Andric 
15024824e7fdSDimitry Andric   if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
15034824e7fdSDimitry Andric     Scope = A->getValue();
150481ad6265SDimitry Andric     if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
150581ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1506bdd1243dSDimitry Andric           << A->getSpelling() << Scope;
15074824e7fdSDimitry Andric     Key = "a_key";
15084824e7fdSDimitry Andric     IndirectBranches = false;
1509cb14a3feSDimitry Andric     BranchProtectionPAuthLR = false;
15104824e7fdSDimitry Andric   } else {
15114824e7fdSDimitry Andric     StringRef DiagMsg;
15124824e7fdSDimitry Andric     llvm::ARM::ParsedBranchProtection PBP;
15134824e7fdSDimitry Andric     if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
151481ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1515bdd1243dSDimitry Andric           << A->getSpelling() << DiagMsg;
15164824e7fdSDimitry Andric     if (!isAArch64 && PBP.Key == "b_key")
15174824e7fdSDimitry Andric       D.Diag(diag::warn_unsupported_branch_protection)
15184824e7fdSDimitry Andric           << "b-key" << A->getAsString(Args);
15194824e7fdSDimitry Andric     Scope = PBP.Scope;
15204824e7fdSDimitry Andric     Key = PBP.Key;
1521cb14a3feSDimitry Andric     BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
15224824e7fdSDimitry Andric     IndirectBranches = PBP.BranchTargetEnforcement;
15234824e7fdSDimitry Andric   }
15244824e7fdSDimitry Andric 
15254824e7fdSDimitry Andric   CmdArgs.push_back(
15264824e7fdSDimitry Andric       Args.MakeArgString(Twine("-msign-return-address=") + Scope));
15274824e7fdSDimitry Andric   if (!Scope.equals("none"))
15284824e7fdSDimitry Andric     CmdArgs.push_back(
15294824e7fdSDimitry Andric         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1530cb14a3feSDimitry Andric   if (BranchProtectionPAuthLR)
1531cb14a3feSDimitry Andric     CmdArgs.push_back(
1532cb14a3feSDimitry Andric         Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
15334824e7fdSDimitry Andric   if (IndirectBranches)
15344824e7fdSDimitry Andric     CmdArgs.push_back("-mbranch-target-enforce");
15354824e7fdSDimitry Andric }
15364824e7fdSDimitry Andric 
15370b57cec5SDimitry Andric void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
15380b57cec5SDimitry Andric                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1539349cc55cSDimitry Andric   RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric   // Determine floating point ABI from the options & target defaults.
15420b57cec5SDimitry Andric   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
15430b57cec5SDimitry Andric   if (ABI == arm::FloatABI::Soft) {
15440b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
15450b57cec5SDimitry Andric     // FIXME: This changes CPP defines, we need -target-soft-float.
15460b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
15470b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
15480b57cec5SDimitry Andric     CmdArgs.push_back("soft");
15490b57cec5SDimitry Andric   } else if (ABI == arm::FloatABI::SoftFP) {
15500b57cec5SDimitry Andric     // Floating point operations are hard, but argument passing is soft.
15510b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
15520b57cec5SDimitry Andric     CmdArgs.push_back("soft");
15530b57cec5SDimitry Andric   } else {
15540b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
15550b57cec5SDimitry Andric     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
15560b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
15570b57cec5SDimitry Andric     CmdArgs.push_back("hard");
15580b57cec5SDimitry Andric   }
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric   // Forward the -mglobal-merge option for explicit control over the pass.
15610b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
15620b57cec5SDimitry Andric                                options::OPT_mno_global_merge)) {
15630b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
15640b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_global_merge))
15650b57cec5SDimitry Andric       CmdArgs.push_back("-arm-global-merge=false");
15660b57cec5SDimitry Andric     else
15670b57cec5SDimitry Andric       CmdArgs.push_back("-arm-global-merge=true");
15680b57cec5SDimitry Andric   }
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
15710b57cec5SDimitry Andric                     options::OPT_mno_implicit_float, true))
15720b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
15730b57cec5SDimitry Andric 
15740b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_mcmse))
15750b57cec5SDimitry Andric     CmdArgs.push_back("-mcmse");
1576fe6060f1SDimitry Andric 
1577fe6060f1SDimitry Andric   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
15784824e7fdSDimitry Andric 
15794824e7fdSDimitry Andric   // Enable/disable return address signing and indirect branch targets.
15801fd87a68SDimitry Andric   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
158181ad6265SDimitry Andric 
158281ad6265SDimitry Andric   AddUnalignedAccessWarning(CmdArgs);
15830b57cec5SDimitry Andric }
15840b57cec5SDimitry Andric 
15850b57cec5SDimitry Andric void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
15860b57cec5SDimitry Andric                                 const ArgList &Args, bool KernelOrKext,
15870b57cec5SDimitry Andric                                 ArgStringList &CmdArgs) const {
15880b57cec5SDimitry Andric   const ToolChain &TC = getToolChain();
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric   // Add the target features
15915ffd83dbSDimitry Andric   getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric   // Add target specific flags.
15940b57cec5SDimitry Andric   switch (TC.getArch()) {
15950b57cec5SDimitry Andric   default:
15960b57cec5SDimitry Andric     break;
15970b57cec5SDimitry Andric 
15980b57cec5SDimitry Andric   case llvm::Triple::arm:
15990b57cec5SDimitry Andric   case llvm::Triple::armeb:
16000b57cec5SDimitry Andric   case llvm::Triple::thumb:
16010b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
16020b57cec5SDimitry Andric     // Use the effective triple, which takes into account the deployment target.
16030b57cec5SDimitry Andric     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
16040b57cec5SDimitry Andric     break;
16050b57cec5SDimitry Andric 
16060b57cec5SDimitry Andric   case llvm::Triple::aarch64:
1607480093f4SDimitry Andric   case llvm::Triple::aarch64_32:
16080b57cec5SDimitry Andric   case llvm::Triple::aarch64_be:
16090b57cec5SDimitry Andric     AddAArch64TargetArgs(Args, CmdArgs);
1610bdd1243dSDimitry Andric     break;
1611bdd1243dSDimitry Andric 
1612bdd1243dSDimitry Andric   case llvm::Triple::loongarch32:
1613bdd1243dSDimitry Andric   case llvm::Triple::loongarch64:
1614bdd1243dSDimitry Andric     AddLoongArchTargetArgs(Args, CmdArgs);
16150b57cec5SDimitry Andric     break;
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   case llvm::Triple::mips:
16180b57cec5SDimitry Andric   case llvm::Triple::mipsel:
16190b57cec5SDimitry Andric   case llvm::Triple::mips64:
16200b57cec5SDimitry Andric   case llvm::Triple::mips64el:
16210b57cec5SDimitry Andric     AddMIPSTargetArgs(Args, CmdArgs);
16220b57cec5SDimitry Andric     break;
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric   case llvm::Triple::ppc:
1625e8d8bef9SDimitry Andric   case llvm::Triple::ppcle:
16260b57cec5SDimitry Andric   case llvm::Triple::ppc64:
16270b57cec5SDimitry Andric   case llvm::Triple::ppc64le:
16280b57cec5SDimitry Andric     AddPPCTargetArgs(Args, CmdArgs);
16290b57cec5SDimitry Andric     break;
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   case llvm::Triple::riscv32:
16320b57cec5SDimitry Andric   case llvm::Triple::riscv64:
16330b57cec5SDimitry Andric     AddRISCVTargetArgs(Args, CmdArgs);
16340b57cec5SDimitry Andric     break;
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric   case llvm::Triple::sparc:
16370b57cec5SDimitry Andric   case llvm::Triple::sparcel:
16380b57cec5SDimitry Andric   case llvm::Triple::sparcv9:
16390b57cec5SDimitry Andric     AddSparcTargetArgs(Args, CmdArgs);
16400b57cec5SDimitry Andric     break;
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric   case llvm::Triple::systemz:
16430b57cec5SDimitry Andric     AddSystemZTargetArgs(Args, CmdArgs);
16440b57cec5SDimitry Andric     break;
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   case llvm::Triple::x86:
16470b57cec5SDimitry Andric   case llvm::Triple::x86_64:
16480b57cec5SDimitry Andric     AddX86TargetArgs(Args, CmdArgs);
16490b57cec5SDimitry Andric     break;
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   case llvm::Triple::lanai:
16520b57cec5SDimitry Andric     AddLanaiTargetArgs(Args, CmdArgs);
16530b57cec5SDimitry Andric     break;
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric   case llvm::Triple::hexagon:
16560b57cec5SDimitry Andric     AddHexagonTargetArgs(Args, CmdArgs);
16570b57cec5SDimitry Andric     break;
16580b57cec5SDimitry Andric 
16590b57cec5SDimitry Andric   case llvm::Triple::wasm32:
16600b57cec5SDimitry Andric   case llvm::Triple::wasm64:
16610b57cec5SDimitry Andric     AddWebAssemblyTargetArgs(Args, CmdArgs);
16620b57cec5SDimitry Andric     break;
16635ffd83dbSDimitry Andric 
16645ffd83dbSDimitry Andric   case llvm::Triple::ve:
16655ffd83dbSDimitry Andric     AddVETargetArgs(Args, CmdArgs);
16665ffd83dbSDimitry Andric     break;
16670b57cec5SDimitry Andric   }
16680b57cec5SDimitry Andric }
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric namespace {
16710b57cec5SDimitry Andric void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
16720b57cec5SDimitry Andric                       ArgStringList &CmdArgs) {
16730b57cec5SDimitry Andric   const char *ABIName = nullptr;
16740b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
16750b57cec5SDimitry Andric     ABIName = A->getValue();
16760b57cec5SDimitry Andric   else if (Triple.isOSDarwin())
16770b57cec5SDimitry Andric     ABIName = "darwinpcs";
16780b57cec5SDimitry Andric   else
16790b57cec5SDimitry Andric     ABIName = "aapcs";
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
16820b57cec5SDimitry Andric   CmdArgs.push_back(ABIName);
16830b57cec5SDimitry Andric }
16840b57cec5SDimitry Andric }
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric void Clang::AddAArch64TargetArgs(const ArgList &Args,
16870b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
16880b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
16910b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel) ||
16920b57cec5SDimitry Andric       Args.hasArg(options::OPT_fapple_kext))
16930b57cec5SDimitry Andric     CmdArgs.push_back("-disable-red-zone");
16940b57cec5SDimitry Andric 
16950b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
16960b57cec5SDimitry Andric                     options::OPT_mno_implicit_float, true))
16970b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric   RenderAArch64ABI(Triple, Args, CmdArgs);
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   // Forward the -mglobal-merge option for explicit control over the pass.
17020b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
17030b57cec5SDimitry Andric                                options::OPT_mno_global_merge)) {
17040b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
17050b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_global_merge))
17060b57cec5SDimitry Andric       CmdArgs.push_back("-aarch64-enable-global-merge=false");
17070b57cec5SDimitry Andric     else
17080b57cec5SDimitry Andric       CmdArgs.push_back("-aarch64-enable-global-merge=true");
17090b57cec5SDimitry Andric   }
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric   // Enable/disable return address signing and indirect branch targets.
17121fd87a68SDimitry Andric   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1713e8d8bef9SDimitry Andric 
1714e8d8bef9SDimitry Andric   // Handle -msve_vector_bits=<bits>
1715e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1716e8d8bef9SDimitry Andric     StringRef Val = A->getValue();
1717e8d8bef9SDimitry Andric     const Driver &D = getToolChain().getDriver();
1718e8d8bef9SDimitry Andric     if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1719349cc55cSDimitry Andric         Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1720349cc55cSDimitry Andric         Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1721349cc55cSDimitry Andric         Val.equals("2048+")) {
1722349cc55cSDimitry Andric       unsigned Bits = 0;
17235f757f3fSDimitry Andric       if (Val.ends_with("+"))
1724349cc55cSDimitry Andric         Val = Val.substr(0, Val.size() - 1);
1725349cc55cSDimitry Andric       else {
1726349cc55cSDimitry Andric         bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1727349cc55cSDimitry Andric         assert(!Invalid && "Failed to parse value");
1728e8d8bef9SDimitry Andric         CmdArgs.push_back(
1729349cc55cSDimitry Andric             Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1730349cc55cSDimitry Andric       }
1731349cc55cSDimitry Andric 
1732349cc55cSDimitry Andric       bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1733349cc55cSDimitry Andric       assert(!Invalid && "Failed to parse value");
1734349cc55cSDimitry Andric       CmdArgs.push_back(
1735349cc55cSDimitry Andric           Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1736e8d8bef9SDimitry Andric     // Silently drop requests for vector-length agnostic code as it's implied.
1737349cc55cSDimitry Andric     } else if (!Val.equals("scalable"))
1738e8d8bef9SDimitry Andric       // Handle the unsupported values passed to msve-vector-bits.
1739e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
1740bdd1243dSDimitry Andric           << A->getSpelling() << Val;
1741e8d8bef9SDimitry Andric   }
1742fe6060f1SDimitry Andric 
1743fe6060f1SDimitry Andric   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1744349cc55cSDimitry Andric 
1745349cc55cSDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1746349cc55cSDimitry Andric     CmdArgs.push_back("-tune-cpu");
1747fcaf7f86SDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
1748fcaf7f86SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1749fcaf7f86SDimitry Andric     else
1750fcaf7f86SDimitry Andric       CmdArgs.push_back(A->getValue());
1751349cc55cSDimitry Andric   }
175281ad6265SDimitry Andric 
175381ad6265SDimitry Andric   AddUnalignedAccessWarning(CmdArgs);
17540b57cec5SDimitry Andric }
17550b57cec5SDimitry Andric 
1756bdd1243dSDimitry Andric void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1757bdd1243dSDimitry Andric                                    ArgStringList &CmdArgs) const {
17588a4dda33SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
17598a4dda33SDimitry Andric 
1760bdd1243dSDimitry Andric   CmdArgs.push_back("-target-abi");
17618a4dda33SDimitry Andric   CmdArgs.push_back(
17628a4dda33SDimitry Andric       loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1763bdd1243dSDimitry Andric           .data());
17648a4dda33SDimitry Andric 
17658a4dda33SDimitry Andric   // Handle -mtune.
17668a4dda33SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
17678a4dda33SDimitry Andric     std::string TuneCPU = A->getValue();
17688a4dda33SDimitry Andric     TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
17698a4dda33SDimitry Andric     CmdArgs.push_back("-tune-cpu");
17708a4dda33SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
17718a4dda33SDimitry Andric   }
1772bdd1243dSDimitry Andric }
1773bdd1243dSDimitry Andric 
17740b57cec5SDimitry Andric void Clang::AddMIPSTargetArgs(const ArgList &Args,
17750b57cec5SDimitry Andric                               ArgStringList &CmdArgs) const {
17760b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
17770b57cec5SDimitry Andric   StringRef CPUName;
17780b57cec5SDimitry Andric   StringRef ABIName;
17790b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
17800b57cec5SDimitry Andric   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
17830b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
17860b57cec5SDimitry Andric   if (ABI == mips::FloatABI::Soft) {
17870b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
17880b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
17890b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
17900b57cec5SDimitry Andric     CmdArgs.push_back("soft");
17910b57cec5SDimitry Andric   } else {
17920b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
17930b57cec5SDimitry Andric     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
17940b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
17950b57cec5SDimitry Andric     CmdArgs.push_back("hard");
17960b57cec5SDimitry Andric   }
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
17990b57cec5SDimitry Andric                                options::OPT_mno_ldc1_sdc1)) {
18000b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
18010b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18020b57cec5SDimitry Andric       CmdArgs.push_back("-mno-ldc1-sdc1");
18030b57cec5SDimitry Andric     }
18040b57cec5SDimitry Andric   }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
18070b57cec5SDimitry Andric                                options::OPT_mno_check_zero_division)) {
18080b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
18090b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18100b57cec5SDimitry Andric       CmdArgs.push_back("-mno-check-zero-division");
18110b57cec5SDimitry Andric     }
18120b57cec5SDimitry Andric   }
18130b57cec5SDimitry Andric 
181404eeddc0SDimitry Andric   if (Args.getLastArg(options::OPT_mfix4300)) {
181504eeddc0SDimitry Andric     CmdArgs.push_back("-mllvm");
181604eeddc0SDimitry Andric     CmdArgs.push_back("-mfix4300");
181704eeddc0SDimitry Andric   }
181804eeddc0SDimitry Andric 
18190b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_G)) {
18200b57cec5SDimitry Andric     StringRef v = A->getValue();
18210b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
18220b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
18230b57cec5SDimitry Andric     A->claim();
18240b57cec5SDimitry Andric   }
18250b57cec5SDimitry Andric 
18260b57cec5SDimitry Andric   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
18270b57cec5SDimitry Andric   Arg *ABICalls =
18280b57cec5SDimitry Andric       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
18310b57cec5SDimitry Andric   // -mgpopt is the default for static, -fno-pic environments but these two
18320b57cec5SDimitry Andric   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
18330b57cec5SDimitry Andric   // the only case where -mllvm -mgpopt is passed.
18340b57cec5SDimitry Andric   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
18350b57cec5SDimitry Andric   //       passed explicitly when compiling something with -mabicalls
18360b57cec5SDimitry Andric   //       (implictly) in affect. Currently the warning is in the backend.
18370b57cec5SDimitry Andric   //
18380b57cec5SDimitry Andric   // When the ABI in use is  N64, we also need to determine the PIC mode that
18390b57cec5SDimitry Andric   // is in use, as -fno-pic for N64 implies -mno-abicalls.
18400b57cec5SDimitry Andric   bool NoABICalls =
18410b57cec5SDimitry Andric       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
18420b57cec5SDimitry Andric 
18430b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
18440b57cec5SDimitry Andric   unsigned PICLevel;
18450b57cec5SDimitry Andric   bool IsPIE;
18460b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) =
18470b57cec5SDimitry Andric       ParsePICArgs(getToolChain(), Args);
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric   NoABICalls = NoABICalls ||
18500b57cec5SDimitry Andric                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
18510b57cec5SDimitry Andric 
18520b57cec5SDimitry Andric   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
18530b57cec5SDimitry Andric   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
18540b57cec5SDimitry Andric   if (NoABICalls && (!GPOpt || WantGPOpt)) {
18550b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
18560b57cec5SDimitry Andric     CmdArgs.push_back("-mgpopt");
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
18590b57cec5SDimitry Andric                                       options::OPT_mno_local_sdata);
18600b57cec5SDimitry Andric     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
18610b57cec5SDimitry Andric                                        options::OPT_mno_extern_sdata);
18620b57cec5SDimitry Andric     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
18630b57cec5SDimitry Andric                                         options::OPT_mno_embedded_data);
18640b57cec5SDimitry Andric     if (LocalSData) {
18650b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18660b57cec5SDimitry Andric       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
18670b57cec5SDimitry Andric         CmdArgs.push_back("-mlocal-sdata=1");
18680b57cec5SDimitry Andric       } else {
18690b57cec5SDimitry Andric         CmdArgs.push_back("-mlocal-sdata=0");
18700b57cec5SDimitry Andric       }
18710b57cec5SDimitry Andric       LocalSData->claim();
18720b57cec5SDimitry Andric     }
18730b57cec5SDimitry Andric 
18740b57cec5SDimitry Andric     if (ExternSData) {
18750b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18760b57cec5SDimitry Andric       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
18770b57cec5SDimitry Andric         CmdArgs.push_back("-mextern-sdata=1");
18780b57cec5SDimitry Andric       } else {
18790b57cec5SDimitry Andric         CmdArgs.push_back("-mextern-sdata=0");
18800b57cec5SDimitry Andric       }
18810b57cec5SDimitry Andric       ExternSData->claim();
18820b57cec5SDimitry Andric     }
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric     if (EmbeddedData) {
18850b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
18860b57cec5SDimitry Andric       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
18870b57cec5SDimitry Andric         CmdArgs.push_back("-membedded-data=1");
18880b57cec5SDimitry Andric       } else {
18890b57cec5SDimitry Andric         CmdArgs.push_back("-membedded-data=0");
18900b57cec5SDimitry Andric       }
18910b57cec5SDimitry Andric       EmbeddedData->claim();
18920b57cec5SDimitry Andric     }
18930b57cec5SDimitry Andric 
18940b57cec5SDimitry Andric   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
18950b57cec5SDimitry Andric     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric   if (GPOpt)
18980b57cec5SDimitry Andric     GPOpt->claim();
18990b57cec5SDimitry Andric 
19000b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
19010b57cec5SDimitry Andric     StringRef Val = StringRef(A->getValue());
19020b57cec5SDimitry Andric     if (mips::hasCompactBranches(CPUName)) {
19030b57cec5SDimitry Andric       if (Val == "never" || Val == "always" || Val == "optimal") {
19040b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
19050b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
19060b57cec5SDimitry Andric       } else
19070b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
1908bdd1243dSDimitry Andric             << A->getSpelling() << Val;
19090b57cec5SDimitry Andric     } else
19100b57cec5SDimitry Andric       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
19110b57cec5SDimitry Andric   }
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
19140b57cec5SDimitry Andric                                options::OPT_mno_relax_pic_calls)) {
19150b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
19160b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
19170b57cec5SDimitry Andric       CmdArgs.push_back("-mips-jalr-reloc=0");
19180b57cec5SDimitry Andric     }
19190b57cec5SDimitry Andric   }
19200b57cec5SDimitry Andric }
19210b57cec5SDimitry Andric 
19220b57cec5SDimitry Andric void Clang::AddPPCTargetArgs(const ArgList &Args,
19230b57cec5SDimitry Andric                              ArgStringList &CmdArgs) const {
192406c3fb27SDimitry Andric   const Driver &D = getToolChain().getDriver();
19251ac55f4cSDimitry Andric   const llvm::Triple &T = getToolChain().getTriple();
192606c3fb27SDimitry Andric   if (Args.getLastArg(options::OPT_mtune_EQ)) {
1927bdd1243dSDimitry Andric     CmdArgs.push_back("-tune-cpu");
19281ac55f4cSDimitry Andric     std::string CPU = ppc::getPPCTuneCPU(Args, T);
19291ac55f4cSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
1930bdd1243dSDimitry Andric   }
1931bdd1243dSDimitry Andric 
19320b57cec5SDimitry Andric   // Select the ABI to use.
19330b57cec5SDimitry Andric   const char *ABIName = nullptr;
1934480093f4SDimitry Andric   if (T.isOSBinFormatELF()) {
19350b57cec5SDimitry Andric     switch (getToolChain().getArch()) {
19360b57cec5SDimitry Andric     case llvm::Triple::ppc64: {
19371ac55f4cSDimitry Andric       if (T.isPPC64ELFv2ABI())
1938480093f4SDimitry Andric         ABIName = "elfv2";
1939480093f4SDimitry Andric       else
19400b57cec5SDimitry Andric         ABIName = "elfv1";
19410b57cec5SDimitry Andric       break;
19420b57cec5SDimitry Andric     }
19430b57cec5SDimitry Andric     case llvm::Triple::ppc64le:
19440b57cec5SDimitry Andric       ABIName = "elfv2";
19450b57cec5SDimitry Andric       break;
19460b57cec5SDimitry Andric     default:
19470b57cec5SDimitry Andric       break;
19480b57cec5SDimitry Andric     }
1949480093f4SDimitry Andric   }
19500b57cec5SDimitry Andric 
195104eeddc0SDimitry Andric   bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
195206c3fb27SDimitry Andric   bool VecExtabi = false;
19530b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
19540b57cec5SDimitry Andric     StringRef V = A->getValue();
195506c3fb27SDimitry Andric     if (V == "ieeelongdouble") {
19560b57cec5SDimitry Andric       IEEELongDouble = true;
195706c3fb27SDimitry Andric       A->claim();
195806c3fb27SDimitry Andric     } else if (V == "ibmlongdouble") {
19590b57cec5SDimitry Andric       IEEELongDouble = false;
196006c3fb27SDimitry Andric       A->claim();
196106c3fb27SDimitry Andric     } else if (V == "vec-default") {
196206c3fb27SDimitry Andric       VecExtabi = false;
196306c3fb27SDimitry Andric       A->claim();
196406c3fb27SDimitry Andric     } else if (V == "vec-extabi") {
196506c3fb27SDimitry Andric       VecExtabi = true;
196606c3fb27SDimitry Andric       A->claim();
19678a4dda33SDimitry Andric     } else if (V == "elfv1") {
19688a4dda33SDimitry Andric       ABIName = "elfv1";
19698a4dda33SDimitry Andric       A->claim();
19708a4dda33SDimitry Andric     } else if (V == "elfv2") {
19718a4dda33SDimitry Andric       ABIName = "elfv2";
19728a4dda33SDimitry Andric       A->claim();
197306c3fb27SDimitry Andric     } else if (V != "altivec")
19740b57cec5SDimitry Andric       // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
19750b57cec5SDimitry Andric       // the option if given as we don't have backend support for any targets
19760b57cec5SDimitry Andric       // that don't use the altivec abi.
19770b57cec5SDimitry Andric       ABIName = A->getValue();
19780b57cec5SDimitry Andric   }
19790b57cec5SDimitry Andric   if (IEEELongDouble)
19800b57cec5SDimitry Andric     CmdArgs.push_back("-mabi=ieeelongdouble");
198106c3fb27SDimitry Andric   if (VecExtabi) {
198206c3fb27SDimitry Andric     if (!T.isOSAIX())
198306c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
198406c3fb27SDimitry Andric           << "-mabi=vec-extabi" << T.str();
198506c3fb27SDimitry Andric     CmdArgs.push_back("-mabi=vec-extabi");
198606c3fb27SDimitry Andric   }
19870b57cec5SDimitry Andric 
198806c3fb27SDimitry Andric   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
19890b57cec5SDimitry Andric   if (FloatABI == ppc::FloatABI::Soft) {
19900b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
19910b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
19920b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
19930b57cec5SDimitry Andric     CmdArgs.push_back("soft");
19940b57cec5SDimitry Andric   } else {
19950b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
19960b57cec5SDimitry Andric     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
19970b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
19980b57cec5SDimitry Andric     CmdArgs.push_back("hard");
19990b57cec5SDimitry Andric   }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric   if (ABIName) {
20020b57cec5SDimitry Andric     CmdArgs.push_back("-target-abi");
20030b57cec5SDimitry Andric     CmdArgs.push_back(ABIName);
20040b57cec5SDimitry Andric   }
20050b57cec5SDimitry Andric }
20060b57cec5SDimitry Andric 
20075ffd83dbSDimitry Andric static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
20085ffd83dbSDimitry Andric                                    ArgStringList &CmdArgs) {
20095ffd83dbSDimitry Andric   const Driver &D = TC.getDriver();
20105ffd83dbSDimitry Andric   const llvm::Triple &Triple = TC.getTriple();
20115ffd83dbSDimitry Andric   // Default small data limitation is eight.
20125ffd83dbSDimitry Andric   const char *SmallDataLimit = "8";
20135ffd83dbSDimitry Andric   // Get small data limitation.
20145ffd83dbSDimitry Andric   if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
20155ffd83dbSDimitry Andric                       options::OPT_fPIC)) {
20165ffd83dbSDimitry Andric     // Not support linker relaxation for PIC.
20175ffd83dbSDimitry Andric     SmallDataLimit = "0";
20185ffd83dbSDimitry Andric     if (Args.hasArg(options::OPT_G)) {
20195ffd83dbSDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
20205ffd83dbSDimitry Andric     }
20215ffd83dbSDimitry Andric   } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2022fe6060f1SDimitry Andric                  .equals_insensitive("large") &&
20235ffd83dbSDimitry Andric              (Triple.getArch() == llvm::Triple::riscv64)) {
20245ffd83dbSDimitry Andric     // Not support linker relaxation for RV64 with large code model.
20255ffd83dbSDimitry Andric     SmallDataLimit = "0";
20265ffd83dbSDimitry Andric     if (Args.hasArg(options::OPT_G)) {
20275ffd83dbSDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
20285ffd83dbSDimitry Andric     }
202906c3fb27SDimitry Andric   } else if (Triple.isAndroid()) {
203006c3fb27SDimitry Andric     // GP relaxation is not supported on Android.
203106c3fb27SDimitry Andric     SmallDataLimit = "0";
203206c3fb27SDimitry Andric     if (Args.hasArg(options::OPT_G)) {
203306c3fb27SDimitry Andric       D.Diag(diag::warn_drv_unsupported_sdata);
203406c3fb27SDimitry Andric     }
20355ffd83dbSDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
20365ffd83dbSDimitry Andric     SmallDataLimit = A->getValue();
20375ffd83dbSDimitry Andric   }
20385ffd83dbSDimitry Andric   // Forward the -msmall-data-limit= option.
20395ffd83dbSDimitry Andric   CmdArgs.push_back("-msmall-data-limit");
20405ffd83dbSDimitry Andric   CmdArgs.push_back(SmallDataLimit);
20415ffd83dbSDimitry Andric }
20425ffd83dbSDimitry Andric 
20430b57cec5SDimitry Andric void Clang::AddRISCVTargetArgs(const ArgList &Args,
20440b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
20450b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
2046a7dea167SDimitry Andric   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
2049a7dea167SDimitry Andric   CmdArgs.push_back(ABIName.data());
20505ffd83dbSDimitry Andric 
20515ffd83dbSDimitry Andric   SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2052e8d8bef9SDimitry Andric 
2053bdd1243dSDimitry Andric   if (!Args.hasFlag(options::OPT_mimplicit_float,
2054bdd1243dSDimitry Andric                     options::OPT_mno_implicit_float, true))
2055bdd1243dSDimitry Andric     CmdArgs.push_back("-no-implicit-float");
2056bdd1243dSDimitry Andric 
2057fcaf7f86SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2058e8d8bef9SDimitry Andric     CmdArgs.push_back("-tune-cpu");
2059bdd1243dSDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
2060bdd1243dSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2061bdd1243dSDimitry Andric     else
2062bdd1243dSDimitry Andric       CmdArgs.push_back(A->getValue());
2063e8d8bef9SDimitry Andric   }
206406c3fb27SDimitry Andric 
206506c3fb27SDimitry Andric   // Handle -mrvv-vector-bits=<bits>
206606c3fb27SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
206706c3fb27SDimitry Andric     StringRef Val = A->getValue();
206806c3fb27SDimitry Andric     const Driver &D = getToolChain().getDriver();
206906c3fb27SDimitry Andric 
207006c3fb27SDimitry Andric     // Get minimum VLen from march.
207106c3fb27SDimitry Andric     unsigned MinVLen = 0;
207206c3fb27SDimitry Andric     StringRef Arch = riscv::getRISCVArch(Args, Triple);
207306c3fb27SDimitry Andric     auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
207406c3fb27SDimitry Andric         Arch, /*EnableExperimentalExtensions*/ true);
207506c3fb27SDimitry Andric     // Ignore parsing error.
2076*647cbc5dSDimitry Andric     if (!errorToBool(ISAInfo.takeError()))
207706c3fb27SDimitry Andric       MinVLen = (*ISAInfo)->getMinVLen();
207806c3fb27SDimitry Andric 
207906c3fb27SDimitry Andric     // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
208006c3fb27SDimitry Andric     // as integer as long as we have a MinVLen.
208106c3fb27SDimitry Andric     unsigned Bits = 0;
208206c3fb27SDimitry Andric     if (Val.equals("zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
208306c3fb27SDimitry Andric       Bits = MinVLen;
208406c3fb27SDimitry Andric     } else if (!Val.getAsInteger(10, Bits)) {
208506c3fb27SDimitry Andric       // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
208606c3fb27SDimitry Andric       // at least MinVLen.
208706c3fb27SDimitry Andric       if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
208806c3fb27SDimitry Andric           Bits > 65536 || !llvm::isPowerOf2_32(Bits))
208906c3fb27SDimitry Andric         Bits = 0;
209006c3fb27SDimitry Andric     }
209106c3fb27SDimitry Andric 
209206c3fb27SDimitry Andric     // If we got a valid value try to use it.
209306c3fb27SDimitry Andric     if (Bits != 0) {
209406c3fb27SDimitry Andric       unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
209506c3fb27SDimitry Andric       CmdArgs.push_back(
209606c3fb27SDimitry Andric           Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
209706c3fb27SDimitry Andric       CmdArgs.push_back(
209806c3fb27SDimitry Andric           Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
209906c3fb27SDimitry Andric     } else if (!Val.equals("scalable")) {
210006c3fb27SDimitry Andric       // Handle the unsupported values passed to mrvv-vector-bits.
210106c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
210206c3fb27SDimitry Andric           << A->getSpelling() << Val;
210306c3fb27SDimitry Andric     }
210406c3fb27SDimitry Andric   }
21050b57cec5SDimitry Andric }
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric void Clang::AddSparcTargetArgs(const ArgList &Args,
21080b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
21090b57cec5SDimitry Andric   sparc::FloatABI FloatABI =
21100b57cec5SDimitry Andric       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   if (FloatABI == sparc::FloatABI::Soft) {
21130b57cec5SDimitry Andric     // Floating point operations and argument passing are soft.
21140b57cec5SDimitry Andric     CmdArgs.push_back("-msoft-float");
21150b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21160b57cec5SDimitry Andric     CmdArgs.push_back("soft");
21170b57cec5SDimitry Andric   } else {
21180b57cec5SDimitry Andric     // Floating point operations and argument passing are hard.
21190b57cec5SDimitry Andric     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
21200b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21210b57cec5SDimitry Andric     CmdArgs.push_back("hard");
21220b57cec5SDimitry Andric   }
212361cfbce3SDimitry Andric 
212461cfbce3SDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
212561cfbce3SDimitry Andric     StringRef Name = A->getValue();
212661cfbce3SDimitry Andric     std::string TuneCPU;
212761cfbce3SDimitry Andric     if (Name == "native")
212861cfbce3SDimitry Andric       TuneCPU = std::string(llvm::sys::getHostCPUName());
212961cfbce3SDimitry Andric     else
213061cfbce3SDimitry Andric       TuneCPU = std::string(Name);
213161cfbce3SDimitry Andric 
213261cfbce3SDimitry Andric     CmdArgs.push_back("-tune-cpu");
213361cfbce3SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
213461cfbce3SDimitry Andric   }
21350b57cec5SDimitry Andric }
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric void Clang::AddSystemZTargetArgs(const ArgList &Args,
21380b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
2139fcaf7f86SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2140753f127fSDimitry Andric     CmdArgs.push_back("-tune-cpu");
2141fcaf7f86SDimitry Andric     if (strcmp(A->getValue(), "native") == 0)
2142fcaf7f86SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2143fcaf7f86SDimitry Andric     else
2144fcaf7f86SDimitry Andric       CmdArgs.push_back(A->getValue());
2145753f127fSDimitry Andric   }
2146753f127fSDimitry Andric 
2147753f127fSDimitry Andric   bool HasBackchain =
2148753f127fSDimitry Andric       Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2149480093f4SDimitry Andric   bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2150480093f4SDimitry Andric                                      options::OPT_mno_packed_stack, false);
21515ffd83dbSDimitry Andric   systemz::FloatABI FloatABI =
21525ffd83dbSDimitry Andric       systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
21535ffd83dbSDimitry Andric   bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
21545ffd83dbSDimitry Andric   if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2155480093f4SDimitry Andric     const Driver &D = getToolChain().getDriver();
2156480093f4SDimitry Andric     D.Diag(diag::err_drv_unsupported_opt)
21575ffd83dbSDimitry Andric       << "-mpacked-stack -mbackchain -mhard-float";
2158480093f4SDimitry Andric   }
2159480093f4SDimitry Andric   if (HasBackchain)
21600b57cec5SDimitry Andric     CmdArgs.push_back("-mbackchain");
2161480093f4SDimitry Andric   if (HasPackedStack)
2162480093f4SDimitry Andric     CmdArgs.push_back("-mpacked-stack");
21635ffd83dbSDimitry Andric   if (HasSoftFloat) {
21645ffd83dbSDimitry Andric     // Floating point operations and argument passing are soft.
21655ffd83dbSDimitry Andric     CmdArgs.push_back("-msoft-float");
21665ffd83dbSDimitry Andric     CmdArgs.push_back("-mfloat-abi");
21675ffd83dbSDimitry Andric     CmdArgs.push_back("soft");
2168480093f4SDimitry Andric   }
21690b57cec5SDimitry Andric }
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric void Clang::AddX86TargetArgs(const ArgList &Args,
21720b57cec5SDimitry Andric                              ArgStringList &CmdArgs) const {
2173480093f4SDimitry Andric   const Driver &D = getToolChain().getDriver();
21745ffd83dbSDimitry Andric   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2175480093f4SDimitry Andric 
21760b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
21770b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel) ||
21780b57cec5SDimitry Andric       Args.hasArg(options::OPT_fapple_kext))
21790b57cec5SDimitry Andric     CmdArgs.push_back("-disable-red-zone");
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
21820b57cec5SDimitry Andric                     options::OPT_mno_tls_direct_seg_refs, true))
21830b57cec5SDimitry Andric     CmdArgs.push_back("-mno-tls-direct-seg-refs");
21840b57cec5SDimitry Andric 
21850b57cec5SDimitry Andric   // Default to avoid implicit floating-point for kernel/kext code, but allow
21860b57cec5SDimitry Andric   // that to be overridden with -mno-soft-float.
21870b57cec5SDimitry Andric   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
21880b57cec5SDimitry Andric                           Args.hasArg(options::OPT_fapple_kext));
21890b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(
21900b57cec5SDimitry Andric           options::OPT_msoft_float, options::OPT_mno_soft_float,
21910b57cec5SDimitry Andric           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
21920b57cec5SDimitry Andric     const Option &O = A->getOption();
21930b57cec5SDimitry Andric     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
21940b57cec5SDimitry Andric                        O.matches(options::OPT_msoft_float));
21950b57cec5SDimitry Andric   }
21960b57cec5SDimitry Andric   if (NoImplicitFloat)
21970b57cec5SDimitry Andric     CmdArgs.push_back("-no-implicit-float");
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
22000b57cec5SDimitry Andric     StringRef Value = A->getValue();
22010b57cec5SDimitry Andric     if (Value == "intel" || Value == "att") {
22020b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
22030b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2204349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
22050b57cec5SDimitry Andric     } else {
2206480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument)
2207bdd1243dSDimitry Andric           << A->getSpelling() << Value;
22080b57cec5SDimitry Andric     }
2209480093f4SDimitry Andric   } else if (D.IsCLMode()) {
22100b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
22110b57cec5SDimitry Andric     CmdArgs.push_back("-x86-asm-syntax=intel");
22120b57cec5SDimitry Andric   }
22130b57cec5SDimitry Andric 
2214349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2215349cc55cSDimitry Andric                                options::OPT_mno_skip_rax_setup))
2216349cc55cSDimitry Andric     if (A->getOption().matches(options::OPT_mskip_rax_setup))
2217349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2218349cc55cSDimitry Andric 
22190b57cec5SDimitry Andric   // Set flags to support MCU ABI.
22200b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
22210b57cec5SDimitry Andric     CmdArgs.push_back("-mfloat-abi");
22220b57cec5SDimitry Andric     CmdArgs.push_back("soft");
22230b57cec5SDimitry Andric     CmdArgs.push_back("-mstack-alignment=4");
22240b57cec5SDimitry Andric   }
2225e8d8bef9SDimitry Andric 
2226e8d8bef9SDimitry Andric   // Handle -mtune.
2227e8d8bef9SDimitry Andric 
222881ad6265SDimitry Andric   // Default to "generic" unless -march is present or targetting the PS4/PS5.
2229e8d8bef9SDimitry Andric   std::string TuneCPU;
2230e8d8bef9SDimitry Andric   if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
223181ad6265SDimitry Andric       !getToolChain().getTriple().isPS())
2232e8d8bef9SDimitry Andric     TuneCPU = "generic";
2233e8d8bef9SDimitry Andric 
2234e8d8bef9SDimitry Andric   // Override based on -mtune.
2235e8d8bef9SDimitry Andric   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2236e8d8bef9SDimitry Andric     StringRef Name = A->getValue();
2237e8d8bef9SDimitry Andric 
2238e8d8bef9SDimitry Andric     if (Name == "native") {
2239e8d8bef9SDimitry Andric       Name = llvm::sys::getHostCPUName();
2240e8d8bef9SDimitry Andric       if (!Name.empty())
2241e8d8bef9SDimitry Andric         TuneCPU = std::string(Name);
2242e8d8bef9SDimitry Andric     } else
2243e8d8bef9SDimitry Andric       TuneCPU = std::string(Name);
2244e8d8bef9SDimitry Andric   }
2245e8d8bef9SDimitry Andric 
2246e8d8bef9SDimitry Andric   if (!TuneCPU.empty()) {
2247e8d8bef9SDimitry Andric     CmdArgs.push_back("-tune-cpu");
2248e8d8bef9SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2249e8d8bef9SDimitry Andric   }
22500b57cec5SDimitry Andric }
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric void Clang::AddHexagonTargetArgs(const ArgList &Args,
22530b57cec5SDimitry Andric                                  ArgStringList &CmdArgs) const {
22540b57cec5SDimitry Andric   CmdArgs.push_back("-mqdsp6-compat");
22550b57cec5SDimitry Andric   CmdArgs.push_back("-Wreturn-type");
22560b57cec5SDimitry Andric 
22570b57cec5SDimitry Andric   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
22580b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
2259bdd1243dSDimitry Andric     CmdArgs.push_back(
2260bdd1243dSDimitry Andric         Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
22610b57cec5SDimitry Andric   }
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fno_short_enums))
22640b57cec5SDimitry Andric     CmdArgs.push_back("-fshort-enums");
22650b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
22660b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
22670b57cec5SDimitry Andric     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
22680b57cec5SDimitry Andric   }
22690b57cec5SDimitry Andric   CmdArgs.push_back("-mllvm");
22700b57cec5SDimitry Andric   CmdArgs.push_back("-machine-sink-split=0");
22710b57cec5SDimitry Andric }
22720b57cec5SDimitry Andric 
22730b57cec5SDimitry Andric void Clang::AddLanaiTargetArgs(const ArgList &Args,
22740b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
22750b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
22760b57cec5SDimitry Andric     StringRef CPUName = A->getValue();
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
22790b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPUName));
22800b57cec5SDimitry Andric   }
22810b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
22820b57cec5SDimitry Andric     StringRef Value = A->getValue();
22830b57cec5SDimitry Andric     // Only support mregparm=4 to support old usage. Report error for all other
22840b57cec5SDimitry Andric     // cases.
22850b57cec5SDimitry Andric     int Mregparm;
22860b57cec5SDimitry Andric     if (Value.getAsInteger(10, Mregparm)) {
22870b57cec5SDimitry Andric       if (Mregparm != 4) {
22880b57cec5SDimitry Andric         getToolChain().getDriver().Diag(
22890b57cec5SDimitry Andric             diag::err_drv_unsupported_option_argument)
2290bdd1243dSDimitry Andric             << A->getSpelling() << Value;
22910b57cec5SDimitry Andric       }
22920b57cec5SDimitry Andric     }
22930b57cec5SDimitry Andric   }
22940b57cec5SDimitry Andric }
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
22970b57cec5SDimitry Andric                                      ArgStringList &CmdArgs) const {
22980b57cec5SDimitry Andric   // Default to "hidden" visibility.
22990b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2300bdd1243dSDimitry Andric                    options::OPT_fvisibility_ms_compat))
2301bdd1243dSDimitry Andric     CmdArgs.push_back("-fvisibility=hidden");
23020b57cec5SDimitry Andric }
23030b57cec5SDimitry Andric 
23045ffd83dbSDimitry Andric void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
23055ffd83dbSDimitry Andric   // Floating point operations and argument passing are hard.
23065ffd83dbSDimitry Andric   CmdArgs.push_back("-mfloat-abi");
23075ffd83dbSDimitry Andric   CmdArgs.push_back("hard");
23085ffd83dbSDimitry Andric }
23095ffd83dbSDimitry Andric 
23100b57cec5SDimitry Andric void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
23110b57cec5SDimitry Andric                                     StringRef Target, const InputInfo &Output,
23120b57cec5SDimitry Andric                                     const InputInfo &Input, const ArgList &Args) const {
23130b57cec5SDimitry Andric   // If this is a dry run, do not create the compilation database file.
23140b57cec5SDimitry Andric   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
23150b57cec5SDimitry Andric     return;
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric   using llvm::yaml::escape;
23180b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric   if (!CompilationDatabase) {
23210b57cec5SDimitry Andric     std::error_code EC;
2322fe6060f1SDimitry Andric     auto File = std::make_unique<llvm::raw_fd_ostream>(
232381ad6265SDimitry Andric         Filename, EC,
232481ad6265SDimitry Andric         llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
23250b57cec5SDimitry Andric     if (EC) {
23260b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
23270b57cec5SDimitry Andric                                                        << EC.message();
23280b57cec5SDimitry Andric       return;
23290b57cec5SDimitry Andric     }
23300b57cec5SDimitry Andric     CompilationDatabase = std::move(File);
23310b57cec5SDimitry Andric   }
23320b57cec5SDimitry Andric   auto &CDB = *CompilationDatabase;
2333a7dea167SDimitry Andric   auto CWD = D.getVFS().getCurrentWorkingDirectory();
2334a7dea167SDimitry Andric   if (!CWD)
2335a7dea167SDimitry Andric     CWD = ".";
2336a7dea167SDimitry Andric   CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
23370b57cec5SDimitry Andric   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
23385f757f3fSDimitry Andric   if (Output.isFilename())
23390b57cec5SDimitry Andric     CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
23400b57cec5SDimitry Andric   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2341a7dea167SDimitry Andric   SmallString<128> Buf;
23420b57cec5SDimitry Andric   Buf = "-x";
23430b57cec5SDimitry Andric   Buf += types::getTypeName(Input.getType());
23440b57cec5SDimitry Andric   CDB << ", \"" << escape(Buf) << "\"";
23450b57cec5SDimitry Andric   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
23460b57cec5SDimitry Andric     Buf = "--sysroot=";
23470b57cec5SDimitry Andric     Buf += D.SysRoot;
23480b57cec5SDimitry Andric     CDB << ", \"" << escape(Buf) << "\"";
23490b57cec5SDimitry Andric   }
23500b57cec5SDimitry Andric   CDB << ", \"" << escape(Input.getFilename()) << "\"";
23515f757f3fSDimitry Andric   if (Output.isFilename())
235281ad6265SDimitry Andric     CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
23530b57cec5SDimitry Andric   for (auto &A: Args) {
23540b57cec5SDimitry Andric     auto &O = A->getOption();
23550b57cec5SDimitry Andric     // Skip language selection, which is positional.
23560b57cec5SDimitry Andric     if (O.getID() == options::OPT_x)
23570b57cec5SDimitry Andric       continue;
23580b57cec5SDimitry Andric     // Skip writing dependency output and the compilation database itself.
23590b57cec5SDimitry Andric     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
23600b57cec5SDimitry Andric       continue;
2361a7dea167SDimitry Andric     if (O.getID() == options::OPT_gen_cdb_fragment_path)
2362a7dea167SDimitry Andric       continue;
23630b57cec5SDimitry Andric     // Skip inputs.
23640b57cec5SDimitry Andric     if (O.getKind() == Option::InputClass)
23650b57cec5SDimitry Andric       continue;
236681ad6265SDimitry Andric     // Skip output.
236781ad6265SDimitry Andric     if (O.getID() == options::OPT_o)
236881ad6265SDimitry Andric       continue;
23690b57cec5SDimitry Andric     // All other arguments are quoted and appended.
23700b57cec5SDimitry Andric     ArgStringList ASL;
23710b57cec5SDimitry Andric     A->render(Args, ASL);
23720b57cec5SDimitry Andric     for (auto &it: ASL)
23730b57cec5SDimitry Andric       CDB << ", \"" << escape(it) << "\"";
23740b57cec5SDimitry Andric   }
23750b57cec5SDimitry Andric   Buf = "--target=";
23760b57cec5SDimitry Andric   Buf += Target;
23770b57cec5SDimitry Andric   CDB << ", \"" << escape(Buf) << "\"]},\n";
23780b57cec5SDimitry Andric }
23790b57cec5SDimitry Andric 
2380a7dea167SDimitry Andric void Clang::DumpCompilationDatabaseFragmentToDir(
2381a7dea167SDimitry Andric     StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2382a7dea167SDimitry Andric     const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2383a7dea167SDimitry Andric   // If this is a dry run, do not create the compilation database file.
2384a7dea167SDimitry Andric   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2385a7dea167SDimitry Andric     return;
2386a7dea167SDimitry Andric 
2387a7dea167SDimitry Andric   if (CompilationDatabase)
2388a7dea167SDimitry Andric     DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2389a7dea167SDimitry Andric 
2390a7dea167SDimitry Andric   SmallString<256> Path = Dir;
2391a7dea167SDimitry Andric   const auto &Driver = C.getDriver();
2392a7dea167SDimitry Andric   Driver.getVFS().makeAbsolute(Path);
2393a7dea167SDimitry Andric   auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2394a7dea167SDimitry Andric   if (Err) {
2395a7dea167SDimitry Andric     Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2396a7dea167SDimitry Andric     return;
2397a7dea167SDimitry Andric   }
2398a7dea167SDimitry Andric 
2399a7dea167SDimitry Andric   llvm::sys::path::append(
2400a7dea167SDimitry Andric       Path,
2401a7dea167SDimitry Andric       Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2402a7dea167SDimitry Andric   int FD;
2403a7dea167SDimitry Andric   SmallString<256> TempPath;
2404fe6060f1SDimitry Andric   Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2405fe6060f1SDimitry Andric                                         llvm::sys::fs::OF_Text);
2406a7dea167SDimitry Andric   if (Err) {
2407a7dea167SDimitry Andric     Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2408a7dea167SDimitry Andric     return;
2409a7dea167SDimitry Andric   }
2410a7dea167SDimitry Andric   CompilationDatabase =
2411a7dea167SDimitry Andric       std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2412a7dea167SDimitry Andric   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2413a7dea167SDimitry Andric }
2414a7dea167SDimitry Andric 
2415fe6060f1SDimitry Andric static bool CheckARMImplicitITArg(StringRef Value) {
2416fe6060f1SDimitry Andric   return Value == "always" || Value == "never" || Value == "arm" ||
2417fe6060f1SDimitry Andric          Value == "thumb";
2418fe6060f1SDimitry Andric }
2419fe6060f1SDimitry Andric 
2420fe6060f1SDimitry Andric static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2421fe6060f1SDimitry Andric                                  StringRef Value) {
2422fe6060f1SDimitry Andric   CmdArgs.push_back("-mllvm");
2423fe6060f1SDimitry Andric   CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2424fe6060f1SDimitry Andric }
2425fe6060f1SDimitry Andric 
24260b57cec5SDimitry Andric static void CollectArgsForIntegratedAssembler(Compilation &C,
24270b57cec5SDimitry Andric                                               const ArgList &Args,
24280b57cec5SDimitry Andric                                               ArgStringList &CmdArgs,
24290b57cec5SDimitry Andric                                               const Driver &D) {
24300b57cec5SDimitry Andric   if (UseRelaxAll(C, Args))
24310b57cec5SDimitry Andric     CmdArgs.push_back("-mrelax-all");
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric   // Only default to -mincremental-linker-compatible if we think we are
24340b57cec5SDimitry Andric   // targeting the MSVC linker.
24350b57cec5SDimitry Andric   bool DefaultIncrementalLinkerCompatible =
24360b57cec5SDimitry Andric       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
24370b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
24380b57cec5SDimitry Andric                    options::OPT_mno_incremental_linker_compatible,
24390b57cec5SDimitry Andric                    DefaultIncrementalLinkerCompatible))
24400b57cec5SDimitry Andric     CmdArgs.push_back("-mincremental-linker-compatible");
24410b57cec5SDimitry Andric 
244281ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
244381ad6265SDimitry Andric 
244406c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
244506c3fb27SDimitry Andric                     options::OPT_fno_emit_compact_unwind_non_canonical);
244606c3fb27SDimitry Andric 
2447a7dea167SDimitry Andric   // If you add more args here, also add them to the block below that
2448a7dea167SDimitry Andric   // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2449a7dea167SDimitry Andric 
24500b57cec5SDimitry Andric   // When passing -I arguments to the assembler we sometimes need to
24510b57cec5SDimitry Andric   // unconditionally take the next argument.  For example, when parsing
24520b57cec5SDimitry Andric   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
24530b57cec5SDimitry Andric   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
24540b57cec5SDimitry Andric   // arg after parsing the '-I' arg.
24550b57cec5SDimitry Andric   bool TakeNextArg = false;
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2458349cc55cSDimitry Andric   bool UseNoExecStack = false;
24590b57cec5SDimitry Andric   const char *MipsTargetFeature = nullptr;
2460fe6060f1SDimitry Andric   StringRef ImplicitIt;
24610b57cec5SDimitry Andric   for (const Arg *A :
2462fe6060f1SDimitry Andric        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2463fe6060f1SDimitry Andric                      options::OPT_mimplicit_it_EQ)) {
24640b57cec5SDimitry Andric     A->claim();
24650b57cec5SDimitry Andric 
2466fe6060f1SDimitry Andric     if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2467fe6060f1SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
2468fe6060f1SDimitry Andric       case llvm::Triple::arm:
2469fe6060f1SDimitry Andric       case llvm::Triple::armeb:
2470fe6060f1SDimitry Andric       case llvm::Triple::thumb:
2471fe6060f1SDimitry Andric       case llvm::Triple::thumbeb:
2472fe6060f1SDimitry Andric         // Only store the value; the last value set takes effect.
2473fe6060f1SDimitry Andric         ImplicitIt = A->getValue();
2474fe6060f1SDimitry Andric         if (!CheckARMImplicitITArg(ImplicitIt))
2475fe6060f1SDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
2476bdd1243dSDimitry Andric               << A->getSpelling() << ImplicitIt;
2477fe6060f1SDimitry Andric         continue;
2478fe6060f1SDimitry Andric       default:
2479fe6060f1SDimitry Andric         break;
2480fe6060f1SDimitry Andric       }
2481fe6060f1SDimitry Andric     }
2482fe6060f1SDimitry Andric 
24830b57cec5SDimitry Andric     for (StringRef Value : A->getValues()) {
24840b57cec5SDimitry Andric       if (TakeNextArg) {
24850b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
24860b57cec5SDimitry Andric         TakeNextArg = false;
24870b57cec5SDimitry Andric         continue;
24880b57cec5SDimitry Andric       }
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
24910b57cec5SDimitry Andric           Value == "-mbig-obj")
24920b57cec5SDimitry Andric         continue; // LLVM handles bigobj automatically
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
24950b57cec5SDimitry Andric       default:
24960b57cec5SDimitry Andric         break;
2497bdd1243dSDimitry Andric       case llvm::Triple::wasm32:
2498bdd1243dSDimitry Andric       case llvm::Triple::wasm64:
2499bdd1243dSDimitry Andric         if (Value == "--no-type-check") {
2500bdd1243dSDimitry Andric           CmdArgs.push_back("-mno-type-check");
2501bdd1243dSDimitry Andric           continue;
2502bdd1243dSDimitry Andric         }
2503bdd1243dSDimitry Andric         break;
25040b57cec5SDimitry Andric       case llvm::Triple::thumb:
25050b57cec5SDimitry Andric       case llvm::Triple::thumbeb:
25060b57cec5SDimitry Andric       case llvm::Triple::arm:
25070b57cec5SDimitry Andric       case llvm::Triple::armeb:
25085f757f3fSDimitry Andric         if (Value.starts_with("-mimplicit-it=")) {
2509fe6060f1SDimitry Andric           // Only store the value; the last value set takes effect.
2510fe6060f1SDimitry Andric           ImplicitIt = Value.split("=").second;
2511fe6060f1SDimitry Andric           if (CheckARMImplicitITArg(ImplicitIt))
2512fe6060f1SDimitry Andric             continue;
2513fe6060f1SDimitry Andric         }
25140b57cec5SDimitry Andric         if (Value == "-mthumb")
25150b57cec5SDimitry Andric           // -mthumb has already been processed in ComputeLLVMTriple()
25160b57cec5SDimitry Andric           // recognize but skip over here.
25170b57cec5SDimitry Andric           continue;
25180b57cec5SDimitry Andric         break;
25190b57cec5SDimitry Andric       case llvm::Triple::mips:
25200b57cec5SDimitry Andric       case llvm::Triple::mipsel:
25210b57cec5SDimitry Andric       case llvm::Triple::mips64:
25220b57cec5SDimitry Andric       case llvm::Triple::mips64el:
25230b57cec5SDimitry Andric         if (Value == "--trap") {
25240b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25250b57cec5SDimitry Andric           CmdArgs.push_back("+use-tcc-in-div");
25260b57cec5SDimitry Andric           continue;
25270b57cec5SDimitry Andric         }
25280b57cec5SDimitry Andric         if (Value == "--break") {
25290b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25300b57cec5SDimitry Andric           CmdArgs.push_back("-use-tcc-in-div");
25310b57cec5SDimitry Andric           continue;
25320b57cec5SDimitry Andric         }
25335f757f3fSDimitry Andric         if (Value.starts_with("-msoft-float")) {
25340b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25350b57cec5SDimitry Andric           CmdArgs.push_back("+soft-float");
25360b57cec5SDimitry Andric           continue;
25370b57cec5SDimitry Andric         }
25385f757f3fSDimitry Andric         if (Value.starts_with("-mhard-float")) {
25390b57cec5SDimitry Andric           CmdArgs.push_back("-target-feature");
25400b57cec5SDimitry Andric           CmdArgs.push_back("-soft-float");
25410b57cec5SDimitry Andric           continue;
25420b57cec5SDimitry Andric         }
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
25450b57cec5SDimitry Andric                                 .Case("-mips1", "+mips1")
25460b57cec5SDimitry Andric                                 .Case("-mips2", "+mips2")
25470b57cec5SDimitry Andric                                 .Case("-mips3", "+mips3")
25480b57cec5SDimitry Andric                                 .Case("-mips4", "+mips4")
25490b57cec5SDimitry Andric                                 .Case("-mips5", "+mips5")
25500b57cec5SDimitry Andric                                 .Case("-mips32", "+mips32")
25510b57cec5SDimitry Andric                                 .Case("-mips32r2", "+mips32r2")
25520b57cec5SDimitry Andric                                 .Case("-mips32r3", "+mips32r3")
25530b57cec5SDimitry Andric                                 .Case("-mips32r5", "+mips32r5")
25540b57cec5SDimitry Andric                                 .Case("-mips32r6", "+mips32r6")
25550b57cec5SDimitry Andric                                 .Case("-mips64", "+mips64")
25560b57cec5SDimitry Andric                                 .Case("-mips64r2", "+mips64r2")
25570b57cec5SDimitry Andric                                 .Case("-mips64r3", "+mips64r3")
25580b57cec5SDimitry Andric                                 .Case("-mips64r5", "+mips64r5")
25590b57cec5SDimitry Andric                                 .Case("-mips64r6", "+mips64r6")
25600b57cec5SDimitry Andric                                 .Default(nullptr);
25610b57cec5SDimitry Andric         if (MipsTargetFeature)
25620b57cec5SDimitry Andric           continue;
25630b57cec5SDimitry Andric       }
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric       if (Value == "-force_cpusubtype_ALL") {
25660b57cec5SDimitry Andric         // Do nothing, this is the default and we don't support anything else.
25670b57cec5SDimitry Andric       } else if (Value == "-L") {
25680b57cec5SDimitry Andric         CmdArgs.push_back("-msave-temp-labels");
25690b57cec5SDimitry Andric       } else if (Value == "--fatal-warnings") {
25700b57cec5SDimitry Andric         CmdArgs.push_back("-massembler-fatal-warnings");
2571a7dea167SDimitry Andric       } else if (Value == "--no-warn" || Value == "-W") {
2572a7dea167SDimitry Andric         CmdArgs.push_back("-massembler-no-warn");
25730b57cec5SDimitry Andric       } else if (Value == "--noexecstack") {
25740b57cec5SDimitry Andric         UseNoExecStack = true;
25755f757f3fSDimitry Andric       } else if (Value.starts_with("-compress-debug-sections") ||
25765f757f3fSDimitry Andric                  Value.starts_with("--compress-debug-sections") ||
25770b57cec5SDimitry Andric                  Value == "-nocompress-debug-sections" ||
25780b57cec5SDimitry Andric                  Value == "--nocompress-debug-sections") {
25790b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
25800b57cec5SDimitry Andric       } else if (Value == "-mrelax-relocations=yes" ||
25810b57cec5SDimitry Andric                  Value == "--mrelax-relocations=yes") {
25820b57cec5SDimitry Andric         UseRelaxRelocations = true;
25830b57cec5SDimitry Andric       } else if (Value == "-mrelax-relocations=no" ||
25840b57cec5SDimitry Andric                  Value == "--mrelax-relocations=no") {
25850b57cec5SDimitry Andric         UseRelaxRelocations = false;
25865f757f3fSDimitry Andric       } else if (Value.starts_with("-I")) {
25870b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
25880b57cec5SDimitry Andric         // We need to consume the next argument if the current arg is a plain
25890b57cec5SDimitry Andric         // -I. The next arg will be the include directory.
25900b57cec5SDimitry Andric         if (Value == "-I")
25910b57cec5SDimitry Andric           TakeNextArg = true;
25925f757f3fSDimitry Andric       } else if (Value.starts_with("-gdwarf-")) {
25930b57cec5SDimitry Andric         // "-gdwarf-N" options are not cc1as options.
25940b57cec5SDimitry Andric         unsigned DwarfVersion = DwarfVersionNum(Value);
25950b57cec5SDimitry Andric         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
25960b57cec5SDimitry Andric           CmdArgs.push_back(Value.data());
25970b57cec5SDimitry Andric         } else {
25980b57cec5SDimitry Andric           RenderDebugEnablingArgs(Args, CmdArgs,
259906c3fb27SDimitry Andric                                   llvm::codegenoptions::DebugInfoConstructor,
26000b57cec5SDimitry Andric                                   DwarfVersion, llvm::DebuggerKind::Default);
26010b57cec5SDimitry Andric         }
26025f757f3fSDimitry Andric       } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
26035f757f3fSDimitry Andric                  Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
26040b57cec5SDimitry Andric         // Do nothing, we'll validate it later.
26050b57cec5SDimitry Andric       } else if (Value == "-defsym") {
26060b57cec5SDimitry Andric         if (A->getNumValues() != 2) {
26070b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_format) << Value;
26080b57cec5SDimitry Andric           break;
26090b57cec5SDimitry Andric         }
26100b57cec5SDimitry Andric         const char *S = A->getValue(1);
26110b57cec5SDimitry Andric         auto Pair = StringRef(S).split('=');
26120b57cec5SDimitry Andric         auto Sym = Pair.first;
26130b57cec5SDimitry Andric         auto SVal = Pair.second;
26140b57cec5SDimitry Andric 
26150b57cec5SDimitry Andric         if (Sym.empty() || SVal.empty()) {
26160b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_format) << S;
26170b57cec5SDimitry Andric           break;
26180b57cec5SDimitry Andric         }
26190b57cec5SDimitry Andric         int64_t IVal;
26200b57cec5SDimitry Andric         if (SVal.getAsInteger(0, IVal)) {
26210b57cec5SDimitry Andric           D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
26220b57cec5SDimitry Andric           break;
26230b57cec5SDimitry Andric         }
26240b57cec5SDimitry Andric         CmdArgs.push_back(Value.data());
26250b57cec5SDimitry Andric         TakeNextArg = true;
26260b57cec5SDimitry Andric       } else if (Value == "-fdebug-compilation-dir") {
26270b57cec5SDimitry Andric         CmdArgs.push_back("-fdebug-compilation-dir");
26280b57cec5SDimitry Andric         TakeNextArg = true;
2629480093f4SDimitry Andric       } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2630480093f4SDimitry Andric         // The flag is a -Wa / -Xassembler argument and Options doesn't
2631480093f4SDimitry Andric         // parse the argument, so this isn't automatically aliased to
2632480093f4SDimitry Andric         // -fdebug-compilation-dir (without '=') here.
2633480093f4SDimitry Andric         CmdArgs.push_back("-fdebug-compilation-dir");
2634480093f4SDimitry Andric         CmdArgs.push_back(Value.data());
2635fe6060f1SDimitry Andric       } else if (Value == "--version") {
2636fe6060f1SDimitry Andric         D.PrintVersion(C, llvm::outs());
26370b57cec5SDimitry Andric       } else {
26380b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2639bdd1243dSDimitry Andric             << A->getSpelling() << Value;
26400b57cec5SDimitry Andric       }
26410b57cec5SDimitry Andric     }
26420b57cec5SDimitry Andric   }
2643fe6060f1SDimitry Andric   if (ImplicitIt.size())
2644fe6060f1SDimitry Andric     AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2645bdd1243dSDimitry Andric   if (!UseRelaxRelocations)
2646bdd1243dSDimitry Andric     CmdArgs.push_back("-mrelax-relocations=no");
26470b57cec5SDimitry Andric   if (UseNoExecStack)
26480b57cec5SDimitry Andric     CmdArgs.push_back("-mnoexecstack");
26490b57cec5SDimitry Andric   if (MipsTargetFeature != nullptr) {
26500b57cec5SDimitry Andric     CmdArgs.push_back("-target-feature");
26510b57cec5SDimitry Andric     CmdArgs.push_back(MipsTargetFeature);
26520b57cec5SDimitry Andric   }
26530b57cec5SDimitry Andric 
26540b57cec5SDimitry Andric   // forward -fembed-bitcode to assmebler
26550b57cec5SDimitry Andric   if (C.getDriver().embedBitcodeEnabled() ||
26560b57cec5SDimitry Andric       C.getDriver().embedBitcodeMarkerOnly())
26570b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2658bdd1243dSDimitry Andric 
2659bdd1243dSDimitry Andric   if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2660bdd1243dSDimitry Andric     CmdArgs.push_back("-as-secure-log-file");
2661bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2662bdd1243dSDimitry Andric   }
26630b57cec5SDimitry Andric }
26640b57cec5SDimitry Andric 
26655f757f3fSDimitry Andric static StringRef EnumComplexRangeToStr(LangOptions::ComplexRangeKind Range) {
26665f757f3fSDimitry Andric   StringRef RangeStr = "";
26675f757f3fSDimitry Andric   switch (Range) {
26685f757f3fSDimitry Andric   case LangOptions::ComplexRangeKind::CX_Limited:
26695f757f3fSDimitry Andric     return "-fcx-limited-range";
26705f757f3fSDimitry Andric     break;
26715f757f3fSDimitry Andric   case LangOptions::ComplexRangeKind::CX_Fortran:
26725f757f3fSDimitry Andric     return "-fcx-fortran-rules";
26735f757f3fSDimitry Andric     break;
26745f757f3fSDimitry Andric   default:
26755f757f3fSDimitry Andric     return RangeStr;
26765f757f3fSDimitry Andric     break;
26775f757f3fSDimitry Andric   }
26785f757f3fSDimitry Andric }
26795f757f3fSDimitry Andric 
26805f757f3fSDimitry Andric static void EmitComplexRangeDiag(const Driver &D,
26815f757f3fSDimitry Andric                                  LangOptions::ComplexRangeKind Range1,
26825f757f3fSDimitry Andric                                  LangOptions::ComplexRangeKind Range2) {
26835f757f3fSDimitry Andric   if (Range1 != LangOptions::ComplexRangeKind::CX_Full)
26845f757f3fSDimitry Andric     D.Diag(clang::diag::warn_drv_overriding_option)
26855f757f3fSDimitry Andric         << EnumComplexRangeToStr(Range1) << EnumComplexRangeToStr(Range2);
26865f757f3fSDimitry Andric }
26875f757f3fSDimitry Andric 
26885f757f3fSDimitry Andric static std::string RenderComplexRangeOption(std::string Range) {
26895f757f3fSDimitry Andric   std::string ComplexRangeStr = "-complex-range=";
26905f757f3fSDimitry Andric   ComplexRangeStr += Range;
26915f757f3fSDimitry Andric   return ComplexRangeStr;
26925f757f3fSDimitry Andric }
26935f757f3fSDimitry Andric 
26940b57cec5SDimitry Andric static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
26950b57cec5SDimitry Andric                                        bool OFastEnabled, const ArgList &Args,
26965ffd83dbSDimitry Andric                                        ArgStringList &CmdArgs,
26975ffd83dbSDimitry Andric                                        const JobAction &JA) {
26980b57cec5SDimitry Andric   // Handle various floating point optimization flags, mapping them to the
26990b57cec5SDimitry Andric   // appropriate LLVM code generation flags. This is complicated by several
27000b57cec5SDimitry Andric   // "umbrella" flags, so we do this by stepping through the flags incrementally
27010b57cec5SDimitry Andric   // adjusting what we think is enabled/disabled, then at the end setting the
27020b57cec5SDimitry Andric   // LLVM flags based on the final state.
27030b57cec5SDimitry Andric   bool HonorINFs = true;
27040b57cec5SDimitry Andric   bool HonorNaNs = true;
2705349cc55cSDimitry Andric   bool ApproxFunc = false;
27060b57cec5SDimitry Andric   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
27070b57cec5SDimitry Andric   bool MathErrno = TC.IsMathErrnoDefault();
27080b57cec5SDimitry Andric   bool AssociativeMath = false;
27090b57cec5SDimitry Andric   bool ReciprocalMath = false;
27100b57cec5SDimitry Andric   bool SignedZeros = true;
2711480093f4SDimitry Andric   bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2712480093f4SDimitry Andric   bool TrappingMathPresent = false; // Is trapping-math in args, and not
2713480093f4SDimitry Andric                                     // overriden by ffp-exception-behavior?
2714480093f4SDimitry Andric   bool RoundingFPMath = false;
2715480093f4SDimitry Andric   bool RoundingMathPresent = false; // Is rounding-math in args?
2716480093f4SDimitry Andric   // -ffp-model values: strict, fast, precise
2717480093f4SDimitry Andric   StringRef FPModel = "";
2718480093f4SDimitry Andric   // -ffp-exception-behavior options: strict, maytrap, ignore
2719480093f4SDimitry Andric   StringRef FPExceptionBehavior = "";
272081ad6265SDimitry Andric   // -ffp-eval-method options: double, extended, source
272181ad6265SDimitry Andric   StringRef FPEvalMethod = "";
27225ffd83dbSDimitry Andric   const llvm::DenormalMode DefaultDenormalFPMath =
27235ffd83dbSDimitry Andric       TC.getDefaultDenormalModeForType(Args, JA);
27245ffd83dbSDimitry Andric   const llvm::DenormalMode DefaultDenormalFP32Math =
27255ffd83dbSDimitry Andric       TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
27265ffd83dbSDimitry Andric 
27275ffd83dbSDimitry Andric   llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
27285ffd83dbSDimitry Andric   llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2729349cc55cSDimitry Andric   // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2730349cc55cSDimitry Andric   // If one wasn't given by the user, don't pass it here.
2731349cc55cSDimitry Andric   StringRef FPContract;
2732bdd1243dSDimitry Andric   StringRef LastSeenFfpContractOption;
2733bdd1243dSDimitry Andric   bool SeenUnsafeMathModeOption = false;
2734349cc55cSDimitry Andric   if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2735349cc55cSDimitry Andric       !JA.isOffloading(Action::OFK_HIP))
2736349cc55cSDimitry Andric     FPContract = "on";
2737480093f4SDimitry Andric   bool StrictFPModel = false;
2738bdd1243dSDimitry Andric   StringRef Float16ExcessPrecision = "";
273906c3fb27SDimitry Andric   StringRef BFloat16ExcessPrecision = "";
27405f757f3fSDimitry Andric   LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_Full;
27410b57cec5SDimitry Andric 
27420b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
27430b57cec5SDimitry Andric     CmdArgs.push_back("-mlimit-float-precision");
27440b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
27450b57cec5SDimitry Andric   }
27460b57cec5SDimitry Andric 
27470b57cec5SDimitry Andric   for (const Arg *A : Args) {
2748480093f4SDimitry Andric     auto optID = A->getOption().getID();
2749480093f4SDimitry Andric     bool PreciseFPModel = false;
2750480093f4SDimitry Andric     switch (optID) {
2751480093f4SDimitry Andric     default:
2752480093f4SDimitry Andric       break;
27535f757f3fSDimitry Andric     case options::OPT_fcx_limited_range: {
27545f757f3fSDimitry Andric       EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Limited);
27555f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Limited;
27565f757f3fSDimitry Andric       std::string ComplexRangeStr = RenderComplexRangeOption("limited");
27575f757f3fSDimitry Andric       if (!ComplexRangeStr.empty())
27585f757f3fSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
27595f757f3fSDimitry Andric       break;
27605f757f3fSDimitry Andric     }
27615f757f3fSDimitry Andric     case options::OPT_fno_cx_limited_range:
27625f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Full;
27635f757f3fSDimitry Andric       break;
27645f757f3fSDimitry Andric     case options::OPT_fcx_fortran_rules: {
27655f757f3fSDimitry Andric       EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Fortran);
27665f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Fortran;
27675f757f3fSDimitry Andric       std::string ComplexRangeStr = RenderComplexRangeOption("fortran");
27685f757f3fSDimitry Andric       if (!ComplexRangeStr.empty())
27695f757f3fSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
27705f757f3fSDimitry Andric       break;
27715f757f3fSDimitry Andric     }
27725f757f3fSDimitry Andric     case options::OPT_fno_cx_fortran_rules:
27735f757f3fSDimitry Andric       Range = LangOptions::ComplexRangeKind::CX_Full;
27745f757f3fSDimitry Andric       break;
2775480093f4SDimitry Andric     case options::OPT_ffp_model_EQ: {
2776480093f4SDimitry Andric       // If -ffp-model= is seen, reset to fno-fast-math
2777480093f4SDimitry Andric       HonorINFs = true;
2778480093f4SDimitry Andric       HonorNaNs = true;
2779bdd1243dSDimitry Andric       ApproxFunc = false;
2780480093f4SDimitry Andric       // Turning *off* -ffast-math restores the toolchain default.
2781480093f4SDimitry Andric       MathErrno = TC.IsMathErrnoDefault();
2782480093f4SDimitry Andric       AssociativeMath = false;
2783480093f4SDimitry Andric       ReciprocalMath = false;
2784480093f4SDimitry Andric       SignedZeros = true;
2785480093f4SDimitry Andric       // -fno_fast_math restores default denormal and fpcontract handling
2786349cc55cSDimitry Andric       FPContract = "on";
27875ffd83dbSDimitry Andric       DenormalFPMath = llvm::DenormalMode::getIEEE();
27885ffd83dbSDimitry Andric 
27895ffd83dbSDimitry Andric       // FIXME: The target may have picked a non-IEEE default mode here based on
27905ffd83dbSDimitry Andric       // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
27915ffd83dbSDimitry Andric       DenormalFP32Math = llvm::DenormalMode::getIEEE();
27925ffd83dbSDimitry Andric 
2793480093f4SDimitry Andric       StringRef Val = A->getValue();
2794480093f4SDimitry Andric       if (OFastEnabled && !Val.equals("fast")) {
2795480093f4SDimitry Andric           // Only -ffp-model=fast is compatible with OFast, ignore.
27965f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
27975f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2798480093f4SDimitry Andric         break;
2799480093f4SDimitry Andric       }
2800480093f4SDimitry Andric       StrictFPModel = false;
2801480093f4SDimitry Andric       PreciseFPModel = true;
2802480093f4SDimitry Andric       // ffp-model= is a Driver option, it is entirely rewritten into more
2803480093f4SDimitry Andric       // granular options before being passed into cc1.
2804480093f4SDimitry Andric       // Use the gcc option in the switch below.
2805349cc55cSDimitry Andric       if (!FPModel.empty() && !FPModel.equals(Val))
28065f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
2807480093f4SDimitry Andric             << Args.MakeArgString("-ffp-model=" + FPModel)
2808480093f4SDimitry Andric             << Args.MakeArgString("-ffp-model=" + Val);
2809480093f4SDimitry Andric       if (Val.equals("fast")) {
2810480093f4SDimitry Andric         optID = options::OPT_ffast_math;
2811480093f4SDimitry Andric         FPModel = Val;
28126e75b2fbSDimitry Andric         FPContract = "fast";
2813480093f4SDimitry Andric       } else if (Val.equals("precise")) {
2814480093f4SDimitry Andric         optID = options::OPT_ffp_contract;
2815480093f4SDimitry Andric         FPModel = Val;
2816349cc55cSDimitry Andric         FPContract = "on";
2817480093f4SDimitry Andric         PreciseFPModel = true;
2818480093f4SDimitry Andric       } else if (Val.equals("strict")) {
2819480093f4SDimitry Andric         StrictFPModel = true;
2820480093f4SDimitry Andric         optID = options::OPT_frounding_math;
2821480093f4SDimitry Andric         FPExceptionBehavior = "strict";
2822480093f4SDimitry Andric         FPModel = Val;
28235ffd83dbSDimitry Andric         FPContract = "off";
2824480093f4SDimitry Andric         TrappingMath = true;
2825480093f4SDimitry Andric       } else
2826480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2827bdd1243dSDimitry Andric             << A->getSpelling() << Val;
2828480093f4SDimitry Andric       break;
2829480093f4SDimitry Andric     }
2830480093f4SDimitry Andric     }
2831480093f4SDimitry Andric 
2832480093f4SDimitry Andric     switch (optID) {
28330b57cec5SDimitry Andric     // If this isn't an FP option skip the claim below
28340b57cec5SDimitry Andric     default: continue;
28350b57cec5SDimitry Andric 
28360b57cec5SDimitry Andric     // Options controlling individual features
28370b57cec5SDimitry Andric     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
28380b57cec5SDimitry Andric     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
28390b57cec5SDimitry Andric     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
28400b57cec5SDimitry Andric     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2841349cc55cSDimitry Andric     case options::OPT_fapprox_func:         ApproxFunc = true;        break;
2842349cc55cSDimitry Andric     case options::OPT_fno_approx_func:      ApproxFunc = false;       break;
28430b57cec5SDimitry Andric     case options::OPT_fmath_errno:          MathErrno = true;         break;
28440b57cec5SDimitry Andric     case options::OPT_fno_math_errno:       MathErrno = false;        break;
28450b57cec5SDimitry Andric     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
28460b57cec5SDimitry Andric     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
28470b57cec5SDimitry Andric     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
28480b57cec5SDimitry Andric     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
28490b57cec5SDimitry Andric     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
28500b57cec5SDimitry Andric     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2851480093f4SDimitry Andric     case options::OPT_ftrapping_math:
2852480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2853480093f4SDimitry Andric           !FPExceptionBehavior.equals("strict"))
2854480093f4SDimitry Andric         // Warn that previous value of option is overridden.
28555f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
28565f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
28575f757f3fSDimitry Andric                                   FPExceptionBehavior)
2858480093f4SDimitry Andric             << "-ftrapping-math";
2859480093f4SDimitry Andric       TrappingMath = true;
2860480093f4SDimitry Andric       TrappingMathPresent = true;
2861480093f4SDimitry Andric       FPExceptionBehavior = "strict";
2862480093f4SDimitry Andric       break;
2863480093f4SDimitry Andric     case options::OPT_fno_trapping_math:
2864480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2865480093f4SDimitry Andric           !FPExceptionBehavior.equals("ignore"))
2866480093f4SDimitry Andric         // Warn that previous value of option is overridden.
28675f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
28685f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
28695f757f3fSDimitry Andric                                   FPExceptionBehavior)
2870480093f4SDimitry Andric             << "-fno-trapping-math";
2871480093f4SDimitry Andric       TrappingMath = false;
2872480093f4SDimitry Andric       TrappingMathPresent = true;
2873480093f4SDimitry Andric       FPExceptionBehavior = "ignore";
2874480093f4SDimitry Andric       break;
2875480093f4SDimitry Andric 
2876480093f4SDimitry Andric     case options::OPT_frounding_math:
2877480093f4SDimitry Andric       RoundingFPMath = true;
2878480093f4SDimitry Andric       RoundingMathPresent = true;
2879480093f4SDimitry Andric       break;
2880480093f4SDimitry Andric 
2881480093f4SDimitry Andric     case options::OPT_fno_rounding_math:
2882480093f4SDimitry Andric       RoundingFPMath = false;
2883480093f4SDimitry Andric       RoundingMathPresent = false;
2884480093f4SDimitry Andric       break;
28850b57cec5SDimitry Andric 
28860b57cec5SDimitry Andric     case options::OPT_fdenormal_fp_math_EQ:
28875ffd83dbSDimitry Andric       DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
288881ad6265SDimitry Andric       DenormalFP32Math = DenormalFPMath;
28895ffd83dbSDimitry Andric       if (!DenormalFPMath.isValid()) {
28905ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
28915ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
28925ffd83dbSDimitry Andric       }
28935ffd83dbSDimitry Andric       break;
28945ffd83dbSDimitry Andric 
28955ffd83dbSDimitry Andric     case options::OPT_fdenormal_fp_math_f32_EQ:
28965ffd83dbSDimitry Andric       DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
28975ffd83dbSDimitry Andric       if (!DenormalFP32Math.isValid()) {
28985ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
28995ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
29005ffd83dbSDimitry Andric       }
29010b57cec5SDimitry Andric       break;
29020b57cec5SDimitry Andric 
2903480093f4SDimitry Andric     // Validate and pass through -ffp-contract option.
29040b57cec5SDimitry Andric     case options::OPT_ffp_contract: {
29050b57cec5SDimitry Andric       StringRef Val = A->getValue();
2906480093f4SDimitry Andric       if (PreciseFPModel) {
2907349cc55cSDimitry Andric         // -ffp-model=precise enables ffp-contract=on.
2908349cc55cSDimitry Andric         // -ffp-model=precise sets PreciseFPModel to on and Val to
2909349cc55cSDimitry Andric         // "precise". FPContract is set.
2910480093f4SDimitry Andric         ;
29115f757f3fSDimitry Andric       } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off") ||
29125f757f3fSDimitry Andric                  Val.equals("fast-honor-pragmas")) {
29130b57cec5SDimitry Andric         FPContract = Val;
2914bdd1243dSDimitry Andric         LastSeenFfpContractOption = Val;
2915bdd1243dSDimitry Andric       } else
29160b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2917bdd1243dSDimitry Andric             << A->getSpelling() << Val;
29180b57cec5SDimitry Andric       break;
29190b57cec5SDimitry Andric     }
29200b57cec5SDimitry Andric 
2921480093f4SDimitry Andric     // Validate and pass through -ffp-model option.
2922480093f4SDimitry Andric     case options::OPT_ffp_model_EQ:
2923480093f4SDimitry Andric       // This should only occur in the error case
2924480093f4SDimitry Andric       // since the optID has been replaced by a more granular
2925480093f4SDimitry Andric       // floating point option.
2926480093f4SDimitry Andric       break;
2927480093f4SDimitry Andric 
2928480093f4SDimitry Andric     // Validate and pass through -ffp-exception-behavior option.
2929480093f4SDimitry Andric     case options::OPT_ffp_exception_behavior_EQ: {
2930480093f4SDimitry Andric       StringRef Val = A->getValue();
2931480093f4SDimitry Andric       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2932480093f4SDimitry Andric           !FPExceptionBehavior.equals(Val))
2933480093f4SDimitry Andric         // Warn that previous value of option is overridden.
29345f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
29355f757f3fSDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" +
29365f757f3fSDimitry Andric                                   FPExceptionBehavior)
2937480093f4SDimitry Andric             << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2938480093f4SDimitry Andric       TrappingMath = TrappingMathPresent = false;
2939480093f4SDimitry Andric       if (Val.equals("ignore") || Val.equals("maytrap"))
2940480093f4SDimitry Andric         FPExceptionBehavior = Val;
2941480093f4SDimitry Andric       else if (Val.equals("strict")) {
2942480093f4SDimitry Andric         FPExceptionBehavior = Val;
2943480093f4SDimitry Andric         TrappingMath = TrappingMathPresent = true;
2944480093f4SDimitry Andric       } else
2945480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2946bdd1243dSDimitry Andric             << A->getSpelling() << Val;
2947480093f4SDimitry Andric       break;
2948480093f4SDimitry Andric     }
2949480093f4SDimitry Andric 
295081ad6265SDimitry Andric     // Validate and pass through -ffp-eval-method option.
295181ad6265SDimitry Andric     case options::OPT_ffp_eval_method_EQ: {
295281ad6265SDimitry Andric       StringRef Val = A->getValue();
295381ad6265SDimitry Andric       if (Val.equals("double") || Val.equals("extended") ||
295481ad6265SDimitry Andric           Val.equals("source"))
295581ad6265SDimitry Andric         FPEvalMethod = Val;
295681ad6265SDimitry Andric       else
295781ad6265SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
2958bdd1243dSDimitry Andric             << A->getSpelling() << Val;
295981ad6265SDimitry Andric       break;
296081ad6265SDimitry Andric     }
296181ad6265SDimitry Andric 
2962bdd1243dSDimitry Andric     case options::OPT_fexcess_precision_EQ: {
2963bdd1243dSDimitry Andric       StringRef Val = A->getValue();
2964bdd1243dSDimitry Andric       const llvm::Triple::ArchType Arch = TC.getArch();
2965bdd1243dSDimitry Andric       if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
2966bdd1243dSDimitry Andric         if (Val.equals("standard") || Val.equals("fast"))
2967bdd1243dSDimitry Andric           Float16ExcessPrecision = Val;
2968bdd1243dSDimitry Andric         // To make it GCC compatible, allow the value of "16" which
2969bdd1243dSDimitry Andric         // means disable excess precision, the same meaning than clang's
2970bdd1243dSDimitry Andric         // equivalent value "none".
2971bdd1243dSDimitry Andric         else if (Val.equals("16"))
2972bdd1243dSDimitry Andric           Float16ExcessPrecision = "none";
2973bdd1243dSDimitry Andric         else
2974bdd1243dSDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
2975bdd1243dSDimitry Andric               << A->getSpelling() << Val;
2976bdd1243dSDimitry Andric       } else {
2977bdd1243dSDimitry Andric         if (!(Val.equals("standard") || Val.equals("fast")))
2978bdd1243dSDimitry Andric           D.Diag(diag::err_drv_unsupported_option_argument)
2979bdd1243dSDimitry Andric               << A->getSpelling() << Val;
2980bdd1243dSDimitry Andric       }
298106c3fb27SDimitry Andric       BFloat16ExcessPrecision = Float16ExcessPrecision;
2982bdd1243dSDimitry Andric       break;
2983bdd1243dSDimitry Andric     }
29840b57cec5SDimitry Andric     case options::OPT_ffinite_math_only:
29850b57cec5SDimitry Andric       HonorINFs = false;
29860b57cec5SDimitry Andric       HonorNaNs = false;
29870b57cec5SDimitry Andric       break;
29880b57cec5SDimitry Andric     case options::OPT_fno_finite_math_only:
29890b57cec5SDimitry Andric       HonorINFs = true;
29900b57cec5SDimitry Andric       HonorNaNs = true;
29910b57cec5SDimitry Andric       break;
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric     case options::OPT_funsafe_math_optimizations:
29940b57cec5SDimitry Andric       AssociativeMath = true;
29950b57cec5SDimitry Andric       ReciprocalMath = true;
29960b57cec5SDimitry Andric       SignedZeros = false;
299704eeddc0SDimitry Andric       ApproxFunc = true;
29980b57cec5SDimitry Andric       TrappingMath = false;
2999480093f4SDimitry Andric       FPExceptionBehavior = "";
3000bdd1243dSDimitry Andric       FPContract = "fast";
3001bdd1243dSDimitry Andric       SeenUnsafeMathModeOption = true;
30020b57cec5SDimitry Andric       break;
30030b57cec5SDimitry Andric     case options::OPT_fno_unsafe_math_optimizations:
30040b57cec5SDimitry Andric       AssociativeMath = false;
30050b57cec5SDimitry Andric       ReciprocalMath = false;
30060b57cec5SDimitry Andric       SignedZeros = true;
300704eeddc0SDimitry Andric       ApproxFunc = false;
30080b57cec5SDimitry Andric       TrappingMath = true;
3009480093f4SDimitry Andric       FPExceptionBehavior = "strict";
30105ffd83dbSDimitry Andric 
30115ffd83dbSDimitry Andric       // The target may have opted to flush by default, so force IEEE.
30125ffd83dbSDimitry Andric       DenormalFPMath = llvm::DenormalMode::getIEEE();
30135ffd83dbSDimitry Andric       DenormalFP32Math = llvm::DenormalMode::getIEEE();
3014bdd1243dSDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3015bdd1243dSDimitry Andric           !JA.isOffloading(Action::OFK_HIP)) {
3016bdd1243dSDimitry Andric         if (LastSeenFfpContractOption != "") {
3017bdd1243dSDimitry Andric           FPContract = LastSeenFfpContractOption;
3018bdd1243dSDimitry Andric         } else if (SeenUnsafeMathModeOption)
3019bdd1243dSDimitry Andric           FPContract = "on";
3020bdd1243dSDimitry Andric       }
30210b57cec5SDimitry Andric       break;
30220b57cec5SDimitry Andric 
30230b57cec5SDimitry Andric     case options::OPT_Ofast:
30240b57cec5SDimitry Andric       // If -Ofast is the optimization level, then -ffast-math should be enabled
30250b57cec5SDimitry Andric       if (!OFastEnabled)
30260b57cec5SDimitry Andric         continue;
3027bdd1243dSDimitry Andric       [[fallthrough]];
30285f757f3fSDimitry Andric     case options::OPT_ffast_math: {
30290b57cec5SDimitry Andric       HonorINFs = false;
30300b57cec5SDimitry Andric       HonorNaNs = false;
30310b57cec5SDimitry Andric       MathErrno = false;
30320b57cec5SDimitry Andric       AssociativeMath = true;
30330b57cec5SDimitry Andric       ReciprocalMath = true;
303404eeddc0SDimitry Andric       ApproxFunc = true;
30350b57cec5SDimitry Andric       SignedZeros = false;
30360b57cec5SDimitry Andric       TrappingMath = false;
3037480093f4SDimitry Andric       RoundingFPMath = false;
3038bdd1243dSDimitry Andric       FPExceptionBehavior = "";
30390b57cec5SDimitry Andric       // If fast-math is set then set the fp-contract mode to fast.
30400b57cec5SDimitry Andric       FPContract = "fast";
3041bdd1243dSDimitry Andric       SeenUnsafeMathModeOption = true;
30425f757f3fSDimitry Andric       // ffast-math enables fortran rules for complex multiplication and
30435f757f3fSDimitry Andric       // division.
30445f757f3fSDimitry Andric       std::string ComplexRangeStr = RenderComplexRangeOption("limited");
30455f757f3fSDimitry Andric       if (!ComplexRangeStr.empty())
30465f757f3fSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
30470b57cec5SDimitry Andric       break;
30485f757f3fSDimitry Andric     }
30490b57cec5SDimitry Andric     case options::OPT_fno_fast_math:
30500b57cec5SDimitry Andric       HonorINFs = true;
30510b57cec5SDimitry Andric       HonorNaNs = true;
30520b57cec5SDimitry Andric       // Turning on -ffast-math (with either flag) removes the need for
30530b57cec5SDimitry Andric       // MathErrno. However, turning *off* -ffast-math merely restores the
30540b57cec5SDimitry Andric       // toolchain default (which may be false).
30550b57cec5SDimitry Andric       MathErrno = TC.IsMathErrnoDefault();
30560b57cec5SDimitry Andric       AssociativeMath = false;
30570b57cec5SDimitry Andric       ReciprocalMath = false;
305804eeddc0SDimitry Andric       ApproxFunc = false;
30590b57cec5SDimitry Andric       SignedZeros = true;
30600b57cec5SDimitry Andric       // -fno_fast_math restores default denormal and fpcontract handling
30615ffd83dbSDimitry Andric       DenormalFPMath = DefaultDenormalFPMath;
30625ffd83dbSDimitry Andric       DenormalFP32Math = llvm::DenormalMode::getIEEE();
3063349cc55cSDimitry Andric       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3064bdd1243dSDimitry Andric           !JA.isOffloading(Action::OFK_HIP)) {
3065bdd1243dSDimitry Andric         if (LastSeenFfpContractOption != "") {
3066bdd1243dSDimitry Andric           FPContract = LastSeenFfpContractOption;
3067bdd1243dSDimitry Andric         } else if (SeenUnsafeMathModeOption)
3068349cc55cSDimitry Andric           FPContract = "on";
3069349cc55cSDimitry Andric       }
30700b57cec5SDimitry Andric       break;
30710b57cec5SDimitry Andric     }
3072480093f4SDimitry Andric     if (StrictFPModel) {
3073480093f4SDimitry Andric       // If -ffp-model=strict has been specified on command line but
3074480093f4SDimitry Andric       // subsequent options conflict then emit warning diagnostic.
3075349cc55cSDimitry Andric       if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
307604eeddc0SDimitry Andric           SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
30775ffd83dbSDimitry Andric           DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3078349cc55cSDimitry Andric           DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3079349cc55cSDimitry Andric           FPContract.equals("off"))
3080480093f4SDimitry Andric         // OK: Current Arg doesn't conflict with -ffp-model=strict
3081480093f4SDimitry Andric         ;
3082480093f4SDimitry Andric       else {
3083480093f4SDimitry Andric         StrictFPModel = false;
3084480093f4SDimitry Andric         FPModel = "";
3085bdd1243dSDimitry Andric         auto RHS = (A->getNumValues() == 0)
3086bdd1243dSDimitry Andric                        ? A->getSpelling()
3087bdd1243dSDimitry Andric                        : Args.MakeArgString(A->getSpelling() + A->getValue());
3088bdd1243dSDimitry Andric         if (RHS != "-ffp-model=strict")
30895f757f3fSDimitry Andric           D.Diag(clang::diag::warn_drv_overriding_option)
3090bdd1243dSDimitry Andric               << "-ffp-model=strict" << RHS;
3091480093f4SDimitry Andric       }
3092480093f4SDimitry Andric     }
30930b57cec5SDimitry Andric 
30940b57cec5SDimitry Andric     // If we handled this option claim it
30950b57cec5SDimitry Andric     A->claim();
30960b57cec5SDimitry Andric   }
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric   if (!HonorINFs)
30990b57cec5SDimitry Andric     CmdArgs.push_back("-menable-no-infs");
31000b57cec5SDimitry Andric 
31010b57cec5SDimitry Andric   if (!HonorNaNs)
31020b57cec5SDimitry Andric     CmdArgs.push_back("-menable-no-nans");
31030b57cec5SDimitry Andric 
3104349cc55cSDimitry Andric   if (ApproxFunc)
3105349cc55cSDimitry Andric     CmdArgs.push_back("-fapprox-func");
3106349cc55cSDimitry Andric 
31070b57cec5SDimitry Andric   if (MathErrno)
31080b57cec5SDimitry Andric     CmdArgs.push_back("-fmath-errno");
31090b57cec5SDimitry Andric 
3110bdd1243dSDimitry Andric  if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3111bdd1243dSDimitry Andric      !TrappingMath)
3112bdd1243dSDimitry Andric     CmdArgs.push_back("-funsafe-math-optimizations");
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric   if (!SignedZeros)
31150b57cec5SDimitry Andric     CmdArgs.push_back("-fno-signed-zeros");
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   if (AssociativeMath && !SignedZeros && !TrappingMath)
31180b57cec5SDimitry Andric     CmdArgs.push_back("-mreassociate");
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric   if (ReciprocalMath)
31210b57cec5SDimitry Andric     CmdArgs.push_back("-freciprocal-math");
31220b57cec5SDimitry Andric 
3123480093f4SDimitry Andric   if (TrappingMath) {
3124480093f4SDimitry Andric     // FP Exception Behavior is also set to strict
3125480093f4SDimitry Andric     assert(FPExceptionBehavior.equals("strict"));
3126e8d8bef9SDimitry Andric   }
31270b57cec5SDimitry Andric 
31285ffd83dbSDimitry Andric   // The default is IEEE.
31295ffd83dbSDimitry Andric   if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
31305ffd83dbSDimitry Andric     llvm::SmallString<64> DenormFlag;
31315ffd83dbSDimitry Andric     llvm::raw_svector_ostream ArgStr(DenormFlag);
31325ffd83dbSDimitry Andric     ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
31335ffd83dbSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
31345ffd83dbSDimitry Andric   }
31355ffd83dbSDimitry Andric 
31365ffd83dbSDimitry Andric   // Add f32 specific denormal mode flag if it's different.
31375ffd83dbSDimitry Andric   if (DenormalFP32Math != DenormalFPMath) {
31385ffd83dbSDimitry Andric     llvm::SmallString<64> DenormFlag;
31395ffd83dbSDimitry Andric     llvm::raw_svector_ostream ArgStr(DenormFlag);
31405ffd83dbSDimitry Andric     ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
31415ffd83dbSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
31425ffd83dbSDimitry Andric   }
31430b57cec5SDimitry Andric 
31440b57cec5SDimitry Andric   if (!FPContract.empty())
31450b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
31460b57cec5SDimitry Andric 
3147480093f4SDimitry Andric   if (!RoundingFPMath)
3148480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3149480093f4SDimitry Andric 
3150480093f4SDimitry Andric   if (RoundingFPMath && RoundingMathPresent)
3151480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3152480093f4SDimitry Andric 
3153480093f4SDimitry Andric   if (!FPExceptionBehavior.empty())
3154480093f4SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3155480093f4SDimitry Andric                       FPExceptionBehavior));
3156480093f4SDimitry Andric 
315781ad6265SDimitry Andric   if (!FPEvalMethod.empty())
315881ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
315981ad6265SDimitry Andric 
3160bdd1243dSDimitry Andric   if (!Float16ExcessPrecision.empty())
3161bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3162bdd1243dSDimitry Andric                                          Float16ExcessPrecision));
316306c3fb27SDimitry Andric   if (!BFloat16ExcessPrecision.empty())
316406c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
316506c3fb27SDimitry Andric                                          BFloat16ExcessPrecision));
3166bdd1243dSDimitry Andric 
31670b57cec5SDimitry Andric   ParseMRecip(D, Args, CmdArgs);
31680b57cec5SDimitry Andric 
31690b57cec5SDimitry Andric   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
31700b57cec5SDimitry Andric   // individual features enabled by -ffast-math instead of the option itself as
31710b57cec5SDimitry Andric   // that's consistent with gcc's behaviour.
317204eeddc0SDimitry Andric   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3173480093f4SDimitry Andric       ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
31740b57cec5SDimitry Andric     CmdArgs.push_back("-ffast-math");
3175480093f4SDimitry Andric     if (FPModel.equals("fast")) {
3176480093f4SDimitry Andric       if (FPContract.equals("fast"))
3177480093f4SDimitry Andric         // All set, do nothing.
3178480093f4SDimitry Andric         ;
3179480093f4SDimitry Andric       else if (FPContract.empty())
3180480093f4SDimitry Andric         // Enable -ffp-contract=fast
3181480093f4SDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3182480093f4SDimitry Andric       else
31835f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_overriding_option)
3184480093f4SDimitry Andric             << "-ffp-model=fast"
3185480093f4SDimitry Andric             << Args.MakeArgString("-ffp-contract=" + FPContract);
3186480093f4SDimitry Andric     }
3187480093f4SDimitry Andric   }
31880b57cec5SDimitry Andric 
31890b57cec5SDimitry Andric   // Handle __FINITE_MATH_ONLY__ similarly.
31900b57cec5SDimitry Andric   if (!HonorINFs && !HonorNaNs)
31910b57cec5SDimitry Andric     CmdArgs.push_back("-ffinite-math-only");
31920b57cec5SDimitry Andric 
31930b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
31940b57cec5SDimitry Andric     CmdArgs.push_back("-mfpmath");
31950b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
31960b57cec5SDimitry Andric   }
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric   // Disable a codegen optimization for floating-point casts.
31990b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
32000b57cec5SDimitry Andric                    options::OPT_fstrict_float_cast_overflow, false))
32010b57cec5SDimitry Andric     CmdArgs.push_back("-fno-strict-float-cast-overflow");
32025f757f3fSDimitry Andric 
3203cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fcx_limited_range))
32045f757f3fSDimitry Andric     CmdArgs.push_back("-fcx-limited-range");
3205cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fcx_fortran_rules))
32065f757f3fSDimitry Andric     CmdArgs.push_back("-fcx-fortran-rules");
3207cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fno_cx_limited_range))
32085f757f3fSDimitry Andric     CmdArgs.push_back("-fno-cx-limited-range");
3209cb14a3feSDimitry Andric   if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
32105f757f3fSDimitry Andric     CmdArgs.push_back("-fno-cx-fortran-rules");
32110b57cec5SDimitry Andric }
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
32140b57cec5SDimitry Andric                                   const llvm::Triple &Triple,
32150b57cec5SDimitry Andric                                   const InputInfo &Input) {
32160b57cec5SDimitry Andric   // Add default argument set.
32170b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
32180b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=core");
32190b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=apiModeling");
32200b57cec5SDimitry Andric 
32210b57cec5SDimitry Andric     if (!Triple.isWindowsMSVCEnvironment()) {
32220b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix");
32230b57cec5SDimitry Andric     } else {
32240b57cec5SDimitry Andric       // Enable "unix" checkers that also work on Windows.
32250b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.API");
32260b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
32270b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
32280b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
32290b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
32300b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
32310b57cec5SDimitry Andric     }
32320b57cec5SDimitry Andric 
323381ad6265SDimitry Andric     // Disable some unix checkers for PS4/PS5.
323481ad6265SDimitry Andric     if (Triple.isPS()) {
32350b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
32360b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
32370b57cec5SDimitry Andric     }
32380b57cec5SDimitry Andric 
3239480093f4SDimitry Andric     if (Triple.isOSDarwin()) {
32400b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=osx");
3241480093f4SDimitry Andric       CmdArgs.push_back(
3242480093f4SDimitry Andric           "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3243480093f4SDimitry Andric     }
3244480093f4SDimitry Andric     else if (Triple.isOSFuchsia())
3245480093f4SDimitry Andric       CmdArgs.push_back("-analyzer-checker=fuchsia");
32460b57cec5SDimitry Andric 
32470b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=deadcode");
32480b57cec5SDimitry Andric 
32490b57cec5SDimitry Andric     if (types::isCXX(Input.getType()))
32500b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=cplusplus");
32510b57cec5SDimitry Andric 
325281ad6265SDimitry Andric     if (!Triple.isPS()) {
32530b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
32540b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
32550b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
32560b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
32570b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
32580b57cec5SDimitry Andric       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
32590b57cec5SDimitry Andric     }
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric     // Default nullability checks.
32620b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
32630b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
32640b57cec5SDimitry Andric   }
32650b57cec5SDimitry Andric 
32660b57cec5SDimitry Andric   // Set the output format. The default is plist, for (lame) historical reasons.
32670b57cec5SDimitry Andric   CmdArgs.push_back("-analyzer-output");
32680b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
32690b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
32700b57cec5SDimitry Andric   else
32710b57cec5SDimitry Andric     CmdArgs.push_back("plist");
32720b57cec5SDimitry Andric 
32730b57cec5SDimitry Andric   // Disable the presentation of standard compiler warnings when using
32740b57cec5SDimitry Andric   // --analyze.  We only want to show static analyzer diagnostics or frontend
32750b57cec5SDimitry Andric   // errors.
32760b57cec5SDimitry Andric   CmdArgs.push_back("-w");
32770b57cec5SDimitry Andric 
32780b57cec5SDimitry Andric   // Add -Xanalyzer arguments when running as analyzer.
32790b57cec5SDimitry Andric   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
32800b57cec5SDimitry Andric }
32810b57cec5SDimitry Andric 
3282753f127fSDimitry Andric static bool isValidSymbolName(StringRef S) {
3283753f127fSDimitry Andric   if (S.empty())
3284753f127fSDimitry Andric     return false;
3285753f127fSDimitry Andric 
3286753f127fSDimitry Andric   if (std::isdigit(S[0]))
3287753f127fSDimitry Andric     return false;
3288753f127fSDimitry Andric 
3289753f127fSDimitry Andric   return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3290753f127fSDimitry Andric }
3291753f127fSDimitry Andric 
3292e8d8bef9SDimitry Andric static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3293e8d8bef9SDimitry Andric                              const ArgList &Args, ArgStringList &CmdArgs,
3294e8d8bef9SDimitry Andric                              bool KernelOrKext) {
32950b57cec5SDimitry Andric   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
32960b57cec5SDimitry Andric 
32970b57cec5SDimitry Andric   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
32980b57cec5SDimitry Andric   // doesn't even have a stack!
32990b57cec5SDimitry Andric   if (EffectiveTriple.isNVPTX())
33000b57cec5SDimitry Andric     return;
33010b57cec5SDimitry Andric 
33020b57cec5SDimitry Andric   // -stack-protector=0 is default.
3303e8d8bef9SDimitry Andric   LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3304e8d8bef9SDimitry Andric   LangOptions::StackProtectorMode DefaultStackProtectorLevel =
33050b57cec5SDimitry Andric       TC.GetDefaultStackProtectorLevel(KernelOrKext);
33060b57cec5SDimitry Andric 
33070b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
33080b57cec5SDimitry Andric                                options::OPT_fstack_protector_all,
33090b57cec5SDimitry Andric                                options::OPT_fstack_protector_strong,
33100b57cec5SDimitry Andric                                options::OPT_fstack_protector)) {
33110b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fstack_protector))
33120b57cec5SDimitry Andric       StackProtectorLevel =
3313e8d8bef9SDimitry Andric           std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
33140b57cec5SDimitry Andric     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
33150b57cec5SDimitry Andric       StackProtectorLevel = LangOptions::SSPStrong;
33160b57cec5SDimitry Andric     else if (A->getOption().matches(options::OPT_fstack_protector_all))
33170b57cec5SDimitry Andric       StackProtectorLevel = LangOptions::SSPReq;
3318bdd1243dSDimitry Andric 
3319bdd1243dSDimitry Andric     if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3320bdd1243dSDimitry Andric       D.Diag(diag::warn_drv_unsupported_option_for_target)
3321bdd1243dSDimitry Andric           << A->getSpelling() << EffectiveTriple.getTriple();
3322bdd1243dSDimitry Andric       StackProtectorLevel = DefaultStackProtectorLevel;
3323bdd1243dSDimitry Andric     }
33240b57cec5SDimitry Andric   } else {
33250b57cec5SDimitry Andric     StackProtectorLevel = DefaultStackProtectorLevel;
33260b57cec5SDimitry Andric   }
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric   if (StackProtectorLevel) {
33290b57cec5SDimitry Andric     CmdArgs.push_back("-stack-protector");
33300b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
33310b57cec5SDimitry Andric   }
33320b57cec5SDimitry Andric 
33330b57cec5SDimitry Andric   // --param ssp-buffer-size=
33340b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT__param)) {
33350b57cec5SDimitry Andric     StringRef Str(A->getValue());
33365f757f3fSDimitry Andric     if (Str.starts_with("ssp-buffer-size=")) {
33370b57cec5SDimitry Andric       if (StackProtectorLevel) {
33380b57cec5SDimitry Andric         CmdArgs.push_back("-stack-protector-buffer-size");
33390b57cec5SDimitry Andric         // FIXME: Verify the argument is a valid integer.
33400b57cec5SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
33410b57cec5SDimitry Andric       }
33420b57cec5SDimitry Andric       A->claim();
33430b57cec5SDimitry Andric     }
33440b57cec5SDimitry Andric   }
3345e8d8bef9SDimitry Andric 
3346e8d8bef9SDimitry Andric   const std::string &TripleStr = EffectiveTriple.getTriple();
3347e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3348e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3349349cc55cSDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3350349cc55cSDimitry Andric         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3351e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3352e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3353349cc55cSDimitry Andric     if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3354349cc55cSDimitry Andric          EffectiveTriple.isThumb()) &&
3355349cc55cSDimitry Andric         Value != "tls" && Value != "global") {
3356e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3357fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "tls global";
3358fe6060f1SDimitry Andric       return;
3359fe6060f1SDimitry Andric     }
3360349cc55cSDimitry Andric     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3361349cc55cSDimitry Andric         Value == "tls") {
3362349cc55cSDimitry Andric       if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3363349cc55cSDimitry Andric         D.Diag(diag::err_drv_ssp_missing_offset_argument)
3364349cc55cSDimitry Andric             << A->getAsString(Args);
3365349cc55cSDimitry Andric         return;
3366349cc55cSDimitry Andric       }
3367349cc55cSDimitry Andric       // Check whether the target subarch supports the hardware TLS register
336804eeddc0SDimitry Andric       if (!arm::isHardTPSupported(EffectiveTriple)) {
3369349cc55cSDimitry Andric         D.Diag(diag::err_target_unsupported_tp_hard)
3370349cc55cSDimitry Andric             << EffectiveTriple.getArchName();
3371349cc55cSDimitry Andric         return;
3372349cc55cSDimitry Andric       }
3373349cc55cSDimitry Andric       // Check whether the user asked for something other than -mtp=cp15
3374349cc55cSDimitry Andric       if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3375349cc55cSDimitry Andric         StringRef Value = A->getValue();
3376349cc55cSDimitry Andric         if (Value != "cp15") {
3377349cc55cSDimitry Andric           D.Diag(diag::err_drv_argument_not_allowed_with)
3378349cc55cSDimitry Andric               << A->getAsString(Args) << "-mstack-protector-guard=tls";
3379349cc55cSDimitry Andric           return;
3380349cc55cSDimitry Andric         }
3381349cc55cSDimitry Andric       }
3382349cc55cSDimitry Andric       CmdArgs.push_back("-target-feature");
338306c3fb27SDimitry Andric       CmdArgs.push_back("+read-tp-tpidruro");
3384349cc55cSDimitry Andric     }
3385fe6060f1SDimitry Andric     if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3386fe6060f1SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3387fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "sysreg global";
3388e8d8bef9SDimitry Andric       return;
3389e8d8bef9SDimitry Andric     }
3390e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3391e8d8bef9SDimitry Andric   }
3392e8d8bef9SDimitry Andric 
3393e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3394e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3395349cc55cSDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3396349cc55cSDimitry Andric         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3397e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3398e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3399fe6060f1SDimitry Andric     int Offset;
3400e8d8bef9SDimitry Andric     if (Value.getAsInteger(10, Offset)) {
3401e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3402e8d8bef9SDimitry Andric       return;
3403e8d8bef9SDimitry Andric     }
3404349cc55cSDimitry Andric     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3405349cc55cSDimitry Andric         (Offset < 0 || Offset > 0xfffff)) {
3406349cc55cSDimitry Andric       D.Diag(diag::err_drv_invalid_int_value)
3407349cc55cSDimitry Andric           << A->getOption().getName() << Value;
3408349cc55cSDimitry Andric       return;
3409349cc55cSDimitry Andric     }
3410e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3411e8d8bef9SDimitry Andric   }
3412e8d8bef9SDimitry Andric 
3413e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3414e8d8bef9SDimitry Andric     StringRef Value = A->getValue();
3415fe6060f1SDimitry Andric     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3416e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
3417e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
3418e8d8bef9SDimitry Andric     if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3419e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3420fe6060f1SDimitry Andric           << A->getOption().getName() << Value << "fs gs";
3421fe6060f1SDimitry Andric       return;
3422fe6060f1SDimitry Andric     }
3423fe6060f1SDimitry Andric     if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3424fe6060f1SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3425e8d8bef9SDimitry Andric       return;
3426e8d8bef9SDimitry Andric     }
3427e8d8bef9SDimitry Andric     A->render(Args, CmdArgs);
3428e8d8bef9SDimitry Andric   }
3429753f127fSDimitry Andric 
3430753f127fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3431753f127fSDimitry Andric     StringRef Value = A->getValue();
3432753f127fSDimitry Andric     if (!isValidSymbolName(Value)) {
3433753f127fSDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
3434753f127fSDimitry Andric           << A->getOption().getName() << "legal symbol name";
3435753f127fSDimitry Andric       return;
3436753f127fSDimitry Andric     }
3437753f127fSDimitry Andric     A->render(Args, CmdArgs);
3438753f127fSDimitry Andric   }
34390b57cec5SDimitry Andric }
34400b57cec5SDimitry Andric 
34415ffd83dbSDimitry Andric static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
34425ffd83dbSDimitry Andric                              ArgStringList &CmdArgs) {
34435ffd83dbSDimitry Andric   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
34445ffd83dbSDimitry Andric 
34453063e1e5SEd Maste   if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
34465ffd83dbSDimitry Andric     return;
34475ffd83dbSDimitry Andric 
34485ffd83dbSDimitry Andric   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
34495f757f3fSDimitry Andric       !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
34505ffd83dbSDimitry Andric     return;
34515ffd83dbSDimitry Andric 
345281ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
345381ad6265SDimitry Andric                     options::OPT_fno_stack_clash_protection);
34545ffd83dbSDimitry Andric }
34555ffd83dbSDimitry Andric 
34560b57cec5SDimitry Andric static void RenderTrivialAutoVarInitOptions(const Driver &D,
34570b57cec5SDimitry Andric                                             const ToolChain &TC,
34580b57cec5SDimitry Andric                                             const ArgList &Args,
34590b57cec5SDimitry Andric                                             ArgStringList &CmdArgs) {
34600b57cec5SDimitry Andric   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
34610b57cec5SDimitry Andric   StringRef TrivialAutoVarInit = "";
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric   for (const Arg *A : Args) {
34640b57cec5SDimitry Andric     switch (A->getOption().getID()) {
34650b57cec5SDimitry Andric     default:
34660b57cec5SDimitry Andric       continue;
34670b57cec5SDimitry Andric     case options::OPT_ftrivial_auto_var_init: {
34680b57cec5SDimitry Andric       A->claim();
34690b57cec5SDimitry Andric       StringRef Val = A->getValue();
34700b57cec5SDimitry Andric       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
34710b57cec5SDimitry Andric         TrivialAutoVarInit = Val;
34720b57cec5SDimitry Andric       else
34730b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_option_argument)
3474bdd1243dSDimitry Andric             << A->getSpelling() << Val;
34750b57cec5SDimitry Andric       break;
34760b57cec5SDimitry Andric     }
34770b57cec5SDimitry Andric     }
34780b57cec5SDimitry Andric   }
34790b57cec5SDimitry Andric 
34800b57cec5SDimitry Andric   if (TrivialAutoVarInit.empty())
34810b57cec5SDimitry Andric     switch (DefaultTrivialAutoVarInit) {
34820b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
34830b57cec5SDimitry Andric       break;
34840b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Pattern:
34850b57cec5SDimitry Andric       TrivialAutoVarInit = "pattern";
34860b57cec5SDimitry Andric       break;
34870b57cec5SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Zero:
34880b57cec5SDimitry Andric       TrivialAutoVarInit = "zero";
34890b57cec5SDimitry Andric       break;
34900b57cec5SDimitry Andric     }
34910b57cec5SDimitry Andric 
34920b57cec5SDimitry Andric   if (!TrivialAutoVarInit.empty()) {
34930b57cec5SDimitry Andric     CmdArgs.push_back(
34940b57cec5SDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
34950b57cec5SDimitry Andric   }
34965ffd83dbSDimitry Andric 
34975ffd83dbSDimitry Andric   if (Arg *A =
34985ffd83dbSDimitry Andric           Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
34995ffd83dbSDimitry Andric     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
35005ffd83dbSDimitry Andric         StringRef(
35015ffd83dbSDimitry Andric             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
35025ffd83dbSDimitry Andric             "uninitialized")
35035ffd83dbSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
35045ffd83dbSDimitry Andric     A->claim();
35055ffd83dbSDimitry Andric     StringRef Val = A->getValue();
35065ffd83dbSDimitry Andric     if (std::stoi(Val.str()) <= 0)
35075ffd83dbSDimitry Andric       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
35085ffd83dbSDimitry Andric     CmdArgs.push_back(
35095ffd83dbSDimitry Andric         Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
35105ffd83dbSDimitry Andric   }
35110b57cec5SDimitry Andric }
35120b57cec5SDimitry Andric 
3513fe6060f1SDimitry Andric static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3514fe6060f1SDimitry Andric                                 types::ID InputType) {
35155ffd83dbSDimitry Andric   // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
35165ffd83dbSDimitry Andric   // for denormal flushing handling based on the target.
35170b57cec5SDimitry Andric   const unsigned ForwardedArguments[] = {
35180b57cec5SDimitry Andric       options::OPT_cl_opt_disable,
35190b57cec5SDimitry Andric       options::OPT_cl_strict_aliasing,
35200b57cec5SDimitry Andric       options::OPT_cl_single_precision_constant,
35210b57cec5SDimitry Andric       options::OPT_cl_finite_math_only,
35220b57cec5SDimitry Andric       options::OPT_cl_kernel_arg_info,
35230b57cec5SDimitry Andric       options::OPT_cl_unsafe_math_optimizations,
35240b57cec5SDimitry Andric       options::OPT_cl_fast_relaxed_math,
35250b57cec5SDimitry Andric       options::OPT_cl_mad_enable,
35260b57cec5SDimitry Andric       options::OPT_cl_no_signed_zeros,
35270b57cec5SDimitry Andric       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
35280b57cec5SDimitry Andric       options::OPT_cl_uniform_work_group_size
35290b57cec5SDimitry Andric   };
35300b57cec5SDimitry Andric 
35310b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
35320b57cec5SDimitry Andric     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
35330b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
353481ad6265SDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
353581ad6265SDimitry Andric     std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
353681ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CLExtStr));
35370b57cec5SDimitry Andric   }
35380b57cec5SDimitry Andric 
35390b57cec5SDimitry Andric   for (const auto &Arg : ForwardedArguments)
35400b57cec5SDimitry Andric     if (const auto *A = Args.getLastArg(Arg))
35410b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3542fe6060f1SDimitry Andric 
3543fe6060f1SDimitry Andric   // Only add the default headers if we are compiling OpenCL sources.
3544fe6060f1SDimitry Andric   if ((types::isOpenCL(InputType) ||
3545fe6060f1SDimitry Andric        (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3546fe6060f1SDimitry Andric       !Args.hasArg(options::OPT_cl_no_stdinc)) {
3547fe6060f1SDimitry Andric     CmdArgs.push_back("-finclude-default-header");
3548fe6060f1SDimitry Andric     CmdArgs.push_back("-fdeclare-opencl-builtins");
3549fe6060f1SDimitry Andric   }
35500b57cec5SDimitry Andric }
35510b57cec5SDimitry Andric 
355281ad6265SDimitry Andric static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
355381ad6265SDimitry Andric                               types::ID InputType) {
355481ad6265SDimitry Andric   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
355581ad6265SDimitry Andric                                          options::OPT_D,
3556fcaf7f86SDimitry Andric                                          options::OPT_I,
355781ad6265SDimitry Andric                                          options::OPT_S,
3558bdd1243dSDimitry Andric                                          options::OPT_O,
355981ad6265SDimitry Andric                                          options::OPT_emit_llvm,
3560bdd1243dSDimitry Andric                                          options::OPT_emit_obj,
356181ad6265SDimitry Andric                                          options::OPT_disable_llvm_passes,
3562bdd1243dSDimitry Andric                                          options::OPT_fnative_half_type,
3563bdd1243dSDimitry Andric                                          options::OPT_hlsl_entrypoint};
3564bdd1243dSDimitry Andric   if (!types::isHLSL(InputType))
3565bdd1243dSDimitry Andric     return;
356681ad6265SDimitry Andric   for (const auto &Arg : ForwardedArguments)
356781ad6265SDimitry Andric     if (const auto *A = Args.getLastArg(Arg))
356881ad6265SDimitry Andric       A->renderAsInput(Args, CmdArgs);
356981ad6265SDimitry Andric   // Add the default headers if dxc_no_stdinc is not set.
3570bdd1243dSDimitry Andric   if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3571bdd1243dSDimitry Andric       !Args.hasArg(options::OPT_nostdinc))
357281ad6265SDimitry Andric     CmdArgs.push_back("-finclude-default-header");
357381ad6265SDimitry Andric }
357481ad6265SDimitry Andric 
35755f757f3fSDimitry Andric static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
35765f757f3fSDimitry Andric                                  ArgStringList &CmdArgs, types::ID InputType) {
35775f757f3fSDimitry Andric   if (!Args.hasArg(options::OPT_fopenacc))
35785f757f3fSDimitry Andric     return;
35795f757f3fSDimitry Andric 
35805f757f3fSDimitry Andric   CmdArgs.push_back("-fopenacc");
35815f757f3fSDimitry Andric 
35825f757f3fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
35835f757f3fSDimitry Andric     StringRef Value = A->getValue();
35845f757f3fSDimitry Andric     int Version;
35855f757f3fSDimitry Andric     if (!Value.getAsInteger(10, Version))
35865f757f3fSDimitry Andric       A->renderAsInput(Args, CmdArgs);
35875f757f3fSDimitry Andric     else
35885f757f3fSDimitry Andric       D.Diag(diag::err_drv_clang_unsupported) << Value;
35895f757f3fSDimitry Andric   }
35905f757f3fSDimitry Andric }
35915f757f3fSDimitry Andric 
35920b57cec5SDimitry Andric static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
35930b57cec5SDimitry Andric                                         ArgStringList &CmdArgs) {
35940b57cec5SDimitry Andric   bool ARCMTEnabled = false;
35950b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
35960b57cec5SDimitry Andric     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
35970b57cec5SDimitry Andric                                        options::OPT_ccc_arcmt_modify,
35980b57cec5SDimitry Andric                                        options::OPT_ccc_arcmt_migrate)) {
35990b57cec5SDimitry Andric       ARCMTEnabled = true;
36000b57cec5SDimitry Andric       switch (A->getOption().getID()) {
36010b57cec5SDimitry Andric       default: llvm_unreachable("missed a case");
36020b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_check:
3603e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=check");
36040b57cec5SDimitry Andric         break;
36050b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_modify:
3606e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=modify");
36070b57cec5SDimitry Andric         break;
36080b57cec5SDimitry Andric       case options::OPT_ccc_arcmt_migrate:
3609e8d8bef9SDimitry Andric         CmdArgs.push_back("-arcmt-action=migrate");
36100b57cec5SDimitry Andric         CmdArgs.push_back("-mt-migrate-directory");
36110b57cec5SDimitry Andric         CmdArgs.push_back(A->getValue());
36120b57cec5SDimitry Andric 
36130b57cec5SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
36140b57cec5SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
36150b57cec5SDimitry Andric         break;
36160b57cec5SDimitry Andric       }
36170b57cec5SDimitry Andric     }
36180b57cec5SDimitry Andric   } else {
36190b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
36200b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
36210b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
36220b57cec5SDimitry Andric   }
36230b57cec5SDimitry Andric 
36240b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
36250b57cec5SDimitry Andric     if (ARCMTEnabled)
36260b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
36270b57cec5SDimitry Andric           << A->getAsString(Args) << "-ccc-arcmt-migrate";
36280b57cec5SDimitry Andric 
36290b57cec5SDimitry Andric     CmdArgs.push_back("-mt-migrate-directory");
36300b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
36310b57cec5SDimitry Andric 
36320b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
36330b57cec5SDimitry Andric                      options::OPT_objcmt_migrate_subscripting,
36340b57cec5SDimitry Andric                      options::OPT_objcmt_migrate_property)) {
36350b57cec5SDimitry Andric       // None specified, means enable them all.
36360b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-literals");
36370b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-subscripting");
36380b57cec5SDimitry Andric       CmdArgs.push_back("-objcmt-migrate-property");
36390b57cec5SDimitry Andric     } else {
36400b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
36410b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
36420b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
36430b57cec5SDimitry Andric     }
36440b57cec5SDimitry Andric   } else {
36450b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
36460b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
36470b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
36480b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
36490b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
36500b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
36510b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
36520b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
36530b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
36540b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
36550b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
36560b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
36570b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
36580b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
36590b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3660349cc55cSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
36610b57cec5SDimitry Andric   }
36620b57cec5SDimitry Andric }
36630b57cec5SDimitry Andric 
36640b57cec5SDimitry Andric static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
36650b57cec5SDimitry Andric                                  const ArgList &Args, ArgStringList &CmdArgs) {
36660b57cec5SDimitry Andric   // -fbuiltin is default unless -mkernel is used.
36670b57cec5SDimitry Andric   bool UseBuiltins =
36680b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
36690b57cec5SDimitry Andric                    !Args.hasArg(options::OPT_mkernel));
36700b57cec5SDimitry Andric   if (!UseBuiltins)
36710b57cec5SDimitry Andric     CmdArgs.push_back("-fno-builtin");
36720b57cec5SDimitry Andric 
36730b57cec5SDimitry Andric   // -ffreestanding implies -fno-builtin.
36740b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_ffreestanding))
36750b57cec5SDimitry Andric     UseBuiltins = false;
36760b57cec5SDimitry Andric 
36770b57cec5SDimitry Andric   // Process the -fno-builtin-* options.
367881ad6265SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
367981ad6265SDimitry Andric     A->claim();
36800b57cec5SDimitry Andric 
36810b57cec5SDimitry Andric     // If -fno-builtin is specified, then there's no need to pass the option to
36820b57cec5SDimitry Andric     // the frontend.
368381ad6265SDimitry Andric     if (UseBuiltins)
368481ad6265SDimitry Andric       A->render(Args, CmdArgs);
36850b57cec5SDimitry Andric   }
36860b57cec5SDimitry Andric 
36870b57cec5SDimitry Andric   // le32-specific flags:
36880b57cec5SDimitry Andric   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
36890b57cec5SDimitry Andric   //                     by default.
36900b57cec5SDimitry Andric   if (TC.getArch() == llvm::Triple::le32)
36910b57cec5SDimitry Andric     CmdArgs.push_back("-fno-math-builtin");
36920b57cec5SDimitry Andric }
36930b57cec5SDimitry Andric 
36945ffd83dbSDimitry Andric bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
369581ad6265SDimitry Andric   if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
369681ad6265SDimitry Andric     Twine Path{Str};
369781ad6265SDimitry Andric     Path.toVector(Result);
369881ad6265SDimitry Andric     return Path.getSingleStringRef() != "";
369981ad6265SDimitry Andric   }
37005ffd83dbSDimitry Andric   if (llvm::sys::path::cache_directory(Result)) {
37015ffd83dbSDimitry Andric     llvm::sys::path::append(Result, "clang");
37020b57cec5SDimitry Andric     llvm::sys::path::append(Result, "ModuleCache");
37035ffd83dbSDimitry Andric     return true;
37045ffd83dbSDimitry Andric   }
37055ffd83dbSDimitry Andric   return false;
37060b57cec5SDimitry Andric }
37070b57cec5SDimitry Andric 
3708bdd1243dSDimitry Andric static bool RenderModulesOptions(Compilation &C, const Driver &D,
37090b57cec5SDimitry Andric                                  const ArgList &Args, const InputInfo &Input,
37105f757f3fSDimitry Andric                                  const InputInfo &Output, bool HaveStd20,
3711bdd1243dSDimitry Andric                                  ArgStringList &CmdArgs) {
3712bdd1243dSDimitry Andric   bool IsCXX = types::isCXX(Input.getType());
37135f757f3fSDimitry Andric   bool HaveStdCXXModules = IsCXX && HaveStd20;
3714bdd1243dSDimitry Andric   bool HaveModules = HaveStdCXXModules;
3715bdd1243dSDimitry Andric 
37160b57cec5SDimitry Andric   // -fmodules enables the use of precompiled modules (off by default).
37170b57cec5SDimitry Andric   // Users can pass -fno-cxx-modules to turn off modules support for
37180b57cec5SDimitry Andric   // C++/Objective-C++ programs.
37190b57cec5SDimitry Andric   bool HaveClangModules = false;
37200b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
37210b57cec5SDimitry Andric     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
37220b57cec5SDimitry Andric                                      options::OPT_fno_cxx_modules, true);
3723bdd1243dSDimitry Andric     if (AllowedInCXX || !IsCXX) {
37240b57cec5SDimitry Andric       CmdArgs.push_back("-fmodules");
37250b57cec5SDimitry Andric       HaveClangModules = true;
37260b57cec5SDimitry Andric     }
37270b57cec5SDimitry Andric   }
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric   HaveModules |= HaveClangModules;
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric   // -fmodule-maps enables implicit reading of module map files. By default,
37320b57cec5SDimitry Andric   // this is enabled if we are using Clang's flavor of precompiled modules.
37330b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
37340b57cec5SDimitry Andric                    options::OPT_fno_implicit_module_maps, HaveClangModules))
37350b57cec5SDimitry Andric     CmdArgs.push_back("-fimplicit-module-maps");
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric   // -fmodules-decluse checks that modules used are declared so (off by default)
373881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
373981ad6265SDimitry Andric                     options::OPT_fno_modules_decluse);
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
37420b57cec5SDimitry Andric   // all #included headers are part of modules.
37430b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
37440b57cec5SDimitry Andric                    options::OPT_fno_modules_strict_decluse, false))
37450b57cec5SDimitry Andric     CmdArgs.push_back("-fmodules-strict-decluse");
37460b57cec5SDimitry Andric 
37470b57cec5SDimitry Andric   // -fno-implicit-modules turns off implicitly compiling modules on demand.
37480b57cec5SDimitry Andric   bool ImplicitModules = false;
37490b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fimplicit_modules,
37500b57cec5SDimitry Andric                     options::OPT_fno_implicit_modules, HaveClangModules)) {
37510b57cec5SDimitry Andric     if (HaveModules)
37520b57cec5SDimitry Andric       CmdArgs.push_back("-fno-implicit-modules");
37530b57cec5SDimitry Andric   } else if (HaveModules) {
37540b57cec5SDimitry Andric     ImplicitModules = true;
37550b57cec5SDimitry Andric     // -fmodule-cache-path specifies where our implicitly-built module files
37560b57cec5SDimitry Andric     // should be written.
37570b57cec5SDimitry Andric     SmallString<128> Path;
37580b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
37590b57cec5SDimitry Andric       Path = A->getValue();
37600b57cec5SDimitry Andric 
37615ffd83dbSDimitry Andric     bool HasPath = true;
37620b57cec5SDimitry Andric     if (C.isForDiagnostics()) {
37630b57cec5SDimitry Andric       // When generating crash reports, we want to emit the modules along with
37640b57cec5SDimitry Andric       // the reproduction sources, so we ignore any provided module path.
37650b57cec5SDimitry Andric       Path = Output.getFilename();
37660b57cec5SDimitry Andric       llvm::sys::path::replace_extension(Path, ".cache");
37670b57cec5SDimitry Andric       llvm::sys::path::append(Path, "modules");
37680b57cec5SDimitry Andric     } else if (Path.empty()) {
37690b57cec5SDimitry Andric       // No module path was provided: use the default.
37705ffd83dbSDimitry Andric       HasPath = Driver::getDefaultModuleCachePath(Path);
37710b57cec5SDimitry Andric     }
37720b57cec5SDimitry Andric 
37735ffd83dbSDimitry Andric     // `HasPath` will only be false if getDefaultModuleCachePath() fails.
37745ffd83dbSDimitry Andric     // That being said, that failure is unlikely and not caching is harmless.
37755ffd83dbSDimitry Andric     if (HasPath) {
37760b57cec5SDimitry Andric       const char Arg[] = "-fmodules-cache-path=";
37770b57cec5SDimitry Andric       Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
37780b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Path));
37790b57cec5SDimitry Andric     }
37805ffd83dbSDimitry Andric   }
37810b57cec5SDimitry Andric 
37820b57cec5SDimitry Andric   if (HaveModules) {
3783e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3784e8d8bef9SDimitry Andric                      options::OPT_fno_prebuilt_implicit_modules, false))
3785e8d8bef9SDimitry Andric       CmdArgs.push_back("-fprebuilt-implicit-modules");
3786a7dea167SDimitry Andric     if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3787a7dea167SDimitry Andric                      options::OPT_fno_modules_validate_input_files_content,
3788a7dea167SDimitry Andric                      false))
3789a7dea167SDimitry Andric       CmdArgs.push_back("-fvalidate-ast-input-files-content");
37900b57cec5SDimitry Andric   }
37910b57cec5SDimitry Andric 
37920b57cec5SDimitry Andric   // -fmodule-name specifies the module that is currently being built (or
37930b57cec5SDimitry Andric   // used for header checking by -fmodule-maps).
37940b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
37950b57cec5SDimitry Andric 
37960b57cec5SDimitry Andric   // -fmodule-map-file can be used to specify files containing module
37970b57cec5SDimitry Andric   // definitions.
37980b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric   // -fbuiltin-module-map can be used to load the clang
38010b57cec5SDimitry Andric   // builtin headers modulemap file.
38020b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
38030b57cec5SDimitry Andric     SmallString<128> BuiltinModuleMap(D.ResourceDir);
38040b57cec5SDimitry Andric     llvm::sys::path::append(BuiltinModuleMap, "include");
38050b57cec5SDimitry Andric     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
38060b57cec5SDimitry Andric     if (llvm::sys::fs::exists(BuiltinModuleMap))
38070b57cec5SDimitry Andric       CmdArgs.push_back(
38080b57cec5SDimitry Andric           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
38090b57cec5SDimitry Andric   }
38100b57cec5SDimitry Andric 
38110b57cec5SDimitry Andric   // The -fmodule-file=<name>=<file> form specifies the mapping of module
38120b57cec5SDimitry Andric   // names to precompiled module files (the module is loaded only if used).
38130b57cec5SDimitry Andric   // The -fmodule-file=<file> form can be used to unconditionally load
38140b57cec5SDimitry Andric   // precompiled module files (whether used or not).
381506c3fb27SDimitry Andric   if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
38160b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
381706c3fb27SDimitry Andric 
381806c3fb27SDimitry Andric     // -fprebuilt-module-path specifies where to load the prebuilt module files.
381906c3fb27SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
382006c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
382106c3fb27SDimitry Andric           std::string("-fprebuilt-module-path=") + A->getValue()));
382206c3fb27SDimitry Andric       A->claim();
382306c3fb27SDimitry Andric     }
382406c3fb27SDimitry Andric   } else
38250b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodule_file);
38260b57cec5SDimitry Andric 
38270b57cec5SDimitry Andric   // When building modules and generating crashdumps, we need to dump a module
38280b57cec5SDimitry Andric   // dependency VFS alongside the output.
38290b57cec5SDimitry Andric   if (HaveClangModules && C.isForDiagnostics()) {
38300b57cec5SDimitry Andric     SmallString<128> VFSDir(Output.getFilename());
38310b57cec5SDimitry Andric     llvm::sys::path::replace_extension(VFSDir, ".cache");
38320b57cec5SDimitry Andric     // Add the cache directory as a temp so the crash diagnostics pick it up.
38330b57cec5SDimitry Andric     C.addTempFile(Args.MakeArgString(VFSDir));
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric     llvm::sys::path::append(VFSDir, "vfs");
38360b57cec5SDimitry Andric     CmdArgs.push_back("-module-dependency-dir");
38370b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(VFSDir));
38380b57cec5SDimitry Andric   }
38390b57cec5SDimitry Andric 
38400b57cec5SDimitry Andric   if (HaveClangModules)
38410b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
38420b57cec5SDimitry Andric 
38430b57cec5SDimitry Andric   // Pass through all -fmodules-ignore-macro arguments.
38440b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
38450b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
38460b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
38470b57cec5SDimitry Andric 
3848753f127fSDimitry Andric   if (HaveClangModules) {
38490b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
38500b57cec5SDimitry Andric 
38510b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
38520b57cec5SDimitry Andric       if (Args.hasArg(options::OPT_fbuild_session_timestamp))
38530b57cec5SDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
38540b57cec5SDimitry Andric             << A->getAsString(Args) << "-fbuild-session-timestamp";
38550b57cec5SDimitry Andric 
38560b57cec5SDimitry Andric       llvm::sys::fs::file_status Status;
38570b57cec5SDimitry Andric       if (llvm::sys::fs::status(A->getValue(), Status))
38580b57cec5SDimitry Andric         D.Diag(diag::err_drv_no_such_file) << A->getValue();
3859349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
3860349cc55cSDimitry Andric           "-fbuild-session-timestamp=" +
3861349cc55cSDimitry Andric           Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3862349cc55cSDimitry Andric                     Status.getLastModificationTime().time_since_epoch())
38630b57cec5SDimitry Andric                     .count())));
38640b57cec5SDimitry Andric     }
38650b57cec5SDimitry Andric 
3866753f127fSDimitry Andric     if (Args.getLastArg(
3867753f127fSDimitry Andric             options::OPT_fmodules_validate_once_per_build_session)) {
38680b57cec5SDimitry Andric       if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
38690b57cec5SDimitry Andric                            options::OPT_fbuild_session_file))
38700b57cec5SDimitry Andric         D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
38710b57cec5SDimitry Andric 
38720b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs,
38730b57cec5SDimitry Andric                       options::OPT_fmodules_validate_once_per_build_session);
38740b57cec5SDimitry Andric     }
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
38770b57cec5SDimitry Andric                      options::OPT_fno_modules_validate_system_headers,
38780b57cec5SDimitry Andric                      ImplicitModules))
38790b57cec5SDimitry Andric       CmdArgs.push_back("-fmodules-validate-system-headers");
38800b57cec5SDimitry Andric 
3881753f127fSDimitry Andric     Args.AddLastArg(CmdArgs,
3882753f127fSDimitry Andric                     options::OPT_fmodules_disable_diagnostic_validation);
3883753f127fSDimitry Andric   } else {
3884753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3885753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3886753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3887753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3888753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3889753f127fSDimitry Andric     Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3890753f127fSDimitry Andric   }
3891bdd1243dSDimitry Andric 
3892bdd1243dSDimitry Andric   // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
3893bdd1243dSDimitry Andric   Args.ClaimAllArgs(options::OPT_fmodule_output);
3894bdd1243dSDimitry Andric   Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
3895bdd1243dSDimitry Andric 
3896bdd1243dSDimitry Andric   return HaveModules;
38970b57cec5SDimitry Andric }
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
39000b57cec5SDimitry Andric                                    ArgStringList &CmdArgs) {
39010b57cec5SDimitry Andric   // -fsigned-char is default.
39020b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
39030b57cec5SDimitry Andric                                      options::OPT_fno_signed_char,
39040b57cec5SDimitry Andric                                      options::OPT_funsigned_char,
39050b57cec5SDimitry Andric                                      options::OPT_fno_unsigned_char)) {
39060b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_funsigned_char) ||
39070b57cec5SDimitry Andric         A->getOption().matches(options::OPT_fno_signed_char)) {
39080b57cec5SDimitry Andric       CmdArgs.push_back("-fno-signed-char");
39090b57cec5SDimitry Andric     }
39100b57cec5SDimitry Andric   } else if (!isSignedCharDefault(T)) {
39110b57cec5SDimitry Andric     CmdArgs.push_back("-fno-signed-char");
39120b57cec5SDimitry Andric   }
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   // The default depends on the language standard.
39150b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
39180b57cec5SDimitry Andric                                      options::OPT_fno_short_wchar)) {
39190b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fshort_wchar)) {
39200b57cec5SDimitry Andric       CmdArgs.push_back("-fwchar-type=short");
39210b57cec5SDimitry Andric       CmdArgs.push_back("-fno-signed-wchar");
39220b57cec5SDimitry Andric     } else {
39230b57cec5SDimitry Andric       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
39240b57cec5SDimitry Andric       CmdArgs.push_back("-fwchar-type=int");
3925e8d8bef9SDimitry Andric       if (T.isOSzOS() ||
3926e8d8bef9SDimitry Andric           (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
39270b57cec5SDimitry Andric         CmdArgs.push_back("-fno-signed-wchar");
39280b57cec5SDimitry Andric       else
39290b57cec5SDimitry Andric         CmdArgs.push_back("-fsigned-wchar");
39300b57cec5SDimitry Andric     }
393106c3fb27SDimitry Andric   } else if (T.isOSzOS())
393206c3fb27SDimitry Andric     CmdArgs.push_back("-fno-signed-wchar");
39330b57cec5SDimitry Andric }
39340b57cec5SDimitry Andric 
39350b57cec5SDimitry Andric static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
39360b57cec5SDimitry Andric                               const llvm::Triple &T, const ArgList &Args,
39370b57cec5SDimitry Andric                               ObjCRuntime &Runtime, bool InferCovariantReturns,
39380b57cec5SDimitry Andric                               const InputInfo &Input, ArgStringList &CmdArgs) {
39390b57cec5SDimitry Andric   const llvm::Triple::ArchType Arch = TC.getArch();
39400b57cec5SDimitry Andric 
39410b57cec5SDimitry Andric   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
39420b57cec5SDimitry Andric   // is the default. Except for deployment target of 10.5, next runtime is
39430b57cec5SDimitry Andric   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
39440b57cec5SDimitry Andric   if (Runtime.isNonFragile()) {
39450b57cec5SDimitry Andric     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
39460b57cec5SDimitry Andric                       options::OPT_fno_objc_legacy_dispatch,
39470b57cec5SDimitry Andric                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
39480b57cec5SDimitry Andric       if (TC.UseObjCMixedDispatch())
39490b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
39500b57cec5SDimitry Andric       else
39510b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
39520b57cec5SDimitry Andric     }
39530b57cec5SDimitry Andric   }
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
39560b57cec5SDimitry Andric   // to do Array/Dictionary subscripting by default.
39570b57cec5SDimitry Andric   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
39580b57cec5SDimitry Andric       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
39590b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
39620b57cec5SDimitry Andric   // NOTE: This logic is duplicated in ToolChains.cpp.
39630b57cec5SDimitry Andric   if (isObjCAutoRefCount(Args)) {
39640b57cec5SDimitry Andric     TC.CheckObjCARC();
39650b57cec5SDimitry Andric 
39660b57cec5SDimitry Andric     CmdArgs.push_back("-fobjc-arc");
39670b57cec5SDimitry Andric 
39680b57cec5SDimitry Andric     // FIXME: It seems like this entire block, and several around it should be
39690b57cec5SDimitry Andric     // wrapped in isObjC, but for now we just use it here as this is where it
39700b57cec5SDimitry Andric     // was being used previously.
39710b57cec5SDimitry Andric     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
39720b57cec5SDimitry Andric       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
39730b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
39740b57cec5SDimitry Andric       else
39750b57cec5SDimitry Andric         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
39760b57cec5SDimitry Andric     }
39770b57cec5SDimitry Andric 
39780b57cec5SDimitry Andric     // Allow the user to enable full exceptions code emission.
39790b57cec5SDimitry Andric     // We default off for Objective-C, on for Objective-C++.
39800b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
39810b57cec5SDimitry Andric                      options::OPT_fno_objc_arc_exceptions,
39820b57cec5SDimitry Andric                      /*Default=*/types::isCXX(Input.getType())))
39830b57cec5SDimitry Andric       CmdArgs.push_back("-fobjc-arc-exceptions");
39840b57cec5SDimitry Andric   }
39850b57cec5SDimitry Andric 
39860b57cec5SDimitry Andric   // Silence warning for full exception code emission options when explicitly
39870b57cec5SDimitry Andric   // set to use no ARC.
39880b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fno_objc_arc)) {
39890b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
39900b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
39910b57cec5SDimitry Andric   }
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric   // Allow the user to control whether messages can be converted to runtime
39940b57cec5SDimitry Andric   // functions.
39950b57cec5SDimitry Andric   if (types::isObjC(Input.getType())) {
39960b57cec5SDimitry Andric     auto *Arg = Args.getLastArg(
39970b57cec5SDimitry Andric         options::OPT_fobjc_convert_messages_to_runtime_calls,
39980b57cec5SDimitry Andric         options::OPT_fno_objc_convert_messages_to_runtime_calls);
39990b57cec5SDimitry Andric     if (Arg &&
40000b57cec5SDimitry Andric         Arg->getOption().matches(
40010b57cec5SDimitry Andric             options::OPT_fno_objc_convert_messages_to_runtime_calls))
40020b57cec5SDimitry Andric       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
40030b57cec5SDimitry Andric   }
40040b57cec5SDimitry Andric 
40050b57cec5SDimitry Andric   // -fobjc-infer-related-result-type is the default, except in the Objective-C
40060b57cec5SDimitry Andric   // rewriter.
40070b57cec5SDimitry Andric   if (InferCovariantReturns)
40080b57cec5SDimitry Andric     CmdArgs.push_back("-fno-objc-infer-related-result-type");
40090b57cec5SDimitry Andric 
40100b57cec5SDimitry Andric   // Pass down -fobjc-weak or -fno-objc-weak if present.
40110b57cec5SDimitry Andric   if (types::isObjC(Input.getType())) {
40120b57cec5SDimitry Andric     auto WeakArg =
40130b57cec5SDimitry Andric         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
40140b57cec5SDimitry Andric     if (!WeakArg) {
40150b57cec5SDimitry Andric       // nothing to do
40160b57cec5SDimitry Andric     } else if (!Runtime.allowsWeak()) {
40170b57cec5SDimitry Andric       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
40180b57cec5SDimitry Andric         D.Diag(diag::err_objc_weak_unsupported);
40190b57cec5SDimitry Andric     } else {
40200b57cec5SDimitry Andric       WeakArg->render(Args, CmdArgs);
40210b57cec5SDimitry Andric     }
40220b57cec5SDimitry Andric   }
4023fe6060f1SDimitry Andric 
4024fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4025fe6060f1SDimitry Andric     CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
40260b57cec5SDimitry Andric }
40270b57cec5SDimitry Andric 
40280b57cec5SDimitry Andric static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
40290b57cec5SDimitry Andric                                      ArgStringList &CmdArgs) {
40300b57cec5SDimitry Andric   bool CaretDefault = true;
40310b57cec5SDimitry Andric   bool ColumnDefault = true;
40320b57cec5SDimitry Andric 
40330b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
40340b57cec5SDimitry Andric                                      options::OPT__SLASH_diagnostics_column,
40350b57cec5SDimitry Andric                                      options::OPT__SLASH_diagnostics_caret)) {
40360b57cec5SDimitry Andric     switch (A->getOption().getID()) {
40370b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_caret:
40380b57cec5SDimitry Andric       CaretDefault = true;
40390b57cec5SDimitry Andric       ColumnDefault = true;
40400b57cec5SDimitry Andric       break;
40410b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_column:
40420b57cec5SDimitry Andric       CaretDefault = false;
40430b57cec5SDimitry Andric       ColumnDefault = true;
40440b57cec5SDimitry Andric       break;
40450b57cec5SDimitry Andric     case options::OPT__SLASH_diagnostics_classic:
40460b57cec5SDimitry Andric       CaretDefault = false;
40470b57cec5SDimitry Andric       ColumnDefault = false;
40480b57cec5SDimitry Andric       break;
40490b57cec5SDimitry Andric     }
40500b57cec5SDimitry Andric   }
40510b57cec5SDimitry Andric 
40520b57cec5SDimitry Andric   // -fcaret-diagnostics is default.
40530b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
40540b57cec5SDimitry Andric                     options::OPT_fno_caret_diagnostics, CaretDefault))
40550b57cec5SDimitry Andric     CmdArgs.push_back("-fno-caret-diagnostics");
40560b57cec5SDimitry Andric 
405781ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
405881ad6265SDimitry Andric                      options::OPT_fno_diagnostics_fixit_info);
405981ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
406081ad6265SDimitry Andric                      options::OPT_fno_diagnostics_show_option);
40610b57cec5SDimitry Andric 
40620b57cec5SDimitry Andric   if (const Arg *A =
40630b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
40640b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-show-category");
40650b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
40660b57cec5SDimitry Andric   }
40670b57cec5SDimitry Andric 
406881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
406981ad6265SDimitry Andric                     options::OPT_fno_diagnostics_show_hotness);
40700b57cec5SDimitry Andric 
40710b57cec5SDimitry Andric   if (const Arg *A =
40720b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
40730b57cec5SDimitry Andric     std::string Opt =
40740b57cec5SDimitry Andric         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
40750b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Opt));
40760b57cec5SDimitry Andric   }
40770b57cec5SDimitry Andric 
407806c3fb27SDimitry Andric   if (const Arg *A =
407906c3fb27SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
408006c3fb27SDimitry Andric     std::string Opt =
408106c3fb27SDimitry Andric         std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
408206c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Opt));
408306c3fb27SDimitry Andric   }
408406c3fb27SDimitry Andric 
40850b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
40860b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-format");
40870b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
4088fcaf7f86SDimitry Andric     if (StringRef(A->getValue()) == "sarif" ||
4089fcaf7f86SDimitry Andric         StringRef(A->getValue()) == "SARIF")
4090fcaf7f86SDimitry Andric       D.Diag(diag::warn_drv_sarif_format_unstable);
40910b57cec5SDimitry Andric   }
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(
40940b57cec5SDimitry Andric           options::OPT_fdiagnostics_show_note_include_stack,
40950b57cec5SDimitry Andric           options::OPT_fno_diagnostics_show_note_include_stack)) {
40960b57cec5SDimitry Andric     const Option &O = A->getOption();
40970b57cec5SDimitry Andric     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
40980b57cec5SDimitry Andric       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
40990b57cec5SDimitry Andric     else
41000b57cec5SDimitry Andric       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
41010b57cec5SDimitry Andric   }
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   // Color diagnostics are parsed by the driver directly from argv and later
41040b57cec5SDimitry Andric   // re-parsed to construct this job; claim any possible color diagnostic here
41050b57cec5SDimitry Andric   // to avoid warn_drv_unused_argument and diagnose bad
41060b57cec5SDimitry Andric   // OPT_fdiagnostics_color_EQ values.
410781ad6265SDimitry Andric   Args.getLastArg(options::OPT_fcolor_diagnostics,
410881ad6265SDimitry Andric                   options::OPT_fno_color_diagnostics);
410981ad6265SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
41100b57cec5SDimitry Andric     StringRef Value(A->getValue());
41110b57cec5SDimitry Andric     if (Value != "always" && Value != "never" && Value != "auto")
411281ad6265SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
411381ad6265SDimitry Andric           << Value << A->getOption().getName();
41140b57cec5SDimitry Andric   }
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric   if (D.getDiags().getDiagnosticOptions().ShowColors)
41170b57cec5SDimitry Andric     CmdArgs.push_back("-fcolor-diagnostics");
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fansi_escape_codes))
41200b57cec5SDimitry Andric     CmdArgs.push_back("-fansi-escape-codes");
41210b57cec5SDimitry Andric 
412281ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
412381ad6265SDimitry Andric                      options::OPT_fno_show_source_location);
41240b57cec5SDimitry Andric 
412506c3fb27SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
412606c3fb27SDimitry Andric                      options::OPT_fno_diagnostics_show_line_numbers);
412706c3fb27SDimitry Andric 
41280b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
41290b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-absolute-paths");
41300b57cec5SDimitry Andric 
41310b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
41320b57cec5SDimitry Andric                     ColumnDefault))
41330b57cec5SDimitry Andric     CmdArgs.push_back("-fno-show-column");
41340b57cec5SDimitry Andric 
413581ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
413681ad6265SDimitry Andric                      options::OPT_fno_spell_checking);
41370b57cec5SDimitry Andric }
41380b57cec5SDimitry Andric 
4139fcaf7f86SDimitry Andric DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
41400b57cec5SDimitry Andric                                             const ArgList &Args, Arg *&Arg) {
4141e8d8bef9SDimitry Andric   Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4142e8d8bef9SDimitry Andric                         options::OPT_gno_split_dwarf);
4143e8d8bef9SDimitry Andric   if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
41440b57cec5SDimitry Andric     return DwarfFissionKind::None;
41450b57cec5SDimitry Andric 
41460b57cec5SDimitry Andric   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
41470b57cec5SDimitry Andric     return DwarfFissionKind::Split;
41480b57cec5SDimitry Andric 
41490b57cec5SDimitry Andric   StringRef Value = Arg->getValue();
41500b57cec5SDimitry Andric   if (Value == "split")
41510b57cec5SDimitry Andric     return DwarfFissionKind::Split;
41520b57cec5SDimitry Andric   if (Value == "single")
41530b57cec5SDimitry Andric     return DwarfFissionKind::Single;
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric   D.Diag(diag::err_drv_unsupported_option_argument)
4156bdd1243dSDimitry Andric       << Arg->getSpelling() << Arg->getValue();
41570b57cec5SDimitry Andric   return DwarfFissionKind::None;
41580b57cec5SDimitry Andric }
41590b57cec5SDimitry Andric 
4160fe6060f1SDimitry Andric static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4161fe6060f1SDimitry Andric                               const ArgList &Args, ArgStringList &CmdArgs,
4162fe6060f1SDimitry Andric                               unsigned DwarfVersion) {
4163fe6060f1SDimitry Andric   auto *DwarfFormatArg =
4164fe6060f1SDimitry Andric       Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4165fe6060f1SDimitry Andric   if (!DwarfFormatArg)
4166fe6060f1SDimitry Andric     return;
4167fe6060f1SDimitry Andric 
4168fe6060f1SDimitry Andric   if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4169fe6060f1SDimitry Andric     if (DwarfVersion < 3)
4170fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4171fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4172fe6060f1SDimitry Andric     else if (!T.isArch64Bit())
4173fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4174fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4175fe6060f1SDimitry Andric     else if (!T.isOSBinFormatELF())
4176fe6060f1SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
4177fe6060f1SDimitry Andric           << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4178fe6060f1SDimitry Andric   }
4179fe6060f1SDimitry Andric 
4180fe6060f1SDimitry Andric   DwarfFormatArg->render(Args, CmdArgs);
4181fe6060f1SDimitry Andric }
4182fe6060f1SDimitry Andric 
418306c3fb27SDimitry Andric static void
418406c3fb27SDimitry Andric renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
41855f757f3fSDimitry Andric                    const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
41865f757f3fSDimitry Andric                    const InputInfo &Output,
418706c3fb27SDimitry Andric                    llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
41880b57cec5SDimitry Andric                    DwarfFissionKind &DwarfFission) {
41890b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
41900b57cec5SDimitry Andric                    options::OPT_fno_debug_info_for_profiling, false) &&
41910b57cec5SDimitry Andric       checkDebugInfoOption(
41920b57cec5SDimitry Andric           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
41930b57cec5SDimitry Andric     CmdArgs.push_back("-fdebug-info-for-profiling");
41940b57cec5SDimitry Andric 
41950b57cec5SDimitry Andric   // The 'g' groups options involve a somewhat intricate sequence of decisions
41960b57cec5SDimitry Andric   // about what to pass from the driver to the frontend, but by the time they
41970b57cec5SDimitry Andric   // reach cc1 they've been factored into three well-defined orthogonal choices:
41980b57cec5SDimitry Andric   //  * what level of debug info to generate
41990b57cec5SDimitry Andric   //  * what dwarf version to write
42000b57cec5SDimitry Andric   //  * what debugger tuning to use
42010b57cec5SDimitry Andric   // This avoids having to monkey around further in cc1 other than to disable
42020b57cec5SDimitry Andric   // codeview if not running in a Windows environment. Perhaps even that
42030b57cec5SDimitry Andric   // decision should be made in the driver as well though.
42040b57cec5SDimitry Andric   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
42050b57cec5SDimitry Andric 
42060b57cec5SDimitry Andric   bool SplitDWARFInlining =
42070b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4208480093f4SDimitry Andric                    options::OPT_fno_split_dwarf_inlining, false);
42090b57cec5SDimitry Andric 
4210e8d8bef9SDimitry Andric   // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4211e8d8bef9SDimitry Andric   // object file generation and no IR generation, -gN should not be needed. So
4212e8d8bef9SDimitry Andric   // allow -gsplit-dwarf with either -gN or IR input.
4213e8d8bef9SDimitry Andric   if (IRInput || Args.hasArg(options::OPT_g_Group)) {
42140b57cec5SDimitry Andric     Arg *SplitDWARFArg;
42150b57cec5SDimitry Andric     DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
42160b57cec5SDimitry Andric     if (DwarfFission != DwarfFissionKind::None &&
42170b57cec5SDimitry Andric         !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
42180b57cec5SDimitry Andric       DwarfFission = DwarfFissionKind::None;
42190b57cec5SDimitry Andric       SplitDWARFInlining = false;
42200b57cec5SDimitry Andric     }
4221e8d8bef9SDimitry Andric   }
4222e8d8bef9SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
422306c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
42240b57cec5SDimitry Andric 
42250b57cec5SDimitry Andric     // If the last option explicitly specified a debug-info level, use it.
42260b57cec5SDimitry Andric     if (checkDebugInfoOption(A, Args, D, TC) &&
42270b57cec5SDimitry Andric         A->getOption().matches(options::OPT_gN_Group)) {
422806c3fb27SDimitry Andric       DebugInfoKind = debugLevelToInfoKind(*A);
42290b57cec5SDimitry Andric       // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
42300b57cec5SDimitry Andric       // complicated if you've disabled inline info in the skeleton CUs
42310b57cec5SDimitry Andric       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
42320b57cec5SDimitry Andric       // line-tables-only, so let those compose naturally in that case.
423306c3fb27SDimitry Andric       if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
423406c3fb27SDimitry Andric           DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
423506c3fb27SDimitry Andric           (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
42360b57cec5SDimitry Andric            SplitDWARFInlining))
42370b57cec5SDimitry Andric         DwarfFission = DwarfFissionKind::None;
42380b57cec5SDimitry Andric     }
42390b57cec5SDimitry Andric   }
42400b57cec5SDimitry Andric 
42410b57cec5SDimitry Andric   // If a debugger tuning argument appeared, remember it.
4242bdd1243dSDimitry Andric   bool HasDebuggerTuning = false;
42430b57cec5SDimitry Andric   if (const Arg *A =
42440b57cec5SDimitry Andric           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4245bdd1243dSDimitry Andric     HasDebuggerTuning = true;
42460b57cec5SDimitry Andric     if (checkDebugInfoOption(A, Args, D, TC)) {
42470b57cec5SDimitry Andric       if (A->getOption().matches(options::OPT_glldb))
42480b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::LLDB;
42490b57cec5SDimitry Andric       else if (A->getOption().matches(options::OPT_gsce))
42500b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::SCE;
4251fe6060f1SDimitry Andric       else if (A->getOption().matches(options::OPT_gdbx))
4252fe6060f1SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::DBX;
42530b57cec5SDimitry Andric       else
42540b57cec5SDimitry Andric         DebuggerTuning = llvm::DebuggerKind::GDB;
42550b57cec5SDimitry Andric     }
42560b57cec5SDimitry Andric   }
42570b57cec5SDimitry Andric 
42580b57cec5SDimitry Andric   // If a -gdwarf argument appeared, remember it.
4259480093f4SDimitry Andric   bool EmitDwarf = false;
4260bdd1243dSDimitry Andric   if (const Arg *A = getDwarfNArg(Args))
4261bdd1243dSDimitry Andric     EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
42620b57cec5SDimitry Andric 
42635f757f3fSDimitry Andric   bool EmitCodeView = false;
4264bdd1243dSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4265bdd1243dSDimitry Andric     EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
42660b57cec5SDimitry Andric 
42670b57cec5SDimitry Andric   // If the user asked for debug info but did not explicitly specify -gcodeview
42680b57cec5SDimitry Andric   // or -gdwarf, ask the toolchain for the default format.
4269480093f4SDimitry Andric   if (!EmitCodeView && !EmitDwarf &&
427006c3fb27SDimitry Andric       DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
42710b57cec5SDimitry Andric     switch (TC.getDefaultDebugFormat()) {
427206c3fb27SDimitry Andric     case llvm::codegenoptions::DIF_CodeView:
42730b57cec5SDimitry Andric       EmitCodeView = true;
42740b57cec5SDimitry Andric       break;
427506c3fb27SDimitry Andric     case llvm::codegenoptions::DIF_DWARF:
4276480093f4SDimitry Andric       EmitDwarf = true;
42770b57cec5SDimitry Andric       break;
42780b57cec5SDimitry Andric     }
42790b57cec5SDimitry Andric   }
42800b57cec5SDimitry Andric 
4281e8d8bef9SDimitry Andric   unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4282e8d8bef9SDimitry Andric   unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4283e8d8bef9SDimitry Andric                                       // be lower than what the user wanted.
4284480093f4SDimitry Andric   if (EmitDwarf) {
4285bdd1243dSDimitry Andric     RequestedDWARFVersion = getDwarfVersion(TC, Args);
4286e8d8bef9SDimitry Andric     // Clamp effective DWARF version to the max supported by the toolchain.
4287e8d8bef9SDimitry Andric     EffectiveDWARFVersion =
4288e8d8bef9SDimitry Andric         std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4289bdd1243dSDimitry Andric   } else {
4290bdd1243dSDimitry Andric     Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4291480093f4SDimitry Andric   }
4292480093f4SDimitry Andric 
42930b57cec5SDimitry Andric   // -gline-directives-only supported only for the DWARF debug info.
4294e8d8bef9SDimitry Andric   if (RequestedDWARFVersion == 0 &&
429506c3fb27SDimitry Andric       DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
429606c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
42970b57cec5SDimitry Andric 
4298fe6060f1SDimitry Andric   // strict DWARF is set to false by default. But for DBX, we need it to be set
4299fe6060f1SDimitry Andric   // as true by default.
4300fe6060f1SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4301fe6060f1SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
4302fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4303fe6060f1SDimitry Andric                    DebuggerTuning == llvm::DebuggerKind::DBX))
4304fe6060f1SDimitry Andric     CmdArgs.push_back("-gstrict-dwarf");
4305fe6060f1SDimitry Andric 
43060b57cec5SDimitry Andric   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
43070b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_g_flags_Group);
43080b57cec5SDimitry Andric 
43090b57cec5SDimitry Andric   // Column info is included by default for everything except SCE and
43100b57cec5SDimitry Andric   // CodeView. Clang doesn't track end columns, just starting columns, which,
43110b57cec5SDimitry Andric   // in theory, is fine for CodeView (and PDB).  In practice, however, the
4312fe6060f1SDimitry Andric   // Microsoft debuggers don't handle missing end columns well, and the AIX
4313fe6060f1SDimitry Andric   // debugger DBX also doesn't handle the columns well, so it's better not to
4314fe6060f1SDimitry Andric   // include any column info.
43150b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
43160b57cec5SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
43175ffd83dbSDimitry Andric   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4318fe6060f1SDimitry Andric                     !EmitCodeView &&
4319fe6060f1SDimitry Andric                         (DebuggerTuning != llvm::DebuggerKind::SCE &&
4320fe6060f1SDimitry Andric                          DebuggerTuning != llvm::DebuggerKind::DBX)))
43215ffd83dbSDimitry Andric     CmdArgs.push_back("-gno-column-info");
43220b57cec5SDimitry Andric 
43230b57cec5SDimitry Andric   // FIXME: Move backend command line options to the module.
4324bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4325bdd1243dSDimitry Andric     // If -gline-tables-only or -gline-directives-only is the last option it
4326bdd1243dSDimitry Andric     // wins.
4327bdd1243dSDimitry Andric     if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4328bdd1243dSDimitry Andric                              TC)) {
432906c3fb27SDimitry Andric       if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
433006c3fb27SDimitry Andric           DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
433106c3fb27SDimitry Andric         DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
43320b57cec5SDimitry Andric         CmdArgs.push_back("-dwarf-ext-refs");
43330b57cec5SDimitry Andric         CmdArgs.push_back("-fmodule-format=obj");
43340b57cec5SDimitry Andric       }
43350b57cec5SDimitry Andric     }
4336bdd1243dSDimitry Andric   }
43370b57cec5SDimitry Andric 
4338fe6060f1SDimitry Andric   if (T.isOSBinFormatELF() && SplitDWARFInlining)
4339fe6060f1SDimitry Andric     CmdArgs.push_back("-fsplit-dwarf-inlining");
43400b57cec5SDimitry Andric 
43410b57cec5SDimitry Andric   // After we've dealt with all combinations of things that could
43420b57cec5SDimitry Andric   // make DebugInfoKind be other than None or DebugLineTablesOnly,
43430b57cec5SDimitry Andric   // figure out if we need to "upgrade" it to standalone debug info.
43440b57cec5SDimitry Andric   // We parse these two '-f' options whether or not they will be used,
43450b57cec5SDimitry Andric   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
43460b57cec5SDimitry Andric   bool NeedFullDebug = Args.hasFlag(
43470b57cec5SDimitry Andric       options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
43480b57cec5SDimitry Andric       DebuggerTuning == llvm::DebuggerKind::LLDB ||
43490b57cec5SDimitry Andric           TC.GetDefaultStandaloneDebug());
43500b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
43510b57cec5SDimitry Andric     (void)checkDebugInfoOption(A, Args, D, TC);
4352e8d8bef9SDimitry Andric 
435306c3fb27SDimitry Andric   if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
435406c3fb27SDimitry Andric       DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4355e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4356e8d8bef9SDimitry Andric                      options::OPT_feliminate_unused_debug_types, false))
435706c3fb27SDimitry Andric       DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4358e8d8bef9SDimitry Andric     else if (NeedFullDebug)
435906c3fb27SDimitry Andric       DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4360e8d8bef9SDimitry Andric   }
43610b57cec5SDimitry Andric 
43620b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
43630b57cec5SDimitry Andric                    false)) {
43640b57cec5SDimitry Andric     // Source embedding is a vendor extension to DWARF v5. By now we have
43650b57cec5SDimitry Andric     // checked if a DWARF version was stated explicitly, and have otherwise
43660b57cec5SDimitry Andric     // fallen back to the target default, so if this is still not at least 5
43670b57cec5SDimitry Andric     // we emit an error.
43680b57cec5SDimitry Andric     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4369e8d8bef9SDimitry Andric     if (RequestedDWARFVersion < 5)
43700b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
43710b57cec5SDimitry Andric           << A->getAsString(Args) << "-gdwarf-5";
4372e8d8bef9SDimitry Andric     else if (EffectiveDWARFVersion < 5)
4373e8d8bef9SDimitry Andric       // The toolchain has reduced allowed dwarf version, so we can't enable
4374e8d8bef9SDimitry Andric       // -gembed-source.
4375e8d8bef9SDimitry Andric       D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4376e8d8bef9SDimitry Andric           << A->getAsString(Args) << TC.getTripleString() << 5
4377e8d8bef9SDimitry Andric           << EffectiveDWARFVersion;
43780b57cec5SDimitry Andric     else if (checkDebugInfoOption(A, Args, D, TC))
43790b57cec5SDimitry Andric       CmdArgs.push_back("-gembed-source");
43800b57cec5SDimitry Andric   }
43810b57cec5SDimitry Andric 
43820b57cec5SDimitry Andric   if (EmitCodeView) {
43830b57cec5SDimitry Andric     CmdArgs.push_back("-gcodeview");
43840b57cec5SDimitry Andric 
4385bdd1243dSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4386bdd1243dSDimitry Andric                       options::OPT_gno_codeview_ghash);
4387bdd1243dSDimitry Andric 
4388bdd1243dSDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4389bdd1243dSDimitry Andric                        options::OPT_gno_codeview_command_line);
43900b57cec5SDimitry Andric   }
43910b57cec5SDimitry Andric 
4392bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4393bdd1243dSDimitry Andric                      options::OPT_gno_inline_line_tables);
4394480093f4SDimitry Andric 
4395480093f4SDimitry Andric   // When emitting remarks, we need at least debug lines in the output.
4396480093f4SDimitry Andric   if (willEmitRemarks(Args) &&
439706c3fb27SDimitry Andric       DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
439806c3fb27SDimitry Andric     DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4399480093f4SDimitry Andric 
4400e8d8bef9SDimitry Andric   // Adjust the debug info kind for the given toolchain.
4401e8d8bef9SDimitry Andric   TC.adjustDebugInfoKind(DebugInfoKind, Args);
4402e8d8bef9SDimitry Andric 
4403bdd1243dSDimitry Andric   // On AIX, the debugger tuning option can be omitted if it is not explicitly
4404bdd1243dSDimitry Andric   // set.
4405e8d8bef9SDimitry Andric   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4406bdd1243dSDimitry Andric                           T.isOSAIX() && !HasDebuggerTuning
4407bdd1243dSDimitry Andric                               ? llvm::DebuggerKind::Default
4408bdd1243dSDimitry Andric                               : DebuggerTuning);
44090b57cec5SDimitry Andric 
44100b57cec5SDimitry Andric   // -fdebug-macro turns on macro debug info generation.
44110b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
44120b57cec5SDimitry Andric                    false))
44130b57cec5SDimitry Andric     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
44140b57cec5SDimitry Andric                              D, TC))
44150b57cec5SDimitry Andric       CmdArgs.push_back("-debug-info-macro");
44160b57cec5SDimitry Andric 
44170b57cec5SDimitry Andric   // -ggnu-pubnames turns on gnu style pubnames in the backend.
44180b57cec5SDimitry Andric   const auto *PubnamesArg =
44190b57cec5SDimitry Andric       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
44200b57cec5SDimitry Andric                       options::OPT_gpubnames, options::OPT_gno_pubnames);
44210b57cec5SDimitry Andric   if (DwarfFission != DwarfFissionKind::None ||
44220b57cec5SDimitry Andric       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
44230b57cec5SDimitry Andric     if (!PubnamesArg ||
44240b57cec5SDimitry Andric         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
44250b57cec5SDimitry Andric          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
44260b57cec5SDimitry Andric       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
44270b57cec5SDimitry Andric                                            options::OPT_gpubnames)
44280b57cec5SDimitry Andric                             ? "-gpubnames"
44290b57cec5SDimitry Andric                             : "-ggnu-pubnames");
4430349cc55cSDimitry Andric   const auto *SimpleTemplateNamesArg =
443181ad6265SDimitry Andric       Args.getLastArg(options::OPT_gsimple_template_names,
443281ad6265SDimitry Andric                       options::OPT_gno_simple_template_names);
4433349cc55cSDimitry Andric   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4434349cc55cSDimitry Andric   if (SimpleTemplateNamesArg &&
4435349cc55cSDimitry Andric       checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4436349cc55cSDimitry Andric     const auto &Opt = SimpleTemplateNamesArg->getOption();
4437349cc55cSDimitry Andric     if (Opt.matches(options::OPT_gsimple_template_names)) {
4438349cc55cSDimitry Andric       ForwardTemplateParams = true;
4439349cc55cSDimitry Andric       CmdArgs.push_back("-gsimple-template-names=simple");
4440349cc55cSDimitry Andric     }
4441349cc55cSDimitry Andric   }
44420b57cec5SDimitry Andric 
4443bdd1243dSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4444bdd1243dSDimitry Andric     StringRef v = A->getValue();
4445bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
44460b57cec5SDimitry Andric   }
44470b57cec5SDimitry Andric 
4448bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4449bdd1243dSDimitry Andric                     options::OPT_fno_debug_ranges_base_address);
4450bdd1243dSDimitry Andric 
44510b57cec5SDimitry Andric   // -gdwarf-aranges turns on the emission of the aranges section in the
44520b57cec5SDimitry Andric   // backend.
44530b57cec5SDimitry Andric   // Always enabled for SCE tuning.
44540b57cec5SDimitry Andric   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
44550b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
44560b57cec5SDimitry Andric     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
44570b57cec5SDimitry Andric   if (NeedAranges) {
44580b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
44590b57cec5SDimitry Andric     CmdArgs.push_back("-generate-arange-section");
44600b57cec5SDimitry Andric   }
44610b57cec5SDimitry Andric 
4462bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4463bdd1243dSDimitry Andric                     options::OPT_fno_force_dwarf_frame);
4464480093f4SDimitry Andric 
44650b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdebug_types_section,
44660b57cec5SDimitry Andric                    options::OPT_fno_debug_types_section, false)) {
4467e8d8bef9SDimitry Andric     if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
44680b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
44690b57cec5SDimitry Andric           << Args.getLastArg(options::OPT_fdebug_types_section)
44700b57cec5SDimitry Andric                  ->getAsString(Args)
44710b57cec5SDimitry Andric           << T.getTriple();
44720b57cec5SDimitry Andric     } else if (checkDebugInfoOption(
44730b57cec5SDimitry Andric                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
44740b57cec5SDimitry Andric                    TC)) {
44750b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
44760b57cec5SDimitry Andric       CmdArgs.push_back("-generate-type-units");
44770b57cec5SDimitry Andric     }
44780b57cec5SDimitry Andric   }
44790b57cec5SDimitry Andric 
4480fe6060f1SDimitry Andric   // To avoid join/split of directory+filename, the integrated assembler prefers
4481fe6060f1SDimitry Andric   // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4482fe6060f1SDimitry Andric   // form before DWARF v5.
4483fe6060f1SDimitry Andric   if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4484fe6060f1SDimitry Andric                     options::OPT_fno_dwarf_directory_asm,
4485fe6060f1SDimitry Andric                     TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4486fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-dwarf-directory-asm");
4487fe6060f1SDimitry Andric 
44880b57cec5SDimitry Andric   // Decide how to render forward declarations of template instantiations.
44890b57cec5SDimitry Andric   // SCE wants full descriptions, others just get them in the name.
4490349cc55cSDimitry Andric   if (ForwardTemplateParams)
44910b57cec5SDimitry Andric     CmdArgs.push_back("-debug-forward-template-params");
44920b57cec5SDimitry Andric 
44930b57cec5SDimitry Andric   // Do we need to explicitly import anonymous namespaces into the parent
44940b57cec5SDimitry Andric   // scope?
44950b57cec5SDimitry Andric   if (DebuggerTuning == llvm::DebuggerKind::SCE)
44960b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-explicit-import");
44970b57cec5SDimitry Andric 
4498fe6060f1SDimitry Andric   renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
44990b57cec5SDimitry Andric   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
45005f757f3fSDimitry Andric 
45015f757f3fSDimitry Andric   // This controls whether or not we perform JustMyCode instrumentation.
45025f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
45035f757f3fSDimitry Andric     if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
45045f757f3fSDimitry Andric       if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
45055f757f3fSDimitry Andric         CmdArgs.push_back("-fjmc");
45065f757f3fSDimitry Andric       else if (D.IsCLMode())
45075f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
45085f757f3fSDimitry Andric                                                              << "'/Zi', '/Z7'";
45095f757f3fSDimitry Andric       else
45105f757f3fSDimitry Andric         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
45115f757f3fSDimitry Andric                                                              << "-g";
45125f757f3fSDimitry Andric     } else {
45135f757f3fSDimitry Andric       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
45145f757f3fSDimitry Andric     }
45155f757f3fSDimitry Andric   }
45165f757f3fSDimitry Andric 
45175f757f3fSDimitry Andric   // Add in -fdebug-compilation-dir if necessary.
45185f757f3fSDimitry Andric   const char *DebugCompilationDir =
45195f757f3fSDimitry Andric       addDebugCompDirArg(Args, CmdArgs, D.getVFS());
45205f757f3fSDimitry Andric 
45215f757f3fSDimitry Andric   addDebugPrefixMapArg(D, TC, Args, CmdArgs);
45225f757f3fSDimitry Andric 
45235f757f3fSDimitry Andric   // Add the output path to the object file for CodeView debug infos.
45245f757f3fSDimitry Andric   if (EmitCodeView && Output.isFilename())
45255f757f3fSDimitry Andric     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
45265f757f3fSDimitry Andric                        Output.getFilename());
45270b57cec5SDimitry Andric }
45280b57cec5SDimitry Andric 
4529bdd1243dSDimitry Andric static void ProcessVSRuntimeLibrary(const ArgList &Args,
4530bdd1243dSDimitry Andric                                     ArgStringList &CmdArgs) {
4531bdd1243dSDimitry Andric   unsigned RTOptionID = options::OPT__SLASH_MT;
4532bdd1243dSDimitry Andric 
4533bdd1243dSDimitry Andric   if (Args.hasArg(options::OPT__SLASH_LDd))
4534bdd1243dSDimitry Andric     // The /LDd option implies /MTd. The dependent lib part can be overridden,
4535bdd1243dSDimitry Andric     // but defining _DEBUG is sticky.
4536bdd1243dSDimitry Andric     RTOptionID = options::OPT__SLASH_MTd;
4537bdd1243dSDimitry Andric 
4538bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4539bdd1243dSDimitry Andric     RTOptionID = A->getOption().getID();
4540bdd1243dSDimitry Andric 
4541bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4542bdd1243dSDimitry Andric     RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4543bdd1243dSDimitry Andric                      .Case("static", options::OPT__SLASH_MT)
4544bdd1243dSDimitry Andric                      .Case("static_dbg", options::OPT__SLASH_MTd)
4545bdd1243dSDimitry Andric                      .Case("dll", options::OPT__SLASH_MD)
4546bdd1243dSDimitry Andric                      .Case("dll_dbg", options::OPT__SLASH_MDd)
4547bdd1243dSDimitry Andric                      .Default(options::OPT__SLASH_MT);
4548bdd1243dSDimitry Andric   }
4549bdd1243dSDimitry Andric 
4550bdd1243dSDimitry Andric   StringRef FlagForCRT;
4551bdd1243dSDimitry Andric   switch (RTOptionID) {
4552bdd1243dSDimitry Andric   case options::OPT__SLASH_MD:
4553bdd1243dSDimitry Andric     if (Args.hasArg(options::OPT__SLASH_LDd))
4554bdd1243dSDimitry Andric       CmdArgs.push_back("-D_DEBUG");
4555bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4556bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DLL");
4557bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=msvcrt";
4558bdd1243dSDimitry Andric     break;
4559bdd1243dSDimitry Andric   case options::OPT__SLASH_MDd:
4560bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DEBUG");
4561bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4562bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DLL");
4563bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=msvcrtd";
4564bdd1243dSDimitry Andric     break;
4565bdd1243dSDimitry Andric   case options::OPT__SLASH_MT:
4566bdd1243dSDimitry Andric     if (Args.hasArg(options::OPT__SLASH_LDd))
4567bdd1243dSDimitry Andric       CmdArgs.push_back("-D_DEBUG");
4568bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4569bdd1243dSDimitry Andric     CmdArgs.push_back("-flto-visibility-public-std");
4570bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=libcmt";
4571bdd1243dSDimitry Andric     break;
4572bdd1243dSDimitry Andric   case options::OPT__SLASH_MTd:
4573bdd1243dSDimitry Andric     CmdArgs.push_back("-D_DEBUG");
4574bdd1243dSDimitry Andric     CmdArgs.push_back("-D_MT");
4575bdd1243dSDimitry Andric     CmdArgs.push_back("-flto-visibility-public-std");
4576bdd1243dSDimitry Andric     FlagForCRT = "--dependent-lib=libcmtd";
4577bdd1243dSDimitry Andric     break;
4578bdd1243dSDimitry Andric   default:
4579bdd1243dSDimitry Andric     llvm_unreachable("Unexpected option ID.");
4580bdd1243dSDimitry Andric   }
4581bdd1243dSDimitry Andric 
4582bdd1243dSDimitry Andric   if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4583bdd1243dSDimitry Andric     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4584bdd1243dSDimitry Andric   } else {
4585bdd1243dSDimitry Andric     CmdArgs.push_back(FlagForCRT.data());
4586bdd1243dSDimitry Andric 
4587bdd1243dSDimitry Andric     // This provides POSIX compatibility (maps 'open' to '_open'), which most
4588bdd1243dSDimitry Andric     // users want.  The /Za flag to cl.exe turns this off, but it's not
4589bdd1243dSDimitry Andric     // implemented in clang.
4590bdd1243dSDimitry Andric     CmdArgs.push_back("--dependent-lib=oldnames");
4591bdd1243dSDimitry Andric   }
4592bdd1243dSDimitry Andric }
4593bdd1243dSDimitry Andric 
45940b57cec5SDimitry Andric void Clang::ConstructJob(Compilation &C, const JobAction &JA,
45950b57cec5SDimitry Andric                          const InputInfo &Output, const InputInfoList &Inputs,
45960b57cec5SDimitry Andric                          const ArgList &Args, const char *LinkingOutput) const {
45970b57cec5SDimitry Andric   const auto &TC = getToolChain();
45980b57cec5SDimitry Andric   const llvm::Triple &RawTriple = TC.getTriple();
45990b57cec5SDimitry Andric   const llvm::Triple &Triple = TC.getEffectiveTriple();
46000b57cec5SDimitry Andric   const std::string &TripleStr = Triple.getTriple();
46010b57cec5SDimitry Andric 
46020b57cec5SDimitry Andric   bool KernelOrKext =
46030b57cec5SDimitry Andric       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
46040b57cec5SDimitry Andric   const Driver &D = TC.getDriver();
46050b57cec5SDimitry Andric   ArgStringList CmdArgs;
46060b57cec5SDimitry Andric 
46070b57cec5SDimitry Andric   assert(Inputs.size() >= 1 && "Must have at least one input.");
46080b57cec5SDimitry Andric   // CUDA/HIP compilation may have multiple inputs (source file + results of
46090b57cec5SDimitry Andric   // device-side compilations). OpenMP device jobs also take the host IR as a
46100b57cec5SDimitry Andric   // second input. Module precompilation accepts a list of header files to
461181ad6265SDimitry Andric   // include as part of the module. API extraction accepts a list of header
461281ad6265SDimitry Andric   // files whose API information is emitted in the output. All other jobs are
461381ad6265SDimitry Andric   // expected to have exactly one input.
46140b57cec5SDimitry Andric   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4615fe6060f1SDimitry Andric   bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
46160b57cec5SDimitry Andric   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4617fe6060f1SDimitry Andric   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
46180b57cec5SDimitry Andric   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
461981ad6265SDimitry Andric   bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4620fe6060f1SDimitry Andric   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4621fe6060f1SDimitry Andric                                  JA.isDeviceOffloading(Action::OFK_Host));
462281ad6265SDimitry Andric   bool IsHostOffloadingAction =
4623bdd1243dSDimitry Andric       JA.isHostOffloading(Action::OFK_OpenMP) ||
462481ad6265SDimitry Andric       (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
462581ad6265SDimitry Andric        Args.hasFlag(options::OPT_offload_new_driver,
462681ad6265SDimitry Andric                     options::OPT_no_offload_new_driver, false));
462781ad6265SDimitry Andric 
4628753f127fSDimitry Andric   bool IsRDCMode =
4629753f127fSDimitry Andric       Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4630fe6060f1SDimitry Andric   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4631fe6060f1SDimitry Andric   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
46320b57cec5SDimitry Andric 
463381ad6265SDimitry Andric   // Extract API doesn't have a main input file, so invent a fake one as a
463481ad6265SDimitry Andric   // placeholder.
463581ad6265SDimitry Andric   InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
463681ad6265SDimitry Andric                                        "extract-api");
463781ad6265SDimitry Andric 
4638bdd1243dSDimitry Andric   const InputInfo &Input =
4639bdd1243dSDimitry Andric       IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
46400b57cec5SDimitry Andric 
464181ad6265SDimitry Andric   InputInfoList ExtractAPIInputs;
464281ad6265SDimitry Andric   InputInfoList HostOffloadingInputs;
46430b57cec5SDimitry Andric   const InputInfo *CudaDeviceInput = nullptr;
46440b57cec5SDimitry Andric   const InputInfo *OpenMPDeviceInput = nullptr;
46450b57cec5SDimitry Andric   for (const InputInfo &I : Inputs) {
4646bdd1243dSDimitry Andric     if (&I == &Input || I.getType() == types::TY_Nothing) {
4647bdd1243dSDimitry Andric       // This is the primary input or contains nothing.
464881ad6265SDimitry Andric     } else if (IsExtractAPI) {
464981ad6265SDimitry Andric       auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
465081ad6265SDimitry Andric       if (I.getType() != ExpectedInputType) {
465181ad6265SDimitry Andric         D.Diag(diag::err_drv_extract_api_wrong_kind)
465281ad6265SDimitry Andric             << I.getFilename() << types::getTypeName(I.getType())
465381ad6265SDimitry Andric             << types::getTypeName(ExpectedInputType);
465481ad6265SDimitry Andric       }
465581ad6265SDimitry Andric       ExtractAPIInputs.push_back(I);
465681ad6265SDimitry Andric     } else if (IsHostOffloadingAction) {
465781ad6265SDimitry Andric       HostOffloadingInputs.push_back(I);
46580b57cec5SDimitry Andric     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
46590b57cec5SDimitry Andric       CudaDeviceInput = &I;
46600b57cec5SDimitry Andric     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
46610b57cec5SDimitry Andric       OpenMPDeviceInput = &I;
46620b57cec5SDimitry Andric     } else {
46630b57cec5SDimitry Andric       llvm_unreachable("unexpectedly given multiple inputs");
46640b57cec5SDimitry Andric     }
46650b57cec5SDimitry Andric   }
46660b57cec5SDimitry Andric 
46675ffd83dbSDimitry Andric   const llvm::Triple *AuxTriple =
46685ffd83dbSDimitry Andric       (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
46690b57cec5SDimitry Andric   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
46700b57cec5SDimitry Andric   bool IsIAMCU = RawTriple.isOSIAMCU();
46710b57cec5SDimitry Andric 
46720b57cec5SDimitry Andric   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
46730b57cec5SDimitry Andric   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
46740b57cec5SDimitry Andric   // Windows), we need to pass Windows-specific flags to cc1.
46750b57cec5SDimitry Andric   if (IsCuda || IsHIP)
46760b57cec5SDimitry Andric     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
46770b57cec5SDimitry Andric 
46780b57cec5SDimitry Andric   // C++ is not supported for IAMCU.
46790b57cec5SDimitry Andric   if (IsIAMCU && types::isCXX(Input.getType()))
46800b57cec5SDimitry Andric     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
46810b57cec5SDimitry Andric 
46820b57cec5SDimitry Andric   // Invoke ourselves in -cc1 mode.
46830b57cec5SDimitry Andric   //
46840b57cec5SDimitry Andric   // FIXME: Implement custom jobs for internal actions.
46850b57cec5SDimitry Andric   CmdArgs.push_back("-cc1");
46860b57cec5SDimitry Andric 
46870b57cec5SDimitry Andric   // Add the "effective" target triple.
46880b57cec5SDimitry Andric   CmdArgs.push_back("-triple");
46890b57cec5SDimitry Andric   CmdArgs.push_back(Args.MakeArgString(TripleStr));
46900b57cec5SDimitry Andric 
46910b57cec5SDimitry Andric   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
46920b57cec5SDimitry Andric     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
46930b57cec5SDimitry Andric     Args.ClaimAllArgs(options::OPT_MJ);
4694a7dea167SDimitry Andric   } else if (const Arg *GenCDBFragment =
4695a7dea167SDimitry Andric                  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4696a7dea167SDimitry Andric     DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4697a7dea167SDimitry Andric                                          TripleStr, Output, Input, Args);
4698a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
46990b57cec5SDimitry Andric   }
47000b57cec5SDimitry Andric 
47010b57cec5SDimitry Andric   if (IsCuda || IsHIP) {
47020b57cec5SDimitry Andric     // We have to pass the triple of the host if compiling for a CUDA/HIP device
47030b57cec5SDimitry Andric     // and vice-versa.
47040b57cec5SDimitry Andric     std::string NormalizedTriple;
47050b57cec5SDimitry Andric     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
47060b57cec5SDimitry Andric         JA.isDeviceOffloading(Action::OFK_HIP))
47070b57cec5SDimitry Andric       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
47080b57cec5SDimitry Andric                              ->getTriple()
47090b57cec5SDimitry Andric                              .normalize();
47100b57cec5SDimitry Andric     else {
47110b57cec5SDimitry Andric       // Host-side compilation.
47120b57cec5SDimitry Andric       NormalizedTriple =
47130b57cec5SDimitry Andric           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
47140b57cec5SDimitry Andric                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
47150b57cec5SDimitry Andric               ->getTriple()
47160b57cec5SDimitry Andric               .normalize();
47170b57cec5SDimitry Andric       if (IsCuda) {
47180b57cec5SDimitry Andric         // We need to figure out which CUDA version we're compiling for, as that
47190b57cec5SDimitry Andric         // determines how we load and launch GPU kernels.
47200b57cec5SDimitry Andric         auto *CTC = static_cast<const toolchains::CudaToolChain *>(
47210b57cec5SDimitry Andric             C.getSingleOffloadToolChain<Action::OFK_Cuda>());
47220b57cec5SDimitry Andric         assert(CTC && "Expected valid CUDA Toolchain.");
47230b57cec5SDimitry Andric         if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
47240b57cec5SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(
47250b57cec5SDimitry Andric               Twine("-target-sdk-version=") +
47260b57cec5SDimitry Andric               CudaVersionToString(CTC->CudaInstallation.version())));
472706c3fb27SDimitry Andric         // Unsized function arguments used for variadics were introduced in
472806c3fb27SDimitry Andric         // CUDA-9.0. We still do not support generating code that actually uses
472906c3fb27SDimitry Andric         // variadic arguments yet, but we do need to allow parsing them as
473006c3fb27SDimitry Andric         // recent CUDA headers rely on that.
473106c3fb27SDimitry Andric         // https://github.com/llvm/llvm-project/issues/58410
473206c3fb27SDimitry Andric         if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
473306c3fb27SDimitry Andric           CmdArgs.push_back("-fcuda-allow-variadic-functions");
47340b57cec5SDimitry Andric       }
47350b57cec5SDimitry Andric     }
47360b57cec5SDimitry Andric     CmdArgs.push_back("-aux-triple");
47370b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
473806c3fb27SDimitry Andric 
473906c3fb27SDimitry Andric     if (JA.isDeviceOffloading(Action::OFK_HIP) &&
474006c3fb27SDimitry Andric         getToolChain().getTriple().isAMDGPU()) {
474106c3fb27SDimitry Andric       // Device side compilation printf
474206c3fb27SDimitry Andric       if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
474306c3fb27SDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
474406c3fb27SDimitry Andric             "-mprintf-kind=" +
474506c3fb27SDimitry Andric             Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
474606c3fb27SDimitry Andric         // Force compiler error on invalid conversion specifiers
474706c3fb27SDimitry Andric         CmdArgs.push_back(
474806c3fb27SDimitry Andric             Args.MakeArgString("-Werror=format-invalid-specifier"));
47490b57cec5SDimitry Andric       }
475006c3fb27SDimitry Andric     }
475106c3fb27SDimitry Andric   }
475206c3fb27SDimitry Andric 
475306c3fb27SDimitry Andric   // Unconditionally claim the printf option now to avoid unused diagnostic.
475406c3fb27SDimitry Andric   if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
475506c3fb27SDimitry Andric     PF->claim();
47560b57cec5SDimitry Andric 
47575ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
47585ffd83dbSDimitry Andric     CmdArgs.push_back("-fsycl-is-device");
47595ffd83dbSDimitry Andric 
47605ffd83dbSDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
47615ffd83dbSDimitry Andric       A->render(Args, CmdArgs);
47625ffd83dbSDimitry Andric     } else {
4763fe6060f1SDimitry Andric       // Ensure the default version in SYCL mode is 2020.
4764fe6060f1SDimitry Andric       CmdArgs.push_back("-sycl-std=2020");
47655ffd83dbSDimitry Andric     }
47665ffd83dbSDimitry Andric   }
47675ffd83dbSDimitry Andric 
47680b57cec5SDimitry Andric   if (IsOpenMPDevice) {
47690b57cec5SDimitry Andric     // We have to pass the triple of the host if compiling for an OpenMP device.
47700b57cec5SDimitry Andric     std::string NormalizedTriple =
47710b57cec5SDimitry Andric         C.getSingleOffloadToolChain<Action::OFK_Host>()
47720b57cec5SDimitry Andric             ->getTriple()
47730b57cec5SDimitry Andric             .normalize();
47740b57cec5SDimitry Andric     CmdArgs.push_back("-aux-triple");
47750b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
47760b57cec5SDimitry Andric   }
47770b57cec5SDimitry Andric 
47780b57cec5SDimitry Andric   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
47790b57cec5SDimitry Andric                                Triple.getArch() == llvm::Triple::thumb)) {
47800b57cec5SDimitry Andric     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
47815ffd83dbSDimitry Andric     unsigned Version = 0;
47825ffd83dbSDimitry Andric     bool Failure =
47835ffd83dbSDimitry Andric         Triple.getArchName().substr(Offset).consumeInteger(10, Version);
47845ffd83dbSDimitry Andric     if (Failure || Version < 7)
47850b57cec5SDimitry Andric       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
47860b57cec5SDimitry Andric                                                 << TripleStr;
47870b57cec5SDimitry Andric   }
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric   // Push all default warning arguments that are specific to
47900b57cec5SDimitry Andric   // the given target.  These come before user provided warning options
47910b57cec5SDimitry Andric   // are provided.
47920b57cec5SDimitry Andric   TC.addClangWarningOptions(CmdArgs);
47930b57cec5SDimitry Andric 
4794fe6060f1SDimitry Andric   // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4795bdd1243dSDimitry Andric   if (Triple.isSPIR() || Triple.isSPIRV())
4796fe6060f1SDimitry Andric     CmdArgs.push_back("-Wspir-compat");
4797fe6060f1SDimitry Andric 
47980b57cec5SDimitry Andric   // Select the appropriate action.
47990b57cec5SDimitry Andric   RewriteKind rewriteKind = RK_None;
48000b57cec5SDimitry Andric 
480106c3fb27SDimitry Andric   bool UnifiedLTO = false;
480206c3fb27SDimitry Andric   if (IsUsingLTO) {
480306c3fb27SDimitry Andric     UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
48045f757f3fSDimitry Andric                               options::OPT_fno_unified_lto, Triple.isPS()) ||
48055f757f3fSDimitry Andric                  Args.hasFlag(options::OPT_ffat_lto_objects,
48065f757f3fSDimitry Andric                               options::OPT_fno_fat_lto_objects, false);
480706c3fb27SDimitry Andric     if (UnifiedLTO)
480806c3fb27SDimitry Andric       CmdArgs.push_back("-funified-lto");
480906c3fb27SDimitry Andric   }
481006c3fb27SDimitry Andric 
4811a7dea167SDimitry Andric   // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4812a7dea167SDimitry Andric   // it claims when not running an assembler. Otherwise, clang would emit
4813a7dea167SDimitry Andric   // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4814a7dea167SDimitry Andric   // flags while debugging something. That'd be somewhat inconvenient, and it's
4815a7dea167SDimitry Andric   // also inconsistent with most other flags -- we don't warn on
4816a7dea167SDimitry Andric   // -ffunction-sections not being used in -E mode either for example, even
4817a7dea167SDimitry Andric   // though it's not really used either.
4818a7dea167SDimitry Andric   if (!isa<AssembleJobAction>(JA)) {
4819a7dea167SDimitry Andric     // The args claimed here should match the args used in
4820a7dea167SDimitry Andric     // CollectArgsForIntegratedAssembler().
4821a7dea167SDimitry Andric     if (TC.useIntegratedAs()) {
4822a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mrelax_all);
4823a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mno_relax_all);
4824a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4825a7dea167SDimitry Andric       Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4826a7dea167SDimitry Andric       switch (C.getDefaultToolChain().getArch()) {
4827a7dea167SDimitry Andric       case llvm::Triple::arm:
4828a7dea167SDimitry Andric       case llvm::Triple::armeb:
4829a7dea167SDimitry Andric       case llvm::Triple::thumb:
4830a7dea167SDimitry Andric       case llvm::Triple::thumbeb:
4831a7dea167SDimitry Andric         Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4832a7dea167SDimitry Andric         break;
4833a7dea167SDimitry Andric       default:
4834a7dea167SDimitry Andric         break;
4835a7dea167SDimitry Andric       }
4836a7dea167SDimitry Andric     }
4837a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4838a7dea167SDimitry Andric     Args.ClaimAllArgs(options::OPT_Xassembler);
483981ad6265SDimitry Andric     Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4840a7dea167SDimitry Andric   }
4841a7dea167SDimitry Andric 
48420b57cec5SDimitry Andric   if (isa<AnalyzeJobAction>(JA)) {
48430b57cec5SDimitry Andric     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
48440b57cec5SDimitry Andric     CmdArgs.push_back("-analyze");
48450b57cec5SDimitry Andric   } else if (isa<MigrateJobAction>(JA)) {
48460b57cec5SDimitry Andric     CmdArgs.push_back("-migrate");
48470b57cec5SDimitry Andric   } else if (isa<PreprocessJobAction>(JA)) {
48480b57cec5SDimitry Andric     if (Output.getType() == types::TY_Dependencies)
48490b57cec5SDimitry Andric       CmdArgs.push_back("-Eonly");
48500b57cec5SDimitry Andric     else {
48510b57cec5SDimitry Andric       CmdArgs.push_back("-E");
48520b57cec5SDimitry Andric       if (Args.hasArg(options::OPT_rewrite_objc) &&
48530b57cec5SDimitry Andric           !Args.hasArg(options::OPT_g_Group))
48540b57cec5SDimitry Andric         CmdArgs.push_back("-P");
485581ad6265SDimitry Andric       else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
485681ad6265SDimitry Andric         CmdArgs.push_back("-fdirectives-only");
48570b57cec5SDimitry Andric     }
48580b57cec5SDimitry Andric   } else if (isa<AssembleJobAction>(JA)) {
48590b57cec5SDimitry Andric     CmdArgs.push_back("-emit-obj");
48600b57cec5SDimitry Andric 
48610b57cec5SDimitry Andric     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
48620b57cec5SDimitry Andric 
48630b57cec5SDimitry Andric     // Also ignore explicit -force_cpusubtype_ALL option.
48640b57cec5SDimitry Andric     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
48650b57cec5SDimitry Andric   } else if (isa<PrecompileJobAction>(JA)) {
48660b57cec5SDimitry Andric     if (JA.getType() == types::TY_Nothing)
48670b57cec5SDimitry Andric       CmdArgs.push_back("-fsyntax-only");
48680b57cec5SDimitry Andric     else if (JA.getType() == types::TY_ModuleFile)
4869bdd1243dSDimitry Andric       CmdArgs.push_back("-emit-module-interface");
487081ad6265SDimitry Andric     else if (JA.getType() == types::TY_HeaderUnit)
487181ad6265SDimitry Andric       CmdArgs.push_back("-emit-header-unit");
48720b57cec5SDimitry Andric     else
48730b57cec5SDimitry Andric       CmdArgs.push_back("-emit-pch");
48740b57cec5SDimitry Andric   } else if (isa<VerifyPCHJobAction>(JA)) {
48750b57cec5SDimitry Andric     CmdArgs.push_back("-verify-pch");
487681ad6265SDimitry Andric   } else if (isa<ExtractAPIJobAction>(JA)) {
487781ad6265SDimitry Andric     assert(JA.getType() == types::TY_API_INFO &&
487881ad6265SDimitry Andric            "Extract API actions must generate a API information.");
487981ad6265SDimitry Andric     CmdArgs.push_back("-extract-api");
488081ad6265SDimitry Andric     if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
488181ad6265SDimitry Andric       ProductNameArg->render(Args, CmdArgs);
4882bdd1243dSDimitry Andric     if (Arg *ExtractAPIIgnoresFileArg =
4883bdd1243dSDimitry Andric             Args.getLastArg(options::OPT_extract_api_ignores_EQ))
4884bdd1243dSDimitry Andric       ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
48850b57cec5SDimitry Andric   } else {
48860b57cec5SDimitry Andric     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
48870b57cec5SDimitry Andric            "Invalid action for clang tool.");
48880b57cec5SDimitry Andric     if (JA.getType() == types::TY_Nothing) {
48890b57cec5SDimitry Andric       CmdArgs.push_back("-fsyntax-only");
48900b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_LLVM_IR ||
48910b57cec5SDimitry Andric                JA.getType() == types::TY_LTO_IR) {
48920b57cec5SDimitry Andric       CmdArgs.push_back("-emit-llvm");
48930b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_LLVM_BC ||
48940b57cec5SDimitry Andric                JA.getType() == types::TY_LTO_BC) {
4895fe6060f1SDimitry Andric       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4896fe6060f1SDimitry Andric       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4897fe6060f1SDimitry Andric           Args.hasArg(options::OPT_emit_llvm)) {
4898fe6060f1SDimitry Andric         CmdArgs.push_back("-emit-llvm");
4899fe6060f1SDimitry Andric       } else {
49000b57cec5SDimitry Andric         CmdArgs.push_back("-emit-llvm-bc");
4901fe6060f1SDimitry Andric       }
4902a7dea167SDimitry Andric     } else if (JA.getType() == types::TY_IFS ||
4903a7dea167SDimitry Andric                JA.getType() == types::TY_IFS_CPP) {
4904a7dea167SDimitry Andric       StringRef ArgStr =
4905a7dea167SDimitry Andric           Args.hasArg(options::OPT_interface_stub_version_EQ)
4906a7dea167SDimitry Andric               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4907fe6060f1SDimitry Andric               : "ifs-v1";
49080b57cec5SDimitry Andric       CmdArgs.push_back("-emit-interface-stubs");
49090b57cec5SDimitry Andric       CmdArgs.push_back(
4910a7dea167SDimitry Andric           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
49110b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_PP_Asm) {
49120b57cec5SDimitry Andric       CmdArgs.push_back("-S");
49130b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_AST) {
49140b57cec5SDimitry Andric       CmdArgs.push_back("-emit-pch");
49150b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_ModuleFile) {
49160b57cec5SDimitry Andric       CmdArgs.push_back("-module-file-info");
49170b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_RewrittenObjC) {
49180b57cec5SDimitry Andric       CmdArgs.push_back("-rewrite-objc");
49190b57cec5SDimitry Andric       rewriteKind = RK_NonFragile;
49200b57cec5SDimitry Andric     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
49210b57cec5SDimitry Andric       CmdArgs.push_back("-rewrite-objc");
49220b57cec5SDimitry Andric       rewriteKind = RK_Fragile;
49230b57cec5SDimitry Andric     } else {
49240b57cec5SDimitry Andric       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
49250b57cec5SDimitry Andric     }
49260b57cec5SDimitry Andric 
49270b57cec5SDimitry Andric     // Preserve use-list order by default when emitting bitcode, so that
49280b57cec5SDimitry Andric     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
49290b57cec5SDimitry Andric     // same result as running passes here.  For LTO, we don't need to preserve
49300b57cec5SDimitry Andric     // the use-list order, since serialization to bitcode is part of the flow.
49310b57cec5SDimitry Andric     if (JA.getType() == types::TY_LLVM_BC)
49320b57cec5SDimitry Andric       CmdArgs.push_back("-emit-llvm-uselists");
49330b57cec5SDimitry Andric 
493481ad6265SDimitry Andric     if (IsUsingLTO) {
4935bdd1243dSDimitry Andric       if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
493681ad6265SDimitry Andric           !Args.hasFlag(options::OPT_offload_new_driver,
493781ad6265SDimitry Andric                         options::OPT_no_offload_new_driver, false) &&
493881ad6265SDimitry Andric           !Triple.isAMDGPU()) {
4939fe6060f1SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
4940fe6060f1SDimitry Andric             << Args.getLastArg(options::OPT_foffload_lto,
4941fe6060f1SDimitry Andric                                options::OPT_foffload_lto_EQ)
4942fe6060f1SDimitry Andric                    ->getAsString(Args)
4943fe6060f1SDimitry Andric             << Triple.getTriple();
4944bdd1243dSDimitry Andric       } else if (Triple.isNVPTX() && !IsRDCMode &&
4945bdd1243dSDimitry Andric                  JA.isDeviceOffloading(Action::OFK_Cuda)) {
4946bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
4947bdd1243dSDimitry Andric             << Args.getLastArg(options::OPT_foffload_lto,
4948bdd1243dSDimitry Andric                                options::OPT_foffload_lto_EQ)
4949bdd1243dSDimitry Andric                    ->getAsString(Args)
4950bdd1243dSDimitry Andric             << "-fno-gpu-rdc";
4951349cc55cSDimitry Andric       } else {
4952349cc55cSDimitry Andric         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4953349cc55cSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
4954349cc55cSDimitry Andric             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
495506c3fb27SDimitry Andric         // PS4 uses the legacy LTO API, which does not support some of the
495606c3fb27SDimitry Andric         // features enabled by -flto-unit.
495706c3fb27SDimitry Andric         if (!RawTriple.isPS4() ||
495806c3fb27SDimitry Andric             (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
4959349cc55cSDimitry Andric           CmdArgs.push_back("-flto-unit");
4960fe6060f1SDimitry Andric       }
49610b57cec5SDimitry Andric     }
49620b57cec5SDimitry Andric   }
49630b57cec5SDimitry Andric 
496406c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
496506c3fb27SDimitry Andric 
49660b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
49670b57cec5SDimitry Andric     if (!types::isLLVMIR(Input.getType()))
49680b57cec5SDimitry Andric       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
49690b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
49700b57cec5SDimitry Andric   }
49710b57cec5SDimitry Andric 
49725f757f3fSDimitry Andric   if (Triple.isPPC())
49735f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
49745f757f3fSDimitry Andric                       options::OPT_mno_regnames);
49755f757f3fSDimitry Andric 
4976480093f4SDimitry Andric   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4977480093f4SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4978480093f4SDimitry Andric 
49790b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_save_temps_EQ))
49800b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
49810b57cec5SDimitry Andric 
4982e8d8bef9SDimitry Andric   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4983e8d8bef9SDimitry Andric                                      options::OPT_fmemory_profile_EQ,
4984e8d8bef9SDimitry Andric                                      options::OPT_fno_memory_profile);
4985e8d8bef9SDimitry Andric   if (MemProfArg &&
4986e8d8bef9SDimitry Andric       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4987e8d8bef9SDimitry Andric     MemProfArg->render(Args, CmdArgs);
4988e8d8bef9SDimitry Andric 
498906c3fb27SDimitry Andric   if (auto *MemProfUseArg =
499006c3fb27SDimitry Andric           Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
499106c3fb27SDimitry Andric     if (MemProfArg)
499206c3fb27SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
499306c3fb27SDimitry Andric           << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
499406c3fb27SDimitry Andric     if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
499506c3fb27SDimitry Andric                                             options::OPT_fprofile_generate_EQ))
499606c3fb27SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with)
499706c3fb27SDimitry Andric           << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
499806c3fb27SDimitry Andric     MemProfUseArg->render(Args, CmdArgs);
499906c3fb27SDimitry Andric   }
500006c3fb27SDimitry Andric 
50010b57cec5SDimitry Andric   // Embed-bitcode option.
50020b57cec5SDimitry Andric   // Only white-listed flags below are allowed to be embedded.
5003fe6060f1SDimitry Andric   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
50040b57cec5SDimitry Andric       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
50050b57cec5SDimitry Andric     // Add flags implied by -fembed-bitcode.
50060b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
50070b57cec5SDimitry Andric     // Disable all llvm IR level optimizations.
50080b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-passes");
50090b57cec5SDimitry Andric 
5010480093f4SDimitry Andric     // Render target options.
50110b57cec5SDimitry Andric     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
50120b57cec5SDimitry Andric 
50130b57cec5SDimitry Andric     // reject options that shouldn't be supported in bitcode
50140b57cec5SDimitry Andric     // also reject kernel/kext
5015349cc55cSDimitry Andric     static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
50160b57cec5SDimitry Andric         options::OPT_mkernel,
50170b57cec5SDimitry Andric         options::OPT_fapple_kext,
50180b57cec5SDimitry Andric         options::OPT_ffunction_sections,
50190b57cec5SDimitry Andric         options::OPT_fno_function_sections,
50200b57cec5SDimitry Andric         options::OPT_fdata_sections,
50210b57cec5SDimitry Andric         options::OPT_fno_data_sections,
50225ffd83dbSDimitry Andric         options::OPT_fbasic_block_sections_EQ,
50235ffd83dbSDimitry Andric         options::OPT_funique_internal_linkage_names,
50245ffd83dbSDimitry Andric         options::OPT_fno_unique_internal_linkage_names,
50250b57cec5SDimitry Andric         options::OPT_funique_section_names,
50260b57cec5SDimitry Andric         options::OPT_fno_unique_section_names,
50275ffd83dbSDimitry Andric         options::OPT_funique_basic_block_section_names,
50285ffd83dbSDimitry Andric         options::OPT_fno_unique_basic_block_section_names,
50290b57cec5SDimitry Andric         options::OPT_mrestrict_it,
50300b57cec5SDimitry Andric         options::OPT_mno_restrict_it,
50310b57cec5SDimitry Andric         options::OPT_mstackrealign,
50320b57cec5SDimitry Andric         options::OPT_mno_stackrealign,
50330b57cec5SDimitry Andric         options::OPT_mstack_alignment,
50340b57cec5SDimitry Andric         options::OPT_mcmodel_EQ,
50350b57cec5SDimitry Andric         options::OPT_mlong_calls,
50360b57cec5SDimitry Andric         options::OPT_mno_long_calls,
50370b57cec5SDimitry Andric         options::OPT_ggnu_pubnames,
50380b57cec5SDimitry Andric         options::OPT_gdwarf_aranges,
50390b57cec5SDimitry Andric         options::OPT_fdebug_types_section,
50400b57cec5SDimitry Andric         options::OPT_fno_debug_types_section,
50410b57cec5SDimitry Andric         options::OPT_fdwarf_directory_asm,
50420b57cec5SDimitry Andric         options::OPT_fno_dwarf_directory_asm,
50430b57cec5SDimitry Andric         options::OPT_mrelax_all,
50440b57cec5SDimitry Andric         options::OPT_mno_relax_all,
50450b57cec5SDimitry Andric         options::OPT_ftrap_function_EQ,
50460b57cec5SDimitry Andric         options::OPT_ffixed_r9,
50470b57cec5SDimitry Andric         options::OPT_mfix_cortex_a53_835769,
50480b57cec5SDimitry Andric         options::OPT_mno_fix_cortex_a53_835769,
50490b57cec5SDimitry Andric         options::OPT_ffixed_x18,
50500b57cec5SDimitry Andric         options::OPT_mglobal_merge,
50510b57cec5SDimitry Andric         options::OPT_mno_global_merge,
50520b57cec5SDimitry Andric         options::OPT_mred_zone,
50530b57cec5SDimitry Andric         options::OPT_mno_red_zone,
50540b57cec5SDimitry Andric         options::OPT_Wa_COMMA,
50550b57cec5SDimitry Andric         options::OPT_Xassembler,
50560b57cec5SDimitry Andric         options::OPT_mllvm,
50570b57cec5SDimitry Andric     };
50580b57cec5SDimitry Andric     for (const auto &A : Args)
5059349cc55cSDimitry Andric       if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
50600b57cec5SDimitry Andric         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
50610b57cec5SDimitry Andric 
50620b57cec5SDimitry Andric     // Render the CodeGen options that need to be passed.
506381ad6265SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
506481ad6265SDimitry Andric                        options::OPT_fno_optimize_sibling_calls);
50650b57cec5SDimitry Andric 
50660b57cec5SDimitry Andric     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
50675ffd83dbSDimitry Andric                                CmdArgs, JA);
50680b57cec5SDimitry Andric 
50690b57cec5SDimitry Andric     // Render ABI arguments
50700b57cec5SDimitry Andric     switch (TC.getArch()) {
50710b57cec5SDimitry Andric     default: break;
50720b57cec5SDimitry Andric     case llvm::Triple::arm:
50730b57cec5SDimitry Andric     case llvm::Triple::armeb:
50740b57cec5SDimitry Andric     case llvm::Triple::thumbeb:
5075349cc55cSDimitry Andric       RenderARMABI(D, Triple, Args, CmdArgs);
50760b57cec5SDimitry Andric       break;
50770b57cec5SDimitry Andric     case llvm::Triple::aarch64:
5078480093f4SDimitry Andric     case llvm::Triple::aarch64_32:
50790b57cec5SDimitry Andric     case llvm::Triple::aarch64_be:
50800b57cec5SDimitry Andric       RenderAArch64ABI(Triple, Args, CmdArgs);
50810b57cec5SDimitry Andric       break;
50820b57cec5SDimitry Andric     }
50830b57cec5SDimitry Andric 
50840b57cec5SDimitry Andric     // Optimization level for CodeGen.
50850b57cec5SDimitry Andric     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
50860b57cec5SDimitry Andric       if (A->getOption().matches(options::OPT_O4)) {
50870b57cec5SDimitry Andric         CmdArgs.push_back("-O3");
50880b57cec5SDimitry Andric         D.Diag(diag::warn_O4_is_O3);
50890b57cec5SDimitry Andric       } else {
50900b57cec5SDimitry Andric         A->render(Args, CmdArgs);
50910b57cec5SDimitry Andric       }
50920b57cec5SDimitry Andric     }
50930b57cec5SDimitry Andric 
50940b57cec5SDimitry Andric     // Input/Output file.
50950b57cec5SDimitry Andric     if (Output.getType() == types::TY_Dependencies) {
50960b57cec5SDimitry Andric       // Handled with other dependency code.
50970b57cec5SDimitry Andric     } else if (Output.isFilename()) {
50980b57cec5SDimitry Andric       CmdArgs.push_back("-o");
50990b57cec5SDimitry Andric       CmdArgs.push_back(Output.getFilename());
51000b57cec5SDimitry Andric     } else {
51010b57cec5SDimitry Andric       assert(Output.isNothing() && "Input output.");
51020b57cec5SDimitry Andric     }
51030b57cec5SDimitry Andric 
51040b57cec5SDimitry Andric     for (const auto &II : Inputs) {
51050b57cec5SDimitry Andric       addDashXForInput(Args, II, CmdArgs);
51060b57cec5SDimitry Andric       if (II.isFilename())
51070b57cec5SDimitry Andric         CmdArgs.push_back(II.getFilename());
51080b57cec5SDimitry Andric       else
51090b57cec5SDimitry Andric         II.getInputArg().renderAsInput(Args, CmdArgs);
51100b57cec5SDimitry Andric     }
51110b57cec5SDimitry Andric 
5112e8d8bef9SDimitry Andric     C.addCommand(std::make_unique<Command>(
5113e8d8bef9SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
511406c3fb27SDimitry Andric         CmdArgs, Inputs, Output, D.getPrependArg()));
51150b57cec5SDimitry Andric     return;
51160b57cec5SDimitry Andric   }
51170b57cec5SDimitry Andric 
5118fe6060f1SDimitry Andric   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
51190b57cec5SDimitry Andric     CmdArgs.push_back("-fembed-bitcode=marker");
51200b57cec5SDimitry Andric 
51210b57cec5SDimitry Andric   // We normally speed up the clang process a bit by skipping destructors at
51220b57cec5SDimitry Andric   // exit, but when we're generating diagnostics we can rely on some of the
51230b57cec5SDimitry Andric   // cleanup.
51240b57cec5SDimitry Andric   if (!C.isForDiagnostics())
51250b57cec5SDimitry Andric     CmdArgs.push_back("-disable-free");
5126349cc55cSDimitry Andric   CmdArgs.push_back("-clear-ast-before-backend");
51270b57cec5SDimitry Andric 
51280b57cec5SDimitry Andric #ifdef NDEBUG
51290b57cec5SDimitry Andric   const bool IsAssertBuild = false;
51300b57cec5SDimitry Andric #else
51310b57cec5SDimitry Andric   const bool IsAssertBuild = true;
51320b57cec5SDimitry Andric #endif
51330b57cec5SDimitry Andric 
51345f757f3fSDimitry Andric   // Disable the verification pass in asserts builds unless otherwise specified.
51355f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
51365f757f3fSDimitry Andric                    options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
51370b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-verifier");
51385f757f3fSDimitry Andric   }
51390b57cec5SDimitry Andric 
51400b57cec5SDimitry Andric   // Discard value names in assert builds unless otherwise specified.
51410b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdiscard_value_names,
514247395794SDimitry Andric                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
514347395794SDimitry Andric     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5144349cc55cSDimitry Andric         llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
514547395794SDimitry Andric           return types::isLLVMIR(II.getType());
5146349cc55cSDimitry Andric         })) {
514747395794SDimitry Andric       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
514847395794SDimitry Andric     }
51490b57cec5SDimitry Andric     CmdArgs.push_back("-discard-value-names");
515047395794SDimitry Andric   }
51510b57cec5SDimitry Andric 
51520b57cec5SDimitry Andric   // Set the main file name, so that debug info works even with
51530b57cec5SDimitry Andric   // -save-temps.
51540b57cec5SDimitry Andric   CmdArgs.push_back("-main-file-name");
51550b57cec5SDimitry Andric   CmdArgs.push_back(getBaseInputName(Args, Input));
51560b57cec5SDimitry Andric 
51570b57cec5SDimitry Andric   // Some flags which affect the language (via preprocessor
51580b57cec5SDimitry Andric   // defines).
51590b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_static))
51600b57cec5SDimitry Andric     CmdArgs.push_back("-static-define");
51610b57cec5SDimitry Andric 
51620b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_municode))
51630b57cec5SDimitry Andric     CmdArgs.push_back("-DUNICODE");
51640b57cec5SDimitry Andric 
51650b57cec5SDimitry Andric   if (isa<AnalyzeJobAction>(JA))
51660b57cec5SDimitry Andric     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
51670b57cec5SDimitry Andric 
5168a7dea167SDimitry Andric   if (isa<AnalyzeJobAction>(JA) ||
5169a7dea167SDimitry Andric       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5170a7dea167SDimitry Andric     CmdArgs.push_back("-setup-static-analyzer");
5171a7dea167SDimitry Andric 
51720b57cec5SDimitry Andric   // Enable compatilibily mode to avoid analyzer-config related errors.
51730b57cec5SDimitry Andric   // Since we can't access frontend flags through hasArg, let's manually iterate
51740b57cec5SDimitry Andric   // through them.
51750b57cec5SDimitry Andric   bool FoundAnalyzerConfig = false;
5176bdd1243dSDimitry Andric   for (auto *Arg : Args.filtered(options::OPT_Xclang))
51770b57cec5SDimitry Andric     if (StringRef(Arg->getValue()) == "-analyzer-config") {
51780b57cec5SDimitry Andric       FoundAnalyzerConfig = true;
51790b57cec5SDimitry Andric       break;
51800b57cec5SDimitry Andric     }
51810b57cec5SDimitry Andric   if (!FoundAnalyzerConfig)
5182bdd1243dSDimitry Andric     for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
51830b57cec5SDimitry Andric       if (StringRef(Arg->getValue()) == "-analyzer-config") {
51840b57cec5SDimitry Andric         FoundAnalyzerConfig = true;
51850b57cec5SDimitry Andric         break;
51860b57cec5SDimitry Andric       }
51870b57cec5SDimitry Andric   if (FoundAnalyzerConfig)
51880b57cec5SDimitry Andric     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
51890b57cec5SDimitry Andric 
51900b57cec5SDimitry Andric   CheckCodeGenerationOptions(D, Args);
51910b57cec5SDimitry Andric 
51920b57cec5SDimitry Andric   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
51930b57cec5SDimitry Andric   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
51940b57cec5SDimitry Andric   if (FunctionAlignment) {
51950b57cec5SDimitry Andric     CmdArgs.push_back("-function-alignment");
51960b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
51970b57cec5SDimitry Andric   }
51980b57cec5SDimitry Andric 
5199349cc55cSDimitry Andric   // We support -falign-loops=N where N is a power of 2. GCC supports more
5200349cc55cSDimitry Andric   // forms.
5201349cc55cSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5202349cc55cSDimitry Andric     unsigned Value = 0;
5203349cc55cSDimitry Andric     if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5204349cc55cSDimitry Andric       TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5205349cc55cSDimitry Andric           << A->getAsString(Args) << A->getValue();
5206349cc55cSDimitry Andric     else if (Value & (Value - 1))
5207349cc55cSDimitry Andric       TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5208349cc55cSDimitry Andric           << A->getAsString(Args) << A->getValue();
5209349cc55cSDimitry Andric     // Treat =0 as unspecified (use the target preference).
5210349cc55cSDimitry Andric     if (Value)
5211349cc55cSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5212349cc55cSDimitry Andric                                            Twine(std::min(Value, 65536u))));
5213349cc55cSDimitry Andric   }
5214349cc55cSDimitry Andric 
521506c3fb27SDimitry Andric   if (Triple.isOSzOS()) {
521606c3fb27SDimitry Andric     // On z/OS some of the system header feature macros need to
521706c3fb27SDimitry Andric     // be defined to enable most cross platform projects to build
521806c3fb27SDimitry Andric     // successfully.  Ths include the libc++ library.  A
521906c3fb27SDimitry Andric     // complicating factor is that users can define these
522006c3fb27SDimitry Andric     // macros to the same or different values.  We need to add
522106c3fb27SDimitry Andric     // the definition for these macros to the compilation command
522206c3fb27SDimitry Andric     // if the user hasn't already defined them.
522306c3fb27SDimitry Andric 
522406c3fb27SDimitry Andric     auto findMacroDefinition = [&](const std::string &Macro) {
522506c3fb27SDimitry Andric       auto MacroDefs = Args.getAllArgValues(options::OPT_D);
52265f757f3fSDimitry Andric       return llvm::any_of(MacroDefs, [&](const std::string &M) {
52275f757f3fSDimitry Andric         return M == Macro || M.find(Macro + '=') != std::string::npos;
52285f757f3fSDimitry Andric       });
522906c3fb27SDimitry Andric     };
523006c3fb27SDimitry Andric 
523106c3fb27SDimitry Andric     // _UNIX03_WITHDRAWN is required for libcxx & porting.
523206c3fb27SDimitry Andric     if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
523306c3fb27SDimitry Andric       CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
523406c3fb27SDimitry Andric     // _OPEN_DEFAULT is required for XL compat
523506c3fb27SDimitry Andric     if (!findMacroDefinition("_OPEN_DEFAULT"))
523606c3fb27SDimitry Andric       CmdArgs.push_back("-D_OPEN_DEFAULT");
523706c3fb27SDimitry Andric     if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
523806c3fb27SDimitry Andric       // _XOPEN_SOURCE=600 is required for libcxx.
523906c3fb27SDimitry Andric       if (!findMacroDefinition("_XOPEN_SOURCE"))
524006c3fb27SDimitry Andric         CmdArgs.push_back("-D_XOPEN_SOURCE=600");
524106c3fb27SDimitry Andric     }
524206c3fb27SDimitry Andric   }
524306c3fb27SDimitry Andric 
52440b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
52450b57cec5SDimitry Andric   unsigned PICLevel;
52460b57cec5SDimitry Andric   bool IsPIE;
52470b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5248bdd1243dSDimitry Andric   Arg *LastPICDataRelArg =
5249bdd1243dSDimitry Andric       Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5250bdd1243dSDimitry Andric                       options::OPT_mpic_data_is_text_relative);
5251bdd1243dSDimitry Andric   bool NoPICDataIsTextRelative = false;
5252bdd1243dSDimitry Andric   if (LastPICDataRelArg) {
5253bdd1243dSDimitry Andric     if (LastPICDataRelArg->getOption().matches(
5254bdd1243dSDimitry Andric             options::OPT_mno_pic_data_is_text_relative)) {
5255bdd1243dSDimitry Andric       NoPICDataIsTextRelative = true;
5256bdd1243dSDimitry Andric       if (!PICLevel)
5257bdd1243dSDimitry Andric         D.Diag(diag::err_drv_argument_only_allowed_with)
5258bdd1243dSDimitry Andric             << "-mno-pic-data-is-text-relative"
5259bdd1243dSDimitry Andric             << "-fpic/-fpie";
5260bdd1243dSDimitry Andric     }
5261bdd1243dSDimitry Andric     if (!Triple.isSystemZ())
5262bdd1243dSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5263bdd1243dSDimitry Andric           << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5264bdd1243dSDimitry Andric                                       : "-mpic-data-is-text-relative")
5265bdd1243dSDimitry Andric           << RawTriple.str();
5266bdd1243dSDimitry Andric   }
52670b57cec5SDimitry Andric 
52685ffd83dbSDimitry Andric   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
52695ffd83dbSDimitry Andric                 RelocationModel == llvm::Reloc::ROPI_RWPI;
52705ffd83dbSDimitry Andric   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
52715ffd83dbSDimitry Andric                 RelocationModel == llvm::Reloc::ROPI_RWPI;
52720b57cec5SDimitry Andric 
52735ffd83dbSDimitry Andric   if (Args.hasArg(options::OPT_mcmse) &&
52745ffd83dbSDimitry Andric       !Args.hasArg(options::OPT_fallow_unsupported)) {
52755ffd83dbSDimitry Andric     if (IsROPI)
52765ffd83dbSDimitry Andric       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
52775ffd83dbSDimitry Andric     if (IsRWPI)
52785ffd83dbSDimitry Andric       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
52795ffd83dbSDimitry Andric   }
52805ffd83dbSDimitry Andric 
52815ffd83dbSDimitry Andric   if (IsROPI && types::isCXX(Input.getType()) &&
52820b57cec5SDimitry Andric       !Args.hasArg(options::OPT_fallow_unsupported))
52830b57cec5SDimitry Andric     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
52840b57cec5SDimitry Andric 
52855ffd83dbSDimitry Andric   const char *RMName = RelocationModelName(RelocationModel);
52860b57cec5SDimitry Andric   if (RMName) {
52870b57cec5SDimitry Andric     CmdArgs.push_back("-mrelocation-model");
52880b57cec5SDimitry Andric     CmdArgs.push_back(RMName);
52890b57cec5SDimitry Andric   }
52900b57cec5SDimitry Andric   if (PICLevel > 0) {
52910b57cec5SDimitry Andric     CmdArgs.push_back("-pic-level");
52920b57cec5SDimitry Andric     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
52930b57cec5SDimitry Andric     if (IsPIE)
52940b57cec5SDimitry Andric       CmdArgs.push_back("-pic-is-pie");
5295bdd1243dSDimitry Andric     if (NoPICDataIsTextRelative)
5296bdd1243dSDimitry Andric       CmdArgs.push_back("-mcmodel=medium");
52970b57cec5SDimitry Andric   }
52980b57cec5SDimitry Andric 
52990b57cec5SDimitry Andric   if (RelocationModel == llvm::Reloc::ROPI ||
53000b57cec5SDimitry Andric       RelocationModel == llvm::Reloc::ROPI_RWPI)
53010b57cec5SDimitry Andric     CmdArgs.push_back("-fropi");
53020b57cec5SDimitry Andric   if (RelocationModel == llvm::Reloc::RWPI ||
53030b57cec5SDimitry Andric       RelocationModel == llvm::Reloc::ROPI_RWPI)
53040b57cec5SDimitry Andric     CmdArgs.push_back("-frwpi");
53050b57cec5SDimitry Andric 
53060b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
53070b57cec5SDimitry Andric     CmdArgs.push_back("-meabi");
53080b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
53090b57cec5SDimitry Andric   }
53100b57cec5SDimitry Andric 
5311e8d8bef9SDimitry Andric   // -fsemantic-interposition is forwarded to CC1: set the
5312e8d8bef9SDimitry Andric   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5313e8d8bef9SDimitry Andric   // make default visibility external linkage definitions dso_preemptable.
5314e8d8bef9SDimitry Andric   //
5315e8d8bef9SDimitry Andric   // -fno-semantic-interposition: if the target supports .Lfoo$local local
5316e8d8bef9SDimitry Andric   // aliases (make default visibility external linkage definitions dso_local).
5317e8d8bef9SDimitry Andric   // This is the CC1 default for ELF to match COFF/Mach-O.
5318e8d8bef9SDimitry Andric   //
5319e8d8bef9SDimitry Andric   // Otherwise use Clang's traditional behavior: like
5320e8d8bef9SDimitry Andric   // -fno-semantic-interposition but local aliases are not used. So references
5321e8d8bef9SDimitry Andric   // can be interposed if not optimized out.
5322e8d8bef9SDimitry Andric   if (Triple.isOSBinFormatELF()) {
5323e8d8bef9SDimitry Andric     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5324e8d8bef9SDimitry Andric                              options::OPT_fno_semantic_interposition);
5325e8d8bef9SDimitry Andric     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5326e8d8bef9SDimitry Andric       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5327fe6060f1SDimitry Andric       bool SupportsLocalAlias =
5328fe6060f1SDimitry Andric           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5329e8d8bef9SDimitry Andric       if (!A)
5330e8d8bef9SDimitry Andric         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5331e8d8bef9SDimitry Andric       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
53325ffd83dbSDimitry Andric         A->render(Args, CmdArgs);
5333e8d8bef9SDimitry Andric       else if (!SupportsLocalAlias)
5334e8d8bef9SDimitry Andric         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5335e8d8bef9SDimitry Andric     }
5336e8d8bef9SDimitry Andric   }
53375ffd83dbSDimitry Andric 
53385ffd83dbSDimitry Andric   {
53395ffd83dbSDimitry Andric     std::string Model;
53400b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
53410b57cec5SDimitry Andric       if (!TC.isThreadModelSupported(A->getValue()))
53420b57cec5SDimitry Andric         D.Diag(diag::err_drv_invalid_thread_model_for_target)
53430b57cec5SDimitry Andric             << A->getValue() << A->getAsString(Args);
53445ffd83dbSDimitry Andric       Model = A->getValue();
53455ffd83dbSDimitry Andric     } else
53465ffd83dbSDimitry Andric       Model = TC.getThreadModel();
53475ffd83dbSDimitry Andric     if (Model != "posix") {
53485ffd83dbSDimitry Andric       CmdArgs.push_back("-mthread-model");
53495ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Model));
53500b57cec5SDimitry Andric     }
53515ffd83dbSDimitry Andric   }
53520b57cec5SDimitry Andric 
5353bdd1243dSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5354bdd1243dSDimitry Andric     StringRef Name = A->getValue();
5355bdd1243dSDimitry Andric     if (Name == "SVML") {
5356bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::x86 &&
5357bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::x86_64)
5358bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5359bdd1243dSDimitry Andric             << Name << Triple.getArchName();
5360bdd1243dSDimitry Andric     } else if (Name == "LIBMVEC-X86") {
5361bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::x86 &&
5362bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::x86_64)
5363bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5364bdd1243dSDimitry Andric             << Name << Triple.getArchName();
536506c3fb27SDimitry Andric     } else if (Name == "SLEEF" || Name == "ArmPL") {
5366bdd1243dSDimitry Andric       if (Triple.getArch() != llvm::Triple::aarch64 &&
5367bdd1243dSDimitry Andric           Triple.getArch() != llvm::Triple::aarch64_be)
5368bdd1243dSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5369bdd1243dSDimitry Andric             << Name << Triple.getArchName();
5370bdd1243dSDimitry Andric     }
5371bdd1243dSDimitry Andric     A->render(Args, CmdArgs);
5372bdd1243dSDimitry Andric   }
53730b57cec5SDimitry Andric 
53740b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fmerge_all_constants,
53750b57cec5SDimitry Andric                    options::OPT_fno_merge_all_constants, false))
53760b57cec5SDimitry Andric     CmdArgs.push_back("-fmerge-all-constants");
53770b57cec5SDimitry Andric 
5378bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5379bdd1243dSDimitry Andric                      options::OPT_fno_delete_null_pointer_checks);
53800b57cec5SDimitry Andric 
53810b57cec5SDimitry Andric   // LLVM Code Generator Options.
53820b57cec5SDimitry Andric 
5383972a253aSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5384972a253aSDimitry Andric     if (!Triple.isOSAIX() || Triple.isPPC32())
5385972a253aSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5386972a253aSDimitry Andric         << A->getSpelling() << RawTriple.str();
5387972a253aSDimitry Andric     CmdArgs.push_back("-mabi=quadword-atomics");
5388972a253aSDimitry Andric   }
5389972a253aSDimitry Andric 
5390fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5391fe6060f1SDimitry Andric     // Emit the unsupported option error until the Clang's library integration
5392fe6060f1SDimitry Andric     // support for 128-bit long double is available for AIX.
5393fe6060f1SDimitry Andric     if (Triple.isOSAIX())
5394fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5395fe6060f1SDimitry Andric           << A->getSpelling() << RawTriple.str();
5396e8d8bef9SDimitry Andric   }
5397e8d8bef9SDimitry Andric 
53980b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
539906c3fb27SDimitry Andric     StringRef V = A->getValue(), V1 = V;
540006c3fb27SDimitry Andric     unsigned Size;
540106c3fb27SDimitry Andric     if (V1.consumeInteger(10, Size) || !V1.empty())
540206c3fb27SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
540306c3fb27SDimitry Andric           << V << A->getOption().getName();
5404fe6060f1SDimitry Andric     else
540506c3fb27SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
54060b57cec5SDimitry Andric   }
54070b57cec5SDimitry Andric 
540881ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
540981ad6265SDimitry Andric                      options::OPT_fno_jump_tables);
541081ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
541181ad6265SDimitry Andric                     options::OPT_fno_profile_sample_accurate);
541281ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
541381ad6265SDimitry Andric                      options::OPT_fno_preserve_as_comments);
54140b57cec5SDimitry Andric 
54150b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
54160b57cec5SDimitry Andric     CmdArgs.push_back("-mregparm");
54170b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
54180b57cec5SDimitry Andric   }
54190b57cec5SDimitry Andric 
5420e86cf8adSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5421e86cf8adSDimitry Andric                                options::OPT_msvr4_struct_return)) {
5422e8d8bef9SDimitry Andric     if (!TC.getTriple().isPPC32()) {
5423e86cf8adSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5424e86cf8adSDimitry Andric           << A->getSpelling() << RawTriple.str();
5425e86cf8adSDimitry Andric     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5426e86cf8adSDimitry Andric       CmdArgs.push_back("-maix-struct-return");
5427e86cf8adSDimitry Andric     } else {
5428e86cf8adSDimitry Andric       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5429e86cf8adSDimitry Andric       CmdArgs.push_back("-msvr4-struct-return");
5430e86cf8adSDimitry Andric     }
5431e86cf8adSDimitry Andric   }
5432e86cf8adSDimitry Andric 
54330b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
54340b57cec5SDimitry Andric                                options::OPT_freg_struct_return)) {
54350b57cec5SDimitry Andric     if (TC.getArch() != llvm::Triple::x86) {
54360b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
54370b57cec5SDimitry Andric           << A->getSpelling() << RawTriple.str();
54380b57cec5SDimitry Andric     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
54390b57cec5SDimitry Andric       CmdArgs.push_back("-fpcc-struct-return");
54400b57cec5SDimitry Andric     } else {
54410b57cec5SDimitry Andric       assert(A->getOption().matches(options::OPT_freg_struct_return));
54420b57cec5SDimitry Andric       CmdArgs.push_back("-freg-struct-return");
54430b57cec5SDimitry Andric     }
54440b57cec5SDimitry Andric   }
54450b57cec5SDimitry Andric 
54465f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
54475f757f3fSDimitry Andric     if (Triple.getArch() == llvm::Triple::m68k)
54485f757f3fSDimitry Andric       CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
54495f757f3fSDimitry Andric     else
54500b57cec5SDimitry Andric       CmdArgs.push_back("-fdefault-calling-conv=stdcall");
54515f757f3fSDimitry Andric   }
54520b57cec5SDimitry Andric 
54535ffd83dbSDimitry Andric   if (Args.hasArg(options::OPT_fenable_matrix)) {
54545ffd83dbSDimitry Andric     // enable-matrix is needed by both the LangOpts and by LLVM.
54555ffd83dbSDimitry Andric     CmdArgs.push_back("-fenable-matrix");
54565ffd83dbSDimitry Andric     CmdArgs.push_back("-mllvm");
54575ffd83dbSDimitry Andric     CmdArgs.push_back("-enable-matrix");
54585ffd83dbSDimitry Andric   }
54595ffd83dbSDimitry Andric 
5460a7dea167SDimitry Andric   CodeGenOptions::FramePointerKind FPKeepKind =
5461a7dea167SDimitry Andric                   getFramePointerKind(Args, RawTriple);
5462a7dea167SDimitry Andric   const char *FPKeepKindStr = nullptr;
5463a7dea167SDimitry Andric   switch (FPKeepKind) {
5464a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::None:
5465a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=none";
5466a7dea167SDimitry Andric     break;
5467a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::NonLeaf:
5468a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=non-leaf";
5469a7dea167SDimitry Andric     break;
5470a7dea167SDimitry Andric   case CodeGenOptions::FramePointerKind::All:
5471a7dea167SDimitry Andric     FPKeepKindStr = "-mframe-pointer=all";
5472a7dea167SDimitry Andric     break;
5473a7dea167SDimitry Andric   }
5474a7dea167SDimitry Andric   assert(FPKeepKindStr && "unknown FramePointerKind");
5475a7dea167SDimitry Andric   CmdArgs.push_back(FPKeepKindStr);
5476a7dea167SDimitry Andric 
547781ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
547881ad6265SDimitry Andric                      options::OPT_fno_zero_initialized_in_bss);
54790b57cec5SDimitry Andric 
54800b57cec5SDimitry Andric   bool OFastEnabled = isOptimizationLevelFast(Args);
54810b57cec5SDimitry Andric   // If -Ofast is the optimization level, then -fstrict-aliasing should be
54820b57cec5SDimitry Andric   // enabled.  This alias option is being used to simplify the hasFlag logic.
54830b57cec5SDimitry Andric   OptSpecifier StrictAliasingAliasOption =
54840b57cec5SDimitry Andric       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
54850b57cec5SDimitry Andric   // We turn strict aliasing off by default if we're in CL mode, since MSVC
54860b57cec5SDimitry Andric   // doesn't do any TBAA.
54870b57cec5SDimitry Andric   bool TBAAOnByDefault = !D.IsCLMode();
54880b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
54890b57cec5SDimitry Andric                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
54900b57cec5SDimitry Andric     CmdArgs.push_back("-relaxed-aliasing");
54910b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
549281ad6265SDimitry Andric                     options::OPT_fno_struct_path_tbaa, true))
54930b57cec5SDimitry Andric     CmdArgs.push_back("-no-struct-path-tbaa");
549481ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
549581ad6265SDimitry Andric                     options::OPT_fno_strict_enums);
549681ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
549781ad6265SDimitry Andric                      options::OPT_fno_strict_return);
549881ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
549981ad6265SDimitry Andric                     options::OPT_fno_allow_editor_placeholders);
550081ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
550181ad6265SDimitry Andric                     options::OPT_fno_strict_vtable_pointers);
550281ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
550381ad6265SDimitry Andric                     options::OPT_fno_force_emit_vtables);
550481ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
550581ad6265SDimitry Andric                      options::OPT_fno_optimize_sibling_calls);
550681ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
550781ad6265SDimitry Andric                      options::OPT_fno_escaping_block_tail_calls);
55080b57cec5SDimitry Andric 
55090b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
55100b57cec5SDimitry Andric                   options::OPT_fno_fine_grained_bitfield_accesses);
55110b57cec5SDimitry Andric 
5512fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5513fe6060f1SDimitry Andric                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5514fe6060f1SDimitry Andric 
55155f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
55165f757f3fSDimitry Andric                   options::OPT_fno_experimental_omit_vtable_rtti);
55175f757f3fSDimitry Andric 
55180b57cec5SDimitry Andric   // Handle segmented stacks.
5519bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5520bdd1243dSDimitry Andric                     options::OPT_fno_split_stack);
5521fe6060f1SDimitry Andric 
5522fe6060f1SDimitry Andric   // -fprotect-parens=0 is default.
5523fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fprotect_parens,
5524fe6060f1SDimitry Andric                    options::OPT_fno_protect_parens, false))
5525fe6060f1SDimitry Andric     CmdArgs.push_back("-fprotect-parens");
55260b57cec5SDimitry Andric 
55275ffd83dbSDimitry Andric   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
55285ffd83dbSDimitry Andric 
5529fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5530fe6060f1SDimitry Andric     const llvm::Triple::ArchType Arch = TC.getArch();
5531fe6060f1SDimitry Andric     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5532fe6060f1SDimitry Andric       StringRef V = A->getValue();
5533fe6060f1SDimitry Andric       if (V == "64")
5534fe6060f1SDimitry Andric         CmdArgs.push_back("-fextend-arguments=64");
5535fe6060f1SDimitry Andric       else if (V != "32")
5536fe6060f1SDimitry Andric         D.Diag(diag::err_drv_invalid_argument_to_option)
5537fe6060f1SDimitry Andric             << A->getValue() << A->getOption().getName();
5538fe6060f1SDimitry Andric     } else
5539fe6060f1SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5540fe6060f1SDimitry Andric           << A->getOption().getName() << TripleStr;
5541fe6060f1SDimitry Andric   }
5542fe6060f1SDimitry Andric 
55435ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
55445ffd83dbSDimitry Andric     if (TC.getArch() == llvm::Triple::avr)
55455ffd83dbSDimitry Andric       A->render(Args, CmdArgs);
55465ffd83dbSDimitry Andric     else
55475ffd83dbSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
55485ffd83dbSDimitry Andric           << A->getAsString(Args) << TripleStr;
55495ffd83dbSDimitry Andric   }
55500b57cec5SDimitry Andric 
5551a7dea167SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5552480093f4SDimitry Andric     if (TC.getTriple().isX86())
5553a7dea167SDimitry Andric       A->render(Args, CmdArgs);
5554e8d8bef9SDimitry Andric     else if (TC.getTriple().isPPC() &&
5555a7dea167SDimitry Andric              (A->getOption().getID() != options::OPT_mlong_double_80))
55560b57cec5SDimitry Andric       A->render(Args, CmdArgs);
55570b57cec5SDimitry Andric     else
55580b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
55590b57cec5SDimitry Andric           << A->getAsString(Args) << TripleStr;
55600b57cec5SDimitry Andric   }
55610b57cec5SDimitry Andric 
55620b57cec5SDimitry Andric   // Decide whether to use verbose asm. Verbose assembly is the default on
55630b57cec5SDimitry Andric   // toolchains which have the integrated assembler on by default.
55640b57cec5SDimitry Andric   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
55655ffd83dbSDimitry Andric   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5566a7dea167SDimitry Andric                     IsIntegratedAssemblerDefault))
55675ffd83dbSDimitry Andric     CmdArgs.push_back("-fno-verbose-asm");
55680b57cec5SDimitry Andric 
5569e8d8bef9SDimitry Andric   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5570e8d8bef9SDimitry Andric   // use that to indicate the MC default in the backend.
5571e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5572e8d8bef9SDimitry Andric     StringRef V = A->getValue();
5573e8d8bef9SDimitry Andric     unsigned Num;
5574e8d8bef9SDimitry Andric     if (V == "none")
5575e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
5576e8d8bef9SDimitry Andric     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5577e8d8bef9SDimitry Andric              (V.empty() || (V.consume_front(".") &&
5578e8d8bef9SDimitry Andric                             !V.consumeInteger(10, Num) && V.empty())))
5579e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
5580e8d8bef9SDimitry Andric     else
5581e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
5582e8d8bef9SDimitry Andric           << A->getValue() << A->getOption().getName();
5583e8d8bef9SDimitry Andric   }
5584e8d8bef9SDimitry Andric 
5585fe6060f1SDimitry Andric   // If toolchain choose to use MCAsmParser for inline asm don't pass the
5586fe6060f1SDimitry Andric   // option to disable integrated-as explictly.
5587fe6060f1SDimitry Andric   if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
55880b57cec5SDimitry Andric     CmdArgs.push_back("-no-integrated-as");
55890b57cec5SDimitry Andric 
55900b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
55910b57cec5SDimitry Andric     CmdArgs.push_back("-mdebug-pass");
55920b57cec5SDimitry Andric     CmdArgs.push_back("Structure");
55930b57cec5SDimitry Andric   }
55940b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
55950b57cec5SDimitry Andric     CmdArgs.push_back("-mdebug-pass");
55960b57cec5SDimitry Andric     CmdArgs.push_back("Arguments");
55970b57cec5SDimitry Andric   }
55980b57cec5SDimitry Andric 
55990b57cec5SDimitry Andric   // Enable -mconstructor-aliases except on darwin, where we have to work around
56005f757f3fSDimitry Andric   // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
56015f757f3fSDimitry Andric   // code, where aliases aren't supported.
5602349cc55cSDimitry Andric   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
56030b57cec5SDimitry Andric     CmdArgs.push_back("-mconstructor-aliases");
56040b57cec5SDimitry Andric 
56050b57cec5SDimitry Andric   // Darwin's kernel doesn't support guard variables; just die if we
56060b57cec5SDimitry Andric   // try to use them.
56070b57cec5SDimitry Andric   if (KernelOrKext && RawTriple.isOSDarwin())
56080b57cec5SDimitry Andric     CmdArgs.push_back("-fforbid-guard-variables");
56090b57cec5SDimitry Andric 
56100b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
56115ffd83dbSDimitry Andric                    Triple.isWindowsGNUEnvironment())) {
56120b57cec5SDimitry Andric     CmdArgs.push_back("-mms-bitfields");
56130b57cec5SDimitry Andric   }
56140b57cec5SDimitry Andric 
56155f757f3fSDimitry Andric   if (Triple.isWindowsGNUEnvironment()) {
56165f757f3fSDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
56175f757f3fSDimitry Andric                        options::OPT_fno_auto_import);
56185f757f3fSDimitry Andric   }
56195f757f3fSDimitry Andric 
56205f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
56215f757f3fSDimitry Andric                    Triple.isX86() && D.IsCLMode()))
56225f757f3fSDimitry Andric     CmdArgs.push_back("-fms-volatile");
56235f757f3fSDimitry Andric 
5624e8d8bef9SDimitry Andric   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5625e8d8bef9SDimitry Andric   // defaults to -fno-direct-access-external-data. Pass the option if different
5626e8d8bef9SDimitry Andric   // from the default.
5627e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
56285f757f3fSDimitry Andric                                options::OPT_fno_direct_access_external_data)) {
5629e8d8bef9SDimitry Andric     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5630e8d8bef9SDimitry Andric         (PICLevel == 0))
5631e8d8bef9SDimitry Andric       A->render(Args, CmdArgs);
56325f757f3fSDimitry Andric   } else if (PICLevel == 0 && Triple.isLoongArch()) {
56335f757f3fSDimitry Andric     // Some targets default to -fno-direct-access-external-data even for
56345f757f3fSDimitry Andric     // -fno-pic.
56355f757f3fSDimitry Andric     CmdArgs.push_back("-fno-direct-access-external-data");
56365f757f3fSDimitry Andric   }
56370b57cec5SDimitry Andric 
56380b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
56390b57cec5SDimitry Andric     CmdArgs.push_back("-fno-plt");
56400b57cec5SDimitry Andric   }
56410b57cec5SDimitry Andric 
56420b57cec5SDimitry Andric   // -fhosted is default.
56430b57cec5SDimitry Andric   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
56440b57cec5SDimitry Andric   // use Freestanding.
56450b57cec5SDimitry Andric   bool Freestanding =
56460b57cec5SDimitry Andric       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
56470b57cec5SDimitry Andric       KernelOrKext;
56480b57cec5SDimitry Andric   if (Freestanding)
56490b57cec5SDimitry Andric     CmdArgs.push_back("-ffreestanding");
56500b57cec5SDimitry Andric 
565181ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
565281ad6265SDimitry Andric 
56530b57cec5SDimitry Andric   // This is a coarse approximation of what llvm-gcc actually does, both
56540b57cec5SDimitry Andric   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
56550b57cec5SDimitry Andric   // complicated ways.
5656349cc55cSDimitry Andric   auto SanitizeArgs = TC.getSanitizerArgs(Args);
5657bdd1243dSDimitry Andric 
5658bdd1243dSDimitry Andric   bool IsAsyncUnwindTablesDefault =
5659bdd1243dSDimitry Andric       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5660bdd1243dSDimitry Andric   bool IsSyncUnwindTablesDefault =
5661bdd1243dSDimitry Andric       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5662bdd1243dSDimitry Andric 
5663349cc55cSDimitry Andric   bool AsyncUnwindTables = Args.hasFlag(
5664349cc55cSDimitry Andric       options::OPT_fasynchronous_unwind_tables,
56650b57cec5SDimitry Andric       options::OPT_fno_asynchronous_unwind_tables,
5666bdd1243dSDimitry Andric       (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
56670b57cec5SDimitry Andric           !Freestanding);
5668bdd1243dSDimitry Andric   bool UnwindTables =
5669bdd1243dSDimitry Andric       Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5670bdd1243dSDimitry Andric                    IsSyncUnwindTablesDefault && !Freestanding);
5671349cc55cSDimitry Andric   if (AsyncUnwindTables)
5672349cc55cSDimitry Andric     CmdArgs.push_back("-funwind-tables=2");
5673349cc55cSDimitry Andric   else if (UnwindTables)
5674349cc55cSDimitry Andric      CmdArgs.push_back("-funwind-tables=1");
56750b57cec5SDimitry Andric 
56765ffd83dbSDimitry Andric   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
56775ffd83dbSDimitry Andric   // `--gpu-use-aux-triple-only` is specified.
56785ffd83dbSDimitry Andric   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5679fe6060f1SDimitry Andric       (IsCudaDevice || IsHIPDevice)) {
56805ffd83dbSDimitry Andric     const ArgList &HostArgs =
56815ffd83dbSDimitry Andric         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
56825ffd83dbSDimitry Andric     std::string HostCPU =
5683349cc55cSDimitry Andric         getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
56845ffd83dbSDimitry Andric     if (!HostCPU.empty()) {
56855ffd83dbSDimitry Andric       CmdArgs.push_back("-aux-target-cpu");
56865ffd83dbSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(HostCPU));
56875ffd83dbSDimitry Andric     }
56885ffd83dbSDimitry Andric     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
56895ffd83dbSDimitry Andric                       /*ForAS*/ false, /*IsAux*/ true);
56905ffd83dbSDimitry Andric   }
56915ffd83dbSDimitry Andric 
56920b57cec5SDimitry Andric   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
56930b57cec5SDimitry Andric 
56940b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
56955ffd83dbSDimitry Andric     StringRef CM = A->getValue();
56965f757f3fSDimitry Andric     bool Ok = false;
5697fe6060f1SDimitry Andric     if (Triple.isOSAIX() && CM == "medium")
56985f757f3fSDimitry Andric       CM = "large";
56995f757f3fSDimitry Andric     if (Triple.isAArch64(64)) {
57005f757f3fSDimitry Andric       Ok = CM == "tiny" || CM == "small" || CM == "large";
57015f757f3fSDimitry Andric       if (CM == "large" && RelocationModel != llvm::Reloc::Static)
57025f757f3fSDimitry Andric         D.Diag(diag::err_drv_argument_only_allowed_with)
57035f757f3fSDimitry Andric             << A->getAsString(Args) << "-fno-pic";
57045f757f3fSDimitry Andric     } else if (Triple.isLoongArch()) {
57055f757f3fSDimitry Andric       if (CM == "extreme" &&
57065f757f3fSDimitry Andric           Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
57075f757f3fSDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
57085f757f3fSDimitry Andric             << A->getAsString(Args) << "-fplt";
57095f757f3fSDimitry Andric       Ok = CM == "normal" || CM == "medium" || CM == "extreme";
57105f757f3fSDimitry Andric       // Convert to LLVM recognizable names.
57115f757f3fSDimitry Andric       if (Ok)
57125f757f3fSDimitry Andric         CM = llvm::StringSwitch<StringRef>(CM)
57135f757f3fSDimitry Andric                  .Case("normal", "small")
57145f757f3fSDimitry Andric                  .Case("extreme", "large")
57155f757f3fSDimitry Andric                  .Default(CM);
57165f757f3fSDimitry Andric     } else if (Triple.isPPC64() || Triple.isOSAIX()) {
57175f757f3fSDimitry Andric       Ok = CM == "small" || CM == "medium" || CM == "large";
57185f757f3fSDimitry Andric     } else if (Triple.isRISCV()) {
57195f757f3fSDimitry Andric       if (CM == "medlow")
57205f757f3fSDimitry Andric         CM = "small";
57215f757f3fSDimitry Andric       else if (CM == "medany")
57225f757f3fSDimitry Andric         CM = "medium";
57235f757f3fSDimitry Andric       Ok = CM == "small" || CM == "medium";
57245f757f3fSDimitry Andric     } else if (Triple.getArch() == llvm::Triple::x86_64) {
57255f757f3fSDimitry Andric       Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
57265f757f3fSDimitry Andric                               CM);
57275f757f3fSDimitry Andric     } else if (Triple.isNVPTX() || Triple.isAMDGPU()) {
57285f757f3fSDimitry Andric       // NVPTX/AMDGPU does not care about the code model and will accept
57295f757f3fSDimitry Andric       // whatever works for the host.
57305f757f3fSDimitry Andric       Ok = true;
57315f757f3fSDimitry Andric     }
57325f757f3fSDimitry Andric     if (Ok) {
57335f757f3fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
5734fe6060f1SDimitry Andric     } else {
57355f757f3fSDimitry Andric       D.Diag(diag::err_drv_unsupported_option_argument_for_target)
57365f757f3fSDimitry Andric           << A->getSpelling() << CM << TripleStr;
57375f757f3fSDimitry Andric     }
57385f757f3fSDimitry Andric   }
57395f757f3fSDimitry Andric 
57405f757f3fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
57415f757f3fSDimitry Andric     if (!Triple.isX86()) {
57425f757f3fSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
57435f757f3fSDimitry Andric           << A->getOption().getName() << TripleStr;
57445f757f3fSDimitry Andric     } else {
57455f757f3fSDimitry Andric       bool IsMediumCM = false;
57465f757f3fSDimitry Andric       if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ))
57475f757f3fSDimitry Andric         IsMediumCM = StringRef(A->getValue()) == "medium";
57485f757f3fSDimitry Andric       if (!IsMediumCM) {
57495f757f3fSDimitry Andric         D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
57505f757f3fSDimitry Andric             << A->getOption().getRenderName();
57515f757f3fSDimitry Andric       } else {
57525f757f3fSDimitry Andric         A->render(Args, CmdArgs);
57535f757f3fSDimitry Andric       }
57540b57cec5SDimitry Andric     }
5755fe6060f1SDimitry Andric   }
57560b57cec5SDimitry Andric 
5757480093f4SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5758480093f4SDimitry Andric     StringRef Value = A->getValue();
5759480093f4SDimitry Andric     unsigned TLSSize = 0;
5760480093f4SDimitry Andric     Value.getAsInteger(10, TLSSize);
5761480093f4SDimitry Andric     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5762480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5763480093f4SDimitry Andric           << A->getOption().getName() << TripleStr;
5764480093f4SDimitry Andric     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5765480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_int_value)
5766480093f4SDimitry Andric           << A->getOption().getName() << Value;
5767480093f4SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5768480093f4SDimitry Andric   }
5769480093f4SDimitry Andric 
57700b57cec5SDimitry Andric   // Add the target cpu
5771349cc55cSDimitry Andric   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
57720b57cec5SDimitry Andric   if (!CPU.empty()) {
57730b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
57740b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
57750b57cec5SDimitry Andric   }
57760b57cec5SDimitry Andric 
57770b57cec5SDimitry Andric   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
57780b57cec5SDimitry Andric 
57790b57cec5SDimitry Andric   // Add clang-cl arguments.
57800b57cec5SDimitry Andric   types::ID InputType = Input.getType();
57810b57cec5SDimitry Andric   if (D.IsCLMode())
57825f757f3fSDimitry Andric     AddClangCLArgs(Args, InputType, CmdArgs);
57830b57cec5SDimitry Andric 
57845f757f3fSDimitry Andric   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
57855f757f3fSDimitry Andric       llvm::codegenoptions::NoDebugInfo;
5786e8d8bef9SDimitry Andric   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
57875f757f3fSDimitry Andric   renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
57885f757f3fSDimitry Andric                      CmdArgs, Output, DebugInfoKind, DwarfFission);
578981ad6265SDimitry Andric 
57900b57cec5SDimitry Andric   // Add the split debug info name to the command lines here so we
57910b57cec5SDimitry Andric   // can propagate it to the backend.
57920b57cec5SDimitry Andric   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5793e8d8bef9SDimitry Andric                     (TC.getTriple().isOSBinFormatELF() ||
579406c3fb27SDimitry Andric                      TC.getTriple().isOSBinFormatWasm() ||
579506c3fb27SDimitry Andric                      TC.getTriple().isOSBinFormatCOFF()) &&
57960b57cec5SDimitry Andric                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
57970b57cec5SDimitry Andric                      isa<BackendJobAction>(JA));
57980b57cec5SDimitry Andric   if (SplitDWARF) {
5799e8d8bef9SDimitry Andric     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
58000b57cec5SDimitry Andric     CmdArgs.push_back("-split-dwarf-file");
58010b57cec5SDimitry Andric     CmdArgs.push_back(SplitDWARFOut);
58020b57cec5SDimitry Andric     if (DwarfFission == DwarfFissionKind::Split) {
58030b57cec5SDimitry Andric       CmdArgs.push_back("-split-dwarf-output");
58040b57cec5SDimitry Andric       CmdArgs.push_back(SplitDWARFOut);
58050b57cec5SDimitry Andric     }
58060b57cec5SDimitry Andric   }
58070b57cec5SDimitry Andric 
58080b57cec5SDimitry Andric   // Pass the linker version in use.
58090b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
58100b57cec5SDimitry Andric     CmdArgs.push_back("-target-linker-version");
58110b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
58120b57cec5SDimitry Andric   }
58130b57cec5SDimitry Andric 
58140b57cec5SDimitry Andric   // Explicitly error on some things we know we don't support and can't just
58150b57cec5SDimitry Andric   // ignore.
58160b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
58170b57cec5SDimitry Andric     Arg *Unsupported;
58180b57cec5SDimitry Andric     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
58190b57cec5SDimitry Andric         TC.getArch() == llvm::Triple::x86) {
58200b57cec5SDimitry Andric       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
58210b57cec5SDimitry Andric           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
58220b57cec5SDimitry Andric         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
58230b57cec5SDimitry Andric             << Unsupported->getOption().getName();
58240b57cec5SDimitry Andric     }
58250b57cec5SDimitry Andric     // The faltivec option has been superseded by the maltivec option.
58260b57cec5SDimitry Andric     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
58270b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
58280b57cec5SDimitry Andric           << Unsupported->getOption().getName()
58290b57cec5SDimitry Andric           << "please use -maltivec and include altivec.h explicitly";
58300b57cec5SDimitry Andric     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
58310b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
58320b57cec5SDimitry Andric           << Unsupported->getOption().getName() << "please use -mno-altivec";
58330b57cec5SDimitry Andric   }
58340b57cec5SDimitry Andric 
58350b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_v);
58365ffd83dbSDimitry Andric 
58375ffd83dbSDimitry Andric   if (Args.getLastArg(options::OPT_H)) {
58385ffd83dbSDimitry Andric     CmdArgs.push_back("-H");
58395ffd83dbSDimitry Andric     CmdArgs.push_back("-sys-header-deps");
58405ffd83dbSDimitry Andric   }
5841fe6060f1SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
58425ffd83dbSDimitry Andric 
5843bdd1243dSDimitry Andric   if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
58440b57cec5SDimitry Andric     CmdArgs.push_back("-header-include-file");
5845fe6060f1SDimitry Andric     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5846fe6060f1SDimitry Andric                           ? D.CCPrintHeadersFilename.c_str()
58470b57cec5SDimitry Andric                           : "-");
58485ffd83dbSDimitry Andric     CmdArgs.push_back("-sys-header-deps");
5849bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
5850bdd1243dSDimitry Andric         "-header-include-format=" +
5851bdd1243dSDimitry Andric         std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
5852bdd1243dSDimitry Andric     CmdArgs.push_back(
5853bdd1243dSDimitry Andric         Args.MakeArgString("-header-include-filtering=" +
5854bdd1243dSDimitry Andric                            std::string(headerIncludeFilteringKindToString(
5855bdd1243dSDimitry Andric                                D.CCPrintHeadersFiltering))));
58560b57cec5SDimitry Andric   }
58570b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_P);
58580b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
58590b57cec5SDimitry Andric 
58600b57cec5SDimitry Andric   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
58610b57cec5SDimitry Andric     CmdArgs.push_back("-diagnostic-log-file");
5862fe6060f1SDimitry Andric     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5863fe6060f1SDimitry Andric                           ? D.CCLogDiagnosticsFilename.c_str()
58640b57cec5SDimitry Andric                           : "-");
58650b57cec5SDimitry Andric   }
58660b57cec5SDimitry Andric 
586713138422SDimitry Andric   // Give the gen diagnostics more chances to succeed, by avoiding intentional
586813138422SDimitry Andric   // crashes.
586913138422SDimitry Andric   if (D.CCGenDiagnostics)
587013138422SDimitry Andric     CmdArgs.push_back("-disable-pragma-debug-crash");
587113138422SDimitry Andric 
5872fe6060f1SDimitry Andric   // Allow backend to put its diagnostic files in the same place as frontend
5873fe6060f1SDimitry Andric   // crash diagnostics files.
5874fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5875fe6060f1SDimitry Andric     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5876fe6060f1SDimitry Andric     CmdArgs.push_back("-mllvm");
5877fe6060f1SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5878fe6060f1SDimitry Andric   }
5879fe6060f1SDimitry Andric 
58800b57cec5SDimitry Andric   bool UseSeparateSections = isUseSeparateSections(Triple);
58810b57cec5SDimitry Andric 
58820b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_ffunction_sections,
58830b57cec5SDimitry Andric                    options::OPT_fno_function_sections, UseSeparateSections)) {
58840b57cec5SDimitry Andric     CmdArgs.push_back("-ffunction-sections");
58850b57cec5SDimitry Andric   }
58860b57cec5SDimitry Andric 
58875ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
58885ffd83dbSDimitry Andric     StringRef Val = A->getValue();
5889fe6060f1SDimitry Andric     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
58905ffd83dbSDimitry Andric       if (Val != "all" && Val != "labels" && Val != "none" &&
58915f757f3fSDimitry Andric           !Val.starts_with("list="))
58925ffd83dbSDimitry Andric         D.Diag(diag::err_drv_invalid_value)
58935ffd83dbSDimitry Andric             << A->getAsString(Args) << A->getValue();
58945ffd83dbSDimitry Andric       else
58955ffd83dbSDimitry Andric         A->render(Args, CmdArgs);
5896fe6060f1SDimitry Andric     } else if (Triple.isNVPTX()) {
5897fe6060f1SDimitry Andric       // Do not pass the option to the GPU compilation. We still want it enabled
5898fe6060f1SDimitry Andric       // for the host-side compilation, so seeing it here is not an error.
5899fe6060f1SDimitry Andric     } else if (Val != "none") {
5900fe6060f1SDimitry Andric       // =none is allowed everywhere. It's useful for overriding the option
5901fe6060f1SDimitry Andric       // and is the same as not specifying the option.
5902e8d8bef9SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
5903e8d8bef9SDimitry Andric           << A->getAsString(Args) << TripleStr;
5904e8d8bef9SDimitry Andric     }
59055ffd83dbSDimitry Andric   }
59065ffd83dbSDimitry Andric 
5907e8d8bef9SDimitry Andric   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
59080b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5909e8d8bef9SDimitry Andric                    UseSeparateSections || HasDefaultDataSections)) {
59100b57cec5SDimitry Andric     CmdArgs.push_back("-fdata-sections");
59110b57cec5SDimitry Andric   }
59120b57cec5SDimitry Andric 
591381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
591481ad6265SDimitry Andric                      options::OPT_fno_unique_section_names);
591581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
591681ad6265SDimitry Andric                     options::OPT_fno_unique_internal_linkage_names);
591781ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
591881ad6265SDimitry Andric                     options::OPT_fno_unique_basic_block_section_names);
591906c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
592006c3fb27SDimitry Andric                     options::OPT_fno_convergent_functions);
59215ffd83dbSDimitry Andric 
5922e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5923e8d8bef9SDimitry Andric                                options::OPT_fno_split_machine_functions)) {
59245f757f3fSDimitry Andric     if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
59255f757f3fSDimitry Andric       // This codegen pass is only available on x86 and AArch64 ELF targets.
59265f757f3fSDimitry Andric       if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
5927e8d8bef9SDimitry Andric         A->render(Args, CmdArgs);
59285f757f3fSDimitry Andric       else
5929e8d8bef9SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
5930e8d8bef9SDimitry Andric             << A->getAsString(Args) << TripleStr;
5931e8d8bef9SDimitry Andric     }
5932e8d8bef9SDimitry Andric   }
5933e8d8bef9SDimitry Andric 
59340b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
59350b57cec5SDimitry Andric                   options::OPT_finstrument_functions_after_inlining,
59360b57cec5SDimitry Andric                   options::OPT_finstrument_function_entry_bare);
59370b57cec5SDimitry Andric 
59385ffd83dbSDimitry Andric   // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
59395ffd83dbSDimitry Andric   // for sampling, overhead of call arc collection is way too high and there's
59405ffd83dbSDimitry Andric   // no way to collect the output.
59415ffd83dbSDimitry Andric   if (!Triple.isNVPTX() && !Triple.isAMDGCN())
594206c3fb27SDimitry Andric     addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
59430b57cec5SDimitry Andric 
59440b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
59450b57cec5SDimitry Andric 
5946bdd1243dSDimitry Andric   if (getLastProfileSampleUseArg(Args) &&
5947bdd1243dSDimitry Andric       Args.hasArg(options::OPT_fsample_profile_use_profi)) {
5948bdd1243dSDimitry Andric     CmdArgs.push_back("-mllvm");
5949bdd1243dSDimitry Andric     CmdArgs.push_back("-sample-profile-use-profi");
5950bdd1243dSDimitry Andric   }
5951bdd1243dSDimitry Andric 
595281ad6265SDimitry Andric   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
595381ad6265SDimitry Andric   if (RawTriple.isPS() &&
59540b57cec5SDimitry Andric       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
595581ad6265SDimitry Andric     PScpu::addProfileRTArgs(TC, Args, CmdArgs);
595681ad6265SDimitry Andric     PScpu::addSanitizerArgs(TC, Args, CmdArgs);
59570b57cec5SDimitry Andric   }
59580b57cec5SDimitry Andric 
59590b57cec5SDimitry Andric   // Pass options for controlling the default header search paths.
59600b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_nostdinc)) {
59610b57cec5SDimitry Andric     CmdArgs.push_back("-nostdsysteminc");
59620b57cec5SDimitry Andric     CmdArgs.push_back("-nobuiltininc");
59630b57cec5SDimitry Andric   } else {
59640b57cec5SDimitry Andric     if (Args.hasArg(options::OPT_nostdlibinc))
59650b57cec5SDimitry Andric       CmdArgs.push_back("-nostdsysteminc");
59660b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
59670b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
59680b57cec5SDimitry Andric   }
59690b57cec5SDimitry Andric 
59700b57cec5SDimitry Andric   // Pass the path to compiler resource files.
59710b57cec5SDimitry Andric   CmdArgs.push_back("-resource-dir");
59720b57cec5SDimitry Andric   CmdArgs.push_back(D.ResourceDir.c_str());
59730b57cec5SDimitry Andric 
59740b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
59750b57cec5SDimitry Andric 
59760b57cec5SDimitry Andric   RenderARCMigrateToolOptions(D, Args, CmdArgs);
59770b57cec5SDimitry Andric 
59780b57cec5SDimitry Andric   // Add preprocessing options like -I, -D, etc. if we are using the
59790b57cec5SDimitry Andric   // preprocessor.
59800b57cec5SDimitry Andric   //
59810b57cec5SDimitry Andric   // FIXME: Support -fpreprocessed
59820b57cec5SDimitry Andric   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
59830b57cec5SDimitry Andric     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
59840b57cec5SDimitry Andric 
59850b57cec5SDimitry Andric   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
59860b57cec5SDimitry Andric   // that "The compiler can only warn and ignore the option if not recognized".
59870b57cec5SDimitry Andric   // When building with ccache, it will pass -D options to clang even on
59880b57cec5SDimitry Andric   // preprocessed inputs and configure concludes that -fPIC is not supported.
59890b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_D);
59900b57cec5SDimitry Andric 
59910b57cec5SDimitry Andric   // Manually translate -O4 to -O3; let clang reject others.
59920b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
59930b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O4)) {
59940b57cec5SDimitry Andric       CmdArgs.push_back("-O3");
59950b57cec5SDimitry Andric       D.Diag(diag::warn_O4_is_O3);
59960b57cec5SDimitry Andric     } else {
59970b57cec5SDimitry Andric       A->render(Args, CmdArgs);
59980b57cec5SDimitry Andric     }
59990b57cec5SDimitry Andric   }
60000b57cec5SDimitry Andric 
60010b57cec5SDimitry Andric   // Warn about ignored options to clang.
60020b57cec5SDimitry Andric   for (const Arg *A :
60030b57cec5SDimitry Andric        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
60040b57cec5SDimitry Andric     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
60050b57cec5SDimitry Andric     A->claim();
60060b57cec5SDimitry Andric   }
60070b57cec5SDimitry Andric 
60080b57cec5SDimitry Andric   for (const Arg *A :
60090b57cec5SDimitry Andric        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
60100b57cec5SDimitry Andric     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
60110b57cec5SDimitry Andric     A->claim();
60120b57cec5SDimitry Andric   }
60130b57cec5SDimitry Andric 
60140b57cec5SDimitry Andric   claimNoWarnArgs(Args);
60150b57cec5SDimitry Andric 
60160b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
60170b57cec5SDimitry Andric 
6018349cc55cSDimitry Andric   for (const Arg *A :
6019349cc55cSDimitry Andric        Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6020349cc55cSDimitry Andric     A->claim();
6021349cc55cSDimitry Andric     if (A->getOption().getID() == options::OPT__SLASH_wd) {
6022349cc55cSDimitry Andric       unsigned WarningNumber;
6023349cc55cSDimitry Andric       if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6024349cc55cSDimitry Andric         D.Diag(diag::err_drv_invalid_int_value)
6025349cc55cSDimitry Andric             << A->getAsString(Args) << A->getValue();
6026349cc55cSDimitry Andric         continue;
6027349cc55cSDimitry Andric       }
6028349cc55cSDimitry Andric 
6029349cc55cSDimitry Andric       if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6030349cc55cSDimitry Andric         CmdArgs.push_back(Args.MakeArgString(
6031349cc55cSDimitry Andric             "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6032349cc55cSDimitry Andric       }
6033349cc55cSDimitry Andric       continue;
6034349cc55cSDimitry Andric     }
6035349cc55cSDimitry Andric     A->render(Args, CmdArgs);
6036349cc55cSDimitry Andric   }
6037349cc55cSDimitry Andric 
60385f757f3fSDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
60395f757f3fSDimitry Andric 
60400b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
60410b57cec5SDimitry Andric     CmdArgs.push_back("-pedantic");
60420b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
60430b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_w);
60440b57cec5SDimitry Andric 
6045bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6046bdd1243dSDimitry Andric                     options::OPT_fno_fixed_point);
60470b57cec5SDimitry Andric 
6048fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6049fe6060f1SDimitry Andric     A->render(Args, CmdArgs);
6050fe6060f1SDimitry Andric 
6051fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6052fe6060f1SDimitry Andric                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
6053fe6060f1SDimitry Andric 
60545f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
60555f757f3fSDimitry Andric                   options::OPT_fno_experimental_omit_vtable_rtti);
60565f757f3fSDimitry Andric 
6057349cc55cSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6058349cc55cSDimitry Andric     A->render(Args, CmdArgs);
6059349cc55cSDimitry Andric 
60600b57cec5SDimitry Andric   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
60610b57cec5SDimitry Andric   // (-ansi is equivalent to -std=c89 or -std=c++98).
60620b57cec5SDimitry Andric   //
60630b57cec5SDimitry Andric   // If a std is supplied, only add -trigraphs if it follows the
60640b57cec5SDimitry Andric   // option.
6065fe6060f1SDimitry Andric   bool ImplyVCPPCVer = false;
60660b57cec5SDimitry Andric   bool ImplyVCPPCXXVer = false;
60670b57cec5SDimitry Andric   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
60680b57cec5SDimitry Andric   if (Std) {
60690b57cec5SDimitry Andric     if (Std->getOption().matches(options::OPT_ansi))
60700b57cec5SDimitry Andric       if (types::isCXX(InputType))
60710b57cec5SDimitry Andric         CmdArgs.push_back("-std=c++98");
60720b57cec5SDimitry Andric       else
60730b57cec5SDimitry Andric         CmdArgs.push_back("-std=c89");
60740b57cec5SDimitry Andric     else
60750b57cec5SDimitry Andric       Std->render(Args, CmdArgs);
60760b57cec5SDimitry Andric 
60770b57cec5SDimitry Andric     // If -f(no-)trigraphs appears after the language standard flag, honor it.
60780b57cec5SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
60790b57cec5SDimitry Andric                                  options::OPT_ftrigraphs,
60800b57cec5SDimitry Andric                                  options::OPT_fno_trigraphs))
60810b57cec5SDimitry Andric       if (A != Std)
60820b57cec5SDimitry Andric         A->render(Args, CmdArgs);
60830b57cec5SDimitry Andric   } else {
60840b57cec5SDimitry Andric     // Honor -std-default.
60850b57cec5SDimitry Andric     //
60860b57cec5SDimitry Andric     // FIXME: Clang doesn't correctly handle -std= when the input language
60870b57cec5SDimitry Andric     // doesn't match. For the time being just ignore this for C++ inputs;
60880b57cec5SDimitry Andric     // eventually we want to do all the standard defaulting here instead of
60890b57cec5SDimitry Andric     // splitting it between the driver and clang -cc1.
6090fe6060f1SDimitry Andric     if (!types::isCXX(InputType)) {
6091fe6060f1SDimitry Andric       if (!Args.hasArg(options::OPT__SLASH_std)) {
60920b57cec5SDimitry Andric         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
60930b57cec5SDimitry Andric                                   /*Joined=*/true);
6094fe6060f1SDimitry Andric       } else
6095fe6060f1SDimitry Andric         ImplyVCPPCVer = true;
6096fe6060f1SDimitry Andric     }
60970b57cec5SDimitry Andric     else if (IsWindowsMSVC)
60980b57cec5SDimitry Andric       ImplyVCPPCXXVer = true;
60990b57cec5SDimitry Andric 
61000b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
61010b57cec5SDimitry Andric                     options::OPT_fno_trigraphs);
61020b57cec5SDimitry Andric   }
61030b57cec5SDimitry Andric 
61040b57cec5SDimitry Andric   // GCC's behavior for -Wwrite-strings is a bit strange:
61050b57cec5SDimitry Andric   //  * In C, this "warning flag" changes the types of string literals from
61060b57cec5SDimitry Andric   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
61070b57cec5SDimitry Andric   //    for the discarded qualifier.
61080b57cec5SDimitry Andric   //  * In C++, this is just a normal warning flag.
61090b57cec5SDimitry Andric   //
61100b57cec5SDimitry Andric   // Implementing this warning correctly in C is hard, so we follow GCC's
61110b57cec5SDimitry Andric   // behavior for now. FIXME: Directly diagnose uses of a string literal as
61120b57cec5SDimitry Andric   // a non-const char* in C, rather than using this crude hack.
61130b57cec5SDimitry Andric   if (!types::isCXX(InputType)) {
61140b57cec5SDimitry Andric     // FIXME: This should behave just like a warning flag, and thus should also
61150b57cec5SDimitry Andric     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
61160b57cec5SDimitry Andric     Arg *WriteStrings =
61170b57cec5SDimitry Andric         Args.getLastArg(options::OPT_Wwrite_strings,
61180b57cec5SDimitry Andric                         options::OPT_Wno_write_strings, options::OPT_w);
61190b57cec5SDimitry Andric     if (WriteStrings &&
61200b57cec5SDimitry Andric         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
61210b57cec5SDimitry Andric       CmdArgs.push_back("-fconst-strings");
61220b57cec5SDimitry Andric   }
61230b57cec5SDimitry Andric 
61240b57cec5SDimitry Andric   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
61250b57cec5SDimitry Andric   // during C++ compilation, which it is by default. GCC keeps this define even
61260b57cec5SDimitry Andric   // in the presence of '-w', match this behavior bug-for-bug.
61270b57cec5SDimitry Andric   if (types::isCXX(InputType) &&
61280b57cec5SDimitry Andric       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
61290b57cec5SDimitry Andric                    true)) {
61300b57cec5SDimitry Andric     CmdArgs.push_back("-fdeprecated-macro");
61310b57cec5SDimitry Andric   }
61320b57cec5SDimitry Andric 
61330b57cec5SDimitry Andric   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
61340b57cec5SDimitry Andric   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
61350b57cec5SDimitry Andric     if (Asm->getOption().matches(options::OPT_fasm))
61360b57cec5SDimitry Andric       CmdArgs.push_back("-fgnu-keywords");
61370b57cec5SDimitry Andric     else
61380b57cec5SDimitry Andric       CmdArgs.push_back("-fno-gnu-keywords");
61390b57cec5SDimitry Andric   }
61400b57cec5SDimitry Andric 
6141480093f4SDimitry Andric   if (!ShouldEnableAutolink(Args, TC, JA))
61420b57cec5SDimitry Andric     CmdArgs.push_back("-fno-autolink");
61430b57cec5SDimitry Andric 
614406c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
614506c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
614606c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
614706c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
61480b57cec5SDimitry Andric 
6149fcaf7f86SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
615081ad6265SDimitry Andric 
6151a7dea167SDimitry Andric   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6152a7dea167SDimitry Andric     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6153a7dea167SDimitry Andric 
61540b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
61550b57cec5SDimitry Andric     CmdArgs.push_back("-fbracket-depth");
61560b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
61570b57cec5SDimitry Andric   }
61580b57cec5SDimitry Andric 
61590b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
61600b57cec5SDimitry Andric                                options::OPT_Wlarge_by_value_copy_def)) {
61610b57cec5SDimitry Andric     if (A->getNumValues()) {
61620b57cec5SDimitry Andric       StringRef bytes = A->getValue();
61630b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
61640b57cec5SDimitry Andric     } else
61650b57cec5SDimitry Andric       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
61660b57cec5SDimitry Andric   }
61670b57cec5SDimitry Andric 
61680b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_relocatable_pch))
61690b57cec5SDimitry Andric     CmdArgs.push_back("-relocatable-pch");
61700b57cec5SDimitry Andric 
61710b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
61720b57cec5SDimitry Andric     static const char *kCFABIs[] = {
61730b57cec5SDimitry Andric       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
61740b57cec5SDimitry Andric     };
61750b57cec5SDimitry Andric 
617681ad6265SDimitry Andric     if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
61770b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
61780b57cec5SDimitry Andric     else
61790b57cec5SDimitry Andric       A->render(Args, CmdArgs);
61800b57cec5SDimitry Andric   }
61810b57cec5SDimitry Andric 
61820b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
61830b57cec5SDimitry Andric     CmdArgs.push_back("-fconstant-string-class");
61840b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
61850b57cec5SDimitry Andric   }
61860b57cec5SDimitry Andric 
61870b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
61880b57cec5SDimitry Andric     CmdArgs.push_back("-ftabstop");
61890b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
61900b57cec5SDimitry Andric   }
61910b57cec5SDimitry Andric 
6192bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6193bdd1243dSDimitry Andric                     options::OPT_fno_stack_size_section);
61940b57cec5SDimitry Andric 
6195fe6060f1SDimitry Andric   if (Args.hasArg(options::OPT_fstack_usage)) {
6196fe6060f1SDimitry Andric     CmdArgs.push_back("-stack-usage-file");
6197fe6060f1SDimitry Andric 
6198fe6060f1SDimitry Andric     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6199fe6060f1SDimitry Andric       SmallString<128> OutputFilename(OutputOpt->getValue());
6200fe6060f1SDimitry Andric       llvm::sys::path::replace_extension(OutputFilename, "su");
6201fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6202fe6060f1SDimitry Andric     } else
6203fe6060f1SDimitry Andric       CmdArgs.push_back(
6204fe6060f1SDimitry Andric           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6205fe6060f1SDimitry Andric   }
6206fe6060f1SDimitry Andric 
62070b57cec5SDimitry Andric   CmdArgs.push_back("-ferror-limit");
62080b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
62090b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
62100b57cec5SDimitry Andric   else
62110b57cec5SDimitry Andric     CmdArgs.push_back("19");
62120b57cec5SDimitry Andric 
621306c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
621406c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
621506c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
621606c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
621706c3fb27SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
62180b57cec5SDimitry Andric 
62190b57cec5SDimitry Andric   // Pass -fmessage-length=.
62205ffd83dbSDimitry Andric   unsigned MessageLength = 0;
62210b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
62225ffd83dbSDimitry Andric     StringRef V(A->getValue());
62235ffd83dbSDimitry Andric     if (V.getAsInteger(0, MessageLength))
62245ffd83dbSDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
62255ffd83dbSDimitry Andric           << V << A->getOption().getName();
62260b57cec5SDimitry Andric   } else {
62270b57cec5SDimitry Andric     // If -fmessage-length=N was not specified, determine whether this is a
62280b57cec5SDimitry Andric     // terminal and, if so, implicitly define -fmessage-length appropriately.
62295ffd83dbSDimitry Andric     MessageLength = llvm::sys::Process::StandardErrColumns();
62300b57cec5SDimitry Andric   }
62315ffd83dbSDimitry Andric   if (MessageLength != 0)
62325ffd83dbSDimitry Andric     CmdArgs.push_back(
62335ffd83dbSDimitry Andric         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
62340b57cec5SDimitry Andric 
623581ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
623681ad6265SDimitry Andric     CmdArgs.push_back(
623781ad6265SDimitry Andric         Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
623881ad6265SDimitry Andric 
623981ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
624081ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
624181ad6265SDimitry Andric                                          Twine(A->getValue(0))));
624281ad6265SDimitry Andric 
62430b57cec5SDimitry Andric   // -fvisibility= and -fvisibility-ms-compat are of a piece.
62440b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
62450b57cec5SDimitry Andric                                      options::OPT_fvisibility_ms_compat)) {
62460b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6247bdd1243dSDimitry Andric       A->render(Args, CmdArgs);
62480b57cec5SDimitry Andric     } else {
62490b57cec5SDimitry Andric       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6250bdd1243dSDimitry Andric       CmdArgs.push_back("-fvisibility=hidden");
6251bdd1243dSDimitry Andric       CmdArgs.push_back("-ftype-visibility=default");
62520b57cec5SDimitry Andric     }
625304eeddc0SDimitry Andric   } else if (IsOpenMPDevice) {
625404eeddc0SDimitry Andric     // When compiling for the OpenMP device we want protected visibility by
6255bdd1243dSDimitry Andric     // default. This prevents the device from accidentally preempting code on
6256bdd1243dSDimitry Andric     // the host, makes the system more robust, and improves performance.
6257bdd1243dSDimitry Andric     CmdArgs.push_back("-fvisibility=protected");
62580b57cec5SDimitry Andric   }
62590b57cec5SDimitry Andric 
6260bdd1243dSDimitry Andric   // PS4/PS5 process these options in addClangTargetOptions.
6261bdd1243dSDimitry Andric   if (!RawTriple.isPS()) {
6262e8d8bef9SDimitry Andric     if (const Arg *A =
6263e8d8bef9SDimitry Andric             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6264e8d8bef9SDimitry Andric                             options::OPT_fno_visibility_from_dllstorageclass)) {
6265e8d8bef9SDimitry Andric       if (A->getOption().matches(
6266e8d8bef9SDimitry Andric               options::OPT_fvisibility_from_dllstorageclass)) {
6267e8d8bef9SDimitry Andric         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6268e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6269e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6270e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6271e8d8bef9SDimitry Andric         Args.AddLastArg(CmdArgs,
6272e8d8bef9SDimitry Andric                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6273e8d8bef9SDimitry Andric       }
6274e8d8bef9SDimitry Andric     }
6275bdd1243dSDimitry Andric   }
6276e8d8bef9SDimitry Andric 
6277fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6278fe6060f1SDimitry Andric                     options::OPT_fno_visibility_inlines_hidden, false))
6279fe6060f1SDimitry Andric     CmdArgs.push_back("-fvisibility-inlines-hidden");
6280fe6060f1SDimitry Andric 
6281e8d8bef9SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6282e8d8bef9SDimitry Andric                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
62830b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
62840b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
62850b57cec5SDimitry Andric 
62864824e7fdSDimitry Andric   if (Args.hasFlag(options::OPT_fnew_infallible,
62874824e7fdSDimitry Andric                    options::OPT_fno_new_infallible, false))
62884824e7fdSDimitry Andric     CmdArgs.push_back("-fnew-infallible");
62894824e7fdSDimitry Andric 
6290fe6060f1SDimitry Andric   if (Args.hasFlag(options::OPT_fno_operator_names,
6291fe6060f1SDimitry Andric                    options::OPT_foperator_names, false))
6292fe6060f1SDimitry Andric     CmdArgs.push_back("-fno-operator-names");
6293fe6060f1SDimitry Andric 
62940b57cec5SDimitry Andric   // Forward -f (flag) options which we can pass directly.
62950b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
62960b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
62970b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
629881ad6265SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
629981ad6265SDimitry Andric 
630006c3fb27SDimitry Andric   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
630106c3fb27SDimitry Andric                    Triple.hasDefaultEmulatedTLS()))
630206c3fb27SDimitry Andric     CmdArgs.push_back("-femulated-tls");
630306c3fb27SDimitry Andric 
630406c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
630506c3fb27SDimitry Andric                     options::OPT_fno_check_new);
630606c3fb27SDimitry Andric 
630781ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
630881ad6265SDimitry Andric     // FIXME: There's no reason for this to be restricted to X86. The backend
630981ad6265SDimitry Andric     // code needs to be changed to include the appropriate function calls
631081ad6265SDimitry Andric     // automatically.
631181ad6265SDimitry Andric     if (!Triple.isX86() && !Triple.isAArch64())
631281ad6265SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
631381ad6265SDimitry Andric           << A->getAsString(Args) << TripleStr;
631481ad6265SDimitry Andric   }
63150b57cec5SDimitry Andric 
63160b57cec5SDimitry Andric   // AltiVec-like language extensions aren't relevant for assembling.
63170b57cec5SDimitry Andric   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
63180b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
63190b57cec5SDimitry Andric 
63200b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
63210b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
63220b57cec5SDimitry Andric 
63230b57cec5SDimitry Andric   // Forward flags for OpenMP. We don't do this if the current action is an
63240b57cec5SDimitry Andric   // device offloading action other than OpenMP.
63250b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
63260b57cec5SDimitry Andric                    options::OPT_fno_openmp, false) &&
63270b57cec5SDimitry Andric       (JA.isDeviceOffloading(Action::OFK_None) ||
63280b57cec5SDimitry Andric        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
63290b57cec5SDimitry Andric     switch (D.getOpenMPRuntime(Args)) {
63300b57cec5SDimitry Andric     case Driver::OMPRT_OMP:
63310b57cec5SDimitry Andric     case Driver::OMPRT_IOMP5:
63320b57cec5SDimitry Andric       // Clang can generate useful OpenMP code for these two runtime libraries.
63330b57cec5SDimitry Andric       CmdArgs.push_back("-fopenmp");
63340b57cec5SDimitry Andric 
63350b57cec5SDimitry Andric       // If no option regarding the use of TLS in OpenMP codegeneration is
63360b57cec5SDimitry Andric       // given, decide a default based on the target. Otherwise rely on the
63370b57cec5SDimitry Andric       // options and pass the right information to the frontend.
63380b57cec5SDimitry Andric       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
63390b57cec5SDimitry Andric                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
63400b57cec5SDimitry Andric         CmdArgs.push_back("-fnoopenmp-use-tls");
63410b57cec5SDimitry Andric       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
63420b57cec5SDimitry Andric                       options::OPT_fno_openmp_simd);
6343480093f4SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
63440b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6345349cc55cSDimitry Andric       if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6346349cc55cSDimitry Andric                         options::OPT_fno_openmp_extensions, /*Default=*/true))
6347349cc55cSDimitry Andric         CmdArgs.push_back("-fno-openmp-extensions");
63480b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
63490b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
63500b57cec5SDimitry Andric       Args.AddAllArgs(CmdArgs,
63510b57cec5SDimitry Andric                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
63520b57cec5SDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
63530b57cec5SDimitry Andric                        options::OPT_fno_openmp_optimistic_collapse,
63540b57cec5SDimitry Andric                        /*Default=*/false))
63550b57cec5SDimitry Andric         CmdArgs.push_back("-fopenmp-optimistic-collapse");
63560b57cec5SDimitry Andric 
63570b57cec5SDimitry Andric       // When in OpenMP offloading mode with NVPTX target, forward
63580b57cec5SDimitry Andric       // cuda-mode flag
63590b57cec5SDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
63600b57cec5SDimitry Andric                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
63610b57cec5SDimitry Andric         CmdArgs.push_back("-fopenmp-cuda-mode");
63620b57cec5SDimitry Andric 
6363349cc55cSDimitry Andric       // When in OpenMP offloading mode, enable debugging on the device.
6364349cc55cSDimitry Andric       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6365349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6366349cc55cSDimitry Andric                        options::OPT_fno_openmp_target_debug, /*Default=*/false))
6367349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-target-debug");
6368349cc55cSDimitry Andric 
6369349cc55cSDimitry Andric       // When in OpenMP offloading mode, forward assumptions information about
6370349cc55cSDimitry Andric       // thread and team counts in the device.
6371349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6372349cc55cSDimitry Andric                        options::OPT_fno_openmp_assume_teams_oversubscription,
6373349cc55cSDimitry Andric                        /*Default=*/false))
6374349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6375349cc55cSDimitry Andric       if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6376349cc55cSDimitry Andric                        options::OPT_fno_openmp_assume_threads_oversubscription,
6377349cc55cSDimitry Andric                        /*Default=*/false))
6378349cc55cSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
637981ad6265SDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
638081ad6265SDimitry Andric         CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6381bdd1243dSDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6382bdd1243dSDimitry Andric         CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
638381ad6265SDimitry Andric       if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
638481ad6265SDimitry Andric         CmdArgs.push_back("-fopenmp-offload-mandatory");
63850b57cec5SDimitry Andric       break;
63860b57cec5SDimitry Andric     default:
63870b57cec5SDimitry Andric       // By default, if Clang doesn't know how to generate useful OpenMP code
63880b57cec5SDimitry Andric       // for a specific runtime library, we just don't pass the '-fopenmp' flag
63890b57cec5SDimitry Andric       // down to the actual compilation.
63900b57cec5SDimitry Andric       // FIXME: It would be better to have a mode which *only* omits IR
63910b57cec5SDimitry Andric       // generation based on the OpenMP support so that we get consistent
63920b57cec5SDimitry Andric       // semantic analysis, etc.
63930b57cec5SDimitry Andric       break;
63940b57cec5SDimitry Andric     }
63950b57cec5SDimitry Andric   } else {
63960b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
63970b57cec5SDimitry Andric                     options::OPT_fno_openmp_simd);
63980b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
639981ad6265SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
640081ad6265SDimitry Andric                        options::OPT_fno_openmp_extensions);
64010b57cec5SDimitry Andric   }
64020b57cec5SDimitry Andric 
640381ad6265SDimitry Andric   // Forward the new driver to change offloading code generation.
6404bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_offload_new_driver,
6405bdd1243dSDimitry Andric                    options::OPT_no_offload_new_driver, false))
640681ad6265SDimitry Andric     CmdArgs.push_back("--offload-new-driver");
640781ad6265SDimitry Andric 
6408349cc55cSDimitry Andric   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
64090b57cec5SDimitry Andric 
64100b57cec5SDimitry Andric   const XRayArgs &XRay = TC.getXRayArgs();
64110b57cec5SDimitry Andric   XRay.addArgs(TC, Args, CmdArgs, InputType);
64120b57cec5SDimitry Andric 
6413e8d8bef9SDimitry Andric   for (const auto &Filename :
6414e8d8bef9SDimitry Andric        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6415e8d8bef9SDimitry Andric     if (D.getVFS().exists(Filename))
6416e8d8bef9SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6417e8d8bef9SDimitry Andric     else
6418e8d8bef9SDimitry Andric       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6419e8d8bef9SDimitry Andric   }
6420e8d8bef9SDimitry Andric 
6421480093f4SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6422480093f4SDimitry Andric     StringRef S0 = A->getValue(), S = S0;
642355e4f9d5SDimitry Andric     unsigned Size, Offset = 0;
642406c3fb27SDimitry Andric     if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
642506c3fb27SDimitry Andric         !Triple.isX86())
6426480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6427480093f4SDimitry Andric           << A->getAsString(Args) << TripleStr;
6428480093f4SDimitry Andric     else if (S.consumeInteger(10, Size) ||
6429480093f4SDimitry Andric              (!S.empty() && (!S.consume_front(",") ||
643055e4f9d5SDimitry Andric                              S.consumeInteger(10, Offset) || !S.empty())))
6431480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_argument_to_option)
6432480093f4SDimitry Andric           << S0 << A->getOption().getName();
643355e4f9d5SDimitry Andric     else if (Size < Offset)
6434480093f4SDimitry Andric       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
643555e4f9d5SDimitry Andric     else {
6436480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
643755e4f9d5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
643855e4f9d5SDimitry Andric           "-fpatchable-function-entry-offset=" + Twine(Offset)));
643955e4f9d5SDimitry Andric     }
6440480093f4SDimitry Andric   }
6441480093f4SDimitry Andric 
644204eeddc0SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
644304eeddc0SDimitry Andric 
6444480093f4SDimitry Andric   if (TC.SupportsProfiling()) {
64450b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_pg);
64460b57cec5SDimitry Andric 
6447480093f4SDimitry Andric     llvm::Triple::ArchType Arch = TC.getArch();
6448480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6449480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6450480093f4SDimitry Andric         A->render(Args, CmdArgs);
6451480093f4SDimitry Andric       else
6452480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6453480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6454480093f4SDimitry Andric     }
6455480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6456480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz)
6457480093f4SDimitry Andric         A->render(Args, CmdArgs);
6458480093f4SDimitry Andric       else
6459480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6460480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6461480093f4SDimitry Andric     }
6462480093f4SDimitry Andric     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6463480093f4SDimitry Andric       if (Arch == llvm::Triple::systemz)
6464480093f4SDimitry Andric         A->render(Args, CmdArgs);
6465480093f4SDimitry Andric       else
6466480093f4SDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
6467480093f4SDimitry Andric             << A->getAsString(Args) << TripleStr;
6468480093f4SDimitry Andric     }
6469480093f4SDimitry Andric   }
647006c3fb27SDimitry Andric 
647106c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
647206c3fb27SDimitry Andric     if (TC.getTriple().isOSzOS()) {
6473bdd1243dSDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
6474bdd1243dSDimitry Andric           << A->getAsString(Args) << TripleStr;
6475bdd1243dSDimitry Andric     }
6476bdd1243dSDimitry Andric   }
647706c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
647806c3fb27SDimitry Andric     if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
647906c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
648006c3fb27SDimitry Andric           << A->getAsString(Args) << TripleStr;
648106c3fb27SDimitry Andric     }
648206c3fb27SDimitry Andric   }
648306c3fb27SDimitry Andric   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
648406c3fb27SDimitry Andric     if (A->getOption().matches(options::OPT_p)) {
648506c3fb27SDimitry Andric       A->claim();
648606c3fb27SDimitry Andric       if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
648706c3fb27SDimitry Andric         CmdArgs.push_back("-pg");
648806c3fb27SDimitry Andric     }
648906c3fb27SDimitry Andric   }
649006c3fb27SDimitry Andric 
649106c3fb27SDimitry Andric   // Reject AIX-specific link options on other targets.
649206c3fb27SDimitry Andric   if (!TC.getTriple().isOSAIX()) {
649306c3fb27SDimitry Andric     for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
649406c3fb27SDimitry Andric                                       options::OPT_mxcoff_build_id_EQ)) {
649506c3fb27SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
649606c3fb27SDimitry Andric           << A->getSpelling() << TripleStr;
649706c3fb27SDimitry Andric     }
649806c3fb27SDimitry Andric   }
64990b57cec5SDimitry Andric 
65000b57cec5SDimitry Andric   if (Args.getLastArg(options::OPT_fapple_kext) ||
65010b57cec5SDimitry Andric       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
65020b57cec5SDimitry Andric     CmdArgs.push_back("-fapple-kext");
65030b57cec5SDimitry Andric 
6504fe6060f1SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6505a7dea167SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
65060b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
65070b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
65080b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
65090b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6510e8d8bef9SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
65110b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
65120b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6513480093f4SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
65140b57cec5SDimitry Andric 
651506c3fb27SDimitry Andric   if (const char *Name = C.getTimeTraceFile(&JA)) {
651606c3fb27SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
651706c3fb27SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
651806c3fb27SDimitry Andric   }
651906c3fb27SDimitry Andric 
65200b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
65210b57cec5SDimitry Andric     CmdArgs.push_back("-ftrapv-handler");
65220b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
65230b57cec5SDimitry Andric   }
65240b57cec5SDimitry Andric 
65250b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
65260b57cec5SDimitry Andric 
65270b57cec5SDimitry Andric   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
65280b57cec5SDimitry Andric   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
65290b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
65300b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fwrapv))
65310b57cec5SDimitry Andric       CmdArgs.push_back("-fwrapv");
65320b57cec5SDimitry Andric   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
65330b57cec5SDimitry Andric                                       options::OPT_fno_strict_overflow)) {
65340b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fno_strict_overflow))
65350b57cec5SDimitry Andric       CmdArgs.push_back("-fwrapv");
65360b57cec5SDimitry Andric   }
65370b57cec5SDimitry Andric 
65380b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
65390b57cec5SDimitry Andric                                options::OPT_fno_reroll_loops))
65400b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_freroll_loops))
65410b57cec5SDimitry Andric       CmdArgs.push_back("-freroll-loops");
65420b57cec5SDimitry Andric 
6543d409305fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6544d409305fSDimitry Andric                   options::OPT_fno_finite_loops);
6545d409305fSDimitry Andric 
65460b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
65470b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
65480b57cec5SDimitry Andric                   options::OPT_fno_unroll_loops);
65490b57cec5SDimitry Andric 
6550fcaf7f86SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6551fcaf7f86SDimitry Andric 
65520b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_pthread);
65530b57cec5SDimitry Andric 
6554bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6555bdd1243dSDimitry Andric                     options::OPT_mno_speculative_load_hardening);
65560b57cec5SDimitry Andric 
6557e8d8bef9SDimitry Andric   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
65585ffd83dbSDimitry Andric   RenderSCPOptions(TC, Args, CmdArgs);
65590b57cec5SDimitry Andric   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
65600b57cec5SDimitry Andric 
6561349cc55cSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6562349cc55cSDimitry Andric 
6563bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6564bdd1243dSDimitry Andric                     options::OPT_mno_stackrealign);
65650b57cec5SDimitry Andric 
65660b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_mstack_alignment)) {
65670b57cec5SDimitry Andric     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
65680b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
65690b57cec5SDimitry Andric   }
65700b57cec5SDimitry Andric 
65710b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_mstack_probe_size)) {
65720b57cec5SDimitry Andric     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
65730b57cec5SDimitry Andric 
65740b57cec5SDimitry Andric     if (!Size.empty())
65750b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
65760b57cec5SDimitry Andric     else
65770b57cec5SDimitry Andric       CmdArgs.push_back("-mstack-probe-size=0");
65780b57cec5SDimitry Andric   }
65790b57cec5SDimitry Andric 
658081ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
658181ad6265SDimitry Andric                      options::OPT_mno_stack_arg_probe);
65820b57cec5SDimitry Andric 
65830b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
65840b57cec5SDimitry Andric                                options::OPT_mno_restrict_it)) {
65850b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_mrestrict_it)) {
65860b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
65870b57cec5SDimitry Andric       CmdArgs.push_back("-arm-restrict-it");
65880b57cec5SDimitry Andric     } else {
65890b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
659081ad6265SDimitry Andric       CmdArgs.push_back("-arm-default-it");
65910b57cec5SDimitry Andric     }
65920b57cec5SDimitry Andric   }
65930b57cec5SDimitry Andric 
65940b57cec5SDimitry Andric   // Forward -cl options to -cc1
6595fe6060f1SDimitry Andric   RenderOpenCLOptions(Args, CmdArgs, InputType);
65960b57cec5SDimitry Andric 
659781ad6265SDimitry Andric   // Forward hlsl options to -cc1
659881ad6265SDimitry Andric   RenderHLSLOptions(Args, CmdArgs, InputType);
659981ad6265SDimitry Andric 
66005f757f3fSDimitry Andric   // Forward OpenACC options to -cc1
66015f757f3fSDimitry Andric   RenderOpenACCOptions(D, Args, CmdArgs, InputType);
66025f757f3fSDimitry Andric 
6603e8d8bef9SDimitry Andric   if (IsHIP) {
6604e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
66055ffd83dbSDimitry Andric                      options::OPT_fno_hip_new_launch_api, true))
6606a7dea167SDimitry Andric       CmdArgs.push_back("-fhip-new-launch-api");
66075f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
66085f757f3fSDimitry Andric                       options::OPT_fno_gpu_allow_device_init);
66095f757f3fSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
66105f757f3fSDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
661181ad6265SDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
661281ad6265SDimitry Andric                       options::OPT_fno_hip_kernel_arg_name);
6613e8d8bef9SDimitry Andric   }
6614e8d8bef9SDimitry Andric 
6615e8d8bef9SDimitry Andric   if (IsCuda || IsHIP) {
6616753f127fSDimitry Andric     if (IsRDCMode)
6617fe6060f1SDimitry Andric       CmdArgs.push_back("-fgpu-rdc");
66185f757f3fSDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
66195f757f3fSDimitry Andric                       options::OPT_fno_gpu_defer_diag);
6620e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6621e8d8bef9SDimitry Andric                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
6622e8d8bef9SDimitry Andric                      false)) {
6623e8d8bef9SDimitry Andric       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6624e8d8bef9SDimitry Andric       CmdArgs.push_back("-fgpu-defer-diag");
6625e8d8bef9SDimitry Andric     }
6626e8d8bef9SDimitry Andric   }
6627a7dea167SDimitry Andric 
662881ad6265SDimitry Andric   // Forward -nogpulib to -cc1.
662981ad6265SDimitry Andric   if (Args.hasArg(options::OPT_nogpulib))
663081ad6265SDimitry Andric     CmdArgs.push_back("-nogpulib");
663181ad6265SDimitry Andric 
66320b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
66330b57cec5SDimitry Andric     CmdArgs.push_back(
66340b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
66350b57cec5SDimitry Andric   }
66360b57cec5SDimitry Andric 
6637753f127fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6638753f127fSDimitry Andric     CmdArgs.push_back(
6639753f127fSDimitry Andric         Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6640753f127fSDimitry Andric 
6641bdd1243dSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6642bdd1243dSDimitry Andric 
6643fe6060f1SDimitry Andric   // Forward -f options with positive and negative forms; we translate these by
6644fe6060f1SDimitry Andric   // hand.  Do not propagate PGO options to the GPU-side compilations as the
6645fe6060f1SDimitry Andric   // profile info is for the host-side compilation only.
6646fe6060f1SDimitry Andric   if (!(IsCudaDevice || IsHIPDevice)) {
66470b57cec5SDimitry Andric     if (Arg *A = getLastProfileSampleUseArg(Args)) {
66480b57cec5SDimitry Andric       auto *PGOArg = Args.getLastArg(
66490b57cec5SDimitry Andric           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6650fe6060f1SDimitry Andric           options::OPT_fcs_profile_generate,
6651fe6060f1SDimitry Andric           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6652fe6060f1SDimitry Andric           options::OPT_fprofile_use_EQ);
66530b57cec5SDimitry Andric       if (PGOArg)
66540b57cec5SDimitry Andric         D.Diag(diag::err_drv_argument_not_allowed_with)
66550b57cec5SDimitry Andric             << "SampleUse with PGO options";
66560b57cec5SDimitry Andric 
66570b57cec5SDimitry Andric       StringRef fname = A->getValue();
66580b57cec5SDimitry Andric       if (!llvm::sys::fs::exists(fname))
66590b57cec5SDimitry Andric         D.Diag(diag::err_drv_no_such_file) << fname;
66600b57cec5SDimitry Andric       else
66610b57cec5SDimitry Andric         A->render(Args, CmdArgs);
66620b57cec5SDimitry Andric     }
66630b57cec5SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
66640b57cec5SDimitry Andric 
6665e8d8bef9SDimitry Andric     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6666fe6060f1SDimitry Andric                      options::OPT_fno_pseudo_probe_for_profiling, false)) {
6667e8d8bef9SDimitry Andric       CmdArgs.push_back("-fpseudo-probe-for-profiling");
6668fe6060f1SDimitry Andric       // Enforce -funique-internal-linkage-names if it's not explicitly turned
6669fe6060f1SDimitry Andric       // off.
6670fe6060f1SDimitry Andric       if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6671fe6060f1SDimitry Andric                        options::OPT_fno_unique_internal_linkage_names, true))
6672fe6060f1SDimitry Andric         CmdArgs.push_back("-funique-internal-linkage-names");
6673fe6060f1SDimitry Andric     }
6674fe6060f1SDimitry Andric   }
66750b57cec5SDimitry Andric   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
66760b57cec5SDimitry Andric 
667781ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
667881ad6265SDimitry Andric                      options::OPT_fno_assume_sane_operator_new);
66790b57cec5SDimitry Andric 
66805f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
66815f757f3fSDimitry Andric     CmdArgs.push_back("-fapinotes");
66825f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fapinotes_modules,
66835f757f3fSDimitry Andric                    options::OPT_fno_apinotes_modules, false))
66845f757f3fSDimitry Andric     CmdArgs.push_back("-fapinotes-modules");
66855f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
66865f757f3fSDimitry Andric 
66870b57cec5SDimitry Andric   // -fblocks=0 is default.
66880b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
66890b57cec5SDimitry Andric                    TC.IsBlocksDefault()) ||
66900b57cec5SDimitry Andric       (Args.hasArg(options::OPT_fgnu_runtime) &&
66910b57cec5SDimitry Andric        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
66920b57cec5SDimitry Andric        !Args.hasArg(options::OPT_fno_blocks))) {
66930b57cec5SDimitry Andric     CmdArgs.push_back("-fblocks");
66940b57cec5SDimitry Andric 
66950b57cec5SDimitry Andric     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
66960b57cec5SDimitry Andric       CmdArgs.push_back("-fblocks-runtime-optional");
66970b57cec5SDimitry Andric   }
66980b57cec5SDimitry Andric 
66990b57cec5SDimitry Andric   // -fencode-extended-block-signature=1 is default.
67000b57cec5SDimitry Andric   if (TC.IsEncodeExtendedBlockSignatureDefault())
67010b57cec5SDimitry Andric     CmdArgs.push_back("-fencode-extended-block-signature");
67020b57cec5SDimitry Andric 
6703bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
6704bdd1243dSDimitry Andric                    options::OPT_fno_coro_aligned_allocation, false) &&
6705bdd1243dSDimitry Andric       types::isCXX(InputType))
6706bdd1243dSDimitry Andric     CmdArgs.push_back("-fcoro-aligned-allocation");
6707bdd1243dSDimitry Andric 
67080b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
67090b57cec5SDimitry Andric                   options::OPT_fno_double_square_bracket_attributes);
67100b57cec5SDimitry Andric 
671181ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
671281ad6265SDimitry Andric                      options::OPT_fno_access_control);
671381ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
671481ad6265SDimitry Andric                      options::OPT_fno_elide_constructors);
67150b57cec5SDimitry Andric 
67160b57cec5SDimitry Andric   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
67170b57cec5SDimitry Andric 
67180b57cec5SDimitry Andric   if (KernelOrKext || (types::isCXX(InputType) &&
67190b57cec5SDimitry Andric                        (RTTIMode == ToolChain::RM_Disabled)))
67200b57cec5SDimitry Andric     CmdArgs.push_back("-fno-rtti");
67210b57cec5SDimitry Andric 
6722e8d8bef9SDimitry Andric   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
67230b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6724e8d8bef9SDimitry Andric                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
67250b57cec5SDimitry Andric     CmdArgs.push_back("-fshort-enums");
67260b57cec5SDimitry Andric 
67270b57cec5SDimitry Andric   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
67280b57cec5SDimitry Andric 
67290b57cec5SDimitry Andric   // -fuse-cxa-atexit is default.
67300b57cec5SDimitry Andric   if (!Args.hasFlag(
67310b57cec5SDimitry Andric           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
67325ffd83dbSDimitry Andric           !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
67330b57cec5SDimitry Andric               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
67340b57cec5SDimitry Andric                RawTriple.hasEnvironment())) ||
67350b57cec5SDimitry Andric       KernelOrKext)
67360b57cec5SDimitry Andric     CmdArgs.push_back("-fno-use-cxa-atexit");
67370b57cec5SDimitry Andric 
67380b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
67390b57cec5SDimitry Andric                    options::OPT_fno_register_global_dtors_with_atexit,
67400b57cec5SDimitry Andric                    RawTriple.isOSDarwin() && !KernelOrKext))
67410b57cec5SDimitry Andric     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
67420b57cec5SDimitry Andric 
674381ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
674481ad6265SDimitry Andric                     options::OPT_fno_use_line_directives);
67450b57cec5SDimitry Andric 
6746349cc55cSDimitry Andric   // -fno-minimize-whitespace is default.
6747349cc55cSDimitry Andric   if (Args.hasFlag(options::OPT_fminimize_whitespace,
6748349cc55cSDimitry Andric                    options::OPT_fno_minimize_whitespace, false)) {
6749349cc55cSDimitry Andric     types::ID InputType = Inputs[0].getType();
6750349cc55cSDimitry Andric     if (!isDerivedFromC(InputType))
67515f757f3fSDimitry Andric       D.Diag(diag::err_drv_opt_unsupported_input_type)
67525f757f3fSDimitry Andric           << "-fminimize-whitespace" << types::getTypeName(InputType);
6753349cc55cSDimitry Andric     CmdArgs.push_back("-fminimize-whitespace");
6754349cc55cSDimitry Andric   }
6755349cc55cSDimitry Andric 
67565f757f3fSDimitry Andric   // -fno-keep-system-includes is default.
67575f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fkeep_system_includes,
67585f757f3fSDimitry Andric                    options::OPT_fno_keep_system_includes, false)) {
67595f757f3fSDimitry Andric     types::ID InputType = Inputs[0].getType();
67605f757f3fSDimitry Andric     if (!isDerivedFromC(InputType))
67615f757f3fSDimitry Andric       D.Diag(diag::err_drv_opt_unsupported_input_type)
67625f757f3fSDimitry Andric           << "-fkeep-system-includes" << types::getTypeName(InputType);
67635f757f3fSDimitry Andric     CmdArgs.push_back("-fkeep-system-includes");
67645f757f3fSDimitry Andric   }
67655f757f3fSDimitry Andric 
67665ffd83dbSDimitry Andric   // -fms-extensions=0 is default.
67675ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
67685ffd83dbSDimitry Andric                    IsWindowsMSVC))
67695ffd83dbSDimitry Andric     CmdArgs.push_back("-fms-extensions");
67705ffd83dbSDimitry Andric 
67710b57cec5SDimitry Andric   // -fms-compatibility=0 is default.
6772a7dea167SDimitry Andric   bool IsMSVCCompat = Args.hasFlag(
6773a7dea167SDimitry Andric       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6774a7dea167SDimitry Andric       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6775a7dea167SDimitry Andric                                      options::OPT_fno_ms_extensions, true)));
6776a7dea167SDimitry Andric   if (IsMSVCCompat)
67770b57cec5SDimitry Andric     CmdArgs.push_back("-fms-compatibility");
67780b57cec5SDimitry Andric 
6779bdd1243dSDimitry Andric   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
6780bdd1243dSDimitry Andric       Args.hasArg(options::OPT_fms_runtime_lib_EQ))
6781bdd1243dSDimitry Andric     ProcessVSRuntimeLibrary(Args, CmdArgs);
6782bdd1243dSDimitry Andric 
6783a7dea167SDimitry Andric   // Handle -fgcc-version, if present.
6784a7dea167SDimitry Andric   VersionTuple GNUCVer;
6785a7dea167SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6786a7dea167SDimitry Andric     // Check that the version has 1 to 3 components and the minor and patch
6787a7dea167SDimitry Andric     // versions fit in two decimal digits.
6788a7dea167SDimitry Andric     StringRef Val = A->getValue();
6789a7dea167SDimitry Andric     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6790a7dea167SDimitry Andric     bool Invalid = GNUCVer.tryParse(Val);
679181ad6265SDimitry Andric     unsigned Minor = GNUCVer.getMinor().value_or(0);
679281ad6265SDimitry Andric     unsigned Patch = GNUCVer.getSubminor().value_or(0);
6793a7dea167SDimitry Andric     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6794a7dea167SDimitry Andric       D.Diag(diag::err_drv_invalid_value)
6795a7dea167SDimitry Andric           << A->getAsString(Args) << A->getValue();
6796a7dea167SDimitry Andric     }
6797a7dea167SDimitry Andric   } else if (!IsMSVCCompat) {
6798a7dea167SDimitry Andric     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6799a7dea167SDimitry Andric     GNUCVer = VersionTuple(4, 2, 1);
6800a7dea167SDimitry Andric   }
6801a7dea167SDimitry Andric   if (!GNUCVer.empty()) {
6802a7dea167SDimitry Andric     CmdArgs.push_back(
6803a7dea167SDimitry Andric         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6804a7dea167SDimitry Andric   }
6805a7dea167SDimitry Andric 
68060b57cec5SDimitry Andric   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
68070b57cec5SDimitry Andric   if (!MSVT.empty())
68080b57cec5SDimitry Andric     CmdArgs.push_back(
68090b57cec5SDimitry Andric         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
68100b57cec5SDimitry Andric 
68110b57cec5SDimitry Andric   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6812fe6060f1SDimitry Andric   if (ImplyVCPPCVer) {
6813fe6060f1SDimitry Andric     StringRef LanguageStandard;
6814fe6060f1SDimitry Andric     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6815fe6060f1SDimitry Andric       Std = StdArg;
6816fe6060f1SDimitry Andric       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6817fe6060f1SDimitry Andric                              .Case("c11", "-std=c11")
6818fe6060f1SDimitry Andric                              .Case("c17", "-std=c17")
6819fe6060f1SDimitry Andric                              .Default("");
6820fe6060f1SDimitry Andric       if (LanguageStandard.empty())
6821fe6060f1SDimitry Andric         D.Diag(clang::diag::warn_drv_unused_argument)
6822fe6060f1SDimitry Andric             << StdArg->getAsString(Args);
6823fe6060f1SDimitry Andric     }
6824fe6060f1SDimitry Andric     CmdArgs.push_back(LanguageStandard.data());
6825fe6060f1SDimitry Andric   }
68260b57cec5SDimitry Andric   if (ImplyVCPPCXXVer) {
68270b57cec5SDimitry Andric     StringRef LanguageStandard;
68280b57cec5SDimitry Andric     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
68290b57cec5SDimitry Andric       Std = StdArg;
68300b57cec5SDimitry Andric       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
68310b57cec5SDimitry Andric                              .Case("c++14", "-std=c++14")
68320b57cec5SDimitry Andric                              .Case("c++17", "-std=c++17")
6833fe6060f1SDimitry Andric                              .Case("c++20", "-std=c++20")
683406c3fb27SDimitry Andric                              // TODO add c++23 and c++26 when MSVC supports it.
683506c3fb27SDimitry Andric                              .Case("c++latest", "-std=c++26")
68360b57cec5SDimitry Andric                              .Default("");
68370b57cec5SDimitry Andric       if (LanguageStandard.empty())
68380b57cec5SDimitry Andric         D.Diag(clang::diag::warn_drv_unused_argument)
68390b57cec5SDimitry Andric             << StdArg->getAsString(Args);
68400b57cec5SDimitry Andric     }
68410b57cec5SDimitry Andric 
68420b57cec5SDimitry Andric     if (LanguageStandard.empty()) {
68430b57cec5SDimitry Andric       if (IsMSVC2015Compatible)
68440b57cec5SDimitry Andric         LanguageStandard = "-std=c++14";
68450b57cec5SDimitry Andric       else
68460b57cec5SDimitry Andric         LanguageStandard = "-std=c++11";
68470b57cec5SDimitry Andric     }
68480b57cec5SDimitry Andric 
68490b57cec5SDimitry Andric     CmdArgs.push_back(LanguageStandard.data());
68500b57cec5SDimitry Andric   }
68510b57cec5SDimitry Andric 
685281ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
685381ad6265SDimitry Andric                     options::OPT_fno_borland_extensions);
68540b57cec5SDimitry Andric 
685581ad6265SDimitry Andric   // -fno-declspec is default, except for PS4/PS5.
68560b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
685781ad6265SDimitry Andric                    RawTriple.isPS()))
68580b57cec5SDimitry Andric     CmdArgs.push_back("-fdeclspec");
68590b57cec5SDimitry Andric   else if (Args.hasArg(options::OPT_fno_declspec))
68600b57cec5SDimitry Andric     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
68610b57cec5SDimitry Andric 
68620b57cec5SDimitry Andric   // -fthreadsafe-static is default, except for MSVC compatibility versions less
68630b57cec5SDimitry Andric   // than 19.
68640b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
68650b57cec5SDimitry Andric                     options::OPT_fno_threadsafe_statics,
6866349cc55cSDimitry Andric                     !types::isOpenCL(InputType) &&
6867349cc55cSDimitry Andric                         (!IsWindowsMSVC || IsMSVC2015Compatible)))
68680b57cec5SDimitry Andric     CmdArgs.push_back("-fno-threadsafe-statics");
68690b57cec5SDimitry Andric 
68700b57cec5SDimitry Andric   // -fgnu-keywords default varies depending on language; only pass if
68710b57cec5SDimitry Andric   // specified.
68720b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
68730b57cec5SDimitry Andric                   options::OPT_fno_gnu_keywords);
68740b57cec5SDimitry Andric 
687581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
687681ad6265SDimitry Andric                     options::OPT_fno_gnu89_inline);
68770b57cec5SDimitry Andric 
687881ad6265SDimitry Andric   const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
68790b57cec5SDimitry Andric                                          options::OPT_finline_hint_functions,
68800b57cec5SDimitry Andric                                          options::OPT_fno_inline_functions);
688181ad6265SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
688281ad6265SDimitry Andric     if (A->getOption().matches(options::OPT_fno_inline))
688381ad6265SDimitry Andric       A->render(Args, CmdArgs);
688481ad6265SDimitry Andric   } else if (InlineArg) {
688581ad6265SDimitry Andric     InlineArg->render(Args, CmdArgs);
688681ad6265SDimitry Andric   }
68870b57cec5SDimitry Andric 
6888bdd1243dSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
6889bdd1243dSDimitry Andric 
68905f757f3fSDimitry Andric   // FIXME: Find a better way to determine whether we are in C++20.
68915f757f3fSDimitry Andric   bool HaveCxx20 =
68925f757f3fSDimitry Andric       Std &&
68935f757f3fSDimitry Andric       (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
68945f757f3fSDimitry Andric        Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
68955f757f3fSDimitry Andric        Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
68965f757f3fSDimitry Andric        Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
68975f757f3fSDimitry Andric        Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
68985f757f3fSDimitry Andric        Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
68995f757f3fSDimitry Andric        Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
69000b57cec5SDimitry Andric   bool HaveModules =
69015f757f3fSDimitry Andric       RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
69025f757f3fSDimitry Andric 
69035f757f3fSDimitry Andric   // -fdelayed-template-parsing is default when targeting MSVC.
69045f757f3fSDimitry Andric   // Many old Windows SDK versions require this to parse.
69055f757f3fSDimitry Andric   //
69065f757f3fSDimitry Andric   // According to
69075f757f3fSDimitry Andric   // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
69085f757f3fSDimitry Andric   // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
69095f757f3fSDimitry Andric   // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
69105f757f3fSDimitry Andric   // not enable -fdelayed-template-parsing by default after C++20.
69115f757f3fSDimitry Andric   //
69125f757f3fSDimitry Andric   // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
69135f757f3fSDimitry Andric   // able to disable this by default at some point.
69145f757f3fSDimitry Andric   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
69155f757f3fSDimitry Andric                    options::OPT_fno_delayed_template_parsing,
69165f757f3fSDimitry Andric                    IsWindowsMSVC && !HaveCxx20)) {
69175f757f3fSDimitry Andric     if (HaveCxx20)
69185f757f3fSDimitry Andric       D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
69195f757f3fSDimitry Andric 
69205f757f3fSDimitry Andric     CmdArgs.push_back("-fdelayed-template-parsing");
69215f757f3fSDimitry Andric   }
69220b57cec5SDimitry Andric 
6923a7dea167SDimitry Andric   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6924a7dea167SDimitry Andric                    options::OPT_fno_pch_validate_input_files_content, false))
6925a7dea167SDimitry Andric     CmdArgs.push_back("-fvalidate-ast-input-files-content");
69265ffd83dbSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
69275ffd83dbSDimitry Andric                    options::OPT_fno_pch_instantiate_templates, false))
69285ffd83dbSDimitry Andric     CmdArgs.push_back("-fpch-instantiate-templates");
6929590d96feSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6930590d96feSDimitry Andric                    false))
6931590d96feSDimitry Andric     CmdArgs.push_back("-fmodules-codegen");
6932590d96feSDimitry Andric   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6933590d96feSDimitry Andric                    false))
6934590d96feSDimitry Andric     CmdArgs.push_back("-fmodules-debuginfo");
6935a7dea167SDimitry Andric 
69365ffd83dbSDimitry Andric   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
69370b57cec5SDimitry Andric   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
69380b57cec5SDimitry Andric                     Input, CmdArgs);
69390b57cec5SDimitry Andric 
6940fe6060f1SDimitry Andric   if (types::isObjC(Input.getType()) &&
6941fe6060f1SDimitry Andric       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6942fe6060f1SDimitry Andric                    options::OPT_fno_objc_encode_cxx_class_template_spec,
6943fe6060f1SDimitry Andric                    !Runtime.isNeXTFamily()))
6944fe6060f1SDimitry Andric     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6945fe6060f1SDimitry Andric 
69460b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fapplication_extension,
69470b57cec5SDimitry Andric                    options::OPT_fno_application_extension, false))
69480b57cec5SDimitry Andric     CmdArgs.push_back("-fapplication-extension");
69490b57cec5SDimitry Andric 
69500b57cec5SDimitry Andric   // Handle GCC-style exception args.
6951fe6060f1SDimitry Andric   bool EH = false;
69520b57cec5SDimitry Andric   if (!C.getDriver().IsCLMode())
6953fe6060f1SDimitry Andric     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
69540b57cec5SDimitry Andric 
69550b57cec5SDimitry Andric   // Handle exception personalities
6956a7dea167SDimitry Andric   Arg *A = Args.getLastArg(
6957a7dea167SDimitry Andric       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6958a7dea167SDimitry Andric       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
69590b57cec5SDimitry Andric   if (A) {
69600b57cec5SDimitry Andric     const Option &Opt = A->getOption();
69610b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fsjlj_exceptions))
6962e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=sjlj");
69630b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fseh_exceptions))
6964e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=seh");
69650b57cec5SDimitry Andric     if (Opt.matches(options::OPT_fdwarf_exceptions))
6966e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=dwarf");
6967a7dea167SDimitry Andric     if (Opt.matches(options::OPT_fwasm_exceptions))
6968e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=wasm");
69690b57cec5SDimitry Andric   } else {
69700b57cec5SDimitry Andric     switch (TC.GetExceptionModel(Args)) {
69710b57cec5SDimitry Andric     default:
69720b57cec5SDimitry Andric       break;
69730b57cec5SDimitry Andric     case llvm::ExceptionHandling::DwarfCFI:
6974e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=dwarf");
69750b57cec5SDimitry Andric       break;
69760b57cec5SDimitry Andric     case llvm::ExceptionHandling::SjLj:
6977e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=sjlj");
69780b57cec5SDimitry Andric       break;
69790b57cec5SDimitry Andric     case llvm::ExceptionHandling::WinEH:
6980e8d8bef9SDimitry Andric       CmdArgs.push_back("-exception-model=seh");
69810b57cec5SDimitry Andric       break;
69820b57cec5SDimitry Andric     }
69830b57cec5SDimitry Andric   }
69840b57cec5SDimitry Andric 
69850b57cec5SDimitry Andric   // C++ "sane" operator new.
698681ad6265SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
698781ad6265SDimitry Andric                      options::OPT_fno_assume_sane_operator_new);
69880b57cec5SDimitry Andric 
698906c3fb27SDimitry Andric   // -fassume-unique-vtables is on by default.
699006c3fb27SDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
699106c3fb27SDimitry Andric                      options::OPT_fno_assume_unique_vtables);
699206c3fb27SDimitry Andric 
69930b57cec5SDimitry Andric   // -frelaxed-template-template-args is off by default, as it is a severe
69940b57cec5SDimitry Andric   // breaking change until a corresponding change to template partial ordering
69950b57cec5SDimitry Andric   // is provided.
699681ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
699781ad6265SDimitry Andric                     options::OPT_fno_relaxed_template_template_args);
69980b57cec5SDimitry Andric 
69990b57cec5SDimitry Andric   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
70000b57cec5SDimitry Andric   // most platforms.
700181ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
700281ad6265SDimitry Andric                     options::OPT_fno_sized_deallocation);
70030b57cec5SDimitry Andric 
70040b57cec5SDimitry Andric   // -faligned-allocation is on by default in C++17 onwards and otherwise off
70050b57cec5SDimitry Andric   // by default.
70060b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
70070b57cec5SDimitry Andric                                options::OPT_fno_aligned_allocation,
70080b57cec5SDimitry Andric                                options::OPT_faligned_new_EQ)) {
70090b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
70100b57cec5SDimitry Andric       CmdArgs.push_back("-fno-aligned-allocation");
70110b57cec5SDimitry Andric     else
70120b57cec5SDimitry Andric       CmdArgs.push_back("-faligned-allocation");
70130b57cec5SDimitry Andric   }
70140b57cec5SDimitry Andric 
70150b57cec5SDimitry Andric   // The default new alignment can be specified using a dedicated option or via
70160b57cec5SDimitry Andric   // a GCC-compatible option that also turns on aligned allocation.
70170b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
70180b57cec5SDimitry Andric                                options::OPT_faligned_new_EQ))
70190b57cec5SDimitry Andric     CmdArgs.push_back(
70200b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
70210b57cec5SDimitry Andric 
70220b57cec5SDimitry Andric   // -fconstant-cfstrings is default, and may be subject to argument translation
70230b57cec5SDimitry Andric   // on Darwin.
70240b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
702581ad6265SDimitry Andric                     options::OPT_fno_constant_cfstrings, true) ||
70260b57cec5SDimitry Andric       !Args.hasFlag(options::OPT_mconstant_cfstrings,
702781ad6265SDimitry Andric                     options::OPT_mno_constant_cfstrings, true))
70280b57cec5SDimitry Andric     CmdArgs.push_back("-fno-constant-cfstrings");
70290b57cec5SDimitry Andric 
703081ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
703181ad6265SDimitry Andric                     options::OPT_fno_pascal_strings);
70320b57cec5SDimitry Andric 
70330b57cec5SDimitry Andric   // Honor -fpack-struct= and -fpack-struct, if given. Note that
70340b57cec5SDimitry Andric   // -fno-pack-struct doesn't apply to -fpack-struct=.
70350b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
70360b57cec5SDimitry Andric     std::string PackStructStr = "-fpack-struct=";
70370b57cec5SDimitry Andric     PackStructStr += A->getValue();
70380b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
70390b57cec5SDimitry Andric   } else if (Args.hasFlag(options::OPT_fpack_struct,
70400b57cec5SDimitry Andric                           options::OPT_fno_pack_struct, false)) {
70410b57cec5SDimitry Andric     CmdArgs.push_back("-fpack-struct=1");
70420b57cec5SDimitry Andric   }
70430b57cec5SDimitry Andric 
70440b57cec5SDimitry Andric   // Handle -fmax-type-align=N and -fno-type-align
70450b57cec5SDimitry Andric   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
70460b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
70470b57cec5SDimitry Andric     if (!SkipMaxTypeAlign) {
70480b57cec5SDimitry Andric       std::string MaxTypeAlignStr = "-fmax-type-align=";
70490b57cec5SDimitry Andric       MaxTypeAlignStr += A->getValue();
70500b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
70510b57cec5SDimitry Andric     }
70520b57cec5SDimitry Andric   } else if (RawTriple.isOSDarwin()) {
70530b57cec5SDimitry Andric     if (!SkipMaxTypeAlign) {
70540b57cec5SDimitry Andric       std::string MaxTypeAlignStr = "-fmax-type-align=16";
70550b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
70560b57cec5SDimitry Andric     }
70570b57cec5SDimitry Andric   }
70580b57cec5SDimitry Andric 
70590b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
70600b57cec5SDimitry Andric     CmdArgs.push_back("-Qn");
70610b57cec5SDimitry Andric 
70625ffd83dbSDimitry Andric   // -fno-common is the default, set -fcommon only when that flag is set.
706381ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
70640b57cec5SDimitry Andric 
70650b57cec5SDimitry Andric   // -fsigned-bitfields is default, and clang doesn't yet support
70660b57cec5SDimitry Andric   // -funsigned-bitfields.
70670b57cec5SDimitry Andric   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
706881ad6265SDimitry Andric                     options::OPT_funsigned_bitfields, true))
70690b57cec5SDimitry Andric     D.Diag(diag::warn_drv_clang_unsupported)
70700b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
70710b57cec5SDimitry Andric 
70720b57cec5SDimitry Andric   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
707381ad6265SDimitry Andric   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
70740b57cec5SDimitry Andric     D.Diag(diag::err_drv_clang_unsupported)
70750b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
70760b57cec5SDimitry Andric 
70770b57cec5SDimitry Andric   // -finput_charset=UTF-8 is default. Reject others
70780b57cec5SDimitry Andric   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
70790b57cec5SDimitry Andric     StringRef value = inputCharset->getValue();
7080fe6060f1SDimitry Andric     if (!value.equals_insensitive("utf-8"))
70810b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
70820b57cec5SDimitry Andric                                           << value;
70830b57cec5SDimitry Andric   }
70840b57cec5SDimitry Andric 
70850b57cec5SDimitry Andric   // -fexec_charset=UTF-8 is default. Reject others
70860b57cec5SDimitry Andric   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
70870b57cec5SDimitry Andric     StringRef value = execCharset->getValue();
7088fe6060f1SDimitry Andric     if (!value.equals_insensitive("utf-8"))
70890b57cec5SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
70900b57cec5SDimitry Andric                                           << value;
70910b57cec5SDimitry Andric   }
70920b57cec5SDimitry Andric 
70930b57cec5SDimitry Andric   RenderDiagnosticsOptions(D, Args, CmdArgs);
70940b57cec5SDimitry Andric 
709581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
709681ad6265SDimitry Andric                     options::OPT_fno_asm_blocks);
70970b57cec5SDimitry Andric 
7098bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7099bdd1243dSDimitry Andric                      options::OPT_fno_gnu_inline_asm);
71000b57cec5SDimitry Andric 
71010b57cec5SDimitry Andric   // Enable vectorization per default according to the optimization level
71020b57cec5SDimitry Andric   // selected. For optimization levels that want vectorization we use the alias
71030b57cec5SDimitry Andric   // option to simplify the hasFlag logic.
71040b57cec5SDimitry Andric   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
71050b57cec5SDimitry Andric   OptSpecifier VectorizeAliasOption =
71060b57cec5SDimitry Andric       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
71070b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
71080b57cec5SDimitry Andric                    options::OPT_fno_vectorize, EnableVec))
71090b57cec5SDimitry Andric     CmdArgs.push_back("-vectorize-loops");
71100b57cec5SDimitry Andric 
71110b57cec5SDimitry Andric   // -fslp-vectorize is enabled based on the optimization level selected.
71120b57cec5SDimitry Andric   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
71130b57cec5SDimitry Andric   OptSpecifier SLPVectAliasOption =
71140b57cec5SDimitry Andric       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
71150b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
71160b57cec5SDimitry Andric                    options::OPT_fno_slp_vectorize, EnableSLPVec))
71170b57cec5SDimitry Andric     CmdArgs.push_back("-vectorize-slp");
71180b57cec5SDimitry Andric 
71190b57cec5SDimitry Andric   ParseMPreferVectorWidth(D, Args, CmdArgs);
71200b57cec5SDimitry Andric 
71210b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
71220b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs,
71230b57cec5SDimitry Andric                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
71240b57cec5SDimitry Andric 
71250b57cec5SDimitry Andric   // -fdollars-in-identifiers default varies depending on platform and
71260b57cec5SDimitry Andric   // language; only pass if specified.
71270b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
71280b57cec5SDimitry Andric                                options::OPT_fno_dollars_in_identifiers)) {
71290b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
71300b57cec5SDimitry Andric       CmdArgs.push_back("-fdollars-in-identifiers");
71310b57cec5SDimitry Andric     else
71320b57cec5SDimitry Andric       CmdArgs.push_back("-fno-dollars-in-identifiers");
71330b57cec5SDimitry Andric   }
71340b57cec5SDimitry Andric 
713581ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
713681ad6265SDimitry Andric                     options::OPT_fno_apple_pragma_pack);
71370b57cec5SDimitry Andric 
71380b57cec5SDimitry Andric   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7139480093f4SDimitry Andric   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7140480093f4SDimitry Andric     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
71410b57cec5SDimitry Andric 
71420b57cec5SDimitry Andric   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
71430b57cec5SDimitry Andric                                      options::OPT_fno_rewrite_imports, false);
71440b57cec5SDimitry Andric   if (RewriteImports)
71450b57cec5SDimitry Andric     CmdArgs.push_back("-frewrite-imports");
71460b57cec5SDimitry Andric 
7147bdd1243dSDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7148bdd1243dSDimitry Andric                     options::OPT_fno_directives_only);
714981ad6265SDimitry Andric 
71500b57cec5SDimitry Andric   // Enable rewrite includes if the user's asked for it or if we're generating
71510b57cec5SDimitry Andric   // diagnostics.
71520b57cec5SDimitry Andric   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
71530b57cec5SDimitry Andric   // nice to enable this when doing a crashdump for modules as well.
71540b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_frewrite_includes,
71550b57cec5SDimitry Andric                    options::OPT_fno_rewrite_includes, false) ||
71560b57cec5SDimitry Andric       (C.isForDiagnostics() && !HaveModules))
71570b57cec5SDimitry Andric     CmdArgs.push_back("-frewrite-includes");
71580b57cec5SDimitry Andric 
71590b57cec5SDimitry Andric   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
71600b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_traditional,
71610b57cec5SDimitry Andric                                options::OPT_traditional_cpp)) {
71620b57cec5SDimitry Andric     if (isa<PreprocessJobAction>(JA))
71630b57cec5SDimitry Andric       CmdArgs.push_back("-traditional-cpp");
71640b57cec5SDimitry Andric     else
71650b57cec5SDimitry Andric       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
71660b57cec5SDimitry Andric   }
71670b57cec5SDimitry Andric 
71680b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dM);
71690b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dD);
717004eeddc0SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_dI);
71710b57cec5SDimitry Andric 
71725ffd83dbSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
71735ffd83dbSDimitry Andric 
71740b57cec5SDimitry Andric   // Handle serialized diagnostics.
71750b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
71760b57cec5SDimitry Andric     CmdArgs.push_back("-serialize-diagnostic-file");
71770b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
71780b57cec5SDimitry Andric   }
71790b57cec5SDimitry Andric 
71800b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
71810b57cec5SDimitry Andric     CmdArgs.push_back("-fretain-comments-from-system-headers");
71820b57cec5SDimitry Andric 
71830b57cec5SDimitry Andric   // Forward -fcomment-block-commands to -cc1.
71840b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
71850b57cec5SDimitry Andric   // Forward -fparse-all-comments to -cc1.
71860b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
71870b57cec5SDimitry Andric 
71880b57cec5SDimitry Andric   // Turn -fplugin=name.so into -load name.so
71890b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
71900b57cec5SDimitry Andric     CmdArgs.push_back("-load");
71910b57cec5SDimitry Andric     CmdArgs.push_back(A->getValue());
71920b57cec5SDimitry Andric     A->claim();
71930b57cec5SDimitry Andric   }
71940b57cec5SDimitry Andric 
71954824e7fdSDimitry Andric   // Turn -fplugin-arg-pluginname-key=value into
71964824e7fdSDimitry Andric   // -plugin-arg-pluginname key=value
71974824e7fdSDimitry Andric   // GCC has an actual plugin_argument struct with key/value pairs that it
71984824e7fdSDimitry Andric   // passes to its plugins, but we don't, so just pass it on as-is.
71994824e7fdSDimitry Andric   //
72004824e7fdSDimitry Andric   // The syntax for -fplugin-arg- is ambiguous if both plugin name and
72014824e7fdSDimitry Andric   // argument key are allowed to contain dashes. GCC therefore only
72024824e7fdSDimitry Andric   // allows dashes in the key. We do the same.
72034824e7fdSDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
72044824e7fdSDimitry Andric     auto ArgValue = StringRef(A->getValue());
72054824e7fdSDimitry Andric     auto FirstDashIndex = ArgValue.find('-');
72064824e7fdSDimitry Andric     StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
72074824e7fdSDimitry Andric     StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
72084824e7fdSDimitry Andric 
72094824e7fdSDimitry Andric     A->claim();
72104824e7fdSDimitry Andric     if (FirstDashIndex == StringRef::npos || Arg.empty()) {
72114824e7fdSDimitry Andric       if (PluginName.empty()) {
72124824e7fdSDimitry Andric         D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
72134824e7fdSDimitry Andric       } else {
72144824e7fdSDimitry Andric         D.Diag(diag::warn_drv_missing_plugin_arg)
72154824e7fdSDimitry Andric             << PluginName << A->getAsString(Args);
72164824e7fdSDimitry Andric       }
72174824e7fdSDimitry Andric       continue;
72184824e7fdSDimitry Andric     }
72194824e7fdSDimitry Andric 
72204824e7fdSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
72214824e7fdSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Arg));
72224824e7fdSDimitry Andric   }
72234824e7fdSDimitry Andric 
72240b57cec5SDimitry Andric   // Forward -fpass-plugin=name.so to -cc1.
72250b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
72260b57cec5SDimitry Andric     CmdArgs.push_back(
72270b57cec5SDimitry Andric         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
72280b57cec5SDimitry Andric     A->claim();
72290b57cec5SDimitry Andric   }
72300b57cec5SDimitry Andric 
723106c3fb27SDimitry Andric   // Forward --vfsoverlay to -cc1.
723206c3fb27SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
723306c3fb27SDimitry Andric     CmdArgs.push_back("--vfsoverlay");
723406c3fb27SDimitry Andric     CmdArgs.push_back(A->getValue());
723506c3fb27SDimitry Andric     A->claim();
723606c3fb27SDimitry Andric   }
723706c3fb27SDimitry Andric 
723806c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
723906c3fb27SDimitry Andric                     options::OPT_fno_safe_buffer_usage_suggestions);
724006c3fb27SDimitry Andric 
72410b57cec5SDimitry Andric   // Setup statistics file output.
72420b57cec5SDimitry Andric   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
724306c3fb27SDimitry Andric   if (!StatsFile.empty()) {
72440b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
724506c3fb27SDimitry Andric     if (D.CCPrintInternalStats)
724606c3fb27SDimitry Andric       CmdArgs.push_back("-stats-file-append");
724706c3fb27SDimitry Andric   }
72480b57cec5SDimitry Andric 
72490b57cec5SDimitry Andric   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
72500b57cec5SDimitry Andric   // parser.
7251bdd1243dSDimitry Andric   for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7252bdd1243dSDimitry Andric     Arg->claim();
72530b57cec5SDimitry Andric     // -finclude-default-header flag is for preprocessor,
72540b57cec5SDimitry Andric     // do not pass it to other cc1 commands when save-temps is enabled
72550b57cec5SDimitry Andric     if (C.getDriver().isSaveTempsEnabled() &&
72560b57cec5SDimitry Andric         !isa<PreprocessJobAction>(JA)) {
7257bdd1243dSDimitry Andric       if (StringRef(Arg->getValue()) == "-finclude-default-header")
7258bdd1243dSDimitry Andric         continue;
7259bdd1243dSDimitry Andric     }
72600b57cec5SDimitry Andric     CmdArgs.push_back(Arg->getValue());
72610b57cec5SDimitry Andric   }
72620b57cec5SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
72630b57cec5SDimitry Andric     A->claim();
72640b57cec5SDimitry Andric 
72650b57cec5SDimitry Andric     // We translate this by hand to the -cc1 argument, since nightly test uses
72660b57cec5SDimitry Andric     // it and developers have been trained to spell it with -mllvm. Both
72670b57cec5SDimitry Andric     // spellings are now deprecated and should be removed.
72680b57cec5SDimitry Andric     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
72690b57cec5SDimitry Andric       CmdArgs.push_back("-disable-llvm-optzns");
72700b57cec5SDimitry Andric     } else {
72710b57cec5SDimitry Andric       A->render(Args, CmdArgs);
72720b57cec5SDimitry Andric     }
72730b57cec5SDimitry Andric   }
72740b57cec5SDimitry Andric 
72750b57cec5SDimitry Andric   // With -save-temps, we want to save the unoptimized bitcode output from the
72760b57cec5SDimitry Andric   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
72770b57cec5SDimitry Andric   // by the frontend.
72780b57cec5SDimitry Andric   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
72790b57cec5SDimitry Andric   // has slightly different breakdown between stages.
72800b57cec5SDimitry Andric   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
72810b57cec5SDimitry Andric   // pristine IR generated by the frontend. Ideally, a new compile action should
72820b57cec5SDimitry Andric   // be added so both IR can be captured.
72835ffd83dbSDimitry Andric   if ((C.getDriver().isSaveTempsEnabled() ||
72845ffd83dbSDimitry Andric        JA.isHostOffloading(Action::OFK_OpenMP)) &&
7285fe6060f1SDimitry Andric       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
72860b57cec5SDimitry Andric       isa<CompileJobAction>(JA))
72870b57cec5SDimitry Andric     CmdArgs.push_back("-disable-llvm-passes");
72880b57cec5SDimitry Andric 
72890b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_undef);
72900b57cec5SDimitry Andric 
72910b57cec5SDimitry Andric   const char *Exec = D.getClangProgramPath();
72920b57cec5SDimitry Andric 
72930b57cec5SDimitry Andric   // Optionally embed the -cc1 level arguments into the debug info or a
72940b57cec5SDimitry Andric   // section, for build analysis.
72950b57cec5SDimitry Andric   // Also record command line arguments into the debug info if
72960b57cec5SDimitry Andric   // -grecord-gcc-switches options is set on.
72970b57cec5SDimitry Andric   // By default, -gno-record-gcc-switches is set on and no recording.
72980b57cec5SDimitry Andric   auto GRecordSwitches =
72990b57cec5SDimitry Andric       Args.hasFlag(options::OPT_grecord_command_line,
73000b57cec5SDimitry Andric                    options::OPT_gno_record_command_line, false);
73010b57cec5SDimitry Andric   auto FRecordSwitches =
73020b57cec5SDimitry Andric       Args.hasFlag(options::OPT_frecord_command_line,
73030b57cec5SDimitry Andric                    options::OPT_fno_record_command_line, false);
730406c3fb27SDimitry Andric   if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
730506c3fb27SDimitry Andric       !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
73060b57cec5SDimitry Andric     D.Diag(diag::err_drv_unsupported_opt_for_target)
73070b57cec5SDimitry Andric         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
73080b57cec5SDimitry Andric         << TripleStr;
73090b57cec5SDimitry Andric   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
73100b57cec5SDimitry Andric     ArgStringList OriginalArgs;
73110b57cec5SDimitry Andric     for (const auto &Arg : Args)
73120b57cec5SDimitry Andric       Arg->render(Args, OriginalArgs);
73130b57cec5SDimitry Andric 
73140b57cec5SDimitry Andric     SmallString<256> Flags;
73155ffd83dbSDimitry Andric     EscapeSpacesAndBackslashes(Exec, Flags);
73160b57cec5SDimitry Andric     for (const char *OriginalArg : OriginalArgs) {
73170b57cec5SDimitry Andric       SmallString<128> EscapedArg;
73180b57cec5SDimitry Andric       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
73190b57cec5SDimitry Andric       Flags += " ";
73200b57cec5SDimitry Andric       Flags += EscapedArg;
73210b57cec5SDimitry Andric     }
73220b57cec5SDimitry Andric     auto FlagsArgString = Args.MakeArgString(Flags);
73230b57cec5SDimitry Andric     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
73240b57cec5SDimitry Andric       CmdArgs.push_back("-dwarf-debug-flags");
73250b57cec5SDimitry Andric       CmdArgs.push_back(FlagsArgString);
73260b57cec5SDimitry Andric     }
73270b57cec5SDimitry Andric     if (FRecordSwitches) {
73280b57cec5SDimitry Andric       CmdArgs.push_back("-record-command-line");
73290b57cec5SDimitry Andric       CmdArgs.push_back(FlagsArgString);
73300b57cec5SDimitry Andric     }
73310b57cec5SDimitry Andric   }
73320b57cec5SDimitry Andric 
7333753f127fSDimitry Andric   // Host-side offloading compilation receives all device-side outputs. Include
7334753f127fSDimitry Andric   // them in the host compilation depending on the target. If the host inputs
7335753f127fSDimitry Andric   // are not empty we use the new-driver scheme, otherwise use the old scheme.
73360b57cec5SDimitry Andric   if ((IsCuda || IsHIP) && CudaDeviceInput) {
73370b57cec5SDimitry Andric     CmdArgs.push_back("-fcuda-include-gpubinary");
73380b57cec5SDimitry Andric     CmdArgs.push_back(CudaDeviceInput->getFilename());
7339753f127fSDimitry Andric   } else if (!HostOffloadingInputs.empty()) {
7340fcaf7f86SDimitry Andric     if ((IsCuda || IsHIP) && !IsRDCMode) {
7341753f127fSDimitry Andric       assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7342753f127fSDimitry Andric       CmdArgs.push_back("-fcuda-include-gpubinary");
7343753f127fSDimitry Andric       CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7344753f127fSDimitry Andric     } else {
7345753f127fSDimitry Andric       for (const InputInfo Input : HostOffloadingInputs)
7346753f127fSDimitry Andric         CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7347753f127fSDimitry Andric                                              TC.getInputFilename(Input)));
7348753f127fSDimitry Andric     }
73490b57cec5SDimitry Andric   }
73500b57cec5SDimitry Andric 
73510b57cec5SDimitry Andric   if (IsCuda) {
73520b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
73530b57cec5SDimitry Andric                      options::OPT_fno_cuda_short_ptr, false))
73540b57cec5SDimitry Andric       CmdArgs.push_back("-fcuda-short-ptr");
73550b57cec5SDimitry Andric   }
73560b57cec5SDimitry Andric 
7357fe6060f1SDimitry Andric   if (IsCuda || IsHIP) {
7358fe6060f1SDimitry Andric     // Determine the original source input.
7359fe6060f1SDimitry Andric     const Action *SourceAction = &JA;
7360fe6060f1SDimitry Andric     while (SourceAction->getKind() != Action::InputClass) {
7361fe6060f1SDimitry Andric       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7362fe6060f1SDimitry Andric       SourceAction = SourceAction->getInputs()[0];
7363fe6060f1SDimitry Andric     }
7364fe6060f1SDimitry Andric     auto CUID = cast<InputAction>(SourceAction)->getId();
7365fe6060f1SDimitry Andric     if (!CUID.empty())
7366fe6060f1SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
73675f757f3fSDimitry Andric 
73685f757f3fSDimitry Andric     // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
73695f757f3fSDimitry Andric     // be overriden by -fno-gpu-approx-transcendentals.
73705f757f3fSDimitry Andric     bool UseApproxTranscendentals = Args.hasFlag(
73715f757f3fSDimitry Andric         options::OPT_ffast_math, options::OPT_fno_fast_math, false);
73725f757f3fSDimitry Andric     if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
73735f757f3fSDimitry Andric                      options::OPT_fno_gpu_approx_transcendentals,
73745f757f3fSDimitry Andric                      UseApproxTranscendentals))
73755f757f3fSDimitry Andric       CmdArgs.push_back("-fgpu-approx-transcendentals");
73765f757f3fSDimitry Andric   } else {
73775f757f3fSDimitry Andric     Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
73785f757f3fSDimitry Andric                       options::OPT_fno_gpu_approx_transcendentals);
7379fe6060f1SDimitry Andric   }
7380fe6060f1SDimitry Andric 
738181ad6265SDimitry Andric   if (IsHIP) {
7382480093f4SDimitry Andric     CmdArgs.push_back("-fcuda-allow-variadic-functions");
738381ad6265SDimitry Andric     Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
738481ad6265SDimitry Andric   }
7385480093f4SDimitry Andric 
73865f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
73875f757f3fSDimitry Andric                   options::OPT_fno_offload_uniform_block);
73885f757f3fSDimitry Andric 
73895f757f3fSDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
73905f757f3fSDimitry Andric                   options::OPT_fno_offload_implicit_host_device_templates);
73915f757f3fSDimitry Andric 
7392fe6060f1SDimitry Andric   if (IsCudaDevice || IsHIPDevice) {
7393fe6060f1SDimitry Andric     StringRef InlineThresh =
7394fe6060f1SDimitry Andric         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7395fe6060f1SDimitry Andric     if (!InlineThresh.empty()) {
7396fe6060f1SDimitry Andric       std::string ArgStr =
7397fe6060f1SDimitry Andric           std::string("-inline-threshold=") + InlineThresh.str();
7398fe6060f1SDimitry Andric       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7399fe6060f1SDimitry Andric     }
7400fe6060f1SDimitry Andric   }
7401fe6060f1SDimitry Andric 
740206c3fb27SDimitry Andric   if (IsHIPDevice)
740306c3fb27SDimitry Andric     Args.addOptOutFlag(CmdArgs,
740406c3fb27SDimitry Andric                        options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
740506c3fb27SDimitry Andric                        options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
740606c3fb27SDimitry Andric 
74070b57cec5SDimitry Andric   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
74080b57cec5SDimitry Andric   // to specify the result of the compile phase on the host, so the meaningful
740906c3fb27SDimitry Andric   // device declarations can be identified. Also, -fopenmp-is-target-device is
741006c3fb27SDimitry Andric   // passed along to tell the frontend that it is generating code for a device,
741106c3fb27SDimitry Andric   // so that only the relevant declarations are emitted.
74120b57cec5SDimitry Andric   if (IsOpenMPDevice) {
741306c3fb27SDimitry Andric     CmdArgs.push_back("-fopenmp-is-target-device");
74140b57cec5SDimitry Andric     if (OpenMPDeviceInput) {
74150b57cec5SDimitry Andric       CmdArgs.push_back("-fopenmp-host-ir-file-path");
74160b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
74170b57cec5SDimitry Andric     }
74180b57cec5SDimitry Andric   }
74190b57cec5SDimitry Andric 
7420e8d8bef9SDimitry Andric   if (Triple.isAMDGPU()) {
7421e8d8bef9SDimitry Andric     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7422e8d8bef9SDimitry Andric 
742381ad6265SDimitry Andric     Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
742481ad6265SDimitry Andric                       options::OPT_mno_unsafe_fp_atomics);
742506c3fb27SDimitry Andric     Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
742606c3fb27SDimitry Andric                        options::OPT_mno_amdgpu_ieee);
7427e8d8bef9SDimitry Andric   }
7428e8d8bef9SDimitry Andric 
74290b57cec5SDimitry Andric   // For all the host OpenMP offloading compile jobs we need to pass the targets
74300b57cec5SDimitry Andric   // information using -fopenmp-targets= option.
74310b57cec5SDimitry Andric   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
743281ad6265SDimitry Andric     SmallString<128> Targets("-fopenmp-targets=");
74330b57cec5SDimitry Andric 
743481ad6265SDimitry Andric     SmallVector<std::string, 4> Triples;
743581ad6265SDimitry Andric     auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
743681ad6265SDimitry Andric     std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
743781ad6265SDimitry Andric                    [](auto TC) { return TC.second->getTripleString(); });
743881ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
74390b57cec5SDimitry Andric   }
74400b57cec5SDimitry Andric 
7441a7dea167SDimitry Andric   bool VirtualFunctionElimination =
7442a7dea167SDimitry Andric       Args.hasFlag(options::OPT_fvirtual_function_elimination,
7443a7dea167SDimitry Andric                    options::OPT_fno_virtual_function_elimination, false);
7444a7dea167SDimitry Andric   if (VirtualFunctionElimination) {
7445a7dea167SDimitry Andric     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7446a7dea167SDimitry Andric     // in the future).
7447fe6060f1SDimitry Andric     if (LTOMode != LTOK_Full)
7448a7dea167SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
7449a7dea167SDimitry Andric           << "-fvirtual-function-elimination"
7450a7dea167SDimitry Andric           << "-flto=full";
7451a7dea167SDimitry Andric 
7452a7dea167SDimitry Andric     CmdArgs.push_back("-fvirtual-function-elimination");
7453a7dea167SDimitry Andric   }
7454a7dea167SDimitry Andric 
7455a7dea167SDimitry Andric   // VFE requires whole-program-vtables, and enables it by default.
7456a7dea167SDimitry Andric   bool WholeProgramVTables = Args.hasFlag(
7457a7dea167SDimitry Andric       options::OPT_fwhole_program_vtables,
7458a7dea167SDimitry Andric       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7459a7dea167SDimitry Andric   if (VirtualFunctionElimination && !WholeProgramVTables) {
7460a7dea167SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with)
7461a7dea167SDimitry Andric         << "-fno-whole-program-vtables"
7462a7dea167SDimitry Andric         << "-fvirtual-function-elimination";
7463a7dea167SDimitry Andric   }
7464a7dea167SDimitry Andric 
74650b57cec5SDimitry Andric   if (WholeProgramVTables) {
746606c3fb27SDimitry Andric     // PS4 uses the legacy LTO API, which does not support this feature in
746706c3fb27SDimitry Andric     // ThinLTO mode.
746806c3fb27SDimitry Andric     bool IsPS4 = getToolChain().getTriple().isPS4();
746906c3fb27SDimitry Andric 
7470fe6060f1SDimitry Andric     // Check if we passed LTO options but they were suppressed because this is a
7471fe6060f1SDimitry Andric     // device offloading action, or we passed device offload LTO options which
7472fe6060f1SDimitry Andric     // were suppressed because this is not the device offload action.
747306c3fb27SDimitry Andric     // Check if we are using PS4 in regular LTO mode.
7474fe6060f1SDimitry Andric     // Otherwise, issue an error.
747506c3fb27SDimitry Andric     if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
747606c3fb27SDimitry Andric         (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
74770b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_only_allowed_with)
74780b57cec5SDimitry Andric           << "-fwhole-program-vtables"
747906c3fb27SDimitry Andric           << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
748006c3fb27SDimitry Andric 
748106c3fb27SDimitry Andric     // Propagate -fwhole-program-vtables if this is an LTO compile.
748206c3fb27SDimitry Andric     if (IsUsingLTO)
748306c3fb27SDimitry Andric       CmdArgs.push_back("-fwhole-program-vtables");
74840b57cec5SDimitry Andric   }
74850b57cec5SDimitry Andric 
7486480093f4SDimitry Andric   bool DefaultsSplitLTOUnit =
748706c3fb27SDimitry Andric       ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
748806c3fb27SDimitry Andric           (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
748906c3fb27SDimitry Andric       (!Triple.isPS4() && UnifiedLTO);
74900b57cec5SDimitry Andric   bool SplitLTOUnit =
74910b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fsplit_lto_unit,
7492a7dea167SDimitry Andric                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7493349cc55cSDimitry Andric   if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7494a7dea167SDimitry Andric     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7495a7dea167SDimitry Andric                                                     << "-fsanitize=cfi";
74960b57cec5SDimitry Andric   if (SplitLTOUnit)
74970b57cec5SDimitry Andric     CmdArgs.push_back("-fsplit-lto-unit");
74980b57cec5SDimitry Andric 
74995f757f3fSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
75005f757f3fSDimitry Andric                                options::OPT_fno_fat_lto_objects)) {
75015f757f3fSDimitry Andric     if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
75025f757f3fSDimitry Andric       assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
75035f757f3fSDimitry Andric       if (!Triple.isOSBinFormatELF()) {
75045f757f3fSDimitry Andric         D.Diag(diag::err_drv_unsupported_opt_for_target)
75055f757f3fSDimitry Andric             << A->getAsString(Args) << TC.getTripleString();
75065f757f3fSDimitry Andric       }
75075f757f3fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
75085f757f3fSDimitry Andric           Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
75095f757f3fSDimitry Andric       CmdArgs.push_back("-flto-unit");
75105f757f3fSDimitry Andric       CmdArgs.push_back("-ffat-lto-objects");
75115f757f3fSDimitry Andric       A->render(Args, CmdArgs);
75125f757f3fSDimitry Andric     }
75135f757f3fSDimitry Andric   }
75145f757f3fSDimitry Andric 
75155ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
75165ffd83dbSDimitry Andric                                options::OPT_fno_global_isel)) {
75170b57cec5SDimitry Andric     CmdArgs.push_back("-mllvm");
75185ffd83dbSDimitry Andric     if (A->getOption().matches(options::OPT_fglobal_isel)) {
75190b57cec5SDimitry Andric       CmdArgs.push_back("-global-isel=1");
75200b57cec5SDimitry Andric 
75210b57cec5SDimitry Andric       // GISel is on by default on AArch64 -O0, so don't bother adding
75220b57cec5SDimitry Andric       // the fallback remarks for it. Other combinations will add a warning of
75230b57cec5SDimitry Andric       // some kind.
75240b57cec5SDimitry Andric       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
75250b57cec5SDimitry Andric       bool IsOptLevelSupported = false;
75260b57cec5SDimitry Andric 
75270b57cec5SDimitry Andric       Arg *A = Args.getLastArg(options::OPT_O_Group);
75280b57cec5SDimitry Andric       if (Triple.getArch() == llvm::Triple::aarch64) {
75290b57cec5SDimitry Andric         if (!A || A->getOption().matches(options::OPT_O0))
75300b57cec5SDimitry Andric           IsOptLevelSupported = true;
75310b57cec5SDimitry Andric       }
75320b57cec5SDimitry Andric       if (!IsArchSupported || !IsOptLevelSupported) {
75330b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
75340b57cec5SDimitry Andric         CmdArgs.push_back("-global-isel-abort=2");
75350b57cec5SDimitry Andric 
75360b57cec5SDimitry Andric         if (!IsArchSupported)
75375ffd83dbSDimitry Andric           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
75380b57cec5SDimitry Andric         else
75395ffd83dbSDimitry Andric           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
75400b57cec5SDimitry Andric       }
75410b57cec5SDimitry Andric     } else {
75420b57cec5SDimitry Andric       CmdArgs.push_back("-global-isel=0");
75430b57cec5SDimitry Andric     }
75440b57cec5SDimitry Andric   }
75450b57cec5SDimitry Andric 
75460b57cec5SDimitry Andric   if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
75470b57cec5SDimitry Andric      CmdArgs.push_back("-forder-file-instrumentation");
75480b57cec5SDimitry Andric      // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
75490b57cec5SDimitry Andric      // on, we need to pass these flags as linker flags and that will be handled
75500b57cec5SDimitry Andric      // outside of the compiler.
7551fe6060f1SDimitry Andric      if (!IsUsingLTO) {
75520b57cec5SDimitry Andric        CmdArgs.push_back("-mllvm");
75530b57cec5SDimitry Andric        CmdArgs.push_back("-enable-order-file-instrumentation");
75540b57cec5SDimitry Andric      }
75550b57cec5SDimitry Andric   }
75560b57cec5SDimitry Andric 
75570b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
75580b57cec5SDimitry Andric                                options::OPT_fno_force_enable_int128)) {
75590b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_fforce_enable_int128))
75600b57cec5SDimitry Andric       CmdArgs.push_back("-fforce-enable-int128");
75610b57cec5SDimitry Andric   }
75620b57cec5SDimitry Andric 
756381ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
756481ad6265SDimitry Andric                     options::OPT_fno_keep_static_consts);
756506c3fb27SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
756606c3fb27SDimitry Andric                     options::OPT_fno_keep_persistent_storage_variables);
756781ad6265SDimitry Andric   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
756881ad6265SDimitry Andric                     options::OPT_fno_complete_member_pointers);
7569bdd1243dSDimitry Andric   Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7570bdd1243dSDimitry Andric                      options::OPT_fno_cxx_static_destructors);
75710b57cec5SDimitry Andric 
7572e8d8bef9SDimitry Andric   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7573e8d8bef9SDimitry Andric 
7574e8d8bef9SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7575e8d8bef9SDimitry Andric                                options::OPT_mno_outline_atomics)) {
7576e8d8bef9SDimitry Andric     // Option -moutline-atomics supported for AArch64 target only.
7577e8d8bef9SDimitry Andric     if (!Triple.isAArch64()) {
7578e8d8bef9SDimitry Andric       D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
75790eae32dcSDimitry Andric           << Triple.getArchName() << A->getOption().getName();
75800b57cec5SDimitry Andric     } else {
75810eae32dcSDimitry Andric       if (A->getOption().matches(options::OPT_moutline_atomics)) {
7582e8d8bef9SDimitry Andric         CmdArgs.push_back("-target-feature");
7583e8d8bef9SDimitry Andric         CmdArgs.push_back("+outline-atomics");
75840b57cec5SDimitry Andric       } else {
7585e8d8bef9SDimitry Andric         CmdArgs.push_back("-target-feature");
7586e8d8bef9SDimitry Andric         CmdArgs.push_back("-outline-atomics");
75870b57cec5SDimitry Andric       }
75880eae32dcSDimitry Andric     }
7589fe6060f1SDimitry Andric   } else if (Triple.isAArch64() &&
7590fe6060f1SDimitry Andric              getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7591fe6060f1SDimitry Andric     CmdArgs.push_back("-target-feature");
7592fe6060f1SDimitry Andric     CmdArgs.push_back("+outline-atomics");
75930b57cec5SDimitry Andric   }
75940b57cec5SDimitry Andric 
7595bdd1243dSDimitry Andric   if (Triple.isAArch64() &&
7596bdd1243dSDimitry Andric       (Args.hasArg(options::OPT_mno_fmv) ||
75975f757f3fSDimitry Andric        (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7598bdd1243dSDimitry Andric        getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7599bdd1243dSDimitry Andric     // Disable Function Multiversioning on AArch64 target.
7600bdd1243dSDimitry Andric     CmdArgs.push_back("-target-feature");
7601bdd1243dSDimitry Andric     CmdArgs.push_back("-fmv");
7602bdd1243dSDimitry Andric   }
7603bdd1243dSDimitry Andric 
76040b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
76050b57cec5SDimitry Andric                    (TC.getTriple().isOSBinFormatELF() ||
76060b57cec5SDimitry Andric                     TC.getTriple().isOSBinFormatCOFF()) &&
7607e8d8bef9SDimitry Andric                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
76080b57cec5SDimitry Andric                        !TC.getTriple().isOSNetBSD() &&
7609480093f4SDimitry Andric                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7610e8d8bef9SDimitry Andric                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
76110b57cec5SDimitry Andric     CmdArgs.push_back("-faddrsig");
76120b57cec5SDimitry Andric 
7613fe6060f1SDimitry Andric   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7614bdd1243dSDimitry Andric       (EH || UnwindTables || AsyncUnwindTables ||
761506c3fb27SDimitry Andric        DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7616fe6060f1SDimitry Andric     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7617fe6060f1SDimitry Andric 
76180b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
76190b57cec5SDimitry Andric     std::string Str = A->getAsString(Args);
76200b57cec5SDimitry Andric     if (!TC.getTriple().isOSBinFormatELF())
76210b57cec5SDimitry Andric       D.Diag(diag::err_drv_unsupported_opt_for_target)
76220b57cec5SDimitry Andric           << Str << TC.getTripleString();
76230b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Str));
76240b57cec5SDimitry Andric   }
76250b57cec5SDimitry Andric 
76260b57cec5SDimitry Andric   // Add the "-o out -x type src.c" flags last. This is done primarily to make
76270b57cec5SDimitry Andric   // the -cc1 command easier to edit when reproducing compiler crashes.
76280b57cec5SDimitry Andric   if (Output.getType() == types::TY_Dependencies) {
76290b57cec5SDimitry Andric     // Handled with other dependency code.
76300b57cec5SDimitry Andric   } else if (Output.isFilename()) {
7631480093f4SDimitry Andric     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7632480093f4SDimitry Andric         Output.getType() == clang::driver::types::TY_IFS) {
7633480093f4SDimitry Andric       SmallString<128> OutputFilename(Output.getFilename());
7634480093f4SDimitry Andric       llvm::sys::path::replace_extension(OutputFilename, "ifs");
7635480093f4SDimitry Andric       CmdArgs.push_back("-o");
7636480093f4SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7637480093f4SDimitry Andric     } else {
76380b57cec5SDimitry Andric       CmdArgs.push_back("-o");
76390b57cec5SDimitry Andric       CmdArgs.push_back(Output.getFilename());
7640480093f4SDimitry Andric     }
76410b57cec5SDimitry Andric   } else {
76420b57cec5SDimitry Andric     assert(Output.isNothing() && "Invalid output.");
76430b57cec5SDimitry Andric   }
76440b57cec5SDimitry Andric 
76450b57cec5SDimitry Andric   addDashXForInput(Args, Input, CmdArgs);
76460b57cec5SDimitry Andric 
76470b57cec5SDimitry Andric   ArrayRef<InputInfo> FrontendInputs = Input;
7648bdd1243dSDimitry Andric   if (IsExtractAPI)
764981ad6265SDimitry Andric     FrontendInputs = ExtractAPIInputs;
76500b57cec5SDimitry Andric   else if (Input.isNothing())
76510b57cec5SDimitry Andric     FrontendInputs = {};
76520b57cec5SDimitry Andric 
76530b57cec5SDimitry Andric   for (const InputInfo &Input : FrontendInputs) {
76540b57cec5SDimitry Andric     if (Input.isFilename())
76550b57cec5SDimitry Andric       CmdArgs.push_back(Input.getFilename());
76560b57cec5SDimitry Andric     else
76570b57cec5SDimitry Andric       Input.getInputArg().renderAsInput(Args, CmdArgs);
76580b57cec5SDimitry Andric   }
76590b57cec5SDimitry Andric 
7660fe6060f1SDimitry Andric   if (D.CC1Main && !D.CCGenDiagnostics) {
7661480093f4SDimitry Andric     // Invoke the CC1 directly in this process
766206c3fb27SDimitry Andric     C.addCommand(std::make_unique<CC1Command>(
766306c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
766406c3fb27SDimitry Andric         Output, D.getPrependArg()));
76650b57cec5SDimitry Andric   } else {
766606c3fb27SDimitry Andric     C.addCommand(std::make_unique<Command>(
766706c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
766806c3fb27SDimitry Andric         Output, D.getPrependArg()));
76690b57cec5SDimitry Andric   }
76700b57cec5SDimitry Andric 
76710b57cec5SDimitry Andric   // Make the compile command echo its inputs for /showFilenames.
76720b57cec5SDimitry Andric   if (Output.getType() == types::TY_Object &&
76730b57cec5SDimitry Andric       Args.hasFlag(options::OPT__SLASH_showFilenames,
76740b57cec5SDimitry Andric                    options::OPT__SLASH_showFilenames_, false)) {
767513138422SDimitry Andric     C.getJobs().getJobs().back()->PrintInputFilenames = true;
76760b57cec5SDimitry Andric   }
76770b57cec5SDimitry Andric 
76780b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_pg))
76795ffd83dbSDimitry Andric     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
76805ffd83dbSDimitry Andric         !Args.hasArg(options::OPT_mfentry))
76810b57cec5SDimitry Andric       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
76820b57cec5SDimitry Andric                                                       << A->getAsString(Args);
76830b57cec5SDimitry Andric 
76840b57cec5SDimitry Andric   // Claim some arguments which clang supports automatically.
76850b57cec5SDimitry Andric 
76860b57cec5SDimitry Andric   // -fpch-preprocess is used with gcc to add a special marker in the output to
76870b57cec5SDimitry Andric   // include the PCH file.
76880b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
76890b57cec5SDimitry Andric 
76900b57cec5SDimitry Andric   // Claim some arguments which clang doesn't support, but we don't
76910b57cec5SDimitry Andric   // care to warn the user about.
76920b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
76930b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
76940b57cec5SDimitry Andric 
76950b57cec5SDimitry Andric   // Disable warnings for clang -E -emit-llvm foo.c
76960b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_emit_llvm);
76970b57cec5SDimitry Andric }
76980b57cec5SDimitry Andric 
76990eae32dcSDimitry Andric Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
77000b57cec5SDimitry Andric     // CAUTION! The first constructor argument ("clang") is not arbitrary,
77010b57cec5SDimitry Andric     // as it is for other tools. Some operations on a Tool actually test
77020b57cec5SDimitry Andric     // whether that tool is Clang based on the Tool's Name as a string.
77030eae32dcSDimitry Andric     : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
77040b57cec5SDimitry Andric 
77050b57cec5SDimitry Andric Clang::~Clang() {}
77060b57cec5SDimitry Andric 
77070b57cec5SDimitry Andric /// Add options related to the Objective-C runtime/ABI.
77080b57cec5SDimitry Andric ///
77090b57cec5SDimitry Andric /// Returns true if the runtime is non-fragile.
77100b57cec5SDimitry Andric ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
77115ffd83dbSDimitry Andric                                       const InputInfoList &inputs,
77120b57cec5SDimitry Andric                                       ArgStringList &cmdArgs,
77130b57cec5SDimitry Andric                                       RewriteKind rewriteKind) const {
77140b57cec5SDimitry Andric   // Look for the controlling runtime option.
77150b57cec5SDimitry Andric   Arg *runtimeArg =
77160b57cec5SDimitry Andric       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
77170b57cec5SDimitry Andric                       options::OPT_fobjc_runtime_EQ);
77180b57cec5SDimitry Andric 
77190b57cec5SDimitry Andric   // Just forward -fobjc-runtime= to the frontend.  This supercedes
77200b57cec5SDimitry Andric   // options about fragility.
77210b57cec5SDimitry Andric   if (runtimeArg &&
77220b57cec5SDimitry Andric       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
77230b57cec5SDimitry Andric     ObjCRuntime runtime;
77240b57cec5SDimitry Andric     StringRef value = runtimeArg->getValue();
77250b57cec5SDimitry Andric     if (runtime.tryParse(value)) {
77260b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
77270b57cec5SDimitry Andric           << value;
77280b57cec5SDimitry Andric     }
77290b57cec5SDimitry Andric     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
77300b57cec5SDimitry Andric         (runtime.getVersion() >= VersionTuple(2, 0)))
77310b57cec5SDimitry Andric       if (!getToolChain().getTriple().isOSBinFormatELF() &&
77320b57cec5SDimitry Andric           !getToolChain().getTriple().isOSBinFormatCOFF()) {
77330b57cec5SDimitry Andric         getToolChain().getDriver().Diag(
77340b57cec5SDimitry Andric             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
77350b57cec5SDimitry Andric           << runtime.getVersion().getMajor();
77360b57cec5SDimitry Andric       }
77370b57cec5SDimitry Andric 
77380b57cec5SDimitry Andric     runtimeArg->render(args, cmdArgs);
77390b57cec5SDimitry Andric     return runtime;
77400b57cec5SDimitry Andric   }
77410b57cec5SDimitry Andric 
77420b57cec5SDimitry Andric   // Otherwise, we'll need the ABI "version".  Version numbers are
77430b57cec5SDimitry Andric   // slightly confusing for historical reasons:
77440b57cec5SDimitry Andric   //   1 - Traditional "fragile" ABI
77450b57cec5SDimitry Andric   //   2 - Non-fragile ABI, version 1
77460b57cec5SDimitry Andric   //   3 - Non-fragile ABI, version 2
77470b57cec5SDimitry Andric   unsigned objcABIVersion = 1;
77480b57cec5SDimitry Andric   // If -fobjc-abi-version= is present, use that to set the version.
77490b57cec5SDimitry Andric   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
77500b57cec5SDimitry Andric     StringRef value = abiArg->getValue();
77510b57cec5SDimitry Andric     if (value == "1")
77520b57cec5SDimitry Andric       objcABIVersion = 1;
77530b57cec5SDimitry Andric     else if (value == "2")
77540b57cec5SDimitry Andric       objcABIVersion = 2;
77550b57cec5SDimitry Andric     else if (value == "3")
77560b57cec5SDimitry Andric       objcABIVersion = 3;
77570b57cec5SDimitry Andric     else
77580b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
77590b57cec5SDimitry Andric   } else {
77600b57cec5SDimitry Andric     // Otherwise, determine if we are using the non-fragile ABI.
77610b57cec5SDimitry Andric     bool nonFragileABIIsDefault =
77620b57cec5SDimitry Andric         (rewriteKind == RK_NonFragile ||
77630b57cec5SDimitry Andric          (rewriteKind == RK_None &&
77640b57cec5SDimitry Andric           getToolChain().IsObjCNonFragileABIDefault()));
77650b57cec5SDimitry Andric     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
77660b57cec5SDimitry Andric                      options::OPT_fno_objc_nonfragile_abi,
77670b57cec5SDimitry Andric                      nonFragileABIIsDefault)) {
77680b57cec5SDimitry Andric // Determine the non-fragile ABI version to use.
77690b57cec5SDimitry Andric #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
77700b57cec5SDimitry Andric       unsigned nonFragileABIVersion = 1;
77710b57cec5SDimitry Andric #else
77720b57cec5SDimitry Andric       unsigned nonFragileABIVersion = 2;
77730b57cec5SDimitry Andric #endif
77740b57cec5SDimitry Andric 
77750b57cec5SDimitry Andric       if (Arg *abiArg =
77760b57cec5SDimitry Andric               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
77770b57cec5SDimitry Andric         StringRef value = abiArg->getValue();
77780b57cec5SDimitry Andric         if (value == "1")
77790b57cec5SDimitry Andric           nonFragileABIVersion = 1;
77800b57cec5SDimitry Andric         else if (value == "2")
77810b57cec5SDimitry Andric           nonFragileABIVersion = 2;
77820b57cec5SDimitry Andric         else
77830b57cec5SDimitry Andric           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
77840b57cec5SDimitry Andric               << value;
77850b57cec5SDimitry Andric       }
77860b57cec5SDimitry Andric 
77870b57cec5SDimitry Andric       objcABIVersion = 1 + nonFragileABIVersion;
77880b57cec5SDimitry Andric     } else {
77890b57cec5SDimitry Andric       objcABIVersion = 1;
77900b57cec5SDimitry Andric     }
77910b57cec5SDimitry Andric   }
77920b57cec5SDimitry Andric 
77930b57cec5SDimitry Andric   // We don't actually care about the ABI version other than whether
77940b57cec5SDimitry Andric   // it's non-fragile.
77950b57cec5SDimitry Andric   bool isNonFragile = objcABIVersion != 1;
77960b57cec5SDimitry Andric 
77970b57cec5SDimitry Andric   // If we have no runtime argument, ask the toolchain for its default runtime.
77980b57cec5SDimitry Andric   // However, the rewriter only really supports the Mac runtime, so assume that.
77990b57cec5SDimitry Andric   ObjCRuntime runtime;
78000b57cec5SDimitry Andric   if (!runtimeArg) {
78010b57cec5SDimitry Andric     switch (rewriteKind) {
78020b57cec5SDimitry Andric     case RK_None:
78030b57cec5SDimitry Andric       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
78040b57cec5SDimitry Andric       break;
78050b57cec5SDimitry Andric     case RK_Fragile:
78060b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
78070b57cec5SDimitry Andric       break;
78080b57cec5SDimitry Andric     case RK_NonFragile:
78090b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
78100b57cec5SDimitry Andric       break;
78110b57cec5SDimitry Andric     }
78120b57cec5SDimitry Andric 
78130b57cec5SDimitry Andric     // -fnext-runtime
78140b57cec5SDimitry Andric   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
78150b57cec5SDimitry Andric     // On Darwin, make this use the default behavior for the toolchain.
78160b57cec5SDimitry Andric     if (getToolChain().getTriple().isOSDarwin()) {
78170b57cec5SDimitry Andric       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
78180b57cec5SDimitry Andric 
78190b57cec5SDimitry Andric       // Otherwise, build for a generic macosx port.
78200b57cec5SDimitry Andric     } else {
78210b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
78220b57cec5SDimitry Andric     }
78230b57cec5SDimitry Andric 
78240b57cec5SDimitry Andric     // -fgnu-runtime
78250b57cec5SDimitry Andric   } else {
78260b57cec5SDimitry Andric     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
78270b57cec5SDimitry Andric     // Legacy behaviour is to target the gnustep runtime if we are in
78280b57cec5SDimitry Andric     // non-fragile mode or the GCC runtime in fragile mode.
78290b57cec5SDimitry Andric     if (isNonFragile)
78300b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
78310b57cec5SDimitry Andric     else
78320b57cec5SDimitry Andric       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
78330b57cec5SDimitry Andric   }
78340b57cec5SDimitry Andric 
78355ffd83dbSDimitry Andric   if (llvm::any_of(inputs, [](const InputInfo &input) {
78365ffd83dbSDimitry Andric         return types::isObjC(input.getType());
78375ffd83dbSDimitry Andric       }))
78380b57cec5SDimitry Andric     cmdArgs.push_back(
78390b57cec5SDimitry Andric         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
78400b57cec5SDimitry Andric   return runtime;
78410b57cec5SDimitry Andric }
78420b57cec5SDimitry Andric 
78430b57cec5SDimitry Andric static bool maybeConsumeDash(const std::string &EH, size_t &I) {
78440b57cec5SDimitry Andric   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
78450b57cec5SDimitry Andric   I += HaveDash;
78460b57cec5SDimitry Andric   return !HaveDash;
78470b57cec5SDimitry Andric }
78480b57cec5SDimitry Andric 
78490b57cec5SDimitry Andric namespace {
78500b57cec5SDimitry Andric struct EHFlags {
78510b57cec5SDimitry Andric   bool Synch = false;
78520b57cec5SDimitry Andric   bool Asynch = false;
78530b57cec5SDimitry Andric   bool NoUnwindC = false;
78540b57cec5SDimitry Andric };
78550b57cec5SDimitry Andric } // end anonymous namespace
78560b57cec5SDimitry Andric 
78570b57cec5SDimitry Andric /// /EH controls whether to run destructor cleanups when exceptions are
78580b57cec5SDimitry Andric /// thrown.  There are three modifiers:
78590b57cec5SDimitry Andric /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
78600b57cec5SDimitry Andric /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
78610b57cec5SDimitry Andric ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
78620b57cec5SDimitry Andric /// - c: Assume that extern "C" functions are implicitly nounwind.
78630b57cec5SDimitry Andric /// The default is /EHs-c-, meaning cleanups are disabled.
78640b57cec5SDimitry Andric static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
78650b57cec5SDimitry Andric   EHFlags EH;
78660b57cec5SDimitry Andric 
78670b57cec5SDimitry Andric   std::vector<std::string> EHArgs =
78680b57cec5SDimitry Andric       Args.getAllArgValues(options::OPT__SLASH_EH);
78690b57cec5SDimitry Andric   for (auto EHVal : EHArgs) {
78700b57cec5SDimitry Andric     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
78710b57cec5SDimitry Andric       switch (EHVal[I]) {
78720b57cec5SDimitry Andric       case 'a':
78730b57cec5SDimitry Andric         EH.Asynch = maybeConsumeDash(EHVal, I);
78740b57cec5SDimitry Andric         if (EH.Asynch)
78750b57cec5SDimitry Andric           EH.Synch = false;
78760b57cec5SDimitry Andric         continue;
78770b57cec5SDimitry Andric       case 'c':
78780b57cec5SDimitry Andric         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
78790b57cec5SDimitry Andric         continue;
78800b57cec5SDimitry Andric       case 's':
78810b57cec5SDimitry Andric         EH.Synch = maybeConsumeDash(EHVal, I);
78820b57cec5SDimitry Andric         if (EH.Synch)
78830b57cec5SDimitry Andric           EH.Asynch = false;
78840b57cec5SDimitry Andric         continue;
78850b57cec5SDimitry Andric       default:
78860b57cec5SDimitry Andric         break;
78870b57cec5SDimitry Andric       }
78880b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
78890b57cec5SDimitry Andric       break;
78900b57cec5SDimitry Andric     }
78910b57cec5SDimitry Andric   }
78920b57cec5SDimitry Andric   // The /GX, /GX- flags are only processed if there are not /EH flags.
78930b57cec5SDimitry Andric   // The default is that /GX is not specified.
78940b57cec5SDimitry Andric   if (EHArgs.empty() &&
78950b57cec5SDimitry Andric       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
78960b57cec5SDimitry Andric                    /*Default=*/false)) {
78970b57cec5SDimitry Andric     EH.Synch = true;
78980b57cec5SDimitry Andric     EH.NoUnwindC = true;
78990b57cec5SDimitry Andric   }
79000b57cec5SDimitry Andric 
790181ad6265SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_kernel)) {
790281ad6265SDimitry Andric     EH.Synch = false;
790381ad6265SDimitry Andric     EH.NoUnwindC = false;
790481ad6265SDimitry Andric     EH.Asynch = false;
790581ad6265SDimitry Andric   }
790681ad6265SDimitry Andric 
79070b57cec5SDimitry Andric   return EH;
79080b57cec5SDimitry Andric }
79090b57cec5SDimitry Andric 
79100b57cec5SDimitry Andric void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
79115f757f3fSDimitry Andric                            ArgStringList &CmdArgs) const {
79125ffd83dbSDimitry Andric   bool isNVPTX = getToolChain().getTriple().isNVPTX();
79130b57cec5SDimitry Andric 
7914bdd1243dSDimitry Andric   ProcessVSRuntimeLibrary(Args, CmdArgs);
79150b57cec5SDimitry Andric 
79165ffd83dbSDimitry Andric   if (Arg *ShowIncludes =
79175ffd83dbSDimitry Andric           Args.getLastArg(options::OPT__SLASH_showIncludes,
79185ffd83dbSDimitry Andric                           options::OPT__SLASH_showIncludes_user)) {
79195ffd83dbSDimitry Andric     CmdArgs.push_back("--show-includes");
79205ffd83dbSDimitry Andric     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
79215ffd83dbSDimitry Andric       CmdArgs.push_back("-sys-header-deps");
79225ffd83dbSDimitry Andric   }
79230b57cec5SDimitry Andric 
79240b57cec5SDimitry Andric   // This controls whether or not we emit RTTI data for polymorphic types.
79250b57cec5SDimitry Andric   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
79260b57cec5SDimitry Andric                    /*Default=*/false))
79270b57cec5SDimitry Andric     CmdArgs.push_back("-fno-rtti-data");
79280b57cec5SDimitry Andric 
79290b57cec5SDimitry Andric   // This controls whether or not we emit stack-protector instrumentation.
79300b57cec5SDimitry Andric   // In MSVC, Buffer Security Check (/GS) is on by default.
79315ffd83dbSDimitry Andric   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
79320b57cec5SDimitry Andric                                /*Default=*/true)) {
79330b57cec5SDimitry Andric     CmdArgs.push_back("-stack-protector");
79340b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
79350b57cec5SDimitry Andric   }
79360b57cec5SDimitry Andric 
79370b57cec5SDimitry Andric   const Driver &D = getToolChain().getDriver();
793881ad6265SDimitry Andric 
79390b57cec5SDimitry Andric   EHFlags EH = parseClangCLEHFlags(D, Args);
79405ffd83dbSDimitry Andric   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
79410b57cec5SDimitry Andric     if (types::isCXX(InputType))
79420b57cec5SDimitry Andric       CmdArgs.push_back("-fcxx-exceptions");
79430b57cec5SDimitry Andric     CmdArgs.push_back("-fexceptions");
794406c3fb27SDimitry Andric     if (EH.Asynch)
794506c3fb27SDimitry Andric       CmdArgs.push_back("-fasync-exceptions");
79460b57cec5SDimitry Andric   }
79470b57cec5SDimitry Andric   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
79480b57cec5SDimitry Andric     CmdArgs.push_back("-fexternc-nounwind");
79490b57cec5SDimitry Andric 
79500b57cec5SDimitry Andric   // /EP should expand to -E -P.
79510b57cec5SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_EP)) {
79520b57cec5SDimitry Andric     CmdArgs.push_back("-E");
79530b57cec5SDimitry Andric     CmdArgs.push_back("-P");
79540b57cec5SDimitry Andric   }
79550b57cec5SDimitry Andric 
79560b57cec5SDimitry Andric  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
79570b57cec5SDimitry Andric                   options::OPT__SLASH_Zc_dllexportInlines,
79580b57cec5SDimitry Andric                   false)) {
79590b57cec5SDimitry Andric   CmdArgs.push_back("-fno-dllexport-inlines");
79600b57cec5SDimitry Andric  }
79610b57cec5SDimitry Andric 
796281ad6265SDimitry Andric  if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
796381ad6265SDimitry Andric                   options::OPT__SLASH_Zc_wchar_t, false)) {
796481ad6265SDimitry Andric    CmdArgs.push_back("-fno-wchar");
796581ad6265SDimitry Andric  }
796681ad6265SDimitry Andric 
796781ad6265SDimitry Andric  if (Args.hasArg(options::OPT__SLASH_kernel)) {
796881ad6265SDimitry Andric    llvm::Triple::ArchType Arch = getToolChain().getArch();
796981ad6265SDimitry Andric    std::vector<std::string> Values =
797081ad6265SDimitry Andric        Args.getAllArgValues(options::OPT__SLASH_arch);
797181ad6265SDimitry Andric    if (!Values.empty()) {
797281ad6265SDimitry Andric      llvm::SmallSet<std::string, 4> SupportedArches;
797381ad6265SDimitry Andric      if (Arch == llvm::Triple::x86)
797481ad6265SDimitry Andric        SupportedArches.insert("IA32");
797581ad6265SDimitry Andric 
797681ad6265SDimitry Andric      for (auto &V : Values)
797781ad6265SDimitry Andric        if (!SupportedArches.contains(V))
797881ad6265SDimitry Andric          D.Diag(diag::err_drv_argument_not_allowed_with)
797981ad6265SDimitry Andric              << std::string("/arch:").append(V) << "/kernel";
798081ad6265SDimitry Andric    }
798181ad6265SDimitry Andric 
798281ad6265SDimitry Andric    CmdArgs.push_back("-fno-rtti");
798381ad6265SDimitry Andric    if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
798481ad6265SDimitry Andric      D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
798581ad6265SDimitry Andric                                                      << "/kernel";
798681ad6265SDimitry Andric  }
798781ad6265SDimitry Andric 
79880b57cec5SDimitry Andric   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
79890b57cec5SDimitry Andric   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
79900b57cec5SDimitry Andric   if (MostGeneralArg && BestCaseArg)
79910b57cec5SDimitry Andric     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
79920b57cec5SDimitry Andric         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
79930b57cec5SDimitry Andric 
79940b57cec5SDimitry Andric   if (MostGeneralArg) {
79950b57cec5SDimitry Andric     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
79960b57cec5SDimitry Andric     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
79970b57cec5SDimitry Andric     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
79980b57cec5SDimitry Andric 
79990b57cec5SDimitry Andric     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
80000b57cec5SDimitry Andric     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
80010b57cec5SDimitry Andric     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
80020b57cec5SDimitry Andric       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
80030b57cec5SDimitry Andric           << FirstConflict->getAsString(Args)
80040b57cec5SDimitry Andric           << SecondConflict->getAsString(Args);
80050b57cec5SDimitry Andric 
80060b57cec5SDimitry Andric     if (SingleArg)
80070b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=single");
80080b57cec5SDimitry Andric     else if (MultipleArg)
80090b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=multiple");
80100b57cec5SDimitry Andric     else
80110b57cec5SDimitry Andric       CmdArgs.push_back("-fms-memptr-rep=virtual");
80120b57cec5SDimitry Andric   }
80130b57cec5SDimitry Andric 
80145f757f3fSDimitry Andric   if (Args.hasArg(options::OPT_regcall4))
80155f757f3fSDimitry Andric     CmdArgs.push_back("-regcall4");
80165f757f3fSDimitry Andric 
80170b57cec5SDimitry Andric   // Parse the default calling convention options.
80180b57cec5SDimitry Andric   if (Arg *CCArg =
80190b57cec5SDimitry Andric           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
80200b57cec5SDimitry Andric                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
80210b57cec5SDimitry Andric                           options::OPT__SLASH_Gregcall)) {
80220b57cec5SDimitry Andric     unsigned DCCOptId = CCArg->getOption().getID();
80230b57cec5SDimitry Andric     const char *DCCFlag = nullptr;
80245ffd83dbSDimitry Andric     bool ArchSupported = !isNVPTX;
80250b57cec5SDimitry Andric     llvm::Triple::ArchType Arch = getToolChain().getArch();
80260b57cec5SDimitry Andric     switch (DCCOptId) {
80270b57cec5SDimitry Andric     case options::OPT__SLASH_Gd:
80280b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=cdecl";
80290b57cec5SDimitry Andric       break;
80300b57cec5SDimitry Andric     case options::OPT__SLASH_Gr:
80310b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86;
80320b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=fastcall";
80330b57cec5SDimitry Andric       break;
80340b57cec5SDimitry Andric     case options::OPT__SLASH_Gz:
80350b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86;
80360b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=stdcall";
80370b57cec5SDimitry Andric       break;
80380b57cec5SDimitry Andric     case options::OPT__SLASH_Gv:
80390b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
80400b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=vectorcall";
80410b57cec5SDimitry Andric       break;
80420b57cec5SDimitry Andric     case options::OPT__SLASH_Gregcall:
80430b57cec5SDimitry Andric       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
80440b57cec5SDimitry Andric       DCCFlag = "-fdefault-calling-conv=regcall";
80450b57cec5SDimitry Andric       break;
80460b57cec5SDimitry Andric     }
80470b57cec5SDimitry Andric 
80480b57cec5SDimitry Andric     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
80490b57cec5SDimitry Andric     if (ArchSupported && DCCFlag)
80500b57cec5SDimitry Andric       CmdArgs.push_back(DCCFlag);
80510b57cec5SDimitry Andric   }
80520b57cec5SDimitry Andric 
80535f757f3fSDimitry Andric   if (Args.hasArg(options::OPT__SLASH_Gregcall4))
80545f757f3fSDimitry Andric     CmdArgs.push_back("-regcall4");
80555f757f3fSDimitry Andric 
80560b57cec5SDimitry Andric   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
80570b57cec5SDimitry Andric 
80580b57cec5SDimitry Andric   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
80590b57cec5SDimitry Andric     CmdArgs.push_back("-fdiagnostics-format");
80600b57cec5SDimitry Andric     CmdArgs.push_back("msvc");
80610b57cec5SDimitry Andric   }
80620b57cec5SDimitry Andric 
806381ad6265SDimitry Andric   if (Args.hasArg(options::OPT__SLASH_kernel))
806481ad6265SDimitry Andric     CmdArgs.push_back("-fms-kernel");
806581ad6265SDimitry Andric 
8066a324c340SDimitry Andric   for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8067480093f4SDimitry Andric     StringRef GuardArgs = A->getValue();
8068fe6060f1SDimitry Andric     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8069fe6060f1SDimitry Andric     // "ehcont-".
8070fe6060f1SDimitry Andric     if (GuardArgs.equals_insensitive("cf")) {
8071480093f4SDimitry Andric       // Emit CFG instrumentation and the table of address-taken functions.
80720b57cec5SDimitry Andric       CmdArgs.push_back("-cfguard");
8073fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8074480093f4SDimitry Andric       // Emit only the table of address-taken functions.
8075480093f4SDimitry Andric       CmdArgs.push_back("-cfguard-no-checks");
8076fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("ehcont")) {
8077fe6060f1SDimitry Andric       // Emit EH continuation table.
8078fe6060f1SDimitry Andric       CmdArgs.push_back("-ehcontguard");
8079fe6060f1SDimitry Andric     } else if (GuardArgs.equals_insensitive("cf-") ||
8080fe6060f1SDimitry Andric                GuardArgs.equals_insensitive("ehcont-")) {
8081480093f4SDimitry Andric       // Do nothing, but we might want to emit a security warning in future.
8082480093f4SDimitry Andric     } else {
8083480093f4SDimitry Andric       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8084480093f4SDimitry Andric     }
80852efbaac7SDimitry Andric     A->claim();
80860b57cec5SDimitry Andric   }
80870b57cec5SDimitry Andric }
80880b57cec5SDimitry Andric 
80890b57cec5SDimitry Andric const char *Clang::getBaseInputName(const ArgList &Args,
80900b57cec5SDimitry Andric                                     const InputInfo &Input) {
80910b57cec5SDimitry Andric   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
80920b57cec5SDimitry Andric }
80930b57cec5SDimitry Andric 
80940b57cec5SDimitry Andric const char *Clang::getBaseInputStem(const ArgList &Args,
80950b57cec5SDimitry Andric                                     const InputInfoList &Inputs) {
80960b57cec5SDimitry Andric   const char *Str = getBaseInputName(Args, Inputs[0]);
80970b57cec5SDimitry Andric 
80980b57cec5SDimitry Andric   if (const char *End = strrchr(Str, '.'))
80990b57cec5SDimitry Andric     return Args.MakeArgString(std::string(Str, End));
81000b57cec5SDimitry Andric 
81010b57cec5SDimitry Andric   return Str;
81020b57cec5SDimitry Andric }
81030b57cec5SDimitry Andric 
81040b57cec5SDimitry Andric const char *Clang::getDependencyFileName(const ArgList &Args,
81050b57cec5SDimitry Andric                                          const InputInfoList &Inputs) {
81060b57cec5SDimitry Andric   // FIXME: Think about this more.
81070b57cec5SDimitry Andric 
81080b57cec5SDimitry Andric   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8109a7dea167SDimitry Andric     SmallString<128> OutputFilename(OutputOpt->getValue());
8110a7dea167SDimitry Andric     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8111a7dea167SDimitry Andric     return Args.MakeArgString(OutputFilename);
81120b57cec5SDimitry Andric   }
8113a7dea167SDimitry Andric 
8114a7dea167SDimitry Andric   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
81150b57cec5SDimitry Andric }
81160b57cec5SDimitry Andric 
81170b57cec5SDimitry Andric // Begin ClangAs
81180b57cec5SDimitry Andric 
81190b57cec5SDimitry Andric void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
81200b57cec5SDimitry Andric                                 ArgStringList &CmdArgs) const {
81210b57cec5SDimitry Andric   StringRef CPUName;
81220b57cec5SDimitry Andric   StringRef ABIName;
81230b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
81240b57cec5SDimitry Andric   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
81250b57cec5SDimitry Andric 
81260b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
81270b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
81280b57cec5SDimitry Andric }
81290b57cec5SDimitry Andric 
81300b57cec5SDimitry Andric void ClangAs::AddX86TargetArgs(const ArgList &Args,
81310b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
81325ffd83dbSDimitry Andric   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
81335ffd83dbSDimitry Andric                         /*IsLTO=*/false);
8134480093f4SDimitry Andric 
81350b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
81360b57cec5SDimitry Andric     StringRef Value = A->getValue();
81370b57cec5SDimitry Andric     if (Value == "intel" || Value == "att") {
81380b57cec5SDimitry Andric       CmdArgs.push_back("-mllvm");
81390b57cec5SDimitry Andric       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
81400b57cec5SDimitry Andric     } else {
81410b57cec5SDimitry Andric       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8142bdd1243dSDimitry Andric           << A->getSpelling() << Value;
81430b57cec5SDimitry Andric     }
81440b57cec5SDimitry Andric   }
81450b57cec5SDimitry Andric }
81460b57cec5SDimitry Andric 
814706c3fb27SDimitry Andric void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
814806c3fb27SDimitry Andric                                      ArgStringList &CmdArgs) const {
814906c3fb27SDimitry Andric   CmdArgs.push_back("-target-abi");
815006c3fb27SDimitry Andric   CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
815106c3fb27SDimitry Andric                                                getToolChain().getTriple())
815206c3fb27SDimitry Andric                         .data());
815306c3fb27SDimitry Andric }
815406c3fb27SDimitry Andric 
81550b57cec5SDimitry Andric void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
81560b57cec5SDimitry Andric                                ArgStringList &CmdArgs) const {
81570b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getTriple();
81580b57cec5SDimitry Andric   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
81590b57cec5SDimitry Andric 
81600b57cec5SDimitry Andric   CmdArgs.push_back("-target-abi");
81610b57cec5SDimitry Andric   CmdArgs.push_back(ABIName.data());
816206c3fb27SDimitry Andric 
816306c3fb27SDimitry Andric   if (Args.hasFlag(options::OPT_mdefault_build_attributes,
816406c3fb27SDimitry Andric                    options::OPT_mno_default_build_attributes, true)) {
816506c3fb27SDimitry Andric       CmdArgs.push_back("-mllvm");
816606c3fb27SDimitry Andric       CmdArgs.push_back("-riscv-add-build-attributes");
816706c3fb27SDimitry Andric   }
81680b57cec5SDimitry Andric }
81690b57cec5SDimitry Andric 
81700b57cec5SDimitry Andric void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
81710b57cec5SDimitry Andric                            const InputInfo &Output, const InputInfoList &Inputs,
81720b57cec5SDimitry Andric                            const ArgList &Args,
81730b57cec5SDimitry Andric                            const char *LinkingOutput) const {
81740b57cec5SDimitry Andric   ArgStringList CmdArgs;
81750b57cec5SDimitry Andric 
81760b57cec5SDimitry Andric   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
81770b57cec5SDimitry Andric   const InputInfo &Input = Inputs[0];
81780b57cec5SDimitry Andric 
81790b57cec5SDimitry Andric   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
81800b57cec5SDimitry Andric   const std::string &TripleStr = Triple.getTriple();
81810b57cec5SDimitry Andric   const auto &D = getToolChain().getDriver();
81820b57cec5SDimitry Andric 
81830b57cec5SDimitry Andric   // Don't warn about "clang -w -c foo.s"
81840b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_w);
81850b57cec5SDimitry Andric   // and "clang -emit-llvm -c foo.s"
81860b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_emit_llvm);
81870b57cec5SDimitry Andric 
81880b57cec5SDimitry Andric   claimNoWarnArgs(Args);
81890b57cec5SDimitry Andric 
81900b57cec5SDimitry Andric   // Invoke ourselves in -cc1as mode.
81910b57cec5SDimitry Andric   //
81920b57cec5SDimitry Andric   // FIXME: Implement custom jobs for internal actions.
81930b57cec5SDimitry Andric   CmdArgs.push_back("-cc1as");
81940b57cec5SDimitry Andric 
81950b57cec5SDimitry Andric   // Add the "effective" target triple.
81960b57cec5SDimitry Andric   CmdArgs.push_back("-triple");
81970b57cec5SDimitry Andric   CmdArgs.push_back(Args.MakeArgString(TripleStr));
8198bdd1243dSDimitry Andric 
8199bdd1243dSDimitry Andric   getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
82000b57cec5SDimitry Andric 
82010b57cec5SDimitry Andric   // Set the output mode, we currently only expect to be used as a real
82020b57cec5SDimitry Andric   // assembler.
82030b57cec5SDimitry Andric   CmdArgs.push_back("-filetype");
82040b57cec5SDimitry Andric   CmdArgs.push_back("obj");
82050b57cec5SDimitry Andric 
82060b57cec5SDimitry Andric   // Set the main file name, so that debug info works even with
82070b57cec5SDimitry Andric   // -save-temps or preprocessed assembly.
82080b57cec5SDimitry Andric   CmdArgs.push_back("-main-file-name");
82090b57cec5SDimitry Andric   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
82100b57cec5SDimitry Andric 
82110b57cec5SDimitry Andric   // Add the target cpu
8212349cc55cSDimitry Andric   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
82130b57cec5SDimitry Andric   if (!CPU.empty()) {
82140b57cec5SDimitry Andric     CmdArgs.push_back("-target-cpu");
82150b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(CPU));
82160b57cec5SDimitry Andric   }
82170b57cec5SDimitry Andric 
82180b57cec5SDimitry Andric   // Add the target features
82195ffd83dbSDimitry Andric   getTargetFeatures(D, Triple, Args, CmdArgs, true);
82200b57cec5SDimitry Andric 
82210b57cec5SDimitry Andric   // Ignore explicit -force_cpusubtype_ALL option.
82220b57cec5SDimitry Andric   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
82230b57cec5SDimitry Andric 
82240b57cec5SDimitry Andric   // Pass along any -I options so we get proper .include search paths.
82250b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
82260b57cec5SDimitry Andric 
82270b57cec5SDimitry Andric   // Determine the original source input.
82280eae32dcSDimitry Andric   auto FindSource = [](const Action *S) -> const Action * {
82290eae32dcSDimitry Andric     while (S->getKind() != Action::InputClass) {
82300eae32dcSDimitry Andric       assert(!S->getInputs().empty() && "unexpected root action!");
82310eae32dcSDimitry Andric       S = S->getInputs()[0];
82320b57cec5SDimitry Andric     }
82330eae32dcSDimitry Andric     return S;
82340eae32dcSDimitry Andric   };
82350eae32dcSDimitry Andric   const Action *SourceAction = FindSource(&JA);
82360b57cec5SDimitry Andric 
82370b57cec5SDimitry Andric   // Forward -g and handle debug info related flags, assuming we are dealing
82380b57cec5SDimitry Andric   // with an actual assembly file.
82390b57cec5SDimitry Andric   bool WantDebug = false;
82400b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_g_Group);
8241fe6060f1SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
82420b57cec5SDimitry Andric     WantDebug = !A->getOption().matches(options::OPT_g0) &&
82430b57cec5SDimitry Andric                 !A->getOption().matches(options::OPT_ggdb0);
8244480093f4SDimitry Andric 
824506c3fb27SDimitry Andric   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
824606c3fb27SDimitry Andric       llvm::codegenoptions::NoDebugInfo;
82470b57cec5SDimitry Andric 
82480eae32dcSDimitry Andric   // Add the -fdebug-compilation-dir flag if needed.
82490eae32dcSDimitry Andric   const char *DebugCompilationDir =
82500eae32dcSDimitry Andric       addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
82510eae32dcSDimitry Andric 
82520b57cec5SDimitry Andric   if (SourceAction->getType() == types::TY_Asm ||
82530b57cec5SDimitry Andric       SourceAction->getType() == types::TY_PP_Asm) {
82540b57cec5SDimitry Andric     // You might think that it would be ok to set DebugInfoKind outside of
82550b57cec5SDimitry Andric     // the guard for source type, however there is a test which asserts
82560b57cec5SDimitry Andric     // that some assembler invocation receives no -debug-info-kind,
82570b57cec5SDimitry Andric     // and it's not clear whether that test is just overly restrictive.
825806c3fb27SDimitry Andric     DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
825906c3fb27SDimitry Andric                                : llvm::codegenoptions::NoDebugInfo);
82600b57cec5SDimitry Andric 
826181ad6265SDimitry Andric     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
826281ad6265SDimitry Andric                          CmdArgs);
82630b57cec5SDimitry Andric 
82640b57cec5SDimitry Andric     // Set the AT_producer to the clang version when using the integrated
82650b57cec5SDimitry Andric     // assembler on assembly source files.
82660b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-debug-producer");
82670b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
82680b57cec5SDimitry Andric 
82690b57cec5SDimitry Andric     // And pass along -I options
82700b57cec5SDimitry Andric     Args.AddAllArgs(CmdArgs, options::OPT_I);
82710b57cec5SDimitry Andric   }
8272bdd1243dSDimitry Andric   const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
82730b57cec5SDimitry Andric   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
82740b57cec5SDimitry Andric                           llvm::DebuggerKind::Default);
8275fe6060f1SDimitry Andric   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
82760b57cec5SDimitry Andric   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
82770b57cec5SDimitry Andric 
82780b57cec5SDimitry Andric   // Handle -fPIC et al -- the relocation-model affects the assembler
82790b57cec5SDimitry Andric   // for some targets.
82800b57cec5SDimitry Andric   llvm::Reloc::Model RelocationModel;
82810b57cec5SDimitry Andric   unsigned PICLevel;
82820b57cec5SDimitry Andric   bool IsPIE;
82830b57cec5SDimitry Andric   std::tie(RelocationModel, PICLevel, IsPIE) =
82840b57cec5SDimitry Andric       ParsePICArgs(getToolChain(), Args);
82850b57cec5SDimitry Andric 
82860b57cec5SDimitry Andric   const char *RMName = RelocationModelName(RelocationModel);
82870b57cec5SDimitry Andric   if (RMName) {
82880b57cec5SDimitry Andric     CmdArgs.push_back("-mrelocation-model");
82890b57cec5SDimitry Andric     CmdArgs.push_back(RMName);
82900b57cec5SDimitry Andric   }
82910b57cec5SDimitry Andric 
82920b57cec5SDimitry Andric   // Optionally embed the -cc1as level arguments into the debug info, for build
82930b57cec5SDimitry Andric   // analysis.
82940b57cec5SDimitry Andric   if (getToolChain().UseDwarfDebugFlags()) {
82950b57cec5SDimitry Andric     ArgStringList OriginalArgs;
82960b57cec5SDimitry Andric     for (const auto &Arg : Args)
82970b57cec5SDimitry Andric       Arg->render(Args, OriginalArgs);
82980b57cec5SDimitry Andric 
82990b57cec5SDimitry Andric     SmallString<256> Flags;
83000b57cec5SDimitry Andric     const char *Exec = getToolChain().getDriver().getClangProgramPath();
83015ffd83dbSDimitry Andric     EscapeSpacesAndBackslashes(Exec, Flags);
83020b57cec5SDimitry Andric     for (const char *OriginalArg : OriginalArgs) {
83030b57cec5SDimitry Andric       SmallString<128> EscapedArg;
83040b57cec5SDimitry Andric       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
83050b57cec5SDimitry Andric       Flags += " ";
83060b57cec5SDimitry Andric       Flags += EscapedArg;
83070b57cec5SDimitry Andric     }
83080b57cec5SDimitry Andric     CmdArgs.push_back("-dwarf-debug-flags");
83090b57cec5SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Flags));
83100b57cec5SDimitry Andric   }
83110b57cec5SDimitry Andric 
83120b57cec5SDimitry Andric   // FIXME: Add -static support, once we have it.
83130b57cec5SDimitry Andric 
83140b57cec5SDimitry Andric   // Add target specific flags.
83150b57cec5SDimitry Andric   switch (getToolChain().getArch()) {
83160b57cec5SDimitry Andric   default:
83170b57cec5SDimitry Andric     break;
83180b57cec5SDimitry Andric 
83190b57cec5SDimitry Andric   case llvm::Triple::mips:
83200b57cec5SDimitry Andric   case llvm::Triple::mipsel:
83210b57cec5SDimitry Andric   case llvm::Triple::mips64:
83220b57cec5SDimitry Andric   case llvm::Triple::mips64el:
83230b57cec5SDimitry Andric     AddMIPSTargetArgs(Args, CmdArgs);
83240b57cec5SDimitry Andric     break;
83250b57cec5SDimitry Andric 
83260b57cec5SDimitry Andric   case llvm::Triple::x86:
83270b57cec5SDimitry Andric   case llvm::Triple::x86_64:
83280b57cec5SDimitry Andric     AddX86TargetArgs(Args, CmdArgs);
83290b57cec5SDimitry Andric     break;
83300b57cec5SDimitry Andric 
83310b57cec5SDimitry Andric   case llvm::Triple::arm:
83320b57cec5SDimitry Andric   case llvm::Triple::armeb:
83330b57cec5SDimitry Andric   case llvm::Triple::thumb:
83340b57cec5SDimitry Andric   case llvm::Triple::thumbeb:
83350b57cec5SDimitry Andric     // This isn't in AddARMTargetArgs because we want to do this for assembly
83360b57cec5SDimitry Andric     // only, not C/C++.
83370b57cec5SDimitry Andric     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
83380b57cec5SDimitry Andric                      options::OPT_mno_default_build_attributes, true)) {
83390b57cec5SDimitry Andric         CmdArgs.push_back("-mllvm");
83400b57cec5SDimitry Andric         CmdArgs.push_back("-arm-add-build-attributes");
83410b57cec5SDimitry Andric     }
83420b57cec5SDimitry Andric     break;
83430b57cec5SDimitry Andric 
8344e8d8bef9SDimitry Andric   case llvm::Triple::aarch64:
8345e8d8bef9SDimitry Andric   case llvm::Triple::aarch64_32:
8346e8d8bef9SDimitry Andric   case llvm::Triple::aarch64_be:
8347e8d8bef9SDimitry Andric     if (Args.hasArg(options::OPT_mmark_bti_property)) {
8348e8d8bef9SDimitry Andric       CmdArgs.push_back("-mllvm");
8349e8d8bef9SDimitry Andric       CmdArgs.push_back("-aarch64-mark-bti-property");
8350e8d8bef9SDimitry Andric     }
8351e8d8bef9SDimitry Andric     break;
8352e8d8bef9SDimitry Andric 
835306c3fb27SDimitry Andric   case llvm::Triple::loongarch32:
835406c3fb27SDimitry Andric   case llvm::Triple::loongarch64:
835506c3fb27SDimitry Andric     AddLoongArchTargetArgs(Args, CmdArgs);
835606c3fb27SDimitry Andric     break;
835706c3fb27SDimitry Andric 
83580b57cec5SDimitry Andric   case llvm::Triple::riscv32:
83590b57cec5SDimitry Andric   case llvm::Triple::riscv64:
83600b57cec5SDimitry Andric     AddRISCVTargetArgs(Args, CmdArgs);
83610b57cec5SDimitry Andric     break;
83620b57cec5SDimitry Andric   }
83630b57cec5SDimitry Andric 
83640b57cec5SDimitry Andric   // Consume all the warning flags. Usually this would be handled more
83650b57cec5SDimitry Andric   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
83660b57cec5SDimitry Andric   // doesn't handle that so rather than warning about unused flags that are
83670b57cec5SDimitry Andric   // actually used, we'll lie by omission instead.
83680b57cec5SDimitry Andric   // FIXME: Stop lying and consume only the appropriate driver flags
83690b57cec5SDimitry Andric   Args.ClaimAllArgs(options::OPT_W_Group);
83700b57cec5SDimitry Andric 
83710b57cec5SDimitry Andric   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
83720b57cec5SDimitry Andric                                     getToolChain().getDriver());
83730b57cec5SDimitry Andric 
83740b57cec5SDimitry Andric   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
83750b57cec5SDimitry Andric 
837606c3fb27SDimitry Andric   if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
83770eae32dcSDimitry Andric     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
83780eae32dcSDimitry Andric                        Output.getFilename());
83790eae32dcSDimitry Andric 
83800eae32dcSDimitry Andric   // Fixup any previous commands that use -object-file-name because when we
83810eae32dcSDimitry Andric   // generated them, the final .obj name wasn't yet known.
83820eae32dcSDimitry Andric   for (Command &J : C.getJobs()) {
83830eae32dcSDimitry Andric     if (SourceAction != FindSource(&J.getSource()))
83840eae32dcSDimitry Andric       continue;
83850eae32dcSDimitry Andric     auto &JArgs = J.getArguments();
83860eae32dcSDimitry Andric     for (unsigned I = 0; I < JArgs.size(); ++I) {
83875f757f3fSDimitry Andric       if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
83880eae32dcSDimitry Andric           Output.isFilename()) {
83890eae32dcSDimitry Andric        ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
83900eae32dcSDimitry Andric        addDebugObjectName(Args, NewArgs, DebugCompilationDir,
83910eae32dcSDimitry Andric                           Output.getFilename());
83920eae32dcSDimitry Andric        NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
83930eae32dcSDimitry Andric        J.replaceArguments(NewArgs);
83940eae32dcSDimitry Andric        break;
83950eae32dcSDimitry Andric       }
83960eae32dcSDimitry Andric     }
83970eae32dcSDimitry Andric   }
83980eae32dcSDimitry Andric 
83990b57cec5SDimitry Andric   assert(Output.isFilename() && "Unexpected lipo output.");
84000b57cec5SDimitry Andric   CmdArgs.push_back("-o");
84010b57cec5SDimitry Andric   CmdArgs.push_back(Output.getFilename());
84020b57cec5SDimitry Andric 
84030b57cec5SDimitry Andric   const llvm::Triple &T = getToolChain().getTriple();
84040b57cec5SDimitry Andric   Arg *A;
84050b57cec5SDimitry Andric   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
84060b57cec5SDimitry Andric       T.isOSBinFormatELF()) {
84070b57cec5SDimitry Andric     CmdArgs.push_back("-split-dwarf-output");
8408e8d8bef9SDimitry Andric     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
84090b57cec5SDimitry Andric   }
84100b57cec5SDimitry Andric 
8411e8d8bef9SDimitry Andric   if (Triple.isAMDGPU())
841281ad6265SDimitry Andric     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8413e8d8bef9SDimitry Andric 
84140b57cec5SDimitry Andric   assert(Input.isFilename() && "Invalid input.");
84150b57cec5SDimitry Andric   CmdArgs.push_back(Input.getFilename());
84160b57cec5SDimitry Andric 
84170b57cec5SDimitry Andric   const char *Exec = getToolChain().getDriver().getClangProgramPath();
8418e8d8bef9SDimitry Andric   if (D.CC1Main && !D.CCGenDiagnostics) {
8419e8d8bef9SDimitry Andric     // Invoke cc1as directly in this process.
842006c3fb27SDimitry Andric     C.addCommand(std::make_unique<CC1Command>(
842106c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
842206c3fb27SDimitry Andric         Output, D.getPrependArg()));
8423e8d8bef9SDimitry Andric   } else {
842406c3fb27SDimitry Andric     C.addCommand(std::make_unique<Command>(
842506c3fb27SDimitry Andric         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
842606c3fb27SDimitry Andric         Output, D.getPrependArg()));
8427e8d8bef9SDimitry Andric   }
84280b57cec5SDimitry Andric }
84290b57cec5SDimitry Andric 
84300b57cec5SDimitry Andric // Begin OffloadBundler
84310b57cec5SDimitry Andric 
84320b57cec5SDimitry Andric void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
84330b57cec5SDimitry Andric                                   const InputInfo &Output,
84340b57cec5SDimitry Andric                                   const InputInfoList &Inputs,
84350b57cec5SDimitry Andric                                   const llvm::opt::ArgList &TCArgs,
84360b57cec5SDimitry Andric                                   const char *LinkingOutput) const {
84370b57cec5SDimitry Andric   // The version with only one output is expected to refer to a bundling job.
84380b57cec5SDimitry Andric   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
84390b57cec5SDimitry Andric 
84400b57cec5SDimitry Andric   // The bundling command looks like this:
84410b57cec5SDimitry Andric   // clang-offload-bundler -type=bc
84420b57cec5SDimitry Andric   //   -targets=host-triple,openmp-triple1,openmp-triple2
844381ad6265SDimitry Andric   //   -output=output_file
844481ad6265SDimitry Andric   //   -input=unbundle_file_host
844581ad6265SDimitry Andric   //   -input=unbundle_file_tgt1
844681ad6265SDimitry Andric   //   -input=unbundle_file_tgt2
84470b57cec5SDimitry Andric 
84480b57cec5SDimitry Andric   ArgStringList CmdArgs;
84490b57cec5SDimitry Andric 
84500b57cec5SDimitry Andric   // Get the type.
84510b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(
84520b57cec5SDimitry Andric       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
84530b57cec5SDimitry Andric 
84540b57cec5SDimitry Andric   assert(JA.getInputs().size() == Inputs.size() &&
84550b57cec5SDimitry Andric          "Not have inputs for all dependence actions??");
84560b57cec5SDimitry Andric 
84570b57cec5SDimitry Andric   // Get the targets.
84580b57cec5SDimitry Andric   SmallString<128> Triples;
84590b57cec5SDimitry Andric   Triples += "-targets=";
84600b57cec5SDimitry Andric   for (unsigned I = 0; I < Inputs.size(); ++I) {
84610b57cec5SDimitry Andric     if (I)
84620b57cec5SDimitry Andric       Triples += ',';
84630b57cec5SDimitry Andric 
84640b57cec5SDimitry Andric     // Find ToolChain for this input.
84650b57cec5SDimitry Andric     Action::OffloadKind CurKind = Action::OFK_Host;
84660b57cec5SDimitry Andric     const ToolChain *CurTC = &getToolChain();
84670b57cec5SDimitry Andric     const Action *CurDep = JA.getInputs()[I];
84680b57cec5SDimitry Andric 
84690b57cec5SDimitry Andric     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
84700b57cec5SDimitry Andric       CurTC = nullptr;
84710b57cec5SDimitry Andric       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
84720b57cec5SDimitry Andric         assert(CurTC == nullptr && "Expected one dependence!");
84730b57cec5SDimitry Andric         CurKind = A->getOffloadingDeviceKind();
84740b57cec5SDimitry Andric         CurTC = TC;
84750b57cec5SDimitry Andric       });
84760b57cec5SDimitry Andric     }
84770b57cec5SDimitry Andric     Triples += Action::GetOffloadKindName(CurKind);
8478349cc55cSDimitry Andric     Triples += '-';
8479349cc55cSDimitry Andric     Triples += CurTC->getTriple().normalize();
8480349cc55cSDimitry Andric     if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
84810eae32dcSDimitry Andric         !StringRef(CurDep->getOffloadingArch()).empty()) {
8482349cc55cSDimitry Andric       Triples += '-';
84830b57cec5SDimitry Andric       Triples += CurDep->getOffloadingArch();
84840b57cec5SDimitry Andric     }
8485349cc55cSDimitry Andric 
8486349cc55cSDimitry Andric     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8487349cc55cSDimitry Andric     //       with each toolchain.
8488349cc55cSDimitry Andric     StringRef GPUArchName;
8489349cc55cSDimitry Andric     if (CurKind == Action::OFK_OpenMP) {
8490349cc55cSDimitry Andric       // Extract GPUArch from -march argument in TC argument list.
8491349cc55cSDimitry Andric       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8492349cc55cSDimitry Andric         auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
849306c3fb27SDimitry Andric         auto Arch = ArchStr.starts_with_insensitive("-march=");
8494349cc55cSDimitry Andric         if (Arch) {
8495349cc55cSDimitry Andric           GPUArchName = ArchStr.substr(7);
8496349cc55cSDimitry Andric           Triples += "-";
8497349cc55cSDimitry Andric           break;
8498349cc55cSDimitry Andric         }
8499349cc55cSDimitry Andric       }
8500349cc55cSDimitry Andric       Triples += GPUArchName.str();
8501349cc55cSDimitry Andric     }
85020b57cec5SDimitry Andric   }
85030b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
85040b57cec5SDimitry Andric 
85050b57cec5SDimitry Andric   // Get bundled file command.
85060b57cec5SDimitry Andric   CmdArgs.push_back(
850781ad6265SDimitry Andric       TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
85080b57cec5SDimitry Andric 
85090b57cec5SDimitry Andric   // Get unbundled files command.
85100b57cec5SDimitry Andric   for (unsigned I = 0; I < Inputs.size(); ++I) {
851181ad6265SDimitry Andric     SmallString<128> UB;
851281ad6265SDimitry Andric     UB += "-input=";
85130b57cec5SDimitry Andric 
85140b57cec5SDimitry Andric     // Find ToolChain for this input.
85150b57cec5SDimitry Andric     const ToolChain *CurTC = &getToolChain();
85160b57cec5SDimitry Andric     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
85170b57cec5SDimitry Andric       CurTC = nullptr;
85180b57cec5SDimitry Andric       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
85190b57cec5SDimitry Andric         assert(CurTC == nullptr && "Expected one dependence!");
85200b57cec5SDimitry Andric         CurTC = TC;
85210b57cec5SDimitry Andric       });
85226e75b2fbSDimitry Andric       UB += C.addTempFile(
85236e75b2fbSDimitry Andric           C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
85246e75b2fbSDimitry Andric     } else {
85250b57cec5SDimitry Andric       UB += CurTC->getInputFilename(Inputs[I]);
85260b57cec5SDimitry Andric     }
85270b57cec5SDimitry Andric     CmdArgs.push_back(TCArgs.MakeArgString(UB));
852881ad6265SDimitry Andric   }
85295f757f3fSDimitry Andric   if (TCArgs.hasFlag(options::OPT_offload_compress,
85305f757f3fSDimitry Andric                      options::OPT_no_offload_compress, false))
85315f757f3fSDimitry Andric     CmdArgs.push_back("-compress");
85325f757f3fSDimitry Andric   if (TCArgs.hasArg(options::OPT_v))
85335f757f3fSDimitry Andric     CmdArgs.push_back("-verbose");
85340b57cec5SDimitry Andric   // All the inputs are encoded as commands.
8535a7dea167SDimitry Andric   C.addCommand(std::make_unique<Command>(
85365ffd83dbSDimitry Andric       JA, *this, ResponseFileSupport::None(),
85370b57cec5SDimitry Andric       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8538bdd1243dSDimitry Andric       CmdArgs, std::nullopt, Output));
85390b57cec5SDimitry Andric }
85400b57cec5SDimitry Andric 
85410b57cec5SDimitry Andric void OffloadBundler::ConstructJobMultipleOutputs(
85420b57cec5SDimitry Andric     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
85430b57cec5SDimitry Andric     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
85440b57cec5SDimitry Andric     const char *LinkingOutput) const {
85450b57cec5SDimitry Andric   // The version with multiple outputs is expected to refer to a unbundling job.
85460b57cec5SDimitry Andric   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
85470b57cec5SDimitry Andric 
85480b57cec5SDimitry Andric   // The unbundling command looks like this:
85490b57cec5SDimitry Andric   // clang-offload-bundler -type=bc
85500b57cec5SDimitry Andric   //   -targets=host-triple,openmp-triple1,openmp-triple2
855181ad6265SDimitry Andric   //   -input=input_file
855281ad6265SDimitry Andric   //   -output=unbundle_file_host
855381ad6265SDimitry Andric   //   -output=unbundle_file_tgt1
855481ad6265SDimitry Andric   //   -output=unbundle_file_tgt2
85550b57cec5SDimitry Andric   //   -unbundle
85560b57cec5SDimitry Andric 
85570b57cec5SDimitry Andric   ArgStringList CmdArgs;
85580b57cec5SDimitry Andric 
85590b57cec5SDimitry Andric   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
85600b57cec5SDimitry Andric   InputInfo Input = Inputs.front();
85610b57cec5SDimitry Andric 
85620b57cec5SDimitry Andric   // Get the type.
85630b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(
85640b57cec5SDimitry Andric       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
85650b57cec5SDimitry Andric 
85660b57cec5SDimitry Andric   // Get the targets.
85670b57cec5SDimitry Andric   SmallString<128> Triples;
85680b57cec5SDimitry Andric   Triples += "-targets=";
85690b57cec5SDimitry Andric   auto DepInfo = UA.getDependentActionsInfo();
85700b57cec5SDimitry Andric   for (unsigned I = 0; I < DepInfo.size(); ++I) {
85710b57cec5SDimitry Andric     if (I)
85720b57cec5SDimitry Andric       Triples += ',';
85730b57cec5SDimitry Andric 
85740b57cec5SDimitry Andric     auto &Dep = DepInfo[I];
85750b57cec5SDimitry Andric     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8576349cc55cSDimitry Andric     Triples += '-';
8577349cc55cSDimitry Andric     Triples += Dep.DependentToolChain->getTriple().normalize();
8578349cc55cSDimitry Andric     if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8579349cc55cSDimitry Andric          Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8580349cc55cSDimitry Andric         !Dep.DependentBoundArch.empty()) {
8581349cc55cSDimitry Andric       Triples += '-';
85820b57cec5SDimitry Andric       Triples += Dep.DependentBoundArch;
85830b57cec5SDimitry Andric     }
8584349cc55cSDimitry Andric     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8585349cc55cSDimitry Andric     //       with each toolchain.
8586349cc55cSDimitry Andric     StringRef GPUArchName;
8587349cc55cSDimitry Andric     if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8588349cc55cSDimitry Andric       // Extract GPUArch from -march argument in TC argument list.
8589349cc55cSDimitry Andric       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8590349cc55cSDimitry Andric         StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
859106c3fb27SDimitry Andric         auto Arch = ArchStr.starts_with_insensitive("-march=");
8592349cc55cSDimitry Andric         if (Arch) {
8593349cc55cSDimitry Andric           GPUArchName = ArchStr.substr(7);
8594349cc55cSDimitry Andric           Triples += "-";
8595349cc55cSDimitry Andric           break;
8596349cc55cSDimitry Andric         }
8597349cc55cSDimitry Andric       }
8598349cc55cSDimitry Andric       Triples += GPUArchName.str();
8599349cc55cSDimitry Andric     }
86000b57cec5SDimitry Andric   }
86010b57cec5SDimitry Andric 
86020b57cec5SDimitry Andric   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
86030b57cec5SDimitry Andric 
86040b57cec5SDimitry Andric   // Get bundled file command.
86050b57cec5SDimitry Andric   CmdArgs.push_back(
860681ad6265SDimitry Andric       TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
86070b57cec5SDimitry Andric 
86080b57cec5SDimitry Andric   // Get unbundled files command.
86090b57cec5SDimitry Andric   for (unsigned I = 0; I < Outputs.size(); ++I) {
861081ad6265SDimitry Andric     SmallString<128> UB;
861181ad6265SDimitry Andric     UB += "-output=";
86120b57cec5SDimitry Andric     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
86130b57cec5SDimitry Andric     CmdArgs.push_back(TCArgs.MakeArgString(UB));
861481ad6265SDimitry Andric   }
86150b57cec5SDimitry Andric   CmdArgs.push_back("-unbundle");
8616e8d8bef9SDimitry Andric   CmdArgs.push_back("-allow-missing-bundles");
86175f757f3fSDimitry Andric   if (TCArgs.hasArg(options::OPT_v))
86185f757f3fSDimitry Andric     CmdArgs.push_back("-verbose");
86190b57cec5SDimitry Andric 
86200b57cec5SDimitry Andric   // All the inputs are encoded as commands.
8621a7dea167SDimitry Andric   C.addCommand(std::make_unique<Command>(
86225ffd83dbSDimitry Andric       JA, *this, ResponseFileSupport::None(),
86230b57cec5SDimitry Andric       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8624bdd1243dSDimitry Andric       CmdArgs, std::nullopt, Outputs));
8625a7dea167SDimitry Andric }
86261fd87a68SDimitry Andric 
862781ad6265SDimitry Andric void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
862881ad6265SDimitry Andric                                    const InputInfo &Output,
862981ad6265SDimitry Andric                                    const InputInfoList &Inputs,
863081ad6265SDimitry Andric                                    const llvm::opt::ArgList &Args,
863181ad6265SDimitry Andric                                    const char *LinkingOutput) const {
863281ad6265SDimitry Andric   ArgStringList CmdArgs;
863381ad6265SDimitry Andric 
863481ad6265SDimitry Andric   // Add the output file name.
863581ad6265SDimitry Andric   assert(Output.isFilename() && "Invalid output.");
863681ad6265SDimitry Andric   CmdArgs.push_back("-o");
863781ad6265SDimitry Andric   CmdArgs.push_back(Output.getFilename());
863881ad6265SDimitry Andric 
863981ad6265SDimitry Andric   // Create the inputs to bundle the needed metadata.
864081ad6265SDimitry Andric   for (const InputInfo &Input : Inputs) {
864181ad6265SDimitry Andric     const Action *OffloadAction = Input.getAction();
864281ad6265SDimitry Andric     const ToolChain *TC = OffloadAction->getOffloadingToolChain();
864381ad6265SDimitry Andric     const ArgList &TCArgs =
864481ad6265SDimitry Andric         C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
864581ad6265SDimitry Andric                               OffloadAction->getOffloadingDeviceKind());
864681ad6265SDimitry Andric     StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
864706c3fb27SDimitry Andric     StringRef Arch = OffloadAction->getOffloadingArch()
864881ad6265SDimitry Andric                          ? OffloadAction->getOffloadingArch()
864981ad6265SDimitry Andric                          : TCArgs.getLastArgValue(options::OPT_march_EQ);
865081ad6265SDimitry Andric     StringRef Kind =
865181ad6265SDimitry Andric       Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
865281ad6265SDimitry Andric 
865381ad6265SDimitry Andric     ArgStringList Features;
865481ad6265SDimitry Andric     SmallVector<StringRef> FeatureArgs;
8655753f127fSDimitry Andric     getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
8656753f127fSDimitry Andric                       false);
865781ad6265SDimitry Andric     llvm::copy_if(Features, std::back_inserter(FeatureArgs),
86585f757f3fSDimitry Andric                   [](StringRef Arg) { return !Arg.starts_with("-target"); });
865981ad6265SDimitry Andric 
866006c3fb27SDimitry Andric     if (TC->getTriple().isAMDGPU()) {
866106c3fb27SDimitry Andric       for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
866206c3fb27SDimitry Andric         FeatureArgs.emplace_back(
866306c3fb27SDimitry Andric             Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
866406c3fb27SDimitry Andric       }
866506c3fb27SDimitry Andric     }
866606c3fb27SDimitry Andric 
866706c3fb27SDimitry Andric     // TODO: We need to pass in the full target-id and handle it properly in the
866806c3fb27SDimitry Andric     // linker wrapper.
866981ad6265SDimitry Andric     SmallVector<std::string> Parts{
867081ad6265SDimitry Andric         "file=" + File.str(),
867181ad6265SDimitry Andric         "triple=" + TC->getTripleString(),
867206c3fb27SDimitry Andric         "arch=" + getProcessorFromTargetID(TC->getTriple(), Arch).str(),
867381ad6265SDimitry Andric         "kind=" + Kind.str(),
867481ad6265SDimitry Andric     };
867581ad6265SDimitry Andric 
867606c3fb27SDimitry Andric     if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
867706c3fb27SDimitry Andric         TC->getTriple().isAMDGPU())
867881ad6265SDimitry Andric       for (StringRef Feature : FeatureArgs)
867981ad6265SDimitry Andric         Parts.emplace_back("feature=" + Feature.str());
868081ad6265SDimitry Andric 
868181ad6265SDimitry Andric     CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
868281ad6265SDimitry Andric   }
868381ad6265SDimitry Andric 
868481ad6265SDimitry Andric   C.addCommand(std::make_unique<Command>(
868581ad6265SDimitry Andric       JA, *this, ResponseFileSupport::None(),
868681ad6265SDimitry Andric       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
868781ad6265SDimitry Andric       CmdArgs, Inputs, Output));
868881ad6265SDimitry Andric }
868981ad6265SDimitry Andric 
86901fd87a68SDimitry Andric void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
86911fd87a68SDimitry Andric                                  const InputInfo &Output,
86921fd87a68SDimitry Andric                                  const InputInfoList &Inputs,
86931fd87a68SDimitry Andric                                  const ArgList &Args,
86941fd87a68SDimitry Andric                                  const char *LinkingOutput) const {
8695d56accc7SDimitry Andric   const Driver &D = getToolChain().getDriver();
8696d56accc7SDimitry Andric   const llvm::Triple TheTriple = getToolChain().getTriple();
86971fd87a68SDimitry Andric   ArgStringList CmdArgs;
86981fd87a68SDimitry Andric 
8699d56accc7SDimitry Andric   // Pass the CUDA path to the linker wrapper tool.
870081ad6265SDimitry Andric   for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
870181ad6265SDimitry Andric     auto TCRange = C.getOffloadToolChains(Kind);
870281ad6265SDimitry Andric     for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
8703d56accc7SDimitry Andric       const ToolChain *TC = I.second;
8704d56accc7SDimitry Andric       if (TC->getTriple().isNVPTX()) {
8705d56accc7SDimitry Andric         CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8706d56accc7SDimitry Andric         if (CudaInstallation.isValid())
8707d56accc7SDimitry Andric           CmdArgs.push_back(Args.MakeArgString(
8708d56accc7SDimitry Andric               "--cuda-path=" + CudaInstallation.getInstallPath()));
8709d56accc7SDimitry Andric         break;
8710d56accc7SDimitry Andric       }
8711d56accc7SDimitry Andric     }
87121fd87a68SDimitry Andric   }
87131fd87a68SDimitry Andric 
87141fd87a68SDimitry Andric   // Pass in the optimization level to use for LTO.
87151fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
87161fd87a68SDimitry Andric     StringRef OOpt;
87171fd87a68SDimitry Andric     if (A->getOption().matches(options::OPT_O4) ||
87181fd87a68SDimitry Andric         A->getOption().matches(options::OPT_Ofast))
87191fd87a68SDimitry Andric       OOpt = "3";
87201fd87a68SDimitry Andric     else if (A->getOption().matches(options::OPT_O)) {
87211fd87a68SDimitry Andric       OOpt = A->getValue();
87221fd87a68SDimitry Andric       if (OOpt == "g")
87231fd87a68SDimitry Andric         OOpt = "1";
87241fd87a68SDimitry Andric       else if (OOpt == "s" || OOpt == "z")
87251fd87a68SDimitry Andric         OOpt = "2";
87261fd87a68SDimitry Andric     } else if (A->getOption().matches(options::OPT_O0))
87271fd87a68SDimitry Andric       OOpt = "0";
87281fd87a68SDimitry Andric     if (!OOpt.empty())
8729753f127fSDimitry Andric       CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
87301fd87a68SDimitry Andric   }
87311fd87a68SDimitry Andric 
8732753f127fSDimitry Andric   CmdArgs.push_back(
8733753f127fSDimitry Andric       Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
87341fd87a68SDimitry Andric   if (Args.hasArg(options::OPT_v))
8735bdd1243dSDimitry Andric     CmdArgs.push_back("--wrapper-verbose");
87361fd87a68SDimitry Andric 
87371fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8738753f127fSDimitry Andric     if (!A->getOption().matches(options::OPT_g0))
8739753f127fSDimitry Andric       CmdArgs.push_back("--device-debug");
87401fd87a68SDimitry Andric   }
87411fd87a68SDimitry Andric 
87425f757f3fSDimitry Andric   // code-object-version=X needs to be passed to clang-linker-wrapper to ensure
87435f757f3fSDimitry Andric   // that it is used by lld.
87445f757f3fSDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
87455f757f3fSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("-mllvm"));
87465f757f3fSDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
87475f757f3fSDimitry Andric         Twine("--amdhsa-code-object-version=") + A->getValue()));
87485f757f3fSDimitry Andric   }
87495f757f3fSDimitry Andric 
87501fd87a68SDimitry Andric   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8751bdd1243dSDimitry Andric     CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
87521fd87a68SDimitry Andric 
87531fd87a68SDimitry Andric   // Forward remarks passes to the LLVM backend in the wrapper.
87541fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8755fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
8756fcaf7f86SDimitry Andric                                          A->getValue()));
87571fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8758fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
8759fcaf7f86SDimitry Andric         Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
87601fd87a68SDimitry Andric   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8761fcaf7f86SDimitry Andric     CmdArgs.push_back(Args.MakeArgString(
8762fcaf7f86SDimitry Andric         Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
87631fd87a68SDimitry Andric   if (Args.getLastArg(options::OPT_save_temps_EQ))
8764753f127fSDimitry Andric     CmdArgs.push_back("--save-temps");
87651fd87a68SDimitry Andric 
8766d56accc7SDimitry Andric   // Construct the link job so we can wrap around it.
8767d56accc7SDimitry Andric   Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8768d56accc7SDimitry Andric   const auto &LinkCommand = C.getJobs().getJobs().back();
8769d56accc7SDimitry Andric 
877081ad6265SDimitry Andric   // Forward -Xoffload-linker<-triple> arguments to the device link job.
8771753f127fSDimitry Andric   for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
8772753f127fSDimitry Andric     StringRef Val = A->getValue(0);
877381ad6265SDimitry Andric     if (Val.empty())
877481ad6265SDimitry Andric       CmdArgs.push_back(
8775753f127fSDimitry Andric           Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
877681ad6265SDimitry Andric     else
877781ad6265SDimitry Andric       CmdArgs.push_back(Args.MakeArgString(
8778753f127fSDimitry Andric           "--device-linker=" +
877981ad6265SDimitry Andric           ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
8780753f127fSDimitry Andric           A->getValue(1)));
878181ad6265SDimitry Andric   }
878281ad6265SDimitry Andric   Args.ClaimAllArgs(options::OPT_Xoffload_linker);
878381ad6265SDimitry Andric 
8784bdd1243dSDimitry Andric   // Embed bitcode instead of an object in JIT mode.
8785bdd1243dSDimitry Andric   if (Args.hasFlag(options::OPT_fopenmp_target_jit,
8786bdd1243dSDimitry Andric                    options::OPT_fno_openmp_target_jit, false))
8787bdd1243dSDimitry Andric     CmdArgs.push_back("--embed-bitcode");
8788bdd1243dSDimitry Andric 
8789753f127fSDimitry Andric   // Forward `-mllvm` arguments to the LLVM invocations if present.
8790753f127fSDimitry Andric   for (Arg *A : Args.filtered(options::OPT_mllvm)) {
8791753f127fSDimitry Andric     CmdArgs.push_back("-mllvm");
8792753f127fSDimitry Andric     CmdArgs.push_back(A->getValue());
8793753f127fSDimitry Andric     A->claim();
8794753f127fSDimitry Andric   }
8795753f127fSDimitry Andric 
87961fd87a68SDimitry Andric   // Add the linker arguments to be forwarded by the wrapper.
8797753f127fSDimitry Andric   CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
8798753f127fSDimitry Andric                                        LinkCommand->getExecutable()));
87991fd87a68SDimitry Andric   CmdArgs.push_back("--");
88001fd87a68SDimitry Andric   for (const char *LinkArg : LinkCommand->getArguments())
88011fd87a68SDimitry Andric     CmdArgs.push_back(LinkArg);
88021fd87a68SDimitry Andric 
88031fd87a68SDimitry Andric   const char *Exec =
88041fd87a68SDimitry Andric       Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
88051fd87a68SDimitry Andric 
88061fd87a68SDimitry Andric   // Replace the executable and arguments of the link job with the
88071fd87a68SDimitry Andric   // wrapper.
88081fd87a68SDimitry Andric   LinkCommand->replaceExecutable(Exec);
88091fd87a68SDimitry Andric   LinkCommand->replaceArguments(CmdArgs);
88101fd87a68SDimitry Andric }
8811