xref: /openbsd-src/gnu/llvm/clang/lib/Driver/ToolChains/Clang.cpp (revision 896063e4d924bef6229f6695f274b5282f1e3d23)
1e5dd7070Spatrick //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick 
9e5dd7070Spatrick #include "Clang.h"
10adae0cfdSpatrick #include "AMDGPU.h"
11e5dd7070Spatrick #include "Arch/AArch64.h"
12e5dd7070Spatrick #include "Arch/ARM.h"
137a9b00ceSrobert #include "Arch/CSKY.h"
147a9b00ceSrobert #include "Arch/LoongArch.h"
15a0747c9fSpatrick #include "Arch/M68k.h"
16e5dd7070Spatrick #include "Arch/Mips.h"
17e5dd7070Spatrick #include "Arch/PPC.h"
18e5dd7070Spatrick #include "Arch/RISCV.h"
19e5dd7070Spatrick #include "Arch/Sparc.h"
20e5dd7070Spatrick #include "Arch/SystemZ.h"
21adae0cfdSpatrick #include "Arch/VE.h"
22e5dd7070Spatrick #include "Arch/X86.h"
23e5dd7070Spatrick #include "CommonArgs.h"
24e5dd7070Spatrick #include "Hexagon.h"
25adae0cfdSpatrick #include "MSP430.h"
26e5dd7070Spatrick #include "PS4CPU.h"
277a9b00ceSrobert #include "clang/Basic/CLWarnings.h"
28e5dd7070Spatrick #include "clang/Basic/CharInfo.h"
29e5dd7070Spatrick #include "clang/Basic/CodeGenOptions.h"
307a9b00ceSrobert #include "clang/Basic/HeaderInclude.h"
31e5dd7070Spatrick #include "clang/Basic/LangOptions.h"
327a9b00ceSrobert #include "clang/Basic/MakeSupport.h"
33e5dd7070Spatrick #include "clang/Basic/ObjCRuntime.h"
34e5dd7070Spatrick #include "clang/Basic/Version.h"
357a9b00ceSrobert #include "clang/Config/config.h"
367a9b00ceSrobert #include "clang/Driver/Action.h"
37e5dd7070Spatrick #include "clang/Driver/Distro.h"
38e5dd7070Spatrick #include "clang/Driver/DriverDiagnostic.h"
39a0747c9fSpatrick #include "clang/Driver/InputInfo.h"
40e5dd7070Spatrick #include "clang/Driver/Options.h"
41e5dd7070Spatrick #include "clang/Driver/SanitizerArgs.h"
427a9b00ceSrobert #include "clang/Driver/Types.h"
43e5dd7070Spatrick #include "clang/Driver/XRayArgs.h"
447a9b00ceSrobert #include "llvm/ADT/SmallSet.h"
45e5dd7070Spatrick #include "llvm/ADT/StringExtras.h"
46e5dd7070Spatrick #include "llvm/Config/llvm-config.h"
47e5dd7070Spatrick #include "llvm/Option/ArgList.h"
487a9b00ceSrobert #include "llvm/Support/ARMTargetParserCommon.h"
49e5dd7070Spatrick #include "llvm/Support/CodeGen.h"
50adae0cfdSpatrick #include "llvm/Support/Compiler.h"
51e5dd7070Spatrick #include "llvm/Support/Compression.h"
52e5dd7070Spatrick #include "llvm/Support/FileSystem.h"
53a0747c9fSpatrick #include "llvm/Support/Host.h"
54e5dd7070Spatrick #include "llvm/Support/Path.h"
55e5dd7070Spatrick #include "llvm/Support/Process.h"
56e5dd7070Spatrick #include "llvm/Support/YAMLParser.h"
577a9b00ceSrobert #include <cctype>
58e5dd7070Spatrick 
59e5dd7070Spatrick using namespace clang::driver;
60e5dd7070Spatrick using namespace clang::driver::tools;
61e5dd7070Spatrick using namespace clang;
62e5dd7070Spatrick using namespace llvm::opt;
63e5dd7070Spatrick 
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)64e5dd7070Spatrick static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
657a9b00ceSrobert   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
667a9b00ceSrobert                                options::OPT_fminimize_whitespace,
677a9b00ceSrobert                                options::OPT_fno_minimize_whitespace)) {
68e5dd7070Spatrick     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
69e5dd7070Spatrick         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
70e5dd7070Spatrick       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
71e5dd7070Spatrick           << A->getBaseArg().getAsString(Args)
72e5dd7070Spatrick           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
73e5dd7070Spatrick     }
74e5dd7070Spatrick   }
75e5dd7070Spatrick }
76e5dd7070Spatrick 
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)77e5dd7070Spatrick static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
78e5dd7070Spatrick   // In gcc, only ARM checks this, but it seems reasonable to check universally.
79e5dd7070Spatrick   if (Args.hasArg(options::OPT_static))
80e5dd7070Spatrick     if (const Arg *A =
81e5dd7070Spatrick             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
82e5dd7070Spatrick       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
83e5dd7070Spatrick                                                       << "-static";
84e5dd7070Spatrick }
85e5dd7070Spatrick 
86e5dd7070Spatrick // Add backslashes to escape spaces and other backslashes.
87e5dd7070Spatrick // This is used for the space-separated argument list specified with
88e5dd7070Spatrick // the -dwarf-debug-flags option.
EscapeSpacesAndBackslashes(const char * Arg,SmallVectorImpl<char> & Res)89e5dd7070Spatrick static void EscapeSpacesAndBackslashes(const char *Arg,
90e5dd7070Spatrick                                        SmallVectorImpl<char> &Res) {
91e5dd7070Spatrick   for (; *Arg; ++Arg) {
92e5dd7070Spatrick     switch (*Arg) {
93e5dd7070Spatrick     default:
94e5dd7070Spatrick       break;
95e5dd7070Spatrick     case ' ':
96e5dd7070Spatrick     case '\\':
97e5dd7070Spatrick       Res.push_back('\\');
98e5dd7070Spatrick       break;
99e5dd7070Spatrick     }
100e5dd7070Spatrick     Res.push_back(*Arg);
101e5dd7070Spatrick   }
102e5dd7070Spatrick }
103e5dd7070Spatrick 
104e5dd7070Spatrick /// Apply \a Work on the current tool chain \a RegularToolChain and any other
105e5dd7070Spatrick /// offloading tool chain that is associated with the current action \a JA.
106e5dd7070Spatrick static void
forAllAssociatedToolChains(Compilation & C,const JobAction & JA,const ToolChain & RegularToolChain,llvm::function_ref<void (const ToolChain &)> Work)107e5dd7070Spatrick forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
108e5dd7070Spatrick                            const ToolChain &RegularToolChain,
109e5dd7070Spatrick                            llvm::function_ref<void(const ToolChain &)> Work) {
110e5dd7070Spatrick   // Apply Work on the current/regular tool chain.
111e5dd7070Spatrick   Work(RegularToolChain);
112e5dd7070Spatrick 
113e5dd7070Spatrick   // Apply Work on all the offloading tool chains associated with the current
114e5dd7070Spatrick   // action.
115e5dd7070Spatrick   if (JA.isHostOffloading(Action::OFK_Cuda))
116e5dd7070Spatrick     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
117e5dd7070Spatrick   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
118e5dd7070Spatrick     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
119e5dd7070Spatrick   else if (JA.isHostOffloading(Action::OFK_HIP))
120e5dd7070Spatrick     Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
121e5dd7070Spatrick   else if (JA.isDeviceOffloading(Action::OFK_HIP))
122e5dd7070Spatrick     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
123e5dd7070Spatrick 
124e5dd7070Spatrick   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
125e5dd7070Spatrick     auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
126e5dd7070Spatrick     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
127e5dd7070Spatrick       Work(*II->second);
128e5dd7070Spatrick   } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
129e5dd7070Spatrick     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
130e5dd7070Spatrick 
131e5dd7070Spatrick   //
132e5dd7070Spatrick   // TODO: Add support for other offloading programming models here.
133e5dd7070Spatrick   //
134e5dd7070Spatrick }
135e5dd7070Spatrick 
136e5dd7070Spatrick /// This is a helper function for validating the optional refinement step
137e5dd7070Spatrick /// parameter in reciprocal argument strings. Return false if there is an error
138e5dd7070Spatrick /// parsing the refinement step. Otherwise, return true and set the Position
139e5dd7070Spatrick /// of the refinement step in the input string.
getRefinementStep(StringRef In,const Driver & D,const Arg & A,size_t & Position)140e5dd7070Spatrick static bool getRefinementStep(StringRef In, const Driver &D,
141e5dd7070Spatrick                               const Arg &A, size_t &Position) {
142e5dd7070Spatrick   const char RefinementStepToken = ':';
143e5dd7070Spatrick   Position = In.find(RefinementStepToken);
144e5dd7070Spatrick   if (Position != StringRef::npos) {
145e5dd7070Spatrick     StringRef Option = A.getOption().getName();
146e5dd7070Spatrick     StringRef RefStep = In.substr(Position + 1);
147e5dd7070Spatrick     // Allow exactly one numeric character for the additional refinement
148e5dd7070Spatrick     // step parameter. This is reasonable for all currently-supported
149e5dd7070Spatrick     // operations and architectures because we would expect that a larger value
150e5dd7070Spatrick     // of refinement steps would cause the estimate "optimization" to
151e5dd7070Spatrick     // under-perform the native operation. Also, if the estimate does not
152e5dd7070Spatrick     // converge quickly, it probably will not ever converge, so further
153e5dd7070Spatrick     // refinement steps will not produce a better answer.
154e5dd7070Spatrick     if (RefStep.size() != 1) {
155e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
156e5dd7070Spatrick       return false;
157e5dd7070Spatrick     }
158e5dd7070Spatrick     char RefStepChar = RefStep[0];
159e5dd7070Spatrick     if (RefStepChar < '0' || RefStepChar > '9') {
160e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
161e5dd7070Spatrick       return false;
162e5dd7070Spatrick     }
163e5dd7070Spatrick   }
164e5dd7070Spatrick   return true;
165e5dd7070Spatrick }
166e5dd7070Spatrick 
167e5dd7070Spatrick /// The -mrecip flag requires processing of many optional parameters.
ParseMRecip(const Driver & D,const ArgList & Args,ArgStringList & OutStrings)168e5dd7070Spatrick static void ParseMRecip(const Driver &D, const ArgList &Args,
169e5dd7070Spatrick                         ArgStringList &OutStrings) {
170e5dd7070Spatrick   StringRef DisabledPrefixIn = "!";
171e5dd7070Spatrick   StringRef DisabledPrefixOut = "!";
172e5dd7070Spatrick   StringRef EnabledPrefixOut = "";
173e5dd7070Spatrick   StringRef Out = "-mrecip=";
174e5dd7070Spatrick 
175e5dd7070Spatrick   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
176e5dd7070Spatrick   if (!A)
177e5dd7070Spatrick     return;
178e5dd7070Spatrick 
179e5dd7070Spatrick   unsigned NumOptions = A->getNumValues();
180e5dd7070Spatrick   if (NumOptions == 0) {
181e5dd7070Spatrick     // No option is the same as "all".
182e5dd7070Spatrick     OutStrings.push_back(Args.MakeArgString(Out + "all"));
183e5dd7070Spatrick     return;
184e5dd7070Spatrick   }
185e5dd7070Spatrick 
186e5dd7070Spatrick   // Pass through "all", "none", or "default" with an optional refinement step.
187e5dd7070Spatrick   if (NumOptions == 1) {
188e5dd7070Spatrick     StringRef Val = A->getValue(0);
189e5dd7070Spatrick     size_t RefStepLoc;
190e5dd7070Spatrick     if (!getRefinementStep(Val, D, *A, RefStepLoc))
191e5dd7070Spatrick       return;
192e5dd7070Spatrick     StringRef ValBase = Val.slice(0, RefStepLoc);
193e5dd7070Spatrick     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
194e5dd7070Spatrick       OutStrings.push_back(Args.MakeArgString(Out + Val));
195e5dd7070Spatrick       return;
196e5dd7070Spatrick     }
197e5dd7070Spatrick   }
198e5dd7070Spatrick 
199e5dd7070Spatrick   // Each reciprocal type may be enabled or disabled individually.
200e5dd7070Spatrick   // Check each input value for validity, concatenate them all back together,
201e5dd7070Spatrick   // and pass through.
202e5dd7070Spatrick 
203e5dd7070Spatrick   llvm::StringMap<bool> OptionStrings;
204e5dd7070Spatrick   OptionStrings.insert(std::make_pair("divd", false));
205e5dd7070Spatrick   OptionStrings.insert(std::make_pair("divf", false));
2067a9b00ceSrobert   OptionStrings.insert(std::make_pair("divh", false));
207e5dd7070Spatrick   OptionStrings.insert(std::make_pair("vec-divd", false));
208e5dd7070Spatrick   OptionStrings.insert(std::make_pair("vec-divf", false));
2097a9b00ceSrobert   OptionStrings.insert(std::make_pair("vec-divh", false));
210e5dd7070Spatrick   OptionStrings.insert(std::make_pair("sqrtd", false));
211e5dd7070Spatrick   OptionStrings.insert(std::make_pair("sqrtf", false));
2127a9b00ceSrobert   OptionStrings.insert(std::make_pair("sqrth", false));
213e5dd7070Spatrick   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
214e5dd7070Spatrick   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
2157a9b00ceSrobert   OptionStrings.insert(std::make_pair("vec-sqrth", false));
216e5dd7070Spatrick 
217e5dd7070Spatrick   for (unsigned i = 0; i != NumOptions; ++i) {
218e5dd7070Spatrick     StringRef Val = A->getValue(i);
219e5dd7070Spatrick 
220e5dd7070Spatrick     bool IsDisabled = Val.startswith(DisabledPrefixIn);
221e5dd7070Spatrick     // Ignore the disablement token for string matching.
222e5dd7070Spatrick     if (IsDisabled)
223e5dd7070Spatrick       Val = Val.substr(1);
224e5dd7070Spatrick 
225e5dd7070Spatrick     size_t RefStep;
226e5dd7070Spatrick     if (!getRefinementStep(Val, D, *A, RefStep))
227e5dd7070Spatrick       return;
228e5dd7070Spatrick 
229e5dd7070Spatrick     StringRef ValBase = Val.slice(0, RefStep);
230e5dd7070Spatrick     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
231e5dd7070Spatrick     if (OptionIter == OptionStrings.end()) {
232e5dd7070Spatrick       // Try again specifying float suffix.
233e5dd7070Spatrick       OptionIter = OptionStrings.find(ValBase.str() + 'f');
234e5dd7070Spatrick       if (OptionIter == OptionStrings.end()) {
235e5dd7070Spatrick         // The input name did not match any known option string.
236e5dd7070Spatrick         D.Diag(diag::err_drv_unknown_argument) << Val;
237e5dd7070Spatrick         return;
238e5dd7070Spatrick       }
2397a9b00ceSrobert       // The option was specified without a half or float or double suffix.
2407a9b00ceSrobert       // Make sure that the double or half entry was not already specified.
241e5dd7070Spatrick       // The float entry will be checked below.
2427a9b00ceSrobert       if (OptionStrings[ValBase.str() + 'd'] ||
2437a9b00ceSrobert           OptionStrings[ValBase.str() + 'h']) {
244e5dd7070Spatrick         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
245e5dd7070Spatrick         return;
246e5dd7070Spatrick       }
247e5dd7070Spatrick     }
248e5dd7070Spatrick 
249e5dd7070Spatrick     if (OptionIter->second == true) {
250e5dd7070Spatrick       // Duplicate option specified.
251e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
252e5dd7070Spatrick       return;
253e5dd7070Spatrick     }
254e5dd7070Spatrick 
255e5dd7070Spatrick     // Mark the matched option as found. Do not allow duplicate specifiers.
256e5dd7070Spatrick     OptionIter->second = true;
257e5dd7070Spatrick 
2587a9b00ceSrobert     // If the precision was not specified, also mark the double and half entry
2597a9b00ceSrobert     // as found.
2607a9b00ceSrobert     if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
261e5dd7070Spatrick       OptionStrings[ValBase.str() + 'd'] = true;
2627a9b00ceSrobert       OptionStrings[ValBase.str() + 'h'] = true;
2637a9b00ceSrobert     }
264e5dd7070Spatrick 
265e5dd7070Spatrick     // Build the output string.
266e5dd7070Spatrick     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
267e5dd7070Spatrick     Out = Args.MakeArgString(Out + Prefix + Val);
268e5dd7070Spatrick     if (i != NumOptions - 1)
269e5dd7070Spatrick       Out = Args.MakeArgString(Out + ",");
270e5dd7070Spatrick   }
271e5dd7070Spatrick 
272e5dd7070Spatrick   OutStrings.push_back(Args.MakeArgString(Out));
273e5dd7070Spatrick }
274e5dd7070Spatrick 
275e5dd7070Spatrick /// The -mprefer-vector-width option accepts either a positive integer
276e5dd7070Spatrick /// or the string "none".
ParseMPreferVectorWidth(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)277e5dd7070Spatrick static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
278e5dd7070Spatrick                                     ArgStringList &CmdArgs) {
279e5dd7070Spatrick   Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
280e5dd7070Spatrick   if (!A)
281e5dd7070Spatrick     return;
282e5dd7070Spatrick 
283e5dd7070Spatrick   StringRef Value = A->getValue();
284e5dd7070Spatrick   if (Value == "none") {
285e5dd7070Spatrick     CmdArgs.push_back("-mprefer-vector-width=none");
286e5dd7070Spatrick   } else {
287e5dd7070Spatrick     unsigned Width;
288e5dd7070Spatrick     if (Value.getAsInteger(10, Width)) {
289e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
290e5dd7070Spatrick       return;
291e5dd7070Spatrick     }
292e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
293e5dd7070Spatrick   }
294e5dd7070Spatrick }
295e5dd7070Spatrick 
296e5dd7070Spatrick static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)297e5dd7070Spatrick shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
298e5dd7070Spatrick                                           const llvm::Triple &Triple) {
299e5dd7070Spatrick   // We use the zero-cost exception tables for Objective-C if the non-fragile
300e5dd7070Spatrick   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
301e5dd7070Spatrick   // later.
302e5dd7070Spatrick   if (runtime.isNonFragile())
303e5dd7070Spatrick     return true;
304e5dd7070Spatrick 
305e5dd7070Spatrick   if (!Triple.isMacOSX())
306e5dd7070Spatrick     return false;
307e5dd7070Spatrick 
308e5dd7070Spatrick   return (!Triple.isMacOSXVersionLT(10, 5) &&
309e5dd7070Spatrick           (Triple.getArch() == llvm::Triple::x86_64 ||
310e5dd7070Spatrick            Triple.getArch() == llvm::Triple::arm));
311e5dd7070Spatrick }
312e5dd7070Spatrick 
313e5dd7070Spatrick /// Adds exception related arguments to the driver command arguments. There's a
3147a9b00ceSrobert /// main flag, -fexceptions and also language specific flags to enable/disable
315e5dd7070Spatrick /// C++ and Objective-C exceptions. This makes it possible to for example
316e5dd7070Spatrick /// disable C++ exceptions but enable Objective-C exceptions.
addExceptionArgs(const ArgList & Args,types::ID InputType,const ToolChain & TC,bool KernelOrKext,const ObjCRuntime & objcRuntime,ArgStringList & CmdArgs)317a0747c9fSpatrick static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
318e5dd7070Spatrick                              const ToolChain &TC, bool KernelOrKext,
319e5dd7070Spatrick                              const ObjCRuntime &objcRuntime,
320e5dd7070Spatrick                              ArgStringList &CmdArgs) {
321e5dd7070Spatrick   const llvm::Triple &Triple = TC.getTriple();
322e5dd7070Spatrick 
323e5dd7070Spatrick   if (KernelOrKext) {
324e5dd7070Spatrick     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
325e5dd7070Spatrick     // arguments now to avoid warnings about unused arguments.
326e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fexceptions);
327e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fno_exceptions);
328e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
329e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
330e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
331e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
332a0747c9fSpatrick     Args.ClaimAllArgs(options::OPT_fasync_exceptions);
333a0747c9fSpatrick     Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
334a0747c9fSpatrick     return false;
335e5dd7070Spatrick   }
336e5dd7070Spatrick 
337e5dd7070Spatrick   // See if the user explicitly enabled exceptions.
338e5dd7070Spatrick   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
339e5dd7070Spatrick                          false);
340e5dd7070Spatrick 
341a0747c9fSpatrick   bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
342a0747c9fSpatrick                           options::OPT_fno_async_exceptions, false);
343a0747c9fSpatrick   if (EHa) {
344a0747c9fSpatrick     CmdArgs.push_back("-fasync-exceptions");
345a0747c9fSpatrick     EH = true;
346a0747c9fSpatrick   }
347a0747c9fSpatrick 
348e5dd7070Spatrick   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
349e5dd7070Spatrick   // is not necessarily sensible, but follows GCC.
350e5dd7070Spatrick   if (types::isObjC(InputType) &&
351e5dd7070Spatrick       Args.hasFlag(options::OPT_fobjc_exceptions,
352e5dd7070Spatrick                    options::OPT_fno_objc_exceptions, true)) {
353e5dd7070Spatrick     CmdArgs.push_back("-fobjc-exceptions");
354e5dd7070Spatrick 
355e5dd7070Spatrick     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
356e5dd7070Spatrick   }
357e5dd7070Spatrick 
358e5dd7070Spatrick   if (types::isCXX(InputType)) {
3597a9b00ceSrobert     // Disable C++ EH by default on XCore and PS4/PS5.
3607a9b00ceSrobert     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
3617a9b00ceSrobert                                 !Triple.isPS() && !Triple.isDriverKit();
362e5dd7070Spatrick     Arg *ExceptionArg = Args.getLastArg(
363e5dd7070Spatrick         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
364e5dd7070Spatrick         options::OPT_fexceptions, options::OPT_fno_exceptions);
365e5dd7070Spatrick     if (ExceptionArg)
366e5dd7070Spatrick       CXXExceptionsEnabled =
367e5dd7070Spatrick           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
368e5dd7070Spatrick           ExceptionArg->getOption().matches(options::OPT_fexceptions);
369e5dd7070Spatrick 
370e5dd7070Spatrick     if (CXXExceptionsEnabled) {
371e5dd7070Spatrick       CmdArgs.push_back("-fcxx-exceptions");
372e5dd7070Spatrick 
373e5dd7070Spatrick       EH = true;
374e5dd7070Spatrick     }
375e5dd7070Spatrick   }
376e5dd7070Spatrick 
377adae0cfdSpatrick   // OPT_fignore_exceptions means exception could still be thrown,
378adae0cfdSpatrick   // but no clean up or catch would happen in current module.
379adae0cfdSpatrick   // So we do not set EH to false.
380adae0cfdSpatrick   Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
381adae0cfdSpatrick 
382e5dd7070Spatrick   if (EH)
383e5dd7070Spatrick     CmdArgs.push_back("-fexceptions");
384a0747c9fSpatrick   return EH;
385e5dd7070Spatrick }
386e5dd7070Spatrick 
ShouldEnableAutolink(const ArgList & Args,const ToolChain & TC,const JobAction & JA)387e5dd7070Spatrick static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
388e5dd7070Spatrick                                  const JobAction &JA) {
389e5dd7070Spatrick   bool Default = true;
390e5dd7070Spatrick   if (TC.getTriple().isOSDarwin()) {
391e5dd7070Spatrick     // The native darwin assembler doesn't support the linker_option directives,
392e5dd7070Spatrick     // so we disable them if we think the .s file will be passed to it.
393e5dd7070Spatrick     Default = TC.useIntegratedAs();
394e5dd7070Spatrick   }
395e5dd7070Spatrick   // The linker_option directives are intended for host compilation.
396e5dd7070Spatrick   if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
397e5dd7070Spatrick       JA.isDeviceOffloading(Action::OFK_HIP))
398e5dd7070Spatrick     Default = false;
399e5dd7070Spatrick   return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
400e5dd7070Spatrick                       Default);
401e5dd7070Spatrick }
402e5dd7070Spatrick 
403e5dd7070Spatrick // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
404e5dd7070Spatrick // to the corresponding DebugInfoKind.
DebugLevelToInfoKind(const Arg & A)405e5dd7070Spatrick static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
406e5dd7070Spatrick   assert(A.getOption().matches(options::OPT_gN_Group) &&
407e5dd7070Spatrick          "Not a -g option that specifies a debug-info level");
408e5dd7070Spatrick   if (A.getOption().matches(options::OPT_g0) ||
409e5dd7070Spatrick       A.getOption().matches(options::OPT_ggdb0))
410e5dd7070Spatrick     return codegenoptions::NoDebugInfo;
411e5dd7070Spatrick   if (A.getOption().matches(options::OPT_gline_tables_only) ||
412e5dd7070Spatrick       A.getOption().matches(options::OPT_ggdb1))
413e5dd7070Spatrick     return codegenoptions::DebugLineTablesOnly;
414e5dd7070Spatrick   if (A.getOption().matches(options::OPT_gline_directives_only))
415e5dd7070Spatrick     return codegenoptions::DebugDirectivesOnly;
416a0747c9fSpatrick   return codegenoptions::DebugInfoConstructor;
417e5dd7070Spatrick }
418e5dd7070Spatrick 
mustUseNonLeafFramePointerForTarget(const llvm::Triple & Triple)419e5dd7070Spatrick static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
420e5dd7070Spatrick   switch (Triple.getArch()){
421e5dd7070Spatrick   default:
422e5dd7070Spatrick     return false;
423e5dd7070Spatrick   case llvm::Triple::arm:
424e5dd7070Spatrick   case llvm::Triple::thumb:
425e5dd7070Spatrick     // ARM Darwin targets require a frame pointer to be always present to aid
426e5dd7070Spatrick     // offline debugging via backtraces.
427e5dd7070Spatrick     return Triple.isOSDarwin();
428e5dd7070Spatrick   }
429e5dd7070Spatrick }
430e5dd7070Spatrick 
useFramePointerForTargetByDefault(const ArgList & Args,const llvm::Triple & Triple)431e5dd7070Spatrick static bool useFramePointerForTargetByDefault(const ArgList &Args,
432e5dd7070Spatrick                                               const llvm::Triple &Triple) {
433adae0cfdSpatrick   if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
434e5dd7070Spatrick     return true;
435e5dd7070Spatrick 
436e5dd7070Spatrick   switch (Triple.getArch()) {
437e5dd7070Spatrick   case llvm::Triple::xcore:
438e5dd7070Spatrick   case llvm::Triple::wasm32:
439e5dd7070Spatrick   case llvm::Triple::wasm64:
440e5dd7070Spatrick   case llvm::Triple::msp430:
441e5dd7070Spatrick     // XCore never wants frame pointers, regardless of OS.
442e5dd7070Spatrick     // WebAssembly never wants frame pointers.
443e5dd7070Spatrick     return false;
444e5dd7070Spatrick   case llvm::Triple::ppc:
445a0747c9fSpatrick   case llvm::Triple::ppcle:
446e5dd7070Spatrick   case llvm::Triple::ppc64:
447e5dd7070Spatrick   case llvm::Triple::ppc64le:
448e5dd7070Spatrick   case llvm::Triple::riscv32:
449e5dd7070Spatrick   case llvm::Triple::riscv64:
4507a9b00ceSrobert   case llvm::Triple::sparc:
4517a9b00ceSrobert   case llvm::Triple::sparcel:
4527a9b00ceSrobert   case llvm::Triple::sparcv9:
453e5dd7070Spatrick   case llvm::Triple::amdgcn:
454e5dd7070Spatrick   case llvm::Triple::r600:
4557a9b00ceSrobert   case llvm::Triple::csky:
4567a9b00ceSrobert   case llvm::Triple::loongarch32:
4577a9b00ceSrobert   case llvm::Triple::loongarch64:
458e5dd7070Spatrick     return !areOptimizationsEnabled(Args);
459e5dd7070Spatrick   default:
460e5dd7070Spatrick     break;
461e5dd7070Spatrick   }
462e5dd7070Spatrick 
4637a9b00ceSrobert   if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
464e5dd7070Spatrick     return !areOptimizationsEnabled(Args);
465e5dd7070Spatrick   }
466e5dd7070Spatrick 
467e5dd7070Spatrick   if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
468e5dd7070Spatrick       Triple.isOSHurd()) {
469e5dd7070Spatrick     switch (Triple.getArch()) {
470e5dd7070Spatrick     // Don't use a frame pointer on linux if optimizing for certain targets.
471adae0cfdSpatrick     case llvm::Triple::arm:
472adae0cfdSpatrick     case llvm::Triple::armeb:
473adae0cfdSpatrick     case llvm::Triple::thumb:
474adae0cfdSpatrick     case llvm::Triple::thumbeb:
475adae0cfdSpatrick       if (Triple.isAndroid())
476adae0cfdSpatrick         return true;
4777a9b00ceSrobert       [[fallthrough]];
478e5dd7070Spatrick     case llvm::Triple::mips64:
479e5dd7070Spatrick     case llvm::Triple::mips64el:
480e5dd7070Spatrick     case llvm::Triple::mips:
481e5dd7070Spatrick     case llvm::Triple::mipsel:
482e5dd7070Spatrick     case llvm::Triple::systemz:
483e5dd7070Spatrick     case llvm::Triple::x86:
484e5dd7070Spatrick     case llvm::Triple::x86_64:
485e5dd7070Spatrick       return !areOptimizationsEnabled(Args);
486e5dd7070Spatrick     default:
487e5dd7070Spatrick       return true;
488e5dd7070Spatrick     }
489e5dd7070Spatrick   }
490e5dd7070Spatrick 
491e5dd7070Spatrick   if (Triple.isOSWindows()) {
492e5dd7070Spatrick     switch (Triple.getArch()) {
493e5dd7070Spatrick     case llvm::Triple::x86:
494e5dd7070Spatrick       return !areOptimizationsEnabled(Args);
495e5dd7070Spatrick     case llvm::Triple::x86_64:
496e5dd7070Spatrick       return Triple.isOSBinFormatMachO();
497e5dd7070Spatrick     case llvm::Triple::arm:
498e5dd7070Spatrick     case llvm::Triple::thumb:
499e5dd7070Spatrick       // Windows on ARM builds with FPO disabled to aid fast stack walking
500e5dd7070Spatrick       return true;
501e5dd7070Spatrick     default:
502e5dd7070Spatrick       // All other supported Windows ISAs use xdata unwind information, so frame
503e5dd7070Spatrick       // pointers are not generally useful.
504e5dd7070Spatrick       return false;
505e5dd7070Spatrick     }
506e5dd7070Spatrick   }
507e5dd7070Spatrick 
508e5dd7070Spatrick   return true;
509e5dd7070Spatrick }
510e5dd7070Spatrick 
511e5dd7070Spatrick static CodeGenOptions::FramePointerKind
getFramePointerKind(const ArgList & Args,const llvm::Triple & Triple)512e5dd7070Spatrick getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
513e5dd7070Spatrick   // We have 4 states:
514e5dd7070Spatrick   //
515e5dd7070Spatrick   //  00) leaf retained, non-leaf retained
516e5dd7070Spatrick   //  01) leaf retained, non-leaf omitted (this is invalid)
517e5dd7070Spatrick   //  10) leaf omitted, non-leaf retained
518e5dd7070Spatrick   //      (what -momit-leaf-frame-pointer was designed for)
519e5dd7070Spatrick   //  11) leaf omitted, non-leaf omitted
520e5dd7070Spatrick   //
521e5dd7070Spatrick   //  "omit" options taking precedence over "no-omit" options is the only way
522e5dd7070Spatrick   //  to make 3 valid states representable
523e5dd7070Spatrick   Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
524e5dd7070Spatrick                            options::OPT_fno_omit_frame_pointer);
525e5dd7070Spatrick   bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
526e5dd7070Spatrick   bool NoOmitFP =
527e5dd7070Spatrick       A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
5287a9b00ceSrobert   bool OmitLeafFP =
5297a9b00ceSrobert       Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
530e5dd7070Spatrick                    options::OPT_mno_omit_leaf_frame_pointer,
5317a9b00ceSrobert                    Triple.isAArch64() || Triple.isPS() || Triple.isVE());
532e5dd7070Spatrick   if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
533e5dd7070Spatrick       (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
534a0747c9fSpatrick     if (OmitLeafFP)
535e5dd7070Spatrick       return CodeGenOptions::FramePointerKind::NonLeaf;
536e5dd7070Spatrick     return CodeGenOptions::FramePointerKind::All;
537e5dd7070Spatrick   }
538e5dd7070Spatrick   return CodeGenOptions::FramePointerKind::None;
539e5dd7070Spatrick }
540e5dd7070Spatrick 
541e5dd7070Spatrick /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs,const llvm::vfs::FileSystem & VFS)5427a9b00ceSrobert static const char *addDebugCompDirArg(const ArgList &Args,
5437a9b00ceSrobert                                       ArgStringList &CmdArgs,
544e5dd7070Spatrick                                       const llvm::vfs::FileSystem &VFS) {
545a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
546a0747c9fSpatrick                                options::OPT_fdebug_compilation_dir_EQ)) {
547a0747c9fSpatrick     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
548a0747c9fSpatrick       CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
549a0747c9fSpatrick                                            A->getValue()));
550a0747c9fSpatrick     else
551a0747c9fSpatrick       A->render(Args, CmdArgs);
552e5dd7070Spatrick   } else if (llvm::ErrorOr<std::string> CWD =
553e5dd7070Spatrick                  VFS.getCurrentWorkingDirectory()) {
554a0747c9fSpatrick     CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
555e5dd7070Spatrick   }
5567a9b00ceSrobert   StringRef Path(CmdArgs.back());
5577a9b00ceSrobert   return Path.substr(Path.find('=') + 1).data();
5587a9b00ceSrobert }
5597a9b00ceSrobert 
addDebugObjectName(const ArgList & Args,ArgStringList & CmdArgs,const char * DebugCompilationDir,const char * OutputFileName)5607a9b00ceSrobert static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
5617a9b00ceSrobert                                const char *DebugCompilationDir,
5627a9b00ceSrobert                                const char *OutputFileName) {
5637a9b00ceSrobert   // No need to generate a value for -object-file-name if it was provided.
5647a9b00ceSrobert   for (auto *Arg : Args.filtered(options::OPT_Xclang))
5657a9b00ceSrobert     if (StringRef(Arg->getValue()).startswith("-object-file-name"))
5667a9b00ceSrobert       return;
5677a9b00ceSrobert 
5687a9b00ceSrobert   if (Args.hasArg(options::OPT_object_file_name_EQ))
5697a9b00ceSrobert     return;
5707a9b00ceSrobert 
5717a9b00ceSrobert   SmallString<128> ObjFileNameForDebug(OutputFileName);
5727a9b00ceSrobert   if (ObjFileNameForDebug != "-" &&
5737a9b00ceSrobert       !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
5747a9b00ceSrobert       (!DebugCompilationDir ||
5757a9b00ceSrobert        llvm::sys::path::is_absolute(DebugCompilationDir))) {
5767a9b00ceSrobert     // Make the path absolute in the debug infos like MSVC does.
5777a9b00ceSrobert     llvm::sys::fs::make_absolute(ObjFileNameForDebug);
5787a9b00ceSrobert   }
5797a9b00ceSrobert   CmdArgs.push_back(
5807a9b00ceSrobert       Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
581e5dd7070Spatrick }
582e5dd7070Spatrick 
583e5dd7070Spatrick /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
addDebugPrefixMapArg(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)5847a9b00ceSrobert static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
5857a9b00ceSrobert                                  const ArgList &Args, ArgStringList &CmdArgs) {
5867a9b00ceSrobert   auto AddOneArg = [&](StringRef Map, StringRef Name) {
5877a9b00ceSrobert     if (!Map.contains('='))
5887a9b00ceSrobert       D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
589e5dd7070Spatrick     else
590e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
5917a9b00ceSrobert   };
5927a9b00ceSrobert 
5937a9b00ceSrobert   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
5947a9b00ceSrobert                                     options::OPT_fdebug_prefix_map_EQ)) {
5957a9b00ceSrobert     AddOneArg(A->getValue(), A->getOption().getName());
596e5dd7070Spatrick     A->claim();
597e5dd7070Spatrick   }
5987a9b00ceSrobert   std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
5997a9b00ceSrobert   if (GlobalRemapEntry.empty())
6007a9b00ceSrobert     return;
6017a9b00ceSrobert   AddOneArg(GlobalRemapEntry, "environment");
602e5dd7070Spatrick }
603e5dd7070Spatrick 
604e5dd7070Spatrick /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
addMacroPrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)605e5dd7070Spatrick static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
606e5dd7070Spatrick                                  ArgStringList &CmdArgs) {
607e5dd7070Spatrick   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
608e5dd7070Spatrick                                     options::OPT_fmacro_prefix_map_EQ)) {
609e5dd7070Spatrick     StringRef Map = A->getValue();
6107a9b00ceSrobert     if (!Map.contains('='))
611e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_argument_to_option)
612e5dd7070Spatrick           << Map << A->getOption().getName();
613e5dd7070Spatrick     else
614e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
615e5dd7070Spatrick     A->claim();
616e5dd7070Spatrick   }
617e5dd7070Spatrick }
618e5dd7070Spatrick 
619a0747c9fSpatrick /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
addCoveragePrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)620a0747c9fSpatrick static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
621a0747c9fSpatrick                                    ArgStringList &CmdArgs) {
622a0747c9fSpatrick   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
623a0747c9fSpatrick                                     options::OPT_fcoverage_prefix_map_EQ)) {
624a0747c9fSpatrick     StringRef Map = A->getValue();
6257a9b00ceSrobert     if (!Map.contains('='))
626a0747c9fSpatrick       D.Diag(diag::err_drv_invalid_argument_to_option)
627a0747c9fSpatrick           << Map << A->getOption().getName();
628a0747c9fSpatrick     else
629a0747c9fSpatrick       CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
630a0747c9fSpatrick     A->claim();
631a0747c9fSpatrick   }
632a0747c9fSpatrick }
633a0747c9fSpatrick 
634e5dd7070Spatrick /// Vectorize at all optimization levels greater than 1 except for -Oz.
635e5dd7070Spatrick /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
636e5dd7070Spatrick /// enabled.
shouldEnableVectorizerAtOLevel(const ArgList & Args,bool isSlpVec)637e5dd7070Spatrick static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
638e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
639e5dd7070Spatrick     if (A->getOption().matches(options::OPT_O4) ||
640e5dd7070Spatrick         A->getOption().matches(options::OPT_Ofast))
641e5dd7070Spatrick       return true;
642e5dd7070Spatrick 
643e5dd7070Spatrick     if (A->getOption().matches(options::OPT_O0))
644e5dd7070Spatrick       return false;
645e5dd7070Spatrick 
646e5dd7070Spatrick     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
647e5dd7070Spatrick 
648e5dd7070Spatrick     // Vectorize -Os.
649e5dd7070Spatrick     StringRef S(A->getValue());
650e5dd7070Spatrick     if (S == "s")
651e5dd7070Spatrick       return true;
652e5dd7070Spatrick 
653e5dd7070Spatrick     // Don't vectorize -Oz, unless it's the slp vectorizer.
654e5dd7070Spatrick     if (S == "z")
655e5dd7070Spatrick       return isSlpVec;
656e5dd7070Spatrick 
657e5dd7070Spatrick     unsigned OptLevel = 0;
658e5dd7070Spatrick     if (S.getAsInteger(10, OptLevel))
659e5dd7070Spatrick       return false;
660e5dd7070Spatrick 
661e5dd7070Spatrick     return OptLevel > 1;
662e5dd7070Spatrick   }
663e5dd7070Spatrick 
664e5dd7070Spatrick   return false;
665e5dd7070Spatrick }
666e5dd7070Spatrick 
667e5dd7070Spatrick /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)668e5dd7070Spatrick static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
669e5dd7070Spatrick                              ArgStringList &CmdArgs) {
670e5dd7070Spatrick   // When using -verify-pch, we don't want to provide the type
671e5dd7070Spatrick   // 'precompiled-header' if it was inferred from the file extension
672e5dd7070Spatrick   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
673e5dd7070Spatrick     return;
674e5dd7070Spatrick 
675e5dd7070Spatrick   CmdArgs.push_back("-x");
676e5dd7070Spatrick   if (Args.hasArg(options::OPT_rewrite_objc))
677e5dd7070Spatrick     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
678e5dd7070Spatrick   else {
679e5dd7070Spatrick     // Map the driver type to the frontend type. This is mostly an identity
680e5dd7070Spatrick     // mapping, except that the distinction between module interface units
681e5dd7070Spatrick     // and other source files does not exist at the frontend layer.
682e5dd7070Spatrick     const char *ClangType;
683e5dd7070Spatrick     switch (Input.getType()) {
684e5dd7070Spatrick     case types::TY_CXXModule:
685e5dd7070Spatrick       ClangType = "c++";
686e5dd7070Spatrick       break;
687e5dd7070Spatrick     case types::TY_PP_CXXModule:
688e5dd7070Spatrick       ClangType = "c++-cpp-output";
689e5dd7070Spatrick       break;
690e5dd7070Spatrick     default:
691e5dd7070Spatrick       ClangType = types::getTypeName(Input.getType());
692e5dd7070Spatrick       break;
693e5dd7070Spatrick     }
694e5dd7070Spatrick     CmdArgs.push_back(ClangType);
695e5dd7070Spatrick   }
696e5dd7070Spatrick }
697e5dd7070Spatrick 
addPGOAndCoverageFlags(const ToolChain & TC,Compilation & C,const Driver & D,const InputInfo & Output,const ArgList & Args,SanitizerArgs & SanArgs,ArgStringList & CmdArgs)698e5dd7070Spatrick static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
699e5dd7070Spatrick                                    const Driver &D, const InputInfo &Output,
7007a9b00ceSrobert                                    const ArgList &Args, SanitizerArgs &SanArgs,
701e5dd7070Spatrick                                    ArgStringList &CmdArgs) {
702e5dd7070Spatrick 
703e5dd7070Spatrick   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
704e5dd7070Spatrick                                          options::OPT_fprofile_generate_EQ,
705e5dd7070Spatrick                                          options::OPT_fno_profile_generate);
706e5dd7070Spatrick   if (PGOGenerateArg &&
707e5dd7070Spatrick       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
708e5dd7070Spatrick     PGOGenerateArg = nullptr;
709e5dd7070Spatrick 
710e5dd7070Spatrick   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
711e5dd7070Spatrick                                            options::OPT_fcs_profile_generate_EQ,
712e5dd7070Spatrick                                            options::OPT_fno_profile_generate);
713e5dd7070Spatrick   if (CSPGOGenerateArg &&
714e5dd7070Spatrick       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
715e5dd7070Spatrick     CSPGOGenerateArg = nullptr;
716e5dd7070Spatrick 
717e5dd7070Spatrick   auto *ProfileGenerateArg = Args.getLastArg(
718e5dd7070Spatrick       options::OPT_fprofile_instr_generate,
719e5dd7070Spatrick       options::OPT_fprofile_instr_generate_EQ,
720e5dd7070Spatrick       options::OPT_fno_profile_instr_generate);
721e5dd7070Spatrick   if (ProfileGenerateArg &&
722e5dd7070Spatrick       ProfileGenerateArg->getOption().matches(
723e5dd7070Spatrick           options::OPT_fno_profile_instr_generate))
724e5dd7070Spatrick     ProfileGenerateArg = nullptr;
725e5dd7070Spatrick 
726e5dd7070Spatrick   if (PGOGenerateArg && ProfileGenerateArg)
727e5dd7070Spatrick     D.Diag(diag::err_drv_argument_not_allowed_with)
728e5dd7070Spatrick         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
729e5dd7070Spatrick 
730e5dd7070Spatrick   auto *ProfileUseArg = getLastProfileUseArg(Args);
731e5dd7070Spatrick 
732e5dd7070Spatrick   if (PGOGenerateArg && ProfileUseArg)
733e5dd7070Spatrick     D.Diag(diag::err_drv_argument_not_allowed_with)
734e5dd7070Spatrick         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
735e5dd7070Spatrick 
736e5dd7070Spatrick   if (ProfileGenerateArg && ProfileUseArg)
737e5dd7070Spatrick     D.Diag(diag::err_drv_argument_not_allowed_with)
738e5dd7070Spatrick         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
739e5dd7070Spatrick 
740a0747c9fSpatrick   if (CSPGOGenerateArg && PGOGenerateArg) {
741e5dd7070Spatrick     D.Diag(diag::err_drv_argument_not_allowed_with)
742e5dd7070Spatrick         << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
743a0747c9fSpatrick     PGOGenerateArg = nullptr;
744a0747c9fSpatrick   }
745a0747c9fSpatrick 
746a0747c9fSpatrick   if (TC.getTriple().isOSAIX()) {
747a0747c9fSpatrick     if (ProfileGenerateArg)
748a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
749a0747c9fSpatrick           << ProfileGenerateArg->getSpelling() << TC.getTriple().str();
750a0747c9fSpatrick     if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
751a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
752a0747c9fSpatrick           << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
753a0747c9fSpatrick   }
754e5dd7070Spatrick 
755e5dd7070Spatrick   if (ProfileGenerateArg) {
756e5dd7070Spatrick     if (ProfileGenerateArg->getOption().matches(
757e5dd7070Spatrick             options::OPT_fprofile_instr_generate_EQ))
758e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
759e5dd7070Spatrick                                            ProfileGenerateArg->getValue()));
760e5dd7070Spatrick     // The default is to use Clang Instrumentation.
761e5dd7070Spatrick     CmdArgs.push_back("-fprofile-instrument=clang");
762e5dd7070Spatrick     if (TC.getTriple().isWindowsMSVCEnvironment()) {
763e5dd7070Spatrick       // Add dependent lib for clang_rt.profile
764adae0cfdSpatrick       CmdArgs.push_back(Args.MakeArgString(
765adae0cfdSpatrick           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
766e5dd7070Spatrick     }
767e5dd7070Spatrick   }
768e5dd7070Spatrick 
769e5dd7070Spatrick   Arg *PGOGenArg = nullptr;
770e5dd7070Spatrick   if (PGOGenerateArg) {
771e5dd7070Spatrick     assert(!CSPGOGenerateArg);
772e5dd7070Spatrick     PGOGenArg = PGOGenerateArg;
773e5dd7070Spatrick     CmdArgs.push_back("-fprofile-instrument=llvm");
774e5dd7070Spatrick   }
775e5dd7070Spatrick   if (CSPGOGenerateArg) {
776e5dd7070Spatrick     assert(!PGOGenerateArg);
777e5dd7070Spatrick     PGOGenArg = CSPGOGenerateArg;
778e5dd7070Spatrick     CmdArgs.push_back("-fprofile-instrument=csllvm");
779e5dd7070Spatrick   }
780e5dd7070Spatrick   if (PGOGenArg) {
781e5dd7070Spatrick     if (TC.getTriple().isWindowsMSVCEnvironment()) {
782adae0cfdSpatrick       // Add dependent lib for clang_rt.profile
783adae0cfdSpatrick       CmdArgs.push_back(Args.MakeArgString(
784adae0cfdSpatrick           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
785e5dd7070Spatrick     }
786e5dd7070Spatrick     if (PGOGenArg->getOption().matches(
787e5dd7070Spatrick             PGOGenerateArg ? options::OPT_fprofile_generate_EQ
788e5dd7070Spatrick                            : options::OPT_fcs_profile_generate_EQ)) {
789e5dd7070Spatrick       SmallString<128> Path(PGOGenArg->getValue());
790e5dd7070Spatrick       llvm::sys::path::append(Path, "default_%m.profraw");
791e5dd7070Spatrick       CmdArgs.push_back(
792e5dd7070Spatrick           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
793e5dd7070Spatrick     }
794e5dd7070Spatrick   }
795e5dd7070Spatrick 
796e5dd7070Spatrick   if (ProfileUseArg) {
797e5dd7070Spatrick     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
798e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(
799e5dd7070Spatrick           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
800e5dd7070Spatrick     else if ((ProfileUseArg->getOption().matches(
801e5dd7070Spatrick                   options::OPT_fprofile_use_EQ) ||
802e5dd7070Spatrick               ProfileUseArg->getOption().matches(
803e5dd7070Spatrick                   options::OPT_fprofile_instr_use))) {
804e5dd7070Spatrick       SmallString<128> Path(
805e5dd7070Spatrick           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
806e5dd7070Spatrick       if (Path.empty() || llvm::sys::fs::is_directory(Path))
807e5dd7070Spatrick         llvm::sys::path::append(Path, "default.profdata");
808e5dd7070Spatrick       CmdArgs.push_back(
809e5dd7070Spatrick           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
810e5dd7070Spatrick     }
811e5dd7070Spatrick   }
812e5dd7070Spatrick 
813adae0cfdSpatrick   bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
814adae0cfdSpatrick                                    options::OPT_fno_test_coverage, false) ||
815e5dd7070Spatrick                       Args.hasArg(options::OPT_coverage);
816adae0cfdSpatrick   bool EmitCovData = TC.needsGCovInstrumentation(Args);
817e5dd7070Spatrick   if (EmitCovNotes)
818a0747c9fSpatrick     CmdArgs.push_back("-ftest-coverage");
819e5dd7070Spatrick   if (EmitCovData)
820a0747c9fSpatrick     CmdArgs.push_back("-fprofile-arcs");
821e5dd7070Spatrick 
822e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fcoverage_mapping,
823e5dd7070Spatrick                    options::OPT_fno_coverage_mapping, false)) {
824e5dd7070Spatrick     if (!ProfileGenerateArg)
825e5dd7070Spatrick       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
826e5dd7070Spatrick           << "-fcoverage-mapping"
827e5dd7070Spatrick           << "-fprofile-instr-generate";
828e5dd7070Spatrick 
829e5dd7070Spatrick     CmdArgs.push_back("-fcoverage-mapping");
830e5dd7070Spatrick   }
831e5dd7070Spatrick 
832a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
833a0747c9fSpatrick                                options::OPT_fcoverage_compilation_dir_EQ)) {
834a0747c9fSpatrick     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
835a0747c9fSpatrick       CmdArgs.push_back(Args.MakeArgString(
836a0747c9fSpatrick           Twine("-fcoverage-compilation-dir=") + A->getValue()));
837a0747c9fSpatrick     else
838a0747c9fSpatrick       A->render(Args, CmdArgs);
839a0747c9fSpatrick   } else if (llvm::ErrorOr<std::string> CWD =
840a0747c9fSpatrick                  D.getVFS().getCurrentWorkingDirectory()) {
841a0747c9fSpatrick     CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
842a0747c9fSpatrick   }
843a0747c9fSpatrick 
844e5dd7070Spatrick   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
845e5dd7070Spatrick     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
846e5dd7070Spatrick     if (!Args.hasArg(options::OPT_coverage))
847e5dd7070Spatrick       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
848e5dd7070Spatrick           << "-fprofile-exclude-files="
849e5dd7070Spatrick           << "--coverage";
850e5dd7070Spatrick 
851e5dd7070Spatrick     StringRef v = Arg->getValue();
852e5dd7070Spatrick     CmdArgs.push_back(
853e5dd7070Spatrick         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
854e5dd7070Spatrick   }
855e5dd7070Spatrick 
856e5dd7070Spatrick   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
857e5dd7070Spatrick     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
858e5dd7070Spatrick     if (!Args.hasArg(options::OPT_coverage))
859e5dd7070Spatrick       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
860e5dd7070Spatrick           << "-fprofile-filter-files="
861e5dd7070Spatrick           << "--coverage";
862e5dd7070Spatrick 
863e5dd7070Spatrick     StringRef v = Arg->getValue();
864e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
865e5dd7070Spatrick   }
866e5dd7070Spatrick 
867a0747c9fSpatrick   if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
868a0747c9fSpatrick     StringRef Val = A->getValue();
869a0747c9fSpatrick     if (Val == "atomic" || Val == "prefer-atomic")
870a0747c9fSpatrick       CmdArgs.push_back("-fprofile-update=atomic");
871a0747c9fSpatrick     else if (Val != "single")
872a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_option_argument)
8737a9b00ceSrobert           << A->getSpelling() << Val;
8747a9b00ceSrobert   } else if (SanArgs.needsTsanRt()) {
875a0747c9fSpatrick     CmdArgs.push_back("-fprofile-update=atomic");
876a0747c9fSpatrick   }
877a0747c9fSpatrick 
8787a9b00ceSrobert   int FunctionGroups = 1;
8797a9b00ceSrobert   int SelectedFunctionGroup = 0;
8807a9b00ceSrobert   if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
8817a9b00ceSrobert     StringRef Val = A->getValue();
8827a9b00ceSrobert     if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
8837a9b00ceSrobert       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
8847a9b00ceSrobert   }
8857a9b00ceSrobert   if (const auto *A =
8867a9b00ceSrobert           Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
8877a9b00ceSrobert     StringRef Val = A->getValue();
8887a9b00ceSrobert     if (Val.getAsInteger(0, SelectedFunctionGroup) ||
8897a9b00ceSrobert         SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
8907a9b00ceSrobert       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
8917a9b00ceSrobert   }
8927a9b00ceSrobert   if (FunctionGroups != 1)
8937a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
8947a9b00ceSrobert                                          Twine(FunctionGroups)));
8957a9b00ceSrobert   if (SelectedFunctionGroup != 0)
8967a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
8977a9b00ceSrobert                                          Twine(SelectedFunctionGroup)));
8987a9b00ceSrobert 
899e5dd7070Spatrick   // Leave -fprofile-dir= an unused argument unless .gcda emission is
900e5dd7070Spatrick   // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
901e5dd7070Spatrick   // the flag used. There is no -fno-profile-dir, so the user has no
902e5dd7070Spatrick   // targeted way to suppress the warning.
903e5dd7070Spatrick   Arg *FProfileDir = nullptr;
904e5dd7070Spatrick   if (Args.hasArg(options::OPT_fprofile_arcs) ||
905e5dd7070Spatrick       Args.hasArg(options::OPT_coverage))
906e5dd7070Spatrick     FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
907e5dd7070Spatrick 
908e5dd7070Spatrick   // Put the .gcno and .gcda files (if needed) next to the object file or
909e5dd7070Spatrick   // bitcode file in the case of LTO.
910e5dd7070Spatrick   // FIXME: There should be a simpler way to find the object file for this
911e5dd7070Spatrick   // input, and this code probably does the wrong thing for commands that
912e5dd7070Spatrick   // compile and link all at once.
913e5dd7070Spatrick   if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
914e5dd7070Spatrick       (EmitCovNotes || EmitCovData) && Output.isFilename()) {
915e5dd7070Spatrick     SmallString<128> OutputFilename;
916e5dd7070Spatrick     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT__SLASH_Fo))
917e5dd7070Spatrick       OutputFilename = FinalOutput->getValue();
918e5dd7070Spatrick     else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
919e5dd7070Spatrick       OutputFilename = FinalOutput->getValue();
920e5dd7070Spatrick     else
921e5dd7070Spatrick       OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
922e5dd7070Spatrick     SmallString<128> CoverageFilename = OutputFilename;
923e5dd7070Spatrick     if (llvm::sys::path::is_relative(CoverageFilename))
924e5dd7070Spatrick       (void)D.getVFS().makeAbsolute(CoverageFilename);
925e5dd7070Spatrick     llvm::sys::path::replace_extension(CoverageFilename, "gcno");
926e5dd7070Spatrick 
927e5dd7070Spatrick     CmdArgs.push_back("-coverage-notes-file");
928e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
929e5dd7070Spatrick 
930e5dd7070Spatrick     if (EmitCovData) {
931e5dd7070Spatrick       if (FProfileDir) {
932e5dd7070Spatrick         CoverageFilename = FProfileDir->getValue();
933e5dd7070Spatrick         llvm::sys::path::append(CoverageFilename, OutputFilename);
934e5dd7070Spatrick       }
935e5dd7070Spatrick       llvm::sys::path::replace_extension(CoverageFilename, "gcda");
936e5dd7070Spatrick       CmdArgs.push_back("-coverage-data-file");
937e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
938e5dd7070Spatrick     }
939e5dd7070Spatrick   }
940e5dd7070Spatrick }
941e5dd7070Spatrick 
942e5dd7070Spatrick /// Check whether the given input tree contains any compilation actions.
ContainsCompileAction(const Action * A)943e5dd7070Spatrick static bool ContainsCompileAction(const Action *A) {
944e5dd7070Spatrick   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
945e5dd7070Spatrick     return true;
946e5dd7070Spatrick 
9477a9b00ceSrobert   return llvm::any_of(A->inputs(), ContainsCompileAction);
948e5dd7070Spatrick }
949e5dd7070Spatrick 
950e5dd7070Spatrick /// Check if -relax-all should be passed to the internal assembler.
951e5dd7070Spatrick /// This is done by default when compiling non-assembler source with -O0.
UseRelaxAll(Compilation & C,const ArgList & Args)952e5dd7070Spatrick static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
953e5dd7070Spatrick   bool RelaxDefault = true;
954e5dd7070Spatrick 
955e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
956e5dd7070Spatrick     RelaxDefault = A->getOption().matches(options::OPT_O0);
957e5dd7070Spatrick 
958e5dd7070Spatrick   if (RelaxDefault) {
959e5dd7070Spatrick     RelaxDefault = false;
960e5dd7070Spatrick     for (const auto &Act : C.getActions()) {
961e5dd7070Spatrick       if (ContainsCompileAction(Act)) {
962e5dd7070Spatrick         RelaxDefault = true;
963e5dd7070Spatrick         break;
964e5dd7070Spatrick       }
965e5dd7070Spatrick     }
966e5dd7070Spatrick   }
967e5dd7070Spatrick 
968e5dd7070Spatrick   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
969e5dd7070Spatrick                       RelaxDefault);
970e5dd7070Spatrick }
971e5dd7070Spatrick 
RenderDebugEnablingArgs(const ArgList & Args,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind DebugInfoKind,unsigned DwarfVersion,llvm::DebuggerKind DebuggerTuning)972e5dd7070Spatrick static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
973e5dd7070Spatrick                                     codegenoptions::DebugInfoKind DebugInfoKind,
974e5dd7070Spatrick                                     unsigned DwarfVersion,
975e5dd7070Spatrick                                     llvm::DebuggerKind DebuggerTuning) {
976e5dd7070Spatrick   switch (DebugInfoKind) {
977e5dd7070Spatrick   case codegenoptions::DebugDirectivesOnly:
978e5dd7070Spatrick     CmdArgs.push_back("-debug-info-kind=line-directives-only");
979e5dd7070Spatrick     break;
980e5dd7070Spatrick   case codegenoptions::DebugLineTablesOnly:
981e5dd7070Spatrick     CmdArgs.push_back("-debug-info-kind=line-tables-only");
982e5dd7070Spatrick     break;
983e5dd7070Spatrick   case codegenoptions::DebugInfoConstructor:
984e5dd7070Spatrick     CmdArgs.push_back("-debug-info-kind=constructor");
985e5dd7070Spatrick     break;
986e5dd7070Spatrick   case codegenoptions::LimitedDebugInfo:
987e5dd7070Spatrick     CmdArgs.push_back("-debug-info-kind=limited");
988e5dd7070Spatrick     break;
989e5dd7070Spatrick   case codegenoptions::FullDebugInfo:
990e5dd7070Spatrick     CmdArgs.push_back("-debug-info-kind=standalone");
991e5dd7070Spatrick     break;
992a0747c9fSpatrick   case codegenoptions::UnusedTypeInfo:
993a0747c9fSpatrick     CmdArgs.push_back("-debug-info-kind=unused-types");
994a0747c9fSpatrick     break;
995e5dd7070Spatrick   default:
996e5dd7070Spatrick     break;
997e5dd7070Spatrick   }
998e5dd7070Spatrick   if (DwarfVersion > 0)
999e5dd7070Spatrick     CmdArgs.push_back(
1000e5dd7070Spatrick         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
1001e5dd7070Spatrick   switch (DebuggerTuning) {
1002e5dd7070Spatrick   case llvm::DebuggerKind::GDB:
1003e5dd7070Spatrick     CmdArgs.push_back("-debugger-tuning=gdb");
1004e5dd7070Spatrick     break;
1005e5dd7070Spatrick   case llvm::DebuggerKind::LLDB:
1006e5dd7070Spatrick     CmdArgs.push_back("-debugger-tuning=lldb");
1007e5dd7070Spatrick     break;
1008e5dd7070Spatrick   case llvm::DebuggerKind::SCE:
1009e5dd7070Spatrick     CmdArgs.push_back("-debugger-tuning=sce");
1010e5dd7070Spatrick     break;
1011a0747c9fSpatrick   case llvm::DebuggerKind::DBX:
1012a0747c9fSpatrick     CmdArgs.push_back("-debugger-tuning=dbx");
1013a0747c9fSpatrick     break;
1014e5dd7070Spatrick   default:
1015e5dd7070Spatrick     break;
1016e5dd7070Spatrick   }
1017e5dd7070Spatrick }
1018e5dd7070Spatrick 
checkDebugInfoOption(const Arg * A,const ArgList & Args,const Driver & D,const ToolChain & TC)1019e5dd7070Spatrick static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1020e5dd7070Spatrick                                  const Driver &D, const ToolChain &TC) {
1021e5dd7070Spatrick   assert(A && "Expected non-nullptr argument.");
1022e5dd7070Spatrick   if (TC.supportsDebugInfoOption(A))
1023e5dd7070Spatrick     return true;
1024e5dd7070Spatrick   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1025e5dd7070Spatrick       << A->getAsString(Args) << TC.getTripleString();
1026e5dd7070Spatrick   return false;
1027e5dd7070Spatrick }
1028e5dd7070Spatrick 
RenderDebugInfoCompressionArgs(const ArgList & Args,ArgStringList & CmdArgs,const Driver & D,const ToolChain & TC)1029e5dd7070Spatrick static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1030e5dd7070Spatrick                                            ArgStringList &CmdArgs,
1031e5dd7070Spatrick                                            const Driver &D,
1032e5dd7070Spatrick                                            const ToolChain &TC) {
1033a0747c9fSpatrick   const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1034e5dd7070Spatrick   if (!A)
1035e5dd7070Spatrick     return;
1036e5dd7070Spatrick   if (checkDebugInfoOption(A, Args, D, TC)) {
1037e5dd7070Spatrick     StringRef Value = A->getValue();
1038e5dd7070Spatrick     if (Value == "none") {
1039e5dd7070Spatrick       CmdArgs.push_back("--compress-debug-sections=none");
10407a9b00ceSrobert     } else if (Value == "zlib") {
10417a9b00ceSrobert       if (llvm::compression::zlib::isAvailable()) {
1042e5dd7070Spatrick         CmdArgs.push_back(
1043e5dd7070Spatrick             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1044e5dd7070Spatrick       } else {
10457a9b00ceSrobert         D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
10467a9b00ceSrobert       }
10477a9b00ceSrobert     } else if (Value == "zstd") {
10487a9b00ceSrobert       if (llvm::compression::zstd::isAvailable()) {
10497a9b00ceSrobert         CmdArgs.push_back(
10507a9b00ceSrobert             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
10517a9b00ceSrobert       } else {
10527a9b00ceSrobert         D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
1053e5dd7070Spatrick       }
1054e5dd7070Spatrick     } else {
1055e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_option_argument)
10567a9b00ceSrobert           << A->getSpelling() << Value;
1057e5dd7070Spatrick     }
1058e5dd7070Spatrick   }
1059e5dd7070Spatrick }
1060e5dd7070Spatrick 
handleAMDGPUCodeObjectVersionOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsCC1As=false)1061a0747c9fSpatrick static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
1062a0747c9fSpatrick                                                  const ArgList &Args,
10637a9b00ceSrobert                                                  ArgStringList &CmdArgs,
10647a9b00ceSrobert                                                  bool IsCC1As = false) {
1065a0747c9fSpatrick   // If no version was requested by the user, use the default value from the
1066a0747c9fSpatrick   // back end. This is consistent with the value returned from
1067a0747c9fSpatrick   // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
1068a0747c9fSpatrick   // requiring the corresponding llvm to have the AMDGPU target enabled,
1069a0747c9fSpatrick   // provided the user (e.g. front end tests) can use the default.
1070a0747c9fSpatrick   if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
1071a0747c9fSpatrick     unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
1072a0747c9fSpatrick     CmdArgs.insert(CmdArgs.begin() + 1,
1073a0747c9fSpatrick                    Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1074a0747c9fSpatrick                                       Twine(CodeObjVer)));
1075a0747c9fSpatrick     CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
10767a9b00ceSrobert     // -cc1as does not accept -mcode-object-version option.
10777a9b00ceSrobert     if (!IsCC1As)
10787a9b00ceSrobert       CmdArgs.insert(CmdArgs.begin() + 1,
10797a9b00ceSrobert                      Args.MakeArgString(Twine("-mcode-object-version=") +
10807a9b00ceSrobert                                         Twine(CodeObjVer)));
1081a0747c9fSpatrick   }
1082a0747c9fSpatrick }
1083e5dd7070Spatrick 
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs) const1084e5dd7070Spatrick void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1085e5dd7070Spatrick                                     const Driver &D, const ArgList &Args,
1086e5dd7070Spatrick                                     ArgStringList &CmdArgs,
1087e5dd7070Spatrick                                     const InputInfo &Output,
1088e5dd7070Spatrick                                     const InputInfoList &Inputs) const {
1089e5dd7070Spatrick   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1090e5dd7070Spatrick 
1091e5dd7070Spatrick   CheckPreprocessingOptions(D, Args);
1092e5dd7070Spatrick 
1093e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_C);
1094e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_CC);
1095e5dd7070Spatrick 
1096e5dd7070Spatrick   // Handle dependency file generation.
1097e5dd7070Spatrick   Arg *ArgM = Args.getLastArg(options::OPT_MM);
1098e5dd7070Spatrick   if (!ArgM)
1099e5dd7070Spatrick     ArgM = Args.getLastArg(options::OPT_M);
1100e5dd7070Spatrick   Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1101e5dd7070Spatrick   if (!ArgMD)
1102e5dd7070Spatrick     ArgMD = Args.getLastArg(options::OPT_MD);
1103e5dd7070Spatrick 
1104e5dd7070Spatrick   // -M and -MM imply -w.
1105e5dd7070Spatrick   if (ArgM)
1106e5dd7070Spatrick     CmdArgs.push_back("-w");
1107e5dd7070Spatrick   else
1108e5dd7070Spatrick     ArgM = ArgMD;
1109e5dd7070Spatrick 
1110e5dd7070Spatrick   if (ArgM) {
1111e5dd7070Spatrick     // Determine the output location.
1112e5dd7070Spatrick     const char *DepFile;
1113e5dd7070Spatrick     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1114e5dd7070Spatrick       DepFile = MF->getValue();
1115e5dd7070Spatrick       C.addFailureResultFile(DepFile, &JA);
1116e5dd7070Spatrick     } else if (Output.getType() == types::TY_Dependencies) {
1117e5dd7070Spatrick       DepFile = Output.getFilename();
1118e5dd7070Spatrick     } else if (!ArgMD) {
1119e5dd7070Spatrick       DepFile = "-";
1120e5dd7070Spatrick     } else {
1121e5dd7070Spatrick       DepFile = getDependencyFileName(Args, Inputs);
1122e5dd7070Spatrick       C.addFailureResultFile(DepFile, &JA);
1123e5dd7070Spatrick     }
1124e5dd7070Spatrick     CmdArgs.push_back("-dependency-file");
1125e5dd7070Spatrick     CmdArgs.push_back(DepFile);
1126e5dd7070Spatrick 
1127e5dd7070Spatrick     bool HasTarget = false;
1128e5dd7070Spatrick     for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1129e5dd7070Spatrick       HasTarget = true;
1130e5dd7070Spatrick       A->claim();
1131e5dd7070Spatrick       if (A->getOption().matches(options::OPT_MT)) {
1132e5dd7070Spatrick         A->render(Args, CmdArgs);
1133e5dd7070Spatrick       } else {
1134e5dd7070Spatrick         CmdArgs.push_back("-MT");
1135e5dd7070Spatrick         SmallString<128> Quoted;
11367a9b00ceSrobert         quoteMakeTarget(A->getValue(), Quoted);
1137e5dd7070Spatrick         CmdArgs.push_back(Args.MakeArgString(Quoted));
1138e5dd7070Spatrick       }
1139e5dd7070Spatrick     }
1140e5dd7070Spatrick 
1141e5dd7070Spatrick     // Add a default target if one wasn't specified.
1142e5dd7070Spatrick     if (!HasTarget) {
1143e5dd7070Spatrick       const char *DepTarget;
1144e5dd7070Spatrick 
1145e5dd7070Spatrick       // If user provided -o, that is the dependency target, except
1146e5dd7070Spatrick       // when we are only generating a dependency file.
1147e5dd7070Spatrick       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1148e5dd7070Spatrick       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1149e5dd7070Spatrick         DepTarget = OutputOpt->getValue();
1150e5dd7070Spatrick       } else {
1151e5dd7070Spatrick         // Otherwise derive from the base input.
1152e5dd7070Spatrick         //
1153e5dd7070Spatrick         // FIXME: This should use the computed output file location.
1154e5dd7070Spatrick         SmallString<128> P(Inputs[0].getBaseInput());
1155e5dd7070Spatrick         llvm::sys::path::replace_extension(P, "o");
1156e5dd7070Spatrick         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1157e5dd7070Spatrick       }
1158e5dd7070Spatrick 
1159e5dd7070Spatrick       CmdArgs.push_back("-MT");
1160e5dd7070Spatrick       SmallString<128> Quoted;
11617a9b00ceSrobert       quoteMakeTarget(DepTarget, Quoted);
1162e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(Quoted));
1163e5dd7070Spatrick     }
1164e5dd7070Spatrick 
1165e5dd7070Spatrick     if (ArgM->getOption().matches(options::OPT_M) ||
1166e5dd7070Spatrick         ArgM->getOption().matches(options::OPT_MD))
1167e5dd7070Spatrick       CmdArgs.push_back("-sys-header-deps");
1168e5dd7070Spatrick     if ((isa<PrecompileJobAction>(JA) &&
1169e5dd7070Spatrick          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1170e5dd7070Spatrick         Args.hasArg(options::OPT_fmodule_file_deps))
1171e5dd7070Spatrick       CmdArgs.push_back("-module-file-deps");
1172e5dd7070Spatrick   }
1173e5dd7070Spatrick 
1174e5dd7070Spatrick   if (Args.hasArg(options::OPT_MG)) {
1175e5dd7070Spatrick     if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1176e5dd7070Spatrick         ArgM->getOption().matches(options::OPT_MMD))
1177e5dd7070Spatrick       D.Diag(diag::err_drv_mg_requires_m_or_mm);
1178e5dd7070Spatrick     CmdArgs.push_back("-MG");
1179e5dd7070Spatrick   }
1180e5dd7070Spatrick 
1181e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_MP);
1182e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_MV);
1183e5dd7070Spatrick 
1184adae0cfdSpatrick   // Add offload include arguments specific for CUDA/HIP.  This must happen
1185adae0cfdSpatrick   // before we -I or -include anything else, because we must pick up the
1186adae0cfdSpatrick   // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1187adae0cfdSpatrick   // from e.g. /usr/local/include.
1188e5dd7070Spatrick   if (JA.isOffloading(Action::OFK_Cuda))
1189e5dd7070Spatrick     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1190adae0cfdSpatrick   if (JA.isOffloading(Action::OFK_HIP))
1191adae0cfdSpatrick     getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1192e5dd7070Spatrick 
1193e5dd7070Spatrick   // If we are offloading to a target via OpenMP we need to include the
1194e5dd7070Spatrick   // openmp_wrappers folder which contains alternative system headers.
1195e5dd7070Spatrick   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
11967a9b00ceSrobert       !Args.hasArg(options::OPT_nostdinc) &&
11977a9b00ceSrobert       !Args.hasArg(options::OPT_nogpuinc) &&
1198a0747c9fSpatrick       (getToolChain().getTriple().isNVPTX() ||
1199a0747c9fSpatrick        getToolChain().getTriple().isAMDGCN())) {
1200e5dd7070Spatrick     if (!Args.hasArg(options::OPT_nobuiltininc)) {
1201e5dd7070Spatrick       // Add openmp_wrappers/* to our system include path.  This lets us wrap
1202e5dd7070Spatrick       // standard library headers.
1203e5dd7070Spatrick       SmallString<128> P(D.ResourceDir);
1204e5dd7070Spatrick       llvm::sys::path::append(P, "include");
1205e5dd7070Spatrick       llvm::sys::path::append(P, "openmp_wrappers");
1206e5dd7070Spatrick       CmdArgs.push_back("-internal-isystem");
1207e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(P));
1208e5dd7070Spatrick     }
1209e5dd7070Spatrick 
1210e5dd7070Spatrick     CmdArgs.push_back("-include");
1211adae0cfdSpatrick     CmdArgs.push_back("__clang_openmp_device_functions.h");
1212e5dd7070Spatrick   }
1213e5dd7070Spatrick 
1214e5dd7070Spatrick   // Add -i* options, and automatically translate to
1215e5dd7070Spatrick   // -include-pch/-include-pth for transparent PCH support. It's
1216e5dd7070Spatrick   // wonky, but we include looking for .gch so we can support seamless
1217e5dd7070Spatrick   // replacement into a build system already set up to be generating
1218e5dd7070Spatrick   // .gch files.
1219e5dd7070Spatrick 
1220e5dd7070Spatrick   if (getToolChain().getDriver().IsCLMode()) {
1221e5dd7070Spatrick     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1222e5dd7070Spatrick     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1223e5dd7070Spatrick     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1224e5dd7070Spatrick         JA.getKind() <= Action::AssembleJobClass) {
1225e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1226adae0cfdSpatrick       // -fpch-instantiate-templates is the default when creating
1227adae0cfdSpatrick       // precomp using /Yc
1228adae0cfdSpatrick       if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1229adae0cfdSpatrick                        options::OPT_fno_pch_instantiate_templates, true))
1230adae0cfdSpatrick         CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1231e5dd7070Spatrick     }
1232e5dd7070Spatrick     if (YcArg || YuArg) {
1233e5dd7070Spatrick       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1234e5dd7070Spatrick       if (!isa<PrecompileJobAction>(JA)) {
1235e5dd7070Spatrick         CmdArgs.push_back("-include-pch");
1236e5dd7070Spatrick         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1237e5dd7070Spatrick             C, !ThroughHeader.empty()
1238e5dd7070Spatrick                    ? ThroughHeader
1239e5dd7070Spatrick                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1240e5dd7070Spatrick       }
1241e5dd7070Spatrick 
1242e5dd7070Spatrick       if (ThroughHeader.empty()) {
1243e5dd7070Spatrick         CmdArgs.push_back(Args.MakeArgString(
1244e5dd7070Spatrick             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1245e5dd7070Spatrick       } else {
1246e5dd7070Spatrick         CmdArgs.push_back(
1247e5dd7070Spatrick             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1248e5dd7070Spatrick       }
1249e5dd7070Spatrick     }
1250e5dd7070Spatrick   }
1251e5dd7070Spatrick 
1252e5dd7070Spatrick   bool RenderedImplicitInclude = false;
1253e5dd7070Spatrick   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
12547a9b00ceSrobert     if (A->getOption().matches(options::OPT_include) &&
12557a9b00ceSrobert         D.getProbePrecompiled()) {
1256e5dd7070Spatrick       // Handling of gcc-style gch precompiled headers.
1257e5dd7070Spatrick       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1258e5dd7070Spatrick       RenderedImplicitInclude = true;
1259e5dd7070Spatrick 
1260e5dd7070Spatrick       bool FoundPCH = false;
1261e5dd7070Spatrick       SmallString<128> P(A->getValue());
1262e5dd7070Spatrick       // We want the files to have a name like foo.h.pch. Add a dummy extension
1263e5dd7070Spatrick       // so that replace_extension does the right thing.
1264e5dd7070Spatrick       P += ".dummy";
1265e5dd7070Spatrick       llvm::sys::path::replace_extension(P, "pch");
12667a9b00ceSrobert       if (D.getVFS().exists(P))
1267e5dd7070Spatrick         FoundPCH = true;
1268e5dd7070Spatrick 
1269e5dd7070Spatrick       if (!FoundPCH) {
1270e5dd7070Spatrick         llvm::sys::path::replace_extension(P, "gch");
12717a9b00ceSrobert         if (D.getVFS().exists(P)) {
1272e5dd7070Spatrick           FoundPCH = true;
1273e5dd7070Spatrick         }
1274e5dd7070Spatrick       }
1275e5dd7070Spatrick 
1276e5dd7070Spatrick       if (FoundPCH) {
1277e5dd7070Spatrick         if (IsFirstImplicitInclude) {
1278e5dd7070Spatrick           A->claim();
1279e5dd7070Spatrick           CmdArgs.push_back("-include-pch");
1280e5dd7070Spatrick           CmdArgs.push_back(Args.MakeArgString(P));
1281e5dd7070Spatrick           continue;
1282e5dd7070Spatrick         } else {
1283e5dd7070Spatrick           // Ignore the PCH if not first on command line and emit warning.
1284e5dd7070Spatrick           D.Diag(diag::warn_drv_pch_not_first_include) << P
1285e5dd7070Spatrick                                                        << A->getAsString(Args);
1286e5dd7070Spatrick         }
1287e5dd7070Spatrick       }
1288e5dd7070Spatrick     } else if (A->getOption().matches(options::OPT_isystem_after)) {
1289e5dd7070Spatrick       // Handling of paths which must come late.  These entries are handled by
1290e5dd7070Spatrick       // the toolchain itself after the resource dir is inserted in the right
1291e5dd7070Spatrick       // search order.
1292e5dd7070Spatrick       // Do not claim the argument so that the use of the argument does not
1293e5dd7070Spatrick       // silently go unnoticed on toolchains which do not honour the option.
1294e5dd7070Spatrick       continue;
1295e5dd7070Spatrick     } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1296e5dd7070Spatrick       // Translated to -internal-isystem by the driver, no need to pass to cc1.
1297e5dd7070Spatrick       continue;
1298e5dd7070Spatrick     }
1299e5dd7070Spatrick 
1300e5dd7070Spatrick     // Not translated, render as usual.
1301e5dd7070Spatrick     A->claim();
1302e5dd7070Spatrick     A->render(Args, CmdArgs);
1303e5dd7070Spatrick   }
1304e5dd7070Spatrick 
1305e5dd7070Spatrick   Args.AddAllArgs(CmdArgs,
1306e5dd7070Spatrick                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1307e5dd7070Spatrick                    options::OPT_F, options::OPT_index_header_map});
1308e5dd7070Spatrick 
1309e5dd7070Spatrick   // Add -Wp, and -Xpreprocessor if using the preprocessor.
1310e5dd7070Spatrick 
1311e5dd7070Spatrick   // FIXME: There is a very unfortunate problem here, some troubled
1312e5dd7070Spatrick   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1313e5dd7070Spatrick   // really support that we would have to parse and then translate
1314e5dd7070Spatrick   // those options. :(
1315e5dd7070Spatrick   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1316e5dd7070Spatrick                        options::OPT_Xpreprocessor);
1317e5dd7070Spatrick 
1318e5dd7070Spatrick   // -I- is a deprecated GCC feature, reject it.
1319e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_I_))
1320e5dd7070Spatrick     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1321e5dd7070Spatrick 
1322e5dd7070Spatrick   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1323e5dd7070Spatrick   // -isysroot to the CC1 invocation.
1324e5dd7070Spatrick   StringRef sysroot = C.getSysRoot();
1325e5dd7070Spatrick   if (sysroot != "") {
1326e5dd7070Spatrick     if (!Args.hasArg(options::OPT_isysroot)) {
1327e5dd7070Spatrick       CmdArgs.push_back("-isysroot");
1328e5dd7070Spatrick       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1329e5dd7070Spatrick     }
1330e5dd7070Spatrick   }
1331e5dd7070Spatrick 
1332e5dd7070Spatrick   // Parse additional include paths from environment variables.
1333e5dd7070Spatrick   // FIXME: We should probably sink the logic for handling these from the
1334e5dd7070Spatrick   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1335e5dd7070Spatrick   // CPATH - included following the user specified includes (but prior to
1336e5dd7070Spatrick   // builtin and standard includes).
1337e5dd7070Spatrick   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1338e5dd7070Spatrick   // C_INCLUDE_PATH - system includes enabled when compiling C.
1339e5dd7070Spatrick   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1340e5dd7070Spatrick   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1341e5dd7070Spatrick   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1342e5dd7070Spatrick   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1343e5dd7070Spatrick   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1344e5dd7070Spatrick   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1345e5dd7070Spatrick   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1346e5dd7070Spatrick 
1347e5dd7070Spatrick   // While adding the include arguments, we also attempt to retrieve the
1348e5dd7070Spatrick   // arguments of related offloading toolchains or arguments that are specific
1349e5dd7070Spatrick   // of an offloading programming model.
1350e5dd7070Spatrick 
1351e5dd7070Spatrick   // Add C++ include arguments, if needed.
1352e5dd7070Spatrick   if (types::isCXX(Inputs[0].getType())) {
1353e5dd7070Spatrick     bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1354e5dd7070Spatrick     forAllAssociatedToolChains(
1355e5dd7070Spatrick         C, JA, getToolChain(),
1356e5dd7070Spatrick         [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1357e5dd7070Spatrick           HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1358e5dd7070Spatrick                              : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1359e5dd7070Spatrick         });
1360e5dd7070Spatrick   }
1361e5dd7070Spatrick 
1362e5dd7070Spatrick   // Add system include arguments for all targets but IAMCU.
1363e5dd7070Spatrick   if (!IsIAMCU)
1364e5dd7070Spatrick     forAllAssociatedToolChains(C, JA, getToolChain(),
1365e5dd7070Spatrick                                [&Args, &CmdArgs](const ToolChain &TC) {
1366e5dd7070Spatrick                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1367e5dd7070Spatrick                                });
1368e5dd7070Spatrick   else {
1369e5dd7070Spatrick     // For IAMCU add special include arguments.
1370e5dd7070Spatrick     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1371e5dd7070Spatrick   }
1372e5dd7070Spatrick 
1373e5dd7070Spatrick   addMacroPrefixMapArg(D, Args, CmdArgs);
1374a0747c9fSpatrick   addCoveragePrefixMapArg(D, Args, CmdArgs);
13757a9b00ceSrobert 
13767a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
13777a9b00ceSrobert                   options::OPT_fno_file_reproducible);
13787a9b00ceSrobert 
13797a9b00ceSrobert   if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
13807a9b00ceSrobert     CmdArgs.push_back("-source-date-epoch");
13817a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(Epoch));
13827a9b00ceSrobert   }
1383e5dd7070Spatrick }
1384e5dd7070Spatrick 
1385e5dd7070Spatrick // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)1386e5dd7070Spatrick static bool isSignedCharDefault(const llvm::Triple &Triple) {
1387e5dd7070Spatrick   switch (Triple.getArch()) {
1388e5dd7070Spatrick   default:
1389e5dd7070Spatrick     return true;
1390e5dd7070Spatrick 
1391e5dd7070Spatrick   case llvm::Triple::aarch64:
1392e5dd7070Spatrick   case llvm::Triple::aarch64_32:
1393e5dd7070Spatrick   case llvm::Triple::aarch64_be:
1394e5dd7070Spatrick   case llvm::Triple::arm:
1395e5dd7070Spatrick   case llvm::Triple::armeb:
1396e5dd7070Spatrick   case llvm::Triple::thumb:
1397e5dd7070Spatrick   case llvm::Triple::thumbeb:
1398e5dd7070Spatrick     if (Triple.isOSDarwin() || Triple.isOSWindows())
1399e5dd7070Spatrick       return true;
1400e5dd7070Spatrick     return false;
1401e5dd7070Spatrick 
1402e5dd7070Spatrick   case llvm::Triple::ppc:
1403e5dd7070Spatrick   case llvm::Triple::ppc64:
1404e5dd7070Spatrick     if (Triple.isOSDarwin())
1405e5dd7070Spatrick       return true;
1406e5dd7070Spatrick     return false;
1407e5dd7070Spatrick 
1408e5dd7070Spatrick   case llvm::Triple::hexagon:
1409a0747c9fSpatrick   case llvm::Triple::ppcle:
1410e5dd7070Spatrick   case llvm::Triple::ppc64le:
1411e5dd7070Spatrick   case llvm::Triple::riscv32:
1412e5dd7070Spatrick   case llvm::Triple::riscv64:
1413e5dd7070Spatrick   case llvm::Triple::systemz:
1414e5dd7070Spatrick   case llvm::Triple::xcore:
1415e5dd7070Spatrick     return false;
1416e5dd7070Spatrick   }
1417e5dd7070Spatrick }
1418e5dd7070Spatrick 
hasMultipleInvocations(const llvm::Triple & Triple,const ArgList & Args)1419e5dd7070Spatrick static bool hasMultipleInvocations(const llvm::Triple &Triple,
1420e5dd7070Spatrick                                    const ArgList &Args) {
1421e5dd7070Spatrick   // Supported only on Darwin where we invoke the compiler multiple times
1422e5dd7070Spatrick   // followed by an invocation to lipo.
1423e5dd7070Spatrick   if (!Triple.isOSDarwin())
1424e5dd7070Spatrick     return false;
1425e5dd7070Spatrick   // If more than one "-arch <arch>" is specified, we're targeting multiple
1426e5dd7070Spatrick   // architectures resulting in a fat binary.
1427e5dd7070Spatrick   return Args.getAllArgValues(options::OPT_arch).size() > 1;
1428e5dd7070Spatrick }
1429e5dd7070Spatrick 
checkRemarksOptions(const Driver & D,const ArgList & Args,const llvm::Triple & Triple)1430e5dd7070Spatrick static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1431e5dd7070Spatrick                                 const llvm::Triple &Triple) {
1432e5dd7070Spatrick   // When enabling remarks, we need to error if:
1433e5dd7070Spatrick   // * The remark file is specified but we're targeting multiple architectures,
1434e5dd7070Spatrick   // which means more than one remark file is being generated.
1435e5dd7070Spatrick   bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1436e5dd7070Spatrick   bool hasExplicitOutputFile =
1437e5dd7070Spatrick       Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1438e5dd7070Spatrick   if (hasMultipleInvocations && hasExplicitOutputFile) {
1439e5dd7070Spatrick     D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1440e5dd7070Spatrick         << "-foptimization-record-file";
1441e5dd7070Spatrick     return false;
1442e5dd7070Spatrick   }
1443e5dd7070Spatrick   return true;
1444e5dd7070Spatrick }
1445e5dd7070Spatrick 
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output,const JobAction & JA)1446e5dd7070Spatrick static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1447e5dd7070Spatrick                                  const llvm::Triple &Triple,
1448e5dd7070Spatrick                                  const InputInfo &Input,
1449e5dd7070Spatrick                                  const InputInfo &Output, const JobAction &JA) {
1450e5dd7070Spatrick   StringRef Format = "yaml";
1451e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1452e5dd7070Spatrick     Format = A->getValue();
1453e5dd7070Spatrick 
1454e5dd7070Spatrick   CmdArgs.push_back("-opt-record-file");
1455e5dd7070Spatrick 
1456e5dd7070Spatrick   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1457e5dd7070Spatrick   if (A) {
1458e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
1459e5dd7070Spatrick   } else {
1460e5dd7070Spatrick     bool hasMultipleArchs =
1461e5dd7070Spatrick         Triple.isOSDarwin() && // Only supported on Darwin platforms.
1462e5dd7070Spatrick         Args.getAllArgValues(options::OPT_arch).size() > 1;
1463e5dd7070Spatrick 
1464e5dd7070Spatrick     SmallString<128> F;
1465e5dd7070Spatrick 
1466e5dd7070Spatrick     if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1467e5dd7070Spatrick       if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1468e5dd7070Spatrick         F = FinalOutput->getValue();
1469e5dd7070Spatrick     } else {
1470e5dd7070Spatrick       if (Format != "yaml" && // For YAML, keep the original behavior.
1471e5dd7070Spatrick           Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1472e5dd7070Spatrick           Output.isFilename())
1473e5dd7070Spatrick         F = Output.getFilename();
1474e5dd7070Spatrick     }
1475e5dd7070Spatrick 
1476e5dd7070Spatrick     if (F.empty()) {
1477e5dd7070Spatrick       // Use the input filename.
1478e5dd7070Spatrick       F = llvm::sys::path::stem(Input.getBaseInput());
1479e5dd7070Spatrick 
1480e5dd7070Spatrick       // If we're compiling for an offload architecture (i.e. a CUDA device),
1481e5dd7070Spatrick       // we need to make the file name for the device compilation different
1482e5dd7070Spatrick       // from the host compilation.
1483e5dd7070Spatrick       if (!JA.isDeviceOffloading(Action::OFK_None) &&
1484e5dd7070Spatrick           !JA.isDeviceOffloading(Action::OFK_Host)) {
1485e5dd7070Spatrick         llvm::sys::path::replace_extension(F, "");
1486e5dd7070Spatrick         F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1487e5dd7070Spatrick                                                  Triple.normalize());
1488e5dd7070Spatrick         F += "-";
1489e5dd7070Spatrick         F += JA.getOffloadingArch();
1490e5dd7070Spatrick       }
1491e5dd7070Spatrick     }
1492e5dd7070Spatrick 
1493e5dd7070Spatrick     // If we're having more than one "-arch", we should name the files
1494e5dd7070Spatrick     // differently so that every cc1 invocation writes to a different file.
1495e5dd7070Spatrick     // We're doing that by appending "-<arch>" with "<arch>" being the arch
1496e5dd7070Spatrick     // name from the triple.
1497e5dd7070Spatrick     if (hasMultipleArchs) {
1498e5dd7070Spatrick       // First, remember the extension.
1499e5dd7070Spatrick       SmallString<64> OldExtension = llvm::sys::path::extension(F);
1500e5dd7070Spatrick       // then, remove it.
1501e5dd7070Spatrick       llvm::sys::path::replace_extension(F, "");
1502e5dd7070Spatrick       // attach -<arch> to it.
1503e5dd7070Spatrick       F += "-";
1504e5dd7070Spatrick       F += Triple.getArchName();
1505e5dd7070Spatrick       // put back the extension.
1506e5dd7070Spatrick       llvm::sys::path::replace_extension(F, OldExtension);
1507e5dd7070Spatrick     }
1508e5dd7070Spatrick 
1509e5dd7070Spatrick     SmallString<32> Extension;
1510e5dd7070Spatrick     Extension += "opt.";
1511e5dd7070Spatrick     Extension += Format;
1512e5dd7070Spatrick 
1513e5dd7070Spatrick     llvm::sys::path::replace_extension(F, Extension);
1514e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(F));
1515e5dd7070Spatrick   }
1516e5dd7070Spatrick 
1517e5dd7070Spatrick   if (const Arg *A =
1518e5dd7070Spatrick           Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1519e5dd7070Spatrick     CmdArgs.push_back("-opt-record-passes");
1520e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
1521e5dd7070Spatrick   }
1522e5dd7070Spatrick 
1523e5dd7070Spatrick   if (!Format.empty()) {
1524e5dd7070Spatrick     CmdArgs.push_back("-opt-record-format");
1525e5dd7070Spatrick     CmdArgs.push_back(Format.data());
1526e5dd7070Spatrick   }
1527e5dd7070Spatrick }
1528e5dd7070Spatrick 
AddAAPCSVolatileBitfieldArgs(const ArgList & Args,ArgStringList & CmdArgs)1529a0747c9fSpatrick void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1530a0747c9fSpatrick   if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1531a0747c9fSpatrick                     options::OPT_fno_aapcs_bitfield_width, true))
1532a0747c9fSpatrick     CmdArgs.push_back("-fno-aapcs-bitfield-width");
1533a0747c9fSpatrick 
1534a0747c9fSpatrick   if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1535a0747c9fSpatrick     CmdArgs.push_back("-faapcs-bitfield-load");
1536a0747c9fSpatrick }
1537a0747c9fSpatrick 
1538e5dd7070Spatrick namespace {
RenderARMABI(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)15397a9b00ceSrobert void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
15407a9b00ceSrobert                   const ArgList &Args, ArgStringList &CmdArgs) {
1541e5dd7070Spatrick   // Select the ABI to use.
1542e5dd7070Spatrick   // FIXME: Support -meabi.
1543e5dd7070Spatrick   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1544e5dd7070Spatrick   const char *ABIName = nullptr;
1545e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1546e5dd7070Spatrick     ABIName = A->getValue();
1547e5dd7070Spatrick   } else {
15487a9b00ceSrobert     std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1549e5dd7070Spatrick     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1550e5dd7070Spatrick   }
1551e5dd7070Spatrick 
1552e5dd7070Spatrick   CmdArgs.push_back("-target-abi");
1553e5dd7070Spatrick   CmdArgs.push_back(ABIName);
1554e5dd7070Spatrick }
15557a9b00ceSrobert 
AddUnalignedAccessWarning(ArgStringList & CmdArgs)15567a9b00ceSrobert void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
15577a9b00ceSrobert   auto StrictAlignIter =
15587a9b00ceSrobert       llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
15597a9b00ceSrobert         return Arg == "+strict-align" || Arg == "-strict-align";
15607a9b00ceSrobert       });
15617a9b00ceSrobert   if (StrictAlignIter != CmdArgs.rend() &&
15627a9b00ceSrobert       StringRef(*StrictAlignIter) == "+strict-align")
15637a9b00ceSrobert     CmdArgs.push_back("-Wunaligned-access");
15647a9b00ceSrobert }
15657a9b00ceSrobert }
15667a9b00ceSrobert 
CollectARMPACBTIOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool isAArch64)15677a9b00ceSrobert static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
15687a9b00ceSrobert                                     ArgStringList &CmdArgs, bool isAArch64) {
15695e530090Skettenis   const llvm::Triple &Triple = TC.getEffectiveTriple();
15707a9b00ceSrobert   const Arg *A = isAArch64
15717a9b00ceSrobert                      ? Args.getLastArg(options::OPT_msign_return_address_EQ,
15727a9b00ceSrobert                                        options::OPT_mbranch_protection_EQ)
15737a9b00ceSrobert                      : Args.getLastArg(options::OPT_mbranch_protection_EQ);
15745e530090Skettenis   if (!A) {
1575c88b7403Sjsg     if (Triple.isOSOpenBSD() && isAArch64) {
15765e530090Skettenis       CmdArgs.push_back("-msign-return-address=non-leaf");
15775e530090Skettenis       CmdArgs.push_back("-msign-return-address-key=a_key");
15785e530090Skettenis       CmdArgs.push_back("-mbranch-target-enforce");
15795e530090Skettenis     }
15807a9b00ceSrobert     return;
15815e530090Skettenis   }
15827a9b00ceSrobert 
15837a9b00ceSrobert   const Driver &D = TC.getDriver();
15847a9b00ceSrobert   if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
15857a9b00ceSrobert     D.Diag(diag::warn_incompatible_branch_protection_option)
15867a9b00ceSrobert         << Triple.getArchName();
15877a9b00ceSrobert 
15887a9b00ceSrobert   StringRef Scope, Key;
15897a9b00ceSrobert   bool IndirectBranches;
15907a9b00ceSrobert 
15917a9b00ceSrobert   if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
15927a9b00ceSrobert     Scope = A->getValue();
15937a9b00ceSrobert     if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
15947a9b00ceSrobert       D.Diag(diag::err_drv_unsupported_option_argument)
15957a9b00ceSrobert           << A->getSpelling() << Scope;
15967a9b00ceSrobert     Key = "a_key";
1597c88b7403Sjsg     if (Triple.isOSOpenBSD() && isAArch64)
15987a9b00ceSrobert       IndirectBranches = true;
15997a9b00ceSrobert     else
16007a9b00ceSrobert       IndirectBranches = false;
16017a9b00ceSrobert   } else {
16027a9b00ceSrobert     StringRef DiagMsg;
16037a9b00ceSrobert     llvm::ARM::ParsedBranchProtection PBP;
16047a9b00ceSrobert     if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
16057a9b00ceSrobert       D.Diag(diag::err_drv_unsupported_option_argument)
16067a9b00ceSrobert           << A->getSpelling() << DiagMsg;
16077a9b00ceSrobert     if (!isAArch64 && PBP.Key == "b_key")
16087a9b00ceSrobert       D.Diag(diag::warn_unsupported_branch_protection)
16097a9b00ceSrobert           << "b-key" << A->getAsString(Args);
16107a9b00ceSrobert     Scope = PBP.Scope;
16117a9b00ceSrobert     Key = PBP.Key;
16127a9b00ceSrobert     IndirectBranches = PBP.BranchTargetEnforcement;
16137a9b00ceSrobert   }
16147a9b00ceSrobert 
16157a9b00ceSrobert   CmdArgs.push_back(
16167a9b00ceSrobert       Args.MakeArgString(Twine("-msign-return-address=") + Scope));
16177a9b00ceSrobert   if (!Scope.equals("none"))
16187a9b00ceSrobert     CmdArgs.push_back(
16197a9b00ceSrobert         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
16207a9b00ceSrobert   if (IndirectBranches)
16217a9b00ceSrobert     CmdArgs.push_back("-mbranch-target-enforce");
1622e5dd7070Spatrick }
1623e5dd7070Spatrick 
AddARMTargetArgs(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const1624e5dd7070Spatrick void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1625e5dd7070Spatrick                              ArgStringList &CmdArgs, bool KernelOrKext) const {
16267a9b00ceSrobert   RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1627e5dd7070Spatrick 
1628e5dd7070Spatrick   // Determine floating point ABI from the options & target defaults.
1629e5dd7070Spatrick   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1630e5dd7070Spatrick   if (ABI == arm::FloatABI::Soft) {
1631e5dd7070Spatrick     // Floating point operations and argument passing are soft.
1632e5dd7070Spatrick     // FIXME: This changes CPP defines, we need -target-soft-float.
1633e5dd7070Spatrick     CmdArgs.push_back("-msoft-float");
1634e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
1635e5dd7070Spatrick     CmdArgs.push_back("soft");
1636e5dd7070Spatrick   } else if (ABI == arm::FloatABI::SoftFP) {
1637e5dd7070Spatrick     // Floating point operations are hard, but argument passing is soft.
1638e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
1639e5dd7070Spatrick     CmdArgs.push_back("soft");
1640e5dd7070Spatrick   } else {
1641e5dd7070Spatrick     // Floating point operations and argument passing are hard.
1642e5dd7070Spatrick     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1643e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
1644e5dd7070Spatrick     CmdArgs.push_back("hard");
1645e5dd7070Spatrick   }
1646e5dd7070Spatrick 
1647e5dd7070Spatrick   // Forward the -mglobal-merge option for explicit control over the pass.
1648e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1649e5dd7070Spatrick                                options::OPT_mno_global_merge)) {
1650e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
1651e5dd7070Spatrick     if (A->getOption().matches(options::OPT_mno_global_merge))
1652e5dd7070Spatrick       CmdArgs.push_back("-arm-global-merge=false");
1653e5dd7070Spatrick     else
1654e5dd7070Spatrick       CmdArgs.push_back("-arm-global-merge=true");
1655e5dd7070Spatrick   }
1656e5dd7070Spatrick 
1657e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_mimplicit_float,
1658e5dd7070Spatrick                     options::OPT_mno_implicit_float, true))
1659e5dd7070Spatrick     CmdArgs.push_back("-no-implicit-float");
1660e5dd7070Spatrick 
1661e5dd7070Spatrick   if (Args.getLastArg(options::OPT_mcmse))
1662e5dd7070Spatrick     CmdArgs.push_back("-mcmse");
1663a0747c9fSpatrick 
1664a0747c9fSpatrick   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
16657a9b00ceSrobert 
16667a9b00ceSrobert   // Enable/disable return address signing and indirect branch targets.
16677a9b00ceSrobert   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
16687a9b00ceSrobert 
16697a9b00ceSrobert   AddUnalignedAccessWarning(CmdArgs);
1670e5dd7070Spatrick }
1671e5dd7070Spatrick 
RenderTargetOptions(const llvm::Triple & EffectiveTriple,const ArgList & Args,bool KernelOrKext,ArgStringList & CmdArgs) const1672e5dd7070Spatrick void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1673e5dd7070Spatrick                                 const ArgList &Args, bool KernelOrKext,
1674e5dd7070Spatrick                                 ArgStringList &CmdArgs) const {
1675e5dd7070Spatrick   const ToolChain &TC = getToolChain();
1676e5dd7070Spatrick 
1677e5dd7070Spatrick   // Add the target features
1678adae0cfdSpatrick   getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1679e5dd7070Spatrick 
1680e5dd7070Spatrick   // Add target specific flags.
1681e5dd7070Spatrick   switch (TC.getArch()) {
1682e5dd7070Spatrick   default:
1683e5dd7070Spatrick     break;
1684e5dd7070Spatrick 
1685e5dd7070Spatrick   case llvm::Triple::arm:
1686e5dd7070Spatrick   case llvm::Triple::armeb:
1687e5dd7070Spatrick   case llvm::Triple::thumb:
1688e5dd7070Spatrick   case llvm::Triple::thumbeb:
1689e5dd7070Spatrick     // Use the effective triple, which takes into account the deployment target.
1690e5dd7070Spatrick     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1691e5dd7070Spatrick     break;
1692e5dd7070Spatrick 
1693e5dd7070Spatrick   case llvm::Triple::aarch64:
1694e5dd7070Spatrick   case llvm::Triple::aarch64_32:
1695e5dd7070Spatrick   case llvm::Triple::aarch64_be:
1696e5dd7070Spatrick     AddAArch64TargetArgs(Args, CmdArgs);
16977a9b00ceSrobert     break;
16987a9b00ceSrobert 
16997a9b00ceSrobert   case llvm::Triple::loongarch32:
17007a9b00ceSrobert   case llvm::Triple::loongarch64:
17017a9b00ceSrobert     AddLoongArchTargetArgs(Args, CmdArgs);
1702e5dd7070Spatrick     break;
1703e5dd7070Spatrick 
1704e5dd7070Spatrick   case llvm::Triple::mips:
1705e5dd7070Spatrick   case llvm::Triple::mipsel:
1706e5dd7070Spatrick   case llvm::Triple::mips64:
1707e5dd7070Spatrick   case llvm::Triple::mips64el:
1708e5dd7070Spatrick     AddMIPSTargetArgs(Args, CmdArgs);
1709e5dd7070Spatrick     break;
1710e5dd7070Spatrick 
1711e5dd7070Spatrick   case llvm::Triple::ppc:
1712a0747c9fSpatrick   case llvm::Triple::ppcle:
1713e5dd7070Spatrick   case llvm::Triple::ppc64:
1714e5dd7070Spatrick   case llvm::Triple::ppc64le:
1715e5dd7070Spatrick     AddPPCTargetArgs(Args, CmdArgs);
1716e5dd7070Spatrick     break;
1717e5dd7070Spatrick 
1718e5dd7070Spatrick   case llvm::Triple::riscv32:
1719e5dd7070Spatrick   case llvm::Triple::riscv64:
1720e5dd7070Spatrick     AddRISCVTargetArgs(Args, CmdArgs);
1721e5dd7070Spatrick     break;
1722e5dd7070Spatrick 
1723e5dd7070Spatrick   case llvm::Triple::sparc:
1724e5dd7070Spatrick   case llvm::Triple::sparcel:
1725e5dd7070Spatrick   case llvm::Triple::sparcv9:
1726e5dd7070Spatrick     AddSparcTargetArgs(Args, CmdArgs);
1727e5dd7070Spatrick     break;
1728e5dd7070Spatrick 
1729e5dd7070Spatrick   case llvm::Triple::systemz:
1730e5dd7070Spatrick     AddSystemZTargetArgs(Args, CmdArgs);
1731e5dd7070Spatrick     break;
1732e5dd7070Spatrick 
1733e5dd7070Spatrick   case llvm::Triple::x86:
1734e5dd7070Spatrick   case llvm::Triple::x86_64:
1735e5dd7070Spatrick     AddX86TargetArgs(Args, CmdArgs);
1736e5dd7070Spatrick     break;
1737e5dd7070Spatrick 
1738e5dd7070Spatrick   case llvm::Triple::lanai:
1739e5dd7070Spatrick     AddLanaiTargetArgs(Args, CmdArgs);
1740e5dd7070Spatrick     break;
1741e5dd7070Spatrick 
1742e5dd7070Spatrick   case llvm::Triple::hexagon:
1743e5dd7070Spatrick     AddHexagonTargetArgs(Args, CmdArgs);
1744e5dd7070Spatrick     break;
1745e5dd7070Spatrick 
1746e5dd7070Spatrick   case llvm::Triple::wasm32:
1747e5dd7070Spatrick   case llvm::Triple::wasm64:
1748e5dd7070Spatrick     AddWebAssemblyTargetArgs(Args, CmdArgs);
1749e5dd7070Spatrick     break;
1750adae0cfdSpatrick 
1751adae0cfdSpatrick   case llvm::Triple::ve:
1752adae0cfdSpatrick     AddVETargetArgs(Args, CmdArgs);
1753adae0cfdSpatrick     break;
1754e5dd7070Spatrick   }
1755e5dd7070Spatrick }
1756e5dd7070Spatrick 
1757e5dd7070Spatrick namespace {
RenderAArch64ABI(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)1758e5dd7070Spatrick void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1759e5dd7070Spatrick                       ArgStringList &CmdArgs) {
1760e5dd7070Spatrick   const char *ABIName = nullptr;
1761e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1762e5dd7070Spatrick     ABIName = A->getValue();
1763e5dd7070Spatrick   else if (Triple.isOSDarwin())
1764e5dd7070Spatrick     ABIName = "darwinpcs";
1765e5dd7070Spatrick   else
1766e5dd7070Spatrick     ABIName = "aapcs";
1767e5dd7070Spatrick 
1768e5dd7070Spatrick   CmdArgs.push_back("-target-abi");
1769e5dd7070Spatrick   CmdArgs.push_back(ABIName);
1770e5dd7070Spatrick }
1771e5dd7070Spatrick }
1772e5dd7070Spatrick 
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1773e5dd7070Spatrick void Clang::AddAArch64TargetArgs(const ArgList &Args,
1774e5dd7070Spatrick                                  ArgStringList &CmdArgs) const {
1775e5dd7070Spatrick   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1776e5dd7070Spatrick 
1777e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1778e5dd7070Spatrick       Args.hasArg(options::OPT_mkernel) ||
1779e5dd7070Spatrick       Args.hasArg(options::OPT_fapple_kext))
1780e5dd7070Spatrick     CmdArgs.push_back("-disable-red-zone");
1781e5dd7070Spatrick 
1782e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_mimplicit_float,
1783e5dd7070Spatrick                     options::OPT_mno_implicit_float, true))
1784e5dd7070Spatrick     CmdArgs.push_back("-no-implicit-float");
1785e5dd7070Spatrick 
1786e5dd7070Spatrick   RenderAArch64ABI(Triple, Args, CmdArgs);
1787e5dd7070Spatrick 
1788e5dd7070Spatrick   // Forward the -mglobal-merge option for explicit control over the pass.
1789e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1790e5dd7070Spatrick                                options::OPT_mno_global_merge)) {
1791e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
1792e5dd7070Spatrick     if (A->getOption().matches(options::OPT_mno_global_merge))
1793e5dd7070Spatrick       CmdArgs.push_back("-aarch64-enable-global-merge=false");
1794e5dd7070Spatrick     else
1795e5dd7070Spatrick       CmdArgs.push_back("-aarch64-enable-global-merge=true");
1796e5dd7070Spatrick   }
1797e5dd7070Spatrick 
1798e5dd7070Spatrick   // Enable/disable return address signing and indirect branch targets.
17997a9b00ceSrobert   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1800a0747c9fSpatrick 
1801a0747c9fSpatrick   // Handle -msve_vector_bits=<bits>
1802a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1803a0747c9fSpatrick     StringRef Val = A->getValue();
1804a0747c9fSpatrick     const Driver &D = getToolChain().getDriver();
1805a0747c9fSpatrick     if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
18067a9b00ceSrobert         Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
18077a9b00ceSrobert         Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
18087a9b00ceSrobert         Val.equals("2048+")) {
18097a9b00ceSrobert       unsigned Bits = 0;
18107a9b00ceSrobert       if (Val.endswith("+"))
18117a9b00ceSrobert         Val = Val.substr(0, Val.size() - 1);
18127a9b00ceSrobert       else {
18137a9b00ceSrobert         bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
18147a9b00ceSrobert         assert(!Invalid && "Failed to parse value");
1815a0747c9fSpatrick         CmdArgs.push_back(
18167a9b00ceSrobert             Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
18177a9b00ceSrobert       }
18187a9b00ceSrobert 
18197a9b00ceSrobert       bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
18207a9b00ceSrobert       assert(!Invalid && "Failed to parse value");
18217a9b00ceSrobert       CmdArgs.push_back(
18227a9b00ceSrobert           Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1823a0747c9fSpatrick     // Silently drop requests for vector-length agnostic code as it's implied.
18247a9b00ceSrobert     } else if (!Val.equals("scalable"))
1825a0747c9fSpatrick       // Handle the unsupported values passed to msve-vector-bits.
1826a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_option_argument)
18277a9b00ceSrobert           << A->getSpelling() << Val;
1828a0747c9fSpatrick   }
1829a0747c9fSpatrick 
1830a0747c9fSpatrick   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
18317a9b00ceSrobert 
18327a9b00ceSrobert   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
18337a9b00ceSrobert     CmdArgs.push_back("-tune-cpu");
18347a9b00ceSrobert     if (strcmp(A->getValue(), "native") == 0)
18357a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
18367a9b00ceSrobert     else
18377a9b00ceSrobert       CmdArgs.push_back(A->getValue());
18387a9b00ceSrobert   }
18397a9b00ceSrobert 
18407a9b00ceSrobert   AddUnalignedAccessWarning(CmdArgs);
18417a9b00ceSrobert }
18427a9b00ceSrobert 
AddLoongArchTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const18437a9b00ceSrobert void Clang::AddLoongArchTargetArgs(const ArgList &Args,
18447a9b00ceSrobert                                    ArgStringList &CmdArgs) const {
18457a9b00ceSrobert   CmdArgs.push_back("-target-abi");
18467a9b00ceSrobert   CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
18477a9b00ceSrobert                                                getToolChain().getTriple())
18487a9b00ceSrobert                         .data());
1849e5dd7070Spatrick }
1850e5dd7070Spatrick 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1851e5dd7070Spatrick void Clang::AddMIPSTargetArgs(const ArgList &Args,
1852e5dd7070Spatrick                               ArgStringList &CmdArgs) const {
1853e5dd7070Spatrick   const Driver &D = getToolChain().getDriver();
1854e5dd7070Spatrick   StringRef CPUName;
1855e5dd7070Spatrick   StringRef ABIName;
1856e5dd7070Spatrick   const llvm::Triple &Triple = getToolChain().getTriple();
1857e5dd7070Spatrick   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1858e5dd7070Spatrick 
1859e5dd7070Spatrick   CmdArgs.push_back("-target-abi");
1860e5dd7070Spatrick   CmdArgs.push_back(ABIName.data());
1861e5dd7070Spatrick 
1862e5dd7070Spatrick   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1863e5dd7070Spatrick   if (ABI == mips::FloatABI::Soft) {
1864e5dd7070Spatrick     // Floating point operations and argument passing are soft.
1865e5dd7070Spatrick     CmdArgs.push_back("-msoft-float");
1866e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
1867e5dd7070Spatrick     CmdArgs.push_back("soft");
1868e5dd7070Spatrick   } else {
1869e5dd7070Spatrick     // Floating point operations and argument passing are hard.
1870e5dd7070Spatrick     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1871e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
1872e5dd7070Spatrick     CmdArgs.push_back("hard");
1873e5dd7070Spatrick   }
1874e5dd7070Spatrick 
1875e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1876e5dd7070Spatrick                                options::OPT_mno_ldc1_sdc1)) {
1877e5dd7070Spatrick     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1878e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
1879e5dd7070Spatrick       CmdArgs.push_back("-mno-ldc1-sdc1");
1880e5dd7070Spatrick     }
1881e5dd7070Spatrick   }
1882e5dd7070Spatrick 
1883e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1884e5dd7070Spatrick                                options::OPT_mno_check_zero_division)) {
1885e5dd7070Spatrick     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1886e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
1887e5dd7070Spatrick       CmdArgs.push_back("-mno-check-zero-division");
1888e5dd7070Spatrick     }
1889e5dd7070Spatrick   }
1890e5dd7070Spatrick 
18917a9b00ceSrobert   if (Args.getLastArg(options::OPT_mfix4300)) {
18927a9b00ceSrobert     CmdArgs.push_back("-mllvm");
18937a9b00ceSrobert     CmdArgs.push_back("-mfix4300");
18947a9b00ceSrobert   }
18957a9b00ceSrobert 
1896e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1897e5dd7070Spatrick     StringRef v = A->getValue();
1898e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
1899e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1900e5dd7070Spatrick     A->claim();
1901e5dd7070Spatrick   }
1902e5dd7070Spatrick 
1903e5dd7070Spatrick   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1904e5dd7070Spatrick   Arg *ABICalls =
1905e5dd7070Spatrick       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1906e5dd7070Spatrick 
1907e5dd7070Spatrick   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1908e5dd7070Spatrick   // -mgpopt is the default for static, -fno-pic environments but these two
1909e5dd7070Spatrick   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1910e5dd7070Spatrick   // the only case where -mllvm -mgpopt is passed.
1911e5dd7070Spatrick   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1912e5dd7070Spatrick   //       passed explicitly when compiling something with -mabicalls
1913e5dd7070Spatrick   //       (implictly) in affect. Currently the warning is in the backend.
1914e5dd7070Spatrick   //
1915e5dd7070Spatrick   // When the ABI in use is  N64, we also need to determine the PIC mode that
1916e5dd7070Spatrick   // is in use, as -fno-pic for N64 implies -mno-abicalls.
1917e5dd7070Spatrick   bool NoABICalls =
1918e5dd7070Spatrick       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1919e5dd7070Spatrick 
1920e5dd7070Spatrick   llvm::Reloc::Model RelocationModel;
1921e5dd7070Spatrick   unsigned PICLevel;
1922e5dd7070Spatrick   bool IsPIE;
1923e5dd7070Spatrick   std::tie(RelocationModel, PICLevel, IsPIE) =
1924e5dd7070Spatrick       ParsePICArgs(getToolChain(), Args);
1925e5dd7070Spatrick 
1926e5dd7070Spatrick   NoABICalls = NoABICalls ||
1927e5dd7070Spatrick                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1928e5dd7070Spatrick 
1929e5dd7070Spatrick   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1930e5dd7070Spatrick   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1931e5dd7070Spatrick   if (NoABICalls && (!GPOpt || WantGPOpt)) {
1932e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
1933e5dd7070Spatrick     CmdArgs.push_back("-mgpopt");
1934e5dd7070Spatrick 
1935e5dd7070Spatrick     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1936e5dd7070Spatrick                                       options::OPT_mno_local_sdata);
1937e5dd7070Spatrick     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1938e5dd7070Spatrick                                        options::OPT_mno_extern_sdata);
1939e5dd7070Spatrick     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1940e5dd7070Spatrick                                         options::OPT_mno_embedded_data);
1941e5dd7070Spatrick     if (LocalSData) {
1942e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
1943e5dd7070Spatrick       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1944e5dd7070Spatrick         CmdArgs.push_back("-mlocal-sdata=1");
1945e5dd7070Spatrick       } else {
1946e5dd7070Spatrick         CmdArgs.push_back("-mlocal-sdata=0");
1947e5dd7070Spatrick       }
1948e5dd7070Spatrick       LocalSData->claim();
1949e5dd7070Spatrick     }
1950e5dd7070Spatrick 
1951e5dd7070Spatrick     if (ExternSData) {
1952e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
1953e5dd7070Spatrick       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1954e5dd7070Spatrick         CmdArgs.push_back("-mextern-sdata=1");
1955e5dd7070Spatrick       } else {
1956e5dd7070Spatrick         CmdArgs.push_back("-mextern-sdata=0");
1957e5dd7070Spatrick       }
1958e5dd7070Spatrick       ExternSData->claim();
1959e5dd7070Spatrick     }
1960e5dd7070Spatrick 
1961e5dd7070Spatrick     if (EmbeddedData) {
1962e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
1963e5dd7070Spatrick       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1964e5dd7070Spatrick         CmdArgs.push_back("-membedded-data=1");
1965e5dd7070Spatrick       } else {
1966e5dd7070Spatrick         CmdArgs.push_back("-membedded-data=0");
1967e5dd7070Spatrick       }
1968e5dd7070Spatrick       EmbeddedData->claim();
1969e5dd7070Spatrick     }
1970e5dd7070Spatrick 
1971e5dd7070Spatrick   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1972e5dd7070Spatrick     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1973e5dd7070Spatrick 
1974e5dd7070Spatrick   if (GPOpt)
1975e5dd7070Spatrick     GPOpt->claim();
1976e5dd7070Spatrick 
1977e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1978e5dd7070Spatrick     StringRef Val = StringRef(A->getValue());
1979e5dd7070Spatrick     if (mips::hasCompactBranches(CPUName)) {
1980e5dd7070Spatrick       if (Val == "never" || Val == "always" || Val == "optimal") {
1981e5dd7070Spatrick         CmdArgs.push_back("-mllvm");
1982e5dd7070Spatrick         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1983e5dd7070Spatrick       } else
1984e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_option_argument)
19857a9b00ceSrobert             << A->getSpelling() << Val;
1986e5dd7070Spatrick     } else
1987e5dd7070Spatrick       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1988e5dd7070Spatrick   }
1989e5dd7070Spatrick 
1990e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1991e5dd7070Spatrick                                options::OPT_mno_relax_pic_calls)) {
1992e5dd7070Spatrick     if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1993e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
1994e5dd7070Spatrick       CmdArgs.push_back("-mips-jalr-reloc=0");
1995e5dd7070Spatrick     }
1996e5dd7070Spatrick   }
1997e5dd7070Spatrick }
1998e5dd7070Spatrick 
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1999e5dd7070Spatrick void Clang::AddPPCTargetArgs(const ArgList &Args,
2000e5dd7070Spatrick                              ArgStringList &CmdArgs) const {
20017a9b00ceSrobert   const llvm::Triple &T = getToolChain().getTriple();
20027a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
20037a9b00ceSrobert     CmdArgs.push_back("-tune-cpu");
20047a9b00ceSrobert     std::string CPU = ppc::getPPCTuneCPU(Args, T);
20057a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(CPU));
20067a9b00ceSrobert   }
20077a9b00ceSrobert 
2008e5dd7070Spatrick   // Select the ABI to use.
2009e5dd7070Spatrick   const char *ABIName = nullptr;
2010e5dd7070Spatrick   if (T.isOSBinFormatELF()) {
2011e5dd7070Spatrick     switch (getToolChain().getArch()) {
2012e5dd7070Spatrick     case llvm::Triple::ppc64: {
20137a9b00ceSrobert       if (T.isPPC64ELFv2ABI())
2014e5dd7070Spatrick         ABIName = "elfv2";
2015e5dd7070Spatrick       else
2016e5dd7070Spatrick         ABIName = "elfv1";
2017e5dd7070Spatrick       break;
2018e5dd7070Spatrick     }
2019e5dd7070Spatrick     case llvm::Triple::ppc64le:
2020e5dd7070Spatrick       ABIName = "elfv2";
2021e5dd7070Spatrick       break;
2022e5dd7070Spatrick     default:
2023e5dd7070Spatrick       break;
2024e5dd7070Spatrick     }
2025e5dd7070Spatrick   }
2026e5dd7070Spatrick 
20277a9b00ceSrobert   bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2028e5dd7070Spatrick   for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2029e5dd7070Spatrick     StringRef V = A->getValue();
2030e5dd7070Spatrick     if (V == "ieeelongdouble")
2031e5dd7070Spatrick       IEEELongDouble = true;
2032e5dd7070Spatrick     else if (V == "ibmlongdouble")
2033e5dd7070Spatrick       IEEELongDouble = false;
2034e5dd7070Spatrick     else if (V != "altivec")
2035e5dd7070Spatrick       // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2036e5dd7070Spatrick       // the option if given as we don't have backend support for any targets
2037e5dd7070Spatrick       // that don't use the altivec abi.
2038e5dd7070Spatrick       ABIName = A->getValue();
2039e5dd7070Spatrick   }
2040e5dd7070Spatrick   if (IEEELongDouble)
2041e5dd7070Spatrick     CmdArgs.push_back("-mabi=ieeelongdouble");
2042e5dd7070Spatrick 
2043e5dd7070Spatrick   ppc::FloatABI FloatABI =
2044e5dd7070Spatrick       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
2045e5dd7070Spatrick 
2046e5dd7070Spatrick   if (FloatABI == ppc::FloatABI::Soft) {
2047e5dd7070Spatrick     // Floating point operations and argument passing are soft.
2048e5dd7070Spatrick     CmdArgs.push_back("-msoft-float");
2049e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
2050e5dd7070Spatrick     CmdArgs.push_back("soft");
2051e5dd7070Spatrick   } else {
2052e5dd7070Spatrick     // Floating point operations and argument passing are hard.
2053e5dd7070Spatrick     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2054e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
2055e5dd7070Spatrick     CmdArgs.push_back("hard");
2056e5dd7070Spatrick   }
2057e5dd7070Spatrick 
2058e5dd7070Spatrick   if (ABIName) {
2059e5dd7070Spatrick     CmdArgs.push_back("-target-abi");
2060e5dd7070Spatrick     CmdArgs.push_back(ABIName);
2061e5dd7070Spatrick   }
2062e5dd7070Spatrick }
2063e5dd7070Spatrick 
SetRISCVSmallDataLimit(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2064adae0cfdSpatrick static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2065adae0cfdSpatrick                                    ArgStringList &CmdArgs) {
2066adae0cfdSpatrick   const Driver &D = TC.getDriver();
2067adae0cfdSpatrick   const llvm::Triple &Triple = TC.getTriple();
2068adae0cfdSpatrick   // Default small data limitation is eight.
2069adae0cfdSpatrick   const char *SmallDataLimit = "8";
2070adae0cfdSpatrick   // Get small data limitation.
2071adae0cfdSpatrick   if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2072adae0cfdSpatrick                       options::OPT_fPIC)) {
2073adae0cfdSpatrick     // Not support linker relaxation for PIC.
2074adae0cfdSpatrick     SmallDataLimit = "0";
2075adae0cfdSpatrick     if (Args.hasArg(options::OPT_G)) {
2076adae0cfdSpatrick       D.Diag(diag::warn_drv_unsupported_sdata);
2077adae0cfdSpatrick     }
2078adae0cfdSpatrick   } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2079a0747c9fSpatrick                  .equals_insensitive("large") &&
2080adae0cfdSpatrick              (Triple.getArch() == llvm::Triple::riscv64)) {
2081adae0cfdSpatrick     // Not support linker relaxation for RV64 with large code model.
2082adae0cfdSpatrick     SmallDataLimit = "0";
2083adae0cfdSpatrick     if (Args.hasArg(options::OPT_G)) {
2084adae0cfdSpatrick       D.Diag(diag::warn_drv_unsupported_sdata);
2085adae0cfdSpatrick     }
2086adae0cfdSpatrick   } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2087adae0cfdSpatrick     SmallDataLimit = A->getValue();
2088adae0cfdSpatrick   }
2089adae0cfdSpatrick   // Forward the -msmall-data-limit= option.
2090adae0cfdSpatrick   CmdArgs.push_back("-msmall-data-limit");
2091adae0cfdSpatrick   CmdArgs.push_back(SmallDataLimit);
2092adae0cfdSpatrick }
2093adae0cfdSpatrick 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2094e5dd7070Spatrick void Clang::AddRISCVTargetArgs(const ArgList &Args,
2095e5dd7070Spatrick                                ArgStringList &CmdArgs) const {
2096e5dd7070Spatrick   const llvm::Triple &Triple = getToolChain().getTriple();
2097e5dd7070Spatrick   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2098e5dd7070Spatrick 
2099e5dd7070Spatrick   CmdArgs.push_back("-target-abi");
2100e5dd7070Spatrick   CmdArgs.push_back(ABIName.data());
2101adae0cfdSpatrick 
2102adae0cfdSpatrick   SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2103a0747c9fSpatrick 
21047a9b00ceSrobert   if (!Args.hasFlag(options::OPT_mimplicit_float,
21057a9b00ceSrobert                     options::OPT_mno_implicit_float, true))
21067a9b00ceSrobert     CmdArgs.push_back("-no-implicit-float");
2107a0747c9fSpatrick 
21087a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2109a0747c9fSpatrick     CmdArgs.push_back("-tune-cpu");
21107a9b00ceSrobert     if (strcmp(A->getValue(), "native") == 0)
21117a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
21127a9b00ceSrobert     else
21137a9b00ceSrobert       CmdArgs.push_back(A->getValue());
2114a0747c9fSpatrick   }
2115e5dd7070Spatrick }
2116e5dd7070Spatrick 
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2117e5dd7070Spatrick void Clang::AddSparcTargetArgs(const ArgList &Args,
2118e5dd7070Spatrick                                ArgStringList &CmdArgs) const {
2119e5dd7070Spatrick   sparc::FloatABI FloatABI =
2120e5dd7070Spatrick       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2121e5dd7070Spatrick 
2122e5dd7070Spatrick   if (FloatABI == sparc::FloatABI::Soft) {
2123e5dd7070Spatrick     // Floating point operations and argument passing are soft.
2124e5dd7070Spatrick     CmdArgs.push_back("-msoft-float");
2125e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
2126e5dd7070Spatrick     CmdArgs.push_back("soft");
2127e5dd7070Spatrick   } else {
2128e5dd7070Spatrick     // Floating point operations and argument passing are hard.
2129e5dd7070Spatrick     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2130e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
2131e5dd7070Spatrick     CmdArgs.push_back("hard");
2132e5dd7070Spatrick   }
21337a9b00ceSrobert 
21347a9b00ceSrobert   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
21357a9b00ceSrobert     StringRef Name = A->getValue();
21367a9b00ceSrobert     std::string TuneCPU;
21377a9b00ceSrobert     if (Name == "native")
21387a9b00ceSrobert       TuneCPU = std::string(llvm::sys::getHostCPUName());
21397a9b00ceSrobert     else
21407a9b00ceSrobert       TuneCPU = std::string(Name);
21417a9b00ceSrobert 
21427a9b00ceSrobert     CmdArgs.push_back("-tune-cpu");
21437a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
21447a9b00ceSrobert   }
2145e5dd7070Spatrick }
2146e5dd7070Spatrick 
AddSystemZTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2147e5dd7070Spatrick void Clang::AddSystemZTargetArgs(const ArgList &Args,
2148e5dd7070Spatrick                                  ArgStringList &CmdArgs) const {
21497a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
21507a9b00ceSrobert     CmdArgs.push_back("-tune-cpu");
21517a9b00ceSrobert     if (strcmp(A->getValue(), "native") == 0)
21527a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
21537a9b00ceSrobert     else
21547a9b00ceSrobert       CmdArgs.push_back(A->getValue());
21557a9b00ceSrobert   }
21567a9b00ceSrobert 
21577a9b00ceSrobert   bool HasBackchain =
21587a9b00ceSrobert       Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2159e5dd7070Spatrick   bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2160e5dd7070Spatrick                                      options::OPT_mno_packed_stack, false);
2161adae0cfdSpatrick   systemz::FloatABI FloatABI =
2162adae0cfdSpatrick       systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2163adae0cfdSpatrick   bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2164adae0cfdSpatrick   if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2165e5dd7070Spatrick     const Driver &D = getToolChain().getDriver();
2166e5dd7070Spatrick     D.Diag(diag::err_drv_unsupported_opt)
2167adae0cfdSpatrick       << "-mpacked-stack -mbackchain -mhard-float";
2168e5dd7070Spatrick   }
2169e5dd7070Spatrick   if (HasBackchain)
2170e5dd7070Spatrick     CmdArgs.push_back("-mbackchain");
2171e5dd7070Spatrick   if (HasPackedStack)
2172e5dd7070Spatrick     CmdArgs.push_back("-mpacked-stack");
2173adae0cfdSpatrick   if (HasSoftFloat) {
2174adae0cfdSpatrick     // Floating point operations and argument passing are soft.
2175adae0cfdSpatrick     CmdArgs.push_back("-msoft-float");
2176adae0cfdSpatrick     CmdArgs.push_back("-mfloat-abi");
2177adae0cfdSpatrick     CmdArgs.push_back("soft");
2178e5dd7070Spatrick   }
2179e5dd7070Spatrick }
2180e5dd7070Spatrick 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2181e5dd7070Spatrick void Clang::AddX86TargetArgs(const ArgList &Args,
2182e5dd7070Spatrick                              ArgStringList &CmdArgs) const {
2183e5dd7070Spatrick   const Driver &D = getToolChain().getDriver();
2184adae0cfdSpatrick   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2185e5dd7070Spatrick 
2186e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2187e5dd7070Spatrick       Args.hasArg(options::OPT_mkernel) ||
2188e5dd7070Spatrick       Args.hasArg(options::OPT_fapple_kext))
2189e5dd7070Spatrick     CmdArgs.push_back("-disable-red-zone");
2190e5dd7070Spatrick 
2191e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2192e5dd7070Spatrick                     options::OPT_mno_tls_direct_seg_refs, true))
2193e5dd7070Spatrick     CmdArgs.push_back("-mno-tls-direct-seg-refs");
2194e5dd7070Spatrick 
2195e5dd7070Spatrick   // Default to avoid implicit floating-point for kernel/kext code, but allow
2196e5dd7070Spatrick   // that to be overridden with -mno-soft-float.
2197e5dd7070Spatrick   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2198e5dd7070Spatrick                           Args.hasArg(options::OPT_fapple_kext));
2199e5dd7070Spatrick   if (Arg *A = Args.getLastArg(
2200e5dd7070Spatrick           options::OPT_msoft_float, options::OPT_mno_soft_float,
2201e5dd7070Spatrick           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2202e5dd7070Spatrick     const Option &O = A->getOption();
2203e5dd7070Spatrick     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2204e5dd7070Spatrick                        O.matches(options::OPT_msoft_float));
2205e5dd7070Spatrick   }
2206e5dd7070Spatrick   if (NoImplicitFloat)
2207e5dd7070Spatrick     CmdArgs.push_back("-no-implicit-float");
2208e5dd7070Spatrick 
2209e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2210e5dd7070Spatrick     StringRef Value = A->getValue();
2211e5dd7070Spatrick     if (Value == "intel" || Value == "att") {
2212e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
2213e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
22147a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2215e5dd7070Spatrick     } else {
2216e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_option_argument)
22177a9b00ceSrobert           << A->getSpelling() << Value;
2218e5dd7070Spatrick     }
2219e5dd7070Spatrick   } else if (D.IsCLMode()) {
2220e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
2221e5dd7070Spatrick     CmdArgs.push_back("-x86-asm-syntax=intel");
2222e5dd7070Spatrick   }
2223e5dd7070Spatrick 
22247a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
22257a9b00ceSrobert                                options::OPT_mno_skip_rax_setup))
22267a9b00ceSrobert     if (A->getOption().matches(options::OPT_mskip_rax_setup))
22277a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
22287a9b00ceSrobert 
2229e5dd7070Spatrick   // Set flags to support MCU ABI.
2230e5dd7070Spatrick   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2231e5dd7070Spatrick     CmdArgs.push_back("-mfloat-abi");
2232e5dd7070Spatrick     CmdArgs.push_back("soft");
2233e5dd7070Spatrick     CmdArgs.push_back("-mstack-alignment=4");
2234e5dd7070Spatrick   }
2235a0747c9fSpatrick 
2236a0747c9fSpatrick   // Handle -mtune.
2237a0747c9fSpatrick 
22387a9b00ceSrobert   // Default to "generic" unless -march is present or targetting the PS4/PS5.
2239a0747c9fSpatrick   std::string TuneCPU;
2240a0747c9fSpatrick   if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
22417a9b00ceSrobert       !getToolChain().getTriple().isPS())
2242a0747c9fSpatrick     TuneCPU = "generic";
2243a0747c9fSpatrick 
2244a0747c9fSpatrick   // Override based on -mtune.
2245a0747c9fSpatrick   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2246a0747c9fSpatrick     StringRef Name = A->getValue();
2247a0747c9fSpatrick 
2248a0747c9fSpatrick     if (Name == "native") {
2249a0747c9fSpatrick       Name = llvm::sys::getHostCPUName();
2250a0747c9fSpatrick       if (!Name.empty())
2251a0747c9fSpatrick         TuneCPU = std::string(Name);
2252a0747c9fSpatrick     } else
2253a0747c9fSpatrick       TuneCPU = std::string(Name);
2254a0747c9fSpatrick   }
2255a0747c9fSpatrick 
2256a0747c9fSpatrick   if (!TuneCPU.empty()) {
2257a0747c9fSpatrick     CmdArgs.push_back("-tune-cpu");
2258a0747c9fSpatrick     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2259a0747c9fSpatrick   }
2260e5dd7070Spatrick }
2261e5dd7070Spatrick 
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2262e5dd7070Spatrick void Clang::AddHexagonTargetArgs(const ArgList &Args,
2263e5dd7070Spatrick                                  ArgStringList &CmdArgs) const {
2264e5dd7070Spatrick   CmdArgs.push_back("-mqdsp6-compat");
2265e5dd7070Spatrick   CmdArgs.push_back("-Wreturn-type");
2266e5dd7070Spatrick 
2267e5dd7070Spatrick   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2268e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
22697a9b00ceSrobert     CmdArgs.push_back(
22707a9b00ceSrobert         Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2271e5dd7070Spatrick   }
2272e5dd7070Spatrick 
2273e5dd7070Spatrick   if (!Args.hasArg(options::OPT_fno_short_enums))
2274e5dd7070Spatrick     CmdArgs.push_back("-fshort-enums");
2275e5dd7070Spatrick   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2276e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
2277e5dd7070Spatrick     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2278e5dd7070Spatrick   }
2279e5dd7070Spatrick   CmdArgs.push_back("-mllvm");
2280e5dd7070Spatrick   CmdArgs.push_back("-machine-sink-split=0");
2281e5dd7070Spatrick }
2282e5dd7070Spatrick 
AddLanaiTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2283e5dd7070Spatrick void Clang::AddLanaiTargetArgs(const ArgList &Args,
2284e5dd7070Spatrick                                ArgStringList &CmdArgs) const {
2285e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2286e5dd7070Spatrick     StringRef CPUName = A->getValue();
2287e5dd7070Spatrick 
2288e5dd7070Spatrick     CmdArgs.push_back("-target-cpu");
2289e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(CPUName));
2290e5dd7070Spatrick   }
2291e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2292e5dd7070Spatrick     StringRef Value = A->getValue();
2293e5dd7070Spatrick     // Only support mregparm=4 to support old usage. Report error for all other
2294e5dd7070Spatrick     // cases.
2295e5dd7070Spatrick     int Mregparm;
2296e5dd7070Spatrick     if (Value.getAsInteger(10, Mregparm)) {
2297e5dd7070Spatrick       if (Mregparm != 4) {
2298e5dd7070Spatrick         getToolChain().getDriver().Diag(
2299e5dd7070Spatrick             diag::err_drv_unsupported_option_argument)
23007a9b00ceSrobert             << A->getSpelling() << Value;
2301e5dd7070Spatrick       }
2302e5dd7070Spatrick     }
2303e5dd7070Spatrick   }
2304e5dd7070Spatrick }
2305e5dd7070Spatrick 
AddWebAssemblyTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2306e5dd7070Spatrick void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2307e5dd7070Spatrick                                      ArgStringList &CmdArgs) const {
2308e5dd7070Spatrick   // Default to "hidden" visibility.
2309e5dd7070Spatrick   if (!Args.hasArg(options::OPT_fvisibility_EQ,
23107a9b00ceSrobert                    options::OPT_fvisibility_ms_compat))
23117a9b00ceSrobert     CmdArgs.push_back("-fvisibility=hidden");
2312e5dd7070Spatrick }
2313e5dd7070Spatrick 
AddVETargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2314adae0cfdSpatrick void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2315adae0cfdSpatrick   // Floating point operations and argument passing are hard.
2316adae0cfdSpatrick   CmdArgs.push_back("-mfloat-abi");
2317adae0cfdSpatrick   CmdArgs.push_back("hard");
2318adae0cfdSpatrick }
2319adae0cfdSpatrick 
DumpCompilationDatabase(Compilation & C,StringRef Filename,StringRef Target,const InputInfo & Output,const InputInfo & Input,const ArgList & Args) const2320e5dd7070Spatrick void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2321e5dd7070Spatrick                                     StringRef Target, const InputInfo &Output,
2322e5dd7070Spatrick                                     const InputInfo &Input, const ArgList &Args) const {
2323e5dd7070Spatrick   // If this is a dry run, do not create the compilation database file.
2324e5dd7070Spatrick   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2325e5dd7070Spatrick     return;
2326e5dd7070Spatrick 
2327e5dd7070Spatrick   using llvm::yaml::escape;
2328e5dd7070Spatrick   const Driver &D = getToolChain().getDriver();
2329e5dd7070Spatrick 
2330e5dd7070Spatrick   if (!CompilationDatabase) {
2331e5dd7070Spatrick     std::error_code EC;
2332a0747c9fSpatrick     auto File = std::make_unique<llvm::raw_fd_ostream>(
23337a9b00ceSrobert         Filename, EC,
23347a9b00ceSrobert         llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2335e5dd7070Spatrick     if (EC) {
2336e5dd7070Spatrick       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2337e5dd7070Spatrick                                                        << EC.message();
2338e5dd7070Spatrick       return;
2339e5dd7070Spatrick     }
2340e5dd7070Spatrick     CompilationDatabase = std::move(File);
2341e5dd7070Spatrick   }
2342e5dd7070Spatrick   auto &CDB = *CompilationDatabase;
2343e5dd7070Spatrick   auto CWD = D.getVFS().getCurrentWorkingDirectory();
2344e5dd7070Spatrick   if (!CWD)
2345e5dd7070Spatrick     CWD = ".";
2346e5dd7070Spatrick   CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2347e5dd7070Spatrick   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2348e5dd7070Spatrick   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2349e5dd7070Spatrick   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2350e5dd7070Spatrick   SmallString<128> Buf;
2351e5dd7070Spatrick   Buf = "-x";
2352e5dd7070Spatrick   Buf += types::getTypeName(Input.getType());
2353e5dd7070Spatrick   CDB << ", \"" << escape(Buf) << "\"";
2354e5dd7070Spatrick   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2355e5dd7070Spatrick     Buf = "--sysroot=";
2356e5dd7070Spatrick     Buf += D.SysRoot;
2357e5dd7070Spatrick     CDB << ", \"" << escape(Buf) << "\"";
2358e5dd7070Spatrick   }
2359e5dd7070Spatrick   CDB << ", \"" << escape(Input.getFilename()) << "\"";
23607a9b00ceSrobert   CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2361e5dd7070Spatrick   for (auto &A: Args) {
2362e5dd7070Spatrick     auto &O = A->getOption();
2363e5dd7070Spatrick     // Skip language selection, which is positional.
2364e5dd7070Spatrick     if (O.getID() == options::OPT_x)
2365e5dd7070Spatrick       continue;
2366e5dd7070Spatrick     // Skip writing dependency output and the compilation database itself.
2367e5dd7070Spatrick     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2368e5dd7070Spatrick       continue;
2369e5dd7070Spatrick     if (O.getID() == options::OPT_gen_cdb_fragment_path)
2370e5dd7070Spatrick       continue;
2371e5dd7070Spatrick     // Skip inputs.
2372e5dd7070Spatrick     if (O.getKind() == Option::InputClass)
2373e5dd7070Spatrick       continue;
23747a9b00ceSrobert     // Skip output.
23757a9b00ceSrobert     if (O.getID() == options::OPT_o)
23767a9b00ceSrobert       continue;
2377e5dd7070Spatrick     // All other arguments are quoted and appended.
2378e5dd7070Spatrick     ArgStringList ASL;
2379e5dd7070Spatrick     A->render(Args, ASL);
2380e5dd7070Spatrick     for (auto &it: ASL)
2381e5dd7070Spatrick       CDB << ", \"" << escape(it) << "\"";
2382e5dd7070Spatrick   }
2383e5dd7070Spatrick   Buf = "--target=";
2384e5dd7070Spatrick   Buf += Target;
2385e5dd7070Spatrick   CDB << ", \"" << escape(Buf) << "\"]},\n";
2386e5dd7070Spatrick }
2387e5dd7070Spatrick 
DumpCompilationDatabaseFragmentToDir(StringRef Dir,Compilation & C,StringRef Target,const InputInfo & Output,const InputInfo & Input,const llvm::opt::ArgList & Args) const2388e5dd7070Spatrick void Clang::DumpCompilationDatabaseFragmentToDir(
2389e5dd7070Spatrick     StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2390e5dd7070Spatrick     const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2391e5dd7070Spatrick   // If this is a dry run, do not create the compilation database file.
2392e5dd7070Spatrick   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2393e5dd7070Spatrick     return;
2394e5dd7070Spatrick 
2395e5dd7070Spatrick   if (CompilationDatabase)
2396e5dd7070Spatrick     DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2397e5dd7070Spatrick 
2398e5dd7070Spatrick   SmallString<256> Path = Dir;
2399e5dd7070Spatrick   const auto &Driver = C.getDriver();
2400e5dd7070Spatrick   Driver.getVFS().makeAbsolute(Path);
2401e5dd7070Spatrick   auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2402e5dd7070Spatrick   if (Err) {
2403e5dd7070Spatrick     Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2404e5dd7070Spatrick     return;
2405e5dd7070Spatrick   }
2406e5dd7070Spatrick 
2407e5dd7070Spatrick   llvm::sys::path::append(
2408e5dd7070Spatrick       Path,
2409e5dd7070Spatrick       Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2410e5dd7070Spatrick   int FD;
2411e5dd7070Spatrick   SmallString<256> TempPath;
2412a0747c9fSpatrick   Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2413a0747c9fSpatrick                                         llvm::sys::fs::OF_Text);
2414e5dd7070Spatrick   if (Err) {
2415e5dd7070Spatrick     Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2416e5dd7070Spatrick     return;
2417e5dd7070Spatrick   }
2418e5dd7070Spatrick   CompilationDatabase =
2419e5dd7070Spatrick       std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2420e5dd7070Spatrick   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2421e5dd7070Spatrick }
2422e5dd7070Spatrick 
CheckARMImplicitITArg(StringRef Value)2423a0747c9fSpatrick static bool CheckARMImplicitITArg(StringRef Value) {
2424a0747c9fSpatrick   return Value == "always" || Value == "never" || Value == "arm" ||
2425a0747c9fSpatrick          Value == "thumb";
2426a0747c9fSpatrick }
2427a0747c9fSpatrick 
AddARMImplicitITArgs(const ArgList & Args,ArgStringList & CmdArgs,StringRef Value)2428a0747c9fSpatrick static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2429a0747c9fSpatrick                                  StringRef Value) {
2430a0747c9fSpatrick   CmdArgs.push_back("-mllvm");
2431a0747c9fSpatrick   CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2432a0747c9fSpatrick }
2433a0747c9fSpatrick 
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)2434e5dd7070Spatrick static void CollectArgsForIntegratedAssembler(Compilation &C,
2435e5dd7070Spatrick                                               const ArgList &Args,
2436e5dd7070Spatrick                                               ArgStringList &CmdArgs,
2437e5dd7070Spatrick                                               const Driver &D) {
2438e5dd7070Spatrick   if (UseRelaxAll(C, Args))
2439e5dd7070Spatrick     CmdArgs.push_back("-mrelax-all");
2440e5dd7070Spatrick 
2441e5dd7070Spatrick   // Only default to -mincremental-linker-compatible if we think we are
2442e5dd7070Spatrick   // targeting the MSVC linker.
2443e5dd7070Spatrick   bool DefaultIncrementalLinkerCompatible =
2444e5dd7070Spatrick       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2445e5dd7070Spatrick   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2446e5dd7070Spatrick                    options::OPT_mno_incremental_linker_compatible,
2447e5dd7070Spatrick                    DefaultIncrementalLinkerCompatible))
2448e5dd7070Spatrick     CmdArgs.push_back("-mincremental-linker-compatible");
2449e5dd7070Spatrick 
24507a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
24517a9b00ceSrobert 
2452e5dd7070Spatrick   // If you add more args here, also add them to the block below that
2453e5dd7070Spatrick   // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2454e5dd7070Spatrick 
2455e5dd7070Spatrick   // When passing -I arguments to the assembler we sometimes need to
2456e5dd7070Spatrick   // unconditionally take the next argument.  For example, when parsing
2457e5dd7070Spatrick   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2458e5dd7070Spatrick   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2459e5dd7070Spatrick   // arg after parsing the '-I' arg.
2460e5dd7070Spatrick   bool TakeNextArg = false;
2461e5dd7070Spatrick 
2462e5dd7070Spatrick   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
24637a9b00ceSrobert   bool UseNoExecStack = false;
2464e5dd7070Spatrick   const char *MipsTargetFeature = nullptr;
2465a0747c9fSpatrick   StringRef ImplicitIt;
2466e5dd7070Spatrick   for (const Arg *A :
2467a0747c9fSpatrick        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2468a0747c9fSpatrick                      options::OPT_mimplicit_it_EQ)) {
2469e5dd7070Spatrick     A->claim();
2470e5dd7070Spatrick 
2471a0747c9fSpatrick     if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2472a0747c9fSpatrick       switch (C.getDefaultToolChain().getArch()) {
2473a0747c9fSpatrick       case llvm::Triple::arm:
2474a0747c9fSpatrick       case llvm::Triple::armeb:
2475a0747c9fSpatrick       case llvm::Triple::thumb:
2476a0747c9fSpatrick       case llvm::Triple::thumbeb:
2477a0747c9fSpatrick         // Only store the value; the last value set takes effect.
2478a0747c9fSpatrick         ImplicitIt = A->getValue();
2479a0747c9fSpatrick         if (!CheckARMImplicitITArg(ImplicitIt))
2480a0747c9fSpatrick           D.Diag(diag::err_drv_unsupported_option_argument)
24817a9b00ceSrobert               << A->getSpelling() << ImplicitIt;
2482a0747c9fSpatrick         continue;
2483a0747c9fSpatrick       default:
2484a0747c9fSpatrick         break;
2485a0747c9fSpatrick       }
2486a0747c9fSpatrick     }
2487a0747c9fSpatrick 
2488e5dd7070Spatrick     for (StringRef Value : A->getValues()) {
2489e5dd7070Spatrick       if (TakeNextArg) {
2490e5dd7070Spatrick         CmdArgs.push_back(Value.data());
2491e5dd7070Spatrick         TakeNextArg = false;
2492e5dd7070Spatrick         continue;
2493e5dd7070Spatrick       }
2494e5dd7070Spatrick 
2495e5dd7070Spatrick       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2496e5dd7070Spatrick           Value == "-mbig-obj")
2497e5dd7070Spatrick         continue; // LLVM handles bigobj automatically
2498e5dd7070Spatrick 
2499e5dd7070Spatrick       switch (C.getDefaultToolChain().getArch()) {
2500e5dd7070Spatrick       default:
2501e5dd7070Spatrick         break;
25027a9b00ceSrobert       case llvm::Triple::wasm32:
25037a9b00ceSrobert       case llvm::Triple::wasm64:
25047a9b00ceSrobert         if (Value == "--no-type-check") {
25057a9b00ceSrobert           CmdArgs.push_back("-mno-type-check");
25067a9b00ceSrobert           continue;
25077a9b00ceSrobert         }
25087a9b00ceSrobert         break;
2509e5dd7070Spatrick       case llvm::Triple::thumb:
2510e5dd7070Spatrick       case llvm::Triple::thumbeb:
2511e5dd7070Spatrick       case llvm::Triple::arm:
2512e5dd7070Spatrick       case llvm::Triple::armeb:
2513a0747c9fSpatrick         if (Value.startswith("-mimplicit-it=")) {
2514a0747c9fSpatrick           // Only store the value; the last value set takes effect.
2515a0747c9fSpatrick           ImplicitIt = Value.split("=").second;
2516a0747c9fSpatrick           if (CheckARMImplicitITArg(ImplicitIt))
2517a0747c9fSpatrick             continue;
2518a0747c9fSpatrick         }
2519e5dd7070Spatrick         if (Value == "-mthumb")
2520e5dd7070Spatrick           // -mthumb has already been processed in ComputeLLVMTriple()
2521e5dd7070Spatrick           // recognize but skip over here.
2522e5dd7070Spatrick           continue;
2523e5dd7070Spatrick         break;
2524e5dd7070Spatrick       case llvm::Triple::mips:
2525e5dd7070Spatrick       case llvm::Triple::mipsel:
2526e5dd7070Spatrick       case llvm::Triple::mips64:
2527e5dd7070Spatrick       case llvm::Triple::mips64el:
2528e5dd7070Spatrick         if (Value == "--trap") {
2529e5dd7070Spatrick           CmdArgs.push_back("-target-feature");
2530e5dd7070Spatrick           CmdArgs.push_back("+use-tcc-in-div");
2531e5dd7070Spatrick           continue;
2532e5dd7070Spatrick         }
2533e5dd7070Spatrick         if (Value == "--break") {
2534e5dd7070Spatrick           CmdArgs.push_back("-target-feature");
2535e5dd7070Spatrick           CmdArgs.push_back("-use-tcc-in-div");
2536e5dd7070Spatrick           continue;
2537e5dd7070Spatrick         }
2538e5dd7070Spatrick         if (Value.startswith("-msoft-float")) {
2539e5dd7070Spatrick           CmdArgs.push_back("-target-feature");
2540e5dd7070Spatrick           CmdArgs.push_back("+soft-float");
2541e5dd7070Spatrick           continue;
2542e5dd7070Spatrick         }
2543e5dd7070Spatrick         if (Value.startswith("-mhard-float")) {
2544e5dd7070Spatrick           CmdArgs.push_back("-target-feature");
2545e5dd7070Spatrick           CmdArgs.push_back("-soft-float");
2546e5dd7070Spatrick           continue;
2547e5dd7070Spatrick         }
2548e73ff4e6Svisa         if (Value.startswith("-mfix-loongson2f-btb")) {
2549e73ff4e6Svisa           CmdArgs.push_back("-mllvm");
2550e73ff4e6Svisa           CmdArgs.push_back("-fix-loongson2f-btb");
2551e73ff4e6Svisa           continue;
2552e73ff4e6Svisa         }
2553e5dd7070Spatrick 
2554e5dd7070Spatrick         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2555e5dd7070Spatrick                                 .Case("-mips1", "+mips1")
2556e5dd7070Spatrick                                 .Case("-mips2", "+mips2")
2557e5dd7070Spatrick                                 .Case("-mips3", "+mips3")
2558e5dd7070Spatrick                                 .Case("-mips4", "+mips4")
2559e5dd7070Spatrick                                 .Case("-mips5", "+mips5")
2560e5dd7070Spatrick                                 .Case("-mips32", "+mips32")
2561e5dd7070Spatrick                                 .Case("-mips32r2", "+mips32r2")
2562e5dd7070Spatrick                                 .Case("-mips32r3", "+mips32r3")
2563e5dd7070Spatrick                                 .Case("-mips32r5", "+mips32r5")
2564e5dd7070Spatrick                                 .Case("-mips32r6", "+mips32r6")
2565e5dd7070Spatrick                                 .Case("-mips64", "+mips64")
2566e5dd7070Spatrick                                 .Case("-mips64r2", "+mips64r2")
2567e5dd7070Spatrick                                 .Case("-mips64r3", "+mips64r3")
2568e5dd7070Spatrick                                 .Case("-mips64r5", "+mips64r5")
2569e5dd7070Spatrick                                 .Case("-mips64r6", "+mips64r6")
2570e5dd7070Spatrick                                 .Default(nullptr);
2571e5dd7070Spatrick         if (MipsTargetFeature)
2572e5dd7070Spatrick           continue;
2573e5dd7070Spatrick       }
2574e5dd7070Spatrick 
2575e5dd7070Spatrick       if (Value == "-force_cpusubtype_ALL") {
2576e5dd7070Spatrick         // Do nothing, this is the default and we don't support anything else.
2577e5dd7070Spatrick       } else if (Value == "-L") {
2578e5dd7070Spatrick         CmdArgs.push_back("-msave-temp-labels");
2579e5dd7070Spatrick       } else if (Value == "--fatal-warnings") {
2580e5dd7070Spatrick         CmdArgs.push_back("-massembler-fatal-warnings");
2581e5dd7070Spatrick       } else if (Value == "--no-warn" || Value == "-W") {
2582e5dd7070Spatrick         CmdArgs.push_back("-massembler-no-warn");
2583e5dd7070Spatrick       } else if (Value == "--noexecstack") {
2584e5dd7070Spatrick         UseNoExecStack = true;
2585e5dd7070Spatrick       } else if (Value.startswith("-compress-debug-sections") ||
2586e5dd7070Spatrick                  Value.startswith("--compress-debug-sections") ||
2587e5dd7070Spatrick                  Value == "-nocompress-debug-sections" ||
2588e5dd7070Spatrick                  Value == "--nocompress-debug-sections") {
2589e5dd7070Spatrick         CmdArgs.push_back(Value.data());
2590e5dd7070Spatrick       } else if (Value == "-mrelax-relocations=yes" ||
2591e5dd7070Spatrick                  Value == "--mrelax-relocations=yes") {
2592e5dd7070Spatrick         UseRelaxRelocations = true;
2593e5dd7070Spatrick       } else if (Value == "-mrelax-relocations=no" ||
2594e5dd7070Spatrick                  Value == "--mrelax-relocations=no") {
2595e5dd7070Spatrick         UseRelaxRelocations = false;
2596e5dd7070Spatrick       } else if (Value.startswith("-I")) {
2597e5dd7070Spatrick         CmdArgs.push_back(Value.data());
2598e5dd7070Spatrick         // We need to consume the next argument if the current arg is a plain
2599e5dd7070Spatrick         // -I. The next arg will be the include directory.
2600e5dd7070Spatrick         if (Value == "-I")
2601e5dd7070Spatrick           TakeNextArg = true;
2602e5dd7070Spatrick       } else if (Value.startswith("-gdwarf-")) {
2603e5dd7070Spatrick         // "-gdwarf-N" options are not cc1as options.
2604e5dd7070Spatrick         unsigned DwarfVersion = DwarfVersionNum(Value);
2605e5dd7070Spatrick         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2606e5dd7070Spatrick           CmdArgs.push_back(Value.data());
2607e5dd7070Spatrick         } else {
2608e5dd7070Spatrick           RenderDebugEnablingArgs(Args, CmdArgs,
2609a0747c9fSpatrick                                   codegenoptions::DebugInfoConstructor,
2610e5dd7070Spatrick                                   DwarfVersion, llvm::DebuggerKind::Default);
2611e5dd7070Spatrick         }
2612e5dd7070Spatrick       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2613e5dd7070Spatrick                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2614e5dd7070Spatrick         // Do nothing, we'll validate it later.
2615e5dd7070Spatrick       } else if (Value == "-defsym") {
2616e5dd7070Spatrick           if (A->getNumValues() != 2) {
2617e5dd7070Spatrick             D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2618e5dd7070Spatrick             break;
2619e5dd7070Spatrick           }
2620e5dd7070Spatrick           const char *S = A->getValue(1);
2621e5dd7070Spatrick           auto Pair = StringRef(S).split('=');
2622e5dd7070Spatrick           auto Sym = Pair.first;
2623e5dd7070Spatrick           auto SVal = Pair.second;
2624e5dd7070Spatrick 
2625e5dd7070Spatrick           if (Sym.empty() || SVal.empty()) {
2626e5dd7070Spatrick             D.Diag(diag::err_drv_defsym_invalid_format) << S;
2627e5dd7070Spatrick             break;
2628e5dd7070Spatrick           }
2629e5dd7070Spatrick           int64_t IVal;
2630e5dd7070Spatrick           if (SVal.getAsInteger(0, IVal)) {
2631e5dd7070Spatrick             D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2632e5dd7070Spatrick             break;
2633e5dd7070Spatrick           }
2634e5dd7070Spatrick           CmdArgs.push_back(Value.data());
2635e5dd7070Spatrick           TakeNextArg = true;
2636e5dd7070Spatrick       } else if (Value == "-fdebug-compilation-dir") {
2637e5dd7070Spatrick         CmdArgs.push_back("-fdebug-compilation-dir");
2638e5dd7070Spatrick         TakeNextArg = true;
2639e5dd7070Spatrick       } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2640e5dd7070Spatrick         // The flag is a -Wa / -Xassembler argument and Options doesn't
2641e5dd7070Spatrick         // parse the argument, so this isn't automatically aliased to
2642e5dd7070Spatrick         // -fdebug-compilation-dir (without '=') here.
2643e5dd7070Spatrick         CmdArgs.push_back("-fdebug-compilation-dir");
2644e5dd7070Spatrick         CmdArgs.push_back(Value.data());
2645a0747c9fSpatrick       } else if (Value == "--version") {
2646a0747c9fSpatrick         D.PrintVersion(C, llvm::outs());
2647e5dd7070Spatrick       } else {
2648e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_option_argument)
26497a9b00ceSrobert             << A->getSpelling() << Value;
2650e5dd7070Spatrick       }
2651e5dd7070Spatrick     }
2652e5dd7070Spatrick   }
2653a0747c9fSpatrick   if (ImplicitIt.size())
2654a0747c9fSpatrick     AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
26557a9b00ceSrobert   if (!UseRelaxRelocations)
26567a9b00ceSrobert     CmdArgs.push_back("-mrelax-relocations=no");
2657e5dd7070Spatrick   if (UseNoExecStack)
2658e5dd7070Spatrick     CmdArgs.push_back("-mnoexecstack");
2659e5dd7070Spatrick   if (MipsTargetFeature != nullptr) {
2660e5dd7070Spatrick     CmdArgs.push_back("-target-feature");
2661e5dd7070Spatrick     CmdArgs.push_back(MipsTargetFeature);
2662e5dd7070Spatrick   }
2663e5dd7070Spatrick 
2664e5dd7070Spatrick   // forward -fembed-bitcode to assmebler
2665e5dd7070Spatrick   if (C.getDriver().embedBitcodeEnabled() ||
2666e5dd7070Spatrick       C.getDriver().embedBitcodeMarkerOnly())
2667e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
26687a9b00ceSrobert 
26697a9b00ceSrobert   if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
26707a9b00ceSrobert     CmdArgs.push_back("-as-secure-log-file");
26717a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
26727a9b00ceSrobert   }
2673e5dd7070Spatrick }
2674e5dd7070Spatrick 
RenderFloatingPointOptions(const ToolChain & TC,const Driver & D,bool OFastEnabled,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)2675e5dd7070Spatrick static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2676e5dd7070Spatrick                                        bool OFastEnabled, const ArgList &Args,
2677adae0cfdSpatrick                                        ArgStringList &CmdArgs,
2678adae0cfdSpatrick                                        const JobAction &JA) {
2679e5dd7070Spatrick   // Handle various floating point optimization flags, mapping them to the
2680e5dd7070Spatrick   // appropriate LLVM code generation flags. This is complicated by several
2681e5dd7070Spatrick   // "umbrella" flags, so we do this by stepping through the flags incrementally
2682e5dd7070Spatrick   // adjusting what we think is enabled/disabled, then at the end setting the
2683e5dd7070Spatrick   // LLVM flags based on the final state.
2684e5dd7070Spatrick   bool HonorINFs = true;
2685e5dd7070Spatrick   bool HonorNaNs = true;
26867a9b00ceSrobert   bool ApproxFunc = false;
2687e5dd7070Spatrick   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2688e5dd7070Spatrick   bool MathErrno = TC.IsMathErrnoDefault();
2689e5dd7070Spatrick   bool AssociativeMath = false;
2690e5dd7070Spatrick   bool ReciprocalMath = false;
2691e5dd7070Spatrick   bool SignedZeros = true;
2692e5dd7070Spatrick   bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2693e5dd7070Spatrick   bool TrappingMathPresent = false; // Is trapping-math in args, and not
2694e5dd7070Spatrick                                     // overriden by ffp-exception-behavior?
2695e5dd7070Spatrick   bool RoundingFPMath = false;
2696e5dd7070Spatrick   bool RoundingMathPresent = false; // Is rounding-math in args?
2697e5dd7070Spatrick   // -ffp-model values: strict, fast, precise
2698e5dd7070Spatrick   StringRef FPModel = "";
2699e5dd7070Spatrick   // -ffp-exception-behavior options: strict, maytrap, ignore
2700e5dd7070Spatrick   StringRef FPExceptionBehavior = "";
27017a9b00ceSrobert   // -ffp-eval-method options: double, extended, source
27027a9b00ceSrobert   StringRef FPEvalMethod = "";
2703adae0cfdSpatrick   const llvm::DenormalMode DefaultDenormalFPMath =
2704adae0cfdSpatrick       TC.getDefaultDenormalModeForType(Args, JA);
2705adae0cfdSpatrick   const llvm::DenormalMode DefaultDenormalFP32Math =
2706adae0cfdSpatrick       TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2707adae0cfdSpatrick 
2708adae0cfdSpatrick   llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2709adae0cfdSpatrick   llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
27107a9b00ceSrobert   // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
27117a9b00ceSrobert   // If one wasn't given by the user, don't pass it here.
27127a9b00ceSrobert   StringRef FPContract;
27137a9b00ceSrobert   StringRef LastSeenFfpContractOption;
27147a9b00ceSrobert   bool SeenUnsafeMathModeOption = false;
27157a9b00ceSrobert   if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
27167a9b00ceSrobert       !JA.isOffloading(Action::OFK_HIP))
27177a9b00ceSrobert     FPContract = "on";
2718e5dd7070Spatrick   bool StrictFPModel = false;
27197a9b00ceSrobert   StringRef Float16ExcessPrecision = "";
2720adae0cfdSpatrick 
2721e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2722e5dd7070Spatrick     CmdArgs.push_back("-mlimit-float-precision");
2723e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
2724e5dd7070Spatrick   }
2725e5dd7070Spatrick 
2726e5dd7070Spatrick   for (const Arg *A : Args) {
2727e5dd7070Spatrick     auto optID = A->getOption().getID();
2728e5dd7070Spatrick     bool PreciseFPModel = false;
2729e5dd7070Spatrick     switch (optID) {
2730e5dd7070Spatrick     default:
2731e5dd7070Spatrick       break;
2732e5dd7070Spatrick     case options::OPT_ffp_model_EQ: {
2733e5dd7070Spatrick       // If -ffp-model= is seen, reset to fno-fast-math
2734e5dd7070Spatrick       HonorINFs = true;
2735e5dd7070Spatrick       HonorNaNs = true;
27367a9b00ceSrobert       ApproxFunc = false;
2737e5dd7070Spatrick       // Turning *off* -ffast-math restores the toolchain default.
2738e5dd7070Spatrick       MathErrno = TC.IsMathErrnoDefault();
2739e5dd7070Spatrick       AssociativeMath = false;
2740e5dd7070Spatrick       ReciprocalMath = false;
2741e5dd7070Spatrick       SignedZeros = true;
2742e5dd7070Spatrick       // -fno_fast_math restores default denormal and fpcontract handling
27437a9b00ceSrobert       FPContract = "on";
2744adae0cfdSpatrick       DenormalFPMath = llvm::DenormalMode::getIEEE();
2745adae0cfdSpatrick 
2746adae0cfdSpatrick       // FIXME: The target may have picked a non-IEEE default mode here based on
2747adae0cfdSpatrick       // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2748adae0cfdSpatrick       DenormalFP32Math = llvm::DenormalMode::getIEEE();
2749adae0cfdSpatrick 
2750e5dd7070Spatrick       StringRef Val = A->getValue();
2751e5dd7070Spatrick       if (OFastEnabled && !Val.equals("fast")) {
2752e5dd7070Spatrick           // Only -ffp-model=fast is compatible with OFast, ignore.
2753e5dd7070Spatrick         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2754e5dd7070Spatrick           << Args.MakeArgString("-ffp-model=" + Val)
2755e5dd7070Spatrick           << "-Ofast";
2756e5dd7070Spatrick         break;
2757e5dd7070Spatrick       }
2758e5dd7070Spatrick       StrictFPModel = false;
2759e5dd7070Spatrick       PreciseFPModel = true;
2760e5dd7070Spatrick       // ffp-model= is a Driver option, it is entirely rewritten into more
2761e5dd7070Spatrick       // granular options before being passed into cc1.
2762e5dd7070Spatrick       // Use the gcc option in the switch below.
27637a9b00ceSrobert       if (!FPModel.empty() && !FPModel.equals(Val))
2764e5dd7070Spatrick         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2765e5dd7070Spatrick             << Args.MakeArgString("-ffp-model=" + FPModel)
2766e5dd7070Spatrick             << Args.MakeArgString("-ffp-model=" + Val);
2767e5dd7070Spatrick       if (Val.equals("fast")) {
2768e5dd7070Spatrick         optID = options::OPT_ffast_math;
2769e5dd7070Spatrick         FPModel = Val;
2770e5dd7070Spatrick         FPContract = "fast";
2771e5dd7070Spatrick       } else if (Val.equals("precise")) {
2772e5dd7070Spatrick         optID = options::OPT_ffp_contract;
2773e5dd7070Spatrick         FPModel = Val;
27747a9b00ceSrobert         FPContract = "on";
2775e5dd7070Spatrick         PreciseFPModel = true;
2776e5dd7070Spatrick       } else if (Val.equals("strict")) {
2777e5dd7070Spatrick         StrictFPModel = true;
2778e5dd7070Spatrick         optID = options::OPT_frounding_math;
2779e5dd7070Spatrick         FPExceptionBehavior = "strict";
2780e5dd7070Spatrick         FPModel = Val;
2781adae0cfdSpatrick         FPContract = "off";
2782e5dd7070Spatrick         TrappingMath = true;
2783e5dd7070Spatrick       } else
2784e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_option_argument)
27857a9b00ceSrobert             << A->getSpelling() << Val;
2786e5dd7070Spatrick       break;
2787e5dd7070Spatrick       }
2788e5dd7070Spatrick     }
2789e5dd7070Spatrick 
2790e5dd7070Spatrick     switch (optID) {
2791e5dd7070Spatrick     // If this isn't an FP option skip the claim below
2792e5dd7070Spatrick     default: continue;
2793e5dd7070Spatrick 
2794e5dd7070Spatrick     // Options controlling individual features
2795e5dd7070Spatrick     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2796e5dd7070Spatrick     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2797e5dd7070Spatrick     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2798e5dd7070Spatrick     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
27997a9b00ceSrobert     case options::OPT_fapprox_func:         ApproxFunc = true;        break;
28007a9b00ceSrobert     case options::OPT_fno_approx_func:      ApproxFunc = false;       break;
2801e5dd7070Spatrick     case options::OPT_fmath_errno:          MathErrno = true;         break;
2802e5dd7070Spatrick     case options::OPT_fno_math_errno:       MathErrno = false;        break;
2803e5dd7070Spatrick     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2804e5dd7070Spatrick     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2805e5dd7070Spatrick     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2806e5dd7070Spatrick     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2807e5dd7070Spatrick     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2808e5dd7070Spatrick     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2809e5dd7070Spatrick     case options::OPT_ftrapping_math:
2810e5dd7070Spatrick       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2811e5dd7070Spatrick           !FPExceptionBehavior.equals("strict"))
2812e5dd7070Spatrick         // Warn that previous value of option is overridden.
2813e5dd7070Spatrick         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2814e5dd7070Spatrick           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2815e5dd7070Spatrick           << "-ftrapping-math";
2816e5dd7070Spatrick       TrappingMath = true;
2817e5dd7070Spatrick       TrappingMathPresent = true;
2818e5dd7070Spatrick       FPExceptionBehavior = "strict";
2819e5dd7070Spatrick       break;
2820e5dd7070Spatrick     case options::OPT_fno_trapping_math:
2821e5dd7070Spatrick       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2822e5dd7070Spatrick           !FPExceptionBehavior.equals("ignore"))
2823e5dd7070Spatrick         // Warn that previous value of option is overridden.
2824e5dd7070Spatrick         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2825e5dd7070Spatrick           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2826e5dd7070Spatrick           << "-fno-trapping-math";
2827e5dd7070Spatrick       TrappingMath = false;
2828e5dd7070Spatrick       TrappingMathPresent = true;
2829e5dd7070Spatrick       FPExceptionBehavior = "ignore";
2830e5dd7070Spatrick       break;
2831e5dd7070Spatrick 
2832e5dd7070Spatrick     case options::OPT_frounding_math:
2833e5dd7070Spatrick       RoundingFPMath = true;
2834e5dd7070Spatrick       RoundingMathPresent = true;
2835e5dd7070Spatrick       break;
2836e5dd7070Spatrick 
2837e5dd7070Spatrick     case options::OPT_fno_rounding_math:
2838e5dd7070Spatrick       RoundingFPMath = false;
2839e5dd7070Spatrick       RoundingMathPresent = false;
2840e5dd7070Spatrick       break;
2841e5dd7070Spatrick 
2842e5dd7070Spatrick     case options::OPT_fdenormal_fp_math_EQ:
2843adae0cfdSpatrick       DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
28447a9b00ceSrobert       DenormalFP32Math = DenormalFPMath;
2845adae0cfdSpatrick       if (!DenormalFPMath.isValid()) {
2846adae0cfdSpatrick         D.Diag(diag::err_drv_invalid_value)
2847adae0cfdSpatrick             << A->getAsString(Args) << A->getValue();
2848adae0cfdSpatrick       }
2849adae0cfdSpatrick       break;
2850adae0cfdSpatrick 
2851adae0cfdSpatrick     case options::OPT_fdenormal_fp_math_f32_EQ:
2852adae0cfdSpatrick       DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2853adae0cfdSpatrick       if (!DenormalFP32Math.isValid()) {
2854adae0cfdSpatrick         D.Diag(diag::err_drv_invalid_value)
2855adae0cfdSpatrick             << A->getAsString(Args) << A->getValue();
2856adae0cfdSpatrick       }
2857e5dd7070Spatrick       break;
2858e5dd7070Spatrick 
2859e5dd7070Spatrick     // Validate and pass through -ffp-contract option.
2860e5dd7070Spatrick     case options::OPT_ffp_contract: {
2861e5dd7070Spatrick       StringRef Val = A->getValue();
2862e5dd7070Spatrick       if (PreciseFPModel) {
28637a9b00ceSrobert         // -ffp-model=precise enables ffp-contract=on.
28647a9b00ceSrobert         // -ffp-model=precise sets PreciseFPModel to on and Val to
28657a9b00ceSrobert         // "precise". FPContract is set.
2866e5dd7070Spatrick         ;
28677a9b00ceSrobert       } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off")) {
2868e5dd7070Spatrick         FPContract = Val;
28697a9b00ceSrobert         LastSeenFfpContractOption = Val;
28707a9b00ceSrobert       } else
2871e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_option_argument)
28727a9b00ceSrobert             << A->getSpelling() << Val;
2873e5dd7070Spatrick       break;
2874e5dd7070Spatrick     }
2875e5dd7070Spatrick 
2876e5dd7070Spatrick     // Validate and pass through -ffp-model option.
2877e5dd7070Spatrick     case options::OPT_ffp_model_EQ:
2878e5dd7070Spatrick       // This should only occur in the error case
2879e5dd7070Spatrick       // since the optID has been replaced by a more granular
2880e5dd7070Spatrick       // floating point option.
2881e5dd7070Spatrick       break;
2882e5dd7070Spatrick 
2883e5dd7070Spatrick     // Validate and pass through -ffp-exception-behavior option.
2884e5dd7070Spatrick     case options::OPT_ffp_exception_behavior_EQ: {
2885e5dd7070Spatrick       StringRef Val = A->getValue();
2886e5dd7070Spatrick       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2887e5dd7070Spatrick           !FPExceptionBehavior.equals(Val))
2888e5dd7070Spatrick         // Warn that previous value of option is overridden.
2889e5dd7070Spatrick         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2890e5dd7070Spatrick           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2891e5dd7070Spatrick           << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2892e5dd7070Spatrick       TrappingMath = TrappingMathPresent = false;
2893e5dd7070Spatrick       if (Val.equals("ignore") || Val.equals("maytrap"))
2894e5dd7070Spatrick         FPExceptionBehavior = Val;
2895e5dd7070Spatrick       else if (Val.equals("strict")) {
2896e5dd7070Spatrick         FPExceptionBehavior = Val;
2897e5dd7070Spatrick         TrappingMath = TrappingMathPresent = true;
2898e5dd7070Spatrick       } else
2899e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_option_argument)
29007a9b00ceSrobert             << A->getSpelling() << Val;
2901e5dd7070Spatrick       break;
2902e5dd7070Spatrick     }
2903e5dd7070Spatrick 
29047a9b00ceSrobert     // Validate and pass through -ffp-eval-method option.
29057a9b00ceSrobert     case options::OPT_ffp_eval_method_EQ: {
29067a9b00ceSrobert       StringRef Val = A->getValue();
29077a9b00ceSrobert       if (Val.equals("double") || Val.equals("extended") ||
29087a9b00ceSrobert           Val.equals("source"))
29097a9b00ceSrobert         FPEvalMethod = Val;
29107a9b00ceSrobert       else
29117a9b00ceSrobert         D.Diag(diag::err_drv_unsupported_option_argument)
29127a9b00ceSrobert             << A->getSpelling() << Val;
29137a9b00ceSrobert       break;
29147a9b00ceSrobert     }
29157a9b00ceSrobert 
29167a9b00ceSrobert     case options::OPT_fexcess_precision_EQ: {
29177a9b00ceSrobert       StringRef Val = A->getValue();
29187a9b00ceSrobert       const llvm::Triple::ArchType Arch = TC.getArch();
29197a9b00ceSrobert       if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
29207a9b00ceSrobert         if (Val.equals("standard") || Val.equals("fast"))
29217a9b00ceSrobert           Float16ExcessPrecision = Val;
29227a9b00ceSrobert         // To make it GCC compatible, allow the value of "16" which
29237a9b00ceSrobert         // means disable excess precision, the same meaning than clang's
29247a9b00ceSrobert         // equivalent value "none".
29257a9b00ceSrobert         else if (Val.equals("16"))
29267a9b00ceSrobert           Float16ExcessPrecision = "none";
29277a9b00ceSrobert         else
29287a9b00ceSrobert           D.Diag(diag::err_drv_unsupported_option_argument)
29297a9b00ceSrobert               << A->getSpelling() << Val;
29307a9b00ceSrobert       } else {
29317a9b00ceSrobert         if (!(Val.equals("standard") || Val.equals("fast")))
29327a9b00ceSrobert           D.Diag(diag::err_drv_unsupported_option_argument)
29337a9b00ceSrobert               << A->getSpelling() << Val;
29347a9b00ceSrobert       }
29357a9b00ceSrobert       break;
29367a9b00ceSrobert     }
2937e5dd7070Spatrick     case options::OPT_ffinite_math_only:
2938e5dd7070Spatrick       HonorINFs = false;
2939e5dd7070Spatrick       HonorNaNs = false;
2940e5dd7070Spatrick       break;
2941e5dd7070Spatrick     case options::OPT_fno_finite_math_only:
2942e5dd7070Spatrick       HonorINFs = true;
2943e5dd7070Spatrick       HonorNaNs = true;
2944e5dd7070Spatrick       break;
2945e5dd7070Spatrick 
2946e5dd7070Spatrick     case options::OPT_funsafe_math_optimizations:
2947e5dd7070Spatrick       AssociativeMath = true;
2948e5dd7070Spatrick       ReciprocalMath = true;
2949e5dd7070Spatrick       SignedZeros = false;
29507a9b00ceSrobert       ApproxFunc = true;
2951e5dd7070Spatrick       TrappingMath = false;
2952e5dd7070Spatrick       FPExceptionBehavior = "";
29537a9b00ceSrobert       FPContract = "fast";
29547a9b00ceSrobert       SeenUnsafeMathModeOption = true;
2955e5dd7070Spatrick       break;
2956e5dd7070Spatrick     case options::OPT_fno_unsafe_math_optimizations:
2957e5dd7070Spatrick       AssociativeMath = false;
2958e5dd7070Spatrick       ReciprocalMath = false;
2959e5dd7070Spatrick       SignedZeros = true;
29607a9b00ceSrobert       ApproxFunc = false;
2961e5dd7070Spatrick       TrappingMath = true;
2962e5dd7070Spatrick       FPExceptionBehavior = "strict";
2963adae0cfdSpatrick 
2964adae0cfdSpatrick       // The target may have opted to flush by default, so force IEEE.
2965adae0cfdSpatrick       DenormalFPMath = llvm::DenormalMode::getIEEE();
2966adae0cfdSpatrick       DenormalFP32Math = llvm::DenormalMode::getIEEE();
29677a9b00ceSrobert       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
29687a9b00ceSrobert           !JA.isOffloading(Action::OFK_HIP)) {
29697a9b00ceSrobert         if (LastSeenFfpContractOption != "") {
29707a9b00ceSrobert           FPContract = LastSeenFfpContractOption;
29717a9b00ceSrobert         } else if (SeenUnsafeMathModeOption)
29727a9b00ceSrobert           FPContract = "on";
29737a9b00ceSrobert       }
2974e5dd7070Spatrick       break;
2975e5dd7070Spatrick 
2976e5dd7070Spatrick     case options::OPT_Ofast:
2977e5dd7070Spatrick       // If -Ofast is the optimization level, then -ffast-math should be enabled
2978e5dd7070Spatrick       if (!OFastEnabled)
2979e5dd7070Spatrick         continue;
29807a9b00ceSrobert       [[fallthrough]];
2981e5dd7070Spatrick     case options::OPT_ffast_math:
2982e5dd7070Spatrick       HonorINFs = false;
2983e5dd7070Spatrick       HonorNaNs = false;
2984e5dd7070Spatrick       MathErrno = false;
2985e5dd7070Spatrick       AssociativeMath = true;
2986e5dd7070Spatrick       ReciprocalMath = true;
29877a9b00ceSrobert       ApproxFunc = true;
2988e5dd7070Spatrick       SignedZeros = false;
2989e5dd7070Spatrick       TrappingMath = false;
2990e5dd7070Spatrick       RoundingFPMath = false;
29917a9b00ceSrobert       FPExceptionBehavior = "";
2992e5dd7070Spatrick       // If fast-math is set then set the fp-contract mode to fast.
2993e5dd7070Spatrick       FPContract = "fast";
29947a9b00ceSrobert       SeenUnsafeMathModeOption = true;
2995e5dd7070Spatrick       break;
2996e5dd7070Spatrick     case options::OPT_fno_fast_math:
2997e5dd7070Spatrick       HonorINFs = true;
2998e5dd7070Spatrick       HonorNaNs = true;
2999e5dd7070Spatrick       // Turning on -ffast-math (with either flag) removes the need for
3000e5dd7070Spatrick       // MathErrno. However, turning *off* -ffast-math merely restores the
3001e5dd7070Spatrick       // toolchain default (which may be false).
3002e5dd7070Spatrick       MathErrno = TC.IsMathErrnoDefault();
3003e5dd7070Spatrick       AssociativeMath = false;
3004e5dd7070Spatrick       ReciprocalMath = false;
30057a9b00ceSrobert       ApproxFunc = false;
3006e5dd7070Spatrick       SignedZeros = true;
3007e5dd7070Spatrick       // -fno_fast_math restores default denormal and fpcontract handling
3008adae0cfdSpatrick       DenormalFPMath = DefaultDenormalFPMath;
3009adae0cfdSpatrick       DenormalFP32Math = llvm::DenormalMode::getIEEE();
30107a9b00ceSrobert       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
30117a9b00ceSrobert           !JA.isOffloading(Action::OFK_HIP)) {
30127a9b00ceSrobert         if (LastSeenFfpContractOption != "") {
30137a9b00ceSrobert           FPContract = LastSeenFfpContractOption;
30147a9b00ceSrobert         } else if (SeenUnsafeMathModeOption)
30157a9b00ceSrobert           FPContract = "on";
30167a9b00ceSrobert       }
3017e5dd7070Spatrick       break;
3018e5dd7070Spatrick     }
3019e5dd7070Spatrick     if (StrictFPModel) {
3020e5dd7070Spatrick       // If -ffp-model=strict has been specified on command line but
3021e5dd7070Spatrick       // subsequent options conflict then emit warning diagnostic.
30227a9b00ceSrobert       if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
30237a9b00ceSrobert           SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3024adae0cfdSpatrick           DenormalFPMath == llvm::DenormalMode::getIEEE() &&
30257a9b00ceSrobert           DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
30267a9b00ceSrobert           FPContract.equals("off"))
3027e5dd7070Spatrick         // OK: Current Arg doesn't conflict with -ffp-model=strict
3028e5dd7070Spatrick         ;
3029e5dd7070Spatrick       else {
3030e5dd7070Spatrick         StrictFPModel = false;
3031e5dd7070Spatrick         FPModel = "";
30327a9b00ceSrobert         auto RHS = (A->getNumValues() == 0)
30337a9b00ceSrobert                        ? A->getSpelling()
30347a9b00ceSrobert                        : Args.MakeArgString(A->getSpelling() + A->getValue());
30357a9b00ceSrobert         if (RHS != "-ffp-model=strict")
3036e5dd7070Spatrick           D.Diag(clang::diag::warn_drv_overriding_flag_option)
30377a9b00ceSrobert               << "-ffp-model=strict" << RHS;
3038e5dd7070Spatrick       }
3039e5dd7070Spatrick     }
3040e5dd7070Spatrick 
3041e5dd7070Spatrick     // If we handled this option claim it
3042e5dd7070Spatrick     A->claim();
3043e5dd7070Spatrick   }
3044e5dd7070Spatrick 
3045e5dd7070Spatrick   if (!HonorINFs)
3046e5dd7070Spatrick     CmdArgs.push_back("-menable-no-infs");
3047e5dd7070Spatrick 
3048e5dd7070Spatrick   if (!HonorNaNs)
3049e5dd7070Spatrick     CmdArgs.push_back("-menable-no-nans");
3050e5dd7070Spatrick 
30517a9b00ceSrobert   if (ApproxFunc)
30527a9b00ceSrobert     CmdArgs.push_back("-fapprox-func");
30537a9b00ceSrobert 
3054e5dd7070Spatrick   if (MathErrno)
3055e5dd7070Spatrick     CmdArgs.push_back("-fmath-errno");
3056e5dd7070Spatrick 
30577a9b00ceSrobert  if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3058e5dd7070Spatrick      !TrappingMath)
30597a9b00ceSrobert     CmdArgs.push_back("-funsafe-math-optimizations");
3060e5dd7070Spatrick 
3061e5dd7070Spatrick   if (!SignedZeros)
3062e5dd7070Spatrick     CmdArgs.push_back("-fno-signed-zeros");
3063e5dd7070Spatrick 
3064e5dd7070Spatrick   if (AssociativeMath && !SignedZeros && !TrappingMath)
3065e5dd7070Spatrick     CmdArgs.push_back("-mreassociate");
3066e5dd7070Spatrick 
3067e5dd7070Spatrick   if (ReciprocalMath)
3068e5dd7070Spatrick     CmdArgs.push_back("-freciprocal-math");
3069e5dd7070Spatrick 
3070e5dd7070Spatrick   if (TrappingMath) {
3071e5dd7070Spatrick     // FP Exception Behavior is also set to strict
3072e5dd7070Spatrick     assert(FPExceptionBehavior.equals("strict"));
3073a0747c9fSpatrick   }
3074e5dd7070Spatrick 
3075adae0cfdSpatrick   // The default is IEEE.
3076adae0cfdSpatrick   if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3077adae0cfdSpatrick     llvm::SmallString<64> DenormFlag;
3078adae0cfdSpatrick     llvm::raw_svector_ostream ArgStr(DenormFlag);
3079adae0cfdSpatrick     ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3080adae0cfdSpatrick     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3081adae0cfdSpatrick   }
3082adae0cfdSpatrick 
3083adae0cfdSpatrick   // Add f32 specific denormal mode flag if it's different.
3084adae0cfdSpatrick   if (DenormalFP32Math != DenormalFPMath) {
3085adae0cfdSpatrick     llvm::SmallString<64> DenormFlag;
3086adae0cfdSpatrick     llvm::raw_svector_ostream ArgStr(DenormFlag);
3087adae0cfdSpatrick     ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3088adae0cfdSpatrick     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3089adae0cfdSpatrick   }
3090e5dd7070Spatrick 
3091e5dd7070Spatrick   if (!FPContract.empty())
3092e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3093e5dd7070Spatrick 
3094e5dd7070Spatrick   if (!RoundingFPMath)
3095e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3096e5dd7070Spatrick 
3097e5dd7070Spatrick   if (RoundingFPMath && RoundingMathPresent)
3098e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3099e5dd7070Spatrick 
3100e5dd7070Spatrick   if (!FPExceptionBehavior.empty())
3101e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3102e5dd7070Spatrick                       FPExceptionBehavior));
3103e5dd7070Spatrick 
31047a9b00ceSrobert   if (!FPEvalMethod.empty())
31057a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
31067a9b00ceSrobert 
31077a9b00ceSrobert   if (!Float16ExcessPrecision.empty())
31087a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
31097a9b00ceSrobert                                          Float16ExcessPrecision));
31107a9b00ceSrobert 
3111e5dd7070Spatrick   ParseMRecip(D, Args, CmdArgs);
3112e5dd7070Spatrick 
3113e5dd7070Spatrick   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3114e5dd7070Spatrick   // individual features enabled by -ffast-math instead of the option itself as
3115e5dd7070Spatrick   // that's consistent with gcc's behaviour.
31167a9b00ceSrobert   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3117e5dd7070Spatrick       ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3118e5dd7070Spatrick     CmdArgs.push_back("-ffast-math");
3119e5dd7070Spatrick     if (FPModel.equals("fast")) {
3120e5dd7070Spatrick       if (FPContract.equals("fast"))
3121e5dd7070Spatrick         // All set, do nothing.
3122e5dd7070Spatrick         ;
3123e5dd7070Spatrick       else if (FPContract.empty())
3124e5dd7070Spatrick         // Enable -ffp-contract=fast
3125e5dd7070Spatrick         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3126e5dd7070Spatrick       else
3127e5dd7070Spatrick         D.Diag(clang::diag::warn_drv_overriding_flag_option)
3128e5dd7070Spatrick           << "-ffp-model=fast"
3129e5dd7070Spatrick           << Args.MakeArgString("-ffp-contract=" + FPContract);
3130e5dd7070Spatrick     }
3131e5dd7070Spatrick   }
3132e5dd7070Spatrick 
3133e5dd7070Spatrick   // Handle __FINITE_MATH_ONLY__ similarly.
3134e5dd7070Spatrick   if (!HonorINFs && !HonorNaNs)
3135e5dd7070Spatrick     CmdArgs.push_back("-ffinite-math-only");
3136e5dd7070Spatrick 
3137e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3138e5dd7070Spatrick     CmdArgs.push_back("-mfpmath");
3139e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
3140e5dd7070Spatrick   }
3141e5dd7070Spatrick 
3142e5dd7070Spatrick   // Disable a codegen optimization for floating-point casts.
3143e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3144e5dd7070Spatrick                    options::OPT_fstrict_float_cast_overflow, false))
3145e5dd7070Spatrick     CmdArgs.push_back("-fno-strict-float-cast-overflow");
3146e5dd7070Spatrick }
3147e5dd7070Spatrick 
RenderAnalyzerOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input)3148e5dd7070Spatrick static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3149e5dd7070Spatrick                                   const llvm::Triple &Triple,
3150e5dd7070Spatrick                                   const InputInfo &Input) {
3151e5dd7070Spatrick   // Add default argument set.
3152e5dd7070Spatrick   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3153e5dd7070Spatrick     CmdArgs.push_back("-analyzer-checker=core");
3154e5dd7070Spatrick     CmdArgs.push_back("-analyzer-checker=apiModeling");
3155e5dd7070Spatrick 
3156e5dd7070Spatrick     if (!Triple.isWindowsMSVCEnvironment()) {
3157e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=unix");
3158e5dd7070Spatrick     } else {
3159e5dd7070Spatrick       // Enable "unix" checkers that also work on Windows.
3160e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=unix.API");
3161e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3162e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3163e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3164e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3165e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3166e5dd7070Spatrick     }
3167e5dd7070Spatrick 
31687a9b00ceSrobert     // Disable some unix checkers for PS4/PS5.
31697a9b00ceSrobert     if (Triple.isPS()) {
3170e5dd7070Spatrick       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3171e5dd7070Spatrick       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3172e5dd7070Spatrick     }
3173e5dd7070Spatrick 
3174e5dd7070Spatrick     if (Triple.isOSDarwin()) {
3175e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=osx");
3176e5dd7070Spatrick       CmdArgs.push_back(
3177e5dd7070Spatrick           "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3178e5dd7070Spatrick     }
3179e5dd7070Spatrick     else if (Triple.isOSFuchsia())
3180e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=fuchsia");
3181e5dd7070Spatrick 
3182e5dd7070Spatrick     CmdArgs.push_back("-analyzer-checker=deadcode");
3183e5dd7070Spatrick 
3184e5dd7070Spatrick     if (types::isCXX(Input.getType()))
3185e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=cplusplus");
3186e5dd7070Spatrick 
31877a9b00ceSrobert     if (!Triple.isPS()) {
3188e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3189e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3190e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3191e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3192e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3193e5dd7070Spatrick       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3194e5dd7070Spatrick     }
3195e5dd7070Spatrick 
3196e5dd7070Spatrick     // Default nullability checks.
3197e5dd7070Spatrick     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3198e5dd7070Spatrick     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3199e5dd7070Spatrick   }
3200e5dd7070Spatrick 
3201e5dd7070Spatrick   // Set the output format. The default is plist, for (lame) historical reasons.
3202e5dd7070Spatrick   CmdArgs.push_back("-analyzer-output");
3203e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3204e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
3205e5dd7070Spatrick   else
3206e5dd7070Spatrick     CmdArgs.push_back("plist");
3207e5dd7070Spatrick 
3208e5dd7070Spatrick   // Disable the presentation of standard compiler warnings when using
3209e5dd7070Spatrick   // --analyze.  We only want to show static analyzer diagnostics or frontend
3210e5dd7070Spatrick   // errors.
3211e5dd7070Spatrick   CmdArgs.push_back("-w");
3212e5dd7070Spatrick 
3213e5dd7070Spatrick   // Add -Xanalyzer arguments when running as analyzer.
3214e5dd7070Spatrick   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3215e5dd7070Spatrick }
3216e5dd7070Spatrick 
isValidSymbolName(StringRef S)32177a9b00ceSrobert static bool isValidSymbolName(StringRef S) {
32187a9b00ceSrobert   if (S.empty())
32197a9b00ceSrobert     return false;
32207a9b00ceSrobert 
32217a9b00ceSrobert   if (std::isdigit(S[0]))
32227a9b00ceSrobert     return false;
32237a9b00ceSrobert 
32247a9b00ceSrobert   return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
32257a9b00ceSrobert }
32267a9b00ceSrobert 
RenderSSPOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext)3227a0747c9fSpatrick static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3228a0747c9fSpatrick                              const ArgList &Args, ArgStringList &CmdArgs,
3229a0747c9fSpatrick                              bool KernelOrKext) {
3230e5dd7070Spatrick   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3231e5dd7070Spatrick 
3232e5dd7070Spatrick   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3233e5dd7070Spatrick   // doesn't even have a stack!
3234e5dd7070Spatrick   if (EffectiveTriple.isNVPTX())
3235e5dd7070Spatrick     return;
3236e5dd7070Spatrick 
3237e5dd7070Spatrick   // -stack-protector=0 is default.
3238a0747c9fSpatrick   LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3239a0747c9fSpatrick   LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3240e5dd7070Spatrick       TC.GetDefaultStackProtectorLevel(KernelOrKext);
3241e5dd7070Spatrick 
3242e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3243e5dd7070Spatrick                                options::OPT_fstack_protector_all,
3244e5dd7070Spatrick                                options::OPT_fstack_protector_strong,
3245e5dd7070Spatrick                                options::OPT_fstack_protector)) {
3246e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fstack_protector))
3247e5dd7070Spatrick       StackProtectorLevel =
3248a0747c9fSpatrick           std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3249e5dd7070Spatrick     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3250e5dd7070Spatrick       StackProtectorLevel = LangOptions::SSPStrong;
3251e5dd7070Spatrick     else if (A->getOption().matches(options::OPT_fstack_protector_all))
3252e5dd7070Spatrick       StackProtectorLevel = LangOptions::SSPReq;
32537a9b00ceSrobert 
32547a9b00ceSrobert     if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
32557a9b00ceSrobert       D.Diag(diag::warn_drv_unsupported_option_for_target)
32567a9b00ceSrobert           << A->getSpelling() << EffectiveTriple.getTriple();
32577a9b00ceSrobert       StackProtectorLevel = DefaultStackProtectorLevel;
32587a9b00ceSrobert     }
3259e5dd7070Spatrick   } else {
3260e5dd7070Spatrick     StackProtectorLevel = DefaultStackProtectorLevel;
3261e5dd7070Spatrick   }
3262e5dd7070Spatrick 
3263e5dd7070Spatrick   if (StackProtectorLevel) {
3264e5dd7070Spatrick     CmdArgs.push_back("-stack-protector");
3265e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3266e5dd7070Spatrick   }
3267e5dd7070Spatrick 
3268e5dd7070Spatrick   // --param ssp-buffer-size=
3269e5dd7070Spatrick   for (const Arg *A : Args.filtered(options::OPT__param)) {
3270e5dd7070Spatrick     StringRef Str(A->getValue());
3271e5dd7070Spatrick     if (Str.startswith("ssp-buffer-size=")) {
3272e5dd7070Spatrick       if (StackProtectorLevel) {
3273e5dd7070Spatrick         CmdArgs.push_back("-stack-protector-buffer-size");
3274e5dd7070Spatrick         // FIXME: Verify the argument is a valid integer.
3275e5dd7070Spatrick         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3276e5dd7070Spatrick       }
3277e5dd7070Spatrick       A->claim();
3278e5dd7070Spatrick     }
3279e5dd7070Spatrick   }
3280a0747c9fSpatrick 
3281a0747c9fSpatrick   const std::string &TripleStr = EffectiveTriple.getTriple();
3282a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3283a0747c9fSpatrick     StringRef Value = A->getValue();
32847a9b00ceSrobert     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
32857a9b00ceSrobert         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3286a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
3287a0747c9fSpatrick           << A->getAsString(Args) << TripleStr;
32887a9b00ceSrobert     if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
32897a9b00ceSrobert          EffectiveTriple.isThumb()) &&
32907a9b00ceSrobert         Value != "tls" && Value != "global") {
3291a0747c9fSpatrick       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3292a0747c9fSpatrick           << A->getOption().getName() << Value << "tls global";
3293a0747c9fSpatrick       return;
3294a0747c9fSpatrick     }
32957a9b00ceSrobert     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
32967a9b00ceSrobert         Value == "tls") {
32977a9b00ceSrobert       if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
32987a9b00ceSrobert         D.Diag(diag::err_drv_ssp_missing_offset_argument)
32997a9b00ceSrobert             << A->getAsString(Args);
33007a9b00ceSrobert         return;
33017a9b00ceSrobert       }
33027a9b00ceSrobert       // Check whether the target subarch supports the hardware TLS register
33037a9b00ceSrobert       if (!arm::isHardTPSupported(EffectiveTriple)) {
33047a9b00ceSrobert         D.Diag(diag::err_target_unsupported_tp_hard)
33057a9b00ceSrobert             << EffectiveTriple.getArchName();
33067a9b00ceSrobert         return;
33077a9b00ceSrobert       }
33087a9b00ceSrobert       // Check whether the user asked for something other than -mtp=cp15
33097a9b00ceSrobert       if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
33107a9b00ceSrobert         StringRef Value = A->getValue();
33117a9b00ceSrobert         if (Value != "cp15") {
33127a9b00ceSrobert           D.Diag(diag::err_drv_argument_not_allowed_with)
33137a9b00ceSrobert               << A->getAsString(Args) << "-mstack-protector-guard=tls";
33147a9b00ceSrobert           return;
33157a9b00ceSrobert         }
33167a9b00ceSrobert       }
33177a9b00ceSrobert       CmdArgs.push_back("-target-feature");
33187a9b00ceSrobert       CmdArgs.push_back("+read-tp-hard");
33197a9b00ceSrobert     }
3320a0747c9fSpatrick     if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3321a0747c9fSpatrick       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3322a0747c9fSpatrick           << A->getOption().getName() << Value << "sysreg global";
3323a0747c9fSpatrick       return;
3324a0747c9fSpatrick     }
3325a0747c9fSpatrick     A->render(Args, CmdArgs);
3326a0747c9fSpatrick   }
3327a0747c9fSpatrick 
3328a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3329a0747c9fSpatrick     StringRef Value = A->getValue();
33307a9b00ceSrobert     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
33317a9b00ceSrobert         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3332a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
3333a0747c9fSpatrick           << A->getAsString(Args) << TripleStr;
3334a0747c9fSpatrick     int Offset;
3335a0747c9fSpatrick     if (Value.getAsInteger(10, Offset)) {
3336a0747c9fSpatrick       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3337a0747c9fSpatrick       return;
3338a0747c9fSpatrick     }
33397a9b00ceSrobert     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
33407a9b00ceSrobert         (Offset < 0 || Offset > 0xfffff)) {
33417a9b00ceSrobert       D.Diag(diag::err_drv_invalid_int_value)
33427a9b00ceSrobert           << A->getOption().getName() << Value;
33437a9b00ceSrobert       return;
33447a9b00ceSrobert     }
3345a0747c9fSpatrick     A->render(Args, CmdArgs);
3346a0747c9fSpatrick   }
3347a0747c9fSpatrick 
3348a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3349a0747c9fSpatrick     StringRef Value = A->getValue();
3350a0747c9fSpatrick     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3351a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
3352a0747c9fSpatrick           << A->getAsString(Args) << TripleStr;
3353a0747c9fSpatrick     if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3354a0747c9fSpatrick       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3355a0747c9fSpatrick           << A->getOption().getName() << Value << "fs gs";
3356a0747c9fSpatrick       return;
3357a0747c9fSpatrick     }
3358a0747c9fSpatrick     if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3359a0747c9fSpatrick       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3360a0747c9fSpatrick       return;
3361a0747c9fSpatrick     }
3362a0747c9fSpatrick     A->render(Args, CmdArgs);
3363a0747c9fSpatrick   }
33647a9b00ceSrobert 
33657a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
33667a9b00ceSrobert     StringRef Value = A->getValue();
33677a9b00ceSrobert     if (!isValidSymbolName(Value)) {
33687a9b00ceSrobert       D.Diag(diag::err_drv_argument_only_allowed_with)
33697a9b00ceSrobert           << A->getOption().getName() << "legal symbol name";
33707a9b00ceSrobert       return;
33717a9b00ceSrobert     }
33727a9b00ceSrobert     A->render(Args, CmdArgs);
33737a9b00ceSrobert   }
3374e5dd7070Spatrick }
3375e5dd7070Spatrick 
RenderSCPOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3376adae0cfdSpatrick static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3377adae0cfdSpatrick                              ArgStringList &CmdArgs) {
3378adae0cfdSpatrick   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3379adae0cfdSpatrick 
33807a9b00ceSrobert   if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3381adae0cfdSpatrick     return;
3382adae0cfdSpatrick 
3383adae0cfdSpatrick   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3384adae0cfdSpatrick       !EffectiveTriple.isPPC64())
3385adae0cfdSpatrick     return;
3386adae0cfdSpatrick 
33877a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
33887a9b00ceSrobert                     options::OPT_fno_stack_clash_protection);
3389adae0cfdSpatrick }
3390adae0cfdSpatrick 
RenderTrivialAutoVarInitOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3391e5dd7070Spatrick static void RenderTrivialAutoVarInitOptions(const Driver &D,
3392e5dd7070Spatrick                                             const ToolChain &TC,
3393e5dd7070Spatrick                                             const ArgList &Args,
3394e5dd7070Spatrick                                             ArgStringList &CmdArgs) {
3395e5dd7070Spatrick   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3396e5dd7070Spatrick   StringRef TrivialAutoVarInit = "";
3397e5dd7070Spatrick 
3398e5dd7070Spatrick   for (const Arg *A : Args) {
3399e5dd7070Spatrick     switch (A->getOption().getID()) {
3400e5dd7070Spatrick     default:
3401e5dd7070Spatrick       continue;
3402e5dd7070Spatrick     case options::OPT_ftrivial_auto_var_init: {
3403e5dd7070Spatrick       A->claim();
3404e5dd7070Spatrick       StringRef Val = A->getValue();
3405e5dd7070Spatrick       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3406e5dd7070Spatrick         TrivialAutoVarInit = Val;
3407e5dd7070Spatrick       else
3408e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_option_argument)
34097a9b00ceSrobert             << A->getSpelling() << Val;
3410e5dd7070Spatrick       break;
3411e5dd7070Spatrick     }
3412e5dd7070Spatrick     }
3413e5dd7070Spatrick   }
3414e5dd7070Spatrick 
3415e5dd7070Spatrick   if (TrivialAutoVarInit.empty())
3416e5dd7070Spatrick     switch (DefaultTrivialAutoVarInit) {
3417e5dd7070Spatrick     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3418e5dd7070Spatrick       break;
3419e5dd7070Spatrick     case LangOptions::TrivialAutoVarInitKind::Pattern:
3420e5dd7070Spatrick       TrivialAutoVarInit = "pattern";
3421e5dd7070Spatrick       break;
3422e5dd7070Spatrick     case LangOptions::TrivialAutoVarInitKind::Zero:
3423e5dd7070Spatrick       TrivialAutoVarInit = "zero";
3424e5dd7070Spatrick       break;
3425e5dd7070Spatrick     }
3426e5dd7070Spatrick 
3427e5dd7070Spatrick   if (!TrivialAutoVarInit.empty()) {
3428e5dd7070Spatrick     CmdArgs.push_back(
3429e5dd7070Spatrick         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3430e5dd7070Spatrick   }
3431adae0cfdSpatrick 
3432adae0cfdSpatrick   if (Arg *A =
3433adae0cfdSpatrick           Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3434adae0cfdSpatrick     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3435adae0cfdSpatrick         StringRef(
3436adae0cfdSpatrick             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3437adae0cfdSpatrick             "uninitialized")
3438adae0cfdSpatrick       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3439adae0cfdSpatrick     A->claim();
3440adae0cfdSpatrick     StringRef Val = A->getValue();
3441adae0cfdSpatrick     if (std::stoi(Val.str()) <= 0)
3442adae0cfdSpatrick       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3443adae0cfdSpatrick     CmdArgs.push_back(
3444adae0cfdSpatrick         Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3445adae0cfdSpatrick   }
3446e5dd7070Spatrick }
3447e5dd7070Spatrick 
RenderOpenCLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)3448a0747c9fSpatrick static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3449a0747c9fSpatrick                                 types::ID InputType) {
3450adae0cfdSpatrick   // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3451adae0cfdSpatrick   // for denormal flushing handling based on the target.
3452e5dd7070Spatrick   const unsigned ForwardedArguments[] = {
3453e5dd7070Spatrick       options::OPT_cl_opt_disable,
3454e5dd7070Spatrick       options::OPT_cl_strict_aliasing,
3455e5dd7070Spatrick       options::OPT_cl_single_precision_constant,
3456e5dd7070Spatrick       options::OPT_cl_finite_math_only,
3457e5dd7070Spatrick       options::OPT_cl_kernel_arg_info,
3458e5dd7070Spatrick       options::OPT_cl_unsafe_math_optimizations,
3459e5dd7070Spatrick       options::OPT_cl_fast_relaxed_math,
3460e5dd7070Spatrick       options::OPT_cl_mad_enable,
3461e5dd7070Spatrick       options::OPT_cl_no_signed_zeros,
3462e5dd7070Spatrick       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3463e5dd7070Spatrick       options::OPT_cl_uniform_work_group_size
3464e5dd7070Spatrick   };
3465e5dd7070Spatrick 
3466e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3467e5dd7070Spatrick     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3468e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
34697a9b00ceSrobert   } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
34707a9b00ceSrobert     std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
34717a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3472e5dd7070Spatrick   }
3473e5dd7070Spatrick 
3474e5dd7070Spatrick   for (const auto &Arg : ForwardedArguments)
3475e5dd7070Spatrick     if (const auto *A = Args.getLastArg(Arg))
3476e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3477a0747c9fSpatrick 
3478a0747c9fSpatrick   // Only add the default headers if we are compiling OpenCL sources.
3479a0747c9fSpatrick   if ((types::isOpenCL(InputType) ||
3480a0747c9fSpatrick        (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3481a0747c9fSpatrick       !Args.hasArg(options::OPT_cl_no_stdinc)) {
3482a0747c9fSpatrick     CmdArgs.push_back("-finclude-default-header");
3483a0747c9fSpatrick     CmdArgs.push_back("-fdeclare-opencl-builtins");
3484a0747c9fSpatrick   }
3485e5dd7070Spatrick }
3486e5dd7070Spatrick 
RenderHLSLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)34877a9b00ceSrobert static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
34887a9b00ceSrobert                               types::ID InputType) {
34897a9b00ceSrobert   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
34907a9b00ceSrobert                                          options::OPT_D,
34917a9b00ceSrobert                                          options::OPT_I,
34927a9b00ceSrobert                                          options::OPT_S,
34937a9b00ceSrobert                                          options::OPT_O,
34947a9b00ceSrobert                                          options::OPT_emit_llvm,
34957a9b00ceSrobert                                          options::OPT_emit_obj,
34967a9b00ceSrobert                                          options::OPT_disable_llvm_passes,
34977a9b00ceSrobert                                          options::OPT_fnative_half_type,
34987a9b00ceSrobert                                          options::OPT_hlsl_entrypoint};
34997a9b00ceSrobert   if (!types::isHLSL(InputType))
35007a9b00ceSrobert     return;
35017a9b00ceSrobert   for (const auto &Arg : ForwardedArguments)
35027a9b00ceSrobert     if (const auto *A = Args.getLastArg(Arg))
35037a9b00ceSrobert       A->renderAsInput(Args, CmdArgs);
35047a9b00ceSrobert   // Add the default headers if dxc_no_stdinc is not set.
35057a9b00ceSrobert   if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
35067a9b00ceSrobert       !Args.hasArg(options::OPT_nostdinc))
35077a9b00ceSrobert     CmdArgs.push_back("-finclude-default-header");
35087a9b00ceSrobert }
35097a9b00ceSrobert 
RenderARCMigrateToolOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)3510e5dd7070Spatrick static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3511e5dd7070Spatrick                                         ArgStringList &CmdArgs) {
3512e5dd7070Spatrick   bool ARCMTEnabled = false;
3513e5dd7070Spatrick   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3514e5dd7070Spatrick     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3515e5dd7070Spatrick                                        options::OPT_ccc_arcmt_modify,
3516e5dd7070Spatrick                                        options::OPT_ccc_arcmt_migrate)) {
3517e5dd7070Spatrick       ARCMTEnabled = true;
3518e5dd7070Spatrick       switch (A->getOption().getID()) {
3519e5dd7070Spatrick       default: llvm_unreachable("missed a case");
3520e5dd7070Spatrick       case options::OPT_ccc_arcmt_check:
3521a0747c9fSpatrick         CmdArgs.push_back("-arcmt-action=check");
3522e5dd7070Spatrick         break;
3523e5dd7070Spatrick       case options::OPT_ccc_arcmt_modify:
3524a0747c9fSpatrick         CmdArgs.push_back("-arcmt-action=modify");
3525e5dd7070Spatrick         break;
3526e5dd7070Spatrick       case options::OPT_ccc_arcmt_migrate:
3527a0747c9fSpatrick         CmdArgs.push_back("-arcmt-action=migrate");
3528e5dd7070Spatrick         CmdArgs.push_back("-mt-migrate-directory");
3529e5dd7070Spatrick         CmdArgs.push_back(A->getValue());
3530e5dd7070Spatrick 
3531e5dd7070Spatrick         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3532e5dd7070Spatrick         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3533e5dd7070Spatrick         break;
3534e5dd7070Spatrick       }
3535e5dd7070Spatrick     }
3536e5dd7070Spatrick   } else {
3537e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3538e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3539e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3540e5dd7070Spatrick   }
3541e5dd7070Spatrick 
3542e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3543e5dd7070Spatrick     if (ARCMTEnabled)
3544e5dd7070Spatrick       D.Diag(diag::err_drv_argument_not_allowed_with)
3545e5dd7070Spatrick           << A->getAsString(Args) << "-ccc-arcmt-migrate";
3546e5dd7070Spatrick 
3547e5dd7070Spatrick     CmdArgs.push_back("-mt-migrate-directory");
3548e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
3549e5dd7070Spatrick 
3550e5dd7070Spatrick     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3551e5dd7070Spatrick                      options::OPT_objcmt_migrate_subscripting,
3552e5dd7070Spatrick                      options::OPT_objcmt_migrate_property)) {
3553e5dd7070Spatrick       // None specified, means enable them all.
3554e5dd7070Spatrick       CmdArgs.push_back("-objcmt-migrate-literals");
3555e5dd7070Spatrick       CmdArgs.push_back("-objcmt-migrate-subscripting");
3556e5dd7070Spatrick       CmdArgs.push_back("-objcmt-migrate-property");
3557e5dd7070Spatrick     } else {
3558e5dd7070Spatrick       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3559e5dd7070Spatrick       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3560e5dd7070Spatrick       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3561e5dd7070Spatrick     }
3562e5dd7070Spatrick   } else {
3563e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3564e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3565e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3566e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3567e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3568e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3569e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3570e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3571e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3572e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3573e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3574e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3575e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3576e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3577e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
35787a9b00ceSrobert     Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3579e5dd7070Spatrick   }
3580e5dd7070Spatrick }
3581e5dd7070Spatrick 
RenderBuiltinOptions(const ToolChain & TC,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs)3582e5dd7070Spatrick static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3583e5dd7070Spatrick                                  const ArgList &Args, ArgStringList &CmdArgs) {
3584e5dd7070Spatrick   // -fbuiltin is default unless -mkernel is used.
3585e5dd7070Spatrick   bool UseBuiltins =
3586e5dd7070Spatrick       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3587e5dd7070Spatrick                    !Args.hasArg(options::OPT_mkernel));
3588e5dd7070Spatrick   if (!UseBuiltins)
3589e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin");
3590e5dd7070Spatrick 
3591e5dd7070Spatrick   // -ffreestanding implies -fno-builtin.
3592e5dd7070Spatrick   if (Args.hasArg(options::OPT_ffreestanding))
3593e5dd7070Spatrick     UseBuiltins = false;
3594e5dd7070Spatrick 
3595e5dd7070Spatrick   // Process the -fno-builtin-* options.
35967a9b00ceSrobert   for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
35977a9b00ceSrobert     A->claim();
3598e5dd7070Spatrick 
3599e5dd7070Spatrick     // If -fno-builtin is specified, then there's no need to pass the option to
3600e5dd7070Spatrick     // the frontend.
36017a9b00ceSrobert     if (UseBuiltins)
36027a9b00ceSrobert       A->render(Args, CmdArgs);
3603e5dd7070Spatrick   }
3604e5dd7070Spatrick 
3605e5dd7070Spatrick   // le32-specific flags:
3606e5dd7070Spatrick   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3607e5dd7070Spatrick   //                     by default.
3608e5dd7070Spatrick   if (TC.getArch() == llvm::Triple::le32)
3609e5dd7070Spatrick     CmdArgs.push_back("-fno-math-builtin");
3610e5dd7070Spatrick }
3611e5dd7070Spatrick 
getDefaultModuleCachePath(SmallVectorImpl<char> & Result)3612adae0cfdSpatrick bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
36137a9b00ceSrobert   if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
36147a9b00ceSrobert     Twine Path{Str};
36157a9b00ceSrobert     Path.toVector(Result);
36167a9b00ceSrobert     return Path.getSingleStringRef() != "";
36177a9b00ceSrobert   }
3618adae0cfdSpatrick   if (llvm::sys::path::cache_directory(Result)) {
3619adae0cfdSpatrick     llvm::sys::path::append(Result, "clang");
3620e5dd7070Spatrick     llvm::sys::path::append(Result, "ModuleCache");
3621adae0cfdSpatrick     return true;
3622adae0cfdSpatrick   }
3623adae0cfdSpatrick   return false;
3624e5dd7070Spatrick }
3625e5dd7070Spatrick 
RenderModulesOptions(Compilation & C,const Driver & D,const ArgList & Args,const InputInfo & Input,const InputInfo & Output,const Arg * Std,ArgStringList & CmdArgs)36267a9b00ceSrobert static bool RenderModulesOptions(Compilation &C, const Driver &D,
3627e5dd7070Spatrick                                  const ArgList &Args, const InputInfo &Input,
36287a9b00ceSrobert                                  const InputInfo &Output, const Arg *Std,
36297a9b00ceSrobert                                  ArgStringList &CmdArgs) {
36307a9b00ceSrobert   bool IsCXX = types::isCXX(Input.getType());
36317a9b00ceSrobert   // FIXME: Find a better way to determine whether the input has standard c++
36327a9b00ceSrobert   // modules support by default.
36337a9b00ceSrobert   bool HaveStdCXXModules =
36347a9b00ceSrobert       IsCXX && Std &&
36357a9b00ceSrobert       (Std->containsValue("c++2a") || Std->containsValue("c++20") ||
36367a9b00ceSrobert        Std->containsValue("c++2b") || Std->containsValue("c++latest"));
36377a9b00ceSrobert   bool HaveModules = HaveStdCXXModules;
36387a9b00ceSrobert 
3639e5dd7070Spatrick   // -fmodules enables the use of precompiled modules (off by default).
3640e5dd7070Spatrick   // Users can pass -fno-cxx-modules to turn off modules support for
3641e5dd7070Spatrick   // C++/Objective-C++ programs.
3642e5dd7070Spatrick   bool HaveClangModules = false;
3643e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3644e5dd7070Spatrick     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3645e5dd7070Spatrick                                      options::OPT_fno_cxx_modules, true);
36467a9b00ceSrobert     if (AllowedInCXX || !IsCXX) {
3647e5dd7070Spatrick       CmdArgs.push_back("-fmodules");
3648e5dd7070Spatrick       HaveClangModules = true;
3649e5dd7070Spatrick     }
3650e5dd7070Spatrick   }
3651e5dd7070Spatrick 
3652e5dd7070Spatrick   HaveModules |= HaveClangModules;
3653e5dd7070Spatrick   if (Args.hasArg(options::OPT_fmodules_ts)) {
36547a9b00ceSrobert     D.Diag(diag::warn_deprecated_fmodules_ts_flag);
3655e5dd7070Spatrick     CmdArgs.push_back("-fmodules-ts");
3656e5dd7070Spatrick     HaveModules = true;
3657e5dd7070Spatrick   }
3658e5dd7070Spatrick 
3659e5dd7070Spatrick   // -fmodule-maps enables implicit reading of module map files. By default,
3660e5dd7070Spatrick   // this is enabled if we are using Clang's flavor of precompiled modules.
3661e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3662e5dd7070Spatrick                    options::OPT_fno_implicit_module_maps, HaveClangModules))
3663e5dd7070Spatrick     CmdArgs.push_back("-fimplicit-module-maps");
3664e5dd7070Spatrick 
3665e5dd7070Spatrick   // -fmodules-decluse checks that modules used are declared so (off by default)
36667a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
36677a9b00ceSrobert                     options::OPT_fno_modules_decluse);
3668e5dd7070Spatrick 
3669e5dd7070Spatrick   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3670e5dd7070Spatrick   // all #included headers are part of modules.
3671e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3672e5dd7070Spatrick                    options::OPT_fno_modules_strict_decluse, false))
3673e5dd7070Spatrick     CmdArgs.push_back("-fmodules-strict-decluse");
3674e5dd7070Spatrick 
3675e5dd7070Spatrick   // -fno-implicit-modules turns off implicitly compiling modules on demand.
3676e5dd7070Spatrick   bool ImplicitModules = false;
3677e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fimplicit_modules,
3678e5dd7070Spatrick                     options::OPT_fno_implicit_modules, HaveClangModules)) {
3679e5dd7070Spatrick     if (HaveModules)
3680e5dd7070Spatrick       CmdArgs.push_back("-fno-implicit-modules");
3681e5dd7070Spatrick   } else if (HaveModules) {
3682e5dd7070Spatrick     ImplicitModules = true;
3683e5dd7070Spatrick     // -fmodule-cache-path specifies where our implicitly-built module files
3684e5dd7070Spatrick     // should be written.
3685e5dd7070Spatrick     SmallString<128> Path;
3686e5dd7070Spatrick     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3687e5dd7070Spatrick       Path = A->getValue();
3688e5dd7070Spatrick 
3689adae0cfdSpatrick     bool HasPath = true;
3690e5dd7070Spatrick     if (C.isForDiagnostics()) {
3691e5dd7070Spatrick       // When generating crash reports, we want to emit the modules along with
3692e5dd7070Spatrick       // the reproduction sources, so we ignore any provided module path.
3693e5dd7070Spatrick       Path = Output.getFilename();
3694e5dd7070Spatrick       llvm::sys::path::replace_extension(Path, ".cache");
3695e5dd7070Spatrick       llvm::sys::path::append(Path, "modules");
3696e5dd7070Spatrick     } else if (Path.empty()) {
3697e5dd7070Spatrick       // No module path was provided: use the default.
3698adae0cfdSpatrick       HasPath = Driver::getDefaultModuleCachePath(Path);
3699e5dd7070Spatrick     }
3700e5dd7070Spatrick 
3701adae0cfdSpatrick     // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3702adae0cfdSpatrick     // That being said, that failure is unlikely and not caching is harmless.
3703adae0cfdSpatrick     if (HasPath) {
3704e5dd7070Spatrick       const char Arg[] = "-fmodules-cache-path=";
3705e5dd7070Spatrick       Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3706e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(Path));
3707e5dd7070Spatrick     }
3708adae0cfdSpatrick   }
3709e5dd7070Spatrick 
3710e5dd7070Spatrick   if (HaveModules) {
3711e5dd7070Spatrick     // -fprebuilt-module-path specifies where to load the prebuilt module files.
3712e5dd7070Spatrick     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3713e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(
3714e5dd7070Spatrick           std::string("-fprebuilt-module-path=") + A->getValue()));
3715e5dd7070Spatrick       A->claim();
3716e5dd7070Spatrick     }
3717a0747c9fSpatrick     if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3718a0747c9fSpatrick                      options::OPT_fno_prebuilt_implicit_modules, false))
3719a0747c9fSpatrick       CmdArgs.push_back("-fprebuilt-implicit-modules");
3720e5dd7070Spatrick     if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3721e5dd7070Spatrick                      options::OPT_fno_modules_validate_input_files_content,
3722e5dd7070Spatrick                      false))
3723e5dd7070Spatrick       CmdArgs.push_back("-fvalidate-ast-input-files-content");
3724e5dd7070Spatrick   }
3725e5dd7070Spatrick 
3726e5dd7070Spatrick   // -fmodule-name specifies the module that is currently being built (or
3727e5dd7070Spatrick   // used for header checking by -fmodule-maps).
3728e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3729e5dd7070Spatrick 
3730e5dd7070Spatrick   // -fmodule-map-file can be used to specify files containing module
3731e5dd7070Spatrick   // definitions.
3732e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3733e5dd7070Spatrick 
3734e5dd7070Spatrick   // -fbuiltin-module-map can be used to load the clang
3735e5dd7070Spatrick   // builtin headers modulemap file.
3736e5dd7070Spatrick   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3737e5dd7070Spatrick     SmallString<128> BuiltinModuleMap(D.ResourceDir);
3738e5dd7070Spatrick     llvm::sys::path::append(BuiltinModuleMap, "include");
3739e5dd7070Spatrick     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3740e5dd7070Spatrick     if (llvm::sys::fs::exists(BuiltinModuleMap))
3741e5dd7070Spatrick       CmdArgs.push_back(
3742e5dd7070Spatrick           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3743e5dd7070Spatrick   }
3744e5dd7070Spatrick 
3745e5dd7070Spatrick   // The -fmodule-file=<name>=<file> form specifies the mapping of module
3746e5dd7070Spatrick   // names to precompiled module files (the module is loaded only if used).
3747e5dd7070Spatrick   // The -fmodule-file=<file> form can be used to unconditionally load
3748e5dd7070Spatrick   // precompiled module files (whether used or not).
3749e5dd7070Spatrick   if (HaveModules)
3750e5dd7070Spatrick     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3751e5dd7070Spatrick   else
3752e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fmodule_file);
3753e5dd7070Spatrick 
3754e5dd7070Spatrick   // When building modules and generating crashdumps, we need to dump a module
3755e5dd7070Spatrick   // dependency VFS alongside the output.
3756e5dd7070Spatrick   if (HaveClangModules && C.isForDiagnostics()) {
3757e5dd7070Spatrick     SmallString<128> VFSDir(Output.getFilename());
3758e5dd7070Spatrick     llvm::sys::path::replace_extension(VFSDir, ".cache");
3759e5dd7070Spatrick     // Add the cache directory as a temp so the crash diagnostics pick it up.
3760e5dd7070Spatrick     C.addTempFile(Args.MakeArgString(VFSDir));
3761e5dd7070Spatrick 
3762e5dd7070Spatrick     llvm::sys::path::append(VFSDir, "vfs");
3763e5dd7070Spatrick     CmdArgs.push_back("-module-dependency-dir");
3764e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(VFSDir));
3765e5dd7070Spatrick   }
3766e5dd7070Spatrick 
3767e5dd7070Spatrick   if (HaveClangModules)
3768e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3769e5dd7070Spatrick 
3770e5dd7070Spatrick   // Pass through all -fmodules-ignore-macro arguments.
3771e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3772e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3773e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3774e5dd7070Spatrick 
37757a9b00ceSrobert   if (HaveClangModules) {
3776e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3777e5dd7070Spatrick 
3778e5dd7070Spatrick     if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3779e5dd7070Spatrick       if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3780e5dd7070Spatrick         D.Diag(diag::err_drv_argument_not_allowed_with)
3781e5dd7070Spatrick             << A->getAsString(Args) << "-fbuild-session-timestamp";
3782e5dd7070Spatrick 
3783e5dd7070Spatrick       llvm::sys::fs::file_status Status;
3784e5dd7070Spatrick       if (llvm::sys::fs::status(A->getValue(), Status))
3785e5dd7070Spatrick         D.Diag(diag::err_drv_no_such_file) << A->getValue();
37867a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString(
37877a9b00ceSrobert           "-fbuild-session-timestamp=" +
37887a9b00ceSrobert           Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
37897a9b00ceSrobert                     Status.getLastModificationTime().time_since_epoch())
3790e5dd7070Spatrick                     .count())));
3791e5dd7070Spatrick     }
3792e5dd7070Spatrick 
37937a9b00ceSrobert     if (Args.getLastArg(
37947a9b00ceSrobert             options::OPT_fmodules_validate_once_per_build_session)) {
3795e5dd7070Spatrick       if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3796e5dd7070Spatrick                            options::OPT_fbuild_session_file))
3797e5dd7070Spatrick         D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3798e5dd7070Spatrick 
3799e5dd7070Spatrick       Args.AddLastArg(CmdArgs,
3800e5dd7070Spatrick                       options::OPT_fmodules_validate_once_per_build_session);
3801e5dd7070Spatrick     }
3802e5dd7070Spatrick 
3803e5dd7070Spatrick     if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3804e5dd7070Spatrick                      options::OPT_fno_modules_validate_system_headers,
3805e5dd7070Spatrick                      ImplicitModules))
3806e5dd7070Spatrick       CmdArgs.push_back("-fmodules-validate-system-headers");
3807e5dd7070Spatrick 
38087a9b00ceSrobert     Args.AddLastArg(CmdArgs,
38097a9b00ceSrobert                     options::OPT_fmodules_disable_diagnostic_validation);
38107a9b00ceSrobert   } else {
38117a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
38127a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_fbuild_session_file);
38137a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
38147a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
38157a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
38167a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
38177a9b00ceSrobert   }
38187a9b00ceSrobert 
38197a9b00ceSrobert   // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
38207a9b00ceSrobert   Args.ClaimAllArgs(options::OPT_fmodule_output);
38217a9b00ceSrobert   Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
38227a9b00ceSrobert 
38237a9b00ceSrobert   return HaveModules;
3824e5dd7070Spatrick }
3825e5dd7070Spatrick 
RenderCharacterOptions(const ArgList & Args,const llvm::Triple & T,ArgStringList & CmdArgs)3826e5dd7070Spatrick static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3827e5dd7070Spatrick                                    ArgStringList &CmdArgs) {
3828e5dd7070Spatrick   // -fsigned-char is default.
3829e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3830e5dd7070Spatrick                                      options::OPT_fno_signed_char,
3831e5dd7070Spatrick                                      options::OPT_funsigned_char,
3832e5dd7070Spatrick                                      options::OPT_fno_unsigned_char)) {
3833e5dd7070Spatrick     if (A->getOption().matches(options::OPT_funsigned_char) ||
3834e5dd7070Spatrick         A->getOption().matches(options::OPT_fno_signed_char)) {
3835e5dd7070Spatrick       CmdArgs.push_back("-fno-signed-char");
3836e5dd7070Spatrick     }
3837e5dd7070Spatrick   } else if (!isSignedCharDefault(T)) {
3838e5dd7070Spatrick     CmdArgs.push_back("-fno-signed-char");
3839e5dd7070Spatrick   }
3840e5dd7070Spatrick 
3841e5dd7070Spatrick   // The default depends on the language standard.
3842e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3843e5dd7070Spatrick 
3844e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3845e5dd7070Spatrick                                      options::OPT_fno_short_wchar)) {
3846e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fshort_wchar)) {
3847e5dd7070Spatrick       CmdArgs.push_back("-fwchar-type=short");
3848e5dd7070Spatrick       CmdArgs.push_back("-fno-signed-wchar");
3849e5dd7070Spatrick     } else {
3850e5dd7070Spatrick       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3851e5dd7070Spatrick       CmdArgs.push_back("-fwchar-type=int");
3852a0747c9fSpatrick       if (T.isOSzOS() ||
3853a0747c9fSpatrick           (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3854e5dd7070Spatrick         CmdArgs.push_back("-fno-signed-wchar");
3855e5dd7070Spatrick       else
3856e5dd7070Spatrick         CmdArgs.push_back("-fsigned-wchar");
3857e5dd7070Spatrick     }
3858e5dd7070Spatrick   }
3859e5dd7070Spatrick }
3860e5dd7070Spatrick 
RenderObjCOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,ObjCRuntime & Runtime,bool InferCovariantReturns,const InputInfo & Input,ArgStringList & CmdArgs)3861e5dd7070Spatrick static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3862e5dd7070Spatrick                               const llvm::Triple &T, const ArgList &Args,
3863e5dd7070Spatrick                               ObjCRuntime &Runtime, bool InferCovariantReturns,
3864e5dd7070Spatrick                               const InputInfo &Input, ArgStringList &CmdArgs) {
3865e5dd7070Spatrick   const llvm::Triple::ArchType Arch = TC.getArch();
3866e5dd7070Spatrick 
3867e5dd7070Spatrick   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3868e5dd7070Spatrick   // is the default. Except for deployment target of 10.5, next runtime is
3869e5dd7070Spatrick   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3870e5dd7070Spatrick   if (Runtime.isNonFragile()) {
3871e5dd7070Spatrick     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3872e5dd7070Spatrick                       options::OPT_fno_objc_legacy_dispatch,
3873e5dd7070Spatrick                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3874e5dd7070Spatrick       if (TC.UseObjCMixedDispatch())
3875e5dd7070Spatrick         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3876e5dd7070Spatrick       else
3877e5dd7070Spatrick         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3878e5dd7070Spatrick     }
3879e5dd7070Spatrick   }
3880e5dd7070Spatrick 
3881e5dd7070Spatrick   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3882e5dd7070Spatrick   // to do Array/Dictionary subscripting by default.
3883e5dd7070Spatrick   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3884e5dd7070Spatrick       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3885e5dd7070Spatrick     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3886e5dd7070Spatrick 
3887e5dd7070Spatrick   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3888e5dd7070Spatrick   // NOTE: This logic is duplicated in ToolChains.cpp.
3889e5dd7070Spatrick   if (isObjCAutoRefCount(Args)) {
3890e5dd7070Spatrick     TC.CheckObjCARC();
3891e5dd7070Spatrick 
3892e5dd7070Spatrick     CmdArgs.push_back("-fobjc-arc");
3893e5dd7070Spatrick 
3894e5dd7070Spatrick     // FIXME: It seems like this entire block, and several around it should be
3895e5dd7070Spatrick     // wrapped in isObjC, but for now we just use it here as this is where it
3896e5dd7070Spatrick     // was being used previously.
3897e5dd7070Spatrick     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3898e5dd7070Spatrick       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3899e5dd7070Spatrick         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3900e5dd7070Spatrick       else
3901e5dd7070Spatrick         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3902e5dd7070Spatrick     }
3903e5dd7070Spatrick 
3904e5dd7070Spatrick     // Allow the user to enable full exceptions code emission.
3905e5dd7070Spatrick     // We default off for Objective-C, on for Objective-C++.
3906e5dd7070Spatrick     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3907e5dd7070Spatrick                      options::OPT_fno_objc_arc_exceptions,
3908e5dd7070Spatrick                      /*Default=*/types::isCXX(Input.getType())))
3909e5dd7070Spatrick       CmdArgs.push_back("-fobjc-arc-exceptions");
3910e5dd7070Spatrick   }
3911e5dd7070Spatrick 
3912e5dd7070Spatrick   // Silence warning for full exception code emission options when explicitly
3913e5dd7070Spatrick   // set to use no ARC.
3914e5dd7070Spatrick   if (Args.hasArg(options::OPT_fno_objc_arc)) {
3915e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3916e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3917e5dd7070Spatrick   }
3918e5dd7070Spatrick 
3919e5dd7070Spatrick   // Allow the user to control whether messages can be converted to runtime
3920e5dd7070Spatrick   // functions.
3921e5dd7070Spatrick   if (types::isObjC(Input.getType())) {
3922e5dd7070Spatrick     auto *Arg = Args.getLastArg(
3923e5dd7070Spatrick         options::OPT_fobjc_convert_messages_to_runtime_calls,
3924e5dd7070Spatrick         options::OPT_fno_objc_convert_messages_to_runtime_calls);
3925e5dd7070Spatrick     if (Arg &&
3926e5dd7070Spatrick         Arg->getOption().matches(
3927e5dd7070Spatrick             options::OPT_fno_objc_convert_messages_to_runtime_calls))
3928e5dd7070Spatrick       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3929e5dd7070Spatrick   }
3930e5dd7070Spatrick 
3931e5dd7070Spatrick   // -fobjc-infer-related-result-type is the default, except in the Objective-C
3932e5dd7070Spatrick   // rewriter.
3933e5dd7070Spatrick   if (InferCovariantReturns)
3934e5dd7070Spatrick     CmdArgs.push_back("-fno-objc-infer-related-result-type");
3935e5dd7070Spatrick 
3936e5dd7070Spatrick   // Pass down -fobjc-weak or -fno-objc-weak if present.
3937e5dd7070Spatrick   if (types::isObjC(Input.getType())) {
3938e5dd7070Spatrick     auto WeakArg =
3939e5dd7070Spatrick         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3940e5dd7070Spatrick     if (!WeakArg) {
3941e5dd7070Spatrick       // nothing to do
3942e5dd7070Spatrick     } else if (!Runtime.allowsWeak()) {
3943e5dd7070Spatrick       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3944e5dd7070Spatrick         D.Diag(diag::err_objc_weak_unsupported);
3945e5dd7070Spatrick     } else {
3946e5dd7070Spatrick       WeakArg->render(Args, CmdArgs);
3947e5dd7070Spatrick     }
3948e5dd7070Spatrick   }
3949a0747c9fSpatrick 
3950a0747c9fSpatrick   if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
3951a0747c9fSpatrick     CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
3952e5dd7070Spatrick }
3953e5dd7070Spatrick 
RenderDiagnosticsOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)3954e5dd7070Spatrick static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3955e5dd7070Spatrick                                      ArgStringList &CmdArgs) {
3956e5dd7070Spatrick   bool CaretDefault = true;
3957e5dd7070Spatrick   bool ColumnDefault = true;
3958e5dd7070Spatrick 
3959e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3960e5dd7070Spatrick                                      options::OPT__SLASH_diagnostics_column,
3961e5dd7070Spatrick                                      options::OPT__SLASH_diagnostics_caret)) {
3962e5dd7070Spatrick     switch (A->getOption().getID()) {
3963e5dd7070Spatrick     case options::OPT__SLASH_diagnostics_caret:
3964e5dd7070Spatrick       CaretDefault = true;
3965e5dd7070Spatrick       ColumnDefault = true;
3966e5dd7070Spatrick       break;
3967e5dd7070Spatrick     case options::OPT__SLASH_diagnostics_column:
3968e5dd7070Spatrick       CaretDefault = false;
3969e5dd7070Spatrick       ColumnDefault = true;
3970e5dd7070Spatrick       break;
3971e5dd7070Spatrick     case options::OPT__SLASH_diagnostics_classic:
3972e5dd7070Spatrick       CaretDefault = false;
3973e5dd7070Spatrick       ColumnDefault = false;
3974e5dd7070Spatrick       break;
3975e5dd7070Spatrick     }
3976e5dd7070Spatrick   }
3977e5dd7070Spatrick 
3978e5dd7070Spatrick   // -fcaret-diagnostics is default.
3979e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3980e5dd7070Spatrick                     options::OPT_fno_caret_diagnostics, CaretDefault))
3981e5dd7070Spatrick     CmdArgs.push_back("-fno-caret-diagnostics");
3982e5dd7070Spatrick 
39837a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
39847a9b00ceSrobert                      options::OPT_fno_diagnostics_fixit_info);
39857a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
39867a9b00ceSrobert                      options::OPT_fno_diagnostics_show_option);
3987e5dd7070Spatrick 
3988e5dd7070Spatrick   if (const Arg *A =
3989e5dd7070Spatrick           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3990e5dd7070Spatrick     CmdArgs.push_back("-fdiagnostics-show-category");
3991e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
3992e5dd7070Spatrick   }
3993e5dd7070Spatrick 
39947a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
39957a9b00ceSrobert                     options::OPT_fno_diagnostics_show_hotness);
3996e5dd7070Spatrick 
3997e5dd7070Spatrick   if (const Arg *A =
3998e5dd7070Spatrick           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3999e5dd7070Spatrick     std::string Opt =
4000e5dd7070Spatrick         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4001e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Opt));
4002e5dd7070Spatrick   }
4003e5dd7070Spatrick 
4004e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4005e5dd7070Spatrick     CmdArgs.push_back("-fdiagnostics-format");
4006e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
40077a9b00ceSrobert     if (StringRef(A->getValue()) == "sarif" ||
40087a9b00ceSrobert         StringRef(A->getValue()) == "SARIF")
40097a9b00ceSrobert       D.Diag(diag::warn_drv_sarif_format_unstable);
4010e5dd7070Spatrick   }
4011e5dd7070Spatrick 
4012e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(
4013e5dd7070Spatrick           options::OPT_fdiagnostics_show_note_include_stack,
4014e5dd7070Spatrick           options::OPT_fno_diagnostics_show_note_include_stack)) {
4015e5dd7070Spatrick     const Option &O = A->getOption();
4016e5dd7070Spatrick     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4017e5dd7070Spatrick       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4018e5dd7070Spatrick     else
4019e5dd7070Spatrick       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4020e5dd7070Spatrick   }
4021e5dd7070Spatrick 
4022e5dd7070Spatrick   // Color diagnostics are parsed by the driver directly from argv and later
4023e5dd7070Spatrick   // re-parsed to construct this job; claim any possible color diagnostic here
4024e5dd7070Spatrick   // to avoid warn_drv_unused_argument and diagnose bad
4025e5dd7070Spatrick   // OPT_fdiagnostics_color_EQ values.
40267a9b00ceSrobert   Args.getLastArg(options::OPT_fcolor_diagnostics,
40277a9b00ceSrobert                   options::OPT_fno_color_diagnostics);
40287a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4029e5dd7070Spatrick     StringRef Value(A->getValue());
4030e5dd7070Spatrick     if (Value != "always" && Value != "never" && Value != "auto")
40317a9b00ceSrobert       D.Diag(diag::err_drv_invalid_argument_to_option)
40327a9b00ceSrobert           << Value << A->getOption().getName();
4033e5dd7070Spatrick   }
4034e5dd7070Spatrick 
4035e5dd7070Spatrick   if (D.getDiags().getDiagnosticOptions().ShowColors)
4036e5dd7070Spatrick     CmdArgs.push_back("-fcolor-diagnostics");
4037e5dd7070Spatrick 
4038e5dd7070Spatrick   if (Args.hasArg(options::OPT_fansi_escape_codes))
4039e5dd7070Spatrick     CmdArgs.push_back("-fansi-escape-codes");
4040e5dd7070Spatrick 
40417a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
40427a9b00ceSrobert                      options::OPT_fno_show_source_location);
4043e5dd7070Spatrick 
4044e5dd7070Spatrick   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4045e5dd7070Spatrick     CmdArgs.push_back("-fdiagnostics-absolute-paths");
4046e5dd7070Spatrick 
4047e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4048e5dd7070Spatrick                     ColumnDefault))
4049e5dd7070Spatrick     CmdArgs.push_back("-fno-show-column");
4050e5dd7070Spatrick 
40517a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
40527a9b00ceSrobert                      options::OPT_fno_spell_checking);
4053e5dd7070Spatrick }
4054e5dd7070Spatrick 
getDebugFissionKind(const Driver & D,const ArgList & Args,Arg * & Arg)40557a9b00ceSrobert DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4056e5dd7070Spatrick                                             const ArgList &Args, Arg *&Arg) {
4057a0747c9fSpatrick   Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4058a0747c9fSpatrick                         options::OPT_gno_split_dwarf);
4059a0747c9fSpatrick   if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4060e5dd7070Spatrick     return DwarfFissionKind::None;
4061e5dd7070Spatrick 
4062e5dd7070Spatrick   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4063e5dd7070Spatrick     return DwarfFissionKind::Split;
4064e5dd7070Spatrick 
4065e5dd7070Spatrick   StringRef Value = Arg->getValue();
4066e5dd7070Spatrick   if (Value == "split")
4067e5dd7070Spatrick     return DwarfFissionKind::Split;
4068e5dd7070Spatrick   if (Value == "single")
4069e5dd7070Spatrick     return DwarfFissionKind::Single;
4070e5dd7070Spatrick 
4071e5dd7070Spatrick   D.Diag(diag::err_drv_unsupported_option_argument)
40727a9b00ceSrobert       << Arg->getSpelling() << Arg->getValue();
4073e5dd7070Spatrick   return DwarfFissionKind::None;
4074e5dd7070Spatrick }
4075e5dd7070Spatrick 
renderDwarfFormat(const Driver & D,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs,unsigned DwarfVersion)4076a0747c9fSpatrick static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4077a0747c9fSpatrick                               const ArgList &Args, ArgStringList &CmdArgs,
4078a0747c9fSpatrick                               unsigned DwarfVersion) {
4079a0747c9fSpatrick   auto *DwarfFormatArg =
4080a0747c9fSpatrick       Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4081a0747c9fSpatrick   if (!DwarfFormatArg)
4082a0747c9fSpatrick     return;
4083a0747c9fSpatrick 
4084a0747c9fSpatrick   if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4085a0747c9fSpatrick     if (DwarfVersion < 3)
4086a0747c9fSpatrick       D.Diag(diag::err_drv_argument_only_allowed_with)
4087a0747c9fSpatrick           << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4088a0747c9fSpatrick     else if (!T.isArch64Bit())
4089a0747c9fSpatrick       D.Diag(diag::err_drv_argument_only_allowed_with)
4090a0747c9fSpatrick           << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4091a0747c9fSpatrick     else if (!T.isOSBinFormatELF())
4092a0747c9fSpatrick       D.Diag(diag::err_drv_argument_only_allowed_with)
4093a0747c9fSpatrick           << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4094a0747c9fSpatrick   }
4095a0747c9fSpatrick 
4096a0747c9fSpatrick   DwarfFormatArg->render(Args, CmdArgs);
4097a0747c9fSpatrick }
4098a0747c9fSpatrick 
renderDebugOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,bool EmitCodeView,bool IRInput,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind & DebugInfoKind,DwarfFissionKind & DwarfFission)4099a0747c9fSpatrick static void renderDebugOptions(const ToolChain &TC, const Driver &D,
4100e5dd7070Spatrick                                const llvm::Triple &T, const ArgList &Args,
4101a0747c9fSpatrick                                bool EmitCodeView, bool IRInput,
4102a0747c9fSpatrick                                ArgStringList &CmdArgs,
4103e5dd7070Spatrick                                codegenoptions::DebugInfoKind &DebugInfoKind,
4104e5dd7070Spatrick                                DwarfFissionKind &DwarfFission) {
4105e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4106e5dd7070Spatrick                    options::OPT_fno_debug_info_for_profiling, false) &&
4107e5dd7070Spatrick       checkDebugInfoOption(
4108e5dd7070Spatrick           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4109e5dd7070Spatrick     CmdArgs.push_back("-fdebug-info-for-profiling");
4110e5dd7070Spatrick 
4111e5dd7070Spatrick   // The 'g' groups options involve a somewhat intricate sequence of decisions
4112e5dd7070Spatrick   // about what to pass from the driver to the frontend, but by the time they
4113e5dd7070Spatrick   // reach cc1 they've been factored into three well-defined orthogonal choices:
4114e5dd7070Spatrick   //  * what level of debug info to generate
4115e5dd7070Spatrick   //  * what dwarf version to write
4116e5dd7070Spatrick   //  * what debugger tuning to use
4117e5dd7070Spatrick   // This avoids having to monkey around further in cc1 other than to disable
4118e5dd7070Spatrick   // codeview if not running in a Windows environment. Perhaps even that
4119e5dd7070Spatrick   // decision should be made in the driver as well though.
4120e5dd7070Spatrick   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4121e5dd7070Spatrick 
4122e5dd7070Spatrick   bool SplitDWARFInlining =
4123e5dd7070Spatrick       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4124e5dd7070Spatrick                    options::OPT_fno_split_dwarf_inlining, false);
4125e5dd7070Spatrick 
4126a0747c9fSpatrick   // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4127a0747c9fSpatrick   // object file generation and no IR generation, -gN should not be needed. So
4128a0747c9fSpatrick   // allow -gsplit-dwarf with either -gN or IR input.
4129a0747c9fSpatrick   if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4130e5dd7070Spatrick     Arg *SplitDWARFArg;
4131e5dd7070Spatrick     DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4132e5dd7070Spatrick     if (DwarfFission != DwarfFissionKind::None &&
4133e5dd7070Spatrick         !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4134e5dd7070Spatrick       DwarfFission = DwarfFissionKind::None;
4135e5dd7070Spatrick       SplitDWARFInlining = false;
4136e5dd7070Spatrick     }
4137a0747c9fSpatrick   }
4138a0747c9fSpatrick   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4139a0747c9fSpatrick     DebugInfoKind = codegenoptions::DebugInfoConstructor;
4140e5dd7070Spatrick 
4141e5dd7070Spatrick     // If the last option explicitly specified a debug-info level, use it.
4142e5dd7070Spatrick     if (checkDebugInfoOption(A, Args, D, TC) &&
4143e5dd7070Spatrick         A->getOption().matches(options::OPT_gN_Group)) {
4144e5dd7070Spatrick       DebugInfoKind = DebugLevelToInfoKind(*A);
4145e5dd7070Spatrick       // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4146e5dd7070Spatrick       // complicated if you've disabled inline info in the skeleton CUs
4147e5dd7070Spatrick       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4148e5dd7070Spatrick       // line-tables-only, so let those compose naturally in that case.
4149e5dd7070Spatrick       if (DebugInfoKind == codegenoptions::NoDebugInfo ||
4150e5dd7070Spatrick           DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
4151e5dd7070Spatrick           (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
4152e5dd7070Spatrick            SplitDWARFInlining))
4153e5dd7070Spatrick         DwarfFission = DwarfFissionKind::None;
4154e5dd7070Spatrick     }
4155e5dd7070Spatrick   }
4156e5dd7070Spatrick 
4157e5dd7070Spatrick   // If a debugger tuning argument appeared, remember it.
41587a9b00ceSrobert   bool HasDebuggerTuning = false;
4159e5dd7070Spatrick   if (const Arg *A =
4160e5dd7070Spatrick           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
41617a9b00ceSrobert     HasDebuggerTuning = true;
4162e5dd7070Spatrick     if (checkDebugInfoOption(A, Args, D, TC)) {
4163e5dd7070Spatrick       if (A->getOption().matches(options::OPT_glldb))
4164e5dd7070Spatrick         DebuggerTuning = llvm::DebuggerKind::LLDB;
4165e5dd7070Spatrick       else if (A->getOption().matches(options::OPT_gsce))
4166e5dd7070Spatrick         DebuggerTuning = llvm::DebuggerKind::SCE;
4167a0747c9fSpatrick       else if (A->getOption().matches(options::OPT_gdbx))
4168a0747c9fSpatrick         DebuggerTuning = llvm::DebuggerKind::DBX;
4169e5dd7070Spatrick       else
4170e5dd7070Spatrick         DebuggerTuning = llvm::DebuggerKind::GDB;
4171e5dd7070Spatrick     }
4172e5dd7070Spatrick   }
4173e5dd7070Spatrick 
4174e5dd7070Spatrick   // If a -gdwarf argument appeared, remember it.
4175e5dd7070Spatrick   bool EmitDwarf = false;
41767a9b00ceSrobert   if (const Arg *A = getDwarfNArg(Args))
41777a9b00ceSrobert     EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4178e5dd7070Spatrick 
41797a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
41807a9b00ceSrobert     EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4181e5dd7070Spatrick 
4182e5dd7070Spatrick   // If the user asked for debug info but did not explicitly specify -gcodeview
4183e5dd7070Spatrick   // or -gdwarf, ask the toolchain for the default format.
4184e5dd7070Spatrick   if (!EmitCodeView && !EmitDwarf &&
4185e5dd7070Spatrick       DebugInfoKind != codegenoptions::NoDebugInfo) {
4186e5dd7070Spatrick     switch (TC.getDefaultDebugFormat()) {
4187e5dd7070Spatrick     case codegenoptions::DIF_CodeView:
4188e5dd7070Spatrick       EmitCodeView = true;
4189e5dd7070Spatrick       break;
4190e5dd7070Spatrick     case codegenoptions::DIF_DWARF:
4191e5dd7070Spatrick       EmitDwarf = true;
4192e5dd7070Spatrick       break;
4193e5dd7070Spatrick     }
4194e5dd7070Spatrick   }
4195e5dd7070Spatrick 
4196a0747c9fSpatrick   unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4197a0747c9fSpatrick   unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4198a0747c9fSpatrick                                       // be lower than what the user wanted.
4199e5dd7070Spatrick   if (EmitDwarf) {
42007a9b00ceSrobert     RequestedDWARFVersion = getDwarfVersion(TC, Args);
4201a0747c9fSpatrick     // Clamp effective DWARF version to the max supported by the toolchain.
4202a0747c9fSpatrick     EffectiveDWARFVersion =
4203a0747c9fSpatrick         std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
42047a9b00ceSrobert   } else {
42057a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4206e5dd7070Spatrick   }
4207e5dd7070Spatrick 
4208e5dd7070Spatrick   // -gline-directives-only supported only for the DWARF debug info.
4209a0747c9fSpatrick   if (RequestedDWARFVersion == 0 &&
4210a0747c9fSpatrick       DebugInfoKind == codegenoptions::DebugDirectivesOnly)
4211e5dd7070Spatrick     DebugInfoKind = codegenoptions::NoDebugInfo;
4212e5dd7070Spatrick 
4213a0747c9fSpatrick   // strict DWARF is set to false by default. But for DBX, we need it to be set
4214a0747c9fSpatrick   // as true by default.
4215a0747c9fSpatrick   if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4216a0747c9fSpatrick     (void)checkDebugInfoOption(A, Args, D, TC);
4217a0747c9fSpatrick   if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4218a0747c9fSpatrick                    DebuggerTuning == llvm::DebuggerKind::DBX))
4219a0747c9fSpatrick     CmdArgs.push_back("-gstrict-dwarf");
4220a0747c9fSpatrick 
4221e5dd7070Spatrick   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4222e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4223e5dd7070Spatrick 
4224e5dd7070Spatrick   // Column info is included by default for everything except SCE and
4225e5dd7070Spatrick   // CodeView. Clang doesn't track end columns, just starting columns, which,
4226e5dd7070Spatrick   // in theory, is fine for CodeView (and PDB).  In practice, however, the
4227a0747c9fSpatrick   // Microsoft debuggers don't handle missing end columns well, and the AIX
4228a0747c9fSpatrick   // debugger DBX also doesn't handle the columns well, so it's better not to
4229a0747c9fSpatrick   // include any column info.
4230e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4231e5dd7070Spatrick     (void)checkDebugInfoOption(A, Args, D, TC);
4232adae0cfdSpatrick   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4233a0747c9fSpatrick                     !EmitCodeView &&
4234a0747c9fSpatrick                         (DebuggerTuning != llvm::DebuggerKind::SCE &&
4235a0747c9fSpatrick                          DebuggerTuning != llvm::DebuggerKind::DBX)))
4236adae0cfdSpatrick     CmdArgs.push_back("-gno-column-info");
4237e5dd7070Spatrick 
4238e5dd7070Spatrick   // FIXME: Move backend command line options to the module.
42397a9b00ceSrobert   if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
42407a9b00ceSrobert     // If -gline-tables-only or -gline-directives-only is the last option it
42417a9b00ceSrobert     // wins.
42427a9b00ceSrobert     if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
42437a9b00ceSrobert                              TC)) {
4244e5dd7070Spatrick       if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
4245e5dd7070Spatrick           DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
4246a0747c9fSpatrick         DebugInfoKind = codegenoptions::DebugInfoConstructor;
4247e5dd7070Spatrick         CmdArgs.push_back("-dwarf-ext-refs");
4248e5dd7070Spatrick         CmdArgs.push_back("-fmodule-format=obj");
4249e5dd7070Spatrick       }
4250e5dd7070Spatrick     }
42517a9b00ceSrobert   }
4252e5dd7070Spatrick 
4253a0747c9fSpatrick   if (T.isOSBinFormatELF() && SplitDWARFInlining)
4254a0747c9fSpatrick     CmdArgs.push_back("-fsplit-dwarf-inlining");
4255e5dd7070Spatrick 
4256e5dd7070Spatrick   // After we've dealt with all combinations of things that could
4257e5dd7070Spatrick   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4258e5dd7070Spatrick   // figure out if we need to "upgrade" it to standalone debug info.
4259e5dd7070Spatrick   // We parse these two '-f' options whether or not they will be used,
4260e5dd7070Spatrick   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4261e5dd7070Spatrick   bool NeedFullDebug = Args.hasFlag(
4262e5dd7070Spatrick       options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4263e5dd7070Spatrick       DebuggerTuning == llvm::DebuggerKind::LLDB ||
4264e5dd7070Spatrick           TC.GetDefaultStandaloneDebug());
4265e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4266e5dd7070Spatrick     (void)checkDebugInfoOption(A, Args, D, TC);
4267a0747c9fSpatrick 
4268a0747c9fSpatrick   if (DebugInfoKind == codegenoptions::LimitedDebugInfo ||
4269a0747c9fSpatrick       DebugInfoKind == codegenoptions::DebugInfoConstructor) {
4270a0747c9fSpatrick     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4271a0747c9fSpatrick                      options::OPT_feliminate_unused_debug_types, false))
4272a0747c9fSpatrick       DebugInfoKind = codegenoptions::UnusedTypeInfo;
4273a0747c9fSpatrick     else if (NeedFullDebug)
4274e5dd7070Spatrick       DebugInfoKind = codegenoptions::FullDebugInfo;
4275a0747c9fSpatrick   }
4276e5dd7070Spatrick 
4277e5dd7070Spatrick   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4278e5dd7070Spatrick                    false)) {
4279e5dd7070Spatrick     // Source embedding is a vendor extension to DWARF v5. By now we have
4280e5dd7070Spatrick     // checked if a DWARF version was stated explicitly, and have otherwise
4281e5dd7070Spatrick     // fallen back to the target default, so if this is still not at least 5
4282e5dd7070Spatrick     // we emit an error.
4283e5dd7070Spatrick     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4284a0747c9fSpatrick     if (RequestedDWARFVersion < 5)
4285e5dd7070Spatrick       D.Diag(diag::err_drv_argument_only_allowed_with)
4286e5dd7070Spatrick           << A->getAsString(Args) << "-gdwarf-5";
4287a0747c9fSpatrick     else if (EffectiveDWARFVersion < 5)
4288a0747c9fSpatrick       // The toolchain has reduced allowed dwarf version, so we can't enable
4289a0747c9fSpatrick       // -gembed-source.
4290a0747c9fSpatrick       D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4291a0747c9fSpatrick           << A->getAsString(Args) << TC.getTripleString() << 5
4292a0747c9fSpatrick           << EffectiveDWARFVersion;
4293e5dd7070Spatrick     else if (checkDebugInfoOption(A, Args, D, TC))
4294e5dd7070Spatrick       CmdArgs.push_back("-gembed-source");
4295e5dd7070Spatrick   }
4296e5dd7070Spatrick 
4297e5dd7070Spatrick   if (EmitCodeView) {
4298e5dd7070Spatrick     CmdArgs.push_back("-gcodeview");
4299e5dd7070Spatrick 
43007a9b00ceSrobert     Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
43017a9b00ceSrobert                       options::OPT_gno_codeview_ghash);
43027a9b00ceSrobert 
43037a9b00ceSrobert     Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
43047a9b00ceSrobert                        options::OPT_gno_codeview_command_line);
4305e5dd7070Spatrick   }
4306e5dd7070Spatrick 
43077a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
43087a9b00ceSrobert                      options::OPT_gno_inline_line_tables);
4309e5dd7070Spatrick 
4310e5dd7070Spatrick   // When emitting remarks, we need at least debug lines in the output.
4311e5dd7070Spatrick   if (willEmitRemarks(Args) &&
4312e5dd7070Spatrick       DebugInfoKind <= codegenoptions::DebugDirectivesOnly)
4313e5dd7070Spatrick     DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4314e5dd7070Spatrick 
4315a0747c9fSpatrick   // Adjust the debug info kind for the given toolchain.
4316a0747c9fSpatrick   TC.adjustDebugInfoKind(DebugInfoKind, Args);
4317a0747c9fSpatrick 
43187a9b00ceSrobert   // On AIX, the debugger tuning option can be omitted if it is not explicitly
43197a9b00ceSrobert   // set.
4320a0747c9fSpatrick   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
43217a9b00ceSrobert                           T.isOSAIX() && !HasDebuggerTuning
43227a9b00ceSrobert                               ? llvm::DebuggerKind::Default
43237a9b00ceSrobert                               : DebuggerTuning);
4324e5dd7070Spatrick 
4325e5dd7070Spatrick   // -fdebug-macro turns on macro debug info generation.
4326e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4327e5dd7070Spatrick                    false))
4328e5dd7070Spatrick     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4329e5dd7070Spatrick                              D, TC))
4330e5dd7070Spatrick       CmdArgs.push_back("-debug-info-macro");
4331e5dd7070Spatrick 
4332e5dd7070Spatrick   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4333e5dd7070Spatrick   const auto *PubnamesArg =
4334e5dd7070Spatrick       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4335e5dd7070Spatrick                       options::OPT_gpubnames, options::OPT_gno_pubnames);
4336e5dd7070Spatrick   if (DwarfFission != DwarfFissionKind::None ||
4337e5dd7070Spatrick       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4338e5dd7070Spatrick     if (!PubnamesArg ||
4339e5dd7070Spatrick         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4340e5dd7070Spatrick          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4341e5dd7070Spatrick       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4342e5dd7070Spatrick                                            options::OPT_gpubnames)
4343e5dd7070Spatrick                             ? "-gpubnames"
4344e5dd7070Spatrick                             : "-ggnu-pubnames");
43457a9b00ceSrobert   const auto *SimpleTemplateNamesArg =
43467a9b00ceSrobert       Args.getLastArg(options::OPT_gsimple_template_names,
43477a9b00ceSrobert                       options::OPT_gno_simple_template_names);
43487a9b00ceSrobert   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
43497a9b00ceSrobert   if (SimpleTemplateNamesArg &&
43507a9b00ceSrobert       checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
43517a9b00ceSrobert     const auto &Opt = SimpleTemplateNamesArg->getOption();
43527a9b00ceSrobert     if (Opt.matches(options::OPT_gsimple_template_names)) {
43537a9b00ceSrobert       ForwardTemplateParams = true;
43547a9b00ceSrobert       CmdArgs.push_back("-gsimple-template-names=simple");
4355e5dd7070Spatrick     }
43567a9b00ceSrobert   }
43577a9b00ceSrobert 
43587a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
43597a9b00ceSrobert     StringRef v = A->getValue();
43607a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
43617a9b00ceSrobert   }
43627a9b00ceSrobert 
43637a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
43647a9b00ceSrobert                     options::OPT_fno_debug_ranges_base_address);
4365e5dd7070Spatrick 
4366e5dd7070Spatrick   // -gdwarf-aranges turns on the emission of the aranges section in the
4367e5dd7070Spatrick   // backend.
4368e5dd7070Spatrick   // Always enabled for SCE tuning.
4369e5dd7070Spatrick   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4370e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4371e5dd7070Spatrick     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4372e5dd7070Spatrick   if (NeedAranges) {
4373e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
4374e5dd7070Spatrick     CmdArgs.push_back("-generate-arange-section");
4375e5dd7070Spatrick   }
4376e5dd7070Spatrick 
43777a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
43787a9b00ceSrobert                     options::OPT_fno_force_dwarf_frame);
4379e5dd7070Spatrick 
4380e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fdebug_types_section,
4381e5dd7070Spatrick                    options::OPT_fno_debug_types_section, false)) {
4382a0747c9fSpatrick     if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4383e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
4384e5dd7070Spatrick           << Args.getLastArg(options::OPT_fdebug_types_section)
4385e5dd7070Spatrick                  ->getAsString(Args)
4386e5dd7070Spatrick           << T.getTriple();
4387e5dd7070Spatrick     } else if (checkDebugInfoOption(
4388e5dd7070Spatrick                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4389e5dd7070Spatrick                    TC)) {
4390e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
4391e5dd7070Spatrick       CmdArgs.push_back("-generate-type-units");
4392e5dd7070Spatrick     }
4393e5dd7070Spatrick   }
4394e5dd7070Spatrick 
4395a0747c9fSpatrick   // To avoid join/split of directory+filename, the integrated assembler prefers
4396a0747c9fSpatrick   // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4397a0747c9fSpatrick   // form before DWARF v5.
4398a0747c9fSpatrick   if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4399a0747c9fSpatrick                     options::OPT_fno_dwarf_directory_asm,
4400a0747c9fSpatrick                     TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4401a0747c9fSpatrick     CmdArgs.push_back("-fno-dwarf-directory-asm");
4402a0747c9fSpatrick 
4403e5dd7070Spatrick   // Decide how to render forward declarations of template instantiations.
4404e5dd7070Spatrick   // SCE wants full descriptions, others just get them in the name.
44057a9b00ceSrobert   if (ForwardTemplateParams)
4406e5dd7070Spatrick     CmdArgs.push_back("-debug-forward-template-params");
4407e5dd7070Spatrick 
4408e5dd7070Spatrick   // Do we need to explicitly import anonymous namespaces into the parent
4409e5dd7070Spatrick   // scope?
4410e5dd7070Spatrick   if (DebuggerTuning == llvm::DebuggerKind::SCE)
4411e5dd7070Spatrick     CmdArgs.push_back("-dwarf-explicit-import");
4412e5dd7070Spatrick 
4413a0747c9fSpatrick   renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4414e5dd7070Spatrick   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4415e5dd7070Spatrick }
4416e5dd7070Spatrick 
ProcessVSRuntimeLibrary(const ArgList & Args,ArgStringList & CmdArgs)44177a9b00ceSrobert static void ProcessVSRuntimeLibrary(const ArgList &Args,
44187a9b00ceSrobert                                     ArgStringList &CmdArgs) {
44197a9b00ceSrobert   unsigned RTOptionID = options::OPT__SLASH_MT;
44207a9b00ceSrobert 
44217a9b00ceSrobert   if (Args.hasArg(options::OPT__SLASH_LDd))
44227a9b00ceSrobert     // The /LDd option implies /MTd. The dependent lib part can be overridden,
44237a9b00ceSrobert     // but defining _DEBUG is sticky.
44247a9b00ceSrobert     RTOptionID = options::OPT__SLASH_MTd;
44257a9b00ceSrobert 
44267a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
44277a9b00ceSrobert     RTOptionID = A->getOption().getID();
44287a9b00ceSrobert 
44297a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
44307a9b00ceSrobert     RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
44317a9b00ceSrobert                      .Case("static", options::OPT__SLASH_MT)
44327a9b00ceSrobert                      .Case("static_dbg", options::OPT__SLASH_MTd)
44337a9b00ceSrobert                      .Case("dll", options::OPT__SLASH_MD)
44347a9b00ceSrobert                      .Case("dll_dbg", options::OPT__SLASH_MDd)
44357a9b00ceSrobert                      .Default(options::OPT__SLASH_MT);
44367a9b00ceSrobert   }
44377a9b00ceSrobert 
44387a9b00ceSrobert   StringRef FlagForCRT;
44397a9b00ceSrobert   switch (RTOptionID) {
44407a9b00ceSrobert   case options::OPT__SLASH_MD:
44417a9b00ceSrobert     if (Args.hasArg(options::OPT__SLASH_LDd))
44427a9b00ceSrobert       CmdArgs.push_back("-D_DEBUG");
44437a9b00ceSrobert     CmdArgs.push_back("-D_MT");
44447a9b00ceSrobert     CmdArgs.push_back("-D_DLL");
44457a9b00ceSrobert     FlagForCRT = "--dependent-lib=msvcrt";
44467a9b00ceSrobert     break;
44477a9b00ceSrobert   case options::OPT__SLASH_MDd:
44487a9b00ceSrobert     CmdArgs.push_back("-D_DEBUG");
44497a9b00ceSrobert     CmdArgs.push_back("-D_MT");
44507a9b00ceSrobert     CmdArgs.push_back("-D_DLL");
44517a9b00ceSrobert     FlagForCRT = "--dependent-lib=msvcrtd";
44527a9b00ceSrobert     break;
44537a9b00ceSrobert   case options::OPT__SLASH_MT:
44547a9b00ceSrobert     if (Args.hasArg(options::OPT__SLASH_LDd))
44557a9b00ceSrobert       CmdArgs.push_back("-D_DEBUG");
44567a9b00ceSrobert     CmdArgs.push_back("-D_MT");
44577a9b00ceSrobert     CmdArgs.push_back("-flto-visibility-public-std");
44587a9b00ceSrobert     FlagForCRT = "--dependent-lib=libcmt";
44597a9b00ceSrobert     break;
44607a9b00ceSrobert   case options::OPT__SLASH_MTd:
44617a9b00ceSrobert     CmdArgs.push_back("-D_DEBUG");
44627a9b00ceSrobert     CmdArgs.push_back("-D_MT");
44637a9b00ceSrobert     CmdArgs.push_back("-flto-visibility-public-std");
44647a9b00ceSrobert     FlagForCRT = "--dependent-lib=libcmtd";
44657a9b00ceSrobert     break;
44667a9b00ceSrobert   default:
44677a9b00ceSrobert     llvm_unreachable("Unexpected option ID.");
44687a9b00ceSrobert   }
44697a9b00ceSrobert 
44707a9b00ceSrobert   if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
44717a9b00ceSrobert     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
44727a9b00ceSrobert   } else {
44737a9b00ceSrobert     CmdArgs.push_back(FlagForCRT.data());
44747a9b00ceSrobert 
44757a9b00ceSrobert     // This provides POSIX compatibility (maps 'open' to '_open'), which most
44767a9b00ceSrobert     // users want.  The /Za flag to cl.exe turns this off, but it's not
44777a9b00ceSrobert     // implemented in clang.
44787a9b00ceSrobert     CmdArgs.push_back("--dependent-lib=oldnames");
44797a9b00ceSrobert   }
44807a9b00ceSrobert }
44817a9b00ceSrobert 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4482e5dd7070Spatrick void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4483e5dd7070Spatrick                          const InputInfo &Output, const InputInfoList &Inputs,
4484e5dd7070Spatrick                          const ArgList &Args, const char *LinkingOutput) const {
4485e5dd7070Spatrick   const auto &TC = getToolChain();
4486e5dd7070Spatrick   const llvm::Triple &RawTriple = TC.getTriple();
4487e5dd7070Spatrick   const llvm::Triple &Triple = TC.getEffectiveTriple();
4488e5dd7070Spatrick   const std::string &TripleStr = Triple.getTriple();
4489e5dd7070Spatrick 
4490e5dd7070Spatrick   bool KernelOrKext =
4491e5dd7070Spatrick       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4492e5dd7070Spatrick   const Driver &D = TC.getDriver();
4493e5dd7070Spatrick   ArgStringList CmdArgs;
4494e5dd7070Spatrick 
4495e5dd7070Spatrick   assert(Inputs.size() >= 1 && "Must have at least one input.");
4496e5dd7070Spatrick   // CUDA/HIP compilation may have multiple inputs (source file + results of
4497e5dd7070Spatrick   // device-side compilations). OpenMP device jobs also take the host IR as a
4498e5dd7070Spatrick   // second input. Module precompilation accepts a list of header files to
44997a9b00ceSrobert   // include as part of the module. API extraction accepts a list of header
45007a9b00ceSrobert   // files whose API information is emitted in the output. All other jobs are
45017a9b00ceSrobert   // expected to have exactly one input.
4502e5dd7070Spatrick   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4503a0747c9fSpatrick   bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4504e5dd7070Spatrick   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4505a0747c9fSpatrick   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4506e5dd7070Spatrick   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
45077a9b00ceSrobert   bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4508a0747c9fSpatrick   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4509a0747c9fSpatrick                                  JA.isDeviceOffloading(Action::OFK_Host));
45107a9b00ceSrobert   bool IsHostOffloadingAction =
45117a9b00ceSrobert       JA.isHostOffloading(Action::OFK_OpenMP) ||
45127a9b00ceSrobert       (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
45137a9b00ceSrobert        Args.hasFlag(options::OPT_offload_new_driver,
45147a9b00ceSrobert                     options::OPT_no_offload_new_driver, false));
45157a9b00ceSrobert 
45167a9b00ceSrobert   bool IsRDCMode =
45177a9b00ceSrobert       Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4518a0747c9fSpatrick   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4519a0747c9fSpatrick   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4520e5dd7070Spatrick 
45217a9b00ceSrobert   // Extract API doesn't have a main input file, so invent a fake one as a
45227a9b00ceSrobert   // placeholder.
45237a9b00ceSrobert   InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
45247a9b00ceSrobert                                        "extract-api");
4525e5dd7070Spatrick 
4526e5dd7070Spatrick   const InputInfo &Input =
45277a9b00ceSrobert       IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4528e5dd7070Spatrick 
45297a9b00ceSrobert   InputInfoList ExtractAPIInputs;
45307a9b00ceSrobert   InputInfoList HostOffloadingInputs;
4531e5dd7070Spatrick   const InputInfo *CudaDeviceInput = nullptr;
4532e5dd7070Spatrick   const InputInfo *OpenMPDeviceInput = nullptr;
4533e5dd7070Spatrick   for (const InputInfo &I : Inputs) {
45347a9b00ceSrobert     if (&I == &Input || I.getType() == types::TY_Nothing) {
45357a9b00ceSrobert       // This is the primary input or contains nothing.
45367a9b00ceSrobert     } else if (IsExtractAPI) {
45377a9b00ceSrobert       auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
45387a9b00ceSrobert       if (I.getType() != ExpectedInputType) {
45397a9b00ceSrobert         D.Diag(diag::err_drv_extract_api_wrong_kind)
4540e5dd7070Spatrick             << I.getFilename() << types::getTypeName(I.getType())
45417a9b00ceSrobert             << types::getTypeName(ExpectedInputType);
4542e5dd7070Spatrick       }
45437a9b00ceSrobert       ExtractAPIInputs.push_back(I);
45447a9b00ceSrobert     } else if (IsHostOffloadingAction) {
45457a9b00ceSrobert       HostOffloadingInputs.push_back(I);
4546e5dd7070Spatrick     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4547e5dd7070Spatrick       CudaDeviceInput = &I;
4548e5dd7070Spatrick     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4549e5dd7070Spatrick       OpenMPDeviceInput = &I;
4550e5dd7070Spatrick     } else {
4551e5dd7070Spatrick       llvm_unreachable("unexpectedly given multiple inputs");
4552e5dd7070Spatrick     }
4553e5dd7070Spatrick   }
4554e5dd7070Spatrick 
4555adae0cfdSpatrick   const llvm::Triple *AuxTriple =
4556adae0cfdSpatrick       (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4557e5dd7070Spatrick   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4558e5dd7070Spatrick   bool IsIAMCU = RawTriple.isOSIAMCU();
4559e5dd7070Spatrick 
4560e5dd7070Spatrick   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
4561e5dd7070Spatrick   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4562e5dd7070Spatrick   // Windows), we need to pass Windows-specific flags to cc1.
4563e5dd7070Spatrick   if (IsCuda || IsHIP)
4564e5dd7070Spatrick     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4565e5dd7070Spatrick 
4566e5dd7070Spatrick   // C++ is not supported for IAMCU.
4567e5dd7070Spatrick   if (IsIAMCU && types::isCXX(Input.getType()))
4568e5dd7070Spatrick     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4569e5dd7070Spatrick 
4570e5dd7070Spatrick   // Invoke ourselves in -cc1 mode.
4571e5dd7070Spatrick   //
4572e5dd7070Spatrick   // FIXME: Implement custom jobs for internal actions.
4573e5dd7070Spatrick   CmdArgs.push_back("-cc1");
4574e5dd7070Spatrick 
4575e5dd7070Spatrick   // Add the "effective" target triple.
4576e5dd7070Spatrick   CmdArgs.push_back("-triple");
4577e5dd7070Spatrick   CmdArgs.push_back(Args.MakeArgString(TripleStr));
4578e5dd7070Spatrick 
4579e5dd7070Spatrick   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4580e5dd7070Spatrick     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4581e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_MJ);
4582e5dd7070Spatrick   } else if (const Arg *GenCDBFragment =
4583e5dd7070Spatrick                  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4584e5dd7070Spatrick     DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4585e5dd7070Spatrick                                          TripleStr, Output, Input, Args);
4586e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4587e5dd7070Spatrick   }
4588e5dd7070Spatrick 
4589e5dd7070Spatrick   if (IsCuda || IsHIP) {
4590e5dd7070Spatrick     // We have to pass the triple of the host if compiling for a CUDA/HIP device
4591e5dd7070Spatrick     // and vice-versa.
4592e5dd7070Spatrick     std::string NormalizedTriple;
4593e5dd7070Spatrick     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4594e5dd7070Spatrick         JA.isDeviceOffloading(Action::OFK_HIP))
4595e5dd7070Spatrick       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4596e5dd7070Spatrick                              ->getTriple()
4597e5dd7070Spatrick                              .normalize();
4598e5dd7070Spatrick     else {
4599e5dd7070Spatrick       // Host-side compilation.
4600e5dd7070Spatrick       NormalizedTriple =
4601e5dd7070Spatrick           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4602e5dd7070Spatrick                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4603e5dd7070Spatrick               ->getTriple()
4604e5dd7070Spatrick               .normalize();
4605e5dd7070Spatrick       if (IsCuda) {
4606e5dd7070Spatrick         // We need to figure out which CUDA version we're compiling for, as that
4607e5dd7070Spatrick         // determines how we load and launch GPU kernels.
4608e5dd7070Spatrick         auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4609e5dd7070Spatrick             C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4610e5dd7070Spatrick         assert(CTC && "Expected valid CUDA Toolchain.");
4611e5dd7070Spatrick         if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4612e5dd7070Spatrick           CmdArgs.push_back(Args.MakeArgString(
4613e5dd7070Spatrick               Twine("-target-sdk-version=") +
4614e5dd7070Spatrick               CudaVersionToString(CTC->CudaInstallation.version())));
4615e5dd7070Spatrick       }
4616e5dd7070Spatrick     }
4617e5dd7070Spatrick     CmdArgs.push_back("-aux-triple");
4618e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4619e5dd7070Spatrick   }
4620e5dd7070Spatrick 
4621adae0cfdSpatrick   if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4622adae0cfdSpatrick     CmdArgs.push_back("-fsycl-is-device");
4623adae0cfdSpatrick 
4624adae0cfdSpatrick     if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4625adae0cfdSpatrick       A->render(Args, CmdArgs);
4626adae0cfdSpatrick     } else {
4627a0747c9fSpatrick       // Ensure the default version in SYCL mode is 2020.
4628a0747c9fSpatrick       CmdArgs.push_back("-sycl-std=2020");
4629adae0cfdSpatrick     }
4630adae0cfdSpatrick   }
4631adae0cfdSpatrick 
4632e5dd7070Spatrick   if (IsOpenMPDevice) {
4633e5dd7070Spatrick     // We have to pass the triple of the host if compiling for an OpenMP device.
4634e5dd7070Spatrick     std::string NormalizedTriple =
4635e5dd7070Spatrick         C.getSingleOffloadToolChain<Action::OFK_Host>()
4636e5dd7070Spatrick             ->getTriple()
4637e5dd7070Spatrick             .normalize();
4638e5dd7070Spatrick     CmdArgs.push_back("-aux-triple");
4639e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4640e5dd7070Spatrick   }
4641e5dd7070Spatrick 
4642e5dd7070Spatrick   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4643e5dd7070Spatrick                                Triple.getArch() == llvm::Triple::thumb)) {
4644e5dd7070Spatrick     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4645adae0cfdSpatrick     unsigned Version = 0;
4646adae0cfdSpatrick     bool Failure =
4647adae0cfdSpatrick         Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4648adae0cfdSpatrick     if (Failure || Version < 7)
4649e5dd7070Spatrick       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4650e5dd7070Spatrick                                                 << TripleStr;
4651e5dd7070Spatrick   }
4652e5dd7070Spatrick 
4653e5dd7070Spatrick   // Push all default warning arguments that are specific to
4654e5dd7070Spatrick   // the given target.  These come before user provided warning options
4655e5dd7070Spatrick   // are provided.
4656e5dd7070Spatrick   TC.addClangWarningOptions(CmdArgs);
4657e5dd7070Spatrick 
4658a0747c9fSpatrick   // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
46597a9b00ceSrobert   if (Triple.isSPIR() || Triple.isSPIRV())
4660a0747c9fSpatrick     CmdArgs.push_back("-Wspir-compat");
4661a0747c9fSpatrick 
4662e5dd7070Spatrick   // Select the appropriate action.
4663e5dd7070Spatrick   RewriteKind rewriteKind = RK_None;
4664e5dd7070Spatrick 
4665e5dd7070Spatrick   // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4666e5dd7070Spatrick   // it claims when not running an assembler. Otherwise, clang would emit
4667e5dd7070Spatrick   // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4668e5dd7070Spatrick   // flags while debugging something. That'd be somewhat inconvenient, and it's
4669e5dd7070Spatrick   // also inconsistent with most other flags -- we don't warn on
4670e5dd7070Spatrick   // -ffunction-sections not being used in -E mode either for example, even
4671e5dd7070Spatrick   // though it's not really used either.
4672e5dd7070Spatrick   if (!isa<AssembleJobAction>(JA)) {
4673e5dd7070Spatrick     // The args claimed here should match the args used in
4674e5dd7070Spatrick     // CollectArgsForIntegratedAssembler().
4675e5dd7070Spatrick     if (TC.useIntegratedAs()) {
4676e5dd7070Spatrick       Args.ClaimAllArgs(options::OPT_mrelax_all);
4677e5dd7070Spatrick       Args.ClaimAllArgs(options::OPT_mno_relax_all);
4678e5dd7070Spatrick       Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4679e5dd7070Spatrick       Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4680e5dd7070Spatrick       switch (C.getDefaultToolChain().getArch()) {
4681e5dd7070Spatrick       case llvm::Triple::arm:
4682e5dd7070Spatrick       case llvm::Triple::armeb:
4683e5dd7070Spatrick       case llvm::Triple::thumb:
4684e5dd7070Spatrick       case llvm::Triple::thumbeb:
4685e5dd7070Spatrick         Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4686e5dd7070Spatrick         break;
4687e5dd7070Spatrick       default:
4688e5dd7070Spatrick         break;
4689e5dd7070Spatrick       }
4690e5dd7070Spatrick     }
4691e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4692e5dd7070Spatrick     Args.ClaimAllArgs(options::OPT_Xassembler);
46937a9b00ceSrobert     Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4694e5dd7070Spatrick   }
4695e5dd7070Spatrick 
4696e5dd7070Spatrick   if (isa<AnalyzeJobAction>(JA)) {
4697e5dd7070Spatrick     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4698e5dd7070Spatrick     CmdArgs.push_back("-analyze");
4699e5dd7070Spatrick   } else if (isa<MigrateJobAction>(JA)) {
4700e5dd7070Spatrick     CmdArgs.push_back("-migrate");
4701e5dd7070Spatrick   } else if (isa<PreprocessJobAction>(JA)) {
4702e5dd7070Spatrick     if (Output.getType() == types::TY_Dependencies)
4703e5dd7070Spatrick       CmdArgs.push_back("-Eonly");
4704e5dd7070Spatrick     else {
4705e5dd7070Spatrick       CmdArgs.push_back("-E");
4706e5dd7070Spatrick       if (Args.hasArg(options::OPT_rewrite_objc) &&
4707e5dd7070Spatrick           !Args.hasArg(options::OPT_g_Group))
4708e5dd7070Spatrick         CmdArgs.push_back("-P");
47097a9b00ceSrobert       else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
47107a9b00ceSrobert         CmdArgs.push_back("-fdirectives-only");
4711e5dd7070Spatrick     }
4712e5dd7070Spatrick   } else if (isa<AssembleJobAction>(JA)) {
4713e5dd7070Spatrick     CmdArgs.push_back("-emit-obj");
4714e5dd7070Spatrick 
4715e5dd7070Spatrick     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4716e5dd7070Spatrick 
4717e5dd7070Spatrick     // Also ignore explicit -force_cpusubtype_ALL option.
4718e5dd7070Spatrick     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4719e5dd7070Spatrick   } else if (isa<PrecompileJobAction>(JA)) {
4720e5dd7070Spatrick     if (JA.getType() == types::TY_Nothing)
4721e5dd7070Spatrick       CmdArgs.push_back("-fsyntax-only");
4722e5dd7070Spatrick     else if (JA.getType() == types::TY_ModuleFile)
47237a9b00ceSrobert       CmdArgs.push_back("-emit-module-interface");
47247a9b00ceSrobert     else if (JA.getType() == types::TY_HeaderUnit)
47257a9b00ceSrobert       CmdArgs.push_back("-emit-header-unit");
4726e5dd7070Spatrick     else
4727e5dd7070Spatrick       CmdArgs.push_back("-emit-pch");
4728e5dd7070Spatrick   } else if (isa<VerifyPCHJobAction>(JA)) {
4729e5dd7070Spatrick     CmdArgs.push_back("-verify-pch");
47307a9b00ceSrobert   } else if (isa<ExtractAPIJobAction>(JA)) {
47317a9b00ceSrobert     assert(JA.getType() == types::TY_API_INFO &&
47327a9b00ceSrobert            "Extract API actions must generate a API information.");
47337a9b00ceSrobert     CmdArgs.push_back("-extract-api");
47347a9b00ceSrobert     if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
47357a9b00ceSrobert       ProductNameArg->render(Args, CmdArgs);
47367a9b00ceSrobert     if (Arg *ExtractAPIIgnoresFileArg =
47377a9b00ceSrobert             Args.getLastArg(options::OPT_extract_api_ignores_EQ))
47387a9b00ceSrobert       ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
4739e5dd7070Spatrick   } else {
4740e5dd7070Spatrick     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4741e5dd7070Spatrick            "Invalid action for clang tool.");
4742e5dd7070Spatrick     if (JA.getType() == types::TY_Nothing) {
4743e5dd7070Spatrick       CmdArgs.push_back("-fsyntax-only");
4744e5dd7070Spatrick     } else if (JA.getType() == types::TY_LLVM_IR ||
4745e5dd7070Spatrick                JA.getType() == types::TY_LTO_IR) {
4746e5dd7070Spatrick       CmdArgs.push_back("-emit-llvm");
4747e5dd7070Spatrick     } else if (JA.getType() == types::TY_LLVM_BC ||
4748e5dd7070Spatrick                JA.getType() == types::TY_LTO_BC) {
4749a0747c9fSpatrick       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4750a0747c9fSpatrick       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4751a0747c9fSpatrick           Args.hasArg(options::OPT_emit_llvm)) {
4752a0747c9fSpatrick         CmdArgs.push_back("-emit-llvm");
4753a0747c9fSpatrick       } else {
4754e5dd7070Spatrick         CmdArgs.push_back("-emit-llvm-bc");
4755a0747c9fSpatrick       }
4756e5dd7070Spatrick     } else if (JA.getType() == types::TY_IFS ||
4757e5dd7070Spatrick                JA.getType() == types::TY_IFS_CPP) {
4758e5dd7070Spatrick       StringRef ArgStr =
4759e5dd7070Spatrick           Args.hasArg(options::OPT_interface_stub_version_EQ)
4760e5dd7070Spatrick               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4761a0747c9fSpatrick               : "ifs-v1";
4762e5dd7070Spatrick       CmdArgs.push_back("-emit-interface-stubs");
4763e5dd7070Spatrick       CmdArgs.push_back(
4764e5dd7070Spatrick           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4765e5dd7070Spatrick     } else if (JA.getType() == types::TY_PP_Asm) {
4766e5dd7070Spatrick       CmdArgs.push_back("-S");
4767e5dd7070Spatrick     } else if (JA.getType() == types::TY_AST) {
4768e5dd7070Spatrick       CmdArgs.push_back("-emit-pch");
4769e5dd7070Spatrick     } else if (JA.getType() == types::TY_ModuleFile) {
4770e5dd7070Spatrick       CmdArgs.push_back("-module-file-info");
4771e5dd7070Spatrick     } else if (JA.getType() == types::TY_RewrittenObjC) {
4772e5dd7070Spatrick       CmdArgs.push_back("-rewrite-objc");
4773e5dd7070Spatrick       rewriteKind = RK_NonFragile;
4774e5dd7070Spatrick     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4775e5dd7070Spatrick       CmdArgs.push_back("-rewrite-objc");
4776e5dd7070Spatrick       rewriteKind = RK_Fragile;
4777e5dd7070Spatrick     } else {
4778e5dd7070Spatrick       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4779e5dd7070Spatrick     }
4780e5dd7070Spatrick 
4781e5dd7070Spatrick     // Preserve use-list order by default when emitting bitcode, so that
4782e5dd7070Spatrick     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4783e5dd7070Spatrick     // same result as running passes here.  For LTO, we don't need to preserve
4784e5dd7070Spatrick     // the use-list order, since serialization to bitcode is part of the flow.
4785e5dd7070Spatrick     if (JA.getType() == types::TY_LLVM_BC)
4786e5dd7070Spatrick       CmdArgs.push_back("-emit-llvm-uselists");
4787e5dd7070Spatrick 
4788a0747c9fSpatrick     if (IsUsingLTO) {
47897a9b00ceSrobert       if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
47907a9b00ceSrobert           !Args.hasFlag(options::OPT_offload_new_driver,
47917a9b00ceSrobert                         options::OPT_no_offload_new_driver, false) &&
47927a9b00ceSrobert           !Triple.isAMDGPU()) {
4793a0747c9fSpatrick         D.Diag(diag::err_drv_unsupported_opt_for_target)
4794a0747c9fSpatrick             << Args.getLastArg(options::OPT_foffload_lto,
4795a0747c9fSpatrick                                options::OPT_foffload_lto_EQ)
4796a0747c9fSpatrick                    ->getAsString(Args)
4797a0747c9fSpatrick             << Triple.getTriple();
47987a9b00ceSrobert       } else if (Triple.isNVPTX() && !IsRDCMode &&
47997a9b00ceSrobert                  JA.isDeviceOffloading(Action::OFK_Cuda)) {
48007a9b00ceSrobert         D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
48017a9b00ceSrobert             << Args.getLastArg(options::OPT_foffload_lto,
48027a9b00ceSrobert                                options::OPT_foffload_lto_EQ)
48037a9b00ceSrobert                    ->getAsString(Args)
48047a9b00ceSrobert             << "-fno-gpu-rdc";
48057a9b00ceSrobert       } else {
48067a9b00ceSrobert         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
48077a9b00ceSrobert         CmdArgs.push_back(Args.MakeArgString(
48087a9b00ceSrobert             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
48097a9b00ceSrobert         CmdArgs.push_back("-flto-unit");
4810a0747c9fSpatrick       }
4811e5dd7070Spatrick     }
4812e5dd7070Spatrick   }
4813e5dd7070Spatrick 
4814e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4815e5dd7070Spatrick     if (!types::isLLVMIR(Input.getType()))
4816e5dd7070Spatrick       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4817e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4818e5dd7070Spatrick   }
4819e5dd7070Spatrick 
4820e5dd7070Spatrick   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4821e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4822e5dd7070Spatrick 
4823e5dd7070Spatrick   if (Args.getLastArg(options::OPT_save_temps_EQ))
4824e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4825e5dd7070Spatrick 
4826a0747c9fSpatrick   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4827a0747c9fSpatrick                                      options::OPT_fmemory_profile_EQ,
4828a0747c9fSpatrick                                      options::OPT_fno_memory_profile);
4829a0747c9fSpatrick   if (MemProfArg &&
4830a0747c9fSpatrick       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4831a0747c9fSpatrick     MemProfArg->render(Args, CmdArgs);
4832a0747c9fSpatrick 
4833e5dd7070Spatrick   // Embed-bitcode option.
4834e5dd7070Spatrick   // Only white-listed flags below are allowed to be embedded.
4835a0747c9fSpatrick   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
4836e5dd7070Spatrick       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4837e5dd7070Spatrick     // Add flags implied by -fembed-bitcode.
4838e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4839e5dd7070Spatrick     // Disable all llvm IR level optimizations.
4840e5dd7070Spatrick     CmdArgs.push_back("-disable-llvm-passes");
4841e5dd7070Spatrick 
4842e5dd7070Spatrick     // Render target options.
4843e5dd7070Spatrick     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4844e5dd7070Spatrick 
4845e5dd7070Spatrick     // reject options that shouldn't be supported in bitcode
4846e5dd7070Spatrick     // also reject kernel/kext
48477a9b00ceSrobert     static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
4848e5dd7070Spatrick         options::OPT_mkernel,
4849e5dd7070Spatrick         options::OPT_fapple_kext,
4850e5dd7070Spatrick         options::OPT_ffunction_sections,
4851e5dd7070Spatrick         options::OPT_fno_function_sections,
4852e5dd7070Spatrick         options::OPT_fdata_sections,
4853e5dd7070Spatrick         options::OPT_fno_data_sections,
4854adae0cfdSpatrick         options::OPT_fbasic_block_sections_EQ,
4855adae0cfdSpatrick         options::OPT_funique_internal_linkage_names,
4856adae0cfdSpatrick         options::OPT_fno_unique_internal_linkage_names,
4857e5dd7070Spatrick         options::OPT_funique_section_names,
4858e5dd7070Spatrick         options::OPT_fno_unique_section_names,
4859adae0cfdSpatrick         options::OPT_funique_basic_block_section_names,
4860adae0cfdSpatrick         options::OPT_fno_unique_basic_block_section_names,
4861e5dd7070Spatrick         options::OPT_mrestrict_it,
4862e5dd7070Spatrick         options::OPT_mno_restrict_it,
4863e5dd7070Spatrick         options::OPT_mstackrealign,
4864e5dd7070Spatrick         options::OPT_mno_stackrealign,
4865e5dd7070Spatrick         options::OPT_mstack_alignment,
4866e5dd7070Spatrick         options::OPT_mcmodel_EQ,
4867e5dd7070Spatrick         options::OPT_mlong_calls,
4868e5dd7070Spatrick         options::OPT_mno_long_calls,
4869e5dd7070Spatrick         options::OPT_ggnu_pubnames,
4870e5dd7070Spatrick         options::OPT_gdwarf_aranges,
4871e5dd7070Spatrick         options::OPT_fdebug_types_section,
4872e5dd7070Spatrick         options::OPT_fno_debug_types_section,
4873e5dd7070Spatrick         options::OPT_fdwarf_directory_asm,
4874e5dd7070Spatrick         options::OPT_fno_dwarf_directory_asm,
4875e5dd7070Spatrick         options::OPT_mrelax_all,
4876e5dd7070Spatrick         options::OPT_mno_relax_all,
4877e5dd7070Spatrick         options::OPT_ftrap_function_EQ,
4878e5dd7070Spatrick         options::OPT_ffixed_r9,
4879e5dd7070Spatrick         options::OPT_mfix_cortex_a53_835769,
4880e5dd7070Spatrick         options::OPT_mno_fix_cortex_a53_835769,
4881e5dd7070Spatrick         options::OPT_ffixed_x18,
4882e5dd7070Spatrick         options::OPT_mglobal_merge,
4883e5dd7070Spatrick         options::OPT_mno_global_merge,
4884e5dd7070Spatrick         options::OPT_mred_zone,
4885e5dd7070Spatrick         options::OPT_mno_red_zone,
4886e5dd7070Spatrick         options::OPT_Wa_COMMA,
4887e5dd7070Spatrick         options::OPT_Xassembler,
4888e5dd7070Spatrick         options::OPT_mllvm,
4889e5dd7070Spatrick     };
4890e5dd7070Spatrick     for (const auto &A : Args)
48917a9b00ceSrobert       if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
4892e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
4893e5dd7070Spatrick 
4894e5dd7070Spatrick     // Render the CodeGen options that need to be passed.
48957a9b00ceSrobert     Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
48967a9b00ceSrobert                        options::OPT_fno_optimize_sibling_calls);
4897e5dd7070Spatrick 
4898e5dd7070Spatrick     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
4899adae0cfdSpatrick                                CmdArgs, JA);
4900e5dd7070Spatrick 
4901e5dd7070Spatrick     // Render ABI arguments
4902e5dd7070Spatrick     switch (TC.getArch()) {
4903e5dd7070Spatrick     default: break;
4904e5dd7070Spatrick     case llvm::Triple::arm:
4905e5dd7070Spatrick     case llvm::Triple::armeb:
4906e5dd7070Spatrick     case llvm::Triple::thumbeb:
49077a9b00ceSrobert       RenderARMABI(D, Triple, Args, CmdArgs);
4908e5dd7070Spatrick       break;
4909e5dd7070Spatrick     case llvm::Triple::aarch64:
4910e5dd7070Spatrick     case llvm::Triple::aarch64_32:
4911e5dd7070Spatrick     case llvm::Triple::aarch64_be:
4912e5dd7070Spatrick       RenderAArch64ABI(Triple, Args, CmdArgs);
4913e5dd7070Spatrick       break;
4914e5dd7070Spatrick     }
4915e5dd7070Spatrick 
4916e5dd7070Spatrick     // Optimization level for CodeGen.
4917e5dd7070Spatrick     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4918e5dd7070Spatrick       if (A->getOption().matches(options::OPT_O4)) {
4919e5dd7070Spatrick         CmdArgs.push_back("-O3");
4920e5dd7070Spatrick         D.Diag(diag::warn_O4_is_O3);
4921e5dd7070Spatrick       } else {
4922e5dd7070Spatrick         A->render(Args, CmdArgs);
4923e5dd7070Spatrick       }
4924e5dd7070Spatrick     }
4925e5dd7070Spatrick 
4926e5dd7070Spatrick     // Input/Output file.
4927e5dd7070Spatrick     if (Output.getType() == types::TY_Dependencies) {
4928e5dd7070Spatrick       // Handled with other dependency code.
4929e5dd7070Spatrick     } else if (Output.isFilename()) {
4930e5dd7070Spatrick       CmdArgs.push_back("-o");
4931e5dd7070Spatrick       CmdArgs.push_back(Output.getFilename());
4932e5dd7070Spatrick     } else {
4933e5dd7070Spatrick       assert(Output.isNothing() && "Input output.");
4934e5dd7070Spatrick     }
4935e5dd7070Spatrick 
4936e5dd7070Spatrick     for (const auto &II : Inputs) {
4937e5dd7070Spatrick       addDashXForInput(Args, II, CmdArgs);
4938e5dd7070Spatrick       if (II.isFilename())
4939e5dd7070Spatrick         CmdArgs.push_back(II.getFilename());
4940e5dd7070Spatrick       else
4941e5dd7070Spatrick         II.getInputArg().renderAsInput(Args, CmdArgs);
4942e5dd7070Spatrick     }
4943e5dd7070Spatrick 
4944a0747c9fSpatrick     C.addCommand(std::make_unique<Command>(
4945a0747c9fSpatrick         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
4946a0747c9fSpatrick         CmdArgs, Inputs, Output));
4947e5dd7070Spatrick     return;
4948e5dd7070Spatrick   }
4949e5dd7070Spatrick 
4950a0747c9fSpatrick   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
4951e5dd7070Spatrick     CmdArgs.push_back("-fembed-bitcode=marker");
4952e5dd7070Spatrick 
4953e5dd7070Spatrick   // We normally speed up the clang process a bit by skipping destructors at
4954e5dd7070Spatrick   // exit, but when we're generating diagnostics we can rely on some of the
4955e5dd7070Spatrick   // cleanup.
4956e5dd7070Spatrick   if (!C.isForDiagnostics())
4957e5dd7070Spatrick     CmdArgs.push_back("-disable-free");
49587a9b00ceSrobert   CmdArgs.push_back("-clear-ast-before-backend");
4959e5dd7070Spatrick 
4960e5dd7070Spatrick #ifdef NDEBUG
4961e5dd7070Spatrick   const bool IsAssertBuild = false;
4962e5dd7070Spatrick #else
4963e5dd7070Spatrick   const bool IsAssertBuild = true;
4964e5dd7070Spatrick #endif
4965e5dd7070Spatrick 
4966e5dd7070Spatrick   // Disable the verification pass in -asserts builds.
4967e5dd7070Spatrick   if (!IsAssertBuild)
4968e5dd7070Spatrick     CmdArgs.push_back("-disable-llvm-verifier");
4969e5dd7070Spatrick 
4970e5dd7070Spatrick   // Discard value names in assert builds unless otherwise specified.
4971e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fdiscard_value_names,
4972e5dd7070Spatrick                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
4973e5dd7070Spatrick     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
49747a9b00ceSrobert         llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
4975e5dd7070Spatrick           return types::isLLVMIR(II.getType());
49767a9b00ceSrobert         })) {
4977e5dd7070Spatrick       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
4978e5dd7070Spatrick     }
4979e5dd7070Spatrick     CmdArgs.push_back("-discard-value-names");
4980e5dd7070Spatrick   }
4981e5dd7070Spatrick 
4982e5dd7070Spatrick   // Set the main file name, so that debug info works even with
4983e5dd7070Spatrick   // -save-temps.
4984e5dd7070Spatrick   CmdArgs.push_back("-main-file-name");
4985e5dd7070Spatrick   CmdArgs.push_back(getBaseInputName(Args, Input));
4986e5dd7070Spatrick 
4987e5dd7070Spatrick   // Some flags which affect the language (via preprocessor
4988e5dd7070Spatrick   // defines).
4989e5dd7070Spatrick   if (Args.hasArg(options::OPT_static))
4990e5dd7070Spatrick     CmdArgs.push_back("-static-define");
4991e5dd7070Spatrick 
4992e5dd7070Spatrick   if (Args.hasArg(options::OPT_municode))
4993e5dd7070Spatrick     CmdArgs.push_back("-DUNICODE");
4994e5dd7070Spatrick 
4995e5dd7070Spatrick   if (isa<AnalyzeJobAction>(JA))
4996e5dd7070Spatrick     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
4997e5dd7070Spatrick 
4998e5dd7070Spatrick   if (isa<AnalyzeJobAction>(JA) ||
4999e5dd7070Spatrick       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5000e5dd7070Spatrick     CmdArgs.push_back("-setup-static-analyzer");
5001e5dd7070Spatrick 
5002e5dd7070Spatrick   // Enable compatilibily mode to avoid analyzer-config related errors.
5003e5dd7070Spatrick   // Since we can't access frontend flags through hasArg, let's manually iterate
5004e5dd7070Spatrick   // through them.
5005e5dd7070Spatrick   bool FoundAnalyzerConfig = false;
50067a9b00ceSrobert   for (auto *Arg : Args.filtered(options::OPT_Xclang))
5007e5dd7070Spatrick     if (StringRef(Arg->getValue()) == "-analyzer-config") {
5008e5dd7070Spatrick       FoundAnalyzerConfig = true;
5009e5dd7070Spatrick       break;
5010e5dd7070Spatrick     }
5011e5dd7070Spatrick   if (!FoundAnalyzerConfig)
50127a9b00ceSrobert     for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5013e5dd7070Spatrick       if (StringRef(Arg->getValue()) == "-analyzer-config") {
5014e5dd7070Spatrick         FoundAnalyzerConfig = true;
5015e5dd7070Spatrick         break;
5016e5dd7070Spatrick       }
5017e5dd7070Spatrick   if (FoundAnalyzerConfig)
5018e5dd7070Spatrick     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5019e5dd7070Spatrick 
5020e5dd7070Spatrick   CheckCodeGenerationOptions(D, Args);
5021e5dd7070Spatrick 
5022e5dd7070Spatrick   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5023e5dd7070Spatrick   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5024e5dd7070Spatrick   if (FunctionAlignment) {
5025e5dd7070Spatrick     CmdArgs.push_back("-function-alignment");
5026e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5027e5dd7070Spatrick   }
5028e5dd7070Spatrick 
50297a9b00ceSrobert   // We support -falign-loops=N where N is a power of 2. GCC supports more
50307a9b00ceSrobert   // forms.
50317a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
50327a9b00ceSrobert     unsigned Value = 0;
50337a9b00ceSrobert     if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
50347a9b00ceSrobert       TC.getDriver().Diag(diag::err_drv_invalid_int_value)
50357a9b00ceSrobert           << A->getAsString(Args) << A->getValue();
50367a9b00ceSrobert     else if (Value & (Value - 1))
50377a9b00ceSrobert       TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
50387a9b00ceSrobert           << A->getAsString(Args) << A->getValue();
50397a9b00ceSrobert     // Treat =0 as unspecified (use the target preference).
50407a9b00ceSrobert     if (Value)
50417a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
50427a9b00ceSrobert                                            Twine(std::min(Value, 65536u))));
50437a9b00ceSrobert   }
50447a9b00ceSrobert 
5045e5dd7070Spatrick   llvm::Reloc::Model RelocationModel;
5046e5dd7070Spatrick   unsigned PICLevel;
5047e5dd7070Spatrick   bool IsPIE;
5048e5dd7070Spatrick   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
50497a9b00ceSrobert   Arg *LastPICDataRelArg =
50507a9b00ceSrobert       Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
50517a9b00ceSrobert                       options::OPT_mpic_data_is_text_relative);
50527a9b00ceSrobert   bool NoPICDataIsTextRelative = false;
50537a9b00ceSrobert   if (LastPICDataRelArg) {
50547a9b00ceSrobert     if (LastPICDataRelArg->getOption().matches(
50557a9b00ceSrobert             options::OPT_mno_pic_data_is_text_relative)) {
50567a9b00ceSrobert       NoPICDataIsTextRelative = true;
50577a9b00ceSrobert       if (!PICLevel)
50587a9b00ceSrobert         D.Diag(diag::err_drv_argument_only_allowed_with)
50597a9b00ceSrobert             << "-mno-pic-data-is-text-relative"
50607a9b00ceSrobert             << "-fpic/-fpie";
50617a9b00ceSrobert     }
50627a9b00ceSrobert     if (!Triple.isSystemZ())
50637a9b00ceSrobert       D.Diag(diag::err_drv_unsupported_opt_for_target)
50647a9b00ceSrobert           << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
50657a9b00ceSrobert                                       : "-mpic-data-is-text-relative")
50667a9b00ceSrobert           << RawTriple.str();
50677a9b00ceSrobert   }
5068e5dd7070Spatrick 
5069adae0cfdSpatrick   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5070adae0cfdSpatrick                 RelocationModel == llvm::Reloc::ROPI_RWPI;
5071adae0cfdSpatrick   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5072adae0cfdSpatrick                 RelocationModel == llvm::Reloc::ROPI_RWPI;
5073e5dd7070Spatrick 
5074adae0cfdSpatrick   if (Args.hasArg(options::OPT_mcmse) &&
5075adae0cfdSpatrick       !Args.hasArg(options::OPT_fallow_unsupported)) {
5076adae0cfdSpatrick     if (IsROPI)
5077adae0cfdSpatrick       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5078adae0cfdSpatrick     if (IsRWPI)
5079adae0cfdSpatrick       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5080adae0cfdSpatrick   }
5081adae0cfdSpatrick 
5082adae0cfdSpatrick   if (IsROPI && types::isCXX(Input.getType()) &&
5083e5dd7070Spatrick       !Args.hasArg(options::OPT_fallow_unsupported))
5084e5dd7070Spatrick     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5085e5dd7070Spatrick 
5086adae0cfdSpatrick   const char *RMName = RelocationModelName(RelocationModel);
5087e5dd7070Spatrick   if (RMName) {
5088e5dd7070Spatrick     CmdArgs.push_back("-mrelocation-model");
5089e5dd7070Spatrick     CmdArgs.push_back(RMName);
5090e5dd7070Spatrick   }
5091e5dd7070Spatrick   if (PICLevel > 0) {
5092e5dd7070Spatrick     CmdArgs.push_back("-pic-level");
5093e5dd7070Spatrick     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5094e5dd7070Spatrick     if (IsPIE)
5095e5dd7070Spatrick       CmdArgs.push_back("-pic-is-pie");
50967a9b00ceSrobert     if (NoPICDataIsTextRelative)
50977a9b00ceSrobert       CmdArgs.push_back("-mcmodel=medium");
5098e5dd7070Spatrick   }
5099e5dd7070Spatrick 
5100e5dd7070Spatrick   if (RelocationModel == llvm::Reloc::ROPI ||
5101e5dd7070Spatrick       RelocationModel == llvm::Reloc::ROPI_RWPI)
5102e5dd7070Spatrick     CmdArgs.push_back("-fropi");
5103e5dd7070Spatrick   if (RelocationModel == llvm::Reloc::RWPI ||
5104e5dd7070Spatrick       RelocationModel == llvm::Reloc::ROPI_RWPI)
5105e5dd7070Spatrick     CmdArgs.push_back("-frwpi");
5106e5dd7070Spatrick 
5107e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5108e5dd7070Spatrick     CmdArgs.push_back("-meabi");
5109e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5110e5dd7070Spatrick   }
5111e5dd7070Spatrick 
5112a0747c9fSpatrick   // -fsemantic-interposition is forwarded to CC1: set the
5113a0747c9fSpatrick   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5114a0747c9fSpatrick   // make default visibility external linkage definitions dso_preemptable.
5115a0747c9fSpatrick   //
5116a0747c9fSpatrick   // -fno-semantic-interposition: if the target supports .Lfoo$local local
5117a0747c9fSpatrick   // aliases (make default visibility external linkage definitions dso_local).
5118a0747c9fSpatrick   // This is the CC1 default for ELF to match COFF/Mach-O.
5119a0747c9fSpatrick   //
5120a0747c9fSpatrick   // Otherwise use Clang's traditional behavior: like
5121a0747c9fSpatrick   // -fno-semantic-interposition but local aliases are not used. So references
5122a0747c9fSpatrick   // can be interposed if not optimized out.
5123a0747c9fSpatrick   if (Triple.isOSBinFormatELF()) {
5124a0747c9fSpatrick     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5125a0747c9fSpatrick                              options::OPT_fno_semantic_interposition);
5126a0747c9fSpatrick     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5127a0747c9fSpatrick       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5128a0747c9fSpatrick       bool SupportsLocalAlias =
5129a0747c9fSpatrick           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5130a0747c9fSpatrick       if (!A)
5131a0747c9fSpatrick         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5132a0747c9fSpatrick       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5133adae0cfdSpatrick         A->render(Args, CmdArgs);
5134a0747c9fSpatrick       else if (!SupportsLocalAlias)
5135a0747c9fSpatrick         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5136a0747c9fSpatrick     }
5137a0747c9fSpatrick   }
5138adae0cfdSpatrick 
5139adae0cfdSpatrick   {
5140adae0cfdSpatrick     std::string Model;
5141e5dd7070Spatrick     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5142e5dd7070Spatrick       if (!TC.isThreadModelSupported(A->getValue()))
5143e5dd7070Spatrick         D.Diag(diag::err_drv_invalid_thread_model_for_target)
5144e5dd7070Spatrick             << A->getValue() << A->getAsString(Args);
5145adae0cfdSpatrick       Model = A->getValue();
5146adae0cfdSpatrick     } else
5147adae0cfdSpatrick       Model = TC.getThreadModel();
5148adae0cfdSpatrick     if (Model != "posix") {
5149adae0cfdSpatrick       CmdArgs.push_back("-mthread-model");
5150adae0cfdSpatrick       CmdArgs.push_back(Args.MakeArgString(Model));
5151e5dd7070Spatrick     }
5152adae0cfdSpatrick   }
5153e5dd7070Spatrick 
51547a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
51557a9b00ceSrobert     StringRef Name = A->getValue();
51567a9b00ceSrobert     if (Name == "SVML") {
51577a9b00ceSrobert       if (Triple.getArch() != llvm::Triple::x86 &&
51587a9b00ceSrobert           Triple.getArch() != llvm::Triple::x86_64)
51597a9b00ceSrobert         D.Diag(diag::err_drv_unsupported_opt_for_target)
51607a9b00ceSrobert             << Name << Triple.getArchName();
51617a9b00ceSrobert     } else if (Name == "LIBMVEC-X86") {
51627a9b00ceSrobert       if (Triple.getArch() != llvm::Triple::x86 &&
51637a9b00ceSrobert           Triple.getArch() != llvm::Triple::x86_64)
51647a9b00ceSrobert         D.Diag(diag::err_drv_unsupported_opt_for_target)
51657a9b00ceSrobert             << Name << Triple.getArchName();
51667a9b00ceSrobert     } else if (Name == "SLEEF") {
51677a9b00ceSrobert       if (Triple.getArch() != llvm::Triple::aarch64 &&
51687a9b00ceSrobert           Triple.getArch() != llvm::Triple::aarch64_be)
51697a9b00ceSrobert         D.Diag(diag::err_drv_unsupported_opt_for_target)
51707a9b00ceSrobert             << Name << Triple.getArchName();
51717a9b00ceSrobert     }
51727a9b00ceSrobert     A->render(Args, CmdArgs);
51737a9b00ceSrobert   }
5174e5dd7070Spatrick 
5175e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fmerge_all_constants,
5176e5dd7070Spatrick                    options::OPT_fno_merge_all_constants, false))
5177e5dd7070Spatrick     CmdArgs.push_back("-fmerge-all-constants");
5178e5dd7070Spatrick 
51797a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
51807a9b00ceSrobert                      options::OPT_fno_delete_null_pointer_checks);
5181e5dd7070Spatrick 
5182e5dd7070Spatrick   // LLVM Code Generator Options.
5183e5dd7070Spatrick 
5184a0747c9fSpatrick   for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) {
5185e5dd7070Spatrick     StringRef Map = A->getValue();
5186e5dd7070Spatrick     if (!llvm::sys::fs::exists(Map)) {
5187e5dd7070Spatrick       D.Diag(diag::err_drv_no_such_file) << Map;
5188e5dd7070Spatrick     } else {
5189a0747c9fSpatrick       A->render(Args, CmdArgs);
5190e5dd7070Spatrick       A->claim();
5191e5dd7070Spatrick     }
5192e5dd7070Spatrick   }
5193a0747c9fSpatrick 
5194a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi,
5195a0747c9fSpatrick                                options::OPT_mabi_EQ_vec_default)) {
5196a0747c9fSpatrick     if (!Triple.isOSAIX())
5197a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5198a0747c9fSpatrick           << A->getSpelling() << RawTriple.str();
5199a0747c9fSpatrick     if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi)
5200a0747c9fSpatrick       CmdArgs.push_back("-mabi=vec-extabi");
5201a0747c9fSpatrick     else
5202a0747c9fSpatrick       CmdArgs.push_back("-mabi=vec-default");
5203a0747c9fSpatrick   }
5204a0747c9fSpatrick 
52057a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
52067a9b00ceSrobert     if (!Triple.isOSAIX() || Triple.isPPC32())
52077a9b00ceSrobert       D.Diag(diag::err_drv_unsupported_opt_for_target)
52087a9b00ceSrobert         << A->getSpelling() << RawTriple.str();
52097a9b00ceSrobert     CmdArgs.push_back("-mabi=quadword-atomics");
52107a9b00ceSrobert   }
52117a9b00ceSrobert 
5212a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5213a0747c9fSpatrick     // Emit the unsupported option error until the Clang's library integration
5214a0747c9fSpatrick     // support for 128-bit long double is available for AIX.
5215a0747c9fSpatrick     if (Triple.isOSAIX())
5216a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5217a0747c9fSpatrick           << A->getSpelling() << RawTriple.str();
5218e5dd7070Spatrick   }
5219e5dd7070Spatrick 
5220e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5221e5dd7070Spatrick     StringRef v = A->getValue();
5222a0747c9fSpatrick     // FIXME: Validate the argument here so we don't produce meaningless errors
5223a0747c9fSpatrick     // about -fwarn-stack-size=.
5224a0747c9fSpatrick     if (v.empty())
5225a0747c9fSpatrick       D.Diag(diag::err_drv_missing_argument) << A->getSpelling() << 1;
5226a0747c9fSpatrick     else
5227a0747c9fSpatrick       CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + v));
5228e5dd7070Spatrick     A->claim();
5229e5dd7070Spatrick   }
5230e5dd7070Spatrick 
52317a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
52327a9b00ceSrobert                      options::OPT_fno_jump_tables);
52337a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
52347a9b00ceSrobert                     options::OPT_fno_profile_sample_accurate);
52357a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
52367a9b00ceSrobert                      options::OPT_fno_preserve_as_comments);
5237e5dd7070Spatrick 
5238e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5239e5dd7070Spatrick     CmdArgs.push_back("-mregparm");
5240e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5241e5dd7070Spatrick   }
5242e5dd7070Spatrick 
5243e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5244e5dd7070Spatrick                                options::OPT_msvr4_struct_return)) {
5245a0747c9fSpatrick     if (!TC.getTriple().isPPC32()) {
5246e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5247e5dd7070Spatrick           << A->getSpelling() << RawTriple.str();
5248e5dd7070Spatrick     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5249e5dd7070Spatrick       CmdArgs.push_back("-maix-struct-return");
5250e5dd7070Spatrick     } else {
5251e5dd7070Spatrick       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5252e5dd7070Spatrick       CmdArgs.push_back("-msvr4-struct-return");
5253e5dd7070Spatrick     }
5254e5dd7070Spatrick   }
5255e5dd7070Spatrick 
5256e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5257e5dd7070Spatrick                                options::OPT_freg_struct_return)) {
5258e5dd7070Spatrick     if (TC.getArch() != llvm::Triple::x86) {
5259e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5260e5dd7070Spatrick           << A->getSpelling() << RawTriple.str();
5261e5dd7070Spatrick     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5262e5dd7070Spatrick       CmdArgs.push_back("-fpcc-struct-return");
5263e5dd7070Spatrick     } else {
5264e5dd7070Spatrick       assert(A->getOption().matches(options::OPT_freg_struct_return));
5265e5dd7070Spatrick       CmdArgs.push_back("-freg-struct-return");
5266e5dd7070Spatrick     }
5267e5dd7070Spatrick   }
5268e5dd7070Spatrick 
5269e5dd7070Spatrick   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
5270e5dd7070Spatrick     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5271e5dd7070Spatrick 
5272adae0cfdSpatrick   if (Args.hasArg(options::OPT_fenable_matrix)) {
5273adae0cfdSpatrick     // enable-matrix is needed by both the LangOpts and by LLVM.
5274adae0cfdSpatrick     CmdArgs.push_back("-fenable-matrix");
5275adae0cfdSpatrick     CmdArgs.push_back("-mllvm");
5276adae0cfdSpatrick     CmdArgs.push_back("-enable-matrix");
5277adae0cfdSpatrick   }
5278adae0cfdSpatrick 
5279e5dd7070Spatrick   CodeGenOptions::FramePointerKind FPKeepKind =
5280e5dd7070Spatrick                   getFramePointerKind(Args, RawTriple);
5281e5dd7070Spatrick   const char *FPKeepKindStr = nullptr;
5282e5dd7070Spatrick   switch (FPKeepKind) {
5283e5dd7070Spatrick   case CodeGenOptions::FramePointerKind::None:
5284e5dd7070Spatrick     FPKeepKindStr = "-mframe-pointer=none";
5285e5dd7070Spatrick     break;
5286e5dd7070Spatrick   case CodeGenOptions::FramePointerKind::NonLeaf:
5287e5dd7070Spatrick     FPKeepKindStr = "-mframe-pointer=non-leaf";
5288e5dd7070Spatrick     break;
5289e5dd7070Spatrick   case CodeGenOptions::FramePointerKind::All:
5290e5dd7070Spatrick     FPKeepKindStr = "-mframe-pointer=all";
5291e5dd7070Spatrick     break;
5292e5dd7070Spatrick   }
5293e5dd7070Spatrick   assert(FPKeepKindStr && "unknown FramePointerKind");
5294e5dd7070Spatrick   CmdArgs.push_back(FPKeepKindStr);
5295e5dd7070Spatrick 
52967a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
52977a9b00ceSrobert                      options::OPT_fno_zero_initialized_in_bss);
5298e5dd7070Spatrick 
5299e5dd7070Spatrick   bool OFastEnabled = isOptimizationLevelFast(Args);
5300e5dd7070Spatrick   // If -Ofast is the optimization level, then -fstrict-aliasing should be
5301e5dd7070Spatrick   // enabled.  This alias option is being used to simplify the hasFlag logic.
5302e5dd7070Spatrick   OptSpecifier StrictAliasingAliasOption =
5303e5dd7070Spatrick       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5304e5dd7070Spatrick   // We turn strict aliasing off by default if we're in CL mode, since MSVC
5305e5dd7070Spatrick   // doesn't do any TBAA.
5306e5dd7070Spatrick   bool StrictAliasingDefault = !D.IsCLMode();
5307e5dd7070Spatrick   // We also turn off strict aliasing on OpenBSD.
5308e5dd7070Spatrick   if (getToolChain().getTriple().isOSOpenBSD())
5309e5dd7070Spatrick     StrictAliasingDefault = false;
5310e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5311e5dd7070Spatrick                     options::OPT_fno_strict_aliasing, StrictAliasingDefault))
5312e5dd7070Spatrick     CmdArgs.push_back("-relaxed-aliasing");
5313e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
53147a9b00ceSrobert                     options::OPT_fno_struct_path_tbaa, true))
5315e5dd7070Spatrick     CmdArgs.push_back("-no-struct-path-tbaa");
53167a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
53177a9b00ceSrobert                     options::OPT_fno_strict_enums);
53187a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
53197a9b00ceSrobert                      options::OPT_fno_strict_return);
53207a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
53217a9b00ceSrobert                     options::OPT_fno_allow_editor_placeholders);
53227a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
53237a9b00ceSrobert                     options::OPT_fno_strict_vtable_pointers);
53247a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
53257a9b00ceSrobert                     options::OPT_fno_force_emit_vtables);
53267a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
53277a9b00ceSrobert                      options::OPT_fno_optimize_sibling_calls);
53287a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
53297a9b00ceSrobert                      options::OPT_fno_escaping_block_tail_calls);
5330e5dd7070Spatrick 
5331e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5332e5dd7070Spatrick                   options::OPT_fno_fine_grained_bitfield_accesses);
5333e5dd7070Spatrick 
5334a0747c9fSpatrick   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5335a0747c9fSpatrick                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5336a0747c9fSpatrick 
5337e5dd7070Spatrick   // Handle segmented stacks.
53387a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
53397a9b00ceSrobert                     options::OPT_fno_split_stack);
5340a0747c9fSpatrick 
5341a0747c9fSpatrick   // -fprotect-parens=0 is default.
5342a0747c9fSpatrick   if (Args.hasFlag(options::OPT_fprotect_parens,
5343a0747c9fSpatrick                    options::OPT_fno_protect_parens, false))
5344a0747c9fSpatrick     CmdArgs.push_back("-fprotect-parens");
5345e5dd7070Spatrick 
5346adae0cfdSpatrick   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5347adae0cfdSpatrick 
5348a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5349a0747c9fSpatrick     const llvm::Triple::ArchType Arch = TC.getArch();
5350a0747c9fSpatrick     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5351a0747c9fSpatrick       StringRef V = A->getValue();
5352a0747c9fSpatrick       if (V == "64")
5353a0747c9fSpatrick         CmdArgs.push_back("-fextend-arguments=64");
5354a0747c9fSpatrick       else if (V != "32")
5355a0747c9fSpatrick         D.Diag(diag::err_drv_invalid_argument_to_option)
5356a0747c9fSpatrick             << A->getValue() << A->getOption().getName();
5357a0747c9fSpatrick     } else
5358a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5359a0747c9fSpatrick           << A->getOption().getName() << TripleStr;
5360a0747c9fSpatrick   }
5361a0747c9fSpatrick 
5362adae0cfdSpatrick   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5363adae0cfdSpatrick     if (TC.getArch() == llvm::Triple::avr)
5364adae0cfdSpatrick       A->render(Args, CmdArgs);
5365adae0cfdSpatrick     else
5366adae0cfdSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5367adae0cfdSpatrick           << A->getAsString(Args) << TripleStr;
5368adae0cfdSpatrick   }
5369e5dd7070Spatrick 
5370e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5371e5dd7070Spatrick     if (TC.getTriple().isX86())
5372e5dd7070Spatrick       A->render(Args, CmdArgs);
5373a0747c9fSpatrick     else if (TC.getTriple().isPPC() &&
5374e5dd7070Spatrick              (A->getOption().getID() != options::OPT_mlong_double_80))
5375e5dd7070Spatrick       A->render(Args, CmdArgs);
5376e5dd7070Spatrick     else
5377e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5378e5dd7070Spatrick           << A->getAsString(Args) << TripleStr;
5379e5dd7070Spatrick   }
5380e5dd7070Spatrick 
5381e5dd7070Spatrick   // Decide whether to use verbose asm. Verbose assembly is the default on
5382e5dd7070Spatrick   // toolchains which have the integrated assembler on by default.
5383e5dd7070Spatrick   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5384adae0cfdSpatrick   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5385e5dd7070Spatrick                     IsIntegratedAssemblerDefault))
5386adae0cfdSpatrick     CmdArgs.push_back("-fno-verbose-asm");
5387e5dd7070Spatrick 
5388a0747c9fSpatrick   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5389a0747c9fSpatrick   // use that to indicate the MC default in the backend.
5390a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5391a0747c9fSpatrick     StringRef V = A->getValue();
5392a0747c9fSpatrick     unsigned Num;
5393a0747c9fSpatrick     if (V == "none")
5394a0747c9fSpatrick       A->render(Args, CmdArgs);
5395a0747c9fSpatrick     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5396a0747c9fSpatrick              (V.empty() || (V.consume_front(".") &&
5397a0747c9fSpatrick                             !V.consumeInteger(10, Num) && V.empty())))
5398a0747c9fSpatrick       A->render(Args, CmdArgs);
5399a0747c9fSpatrick     else
5400a0747c9fSpatrick       D.Diag(diag::err_drv_invalid_argument_to_option)
5401a0747c9fSpatrick           << A->getValue() << A->getOption().getName();
5402a0747c9fSpatrick   }
5403a0747c9fSpatrick 
5404a0747c9fSpatrick   // If toolchain choose to use MCAsmParser for inline asm don't pass the
5405a0747c9fSpatrick   // option to disable integrated-as explictly.
5406a0747c9fSpatrick   if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5407e5dd7070Spatrick     CmdArgs.push_back("-no-integrated-as");
5408e5dd7070Spatrick 
5409e5dd7070Spatrick   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5410e5dd7070Spatrick     CmdArgs.push_back("-mdebug-pass");
5411e5dd7070Spatrick     CmdArgs.push_back("Structure");
5412e5dd7070Spatrick   }
5413e5dd7070Spatrick   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5414e5dd7070Spatrick     CmdArgs.push_back("-mdebug-pass");
5415e5dd7070Spatrick     CmdArgs.push_back("Arguments");
5416e5dd7070Spatrick   }
5417e5dd7070Spatrick 
5418e5dd7070Spatrick   // Enable -mconstructor-aliases except on darwin, where we have to work around
54197a9b00ceSrobert   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
54207a9b00ceSrobert   // aliases aren't supported.
54217a9b00ceSrobert   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5422e5dd7070Spatrick     CmdArgs.push_back("-mconstructor-aliases");
5423e5dd7070Spatrick 
5424e5dd7070Spatrick   // Darwin's kernel doesn't support guard variables; just die if we
5425e5dd7070Spatrick   // try to use them.
5426e5dd7070Spatrick   if (KernelOrKext && RawTriple.isOSDarwin())
5427e5dd7070Spatrick     CmdArgs.push_back("-fforbid-guard-variables");
5428e5dd7070Spatrick 
5429e5dd7070Spatrick   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5430adae0cfdSpatrick                    Triple.isWindowsGNUEnvironment())) {
5431e5dd7070Spatrick     CmdArgs.push_back("-mms-bitfields");
5432e5dd7070Spatrick   }
5433e5dd7070Spatrick 
5434a0747c9fSpatrick   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5435a0747c9fSpatrick   // defaults to -fno-direct-access-external-data. Pass the option if different
5436a0747c9fSpatrick   // from the default.
5437a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5438a0747c9fSpatrick                                options::OPT_fno_direct_access_external_data))
5439a0747c9fSpatrick     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5440a0747c9fSpatrick         (PICLevel == 0))
5441a0747c9fSpatrick       A->render(Args, CmdArgs);
5442e5dd7070Spatrick 
5443e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5444e5dd7070Spatrick     CmdArgs.push_back("-fno-plt");
5445e5dd7070Spatrick   }
5446e5dd7070Spatrick 
5447e5dd7070Spatrick   // -fhosted is default.
5448e5dd7070Spatrick   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5449e5dd7070Spatrick   // use Freestanding.
5450e5dd7070Spatrick   bool Freestanding =
5451e5dd7070Spatrick       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5452e5dd7070Spatrick       KernelOrKext;
5453e5dd7070Spatrick   if (Freestanding)
5454e5dd7070Spatrick     CmdArgs.push_back("-ffreestanding");
5455e5dd7070Spatrick 
54567a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
54577a9b00ceSrobert 
5458e5dd7070Spatrick   // This is a coarse approximation of what llvm-gcc actually does, both
5459e5dd7070Spatrick   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5460e5dd7070Spatrick   // complicated ways.
54617a9b00ceSrobert   auto SanitizeArgs = TC.getSanitizerArgs(Args);
54627a9b00ceSrobert 
54637a9b00ceSrobert   bool IsAsyncUnwindTablesDefault =
54647a9b00ceSrobert       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
54657a9b00ceSrobert   bool IsSyncUnwindTablesDefault =
54667a9b00ceSrobert       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
54677a9b00ceSrobert 
54687a9b00ceSrobert   bool AsyncUnwindTables = Args.hasFlag(
54697a9b00ceSrobert       options::OPT_fasynchronous_unwind_tables,
5470e5dd7070Spatrick       options::OPT_fno_asynchronous_unwind_tables,
54717a9b00ceSrobert       (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5472e5dd7070Spatrick           !Freestanding);
54737a9b00ceSrobert   bool UnwindTables =
54747a9b00ceSrobert       Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
54757a9b00ceSrobert                    IsSyncUnwindTablesDefault && !Freestanding);
54767a9b00ceSrobert   if (AsyncUnwindTables)
54777a9b00ceSrobert     CmdArgs.push_back("-funwind-tables=2");
54787a9b00ceSrobert   else if (UnwindTables)
54797a9b00ceSrobert      CmdArgs.push_back("-funwind-tables=1");
5480e5dd7070Spatrick 
5481adae0cfdSpatrick   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5482adae0cfdSpatrick   // `--gpu-use-aux-triple-only` is specified.
5483adae0cfdSpatrick   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5484a0747c9fSpatrick       (IsCudaDevice || IsHIPDevice)) {
5485adae0cfdSpatrick     const ArgList &HostArgs =
5486adae0cfdSpatrick         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5487adae0cfdSpatrick     std::string HostCPU =
54887a9b00ceSrobert         getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5489adae0cfdSpatrick     if (!HostCPU.empty()) {
5490adae0cfdSpatrick       CmdArgs.push_back("-aux-target-cpu");
5491adae0cfdSpatrick       CmdArgs.push_back(Args.MakeArgString(HostCPU));
5492adae0cfdSpatrick     }
5493adae0cfdSpatrick     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5494adae0cfdSpatrick                       /*ForAS*/ false, /*IsAux*/ true);
5495adae0cfdSpatrick   }
5496adae0cfdSpatrick 
5497e5dd7070Spatrick   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5498e5dd7070Spatrick 
5499e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5500adae0cfdSpatrick     StringRef CM = A->getValue();
5501adae0cfdSpatrick     if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
5502a0747c9fSpatrick         CM == "tiny") {
5503a0747c9fSpatrick       if (Triple.isOSAIX() && CM == "medium")
5504a0747c9fSpatrick         CmdArgs.push_back("-mcmodel=large");
55057a9b00ceSrobert       else if (Triple.isAArch64() && (CM == "kernel" || CM == "medium"))
55067a9b00ceSrobert         D.Diag(diag::err_drv_invalid_argument_to_option)
55077a9b00ceSrobert             << CM << A->getOption().getName();
5508adae0cfdSpatrick       else
5509a0747c9fSpatrick         A->render(Args, CmdArgs);
5510a0747c9fSpatrick     } else {
5511adae0cfdSpatrick       D.Diag(diag::err_drv_invalid_argument_to_option)
5512adae0cfdSpatrick           << CM << A->getOption().getName();
5513e5dd7070Spatrick     }
5514a0747c9fSpatrick   }
5515e5dd7070Spatrick 
5516e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5517e5dd7070Spatrick     StringRef Value = A->getValue();
5518e5dd7070Spatrick     unsigned TLSSize = 0;
5519e5dd7070Spatrick     Value.getAsInteger(10, TLSSize);
5520e5dd7070Spatrick     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5521e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5522e5dd7070Spatrick           << A->getOption().getName() << TripleStr;
5523e5dd7070Spatrick     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5524e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_int_value)
5525e5dd7070Spatrick           << A->getOption().getName() << Value;
5526e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5527e5dd7070Spatrick   }
5528e5dd7070Spatrick 
5529e5dd7070Spatrick   // Add the target cpu
55307a9b00ceSrobert   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5531e5dd7070Spatrick   if (!CPU.empty()) {
5532e5dd7070Spatrick     CmdArgs.push_back("-target-cpu");
5533e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(CPU));
5534e5dd7070Spatrick   }
5535e5dd7070Spatrick 
5536e5dd7070Spatrick   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5537e5dd7070Spatrick 
5538a0747c9fSpatrick   // FIXME: For now we want to demote any errors to warnings, when they have
5539a0747c9fSpatrick   // been raised for asking the wrong question of scalable vectors, such as
5540a0747c9fSpatrick   // asking for the fixed number of elements. This may happen because code that
5541a0747c9fSpatrick   // is not yet ported to work for scalable vectors uses the wrong interfaces,
5542a0747c9fSpatrick   // whereas the behaviour is actually correct. Emitting a warning helps bring
5543a0747c9fSpatrick   // up scalable vector support in an incremental way. When scalable vector
5544a0747c9fSpatrick   // support is stable enough, all uses of wrong interfaces should be considered
5545a0747c9fSpatrick   // as errors, but until then, we can live with a warning being emitted by the
5546a0747c9fSpatrick   // compiler. This way, Clang can be used to compile code with scalable vectors
5547a0747c9fSpatrick   // and identify possible issues.
55487a9b00ceSrobert   if (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
55497a9b00ceSrobert       isa<BackendJobAction>(JA)) {
5550a0747c9fSpatrick     CmdArgs.push_back("-mllvm");
5551a0747c9fSpatrick     CmdArgs.push_back("-treat-scalable-fixed-error-as-warning");
5552a0747c9fSpatrick   }
5553a0747c9fSpatrick 
5554e5dd7070Spatrick   // These two are potentially updated by AddClangCLArgs.
5555e5dd7070Spatrick   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5556e5dd7070Spatrick   bool EmitCodeView = false;
5557e5dd7070Spatrick 
5558e5dd7070Spatrick   // Add clang-cl arguments.
5559e5dd7070Spatrick   types::ID InputType = Input.getType();
5560e5dd7070Spatrick   if (D.IsCLMode())
5561e5dd7070Spatrick     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5562e5dd7070Spatrick 
5563a0747c9fSpatrick   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5564a0747c9fSpatrick   renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5565a0747c9fSpatrick                      types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5566a0747c9fSpatrick                      DwarfFission);
5567e5dd7070Spatrick 
55687a9b00ceSrobert   // This controls whether or not we perform JustMyCode instrumentation.
55697a9b00ceSrobert   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
55707a9b00ceSrobert     if (TC.getTriple().isOSBinFormatELF()) {
55717a9b00ceSrobert       if (DebugInfoKind >= codegenoptions::DebugInfoConstructor)
55727a9b00ceSrobert         CmdArgs.push_back("-fjmc");
55737a9b00ceSrobert       else
55747a9b00ceSrobert         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
55757a9b00ceSrobert                                                              << "-g";
55767a9b00ceSrobert     } else {
55777a9b00ceSrobert       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
55787a9b00ceSrobert     }
55797a9b00ceSrobert   }
55807a9b00ceSrobert 
5581e5dd7070Spatrick   // Add the split debug info name to the command lines here so we
5582e5dd7070Spatrick   // can propagate it to the backend.
5583e5dd7070Spatrick   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5584a0747c9fSpatrick                     (TC.getTriple().isOSBinFormatELF() ||
5585a0747c9fSpatrick                      TC.getTriple().isOSBinFormatWasm()) &&
5586e5dd7070Spatrick                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5587e5dd7070Spatrick                      isa<BackendJobAction>(JA));
5588e5dd7070Spatrick   if (SplitDWARF) {
5589a0747c9fSpatrick     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5590e5dd7070Spatrick     CmdArgs.push_back("-split-dwarf-file");
5591e5dd7070Spatrick     CmdArgs.push_back(SplitDWARFOut);
5592e5dd7070Spatrick     if (DwarfFission == DwarfFissionKind::Split) {
5593e5dd7070Spatrick       CmdArgs.push_back("-split-dwarf-output");
5594e5dd7070Spatrick       CmdArgs.push_back(SplitDWARFOut);
5595e5dd7070Spatrick     }
5596e5dd7070Spatrick   }
5597e5dd7070Spatrick 
5598e5dd7070Spatrick   // Pass the linker version in use.
5599e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5600e5dd7070Spatrick     CmdArgs.push_back("-target-linker-version");
5601e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5602e5dd7070Spatrick   }
5603e5dd7070Spatrick 
5604e5dd7070Spatrick   // Explicitly error on some things we know we don't support and can't just
5605e5dd7070Spatrick   // ignore.
5606e5dd7070Spatrick   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5607e5dd7070Spatrick     Arg *Unsupported;
5608e5dd7070Spatrick     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5609e5dd7070Spatrick         TC.getArch() == llvm::Triple::x86) {
5610e5dd7070Spatrick       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5611e5dd7070Spatrick           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5612e5dd7070Spatrick         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5613e5dd7070Spatrick             << Unsupported->getOption().getName();
5614e5dd7070Spatrick     }
5615e5dd7070Spatrick     // The faltivec option has been superseded by the maltivec option.
5616e5dd7070Spatrick     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5617e5dd7070Spatrick       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5618e5dd7070Spatrick           << Unsupported->getOption().getName()
5619e5dd7070Spatrick           << "please use -maltivec and include altivec.h explicitly";
5620e5dd7070Spatrick     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5621e5dd7070Spatrick       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5622e5dd7070Spatrick           << Unsupported->getOption().getName() << "please use -mno-altivec";
5623e5dd7070Spatrick   }
5624e5dd7070Spatrick 
5625e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_v);
5626adae0cfdSpatrick 
5627adae0cfdSpatrick   if (Args.getLastArg(options::OPT_H)) {
5628adae0cfdSpatrick     CmdArgs.push_back("-H");
5629adae0cfdSpatrick     CmdArgs.push_back("-sys-header-deps");
5630adae0cfdSpatrick   }
5631a0747c9fSpatrick   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5632adae0cfdSpatrick 
56337a9b00ceSrobert   if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
5634e5dd7070Spatrick     CmdArgs.push_back("-header-include-file");
5635a0747c9fSpatrick     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5636a0747c9fSpatrick                           ? D.CCPrintHeadersFilename.c_str()
5637e5dd7070Spatrick                           : "-");
5638adae0cfdSpatrick     CmdArgs.push_back("-sys-header-deps");
56397a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(
56407a9b00ceSrobert         "-header-include-format=" +
56417a9b00ceSrobert         std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
56427a9b00ceSrobert     CmdArgs.push_back(
56437a9b00ceSrobert         Args.MakeArgString("-header-include-filtering=" +
56447a9b00ceSrobert                            std::string(headerIncludeFilteringKindToString(
56457a9b00ceSrobert                                D.CCPrintHeadersFiltering))));
5646e5dd7070Spatrick   }
5647e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_P);
5648e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5649e5dd7070Spatrick 
5650e5dd7070Spatrick   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5651e5dd7070Spatrick     CmdArgs.push_back("-diagnostic-log-file");
5652a0747c9fSpatrick     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5653a0747c9fSpatrick                           ? D.CCLogDiagnosticsFilename.c_str()
5654e5dd7070Spatrick                           : "-");
5655e5dd7070Spatrick   }
5656e5dd7070Spatrick 
5657e5dd7070Spatrick   // Give the gen diagnostics more chances to succeed, by avoiding intentional
5658e5dd7070Spatrick   // crashes.
5659e5dd7070Spatrick   if (D.CCGenDiagnostics)
5660e5dd7070Spatrick     CmdArgs.push_back("-disable-pragma-debug-crash");
5661e5dd7070Spatrick 
5662a0747c9fSpatrick   // Allow backend to put its diagnostic files in the same place as frontend
5663a0747c9fSpatrick   // crash diagnostics files.
5664a0747c9fSpatrick   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5665a0747c9fSpatrick     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5666a0747c9fSpatrick     CmdArgs.push_back("-mllvm");
5667a0747c9fSpatrick     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5668a0747c9fSpatrick   }
5669a0747c9fSpatrick 
5670e5dd7070Spatrick   bool UseSeparateSections = isUseSeparateSections(Triple);
5671e5dd7070Spatrick 
5672e5dd7070Spatrick   if (Args.hasFlag(options::OPT_ffunction_sections,
5673e5dd7070Spatrick                    options::OPT_fno_function_sections, UseSeparateSections)) {
5674e5dd7070Spatrick     CmdArgs.push_back("-ffunction-sections");
5675e5dd7070Spatrick   }
5676e5dd7070Spatrick 
5677adae0cfdSpatrick   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5678adae0cfdSpatrick     StringRef Val = A->getValue();
5679a0747c9fSpatrick     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5680adae0cfdSpatrick       if (Val != "all" && Val != "labels" && Val != "none" &&
5681a0747c9fSpatrick           !Val.startswith("list="))
5682adae0cfdSpatrick         D.Diag(diag::err_drv_invalid_value)
5683adae0cfdSpatrick             << A->getAsString(Args) << A->getValue();
5684adae0cfdSpatrick       else
5685adae0cfdSpatrick         A->render(Args, CmdArgs);
5686a0747c9fSpatrick     } else if (Triple.isNVPTX()) {
5687a0747c9fSpatrick       // Do not pass the option to the GPU compilation. We still want it enabled
5688a0747c9fSpatrick       // for the host-side compilation, so seeing it here is not an error.
5689a0747c9fSpatrick     } else if (Val != "none") {
5690a0747c9fSpatrick       // =none is allowed everywhere. It's useful for overriding the option
5691a0747c9fSpatrick       // and is the same as not specifying the option.
5692a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5693a0747c9fSpatrick           << A->getAsString(Args) << TripleStr;
5694a0747c9fSpatrick     }
5695adae0cfdSpatrick   }
5696adae0cfdSpatrick 
5697a0747c9fSpatrick   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5698e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5699a0747c9fSpatrick                    UseSeparateSections || HasDefaultDataSections)) {
5700e5dd7070Spatrick     CmdArgs.push_back("-fdata-sections");
5701e5dd7070Spatrick   }
5702e5dd7070Spatrick 
57037a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
57047a9b00ceSrobert                      options::OPT_fno_unique_section_names);
57057a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
57067a9b00ceSrobert                     options::OPT_fno_unique_internal_linkage_names);
57077a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
57087a9b00ceSrobert                     options::OPT_fno_unique_basic_block_section_names);
5709adae0cfdSpatrick 
5710a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5711a0747c9fSpatrick                                options::OPT_fno_split_machine_functions)) {
5712a0747c9fSpatrick     // This codegen pass is only available on x86-elf targets.
5713a0747c9fSpatrick     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5714a0747c9fSpatrick       if (A->getOption().matches(options::OPT_fsplit_machine_functions))
5715a0747c9fSpatrick         A->render(Args, CmdArgs);
5716a0747c9fSpatrick     } else {
5717a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
5718a0747c9fSpatrick           << A->getAsString(Args) << TripleStr;
5719a0747c9fSpatrick     }
5720a0747c9fSpatrick   }
5721a0747c9fSpatrick 
5722e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5723e5dd7070Spatrick                   options::OPT_finstrument_functions_after_inlining,
5724e5dd7070Spatrick                   options::OPT_finstrument_function_entry_bare);
5725e5dd7070Spatrick 
5726adae0cfdSpatrick   // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5727adae0cfdSpatrick   // for sampling, overhead of call arc collection is way too high and there's
5728adae0cfdSpatrick   // no way to collect the output.
5729adae0cfdSpatrick   if (!Triple.isNVPTX() && !Triple.isAMDGCN())
57307a9b00ceSrobert     addPGOAndCoverageFlags(TC, C, D, Output, Args, SanitizeArgs, CmdArgs);
5731e5dd7070Spatrick 
5732e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5733e5dd7070Spatrick 
57347a9b00ceSrobert   if (getLastProfileSampleUseArg(Args) &&
57357a9b00ceSrobert       Args.hasArg(options::OPT_fsample_profile_use_profi)) {
57367a9b00ceSrobert     CmdArgs.push_back("-mllvm");
57377a9b00ceSrobert     CmdArgs.push_back("-sample-profile-use-profi");
57387a9b00ceSrobert   }
57397a9b00ceSrobert 
57407a9b00ceSrobert   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
57417a9b00ceSrobert   if (RawTriple.isPS() &&
5742e5dd7070Spatrick       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
57437a9b00ceSrobert     PScpu::addProfileRTArgs(TC, Args, CmdArgs);
57447a9b00ceSrobert     PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5745e5dd7070Spatrick   }
5746e5dd7070Spatrick 
5747e5dd7070Spatrick   // Pass options for controlling the default header search paths.
5748e5dd7070Spatrick   if (Args.hasArg(options::OPT_nostdinc)) {
5749e5dd7070Spatrick     CmdArgs.push_back("-nostdsysteminc");
5750e5dd7070Spatrick     CmdArgs.push_back("-nobuiltininc");
5751e5dd7070Spatrick   } else {
5752e5dd7070Spatrick     if (Args.hasArg(options::OPT_nostdlibinc))
5753e5dd7070Spatrick       CmdArgs.push_back("-nostdsysteminc");
5754e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5755e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5756e5dd7070Spatrick   }
5757e5dd7070Spatrick 
5758e5dd7070Spatrick   // Pass the path to compiler resource files.
5759e5dd7070Spatrick   CmdArgs.push_back("-resource-dir");
5760e5dd7070Spatrick   CmdArgs.push_back(D.ResourceDir.c_str());
5761e5dd7070Spatrick 
5762e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5763e5dd7070Spatrick 
5764e5dd7070Spatrick   RenderARCMigrateToolOptions(D, Args, CmdArgs);
5765e5dd7070Spatrick 
5766e5dd7070Spatrick   // Add preprocessing options like -I, -D, etc. if we are using the
5767e5dd7070Spatrick   // preprocessor.
5768e5dd7070Spatrick   //
5769e5dd7070Spatrick   // FIXME: Support -fpreprocessed
5770e5dd7070Spatrick   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5771e5dd7070Spatrick     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5772e5dd7070Spatrick 
5773e5dd7070Spatrick   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5774e5dd7070Spatrick   // that "The compiler can only warn and ignore the option if not recognized".
5775e5dd7070Spatrick   // When building with ccache, it will pass -D options to clang even on
5776e5dd7070Spatrick   // preprocessed inputs and configure concludes that -fPIC is not supported.
5777e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_D);
5778e5dd7070Spatrick 
5779e5dd7070Spatrick   // Manually translate -O4 to -O3; let clang reject others.
5780e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5781e5dd7070Spatrick     if (A->getOption().matches(options::OPT_O4)) {
5782e5dd7070Spatrick       CmdArgs.push_back("-O3");
5783e5dd7070Spatrick       D.Diag(diag::warn_O4_is_O3);
5784e5dd7070Spatrick     } else {
5785e5dd7070Spatrick       A->render(Args, CmdArgs);
5786e5dd7070Spatrick     }
5787e5dd7070Spatrick   }
5788e5dd7070Spatrick 
5789e5dd7070Spatrick   // Warn about ignored options to clang.
5790e5dd7070Spatrick   for (const Arg *A :
5791e5dd7070Spatrick        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5792e5dd7070Spatrick     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5793e5dd7070Spatrick     A->claim();
5794e5dd7070Spatrick   }
5795e5dd7070Spatrick 
5796e5dd7070Spatrick   for (const Arg *A :
5797e5dd7070Spatrick        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
5798e5dd7070Spatrick     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
5799e5dd7070Spatrick     A->claim();
5800e5dd7070Spatrick   }
5801e5dd7070Spatrick 
5802e5dd7070Spatrick   claimNoWarnArgs(Args);
5803e5dd7070Spatrick 
5804e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5805e5dd7070Spatrick 
58067a9b00ceSrobert   for (const Arg *A :
58077a9b00ceSrobert        Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
58087a9b00ceSrobert     A->claim();
58097a9b00ceSrobert     if (A->getOption().getID() == options::OPT__SLASH_wd) {
58107a9b00ceSrobert       unsigned WarningNumber;
58117a9b00ceSrobert       if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
58127a9b00ceSrobert         D.Diag(diag::err_drv_invalid_int_value)
58137a9b00ceSrobert             << A->getAsString(Args) << A->getValue();
58147a9b00ceSrobert         continue;
58157a9b00ceSrobert       }
58167a9b00ceSrobert 
58177a9b00ceSrobert       if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
58187a9b00ceSrobert         CmdArgs.push_back(Args.MakeArgString(
58197a9b00ceSrobert             "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
58207a9b00ceSrobert       }
58217a9b00ceSrobert       continue;
58227a9b00ceSrobert     }
58237a9b00ceSrobert     A->render(Args, CmdArgs);
58247a9b00ceSrobert   }
58257a9b00ceSrobert 
5826e5dd7070Spatrick   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5827e5dd7070Spatrick     CmdArgs.push_back("-pedantic");
5828e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5829e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_w);
5830e5dd7070Spatrick 
58317a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
58327a9b00ceSrobert                     options::OPT_fno_fixed_point);
5833e5dd7070Spatrick 
5834a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
5835a0747c9fSpatrick     A->render(Args, CmdArgs);
5836a0747c9fSpatrick 
5837a0747c9fSpatrick   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5838a0747c9fSpatrick                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5839a0747c9fSpatrick 
58407a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
58417a9b00ceSrobert     A->render(Args, CmdArgs);
58427a9b00ceSrobert 
5843e5dd7070Spatrick   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5844e5dd7070Spatrick   // (-ansi is equivalent to -std=c89 or -std=c++98).
5845e5dd7070Spatrick   //
5846e5dd7070Spatrick   // If a std is supplied, only add -trigraphs if it follows the
5847e5dd7070Spatrick   // option.
5848a0747c9fSpatrick   bool ImplyVCPPCVer = false;
5849e5dd7070Spatrick   bool ImplyVCPPCXXVer = false;
5850e5dd7070Spatrick   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
5851e5dd7070Spatrick   if (Std) {
5852e5dd7070Spatrick     if (Std->getOption().matches(options::OPT_ansi))
5853e5dd7070Spatrick       if (types::isCXX(InputType))
5854e5dd7070Spatrick         CmdArgs.push_back("-std=c++98");
5855e5dd7070Spatrick       else
5856e5dd7070Spatrick         CmdArgs.push_back("-std=c89");
5857e5dd7070Spatrick     else
5858e5dd7070Spatrick       Std->render(Args, CmdArgs);
5859e5dd7070Spatrick 
5860e5dd7070Spatrick     // If -f(no-)trigraphs appears after the language standard flag, honor it.
5861e5dd7070Spatrick     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
5862e5dd7070Spatrick                                  options::OPT_ftrigraphs,
5863e5dd7070Spatrick                                  options::OPT_fno_trigraphs))
5864e5dd7070Spatrick       if (A != Std)
5865e5dd7070Spatrick         A->render(Args, CmdArgs);
5866e5dd7070Spatrick   } else {
5867e5dd7070Spatrick     // Honor -std-default.
5868e5dd7070Spatrick     //
5869e5dd7070Spatrick     // FIXME: Clang doesn't correctly handle -std= when the input language
5870e5dd7070Spatrick     // doesn't match. For the time being just ignore this for C++ inputs;
5871e5dd7070Spatrick     // eventually we want to do all the standard defaulting here instead of
5872e5dd7070Spatrick     // splitting it between the driver and clang -cc1.
5873a0747c9fSpatrick     if (!types::isCXX(InputType)) {
5874a0747c9fSpatrick       if (!Args.hasArg(options::OPT__SLASH_std)) {
5875e5dd7070Spatrick         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
5876e5dd7070Spatrick                                   /*Joined=*/true);
5877a0747c9fSpatrick       } else
5878a0747c9fSpatrick         ImplyVCPPCVer = true;
5879a0747c9fSpatrick     }
5880e5dd7070Spatrick     else if (IsWindowsMSVC)
5881e5dd7070Spatrick       ImplyVCPPCXXVer = true;
5882e5dd7070Spatrick 
5883e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
5884e5dd7070Spatrick                     options::OPT_fno_trigraphs);
5885e5dd7070Spatrick   }
5886e5dd7070Spatrick 
5887e5dd7070Spatrick   // GCC's behavior for -Wwrite-strings is a bit strange:
5888e5dd7070Spatrick   //  * In C, this "warning flag" changes the types of string literals from
5889e5dd7070Spatrick   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
5890e5dd7070Spatrick   //    for the discarded qualifier.
5891e5dd7070Spatrick   //  * In C++, this is just a normal warning flag.
5892e5dd7070Spatrick   //
5893e5dd7070Spatrick   // Implementing this warning correctly in C is hard, so we follow GCC's
5894e5dd7070Spatrick   // behavior for now. FIXME: Directly diagnose uses of a string literal as
5895e5dd7070Spatrick   // a non-const char* in C, rather than using this crude hack.
5896e5dd7070Spatrick   if (!types::isCXX(InputType)) {
5897e5dd7070Spatrick     // FIXME: This should behave just like a warning flag, and thus should also
5898e5dd7070Spatrick     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
5899e5dd7070Spatrick     Arg *WriteStrings =
5900e5dd7070Spatrick         Args.getLastArg(options::OPT_Wwrite_strings,
5901e5dd7070Spatrick                         options::OPT_Wno_write_strings, options::OPT_w);
5902e5dd7070Spatrick     if (WriteStrings &&
5903e5dd7070Spatrick         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
5904e5dd7070Spatrick       CmdArgs.push_back("-fconst-strings");
5905e5dd7070Spatrick   }
5906e5dd7070Spatrick 
5907e5dd7070Spatrick   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
5908e5dd7070Spatrick   // during C++ compilation, which it is by default. GCC keeps this define even
5909e5dd7070Spatrick   // in the presence of '-w', match this behavior bug-for-bug.
5910e5dd7070Spatrick   if (types::isCXX(InputType) &&
5911e5dd7070Spatrick       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
5912e5dd7070Spatrick                    true)) {
5913e5dd7070Spatrick     CmdArgs.push_back("-fdeprecated-macro");
5914e5dd7070Spatrick   }
5915e5dd7070Spatrick 
5916e5dd7070Spatrick   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
5917e5dd7070Spatrick   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
5918e5dd7070Spatrick     if (Asm->getOption().matches(options::OPT_fasm))
5919e5dd7070Spatrick       CmdArgs.push_back("-fgnu-keywords");
5920e5dd7070Spatrick     else
5921e5dd7070Spatrick       CmdArgs.push_back("-fno-gnu-keywords");
5922e5dd7070Spatrick   }
5923e5dd7070Spatrick 
5924e5dd7070Spatrick   if (!ShouldEnableAutolink(Args, TC, JA))
5925e5dd7070Spatrick     CmdArgs.push_back("-fno-autolink");
5926e5dd7070Spatrick 
5927e5dd7070Spatrick   // Add in -fdebug-compilation-dir if necessary.
59287a9b00ceSrobert   const char *DebugCompilationDir =
5929e5dd7070Spatrick       addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5930e5dd7070Spatrick 
59317a9b00ceSrobert   addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5932e5dd7070Spatrick 
5933e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
5934e5dd7070Spatrick                                options::OPT_ftemplate_depth_EQ)) {
5935e5dd7070Spatrick     CmdArgs.push_back("-ftemplate-depth");
5936e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5937e5dd7070Spatrick   }
5938e5dd7070Spatrick 
5939e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
5940e5dd7070Spatrick     CmdArgs.push_back("-foperator-arrow-depth");
5941e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5942e5dd7070Spatrick   }
5943e5dd7070Spatrick 
5944e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
5945e5dd7070Spatrick     CmdArgs.push_back("-fconstexpr-depth");
5946e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5947e5dd7070Spatrick   }
5948e5dd7070Spatrick 
5949e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
5950e5dd7070Spatrick     CmdArgs.push_back("-fconstexpr-steps");
5951e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5952e5dd7070Spatrick   }
5953e5dd7070Spatrick 
59547a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
59557a9b00ceSrobert 
5956e5dd7070Spatrick   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
5957e5dd7070Spatrick     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
5958e5dd7070Spatrick 
5959e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
5960e5dd7070Spatrick     CmdArgs.push_back("-fbracket-depth");
5961e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5962e5dd7070Spatrick   }
5963e5dd7070Spatrick 
5964e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
5965e5dd7070Spatrick                                options::OPT_Wlarge_by_value_copy_def)) {
5966e5dd7070Spatrick     if (A->getNumValues()) {
5967e5dd7070Spatrick       StringRef bytes = A->getValue();
5968e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
5969e5dd7070Spatrick     } else
5970e5dd7070Spatrick       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
5971e5dd7070Spatrick   }
5972e5dd7070Spatrick 
5973e5dd7070Spatrick   if (Args.hasArg(options::OPT_relocatable_pch))
5974e5dd7070Spatrick     CmdArgs.push_back("-relocatable-pch");
5975e5dd7070Spatrick 
5976e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
5977e5dd7070Spatrick     static const char *kCFABIs[] = {
5978e5dd7070Spatrick       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
5979e5dd7070Spatrick     };
5980e5dd7070Spatrick 
59817a9b00ceSrobert     if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
5982e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
5983e5dd7070Spatrick     else
5984e5dd7070Spatrick       A->render(Args, CmdArgs);
5985e5dd7070Spatrick   }
5986e5dd7070Spatrick 
5987e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
5988e5dd7070Spatrick     CmdArgs.push_back("-fconstant-string-class");
5989e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5990e5dd7070Spatrick   }
5991e5dd7070Spatrick 
5992e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
5993e5dd7070Spatrick     CmdArgs.push_back("-ftabstop");
5994e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
5995e5dd7070Spatrick   }
5996e5dd7070Spatrick 
59977a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
59987a9b00ceSrobert                     options::OPT_fno_stack_size_section);
5999e5dd7070Spatrick 
6000a0747c9fSpatrick   if (Args.hasArg(options::OPT_fstack_usage)) {
6001a0747c9fSpatrick     CmdArgs.push_back("-stack-usage-file");
6002a0747c9fSpatrick 
6003a0747c9fSpatrick     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6004a0747c9fSpatrick       SmallString<128> OutputFilename(OutputOpt->getValue());
6005a0747c9fSpatrick       llvm::sys::path::replace_extension(OutputFilename, "su");
6006a0747c9fSpatrick       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6007a0747c9fSpatrick     } else
6008a0747c9fSpatrick       CmdArgs.push_back(
6009a0747c9fSpatrick           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6010a0747c9fSpatrick   }
6011a0747c9fSpatrick 
6012e5dd7070Spatrick   CmdArgs.push_back("-ferror-limit");
6013e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6014e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
6015e5dd7070Spatrick   else
6016e5dd7070Spatrick     CmdArgs.push_back("19");
6017e5dd7070Spatrick 
6018e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
6019e5dd7070Spatrick     CmdArgs.push_back("-fmacro-backtrace-limit");
6020e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
6021e5dd7070Spatrick   }
6022e5dd7070Spatrick 
6023e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
6024e5dd7070Spatrick     CmdArgs.push_back("-ftemplate-backtrace-limit");
6025e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
6026e5dd7070Spatrick   }
6027e5dd7070Spatrick 
6028e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
6029e5dd7070Spatrick     CmdArgs.push_back("-fconstexpr-backtrace-limit");
6030e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
6031e5dd7070Spatrick   }
6032e5dd7070Spatrick 
6033e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
6034e5dd7070Spatrick     CmdArgs.push_back("-fspell-checking-limit");
6035e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
6036e5dd7070Spatrick   }
6037e5dd7070Spatrick 
6038e5dd7070Spatrick   // Pass -fmessage-length=.
6039adae0cfdSpatrick   unsigned MessageLength = 0;
6040e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6041adae0cfdSpatrick     StringRef V(A->getValue());
6042adae0cfdSpatrick     if (V.getAsInteger(0, MessageLength))
6043adae0cfdSpatrick       D.Diag(diag::err_drv_invalid_argument_to_option)
6044adae0cfdSpatrick           << V << A->getOption().getName();
6045e5dd7070Spatrick   } else {
6046e5dd7070Spatrick     // If -fmessage-length=N was not specified, determine whether this is a
6047e5dd7070Spatrick     // terminal and, if so, implicitly define -fmessage-length appropriately.
6048adae0cfdSpatrick     MessageLength = llvm::sys::Process::StandardErrColumns();
6049e5dd7070Spatrick   }
6050adae0cfdSpatrick   if (MessageLength != 0)
6051adae0cfdSpatrick     CmdArgs.push_back(
6052adae0cfdSpatrick         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6053e5dd7070Spatrick 
60547a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
60557a9b00ceSrobert     CmdArgs.push_back(
60567a9b00ceSrobert         Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
60577a9b00ceSrobert 
60587a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
60597a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
60607a9b00ceSrobert                                          Twine(A->getValue(0))));
60617a9b00ceSrobert 
6062e5dd7070Spatrick   // -fvisibility= and -fvisibility-ms-compat are of a piece.
6063e5dd7070Spatrick   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6064e5dd7070Spatrick                                      options::OPT_fvisibility_ms_compat)) {
6065e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
60667a9b00ceSrobert       A->render(Args, CmdArgs);
6067e5dd7070Spatrick     } else {
6068e5dd7070Spatrick       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
60697a9b00ceSrobert       CmdArgs.push_back("-fvisibility=hidden");
60707a9b00ceSrobert       CmdArgs.push_back("-ftype-visibility=default");
6071e5dd7070Spatrick     }
60727a9b00ceSrobert   } else if (IsOpenMPDevice) {
60737a9b00ceSrobert     // When compiling for the OpenMP device we want protected visibility by
60747a9b00ceSrobert     // default. This prevents the device from accidentally preempting code on
60757a9b00ceSrobert     // the host, makes the system more robust, and improves performance.
60767a9b00ceSrobert     CmdArgs.push_back("-fvisibility=protected");
6077e5dd7070Spatrick   }
6078e5dd7070Spatrick 
60797a9b00ceSrobert   // PS4/PS5 process these options in addClangTargetOptions.
60807a9b00ceSrobert   if (!RawTriple.isPS()) {
6081a0747c9fSpatrick     if (const Arg *A =
6082a0747c9fSpatrick             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6083a0747c9fSpatrick                             options::OPT_fno_visibility_from_dllstorageclass)) {
6084a0747c9fSpatrick       if (A->getOption().matches(
6085a0747c9fSpatrick               options::OPT_fvisibility_from_dllstorageclass)) {
6086a0747c9fSpatrick         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6087a0747c9fSpatrick         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6088a0747c9fSpatrick         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6089a0747c9fSpatrick         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6090a0747c9fSpatrick         Args.AddLastArg(CmdArgs,
6091a0747c9fSpatrick                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6092a0747c9fSpatrick       }
6093a0747c9fSpatrick     }
60947a9b00ceSrobert   }
6095a0747c9fSpatrick 
6096a0747c9fSpatrick   if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) {
6097a0747c9fSpatrick     if (Triple.isOSAIX())
6098a0747c9fSpatrick       CmdArgs.push_back("-mignore-xcoff-visibility");
6099a0747c9fSpatrick     else
6100a0747c9fSpatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
6101a0747c9fSpatrick           << A->getAsString(Args) << TripleStr;
6102a0747c9fSpatrick   }
6103a0747c9fSpatrick 
61047a9b00ceSrobert   if (const Arg *A =
61057a9b00ceSrobert           Args.getLastArg(options::OPT_mdefault_visibility_export_mapping_EQ)) {
61067a9b00ceSrobert     if (Triple.isOSAIX())
61077a9b00ceSrobert       A->render(Args, CmdArgs);
61087a9b00ceSrobert     else
61097a9b00ceSrobert       D.Diag(diag::err_drv_unsupported_opt_for_target)
61107a9b00ceSrobert           << A->getAsString(Args) << TripleStr;
61117a9b00ceSrobert   }
6112a0747c9fSpatrick 
6113a0747c9fSpatrick   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6114a0747c9fSpatrick                     options::OPT_fno_visibility_inlines_hidden, false))
6115a0747c9fSpatrick     CmdArgs.push_back("-fvisibility-inlines-hidden");
6116a0747c9fSpatrick 
6117a0747c9fSpatrick   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6118a0747c9fSpatrick                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
6119e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
6120e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6121e5dd7070Spatrick 
61227a9b00ceSrobert   if (Args.hasFlag(options::OPT_fnew_infallible,
61237a9b00ceSrobert                    options::OPT_fno_new_infallible, false))
61247a9b00ceSrobert     CmdArgs.push_back("-fnew-infallible");
61257a9b00ceSrobert 
6126a0747c9fSpatrick   if (Args.hasFlag(options::OPT_fno_operator_names,
6127a0747c9fSpatrick                    options::OPT_foperator_names, false))
6128a0747c9fSpatrick     CmdArgs.push_back("-fno-operator-names");
6129a0747c9fSpatrick 
6130e5dd7070Spatrick   // Forward -f (flag) options which we can pass directly.
6131e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6132e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6133e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6134e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
6135e5dd7070Spatrick                   options::OPT_fno_emulated_tls);
61367a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
61377a9b00ceSrobert 
61387a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
61397a9b00ceSrobert     // FIXME: There's no reason for this to be restricted to X86. The backend
61407a9b00ceSrobert     // code needs to be changed to include the appropriate function calls
61417a9b00ceSrobert     // automatically.
61427a9b00ceSrobert     if (!Triple.isX86() && !Triple.isAArch64())
61437a9b00ceSrobert       D.Diag(diag::err_drv_unsupported_opt_for_target)
61447a9b00ceSrobert           << A->getAsString(Args) << TripleStr;
61457a9b00ceSrobert   }
6146e5dd7070Spatrick 
6147e5dd7070Spatrick   // AltiVec-like language extensions aren't relevant for assembling.
6148e5dd7070Spatrick   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6149e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6150e5dd7070Spatrick 
6151e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6152e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6153e5dd7070Spatrick 
6154e5dd7070Spatrick   // Forward flags for OpenMP. We don't do this if the current action is an
6155e5dd7070Spatrick   // device offloading action other than OpenMP.
6156e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6157e5dd7070Spatrick                    options::OPT_fno_openmp, false) &&
6158e5dd7070Spatrick       (JA.isDeviceOffloading(Action::OFK_None) ||
6159e5dd7070Spatrick        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6160e5dd7070Spatrick     switch (D.getOpenMPRuntime(Args)) {
6161e5dd7070Spatrick     case Driver::OMPRT_OMP:
6162e5dd7070Spatrick     case Driver::OMPRT_IOMP5:
6163e5dd7070Spatrick       // Clang can generate useful OpenMP code for these two runtime libraries.
6164e5dd7070Spatrick       CmdArgs.push_back("-fopenmp");
6165e5dd7070Spatrick 
6166e5dd7070Spatrick       // If no option regarding the use of TLS in OpenMP codegeneration is
6167e5dd7070Spatrick       // given, decide a default based on the target. Otherwise rely on the
6168e5dd7070Spatrick       // options and pass the right information to the frontend.
6169e5dd7070Spatrick       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6170e5dd7070Spatrick                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6171e5dd7070Spatrick         CmdArgs.push_back("-fnoopenmp-use-tls");
6172e5dd7070Spatrick       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6173e5dd7070Spatrick                       options::OPT_fno_openmp_simd);
6174e5dd7070Spatrick       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6175e5dd7070Spatrick       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
61767a9b00ceSrobert       if (!Args.hasFlag(options::OPT_fopenmp_extensions,
61777a9b00ceSrobert                         options::OPT_fno_openmp_extensions, /*Default=*/true))
61787a9b00ceSrobert         CmdArgs.push_back("-fno-openmp-extensions");
6179e5dd7070Spatrick       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6180e5dd7070Spatrick       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6181e5dd7070Spatrick       Args.AddAllArgs(CmdArgs,
6182e5dd7070Spatrick                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6183e5dd7070Spatrick       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6184e5dd7070Spatrick                        options::OPT_fno_openmp_optimistic_collapse,
6185e5dd7070Spatrick                        /*Default=*/false))
6186e5dd7070Spatrick         CmdArgs.push_back("-fopenmp-optimistic-collapse");
6187e5dd7070Spatrick 
6188e5dd7070Spatrick       // When in OpenMP offloading mode with NVPTX target, forward
6189e5dd7070Spatrick       // cuda-mode flag
6190e5dd7070Spatrick       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6191e5dd7070Spatrick                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6192e5dd7070Spatrick         CmdArgs.push_back("-fopenmp-cuda-mode");
6193e5dd7070Spatrick 
61947a9b00ceSrobert       // When in OpenMP offloading mode, enable debugging on the device.
61957a9b00ceSrobert       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
61967a9b00ceSrobert       if (Args.hasFlag(options::OPT_fopenmp_target_debug,
61977a9b00ceSrobert                        options::OPT_fno_openmp_target_debug, /*Default=*/false))
61987a9b00ceSrobert         CmdArgs.push_back("-fopenmp-target-debug");
61997a9b00ceSrobert 
62007a9b00ceSrobert       // When in OpenMP offloading mode, forward assumptions information about
62017a9b00ceSrobert       // thread and team counts in the device.
62027a9b00ceSrobert       if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
62037a9b00ceSrobert                        options::OPT_fno_openmp_assume_teams_oversubscription,
6204e5dd7070Spatrick                        /*Default=*/false))
62057a9b00ceSrobert         CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
62067a9b00ceSrobert       if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
62077a9b00ceSrobert                        options::OPT_fno_openmp_assume_threads_oversubscription,
62087a9b00ceSrobert                        /*Default=*/false))
62097a9b00ceSrobert         CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
62107a9b00ceSrobert       if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
62117a9b00ceSrobert         CmdArgs.push_back("-fopenmp-assume-no-thread-state");
62127a9b00ceSrobert       if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
62137a9b00ceSrobert         CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
62147a9b00ceSrobert       if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
62157a9b00ceSrobert         CmdArgs.push_back("-fopenmp-offload-mandatory");
6216e5dd7070Spatrick       break;
6217e5dd7070Spatrick     default:
6218e5dd7070Spatrick       // By default, if Clang doesn't know how to generate useful OpenMP code
6219e5dd7070Spatrick       // for a specific runtime library, we just don't pass the '-fopenmp' flag
6220e5dd7070Spatrick       // down to the actual compilation.
6221e5dd7070Spatrick       // FIXME: It would be better to have a mode which *only* omits IR
6222e5dd7070Spatrick       // generation based on the OpenMP support so that we get consistent
6223e5dd7070Spatrick       // semantic analysis, etc.
6224e5dd7070Spatrick       break;
6225e5dd7070Spatrick     }
6226e5dd7070Spatrick   } else {
6227e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6228e5dd7070Spatrick                     options::OPT_fno_openmp_simd);
6229e5dd7070Spatrick     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
62307a9b00ceSrobert     Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
62317a9b00ceSrobert                        options::OPT_fno_openmp_extensions);
6232e5dd7070Spatrick   }
6233e5dd7070Spatrick 
62347a9b00ceSrobert   // Forward the new driver to change offloading code generation.
62357a9b00ceSrobert   if (Args.hasFlag(options::OPT_offload_new_driver,
62367a9b00ceSrobert                    options::OPT_no_offload_new_driver, false))
62377a9b00ceSrobert     CmdArgs.push_back("--offload-new-driver");
62387a9b00ceSrobert 
62397a9b00ceSrobert   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6240e5dd7070Spatrick 
6241e5dd7070Spatrick   const XRayArgs &XRay = TC.getXRayArgs();
6242e5dd7070Spatrick   XRay.addArgs(TC, Args, CmdArgs, InputType);
6243e5dd7070Spatrick 
6244a0747c9fSpatrick   for (const auto &Filename :
6245a0747c9fSpatrick        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6246a0747c9fSpatrick     if (D.getVFS().exists(Filename))
6247a0747c9fSpatrick       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6248a0747c9fSpatrick     else
6249a0747c9fSpatrick       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6250a0747c9fSpatrick   }
6251a0747c9fSpatrick 
6252e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6253e5dd7070Spatrick     StringRef S0 = A->getValue(), S = S0;
6254e5dd7070Spatrick     unsigned Size, Offset = 0;
6255a0747c9fSpatrick     if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86())
6256e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
6257e5dd7070Spatrick           << A->getAsString(Args) << TripleStr;
6258e5dd7070Spatrick     else if (S.consumeInteger(10, Size) ||
6259e5dd7070Spatrick              (!S.empty() && (!S.consume_front(",") ||
6260e5dd7070Spatrick                              S.consumeInteger(10, Offset) || !S.empty())))
6261e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_argument_to_option)
6262e5dd7070Spatrick           << S0 << A->getOption().getName();
6263e5dd7070Spatrick     else if (Size < Offset)
6264e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6265e5dd7070Spatrick     else {
6266e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6267e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(
6268e5dd7070Spatrick           "-fpatchable-function-entry-offset=" + Twine(Offset)));
6269e5dd7070Spatrick     }
6270e5dd7070Spatrick   }
6271e5dd7070Spatrick 
62727a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
62737a9b00ceSrobert 
6274e5dd7070Spatrick   if (TC.SupportsProfiling()) {
6275e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_pg);
6276e5dd7070Spatrick 
6277e5dd7070Spatrick     llvm::Triple::ArchType Arch = TC.getArch();
6278e5dd7070Spatrick     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6279e5dd7070Spatrick       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6280e5dd7070Spatrick         A->render(Args, CmdArgs);
6281e5dd7070Spatrick       else
6282e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_opt_for_target)
6283e5dd7070Spatrick             << A->getAsString(Args) << TripleStr;
6284e5dd7070Spatrick     }
6285e5dd7070Spatrick     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6286e5dd7070Spatrick       if (Arch == llvm::Triple::systemz)
6287e5dd7070Spatrick         A->render(Args, CmdArgs);
6288e5dd7070Spatrick       else
6289e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_opt_for_target)
6290e5dd7070Spatrick             << A->getAsString(Args) << TripleStr;
6291e5dd7070Spatrick     }
6292e5dd7070Spatrick     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6293e5dd7070Spatrick       if (Arch == llvm::Triple::systemz)
6294e5dd7070Spatrick         A->render(Args, CmdArgs);
6295e5dd7070Spatrick       else
6296e5dd7070Spatrick         D.Diag(diag::err_drv_unsupported_opt_for_target)
6297e5dd7070Spatrick             << A->getAsString(Args) << TripleStr;
6298e5dd7070Spatrick     }
6299e5dd7070Spatrick   }
63007a9b00ceSrobert   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
63017a9b00ceSrobert     if (!TC.getTriple().isOSAIX() && !TC.getTriple().isOSOpenBSD()) {
63027a9b00ceSrobert       D.Diag(diag::err_drv_unsupported_opt_for_target)
63037a9b00ceSrobert           << A->getAsString(Args) << TripleStr;
63047a9b00ceSrobert     }
63057a9b00ceSrobert   }
6306e5dd7070Spatrick 
6307e5dd7070Spatrick   if (Args.getLastArg(options::OPT_fapple_kext) ||
6308e5dd7070Spatrick       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6309e5dd7070Spatrick     CmdArgs.push_back("-fapple-kext");
6310e5dd7070Spatrick 
6311a0747c9fSpatrick   Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6312e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6313e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6314e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6315e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6316e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6317a0747c9fSpatrick   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6318e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
6319e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
63207a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_EQ);
6321e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6322e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6323e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6324e5dd7070Spatrick 
6325e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6326e5dd7070Spatrick     CmdArgs.push_back("-ftrapv-handler");
6327e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
6328e5dd7070Spatrick   }
6329e5dd7070Spatrick 
6330e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6331e5dd7070Spatrick 
6332e5dd7070Spatrick   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
6333e5dd7070Spatrick   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
6334e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
6335e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fwrapv))
6336e5dd7070Spatrick       CmdArgs.push_back("-fwrapv");
6337e5dd7070Spatrick   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
6338e5dd7070Spatrick                                       options::OPT_fno_strict_overflow)) {
6339e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fno_strict_overflow))
6340e5dd7070Spatrick       CmdArgs.push_back("-fwrapv");
6341e5dd7070Spatrick   } else if (getToolChain().getTriple().isOSOpenBSD())
6342e5dd7070Spatrick     CmdArgs.push_back("-fwrapv");
6343e5dd7070Spatrick 
6344e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
6345e5dd7070Spatrick                                options::OPT_fno_reroll_loops))
6346e5dd7070Spatrick     if (A->getOption().matches(options::OPT_freroll_loops))
6347e5dd7070Spatrick       CmdArgs.push_back("-freroll-loops");
6348e5dd7070Spatrick 
6349a0747c9fSpatrick   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6350a0747c9fSpatrick                   options::OPT_fno_finite_loops);
6351a0747c9fSpatrick 
6352e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6353e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6354e5dd7070Spatrick                   options::OPT_fno_unroll_loops);
6355e5dd7070Spatrick 
63567a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
63577a9b00ceSrobert 
6358e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_pthread);
6359e5dd7070Spatrick 
63607a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
63617a9b00ceSrobert                     options::OPT_mno_speculative_load_hardening);
6362e5dd7070Spatrick 
6363e5dd7070Spatrick   // -ret-protector
6364e5dd7070Spatrick   unsigned RetProtector = 1;
6365e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fno_ret_protector,
6366e5dd7070Spatrick         options::OPT_fret_protector)) {
6367e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fno_ret_protector))
6368e5dd7070Spatrick       RetProtector = 0;
6369e5dd7070Spatrick     else if (A->getOption().matches(options::OPT_fret_protector))
6370e5dd7070Spatrick       RetProtector = 1;
6371e5dd7070Spatrick   }
6372e836804dSmortimer 
6373e5dd7070Spatrick   if (RetProtector &&
6374e5dd7070Spatrick       ((getToolChain().getArch() == llvm::Triple::x86_64) ||
6375e5dd7070Spatrick        (getToolChain().getArch() == llvm::Triple::mips64) ||
6376e5dd7070Spatrick        (getToolChain().getArch() == llvm::Triple::mips64el) ||
6377e836804dSmortimer        (getToolChain().getArch() == llvm::Triple::ppc) ||
6378e836804dSmortimer        (getToolChain().getArch() == llvm::Triple::ppc64) ||
6379e836804dSmortimer        (getToolChain().getArch() == llvm::Triple::ppc64le) ||
6380e5dd7070Spatrick        (getToolChain().getArch() == llvm::Triple::aarch64)) &&
6381e5dd7070Spatrick       !Args.hasArg(options::OPT_fno_stack_protector) &&
6382e5dd7070Spatrick       !Args.hasArg(options::OPT_pg)) {
6383e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-D_RET_PROTECTOR"));
6384e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-ret-protector"));
6385e5dd7070Spatrick     // Consume the stack protector arguments to prevent warning
6386e5dd7070Spatrick     Args.getLastArg(options::OPT_fstack_protector_all,
6387e5dd7070Spatrick         options::OPT_fstack_protector_strong,
6388e5dd7070Spatrick         options::OPT_fstack_protector,
6389e5dd7070Spatrick         options::OPT__param); // ssp-buffer-size
6390e5dd7070Spatrick   } else {
6391e5dd7070Spatrick     // If we're not using retguard, then do the usual stack protector
6392a0747c9fSpatrick     RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6393e5dd7070Spatrick   }
6394e5dd7070Spatrick 
6395e5dd7070Spatrick   // -fixup-gadgets
6396e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fno_fixup_gadgets,
6397e5dd7070Spatrick                                options::OPT_ffixup_gadgets)) {
6398e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Twine("-mllvm")));
6399e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fno_fixup_gadgets))
6400e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(Twine("-x86-fixup-gadgets=false")));
6401e5dd7070Spatrick     else if (A->getOption().matches(options::OPT_ffixup_gadgets))
6402e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(Twine("-x86-fixup-gadgets=true")));
6403e5dd7070Spatrick   }
6404e5dd7070Spatrick 
6405*896063e4Sderaadt   // -ret-clean
6406*896063e4Sderaadt   if (Arg *A = Args.getLastArg(options::OPT_fno_ret_clean,
6407*896063e4Sderaadt                                options::OPT_fret_clean)) {
6408*896063e4Sderaadt     CmdArgs.push_back(Args.MakeArgString(Twine("-mllvm")));
6409*896063e4Sderaadt     if (A->getOption().matches(options::OPT_fno_ret_clean))
6410*896063e4Sderaadt       CmdArgs.push_back(Args.MakeArgString(Twine("-x86-ret-clean=false")));
6411*896063e4Sderaadt     else if (A->getOption().matches(options::OPT_fret_clean))
6412*896063e4Sderaadt       CmdArgs.push_back(Args.MakeArgString(Twine("-x86-ret-clean=true")));
6413*896063e4Sderaadt   }
6414*896063e4Sderaadt 
6415a0747c9fSpatrick   RenderSCPOptions(TC, Args, CmdArgs);
6416a0747c9fSpatrick   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6417a0747c9fSpatrick 
64187a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
64197a9b00ceSrobert 
64207a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
64217a9b00ceSrobert                     options::OPT_mno_stackrealign);
6422e5dd7070Spatrick 
6423e5dd7070Spatrick   if (Args.hasArg(options::OPT_mstack_alignment)) {
6424e5dd7070Spatrick     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6425e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
6426e5dd7070Spatrick   }
6427e5dd7070Spatrick 
6428e5dd7070Spatrick   if (Args.hasArg(options::OPT_mstack_probe_size)) {
6429e5dd7070Spatrick     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6430e5dd7070Spatrick 
6431e5dd7070Spatrick     if (!Size.empty())
6432e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6433e5dd7070Spatrick     else
6434e5dd7070Spatrick       CmdArgs.push_back("-mstack-probe-size=0");
6435e5dd7070Spatrick   }
6436e5dd7070Spatrick 
64377a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
64387a9b00ceSrobert                      options::OPT_mno_stack_arg_probe);
6439e5dd7070Spatrick 
6440e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6441e5dd7070Spatrick                                options::OPT_mno_restrict_it)) {
6442e5dd7070Spatrick     if (A->getOption().matches(options::OPT_mrestrict_it)) {
6443e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
6444e5dd7070Spatrick       CmdArgs.push_back("-arm-restrict-it");
6445e5dd7070Spatrick     } else {
6446e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
64477a9b00ceSrobert       CmdArgs.push_back("-arm-default-it");
6448e5dd7070Spatrick     }
6449e5dd7070Spatrick   }
6450e5dd7070Spatrick 
6451e5dd7070Spatrick   // Forward -cl options to -cc1
6452a0747c9fSpatrick   RenderOpenCLOptions(Args, CmdArgs, InputType);
6453e5dd7070Spatrick 
64547a9b00ceSrobert   // Forward hlsl options to -cc1
64557a9b00ceSrobert   RenderHLSLOptions(Args, CmdArgs, InputType);
64567a9b00ceSrobert 
6457a0747c9fSpatrick   if (IsHIP) {
6458a0747c9fSpatrick     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6459adae0cfdSpatrick                      options::OPT_fno_hip_new_launch_api, true))
6460e5dd7070Spatrick       CmdArgs.push_back("-fhip-new-launch-api");
6461a0747c9fSpatrick     if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
6462a0747c9fSpatrick                      options::OPT_fno_gpu_allow_device_init, false))
6463a0747c9fSpatrick       CmdArgs.push_back("-fgpu-allow-device-init");
64647a9b00ceSrobert     Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
64657a9b00ceSrobert                       options::OPT_fno_hip_kernel_arg_name);
6466a0747c9fSpatrick   }
6467a0747c9fSpatrick 
6468a0747c9fSpatrick   if (IsCuda || IsHIP) {
64697a9b00ceSrobert     if (IsRDCMode)
6470a0747c9fSpatrick       CmdArgs.push_back("-fgpu-rdc");
6471a0747c9fSpatrick     if (Args.hasFlag(options::OPT_fgpu_defer_diag,
6472a0747c9fSpatrick                      options::OPT_fno_gpu_defer_diag, false))
6473a0747c9fSpatrick       CmdArgs.push_back("-fgpu-defer-diag");
6474a0747c9fSpatrick     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6475a0747c9fSpatrick                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
6476a0747c9fSpatrick                      false)) {
6477a0747c9fSpatrick       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6478a0747c9fSpatrick       CmdArgs.push_back("-fgpu-defer-diag");
6479a0747c9fSpatrick     }
6480a0747c9fSpatrick   }
6481e5dd7070Spatrick 
64827a9b00ceSrobert   // Forward -nogpulib to -cc1.
64837a9b00ceSrobert   if (Args.hasArg(options::OPT_nogpulib))
64847a9b00ceSrobert     CmdArgs.push_back("-nogpulib");
64857a9b00ceSrobert 
6486e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6487e5dd7070Spatrick     CmdArgs.push_back(
6488e5dd7070Spatrick         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6489bba006a8Sderaadt   } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
6490bba006a8Sderaadt     // Emit IBT endbr64 instructions by default
6491bba006a8Sderaadt     CmdArgs.push_back("-fcf-protection=branch");
649280e1ae21Sderaadt     // jump-table can generate indirect jumps, which are not permitted
649380e1ae21Sderaadt     CmdArgs.push_back("-fno-jump-tables");
6494e5dd7070Spatrick   }
6495e5dd7070Spatrick 
64967a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
64977a9b00ceSrobert     CmdArgs.push_back(
64987a9b00ceSrobert         Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
64997a9b00ceSrobert 
65007a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
65017a9b00ceSrobert 
6502a0747c9fSpatrick   // Forward -f options with positive and negative forms; we translate these by
6503a0747c9fSpatrick   // hand.  Do not propagate PGO options to the GPU-side compilations as the
6504a0747c9fSpatrick   // profile info is for the host-side compilation only.
6505a0747c9fSpatrick   if (!(IsCudaDevice || IsHIPDevice)) {
6506e5dd7070Spatrick     if (Arg *A = getLastProfileSampleUseArg(Args)) {
6507e5dd7070Spatrick       auto *PGOArg = Args.getLastArg(
6508e5dd7070Spatrick           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6509a0747c9fSpatrick           options::OPT_fcs_profile_generate,
6510a0747c9fSpatrick           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6511a0747c9fSpatrick           options::OPT_fprofile_use_EQ);
6512e5dd7070Spatrick       if (PGOArg)
6513e5dd7070Spatrick         D.Diag(diag::err_drv_argument_not_allowed_with)
6514e5dd7070Spatrick             << "SampleUse with PGO options";
6515e5dd7070Spatrick 
6516e5dd7070Spatrick       StringRef fname = A->getValue();
6517e5dd7070Spatrick       if (!llvm::sys::fs::exists(fname))
6518e5dd7070Spatrick         D.Diag(diag::err_drv_no_such_file) << fname;
6519e5dd7070Spatrick       else
6520e5dd7070Spatrick         A->render(Args, CmdArgs);
6521e5dd7070Spatrick     }
6522e5dd7070Spatrick     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6523e5dd7070Spatrick 
6524a0747c9fSpatrick     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6525a0747c9fSpatrick                      options::OPT_fno_pseudo_probe_for_profiling, false)) {
6526a0747c9fSpatrick       CmdArgs.push_back("-fpseudo-probe-for-profiling");
6527a0747c9fSpatrick       // Enforce -funique-internal-linkage-names if it's not explicitly turned
6528a0747c9fSpatrick       // off.
6529a0747c9fSpatrick       if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6530a0747c9fSpatrick                        options::OPT_fno_unique_internal_linkage_names, true))
6531a0747c9fSpatrick         CmdArgs.push_back("-funique-internal-linkage-names");
6532a0747c9fSpatrick     }
6533a0747c9fSpatrick   }
6534e5dd7070Spatrick   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
6535e5dd7070Spatrick 
65367a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
65377a9b00ceSrobert                      options::OPT_fno_assume_sane_operator_new);
6538e5dd7070Spatrick 
6539e5dd7070Spatrick   // -fblocks=0 is default.
6540e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6541e5dd7070Spatrick                    TC.IsBlocksDefault()) ||
6542e5dd7070Spatrick       (Args.hasArg(options::OPT_fgnu_runtime) &&
6543e5dd7070Spatrick        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6544e5dd7070Spatrick        !Args.hasArg(options::OPT_fno_blocks))) {
6545e5dd7070Spatrick     CmdArgs.push_back("-fblocks");
6546e5dd7070Spatrick 
6547e5dd7070Spatrick     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6548e5dd7070Spatrick       CmdArgs.push_back("-fblocks-runtime-optional");
6549e5dd7070Spatrick   }
6550e5dd7070Spatrick 
6551e5dd7070Spatrick   // -fencode-extended-block-signature=1 is default.
6552e5dd7070Spatrick   if (TC.IsEncodeExtendedBlockSignatureDefault())
6553e5dd7070Spatrick     CmdArgs.push_back("-fencode-extended-block-signature");
6554e5dd7070Spatrick 
6555e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
6556e5dd7070Spatrick                    false) &&
6557e5dd7070Spatrick       types::isCXX(InputType)) {
65587a9b00ceSrobert     D.Diag(diag::warn_deperecated_fcoroutines_ts_flag);
6559e5dd7070Spatrick     CmdArgs.push_back("-fcoroutines-ts");
6560e5dd7070Spatrick   }
6561e5dd7070Spatrick 
65627a9b00ceSrobert   if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
65637a9b00ceSrobert                    options::OPT_fno_coro_aligned_allocation, false) &&
65647a9b00ceSrobert       types::isCXX(InputType))
65657a9b00ceSrobert     CmdArgs.push_back("-fcoro-aligned-allocation");
65667a9b00ceSrobert 
6567e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6568e5dd7070Spatrick                   options::OPT_fno_double_square_bracket_attributes);
6569e5dd7070Spatrick 
65707a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
65717a9b00ceSrobert                      options::OPT_fno_access_control);
65727a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
65737a9b00ceSrobert                      options::OPT_fno_elide_constructors);
6574e5dd7070Spatrick 
6575e5dd7070Spatrick   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6576e5dd7070Spatrick 
6577e5dd7070Spatrick   if (KernelOrKext || (types::isCXX(InputType) &&
6578e5dd7070Spatrick                        (RTTIMode == ToolChain::RM_Disabled)))
6579e5dd7070Spatrick     CmdArgs.push_back("-fno-rtti");
6580e5dd7070Spatrick 
6581a0747c9fSpatrick   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6582e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6583a0747c9fSpatrick                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6584e5dd7070Spatrick     CmdArgs.push_back("-fshort-enums");
6585e5dd7070Spatrick 
6586e5dd7070Spatrick   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6587e5dd7070Spatrick 
6588e5dd7070Spatrick   // -fuse-cxa-atexit is default.
6589e5dd7070Spatrick   if (!Args.hasFlag(
6590e5dd7070Spatrick           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6591adae0cfdSpatrick           !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6592e5dd7070Spatrick               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6593e5dd7070Spatrick                RawTriple.hasEnvironment())) ||
6594e5dd7070Spatrick       KernelOrKext)
6595e5dd7070Spatrick     CmdArgs.push_back("-fno-use-cxa-atexit");
6596e5dd7070Spatrick 
6597e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6598e5dd7070Spatrick                    options::OPT_fno_register_global_dtors_with_atexit,
6599e5dd7070Spatrick                    RawTriple.isOSDarwin() && !KernelOrKext))
6600e5dd7070Spatrick     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6601e5dd7070Spatrick 
66027a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
66037a9b00ceSrobert                     options::OPT_fno_use_line_directives);
66047a9b00ceSrobert 
66057a9b00ceSrobert   // -fno-minimize-whitespace is default.
66067a9b00ceSrobert   if (Args.hasFlag(options::OPT_fminimize_whitespace,
66077a9b00ceSrobert                    options::OPT_fno_minimize_whitespace, false)) {
66087a9b00ceSrobert     types::ID InputType = Inputs[0].getType();
66097a9b00ceSrobert     if (!isDerivedFromC(InputType))
66107a9b00ceSrobert       D.Diag(diag::err_drv_minws_unsupported_input_type)
66117a9b00ceSrobert           << types::getTypeName(InputType);
66127a9b00ceSrobert     CmdArgs.push_back("-fminimize-whitespace");
66137a9b00ceSrobert   }
6614e5dd7070Spatrick 
6615adae0cfdSpatrick   // -fms-extensions=0 is default.
6616adae0cfdSpatrick   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6617adae0cfdSpatrick                    IsWindowsMSVC))
6618adae0cfdSpatrick     CmdArgs.push_back("-fms-extensions");
6619adae0cfdSpatrick 
6620e5dd7070Spatrick   // -fms-compatibility=0 is default.
6621e5dd7070Spatrick   bool IsMSVCCompat = Args.hasFlag(
6622e5dd7070Spatrick       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6623e5dd7070Spatrick       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6624e5dd7070Spatrick                                      options::OPT_fno_ms_extensions, true)));
6625e5dd7070Spatrick   if (IsMSVCCompat)
6626e5dd7070Spatrick     CmdArgs.push_back("-fms-compatibility");
6627e5dd7070Spatrick 
66287a9b00ceSrobert   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
66297a9b00ceSrobert       Args.hasArg(options::OPT_fms_runtime_lib_EQ))
66307a9b00ceSrobert     ProcessVSRuntimeLibrary(Args, CmdArgs);
66317a9b00ceSrobert 
6632e5dd7070Spatrick   // Handle -fgcc-version, if present.
6633e5dd7070Spatrick   VersionTuple GNUCVer;
6634e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6635e5dd7070Spatrick     // Check that the version has 1 to 3 components and the minor and patch
6636e5dd7070Spatrick     // versions fit in two decimal digits.
6637e5dd7070Spatrick     StringRef Val = A->getValue();
6638e5dd7070Spatrick     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6639e5dd7070Spatrick     bool Invalid = GNUCVer.tryParse(Val);
66407a9b00ceSrobert     unsigned Minor = GNUCVer.getMinor().value_or(0);
66417a9b00ceSrobert     unsigned Patch = GNUCVer.getSubminor().value_or(0);
6642e5dd7070Spatrick     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6643e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value)
6644e5dd7070Spatrick           << A->getAsString(Args) << A->getValue();
6645e5dd7070Spatrick     }
6646e5dd7070Spatrick   } else if (!IsMSVCCompat) {
6647e5dd7070Spatrick     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6648e5dd7070Spatrick     GNUCVer = VersionTuple(4, 2, 1);
6649e5dd7070Spatrick   }
6650e5dd7070Spatrick   if (!GNUCVer.empty()) {
6651e5dd7070Spatrick     CmdArgs.push_back(
6652e5dd7070Spatrick         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6653e5dd7070Spatrick   }
6654e5dd7070Spatrick 
6655e5dd7070Spatrick   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6656e5dd7070Spatrick   if (!MSVT.empty())
6657e5dd7070Spatrick     CmdArgs.push_back(
6658e5dd7070Spatrick         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6659e5dd7070Spatrick 
6660e5dd7070Spatrick   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6661a0747c9fSpatrick   if (ImplyVCPPCVer) {
6662a0747c9fSpatrick     StringRef LanguageStandard;
6663a0747c9fSpatrick     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6664a0747c9fSpatrick       Std = StdArg;
6665a0747c9fSpatrick       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6666a0747c9fSpatrick                              .Case("c11", "-std=c11")
6667a0747c9fSpatrick                              .Case("c17", "-std=c17")
6668a0747c9fSpatrick                              .Default("");
6669a0747c9fSpatrick       if (LanguageStandard.empty())
6670a0747c9fSpatrick         D.Diag(clang::diag::warn_drv_unused_argument)
6671a0747c9fSpatrick             << StdArg->getAsString(Args);
6672a0747c9fSpatrick     }
6673a0747c9fSpatrick     CmdArgs.push_back(LanguageStandard.data());
6674a0747c9fSpatrick   }
6675e5dd7070Spatrick   if (ImplyVCPPCXXVer) {
6676e5dd7070Spatrick     StringRef LanguageStandard;
6677e5dd7070Spatrick     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6678e5dd7070Spatrick       Std = StdArg;
6679e5dd7070Spatrick       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6680e5dd7070Spatrick                              .Case("c++14", "-std=c++14")
6681e5dd7070Spatrick                              .Case("c++17", "-std=c++17")
6682a0747c9fSpatrick                              .Case("c++20", "-std=c++20")
6683a0747c9fSpatrick                              .Case("c++latest", "-std=c++2b")
6684e5dd7070Spatrick                              .Default("");
6685e5dd7070Spatrick       if (LanguageStandard.empty())
6686e5dd7070Spatrick         D.Diag(clang::diag::warn_drv_unused_argument)
6687e5dd7070Spatrick             << StdArg->getAsString(Args);
6688e5dd7070Spatrick     }
6689e5dd7070Spatrick 
6690e5dd7070Spatrick     if (LanguageStandard.empty()) {
6691e5dd7070Spatrick       if (IsMSVC2015Compatible)
6692e5dd7070Spatrick         LanguageStandard = "-std=c++14";
6693e5dd7070Spatrick       else
6694e5dd7070Spatrick         LanguageStandard = "-std=c++11";
6695e5dd7070Spatrick     }
6696e5dd7070Spatrick 
6697e5dd7070Spatrick     CmdArgs.push_back(LanguageStandard.data());
6698e5dd7070Spatrick   }
6699e5dd7070Spatrick 
67007a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
67017a9b00ceSrobert                     options::OPT_fno_borland_extensions);
6702e5dd7070Spatrick 
67037a9b00ceSrobert   // -fno-declspec is default, except for PS4/PS5.
6704e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
67057a9b00ceSrobert                    RawTriple.isPS()))
6706e5dd7070Spatrick     CmdArgs.push_back("-fdeclspec");
6707e5dd7070Spatrick   else if (Args.hasArg(options::OPT_fno_declspec))
6708e5dd7070Spatrick     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6709e5dd7070Spatrick 
6710e5dd7070Spatrick   // -fthreadsafe-static is default, except for MSVC compatibility versions less
6711e5dd7070Spatrick   // than 19.
6712e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6713e5dd7070Spatrick                     options::OPT_fno_threadsafe_statics,
67147a9b00ceSrobert                     !types::isOpenCL(InputType) &&
67157a9b00ceSrobert                         (!IsWindowsMSVC || IsMSVC2015Compatible)))
6716e5dd7070Spatrick     CmdArgs.push_back("-fno-threadsafe-statics");
6717e5dd7070Spatrick 
6718e5dd7070Spatrick   // -fno-delayed-template-parsing is default, except when targeting MSVC.
6719e5dd7070Spatrick   // Many old Windows SDK versions require this to parse.
6720e5dd7070Spatrick   // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
6721e5dd7070Spatrick   // compiler. We should be able to disable this by default at some point.
6722e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6723e5dd7070Spatrick                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
6724e5dd7070Spatrick     CmdArgs.push_back("-fdelayed-template-parsing");
6725e5dd7070Spatrick 
6726e5dd7070Spatrick   // -fgnu-keywords default varies depending on language; only pass if
6727e5dd7070Spatrick   // specified.
6728e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6729e5dd7070Spatrick                   options::OPT_fno_gnu_keywords);
6730e5dd7070Spatrick 
67317a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
67327a9b00ceSrobert                     options::OPT_fno_gnu89_inline);
6733e5dd7070Spatrick 
67347a9b00ceSrobert   const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
6735e5dd7070Spatrick                                          options::OPT_finline_hint_functions,
6736e5dd7070Spatrick                                          options::OPT_fno_inline_functions);
67377a9b00ceSrobert   if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
67387a9b00ceSrobert     if (A->getOption().matches(options::OPT_fno_inline))
67397a9b00ceSrobert       A->render(Args, CmdArgs);
67407a9b00ceSrobert   } else if (InlineArg) {
67417a9b00ceSrobert     InlineArg->render(Args, CmdArgs);
67427a9b00ceSrobert   }
6743e5dd7070Spatrick 
67447a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
67457a9b00ceSrobert 
6746e5dd7070Spatrick   bool HaveModules =
67477a9b00ceSrobert       RenderModulesOptions(C, D, Args, Input, Output, Std, CmdArgs);
6748e5dd7070Spatrick 
6749e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6750e5dd7070Spatrick                    options::OPT_fno_pch_validate_input_files_content, false))
6751e5dd7070Spatrick     CmdArgs.push_back("-fvalidate-ast-input-files-content");
6752adae0cfdSpatrick   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6753adae0cfdSpatrick                    options::OPT_fno_pch_instantiate_templates, false))
6754adae0cfdSpatrick     CmdArgs.push_back("-fpch-instantiate-templates");
6755adae0cfdSpatrick   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6756adae0cfdSpatrick                    false))
6757adae0cfdSpatrick     CmdArgs.push_back("-fmodules-codegen");
6758adae0cfdSpatrick   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6759adae0cfdSpatrick                    false))
6760adae0cfdSpatrick     CmdArgs.push_back("-fmodules-debuginfo");
6761e5dd7070Spatrick 
6762adae0cfdSpatrick   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6763e5dd7070Spatrick   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6764e5dd7070Spatrick                     Input, CmdArgs);
6765e5dd7070Spatrick 
6766a0747c9fSpatrick   if (types::isObjC(Input.getType()) &&
6767a0747c9fSpatrick       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6768a0747c9fSpatrick                    options::OPT_fno_objc_encode_cxx_class_template_spec,
6769a0747c9fSpatrick                    !Runtime.isNeXTFamily()))
6770a0747c9fSpatrick     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6771a0747c9fSpatrick 
6772e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fapplication_extension,
6773e5dd7070Spatrick                    options::OPT_fno_application_extension, false))
6774e5dd7070Spatrick     CmdArgs.push_back("-fapplication-extension");
6775e5dd7070Spatrick 
6776e5dd7070Spatrick   // Handle GCC-style exception args.
6777a0747c9fSpatrick   bool EH = false;
6778e5dd7070Spatrick   if (!C.getDriver().IsCLMode())
6779a0747c9fSpatrick     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6780e5dd7070Spatrick 
6781e5dd7070Spatrick   // Handle exception personalities
6782e5dd7070Spatrick   Arg *A = Args.getLastArg(
6783e5dd7070Spatrick       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6784e5dd7070Spatrick       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6785e5dd7070Spatrick   if (A) {
6786e5dd7070Spatrick     const Option &Opt = A->getOption();
6787e5dd7070Spatrick     if (Opt.matches(options::OPT_fsjlj_exceptions))
6788a0747c9fSpatrick       CmdArgs.push_back("-exception-model=sjlj");
6789e5dd7070Spatrick     if (Opt.matches(options::OPT_fseh_exceptions))
6790a0747c9fSpatrick       CmdArgs.push_back("-exception-model=seh");
6791e5dd7070Spatrick     if (Opt.matches(options::OPT_fdwarf_exceptions))
6792a0747c9fSpatrick       CmdArgs.push_back("-exception-model=dwarf");
6793e5dd7070Spatrick     if (Opt.matches(options::OPT_fwasm_exceptions))
6794a0747c9fSpatrick       CmdArgs.push_back("-exception-model=wasm");
6795e5dd7070Spatrick   } else {
6796e5dd7070Spatrick     switch (TC.GetExceptionModel(Args)) {
6797e5dd7070Spatrick     default:
6798e5dd7070Spatrick       break;
6799e5dd7070Spatrick     case llvm::ExceptionHandling::DwarfCFI:
6800a0747c9fSpatrick       CmdArgs.push_back("-exception-model=dwarf");
6801e5dd7070Spatrick       break;
6802e5dd7070Spatrick     case llvm::ExceptionHandling::SjLj:
6803a0747c9fSpatrick       CmdArgs.push_back("-exception-model=sjlj");
6804e5dd7070Spatrick       break;
6805e5dd7070Spatrick     case llvm::ExceptionHandling::WinEH:
6806a0747c9fSpatrick       CmdArgs.push_back("-exception-model=seh");
6807e5dd7070Spatrick       break;
6808e5dd7070Spatrick     }
6809e5dd7070Spatrick   }
6810e5dd7070Spatrick 
6811e5dd7070Spatrick   // C++ "sane" operator new.
68127a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
68137a9b00ceSrobert                      options::OPT_fno_assume_sane_operator_new);
6814e5dd7070Spatrick 
6815e5dd7070Spatrick   // -frelaxed-template-template-args is off by default, as it is a severe
6816e5dd7070Spatrick   // breaking change until a corresponding change to template partial ordering
6817e5dd7070Spatrick   // is provided.
68187a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
68197a9b00ceSrobert                     options::OPT_fno_relaxed_template_template_args);
6820e5dd7070Spatrick 
6821e5dd7070Spatrick   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
6822e5dd7070Spatrick   // most platforms.
68237a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
68247a9b00ceSrobert                     options::OPT_fno_sized_deallocation);
6825e5dd7070Spatrick 
6826e5dd7070Spatrick   // -faligned-allocation is on by default in C++17 onwards and otherwise off
6827e5dd7070Spatrick   // by default.
6828e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
6829e5dd7070Spatrick                                options::OPT_fno_aligned_allocation,
6830e5dd7070Spatrick                                options::OPT_faligned_new_EQ)) {
6831e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
6832e5dd7070Spatrick       CmdArgs.push_back("-fno-aligned-allocation");
6833e5dd7070Spatrick     else
6834e5dd7070Spatrick       CmdArgs.push_back("-faligned-allocation");
6835e5dd7070Spatrick   }
6836e5dd7070Spatrick 
6837e5dd7070Spatrick   // The default new alignment can be specified using a dedicated option or via
6838e5dd7070Spatrick   // a GCC-compatible option that also turns on aligned allocation.
6839e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
6840e5dd7070Spatrick                                options::OPT_faligned_new_EQ))
6841e5dd7070Spatrick     CmdArgs.push_back(
6842e5dd7070Spatrick         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
6843e5dd7070Spatrick 
6844e5dd7070Spatrick   // -fconstant-cfstrings is default, and may be subject to argument translation
6845e5dd7070Spatrick   // on Darwin.
6846e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
68477a9b00ceSrobert                     options::OPT_fno_constant_cfstrings, true) ||
6848e5dd7070Spatrick       !Args.hasFlag(options::OPT_mconstant_cfstrings,
68497a9b00ceSrobert                     options::OPT_mno_constant_cfstrings, true))
6850e5dd7070Spatrick     CmdArgs.push_back("-fno-constant-cfstrings");
6851e5dd7070Spatrick 
68527a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
68537a9b00ceSrobert                     options::OPT_fno_pascal_strings);
6854e5dd7070Spatrick 
6855e5dd7070Spatrick   // Honor -fpack-struct= and -fpack-struct, if given. Note that
6856e5dd7070Spatrick   // -fno-pack-struct doesn't apply to -fpack-struct=.
6857e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
6858e5dd7070Spatrick     std::string PackStructStr = "-fpack-struct=";
6859e5dd7070Spatrick     PackStructStr += A->getValue();
6860e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
6861e5dd7070Spatrick   } else if (Args.hasFlag(options::OPT_fpack_struct,
6862e5dd7070Spatrick                           options::OPT_fno_pack_struct, false)) {
6863e5dd7070Spatrick     CmdArgs.push_back("-fpack-struct=1");
6864e5dd7070Spatrick   }
6865e5dd7070Spatrick 
6866e5dd7070Spatrick   // Handle -fmax-type-align=N and -fno-type-align
6867e5dd7070Spatrick   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
6868e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
6869e5dd7070Spatrick     if (!SkipMaxTypeAlign) {
6870e5dd7070Spatrick       std::string MaxTypeAlignStr = "-fmax-type-align=";
6871e5dd7070Spatrick       MaxTypeAlignStr += A->getValue();
6872e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6873e5dd7070Spatrick     }
6874e5dd7070Spatrick   } else if (RawTriple.isOSDarwin()) {
6875e5dd7070Spatrick     if (!SkipMaxTypeAlign) {
6876e5dd7070Spatrick       std::string MaxTypeAlignStr = "-fmax-type-align=16";
6877e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6878e5dd7070Spatrick     }
6879e5dd7070Spatrick   }
6880e5dd7070Spatrick 
6881e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
6882e5dd7070Spatrick     CmdArgs.push_back("-Qn");
6883e5dd7070Spatrick 
688487a29e4dSnaddy   // -fno-common is the default, set -fcommon only when that flag is set.
68857a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
6886e5dd7070Spatrick 
6887e5dd7070Spatrick   // -fsigned-bitfields is default, and clang doesn't yet support
6888e5dd7070Spatrick   // -funsigned-bitfields.
6889e5dd7070Spatrick   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
68907a9b00ceSrobert                     options::OPT_funsigned_bitfields, true))
6891e5dd7070Spatrick     D.Diag(diag::warn_drv_clang_unsupported)
6892e5dd7070Spatrick         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
6893e5dd7070Spatrick 
6894e5dd7070Spatrick   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
68957a9b00ceSrobert   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
6896e5dd7070Spatrick     D.Diag(diag::err_drv_clang_unsupported)
6897e5dd7070Spatrick         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
6898e5dd7070Spatrick 
6899e5dd7070Spatrick   // -finput_charset=UTF-8 is default. Reject others
6900e5dd7070Spatrick   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
6901e5dd7070Spatrick     StringRef value = inputCharset->getValue();
6902a0747c9fSpatrick     if (!value.equals_insensitive("utf-8"))
6903e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
6904e5dd7070Spatrick                                           << value;
6905e5dd7070Spatrick   }
6906e5dd7070Spatrick 
6907e5dd7070Spatrick   // -fexec_charset=UTF-8 is default. Reject others
6908e5dd7070Spatrick   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
6909e5dd7070Spatrick     StringRef value = execCharset->getValue();
6910a0747c9fSpatrick     if (!value.equals_insensitive("utf-8"))
6911e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
6912e5dd7070Spatrick                                           << value;
6913e5dd7070Spatrick   }
6914e5dd7070Spatrick 
6915e5dd7070Spatrick   RenderDiagnosticsOptions(D, Args, CmdArgs);
6916e5dd7070Spatrick 
69177a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
69187a9b00ceSrobert                     options::OPT_fno_asm_blocks);
6919e5dd7070Spatrick 
69207a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
69217a9b00ceSrobert                      options::OPT_fno_gnu_inline_asm);
6922e5dd7070Spatrick 
6923e5dd7070Spatrick   // Enable vectorization per default according to the optimization level
6924e5dd7070Spatrick   // selected. For optimization levels that want vectorization we use the alias
6925e5dd7070Spatrick   // option to simplify the hasFlag logic.
6926e5dd7070Spatrick   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
6927e5dd7070Spatrick   OptSpecifier VectorizeAliasOption =
6928e5dd7070Spatrick       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
6929e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
6930e5dd7070Spatrick                    options::OPT_fno_vectorize, EnableVec))
6931e5dd7070Spatrick     CmdArgs.push_back("-vectorize-loops");
6932e5dd7070Spatrick 
6933e5dd7070Spatrick   // -fslp-vectorize is enabled based on the optimization level selected.
6934e5dd7070Spatrick   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
6935e5dd7070Spatrick   OptSpecifier SLPVectAliasOption =
6936e5dd7070Spatrick       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
6937e5dd7070Spatrick   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
6938e5dd7070Spatrick                    options::OPT_fno_slp_vectorize, EnableSLPVec))
6939e5dd7070Spatrick     CmdArgs.push_back("-vectorize-slp");
6940e5dd7070Spatrick 
6941e5dd7070Spatrick   ParseMPreferVectorWidth(D, Args, CmdArgs);
6942e5dd7070Spatrick 
6943e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
6944e5dd7070Spatrick   Args.AddLastArg(CmdArgs,
6945e5dd7070Spatrick                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
6946e5dd7070Spatrick 
6947e5dd7070Spatrick   // -fdollars-in-identifiers default varies depending on platform and
6948e5dd7070Spatrick   // language; only pass if specified.
6949e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
6950e5dd7070Spatrick                                options::OPT_fno_dollars_in_identifiers)) {
6951e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
6952e5dd7070Spatrick       CmdArgs.push_back("-fdollars-in-identifiers");
6953e5dd7070Spatrick     else
6954e5dd7070Spatrick       CmdArgs.push_back("-fno-dollars-in-identifiers");
6955e5dd7070Spatrick   }
6956e5dd7070Spatrick 
69577a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
69587a9b00ceSrobert                     options::OPT_fno_apple_pragma_pack);
6959e5dd7070Spatrick 
6960a0747c9fSpatrick   if (Args.hasFlag(options::OPT_fxl_pragma_pack,
6961a0747c9fSpatrick                    options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX()))
6962a0747c9fSpatrick     CmdArgs.push_back("-fxl-pragma-pack");
6963a0747c9fSpatrick 
6964e5dd7070Spatrick   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
6965e5dd7070Spatrick   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
6966e5dd7070Spatrick     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
6967e5dd7070Spatrick 
6968e5dd7070Spatrick   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
6969e5dd7070Spatrick                                      options::OPT_fno_rewrite_imports, false);
6970e5dd7070Spatrick   if (RewriteImports)
6971e5dd7070Spatrick     CmdArgs.push_back("-frewrite-imports");
6972e5dd7070Spatrick 
6973e5dd7070Spatrick   // Disable some builtins on OpenBSD because they are just not
6974e5dd7070Spatrick   // right...
6975e5dd7070Spatrick   if (getToolChain().getTriple().isOSOpenBSD()) {
6976e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin-malloc");
6977e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin-calloc");
6978e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin-realloc");
6979e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin-valloc");
6980e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin-free");
6981e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin-strdup");
6982e5dd7070Spatrick     CmdArgs.push_back("-fno-builtin-strndup");
6983e5dd7070Spatrick   }
6984e5dd7070Spatrick 
69857a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
69867a9b00ceSrobert                     options::OPT_fno_directives_only);
69877a9b00ceSrobert 
6988e5dd7070Spatrick   // Enable rewrite includes if the user's asked for it or if we're generating
6989e5dd7070Spatrick   // diagnostics.
6990e5dd7070Spatrick   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
6991e5dd7070Spatrick   // nice to enable this when doing a crashdump for modules as well.
6992e5dd7070Spatrick   if (Args.hasFlag(options::OPT_frewrite_includes,
6993e5dd7070Spatrick                    options::OPT_fno_rewrite_includes, false) ||
6994e5dd7070Spatrick       (C.isForDiagnostics() && !HaveModules))
6995e5dd7070Spatrick     CmdArgs.push_back("-frewrite-includes");
6996e5dd7070Spatrick 
6997e5dd7070Spatrick   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
6998e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_traditional,
6999e5dd7070Spatrick                                options::OPT_traditional_cpp)) {
7000e5dd7070Spatrick     if (isa<PreprocessJobAction>(JA))
7001e5dd7070Spatrick       CmdArgs.push_back("-traditional-cpp");
7002e5dd7070Spatrick     else
7003e5dd7070Spatrick       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7004e5dd7070Spatrick   }
7005e5dd7070Spatrick 
7006e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_dM);
7007e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_dD);
70087a9b00ceSrobert   Args.AddLastArg(CmdArgs, options::OPT_dI);
7009e5dd7070Spatrick 
7010adae0cfdSpatrick   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7011adae0cfdSpatrick 
7012e5dd7070Spatrick   // Handle serialized diagnostics.
7013e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7014e5dd7070Spatrick     CmdArgs.push_back("-serialize-diagnostic-file");
7015e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7016e5dd7070Spatrick   }
7017e5dd7070Spatrick 
7018e5dd7070Spatrick   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7019e5dd7070Spatrick     CmdArgs.push_back("-fretain-comments-from-system-headers");
7020e5dd7070Spatrick 
7021e5dd7070Spatrick   // Forward -fcomment-block-commands to -cc1.
7022e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7023e5dd7070Spatrick   // Forward -fparse-all-comments to -cc1.
7024e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7025e5dd7070Spatrick 
7026e5dd7070Spatrick   // Turn -fplugin=name.so into -load name.so
7027e5dd7070Spatrick   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7028e5dd7070Spatrick     CmdArgs.push_back("-load");
7029e5dd7070Spatrick     CmdArgs.push_back(A->getValue());
7030e5dd7070Spatrick     A->claim();
7031e5dd7070Spatrick   }
7032e5dd7070Spatrick 
70337a9b00ceSrobert   // Turn -fplugin-arg-pluginname-key=value into
70347a9b00ceSrobert   // -plugin-arg-pluginname key=value
70357a9b00ceSrobert   // GCC has an actual plugin_argument struct with key/value pairs that it
70367a9b00ceSrobert   // passes to its plugins, but we don't, so just pass it on as-is.
70377a9b00ceSrobert   //
70387a9b00ceSrobert   // The syntax for -fplugin-arg- is ambiguous if both plugin name and
70397a9b00ceSrobert   // argument key are allowed to contain dashes. GCC therefore only
70407a9b00ceSrobert   // allows dashes in the key. We do the same.
70417a9b00ceSrobert   for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
70427a9b00ceSrobert     auto ArgValue = StringRef(A->getValue());
70437a9b00ceSrobert     auto FirstDashIndex = ArgValue.find('-');
70447a9b00ceSrobert     StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
70457a9b00ceSrobert     StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
70467a9b00ceSrobert 
70477a9b00ceSrobert     A->claim();
70487a9b00ceSrobert     if (FirstDashIndex == StringRef::npos || Arg.empty()) {
70497a9b00ceSrobert       if (PluginName.empty()) {
70507a9b00ceSrobert         D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
70517a9b00ceSrobert       } else {
70527a9b00ceSrobert         D.Diag(diag::warn_drv_missing_plugin_arg)
70537a9b00ceSrobert             << PluginName << A->getAsString(Args);
70547a9b00ceSrobert       }
70557a9b00ceSrobert       continue;
70567a9b00ceSrobert     }
70577a9b00ceSrobert 
70587a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
70597a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(Arg));
70607a9b00ceSrobert   }
70617a9b00ceSrobert 
7062e5dd7070Spatrick   // Forward -fpass-plugin=name.so to -cc1.
7063e5dd7070Spatrick   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7064e5dd7070Spatrick     CmdArgs.push_back(
7065e5dd7070Spatrick         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7066e5dd7070Spatrick     A->claim();
7067e5dd7070Spatrick   }
7068e5dd7070Spatrick 
7069e5dd7070Spatrick   // Setup statistics file output.
7070e5dd7070Spatrick   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7071e5dd7070Spatrick   if (!StatsFile.empty())
7072e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7073e5dd7070Spatrick 
7074e5dd7070Spatrick   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7075e5dd7070Spatrick   // parser.
70767a9b00ceSrobert   for (auto Arg : Args.filtered(options::OPT_Xclang)) {
70777a9b00ceSrobert     Arg->claim();
7078e5dd7070Spatrick     // -finclude-default-header flag is for preprocessor,
7079e5dd7070Spatrick     // do not pass it to other cc1 commands when save-temps is enabled
7080e5dd7070Spatrick     if (C.getDriver().isSaveTempsEnabled() &&
7081e5dd7070Spatrick         !isa<PreprocessJobAction>(JA)) {
70827a9b00ceSrobert       if (StringRef(Arg->getValue()) == "-finclude-default-header")
70837a9b00ceSrobert         continue;
70847a9b00ceSrobert     }
7085e5dd7070Spatrick     CmdArgs.push_back(Arg->getValue());
7086e5dd7070Spatrick   }
7087e5dd7070Spatrick   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7088e5dd7070Spatrick     A->claim();
7089e5dd7070Spatrick 
7090e5dd7070Spatrick     // We translate this by hand to the -cc1 argument, since nightly test uses
7091e5dd7070Spatrick     // it and developers have been trained to spell it with -mllvm. Both
7092e5dd7070Spatrick     // spellings are now deprecated and should be removed.
7093e5dd7070Spatrick     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7094e5dd7070Spatrick       CmdArgs.push_back("-disable-llvm-optzns");
7095e5dd7070Spatrick     } else {
7096e5dd7070Spatrick       A->render(Args, CmdArgs);
7097e5dd7070Spatrick     }
7098e5dd7070Spatrick   }
7099e5dd7070Spatrick 
7100e5dd7070Spatrick   // With -save-temps, we want to save the unoptimized bitcode output from the
7101e5dd7070Spatrick   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7102e5dd7070Spatrick   // by the frontend.
7103e5dd7070Spatrick   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7104e5dd7070Spatrick   // has slightly different breakdown between stages.
7105e5dd7070Spatrick   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7106e5dd7070Spatrick   // pristine IR generated by the frontend. Ideally, a new compile action should
7107e5dd7070Spatrick   // be added so both IR can be captured.
7108adae0cfdSpatrick   if ((C.getDriver().isSaveTempsEnabled() ||
7109adae0cfdSpatrick        JA.isHostOffloading(Action::OFK_OpenMP)) &&
7110a0747c9fSpatrick       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7111e5dd7070Spatrick       isa<CompileJobAction>(JA))
7112e5dd7070Spatrick     CmdArgs.push_back("-disable-llvm-passes");
7113e5dd7070Spatrick 
7114e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_undef);
7115e5dd7070Spatrick 
7116e5dd7070Spatrick   const char *Exec = D.getClangProgramPath();
7117e5dd7070Spatrick 
7118e5dd7070Spatrick   // Optionally embed the -cc1 level arguments into the debug info or a
7119e5dd7070Spatrick   // section, for build analysis.
7120e5dd7070Spatrick   // Also record command line arguments into the debug info if
7121e5dd7070Spatrick   // -grecord-gcc-switches options is set on.
7122e5dd7070Spatrick   // By default, -gno-record-gcc-switches is set on and no recording.
7123e5dd7070Spatrick   auto GRecordSwitches =
7124e5dd7070Spatrick       Args.hasFlag(options::OPT_grecord_command_line,
7125e5dd7070Spatrick                    options::OPT_gno_record_command_line, false);
7126e5dd7070Spatrick   auto FRecordSwitches =
7127e5dd7070Spatrick       Args.hasFlag(options::OPT_frecord_command_line,
7128e5dd7070Spatrick                    options::OPT_fno_record_command_line, false);
7129e5dd7070Spatrick   if (FRecordSwitches && !Triple.isOSBinFormatELF())
7130e5dd7070Spatrick     D.Diag(diag::err_drv_unsupported_opt_for_target)
7131e5dd7070Spatrick         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
7132e5dd7070Spatrick         << TripleStr;
7133e5dd7070Spatrick   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
7134e5dd7070Spatrick     ArgStringList OriginalArgs;
7135e5dd7070Spatrick     for (const auto &Arg : Args)
7136e5dd7070Spatrick       Arg->render(Args, OriginalArgs);
7137e5dd7070Spatrick 
7138e5dd7070Spatrick     SmallString<256> Flags;
7139adae0cfdSpatrick     EscapeSpacesAndBackslashes(Exec, Flags);
7140e5dd7070Spatrick     for (const char *OriginalArg : OriginalArgs) {
7141e5dd7070Spatrick       SmallString<128> EscapedArg;
7142e5dd7070Spatrick       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7143e5dd7070Spatrick       Flags += " ";
7144e5dd7070Spatrick       Flags += EscapedArg;
7145e5dd7070Spatrick     }
7146e5dd7070Spatrick     auto FlagsArgString = Args.MakeArgString(Flags);
7147e5dd7070Spatrick     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7148e5dd7070Spatrick       CmdArgs.push_back("-dwarf-debug-flags");
7149e5dd7070Spatrick       CmdArgs.push_back(FlagsArgString);
7150e5dd7070Spatrick     }
7151e5dd7070Spatrick     if (FRecordSwitches) {
7152e5dd7070Spatrick       CmdArgs.push_back("-record-command-line");
7153e5dd7070Spatrick       CmdArgs.push_back(FlagsArgString);
7154e5dd7070Spatrick     }
7155e5dd7070Spatrick   }
7156e5dd7070Spatrick 
71577a9b00ceSrobert   // Host-side offloading compilation receives all device-side outputs. Include
71587a9b00ceSrobert   // them in the host compilation depending on the target. If the host inputs
71597a9b00ceSrobert   // are not empty we use the new-driver scheme, otherwise use the old scheme.
7160e5dd7070Spatrick   if ((IsCuda || IsHIP) && CudaDeviceInput) {
7161e5dd7070Spatrick     CmdArgs.push_back("-fcuda-include-gpubinary");
7162e5dd7070Spatrick     CmdArgs.push_back(CudaDeviceInput->getFilename());
71637a9b00ceSrobert   } else if (!HostOffloadingInputs.empty()) {
71647a9b00ceSrobert     if ((IsCuda || IsHIP) && !IsRDCMode) {
71657a9b00ceSrobert       assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
71667a9b00ceSrobert       CmdArgs.push_back("-fcuda-include-gpubinary");
71677a9b00ceSrobert       CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
71687a9b00ceSrobert     } else {
71697a9b00ceSrobert       for (const InputInfo Input : HostOffloadingInputs)
71707a9b00ceSrobert         CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
71717a9b00ceSrobert                                              TC.getInputFilename(Input)));
71727a9b00ceSrobert     }
7173e5dd7070Spatrick   }
7174e5dd7070Spatrick 
7175e5dd7070Spatrick   if (IsCuda) {
7176e5dd7070Spatrick     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7177e5dd7070Spatrick                      options::OPT_fno_cuda_short_ptr, false))
7178e5dd7070Spatrick       CmdArgs.push_back("-fcuda-short-ptr");
7179e5dd7070Spatrick   }
7180e5dd7070Spatrick 
7181a0747c9fSpatrick   if (IsCuda || IsHIP) {
7182a0747c9fSpatrick     // Determine the original source input.
7183a0747c9fSpatrick     const Action *SourceAction = &JA;
7184a0747c9fSpatrick     while (SourceAction->getKind() != Action::InputClass) {
7185a0747c9fSpatrick       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7186a0747c9fSpatrick       SourceAction = SourceAction->getInputs()[0];
7187a0747c9fSpatrick     }
7188a0747c9fSpatrick     auto CUID = cast<InputAction>(SourceAction)->getId();
7189a0747c9fSpatrick     if (!CUID.empty())
7190a0747c9fSpatrick       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7191a0747c9fSpatrick   }
7192a0747c9fSpatrick 
71937a9b00ceSrobert   if (IsHIP) {
7194e5dd7070Spatrick     CmdArgs.push_back("-fcuda-allow-variadic-functions");
71957a9b00ceSrobert     Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
71967a9b00ceSrobert   }
7197e5dd7070Spatrick 
7198a0747c9fSpatrick   if (IsCudaDevice || IsHIPDevice) {
7199a0747c9fSpatrick     StringRef InlineThresh =
7200a0747c9fSpatrick         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7201a0747c9fSpatrick     if (!InlineThresh.empty()) {
7202a0747c9fSpatrick       std::string ArgStr =
7203a0747c9fSpatrick           std::string("-inline-threshold=") + InlineThresh.str();
7204a0747c9fSpatrick       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7205a0747c9fSpatrick     }
7206a0747c9fSpatrick   }
7207a0747c9fSpatrick 
7208e5dd7070Spatrick   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7209e5dd7070Spatrick   // to specify the result of the compile phase on the host, so the meaningful
7210e5dd7070Spatrick   // device declarations can be identified. Also, -fopenmp-is-device is passed
7211e5dd7070Spatrick   // along to tell the frontend that it is generating code for a device, so that
7212e5dd7070Spatrick   // only the relevant declarations are emitted.
7213e5dd7070Spatrick   if (IsOpenMPDevice) {
7214e5dd7070Spatrick     CmdArgs.push_back("-fopenmp-is-device");
7215e5dd7070Spatrick     if (OpenMPDeviceInput) {
7216e5dd7070Spatrick       CmdArgs.push_back("-fopenmp-host-ir-file-path");
7217e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7218e5dd7070Spatrick     }
7219e5dd7070Spatrick   }
7220e5dd7070Spatrick 
7221a0747c9fSpatrick   if (Triple.isAMDGPU()) {
7222a0747c9fSpatrick     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7223a0747c9fSpatrick 
72247a9b00ceSrobert     Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
72257a9b00ceSrobert                       options::OPT_mno_unsafe_fp_atomics);
7226a0747c9fSpatrick   }
7227a0747c9fSpatrick 
7228e5dd7070Spatrick   // For all the host OpenMP offloading compile jobs we need to pass the targets
7229e5dd7070Spatrick   // information using -fopenmp-targets= option.
7230e5dd7070Spatrick   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
72317a9b00ceSrobert     SmallString<128> Targets("-fopenmp-targets=");
7232e5dd7070Spatrick 
72337a9b00ceSrobert     SmallVector<std::string, 4> Triples;
72347a9b00ceSrobert     auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
72357a9b00ceSrobert     std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
72367a9b00ceSrobert                    [](auto TC) { return TC.second->getTripleString(); });
72377a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
7238e5dd7070Spatrick   }
7239e5dd7070Spatrick 
7240e5dd7070Spatrick   bool VirtualFunctionElimination =
7241e5dd7070Spatrick       Args.hasFlag(options::OPT_fvirtual_function_elimination,
7242e5dd7070Spatrick                    options::OPT_fno_virtual_function_elimination, false);
7243e5dd7070Spatrick   if (VirtualFunctionElimination) {
7244e5dd7070Spatrick     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7245e5dd7070Spatrick     // in the future).
7246a0747c9fSpatrick     if (LTOMode != LTOK_Full)
7247e5dd7070Spatrick       D.Diag(diag::err_drv_argument_only_allowed_with)
7248e5dd7070Spatrick           << "-fvirtual-function-elimination"
7249e5dd7070Spatrick           << "-flto=full";
7250e5dd7070Spatrick 
7251e5dd7070Spatrick     CmdArgs.push_back("-fvirtual-function-elimination");
7252e5dd7070Spatrick   }
7253e5dd7070Spatrick 
7254e5dd7070Spatrick   // VFE requires whole-program-vtables, and enables it by default.
7255e5dd7070Spatrick   bool WholeProgramVTables = Args.hasFlag(
7256e5dd7070Spatrick       options::OPT_fwhole_program_vtables,
7257e5dd7070Spatrick       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7258e5dd7070Spatrick   if (VirtualFunctionElimination && !WholeProgramVTables) {
7259e5dd7070Spatrick     D.Diag(diag::err_drv_argument_not_allowed_with)
7260e5dd7070Spatrick         << "-fno-whole-program-vtables"
7261e5dd7070Spatrick         << "-fvirtual-function-elimination";
7262e5dd7070Spatrick   }
7263e5dd7070Spatrick 
7264e5dd7070Spatrick   if (WholeProgramVTables) {
7265a0747c9fSpatrick     // Propagate -fwhole-program-vtables if this is an LTO compile.
7266a0747c9fSpatrick     if (IsUsingLTO)
7267a0747c9fSpatrick       CmdArgs.push_back("-fwhole-program-vtables");
7268a0747c9fSpatrick     // Check if we passed LTO options but they were suppressed because this is a
7269a0747c9fSpatrick     // device offloading action, or we passed device offload LTO options which
7270a0747c9fSpatrick     // were suppressed because this is not the device offload action.
7271a0747c9fSpatrick     // Otherwise, issue an error.
7272a0747c9fSpatrick     else if (!D.isUsingLTO(!IsDeviceOffloadAction))
7273e5dd7070Spatrick       D.Diag(diag::err_drv_argument_only_allowed_with)
7274e5dd7070Spatrick           << "-fwhole-program-vtables"
7275e5dd7070Spatrick           << "-flto";
7276e5dd7070Spatrick   }
7277e5dd7070Spatrick 
7278e5dd7070Spatrick   bool DefaultsSplitLTOUnit =
72797a9b00ceSrobert       (WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7280a0747c9fSpatrick       (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit());
7281e5dd7070Spatrick   bool SplitLTOUnit =
7282e5dd7070Spatrick       Args.hasFlag(options::OPT_fsplit_lto_unit,
7283e5dd7070Spatrick                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
72847a9b00ceSrobert   if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7285e5dd7070Spatrick     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7286e5dd7070Spatrick                                                     << "-fsanitize=cfi";
7287e5dd7070Spatrick   if (SplitLTOUnit)
7288e5dd7070Spatrick     CmdArgs.push_back("-fsplit-lto-unit");
7289e5dd7070Spatrick 
7290adae0cfdSpatrick   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7291adae0cfdSpatrick                                options::OPT_fno_global_isel)) {
7292e5dd7070Spatrick     CmdArgs.push_back("-mllvm");
7293adae0cfdSpatrick     if (A->getOption().matches(options::OPT_fglobal_isel)) {
7294e5dd7070Spatrick       CmdArgs.push_back("-global-isel=1");
7295e5dd7070Spatrick 
7296e5dd7070Spatrick       // GISel is on by default on AArch64 -O0, so don't bother adding
7297e5dd7070Spatrick       // the fallback remarks for it. Other combinations will add a warning of
7298e5dd7070Spatrick       // some kind.
7299e5dd7070Spatrick       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7300e5dd7070Spatrick       bool IsOptLevelSupported = false;
7301e5dd7070Spatrick 
7302e5dd7070Spatrick       Arg *A = Args.getLastArg(options::OPT_O_Group);
7303e5dd7070Spatrick       if (Triple.getArch() == llvm::Triple::aarch64) {
7304e5dd7070Spatrick         if (!A || A->getOption().matches(options::OPT_O0))
7305e5dd7070Spatrick           IsOptLevelSupported = true;
7306e5dd7070Spatrick       }
7307e5dd7070Spatrick       if (!IsArchSupported || !IsOptLevelSupported) {
7308e5dd7070Spatrick         CmdArgs.push_back("-mllvm");
7309e5dd7070Spatrick         CmdArgs.push_back("-global-isel-abort=2");
7310e5dd7070Spatrick 
7311e5dd7070Spatrick         if (!IsArchSupported)
7312adae0cfdSpatrick           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7313e5dd7070Spatrick         else
7314adae0cfdSpatrick           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7315e5dd7070Spatrick       }
7316e5dd7070Spatrick     } else {
7317e5dd7070Spatrick       CmdArgs.push_back("-global-isel=0");
7318e5dd7070Spatrick     }
7319e5dd7070Spatrick   }
7320e5dd7070Spatrick 
7321e5dd7070Spatrick   if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
7322e5dd7070Spatrick      CmdArgs.push_back("-forder-file-instrumentation");
7323e5dd7070Spatrick      // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
7324e5dd7070Spatrick      // on, we need to pass these flags as linker flags and that will be handled
7325e5dd7070Spatrick      // outside of the compiler.
7326a0747c9fSpatrick      if (!IsUsingLTO) {
7327e5dd7070Spatrick        CmdArgs.push_back("-mllvm");
7328e5dd7070Spatrick        CmdArgs.push_back("-enable-order-file-instrumentation");
7329e5dd7070Spatrick      }
7330e5dd7070Spatrick   }
7331e5dd7070Spatrick 
7332e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7333e5dd7070Spatrick                                options::OPT_fno_force_enable_int128)) {
7334e5dd7070Spatrick     if (A->getOption().matches(options::OPT_fforce_enable_int128))
7335e5dd7070Spatrick       CmdArgs.push_back("-fforce-enable-int128");
7336e5dd7070Spatrick   }
7337e5dd7070Spatrick 
73387a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
73397a9b00ceSrobert                     options::OPT_fno_keep_static_consts);
73407a9b00ceSrobert   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
73417a9b00ceSrobert                     options::OPT_fno_complete_member_pointers);
73427a9b00ceSrobert   Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
73437a9b00ceSrobert                      options::OPT_fno_cxx_static_destructors);
7344e5dd7070Spatrick 
7345a0747c9fSpatrick   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7346a0747c9fSpatrick 
7347a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7348a0747c9fSpatrick                                options::OPT_mno_outline_atomics)) {
7349a0747c9fSpatrick     // Option -moutline-atomics supported for AArch64 target only.
7350a0747c9fSpatrick     if (!Triple.isAArch64()) {
7351a0747c9fSpatrick       D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
73527a9b00ceSrobert           << Triple.getArchName() << A->getOption().getName();
7353e5dd7070Spatrick     } else {
73547a9b00ceSrobert       if (A->getOption().matches(options::OPT_moutline_atomics)) {
7355a0747c9fSpatrick         CmdArgs.push_back("-target-feature");
7356a0747c9fSpatrick         CmdArgs.push_back("+outline-atomics");
7357e5dd7070Spatrick       } else {
7358a0747c9fSpatrick         CmdArgs.push_back("-target-feature");
7359a0747c9fSpatrick         CmdArgs.push_back("-outline-atomics");
7360e5dd7070Spatrick       }
73617a9b00ceSrobert     }
7362a0747c9fSpatrick   } else if (Triple.isAArch64() &&
7363a0747c9fSpatrick              getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7364a0747c9fSpatrick     CmdArgs.push_back("-target-feature");
7365a0747c9fSpatrick     CmdArgs.push_back("+outline-atomics");
7366e5dd7070Spatrick   }
7367e5dd7070Spatrick 
73687a9b00ceSrobert   if (Triple.isAArch64() &&
73697a9b00ceSrobert       (Args.hasArg(options::OPT_mno_fmv) ||
73707a9b00ceSrobert        getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
73717a9b00ceSrobert     // Disable Function Multiversioning on AArch64 target.
73727a9b00ceSrobert     CmdArgs.push_back("-target-feature");
73737a9b00ceSrobert     CmdArgs.push_back("-fmv");
73747a9b00ceSrobert   }
73757a9b00ceSrobert 
7376e5dd7070Spatrick   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7377e5dd7070Spatrick                    (TC.getTriple().isOSBinFormatELF() ||
7378e5dd7070Spatrick                     TC.getTriple().isOSBinFormatCOFF()) &&
7379a0747c9fSpatrick                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7380e5dd7070Spatrick                        !TC.getTriple().isOSNetBSD() &&
7381e5dd7070Spatrick                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7382a0747c9fSpatrick                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7383e5dd7070Spatrick     CmdArgs.push_back("-faddrsig");
7384e5dd7070Spatrick 
7385a0747c9fSpatrick   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
73867a9b00ceSrobert       (EH || UnwindTables || AsyncUnwindTables ||
73877a9b00ceSrobert        DebugInfoKind != codegenoptions::NoDebugInfo))
7388a0747c9fSpatrick     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7389a0747c9fSpatrick 
7390e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7391e5dd7070Spatrick     std::string Str = A->getAsString(Args);
7392e5dd7070Spatrick     if (!TC.getTriple().isOSBinFormatELF())
7393e5dd7070Spatrick       D.Diag(diag::err_drv_unsupported_opt_for_target)
7394e5dd7070Spatrick           << Str << TC.getTripleString();
7395e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Str));
7396e5dd7070Spatrick   }
7397e5dd7070Spatrick 
73987a9b00ceSrobert   // Add the output path to the object file for CodeView debug infos.
73997a9b00ceSrobert   if (EmitCodeView && Output.isFilename())
74007a9b00ceSrobert     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
74017a9b00ceSrobert                        Output.getFilename());
74027a9b00ceSrobert 
7403e5dd7070Spatrick   // Add the "-o out -x type src.c" flags last. This is done primarily to make
7404e5dd7070Spatrick   // the -cc1 command easier to edit when reproducing compiler crashes.
7405e5dd7070Spatrick   if (Output.getType() == types::TY_Dependencies) {
7406e5dd7070Spatrick     // Handled with other dependency code.
7407e5dd7070Spatrick   } else if (Output.isFilename()) {
7408e5dd7070Spatrick     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7409e5dd7070Spatrick         Output.getType() == clang::driver::types::TY_IFS) {
7410e5dd7070Spatrick       SmallString<128> OutputFilename(Output.getFilename());
7411e5dd7070Spatrick       llvm::sys::path::replace_extension(OutputFilename, "ifs");
7412e5dd7070Spatrick       CmdArgs.push_back("-o");
7413e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7414e5dd7070Spatrick     } else {
7415e5dd7070Spatrick       CmdArgs.push_back("-o");
7416e5dd7070Spatrick       CmdArgs.push_back(Output.getFilename());
7417e5dd7070Spatrick     }
7418e5dd7070Spatrick   } else {
7419e5dd7070Spatrick     assert(Output.isNothing() && "Invalid output.");
7420e5dd7070Spatrick   }
7421e5dd7070Spatrick 
7422e5dd7070Spatrick   addDashXForInput(Args, Input, CmdArgs);
7423e5dd7070Spatrick 
7424e5dd7070Spatrick   ArrayRef<InputInfo> FrontendInputs = Input;
74257a9b00ceSrobert   if (IsExtractAPI)
74267a9b00ceSrobert     FrontendInputs = ExtractAPIInputs;
7427e5dd7070Spatrick   else if (Input.isNothing())
7428e5dd7070Spatrick     FrontendInputs = {};
7429e5dd7070Spatrick 
7430e5dd7070Spatrick   for (const InputInfo &Input : FrontendInputs) {
7431e5dd7070Spatrick     if (Input.isFilename())
7432e5dd7070Spatrick       CmdArgs.push_back(Input.getFilename());
7433e5dd7070Spatrick     else
7434e5dd7070Spatrick       Input.getInputArg().renderAsInput(Args, CmdArgs);
7435e5dd7070Spatrick   }
7436e5dd7070Spatrick 
7437a0747c9fSpatrick   if (D.CC1Main && !D.CCGenDiagnostics) {
7438e5dd7070Spatrick     // Invoke the CC1 directly in this process
7439a0747c9fSpatrick     C.addCommand(std::make_unique<CC1Command>(JA, *this,
7440a0747c9fSpatrick                                               ResponseFileSupport::AtFileUTF8(),
7441a0747c9fSpatrick                                               Exec, CmdArgs, Inputs, Output));
7442e5dd7070Spatrick   } else {
7443a0747c9fSpatrick     C.addCommand(std::make_unique<Command>(JA, *this,
7444a0747c9fSpatrick                                            ResponseFileSupport::AtFileUTF8(),
7445a0747c9fSpatrick                                            Exec, CmdArgs, Inputs, Output));
7446e5dd7070Spatrick   }
7447e5dd7070Spatrick 
7448e5dd7070Spatrick   // Make the compile command echo its inputs for /showFilenames.
7449e5dd7070Spatrick   if (Output.getType() == types::TY_Object &&
7450e5dd7070Spatrick       Args.hasFlag(options::OPT__SLASH_showFilenames,
7451e5dd7070Spatrick                    options::OPT__SLASH_showFilenames_, false)) {
7452e5dd7070Spatrick     C.getJobs().getJobs().back()->PrintInputFilenames = true;
7453e5dd7070Spatrick   }
7454e5dd7070Spatrick 
7455e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_pg))
7456adae0cfdSpatrick     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7457adae0cfdSpatrick         !Args.hasArg(options::OPT_mfentry))
7458e5dd7070Spatrick       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
7459e5dd7070Spatrick                                                       << A->getAsString(Args);
7460e5dd7070Spatrick 
7461e5dd7070Spatrick   // Claim some arguments which clang supports automatically.
7462e5dd7070Spatrick 
7463e5dd7070Spatrick   // -fpch-preprocess is used with gcc to add a special marker in the output to
7464e5dd7070Spatrick   // include the PCH file.
7465e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
7466e5dd7070Spatrick 
7467e5dd7070Spatrick   // Claim some arguments which clang doesn't support, but we don't
7468e5dd7070Spatrick   // care to warn the user about.
7469e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
7470e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
7471e5dd7070Spatrick 
7472e5dd7070Spatrick   // Disable warnings for clang -E -emit-llvm foo.c
7473e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_emit_llvm);
7474e5dd7070Spatrick }
7475e5dd7070Spatrick 
Clang(const ToolChain & TC,bool HasIntegratedBackend)74767a9b00ceSrobert Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
7477e5dd7070Spatrick     // CAUTION! The first constructor argument ("clang") is not arbitrary,
7478e5dd7070Spatrick     // as it is for other tools. Some operations on a Tool actually test
7479e5dd7070Spatrick     // whether that tool is Clang based on the Tool's Name as a string.
74807a9b00ceSrobert     : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
7481e5dd7070Spatrick 
~Clang()7482e5dd7070Spatrick Clang::~Clang() {}
7483e5dd7070Spatrick 
7484e5dd7070Spatrick /// Add options related to the Objective-C runtime/ABI.
7485e5dd7070Spatrick ///
7486e5dd7070Spatrick /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,const InputInfoList & inputs,ArgStringList & cmdArgs,RewriteKind rewriteKind) const7487e5dd7070Spatrick ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
7488adae0cfdSpatrick                                       const InputInfoList &inputs,
7489e5dd7070Spatrick                                       ArgStringList &cmdArgs,
7490e5dd7070Spatrick                                       RewriteKind rewriteKind) const {
7491e5dd7070Spatrick   // Look for the controlling runtime option.
7492e5dd7070Spatrick   Arg *runtimeArg =
7493e5dd7070Spatrick       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
7494e5dd7070Spatrick                       options::OPT_fobjc_runtime_EQ);
7495e5dd7070Spatrick 
7496e5dd7070Spatrick   // Just forward -fobjc-runtime= to the frontend.  This supercedes
7497e5dd7070Spatrick   // options about fragility.
7498e5dd7070Spatrick   if (runtimeArg &&
7499e5dd7070Spatrick       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
7500e5dd7070Spatrick     ObjCRuntime runtime;
7501e5dd7070Spatrick     StringRef value = runtimeArg->getValue();
7502e5dd7070Spatrick     if (runtime.tryParse(value)) {
7503e5dd7070Spatrick       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
7504e5dd7070Spatrick           << value;
7505e5dd7070Spatrick     }
7506e5dd7070Spatrick     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
7507e5dd7070Spatrick         (runtime.getVersion() >= VersionTuple(2, 0)))
7508e5dd7070Spatrick       if (!getToolChain().getTriple().isOSBinFormatELF() &&
7509e5dd7070Spatrick           !getToolChain().getTriple().isOSBinFormatCOFF()) {
7510e5dd7070Spatrick         getToolChain().getDriver().Diag(
7511e5dd7070Spatrick             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
7512e5dd7070Spatrick           << runtime.getVersion().getMajor();
7513e5dd7070Spatrick       }
7514e5dd7070Spatrick 
7515e5dd7070Spatrick     runtimeArg->render(args, cmdArgs);
7516e5dd7070Spatrick     return runtime;
7517e5dd7070Spatrick   }
7518e5dd7070Spatrick 
7519e5dd7070Spatrick   // Otherwise, we'll need the ABI "version".  Version numbers are
7520e5dd7070Spatrick   // slightly confusing for historical reasons:
7521e5dd7070Spatrick   //   1 - Traditional "fragile" ABI
7522e5dd7070Spatrick   //   2 - Non-fragile ABI, version 1
7523e5dd7070Spatrick   //   3 - Non-fragile ABI, version 2
7524e5dd7070Spatrick   unsigned objcABIVersion = 1;
7525e5dd7070Spatrick   // If -fobjc-abi-version= is present, use that to set the version.
7526e5dd7070Spatrick   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
7527e5dd7070Spatrick     StringRef value = abiArg->getValue();
7528e5dd7070Spatrick     if (value == "1")
7529e5dd7070Spatrick       objcABIVersion = 1;
7530e5dd7070Spatrick     else if (value == "2")
7531e5dd7070Spatrick       objcABIVersion = 2;
7532e5dd7070Spatrick     else if (value == "3")
7533e5dd7070Spatrick       objcABIVersion = 3;
7534e5dd7070Spatrick     else
7535e5dd7070Spatrick       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
7536e5dd7070Spatrick   } else {
7537e5dd7070Spatrick     // Otherwise, determine if we are using the non-fragile ABI.
7538e5dd7070Spatrick     bool nonFragileABIIsDefault =
7539e5dd7070Spatrick         (rewriteKind == RK_NonFragile ||
7540e5dd7070Spatrick          (rewriteKind == RK_None &&
7541e5dd7070Spatrick           getToolChain().IsObjCNonFragileABIDefault()));
7542e5dd7070Spatrick     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
7543e5dd7070Spatrick                      options::OPT_fno_objc_nonfragile_abi,
7544e5dd7070Spatrick                      nonFragileABIIsDefault)) {
7545e5dd7070Spatrick // Determine the non-fragile ABI version to use.
7546e5dd7070Spatrick #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
7547e5dd7070Spatrick       unsigned nonFragileABIVersion = 1;
7548e5dd7070Spatrick #else
7549e5dd7070Spatrick       unsigned nonFragileABIVersion = 2;
7550e5dd7070Spatrick #endif
7551e5dd7070Spatrick 
7552e5dd7070Spatrick       if (Arg *abiArg =
7553e5dd7070Spatrick               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
7554e5dd7070Spatrick         StringRef value = abiArg->getValue();
7555e5dd7070Spatrick         if (value == "1")
7556e5dd7070Spatrick           nonFragileABIVersion = 1;
7557e5dd7070Spatrick         else if (value == "2")
7558e5dd7070Spatrick           nonFragileABIVersion = 2;
7559e5dd7070Spatrick         else
7560e5dd7070Spatrick           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
7561e5dd7070Spatrick               << value;
7562e5dd7070Spatrick       }
7563e5dd7070Spatrick 
7564e5dd7070Spatrick       objcABIVersion = 1 + nonFragileABIVersion;
7565e5dd7070Spatrick     } else {
7566e5dd7070Spatrick       objcABIVersion = 1;
7567e5dd7070Spatrick     }
7568e5dd7070Spatrick   }
7569e5dd7070Spatrick 
7570e5dd7070Spatrick   // We don't actually care about the ABI version other than whether
7571e5dd7070Spatrick   // it's non-fragile.
7572e5dd7070Spatrick   bool isNonFragile = objcABIVersion != 1;
7573e5dd7070Spatrick 
7574e5dd7070Spatrick   // If we have no runtime argument, ask the toolchain for its default runtime.
7575e5dd7070Spatrick   // However, the rewriter only really supports the Mac runtime, so assume that.
7576e5dd7070Spatrick   ObjCRuntime runtime;
7577e5dd7070Spatrick   if (!runtimeArg) {
7578e5dd7070Spatrick     switch (rewriteKind) {
7579e5dd7070Spatrick     case RK_None:
7580e5dd7070Spatrick       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7581e5dd7070Spatrick       break;
7582e5dd7070Spatrick     case RK_Fragile:
7583e5dd7070Spatrick       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7584e5dd7070Spatrick       break;
7585e5dd7070Spatrick     case RK_NonFragile:
7586e5dd7070Spatrick       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7587e5dd7070Spatrick       break;
7588e5dd7070Spatrick     }
7589e5dd7070Spatrick 
7590e5dd7070Spatrick     // -fnext-runtime
7591e5dd7070Spatrick   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7592e5dd7070Spatrick     // On Darwin, make this use the default behavior for the toolchain.
7593e5dd7070Spatrick     if (getToolChain().getTriple().isOSDarwin()) {
7594e5dd7070Spatrick       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7595e5dd7070Spatrick 
7596e5dd7070Spatrick       // Otherwise, build for a generic macosx port.
7597e5dd7070Spatrick     } else {
7598e5dd7070Spatrick       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7599e5dd7070Spatrick     }
7600e5dd7070Spatrick 
7601e5dd7070Spatrick     // -fgnu-runtime
7602e5dd7070Spatrick   } else {
7603e5dd7070Spatrick     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7604e5dd7070Spatrick     // Legacy behaviour is to target the gnustep runtime if we are in
7605e5dd7070Spatrick     // non-fragile mode or the GCC runtime in fragile mode.
7606e5dd7070Spatrick     if (isNonFragile)
7607e5dd7070Spatrick       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7608e5dd7070Spatrick     else
7609e5dd7070Spatrick       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7610e5dd7070Spatrick   }
7611e5dd7070Spatrick 
7612adae0cfdSpatrick   if (llvm::any_of(inputs, [](const InputInfo &input) {
7613adae0cfdSpatrick         return types::isObjC(input.getType());
7614adae0cfdSpatrick       }))
7615e5dd7070Spatrick     cmdArgs.push_back(
7616e5dd7070Spatrick         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7617e5dd7070Spatrick   return runtime;
7618e5dd7070Spatrick }
7619e5dd7070Spatrick 
maybeConsumeDash(const std::string & EH,size_t & I)7620e5dd7070Spatrick static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7621e5dd7070Spatrick   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7622e5dd7070Spatrick   I += HaveDash;
7623e5dd7070Spatrick   return !HaveDash;
7624e5dd7070Spatrick }
7625e5dd7070Spatrick 
7626e5dd7070Spatrick namespace {
7627e5dd7070Spatrick struct EHFlags {
7628e5dd7070Spatrick   bool Synch = false;
7629e5dd7070Spatrick   bool Asynch = false;
7630e5dd7070Spatrick   bool NoUnwindC = false;
7631e5dd7070Spatrick };
7632e5dd7070Spatrick } // end anonymous namespace
7633e5dd7070Spatrick 
7634e5dd7070Spatrick /// /EH controls whether to run destructor cleanups when exceptions are
7635e5dd7070Spatrick /// thrown.  There are three modifiers:
7636e5dd7070Spatrick /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7637e5dd7070Spatrick /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7638e5dd7070Spatrick ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7639e5dd7070Spatrick /// - c: Assume that extern "C" functions are implicitly nounwind.
7640e5dd7070Spatrick /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args)7641e5dd7070Spatrick static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7642e5dd7070Spatrick   EHFlags EH;
7643e5dd7070Spatrick 
7644e5dd7070Spatrick   std::vector<std::string> EHArgs =
7645e5dd7070Spatrick       Args.getAllArgValues(options::OPT__SLASH_EH);
7646e5dd7070Spatrick   for (auto EHVal : EHArgs) {
7647e5dd7070Spatrick     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7648e5dd7070Spatrick       switch (EHVal[I]) {
7649e5dd7070Spatrick       case 'a':
7650e5dd7070Spatrick         EH.Asynch = maybeConsumeDash(EHVal, I);
7651e5dd7070Spatrick         if (EH.Asynch)
7652e5dd7070Spatrick           EH.Synch = false;
7653e5dd7070Spatrick         continue;
7654e5dd7070Spatrick       case 'c':
7655e5dd7070Spatrick         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7656e5dd7070Spatrick         continue;
7657e5dd7070Spatrick       case 's':
7658e5dd7070Spatrick         EH.Synch = maybeConsumeDash(EHVal, I);
7659e5dd7070Spatrick         if (EH.Synch)
7660e5dd7070Spatrick           EH.Asynch = false;
7661e5dd7070Spatrick         continue;
7662e5dd7070Spatrick       default:
7663e5dd7070Spatrick         break;
7664e5dd7070Spatrick       }
7665e5dd7070Spatrick       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7666e5dd7070Spatrick       break;
7667e5dd7070Spatrick     }
7668e5dd7070Spatrick   }
7669e5dd7070Spatrick   // The /GX, /GX- flags are only processed if there are not /EH flags.
7670e5dd7070Spatrick   // The default is that /GX is not specified.
7671e5dd7070Spatrick   if (EHArgs.empty() &&
7672e5dd7070Spatrick       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7673e5dd7070Spatrick                    /*Default=*/false)) {
7674e5dd7070Spatrick     EH.Synch = true;
7675e5dd7070Spatrick     EH.NoUnwindC = true;
7676e5dd7070Spatrick   }
7677e5dd7070Spatrick 
76787a9b00ceSrobert   if (Args.hasArg(options::OPT__SLASH_kernel)) {
76797a9b00ceSrobert     EH.Synch = false;
76807a9b00ceSrobert     EH.NoUnwindC = false;
76817a9b00ceSrobert     EH.Asynch = false;
76827a9b00ceSrobert   }
76837a9b00ceSrobert 
7684e5dd7070Spatrick   return EH;
7685e5dd7070Spatrick }
7686e5dd7070Spatrick 
AddClangCLArgs(const ArgList & Args,types::ID InputType,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind * DebugInfoKind,bool * EmitCodeView) const7687e5dd7070Spatrick void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7688e5dd7070Spatrick                            ArgStringList &CmdArgs,
7689e5dd7070Spatrick                            codegenoptions::DebugInfoKind *DebugInfoKind,
7690e5dd7070Spatrick                            bool *EmitCodeView) const {
7691adae0cfdSpatrick   bool isNVPTX = getToolChain().getTriple().isNVPTX();
7692e5dd7070Spatrick 
76937a9b00ceSrobert   ProcessVSRuntimeLibrary(Args, CmdArgs);
7694e5dd7070Spatrick 
7695adae0cfdSpatrick   if (Arg *ShowIncludes =
7696adae0cfdSpatrick           Args.getLastArg(options::OPT__SLASH_showIncludes,
7697adae0cfdSpatrick                           options::OPT__SLASH_showIncludes_user)) {
7698adae0cfdSpatrick     CmdArgs.push_back("--show-includes");
7699adae0cfdSpatrick     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7700adae0cfdSpatrick       CmdArgs.push_back("-sys-header-deps");
7701adae0cfdSpatrick   }
7702e5dd7070Spatrick 
7703e5dd7070Spatrick   // This controls whether or not we emit RTTI data for polymorphic types.
7704e5dd7070Spatrick   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7705e5dd7070Spatrick                    /*Default=*/false))
7706e5dd7070Spatrick     CmdArgs.push_back("-fno-rtti-data");
7707e5dd7070Spatrick 
7708e5dd7070Spatrick   // This controls whether or not we emit stack-protector instrumentation.
7709e5dd7070Spatrick   // In MSVC, Buffer Security Check (/GS) is on by default.
7710adae0cfdSpatrick   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7711e5dd7070Spatrick                                /*Default=*/true)) {
7712e5dd7070Spatrick     CmdArgs.push_back("-stack-protector");
7713e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7714e5dd7070Spatrick   }
7715e5dd7070Spatrick 
7716a0747c9fSpatrick   // Emit CodeView if -Z7 or -gline-tables-only are present.
7717a0747c9fSpatrick   if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7,
7718e5dd7070Spatrick                                           options::OPT_gline_tables_only)) {
7719e5dd7070Spatrick     *EmitCodeView = true;
7720e5dd7070Spatrick     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
7721a0747c9fSpatrick       *DebugInfoKind = codegenoptions::DebugInfoConstructor;
7722e5dd7070Spatrick     else
7723e5dd7070Spatrick       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
7724e5dd7070Spatrick   } else {
7725e5dd7070Spatrick     *EmitCodeView = false;
7726e5dd7070Spatrick   }
7727e5dd7070Spatrick 
7728e5dd7070Spatrick   const Driver &D = getToolChain().getDriver();
77297a9b00ceSrobert 
77307a9b00ceSrobert   // This controls whether or not we perform JustMyCode instrumentation.
77317a9b00ceSrobert   if (Args.hasFlag(options::OPT__SLASH_JMC, options::OPT__SLASH_JMC_,
77327a9b00ceSrobert                    /*Default=*/false)) {
77337a9b00ceSrobert     if (*EmitCodeView && *DebugInfoKind >= codegenoptions::DebugInfoConstructor)
77347a9b00ceSrobert       CmdArgs.push_back("-fjmc");
77357a9b00ceSrobert     else
77367a9b00ceSrobert       D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
77377a9b00ceSrobert                                                            << "'/Zi', '/Z7'";
77387a9b00ceSrobert   }
77397a9b00ceSrobert 
7740e5dd7070Spatrick   EHFlags EH = parseClangCLEHFlags(D, Args);
7741adae0cfdSpatrick   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7742e5dd7070Spatrick     if (types::isCXX(InputType))
7743e5dd7070Spatrick       CmdArgs.push_back("-fcxx-exceptions");
7744e5dd7070Spatrick     CmdArgs.push_back("-fexceptions");
7745e5dd7070Spatrick   }
7746e5dd7070Spatrick   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7747e5dd7070Spatrick     CmdArgs.push_back("-fexternc-nounwind");
7748e5dd7070Spatrick 
7749e5dd7070Spatrick   // /EP should expand to -E -P.
7750e5dd7070Spatrick   if (Args.hasArg(options::OPT__SLASH_EP)) {
7751e5dd7070Spatrick     CmdArgs.push_back("-E");
7752e5dd7070Spatrick     CmdArgs.push_back("-P");
7753e5dd7070Spatrick   }
7754e5dd7070Spatrick 
7755e5dd7070Spatrick   unsigned VolatileOptionID;
7756e5dd7070Spatrick   if (getToolChain().getTriple().isX86())
7757e5dd7070Spatrick     VolatileOptionID = options::OPT__SLASH_volatile_ms;
7758e5dd7070Spatrick   else
7759e5dd7070Spatrick     VolatileOptionID = options::OPT__SLASH_volatile_iso;
7760e5dd7070Spatrick 
7761e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
7762e5dd7070Spatrick     VolatileOptionID = A->getOption().getID();
7763e5dd7070Spatrick 
7764e5dd7070Spatrick   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
7765e5dd7070Spatrick     CmdArgs.push_back("-fms-volatile");
7766e5dd7070Spatrick 
7767e5dd7070Spatrick  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7768e5dd7070Spatrick                   options::OPT__SLASH_Zc_dllexportInlines,
7769e5dd7070Spatrick                   false)) {
7770e5dd7070Spatrick   CmdArgs.push_back("-fno-dllexport-inlines");
7771e5dd7070Spatrick  }
7772e5dd7070Spatrick 
77737a9b00ceSrobert  if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
77747a9b00ceSrobert                   options::OPT__SLASH_Zc_wchar_t, false)) {
77757a9b00ceSrobert    CmdArgs.push_back("-fno-wchar");
77767a9b00ceSrobert  }
77777a9b00ceSrobert 
77787a9b00ceSrobert  if (Args.hasArg(options::OPT__SLASH_kernel)) {
77797a9b00ceSrobert    llvm::Triple::ArchType Arch = getToolChain().getArch();
77807a9b00ceSrobert    std::vector<std::string> Values =
77817a9b00ceSrobert        Args.getAllArgValues(options::OPT__SLASH_arch);
77827a9b00ceSrobert    if (!Values.empty()) {
77837a9b00ceSrobert      llvm::SmallSet<std::string, 4> SupportedArches;
77847a9b00ceSrobert      if (Arch == llvm::Triple::x86)
77857a9b00ceSrobert        SupportedArches.insert("IA32");
77867a9b00ceSrobert 
77877a9b00ceSrobert      for (auto &V : Values)
77887a9b00ceSrobert        if (!SupportedArches.contains(V))
77897a9b00ceSrobert          D.Diag(diag::err_drv_argument_not_allowed_with)
77907a9b00ceSrobert              << std::string("/arch:").append(V) << "/kernel";
77917a9b00ceSrobert    }
77927a9b00ceSrobert 
77937a9b00ceSrobert    CmdArgs.push_back("-fno-rtti");
77947a9b00ceSrobert    if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
77957a9b00ceSrobert      D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
77967a9b00ceSrobert                                                      << "/kernel";
77977a9b00ceSrobert  }
77987a9b00ceSrobert 
7799e5dd7070Spatrick   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
7800e5dd7070Spatrick   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
7801e5dd7070Spatrick   if (MostGeneralArg && BestCaseArg)
7802e5dd7070Spatrick     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7803e5dd7070Spatrick         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
7804e5dd7070Spatrick 
7805e5dd7070Spatrick   if (MostGeneralArg) {
7806e5dd7070Spatrick     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
7807e5dd7070Spatrick     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
7808e5dd7070Spatrick     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
7809e5dd7070Spatrick 
7810e5dd7070Spatrick     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
7811e5dd7070Spatrick     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
7812e5dd7070Spatrick     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
7813e5dd7070Spatrick       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7814e5dd7070Spatrick           << FirstConflict->getAsString(Args)
7815e5dd7070Spatrick           << SecondConflict->getAsString(Args);
7816e5dd7070Spatrick 
7817e5dd7070Spatrick     if (SingleArg)
7818e5dd7070Spatrick       CmdArgs.push_back("-fms-memptr-rep=single");
7819e5dd7070Spatrick     else if (MultipleArg)
7820e5dd7070Spatrick       CmdArgs.push_back("-fms-memptr-rep=multiple");
7821e5dd7070Spatrick     else
7822e5dd7070Spatrick       CmdArgs.push_back("-fms-memptr-rep=virtual");
7823e5dd7070Spatrick   }
7824e5dd7070Spatrick 
7825e5dd7070Spatrick   // Parse the default calling convention options.
7826e5dd7070Spatrick   if (Arg *CCArg =
7827e5dd7070Spatrick           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
7828e5dd7070Spatrick                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
7829e5dd7070Spatrick                           options::OPT__SLASH_Gregcall)) {
7830e5dd7070Spatrick     unsigned DCCOptId = CCArg->getOption().getID();
7831e5dd7070Spatrick     const char *DCCFlag = nullptr;
7832adae0cfdSpatrick     bool ArchSupported = !isNVPTX;
7833e5dd7070Spatrick     llvm::Triple::ArchType Arch = getToolChain().getArch();
7834e5dd7070Spatrick     switch (DCCOptId) {
7835e5dd7070Spatrick     case options::OPT__SLASH_Gd:
7836e5dd7070Spatrick       DCCFlag = "-fdefault-calling-conv=cdecl";
7837e5dd7070Spatrick       break;
7838e5dd7070Spatrick     case options::OPT__SLASH_Gr:
7839e5dd7070Spatrick       ArchSupported = Arch == llvm::Triple::x86;
7840e5dd7070Spatrick       DCCFlag = "-fdefault-calling-conv=fastcall";
7841e5dd7070Spatrick       break;
7842e5dd7070Spatrick     case options::OPT__SLASH_Gz:
7843e5dd7070Spatrick       ArchSupported = Arch == llvm::Triple::x86;
7844e5dd7070Spatrick       DCCFlag = "-fdefault-calling-conv=stdcall";
7845e5dd7070Spatrick       break;
7846e5dd7070Spatrick     case options::OPT__SLASH_Gv:
7847e5dd7070Spatrick       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7848e5dd7070Spatrick       DCCFlag = "-fdefault-calling-conv=vectorcall";
7849e5dd7070Spatrick       break;
7850e5dd7070Spatrick     case options::OPT__SLASH_Gregcall:
7851e5dd7070Spatrick       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7852e5dd7070Spatrick       DCCFlag = "-fdefault-calling-conv=regcall";
7853e5dd7070Spatrick       break;
7854e5dd7070Spatrick     }
7855e5dd7070Spatrick 
7856e5dd7070Spatrick     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
7857e5dd7070Spatrick     if (ArchSupported && DCCFlag)
7858e5dd7070Spatrick       CmdArgs.push_back(DCCFlag);
7859e5dd7070Spatrick   }
7860e5dd7070Spatrick 
7861e5dd7070Spatrick   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
7862e5dd7070Spatrick 
7863e5dd7070Spatrick   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
7864e5dd7070Spatrick     CmdArgs.push_back("-fdiagnostics-format");
7865e5dd7070Spatrick     CmdArgs.push_back("msvc");
7866e5dd7070Spatrick   }
7867e5dd7070Spatrick 
78687a9b00ceSrobert   if (Args.hasArg(options::OPT__SLASH_kernel))
78697a9b00ceSrobert     CmdArgs.push_back("-fms-kernel");
78707a9b00ceSrobert 
78717a9b00ceSrobert   for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
7872e5dd7070Spatrick     StringRef GuardArgs = A->getValue();
7873a0747c9fSpatrick     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
7874a0747c9fSpatrick     // "ehcont-".
7875a0747c9fSpatrick     if (GuardArgs.equals_insensitive("cf")) {
7876e5dd7070Spatrick       // Emit CFG instrumentation and the table of address-taken functions.
7877e5dd7070Spatrick       CmdArgs.push_back("-cfguard");
7878a0747c9fSpatrick     } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
7879e5dd7070Spatrick       // Emit only the table of address-taken functions.
7880e5dd7070Spatrick       CmdArgs.push_back("-cfguard-no-checks");
7881a0747c9fSpatrick     } else if (GuardArgs.equals_insensitive("ehcont")) {
7882a0747c9fSpatrick       // Emit EH continuation table.
7883a0747c9fSpatrick       CmdArgs.push_back("-ehcontguard");
7884a0747c9fSpatrick     } else if (GuardArgs.equals_insensitive("cf-") ||
7885a0747c9fSpatrick                GuardArgs.equals_insensitive("ehcont-")) {
7886e5dd7070Spatrick       // Do nothing, but we might want to emit a security warning in future.
7887e5dd7070Spatrick     } else {
7888e5dd7070Spatrick       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
7889e5dd7070Spatrick     }
78907a9b00ceSrobert     A->claim();
7891e5dd7070Spatrick   }
7892e5dd7070Spatrick }
7893e5dd7070Spatrick 
getBaseInputName(const ArgList & Args,const InputInfo & Input)7894e5dd7070Spatrick const char *Clang::getBaseInputName(const ArgList &Args,
7895e5dd7070Spatrick                                     const InputInfo &Input) {
7896e5dd7070Spatrick   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7897e5dd7070Spatrick }
7898e5dd7070Spatrick 
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)7899e5dd7070Spatrick const char *Clang::getBaseInputStem(const ArgList &Args,
7900e5dd7070Spatrick                                     const InputInfoList &Inputs) {
7901e5dd7070Spatrick   const char *Str = getBaseInputName(Args, Inputs[0]);
7902e5dd7070Spatrick 
7903e5dd7070Spatrick   if (const char *End = strrchr(Str, '.'))
7904e5dd7070Spatrick     return Args.MakeArgString(std::string(Str, End));
7905e5dd7070Spatrick 
7906e5dd7070Spatrick   return Str;
7907e5dd7070Spatrick }
7908e5dd7070Spatrick 
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)7909e5dd7070Spatrick const char *Clang::getDependencyFileName(const ArgList &Args,
7910e5dd7070Spatrick                                          const InputInfoList &Inputs) {
7911e5dd7070Spatrick   // FIXME: Think about this more.
7912e5dd7070Spatrick 
7913e5dd7070Spatrick   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7914e5dd7070Spatrick     SmallString<128> OutputFilename(OutputOpt->getValue());
7915e5dd7070Spatrick     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
7916e5dd7070Spatrick     return Args.MakeArgString(OutputFilename);
7917e5dd7070Spatrick   }
7918e5dd7070Spatrick 
7919e5dd7070Spatrick   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
7920e5dd7070Spatrick }
7921e5dd7070Spatrick 
7922e5dd7070Spatrick // Begin ClangAs
7923e5dd7070Spatrick 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const7924e5dd7070Spatrick void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
7925e5dd7070Spatrick                                 ArgStringList &CmdArgs) const {
7926e5dd7070Spatrick   StringRef CPUName;
7927e5dd7070Spatrick   StringRef ABIName;
7928e5dd7070Spatrick   const llvm::Triple &Triple = getToolChain().getTriple();
7929e5dd7070Spatrick   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
7930e5dd7070Spatrick 
7931e5dd7070Spatrick   CmdArgs.push_back("-target-abi");
7932e5dd7070Spatrick   CmdArgs.push_back(ABIName.data());
7933e5dd7070Spatrick }
7934e5dd7070Spatrick 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const7935e5dd7070Spatrick void ClangAs::AddX86TargetArgs(const ArgList &Args,
7936e5dd7070Spatrick                                ArgStringList &CmdArgs) const {
7937adae0cfdSpatrick   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
7938adae0cfdSpatrick                         /*IsLTO=*/false);
7939e5dd7070Spatrick 
7940e5dd7070Spatrick   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
7941e5dd7070Spatrick     StringRef Value = A->getValue();
7942e5dd7070Spatrick     if (Value == "intel" || Value == "att") {
7943e5dd7070Spatrick       CmdArgs.push_back("-mllvm");
7944e5dd7070Spatrick       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
7945e5dd7070Spatrick     } else {
7946e5dd7070Spatrick       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
79477a9b00ceSrobert           << A->getSpelling() << Value;
7948e5dd7070Spatrick     }
7949e5dd7070Spatrick   }
7950e5dd7070Spatrick }
7951e5dd7070Spatrick 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const7952e5dd7070Spatrick void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
7953e5dd7070Spatrick                                ArgStringList &CmdArgs) const {
7954e5dd7070Spatrick   const llvm::Triple &Triple = getToolChain().getTriple();
7955e5dd7070Spatrick   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
7956e5dd7070Spatrick 
7957e5dd7070Spatrick   CmdArgs.push_back("-target-abi");
7958e5dd7070Spatrick   CmdArgs.push_back(ABIName.data());
7959e5dd7070Spatrick }
7960e5dd7070Spatrick 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7961e5dd7070Spatrick void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
7962e5dd7070Spatrick                            const InputInfo &Output, const InputInfoList &Inputs,
7963e5dd7070Spatrick                            const ArgList &Args,
7964e5dd7070Spatrick                            const char *LinkingOutput) const {
7965e5dd7070Spatrick   ArgStringList CmdArgs;
7966e5dd7070Spatrick 
7967e5dd7070Spatrick   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7968e5dd7070Spatrick   const InputInfo &Input = Inputs[0];
7969e5dd7070Spatrick 
7970e5dd7070Spatrick   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
7971e5dd7070Spatrick   const std::string &TripleStr = Triple.getTriple();
7972e5dd7070Spatrick   const auto &D = getToolChain().getDriver();
7973e5dd7070Spatrick 
7974e5dd7070Spatrick   // Don't warn about "clang -w -c foo.s"
7975e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_w);
7976e5dd7070Spatrick   // and "clang -emit-llvm -c foo.s"
7977e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_emit_llvm);
7978e5dd7070Spatrick 
7979e5dd7070Spatrick   claimNoWarnArgs(Args);
7980e5dd7070Spatrick 
7981e5dd7070Spatrick   // Invoke ourselves in -cc1as mode.
7982e5dd7070Spatrick   //
7983e5dd7070Spatrick   // FIXME: Implement custom jobs for internal actions.
7984e5dd7070Spatrick   CmdArgs.push_back("-cc1as");
7985e5dd7070Spatrick 
7986e5dd7070Spatrick   // Add the "effective" target triple.
7987e5dd7070Spatrick   CmdArgs.push_back("-triple");
7988e5dd7070Spatrick   CmdArgs.push_back(Args.MakeArgString(TripleStr));
7989e5dd7070Spatrick 
79907a9b00ceSrobert   getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
79917a9b00ceSrobert 
7992e5dd7070Spatrick   // Set the output mode, we currently only expect to be used as a real
7993e5dd7070Spatrick   // assembler.
7994e5dd7070Spatrick   CmdArgs.push_back("-filetype");
7995e5dd7070Spatrick   CmdArgs.push_back("obj");
7996e5dd7070Spatrick 
7997e5dd7070Spatrick   // Set the main file name, so that debug info works even with
7998e5dd7070Spatrick   // -save-temps or preprocessed assembly.
7999e5dd7070Spatrick   CmdArgs.push_back("-main-file-name");
8000e5dd7070Spatrick   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8001e5dd7070Spatrick 
8002e5dd7070Spatrick   // Add the target cpu
80037a9b00ceSrobert   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8004e5dd7070Spatrick   if (!CPU.empty()) {
8005e5dd7070Spatrick     CmdArgs.push_back("-target-cpu");
8006e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(CPU));
8007e5dd7070Spatrick   }
8008e5dd7070Spatrick 
8009e5dd7070Spatrick   // Add the target features
8010adae0cfdSpatrick   getTargetFeatures(D, Triple, Args, CmdArgs, true);
8011e5dd7070Spatrick 
8012e5dd7070Spatrick   // Ignore explicit -force_cpusubtype_ALL option.
8013e5dd7070Spatrick   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8014e5dd7070Spatrick 
8015e5dd7070Spatrick   // Pass along any -I options so we get proper .include search paths.
8016e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8017e5dd7070Spatrick 
8018e5dd7070Spatrick   // Determine the original source input.
80197a9b00ceSrobert   auto FindSource = [](const Action *S) -> const Action * {
80207a9b00ceSrobert     while (S->getKind() != Action::InputClass) {
80217a9b00ceSrobert       assert(!S->getInputs().empty() && "unexpected root action!");
80227a9b00ceSrobert       S = S->getInputs()[0];
8023e5dd7070Spatrick     }
80247a9b00ceSrobert     return S;
80257a9b00ceSrobert   };
80267a9b00ceSrobert   const Action *SourceAction = FindSource(&JA);
8027e5dd7070Spatrick 
8028e5dd7070Spatrick   // Forward -g and handle debug info related flags, assuming we are dealing
8029e5dd7070Spatrick   // with an actual assembly file.
8030e5dd7070Spatrick   bool WantDebug = false;
8031e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_g_Group);
8032a0747c9fSpatrick   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8033e5dd7070Spatrick     WantDebug = !A->getOption().matches(options::OPT_g0) &&
8034e5dd7070Spatrick                 !A->getOption().matches(options::OPT_ggdb0);
8035e5dd7070Spatrick 
8036e5dd7070Spatrick   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
8037e5dd7070Spatrick 
80387a9b00ceSrobert   // Add the -fdebug-compilation-dir flag if needed.
80397a9b00ceSrobert   const char *DebugCompilationDir =
80407a9b00ceSrobert       addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
80417a9b00ceSrobert 
8042e5dd7070Spatrick   if (SourceAction->getType() == types::TY_Asm ||
8043e5dd7070Spatrick       SourceAction->getType() == types::TY_PP_Asm) {
8044e5dd7070Spatrick     // You might think that it would be ok to set DebugInfoKind outside of
8045e5dd7070Spatrick     // the guard for source type, however there is a test which asserts
8046e5dd7070Spatrick     // that some assembler invocation receives no -debug-info-kind,
8047e5dd7070Spatrick     // and it's not clear whether that test is just overly restrictive.
8048a0747c9fSpatrick     DebugInfoKind = (WantDebug ? codegenoptions::DebugInfoConstructor
8049e5dd7070Spatrick                                : codegenoptions::NoDebugInfo);
8050e5dd7070Spatrick 
80517a9b00ceSrobert     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
80527a9b00ceSrobert                          CmdArgs);
8053e5dd7070Spatrick 
8054e5dd7070Spatrick     // Set the AT_producer to the clang version when using the integrated
8055e5dd7070Spatrick     // assembler on assembly source files.
8056e5dd7070Spatrick     CmdArgs.push_back("-dwarf-debug-producer");
8057e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8058e5dd7070Spatrick 
8059e5dd7070Spatrick     // And pass along -I options
8060e5dd7070Spatrick     Args.AddAllArgs(CmdArgs, options::OPT_I);
8061e5dd7070Spatrick   }
80627a9b00ceSrobert   const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8063e5dd7070Spatrick   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8064e5dd7070Spatrick                           llvm::DebuggerKind::Default);
8065a0747c9fSpatrick   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8066e5dd7070Spatrick   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
8067e5dd7070Spatrick 
8068e5dd7070Spatrick   // Handle -fPIC et al -- the relocation-model affects the assembler
8069e5dd7070Spatrick   // for some targets.
8070e5dd7070Spatrick   llvm::Reloc::Model RelocationModel;
8071e5dd7070Spatrick   unsigned PICLevel;
8072e5dd7070Spatrick   bool IsPIE;
8073e5dd7070Spatrick   std::tie(RelocationModel, PICLevel, IsPIE) =
8074e5dd7070Spatrick       ParsePICArgs(getToolChain(), Args);
8075e5dd7070Spatrick 
8076e5dd7070Spatrick   const char *RMName = RelocationModelName(RelocationModel);
8077e5dd7070Spatrick   if (RMName) {
8078e5dd7070Spatrick     CmdArgs.push_back("-mrelocation-model");
8079e5dd7070Spatrick     CmdArgs.push_back(RMName);
8080e5dd7070Spatrick   }
8081e5dd7070Spatrick 
8082e5dd7070Spatrick   // Optionally embed the -cc1as level arguments into the debug info, for build
8083e5dd7070Spatrick   // analysis.
8084e5dd7070Spatrick   if (getToolChain().UseDwarfDebugFlags()) {
8085e5dd7070Spatrick     ArgStringList OriginalArgs;
8086e5dd7070Spatrick     for (const auto &Arg : Args)
8087e5dd7070Spatrick       Arg->render(Args, OriginalArgs);
8088e5dd7070Spatrick 
8089e5dd7070Spatrick     SmallString<256> Flags;
8090e5dd7070Spatrick     const char *Exec = getToolChain().getDriver().getClangProgramPath();
8091adae0cfdSpatrick     EscapeSpacesAndBackslashes(Exec, Flags);
8092e5dd7070Spatrick     for (const char *OriginalArg : OriginalArgs) {
8093e5dd7070Spatrick       SmallString<128> EscapedArg;
8094e5dd7070Spatrick       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8095e5dd7070Spatrick       Flags += " ";
8096e5dd7070Spatrick       Flags += EscapedArg;
8097e5dd7070Spatrick     }
8098e5dd7070Spatrick     CmdArgs.push_back("-dwarf-debug-flags");
8099e5dd7070Spatrick     CmdArgs.push_back(Args.MakeArgString(Flags));
8100e5dd7070Spatrick   }
8101e5dd7070Spatrick 
8102e5dd7070Spatrick   // FIXME: Add -static support, once we have it.
8103e5dd7070Spatrick 
8104e5dd7070Spatrick   // Add target specific flags.
8105e5dd7070Spatrick   switch (getToolChain().getArch()) {
8106e5dd7070Spatrick   default:
8107e5dd7070Spatrick     break;
8108e5dd7070Spatrick 
8109e5dd7070Spatrick   case llvm::Triple::mips:
8110e5dd7070Spatrick   case llvm::Triple::mipsel:
8111e5dd7070Spatrick   case llvm::Triple::mips64:
8112e5dd7070Spatrick   case llvm::Triple::mips64el:
8113e5dd7070Spatrick     AddMIPSTargetArgs(Args, CmdArgs);
8114e5dd7070Spatrick     break;
8115e5dd7070Spatrick 
8116e5dd7070Spatrick   case llvm::Triple::x86:
8117e5dd7070Spatrick   case llvm::Triple::x86_64:
8118e5dd7070Spatrick     AddX86TargetArgs(Args, CmdArgs);
8119e5dd7070Spatrick     break;
8120e5dd7070Spatrick 
8121e5dd7070Spatrick   case llvm::Triple::arm:
8122e5dd7070Spatrick   case llvm::Triple::armeb:
8123e5dd7070Spatrick   case llvm::Triple::thumb:
8124e5dd7070Spatrick   case llvm::Triple::thumbeb:
8125e5dd7070Spatrick     // This isn't in AddARMTargetArgs because we want to do this for assembly
8126e5dd7070Spatrick     // only, not C/C++.
8127e5dd7070Spatrick     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8128e5dd7070Spatrick                      options::OPT_mno_default_build_attributes, true)) {
8129e5dd7070Spatrick         CmdArgs.push_back("-mllvm");
8130e5dd7070Spatrick         CmdArgs.push_back("-arm-add-build-attributes");
8131e5dd7070Spatrick     }
8132e5dd7070Spatrick     break;
8133e5dd7070Spatrick 
8134a0747c9fSpatrick   case llvm::Triple::aarch64:
8135a0747c9fSpatrick   case llvm::Triple::aarch64_32:
8136a0747c9fSpatrick   case llvm::Triple::aarch64_be:
8137a0747c9fSpatrick     if (Args.hasArg(options::OPT_mmark_bti_property)) {
8138a0747c9fSpatrick       CmdArgs.push_back("-mllvm");
8139a0747c9fSpatrick       CmdArgs.push_back("-aarch64-mark-bti-property");
8140a0747c9fSpatrick     }
8141a0747c9fSpatrick     break;
8142a0747c9fSpatrick 
8143e5dd7070Spatrick   case llvm::Triple::riscv32:
8144e5dd7070Spatrick   case llvm::Triple::riscv64:
8145e5dd7070Spatrick     AddRISCVTargetArgs(Args, CmdArgs);
8146e5dd7070Spatrick     break;
8147e5dd7070Spatrick   }
8148e5dd7070Spatrick 
8149e5dd7070Spatrick   // Consume all the warning flags. Usually this would be handled more
8150e5dd7070Spatrick   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8151e5dd7070Spatrick   // doesn't handle that so rather than warning about unused flags that are
8152e5dd7070Spatrick   // actually used, we'll lie by omission instead.
8153e5dd7070Spatrick   // FIXME: Stop lying and consume only the appropriate driver flags
8154e5dd7070Spatrick   Args.ClaimAllArgs(options::OPT_W_Group);
8155e5dd7070Spatrick 
8156e5dd7070Spatrick   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8157e5dd7070Spatrick                                     getToolChain().getDriver());
8158e5dd7070Spatrick 
8159e5dd7070Spatrick   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8160e5dd7070Spatrick 
81617a9b00ceSrobert   if (DebugInfoKind > codegenoptions::NoDebugInfo && Output.isFilename())
81627a9b00ceSrobert     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
81637a9b00ceSrobert                        Output.getFilename());
81647a9b00ceSrobert 
81657a9b00ceSrobert   // Fixup any previous commands that use -object-file-name because when we
81667a9b00ceSrobert   // generated them, the final .obj name wasn't yet known.
81677a9b00ceSrobert   for (Command &J : C.getJobs()) {
81687a9b00ceSrobert     if (SourceAction != FindSource(&J.getSource()))
81697a9b00ceSrobert       continue;
81707a9b00ceSrobert     auto &JArgs = J.getArguments();
81717a9b00ceSrobert     for (unsigned I = 0; I < JArgs.size(); ++I) {
81727a9b00ceSrobert       if (StringRef(JArgs[I]).startswith("-object-file-name=") &&
81737a9b00ceSrobert           Output.isFilename()) {
81747a9b00ceSrobert         ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
81757a9b00ceSrobert         addDebugObjectName(Args, NewArgs, DebugCompilationDir,
81767a9b00ceSrobert                            Output.getFilename());
81777a9b00ceSrobert         NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
81787a9b00ceSrobert         J.replaceArguments(NewArgs);
81797a9b00ceSrobert         break;
81807a9b00ceSrobert       }
81817a9b00ceSrobert     }
81827a9b00ceSrobert   }
81837a9b00ceSrobert 
8184e5dd7070Spatrick   assert(Output.isFilename() && "Unexpected lipo output.");
8185e5dd7070Spatrick   CmdArgs.push_back("-o");
8186e5dd7070Spatrick   CmdArgs.push_back(Output.getFilename());
8187e5dd7070Spatrick 
8188e5dd7070Spatrick   const llvm::Triple &T = getToolChain().getTriple();
8189e5dd7070Spatrick   Arg *A;
8190e5dd7070Spatrick   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
8191e5dd7070Spatrick       T.isOSBinFormatELF()) {
8192e5dd7070Spatrick     CmdArgs.push_back("-split-dwarf-output");
8193a0747c9fSpatrick     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8194e5dd7070Spatrick   }
8195e5dd7070Spatrick 
8196a0747c9fSpatrick   if (Triple.isAMDGPU())
81977a9b00ceSrobert     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8198a0747c9fSpatrick 
8199e5dd7070Spatrick   assert(Input.isFilename() && "Invalid input.");
8200e5dd7070Spatrick   CmdArgs.push_back(Input.getFilename());
8201e5dd7070Spatrick 
8202e5dd7070Spatrick   const char *Exec = getToolChain().getDriver().getClangProgramPath();
8203a0747c9fSpatrick   if (D.CC1Main && !D.CCGenDiagnostics) {
8204a0747c9fSpatrick     // Invoke cc1as directly in this process.
8205a0747c9fSpatrick     C.addCommand(std::make_unique<CC1Command>(JA, *this,
8206a0747c9fSpatrick                                               ResponseFileSupport::AtFileUTF8(),
8207a0747c9fSpatrick                                               Exec, CmdArgs, Inputs, Output));
8208a0747c9fSpatrick   } else {
8209a0747c9fSpatrick     C.addCommand(std::make_unique<Command>(JA, *this,
8210a0747c9fSpatrick                                            ResponseFileSupport::AtFileUTF8(),
8211a0747c9fSpatrick                                            Exec, CmdArgs, Inputs, Output));
8212a0747c9fSpatrick   }
8213e5dd7070Spatrick }
8214e5dd7070Spatrick 
8215e5dd7070Spatrick // Begin OffloadBundler
8216e5dd7070Spatrick 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const8217e5dd7070Spatrick void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8218e5dd7070Spatrick                                   const InputInfo &Output,
8219e5dd7070Spatrick                                   const InputInfoList &Inputs,
8220e5dd7070Spatrick                                   const llvm::opt::ArgList &TCArgs,
8221e5dd7070Spatrick                                   const char *LinkingOutput) const {
8222e5dd7070Spatrick   // The version with only one output is expected to refer to a bundling job.
8223e5dd7070Spatrick   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8224e5dd7070Spatrick 
8225e5dd7070Spatrick   // The bundling command looks like this:
8226e5dd7070Spatrick   // clang-offload-bundler -type=bc
8227e5dd7070Spatrick   //   -targets=host-triple,openmp-triple1,openmp-triple2
82287a9b00ceSrobert   //   -output=output_file
82297a9b00ceSrobert   //   -input=unbundle_file_host
82307a9b00ceSrobert   //   -input=unbundle_file_tgt1
82317a9b00ceSrobert   //   -input=unbundle_file_tgt2
8232e5dd7070Spatrick 
8233e5dd7070Spatrick   ArgStringList CmdArgs;
8234e5dd7070Spatrick 
8235e5dd7070Spatrick   // Get the type.
8236e5dd7070Spatrick   CmdArgs.push_back(TCArgs.MakeArgString(
8237e5dd7070Spatrick       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8238e5dd7070Spatrick 
8239e5dd7070Spatrick   assert(JA.getInputs().size() == Inputs.size() &&
8240e5dd7070Spatrick          "Not have inputs for all dependence actions??");
8241e5dd7070Spatrick 
8242e5dd7070Spatrick   // Get the targets.
8243e5dd7070Spatrick   SmallString<128> Triples;
8244e5dd7070Spatrick   Triples += "-targets=";
8245e5dd7070Spatrick   for (unsigned I = 0; I < Inputs.size(); ++I) {
8246e5dd7070Spatrick     if (I)
8247e5dd7070Spatrick       Triples += ',';
8248e5dd7070Spatrick 
8249e5dd7070Spatrick     // Find ToolChain for this input.
8250e5dd7070Spatrick     Action::OffloadKind CurKind = Action::OFK_Host;
8251e5dd7070Spatrick     const ToolChain *CurTC = &getToolChain();
8252e5dd7070Spatrick     const Action *CurDep = JA.getInputs()[I];
8253e5dd7070Spatrick 
8254e5dd7070Spatrick     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8255e5dd7070Spatrick       CurTC = nullptr;
8256e5dd7070Spatrick       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8257e5dd7070Spatrick         assert(CurTC == nullptr && "Expected one dependence!");
8258e5dd7070Spatrick         CurKind = A->getOffloadingDeviceKind();
8259e5dd7070Spatrick         CurTC = TC;
8260e5dd7070Spatrick       });
8261e5dd7070Spatrick     }
8262e5dd7070Spatrick     Triples += Action::GetOffloadKindName(CurKind);
82637a9b00ceSrobert     Triples += '-';
82647a9b00ceSrobert     Triples += CurTC->getTriple().normalize();
82657a9b00ceSrobert     if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
82667a9b00ceSrobert         !StringRef(CurDep->getOffloadingArch()).empty()) {
82677a9b00ceSrobert       Triples += '-';
8268e5dd7070Spatrick       Triples += CurDep->getOffloadingArch();
8269e5dd7070Spatrick     }
82707a9b00ceSrobert 
82717a9b00ceSrobert     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
82727a9b00ceSrobert     //       with each toolchain.
82737a9b00ceSrobert     StringRef GPUArchName;
82747a9b00ceSrobert     if (CurKind == Action::OFK_OpenMP) {
82757a9b00ceSrobert       // Extract GPUArch from -march argument in TC argument list.
82767a9b00ceSrobert       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
82777a9b00ceSrobert         auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
82787a9b00ceSrobert         auto Arch = ArchStr.startswith_insensitive("-march=");
82797a9b00ceSrobert         if (Arch) {
82807a9b00ceSrobert           GPUArchName = ArchStr.substr(7);
82817a9b00ceSrobert           Triples += "-";
82827a9b00ceSrobert           break;
82837a9b00ceSrobert         }
82847a9b00ceSrobert       }
82857a9b00ceSrobert       Triples += GPUArchName.str();
82867a9b00ceSrobert     }
8287e5dd7070Spatrick   }
8288e5dd7070Spatrick   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8289e5dd7070Spatrick 
8290e5dd7070Spatrick   // Get bundled file command.
8291e5dd7070Spatrick   CmdArgs.push_back(
82927a9b00ceSrobert       TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8293e5dd7070Spatrick 
8294e5dd7070Spatrick   // Get unbundled files command.
8295e5dd7070Spatrick   for (unsigned I = 0; I < Inputs.size(); ++I) {
82967a9b00ceSrobert     SmallString<128> UB;
82977a9b00ceSrobert     UB += "-input=";
8298e5dd7070Spatrick 
8299e5dd7070Spatrick     // Find ToolChain for this input.
8300e5dd7070Spatrick     const ToolChain *CurTC = &getToolChain();
8301e5dd7070Spatrick     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8302e5dd7070Spatrick       CurTC = nullptr;
8303e5dd7070Spatrick       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8304e5dd7070Spatrick         assert(CurTC == nullptr && "Expected one dependence!");
8305e5dd7070Spatrick         CurTC = TC;
8306e5dd7070Spatrick       });
8307a0747c9fSpatrick       UB += C.addTempFile(
8308a0747c9fSpatrick           C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8309a0747c9fSpatrick     } else {
8310e5dd7070Spatrick       UB += CurTC->getInputFilename(Inputs[I]);
8311e5dd7070Spatrick     }
8312e5dd7070Spatrick     CmdArgs.push_back(TCArgs.MakeArgString(UB));
83137a9b00ceSrobert   }
8314e5dd7070Spatrick   // All the inputs are encoded as commands.
8315e5dd7070Spatrick   C.addCommand(std::make_unique<Command>(
8316adae0cfdSpatrick       JA, *this, ResponseFileSupport::None(),
8317e5dd7070Spatrick       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
83187a9b00ceSrobert       CmdArgs, std::nullopt, Output));
8319e5dd7070Spatrick }
8320e5dd7070Spatrick 
ConstructJobMultipleOutputs(Compilation & C,const JobAction & JA,const InputInfoList & Outputs,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const8321e5dd7070Spatrick void OffloadBundler::ConstructJobMultipleOutputs(
8322e5dd7070Spatrick     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8323e5dd7070Spatrick     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8324e5dd7070Spatrick     const char *LinkingOutput) const {
8325e5dd7070Spatrick   // The version with multiple outputs is expected to refer to a unbundling job.
8326e5dd7070Spatrick   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8327e5dd7070Spatrick 
8328e5dd7070Spatrick   // The unbundling command looks like this:
8329e5dd7070Spatrick   // clang-offload-bundler -type=bc
8330e5dd7070Spatrick   //   -targets=host-triple,openmp-triple1,openmp-triple2
83317a9b00ceSrobert   //   -input=input_file
83327a9b00ceSrobert   //   -output=unbundle_file_host
83337a9b00ceSrobert   //   -output=unbundle_file_tgt1
83347a9b00ceSrobert   //   -output=unbundle_file_tgt2
8335e5dd7070Spatrick   //   -unbundle
8336e5dd7070Spatrick 
8337e5dd7070Spatrick   ArgStringList CmdArgs;
8338e5dd7070Spatrick 
8339e5dd7070Spatrick   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8340e5dd7070Spatrick   InputInfo Input = Inputs.front();
8341e5dd7070Spatrick 
8342e5dd7070Spatrick   // Get the type.
8343e5dd7070Spatrick   CmdArgs.push_back(TCArgs.MakeArgString(
8344e5dd7070Spatrick       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8345e5dd7070Spatrick 
8346e5dd7070Spatrick   // Get the targets.
8347e5dd7070Spatrick   SmallString<128> Triples;
8348e5dd7070Spatrick   Triples += "-targets=";
8349e5dd7070Spatrick   auto DepInfo = UA.getDependentActionsInfo();
8350e5dd7070Spatrick   for (unsigned I = 0; I < DepInfo.size(); ++I) {
8351e5dd7070Spatrick     if (I)
8352e5dd7070Spatrick       Triples += ',';
8353e5dd7070Spatrick 
8354e5dd7070Spatrick     auto &Dep = DepInfo[I];
8355e5dd7070Spatrick     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
83567a9b00ceSrobert     Triples += '-';
83577a9b00ceSrobert     Triples += Dep.DependentToolChain->getTriple().normalize();
83587a9b00ceSrobert     if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
83597a9b00ceSrobert          Dep.DependentOffloadKind == Action::OFK_Cuda) &&
83607a9b00ceSrobert         !Dep.DependentBoundArch.empty()) {
83617a9b00ceSrobert       Triples += '-';
8362e5dd7070Spatrick       Triples += Dep.DependentBoundArch;
8363e5dd7070Spatrick     }
83647a9b00ceSrobert     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
83657a9b00ceSrobert     //       with each toolchain.
83667a9b00ceSrobert     StringRef GPUArchName;
83677a9b00ceSrobert     if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
83687a9b00ceSrobert       // Extract GPUArch from -march argument in TC argument list.
83697a9b00ceSrobert       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
83707a9b00ceSrobert         StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
83717a9b00ceSrobert         auto Arch = ArchStr.startswith_insensitive("-march=");
83727a9b00ceSrobert         if (Arch) {
83737a9b00ceSrobert           GPUArchName = ArchStr.substr(7);
83747a9b00ceSrobert           Triples += "-";
83757a9b00ceSrobert           break;
83767a9b00ceSrobert         }
83777a9b00ceSrobert       }
83787a9b00ceSrobert       Triples += GPUArchName.str();
83797a9b00ceSrobert     }
8380e5dd7070Spatrick   }
8381e5dd7070Spatrick 
8382e5dd7070Spatrick   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8383e5dd7070Spatrick 
8384e5dd7070Spatrick   // Get bundled file command.
8385e5dd7070Spatrick   CmdArgs.push_back(
83867a9b00ceSrobert       TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
8387e5dd7070Spatrick 
8388e5dd7070Spatrick   // Get unbundled files command.
8389e5dd7070Spatrick   for (unsigned I = 0; I < Outputs.size(); ++I) {
83907a9b00ceSrobert     SmallString<128> UB;
83917a9b00ceSrobert     UB += "-output=";
8392e5dd7070Spatrick     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
8393e5dd7070Spatrick     CmdArgs.push_back(TCArgs.MakeArgString(UB));
83947a9b00ceSrobert   }
8395e5dd7070Spatrick   CmdArgs.push_back("-unbundle");
8396a0747c9fSpatrick   CmdArgs.push_back("-allow-missing-bundles");
8397e5dd7070Spatrick 
8398e5dd7070Spatrick   // All the inputs are encoded as commands.
8399e5dd7070Spatrick   C.addCommand(std::make_unique<Command>(
8400adae0cfdSpatrick       JA, *this, ResponseFileSupport::None(),
8401e5dd7070Spatrick       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
84027a9b00ceSrobert       CmdArgs, std::nullopt, Outputs));
8403e5dd7070Spatrick }
8404e5dd7070Spatrick 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & Args,const char * LinkingOutput) const84057a9b00ceSrobert void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
8406e5dd7070Spatrick                                    const InputInfo &Output,
8407e5dd7070Spatrick                                    const InputInfoList &Inputs,
84087a9b00ceSrobert                                    const llvm::opt::ArgList &Args,
8409e5dd7070Spatrick                                    const char *LinkingOutput) const {
8410e5dd7070Spatrick   ArgStringList CmdArgs;
8411e5dd7070Spatrick 
8412e5dd7070Spatrick   // Add the output file name.
8413e5dd7070Spatrick   assert(Output.isFilename() && "Invalid output.");
8414e5dd7070Spatrick   CmdArgs.push_back("-o");
8415e5dd7070Spatrick   CmdArgs.push_back(Output.getFilename());
8416e5dd7070Spatrick 
84177a9b00ceSrobert   // Create the inputs to bundle the needed metadata.
84187a9b00ceSrobert   for (const InputInfo &Input : Inputs) {
84197a9b00ceSrobert     const Action *OffloadAction = Input.getAction();
84207a9b00ceSrobert     const ToolChain *TC = OffloadAction->getOffloadingToolChain();
84217a9b00ceSrobert     const ArgList &TCArgs =
84227a9b00ceSrobert         C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
84237a9b00ceSrobert                               OffloadAction->getOffloadingDeviceKind());
84247a9b00ceSrobert     StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
84257a9b00ceSrobert     StringRef Arch = (OffloadAction->getOffloadingArch())
84267a9b00ceSrobert                          ? OffloadAction->getOffloadingArch()
84277a9b00ceSrobert                          : TCArgs.getLastArgValue(options::OPT_march_EQ);
84287a9b00ceSrobert     StringRef Kind =
84297a9b00ceSrobert       Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
84307a9b00ceSrobert 
84317a9b00ceSrobert     ArgStringList Features;
84327a9b00ceSrobert     SmallVector<StringRef> FeatureArgs;
84337a9b00ceSrobert     getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
84347a9b00ceSrobert                       false);
84357a9b00ceSrobert     llvm::copy_if(Features, std::back_inserter(FeatureArgs),
84367a9b00ceSrobert                   [](StringRef Arg) { return !Arg.startswith("-target"); });
84377a9b00ceSrobert 
84387a9b00ceSrobert     SmallVector<std::string> Parts{
84397a9b00ceSrobert         "file=" + File.str(),
84407a9b00ceSrobert         "triple=" + TC->getTripleString(),
84417a9b00ceSrobert         "arch=" + Arch.str(),
84427a9b00ceSrobert         "kind=" + Kind.str(),
84437a9b00ceSrobert     };
84447a9b00ceSrobert 
84457a9b00ceSrobert     if (TC->getDriver().isUsingLTO(/* IsOffload */ true))
84467a9b00ceSrobert       for (StringRef Feature : FeatureArgs)
84477a9b00ceSrobert         Parts.emplace_back("feature=" + Feature.str());
84487a9b00ceSrobert 
84497a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
8450e5dd7070Spatrick   }
8451e5dd7070Spatrick 
8452e5dd7070Spatrick   C.addCommand(std::make_unique<Command>(
8453adae0cfdSpatrick       JA, *this, ResponseFileSupport::None(),
8454e5dd7070Spatrick       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8455a0747c9fSpatrick       CmdArgs, Inputs, Output));
8456e5dd7070Spatrick }
84577a9b00ceSrobert 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const84587a9b00ceSrobert void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
84597a9b00ceSrobert                                  const InputInfo &Output,
84607a9b00ceSrobert                                  const InputInfoList &Inputs,
84617a9b00ceSrobert                                  const ArgList &Args,
84627a9b00ceSrobert                                  const char *LinkingOutput) const {
84637a9b00ceSrobert   const Driver &D = getToolChain().getDriver();
84647a9b00ceSrobert   const llvm::Triple TheTriple = getToolChain().getTriple();
84657a9b00ceSrobert   ArgStringList CmdArgs;
84667a9b00ceSrobert 
84677a9b00ceSrobert   // Pass the CUDA path to the linker wrapper tool.
84687a9b00ceSrobert   for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
84697a9b00ceSrobert     auto TCRange = C.getOffloadToolChains(Kind);
84707a9b00ceSrobert     for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
84717a9b00ceSrobert       const ToolChain *TC = I.second;
84727a9b00ceSrobert       if (TC->getTriple().isNVPTX()) {
84737a9b00ceSrobert         CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
84747a9b00ceSrobert         if (CudaInstallation.isValid())
84757a9b00ceSrobert           CmdArgs.push_back(Args.MakeArgString(
84767a9b00ceSrobert               "--cuda-path=" + CudaInstallation.getInstallPath()));
84777a9b00ceSrobert         break;
84787a9b00ceSrobert       }
84797a9b00ceSrobert     }
84807a9b00ceSrobert   }
84817a9b00ceSrobert 
84827a9b00ceSrobert   if (D.isUsingLTO(/* IsOffload */ true)) {
84837a9b00ceSrobert     // Pass in the optimization level to use for LTO.
84847a9b00ceSrobert     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
84857a9b00ceSrobert       StringRef OOpt;
84867a9b00ceSrobert       if (A->getOption().matches(options::OPT_O4) ||
84877a9b00ceSrobert           A->getOption().matches(options::OPT_Ofast))
84887a9b00ceSrobert         OOpt = "3";
84897a9b00ceSrobert       else if (A->getOption().matches(options::OPT_O)) {
84907a9b00ceSrobert         OOpt = A->getValue();
84917a9b00ceSrobert         if (OOpt == "g")
84927a9b00ceSrobert           OOpt = "1";
84937a9b00ceSrobert         else if (OOpt == "s" || OOpt == "z")
84947a9b00ceSrobert           OOpt = "2";
84957a9b00ceSrobert       } else if (A->getOption().matches(options::OPT_O0))
84967a9b00ceSrobert         OOpt = "0";
84977a9b00ceSrobert       if (!OOpt.empty())
84987a9b00ceSrobert         CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
84997a9b00ceSrobert     }
85007a9b00ceSrobert   }
85017a9b00ceSrobert 
85027a9b00ceSrobert   CmdArgs.push_back(
85037a9b00ceSrobert       Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
85047a9b00ceSrobert   if (Args.hasArg(options::OPT_v))
85057a9b00ceSrobert     CmdArgs.push_back("--wrapper-verbose");
85067a9b00ceSrobert 
85077a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
85087a9b00ceSrobert     if (!A->getOption().matches(options::OPT_g0))
85097a9b00ceSrobert       CmdArgs.push_back("--device-debug");
85107a9b00ceSrobert   }
85117a9b00ceSrobert 
85127a9b00ceSrobert   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
85137a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
85147a9b00ceSrobert 
85157a9b00ceSrobert   // Forward remarks passes to the LLVM backend in the wrapper.
85167a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
85177a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
85187a9b00ceSrobert                                          A->getValue()));
85197a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
85207a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(
85217a9b00ceSrobert         Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
85227a9b00ceSrobert   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
85237a9b00ceSrobert     CmdArgs.push_back(Args.MakeArgString(
85247a9b00ceSrobert         Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
85257a9b00ceSrobert   if (Args.getLastArg(options::OPT_save_temps_EQ))
85267a9b00ceSrobert     CmdArgs.push_back("--save-temps");
85277a9b00ceSrobert 
85287a9b00ceSrobert   // Construct the link job so we can wrap around it.
85297a9b00ceSrobert   Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
85307a9b00ceSrobert   const auto &LinkCommand = C.getJobs().getJobs().back();
85317a9b00ceSrobert 
85327a9b00ceSrobert   // Forward -Xoffload-linker<-triple> arguments to the device link job.
85337a9b00ceSrobert   for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
85347a9b00ceSrobert     StringRef Val = A->getValue(0);
85357a9b00ceSrobert     if (Val.empty())
85367a9b00ceSrobert       CmdArgs.push_back(
85377a9b00ceSrobert           Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
85387a9b00ceSrobert     else
85397a9b00ceSrobert       CmdArgs.push_back(Args.MakeArgString(
85407a9b00ceSrobert           "--device-linker=" +
85417a9b00ceSrobert           ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
85427a9b00ceSrobert           A->getValue(1)));
85437a9b00ceSrobert   }
85447a9b00ceSrobert   Args.ClaimAllArgs(options::OPT_Xoffload_linker);
85457a9b00ceSrobert 
85467a9b00ceSrobert   // Embed bitcode instead of an object in JIT mode.
85477a9b00ceSrobert   if (Args.hasFlag(options::OPT_fopenmp_target_jit,
85487a9b00ceSrobert                    options::OPT_fno_openmp_target_jit, false))
85497a9b00ceSrobert     CmdArgs.push_back("--embed-bitcode");
85507a9b00ceSrobert 
85517a9b00ceSrobert   // Forward `-mllvm` arguments to the LLVM invocations if present.
85527a9b00ceSrobert   for (Arg *A : Args.filtered(options::OPT_mllvm)) {
85537a9b00ceSrobert     CmdArgs.push_back("-mllvm");
85547a9b00ceSrobert     CmdArgs.push_back(A->getValue());
85557a9b00ceSrobert     A->claim();
85567a9b00ceSrobert   }
85577a9b00ceSrobert 
85587a9b00ceSrobert   // Add the linker arguments to be forwarded by the wrapper.
85597a9b00ceSrobert   CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
85607a9b00ceSrobert                                        LinkCommand->getExecutable()));
85617a9b00ceSrobert   CmdArgs.push_back("--");
85627a9b00ceSrobert   for (const char *LinkArg : LinkCommand->getArguments())
85637a9b00ceSrobert     CmdArgs.push_back(LinkArg);
85647a9b00ceSrobert 
85657a9b00ceSrobert   const char *Exec =
85667a9b00ceSrobert       Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
85677a9b00ceSrobert 
85687a9b00ceSrobert   // Replace the executable and arguments of the link job with the
85697a9b00ceSrobert   // wrapper.
85707a9b00ceSrobert   LinkCommand->replaceExecutable(Exec);
85717a9b00ceSrobert   LinkCommand->replaceArguments(CmdArgs);
85727a9b00ceSrobert }
8573