xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp (revision 3bd749dbd90cc3b95719b65393df5ca8a0fe919d)
1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Clang.h"
10 #include "AMDGPU.h"
11 #include "Arch/AArch64.h"
12 #include "Arch/ARM.h"
13 #include "Arch/CSKY.h"
14 #include "Arch/LoongArch.h"
15 #include "Arch/M68k.h"
16 #include "Arch/Mips.h"
17 #include "Arch/PPC.h"
18 #include "Arch/RISCV.h"
19 #include "Arch/Sparc.h"
20 #include "Arch/SystemZ.h"
21 #include "Arch/VE.h"
22 #include "Arch/X86.h"
23 #include "CommonArgs.h"
24 #include "Hexagon.h"
25 #include "MSP430.h"
26 #include "PS4CPU.h"
27 #include "clang/Basic/CLWarnings.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/CodeGenOptions.h"
30 #include "clang/Basic/HeaderInclude.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/MakeSupport.h"
33 #include "clang/Basic/ObjCRuntime.h"
34 #include "clang/Basic/Version.h"
35 #include "clang/Config/config.h"
36 #include "clang/Driver/Action.h"
37 #include "clang/Driver/Distro.h"
38 #include "clang/Driver/DriverDiagnostic.h"
39 #include "clang/Driver/InputInfo.h"
40 #include "clang/Driver/Options.h"
41 #include "clang/Driver/SanitizerArgs.h"
42 #include "clang/Driver/Types.h"
43 #include "clang/Driver/XRayArgs.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Config/llvm-config.h"
47 #include "llvm/Option/ArgList.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Compression.h"
51 #include "llvm/Support/Error.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/Process.h"
55 #include "llvm/Support/RISCVISAInfo.h"
56 #include "llvm/Support/YAMLParser.h"
57 #include "llvm/TargetParser/ARMTargetParserCommon.h"
58 #include "llvm/TargetParser/Host.h"
59 #include "llvm/TargetParser/LoongArchTargetParser.h"
60 #include "llvm/TargetParser/RISCVTargetParser.h"
61 #include <cctype>
62 
63 using namespace clang::driver;
64 using namespace clang::driver::tools;
65 using namespace clang;
66 using namespace llvm::opt;
67 
68 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
69   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
70                                options::OPT_fminimize_whitespace,
71                                options::OPT_fno_minimize_whitespace)) {
72     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
73         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
74       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
75           << A->getBaseArg().getAsString(Args)
76           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
77     }
78   }
79 }
80 
81 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
82   // In gcc, only ARM checks this, but it seems reasonable to check universally.
83   if (Args.hasArg(options::OPT_static))
84     if (const Arg *A =
85             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
86       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
87                                                       << "-static";
88 }
89 
90 // Add backslashes to escape spaces and other backslashes.
91 // This is used for the space-separated argument list specified with
92 // the -dwarf-debug-flags option.
93 static void EscapeSpacesAndBackslashes(const char *Arg,
94                                        SmallVectorImpl<char> &Res) {
95   for (; *Arg; ++Arg) {
96     switch (*Arg) {
97     default:
98       break;
99     case ' ':
100     case '\\':
101       Res.push_back('\\');
102       break;
103     }
104     Res.push_back(*Arg);
105   }
106 }
107 
108 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
109 /// offloading tool chain that is associated with the current action \a JA.
110 static void
111 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
112                            const ToolChain &RegularToolChain,
113                            llvm::function_ref<void(const ToolChain &)> Work) {
114   // Apply Work on the current/regular tool chain.
115   Work(RegularToolChain);
116 
117   // Apply Work on all the offloading tool chains associated with the current
118   // action.
119   if (JA.isHostOffloading(Action::OFK_Cuda))
120     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
121   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
122     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
123   else if (JA.isHostOffloading(Action::OFK_HIP))
124     Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
125   else if (JA.isDeviceOffloading(Action::OFK_HIP))
126     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
127 
128   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
129     auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
130     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
131       Work(*II->second);
132   } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
133     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
134 
135   //
136   // TODO: Add support for other offloading programming models here.
137   //
138 }
139 
140 /// This is a helper function for validating the optional refinement step
141 /// parameter in reciprocal argument strings. Return false if there is an error
142 /// parsing the refinement step. Otherwise, return true and set the Position
143 /// of the refinement step in the input string.
144 static bool getRefinementStep(StringRef In, const Driver &D,
145                               const Arg &A, size_t &Position) {
146   const char RefinementStepToken = ':';
147   Position = In.find(RefinementStepToken);
148   if (Position != StringRef::npos) {
149     StringRef Option = A.getOption().getName();
150     StringRef RefStep = In.substr(Position + 1);
151     // Allow exactly one numeric character for the additional refinement
152     // step parameter. This is reasonable for all currently-supported
153     // operations and architectures because we would expect that a larger value
154     // of refinement steps would cause the estimate "optimization" to
155     // under-perform the native operation. Also, if the estimate does not
156     // converge quickly, it probably will not ever converge, so further
157     // refinement steps will not produce a better answer.
158     if (RefStep.size() != 1) {
159       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
160       return false;
161     }
162     char RefStepChar = RefStep[0];
163     if (RefStepChar < '0' || RefStepChar > '9') {
164       D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
165       return false;
166     }
167   }
168   return true;
169 }
170 
171 /// The -mrecip flag requires processing of many optional parameters.
172 static void ParseMRecip(const Driver &D, const ArgList &Args,
173                         ArgStringList &OutStrings) {
174   StringRef DisabledPrefixIn = "!";
175   StringRef DisabledPrefixOut = "!";
176   StringRef EnabledPrefixOut = "";
177   StringRef Out = "-mrecip=";
178 
179   Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
180   if (!A)
181     return;
182 
183   unsigned NumOptions = A->getNumValues();
184   if (NumOptions == 0) {
185     // No option is the same as "all".
186     OutStrings.push_back(Args.MakeArgString(Out + "all"));
187     return;
188   }
189 
190   // Pass through "all", "none", or "default" with an optional refinement step.
191   if (NumOptions == 1) {
192     StringRef Val = A->getValue(0);
193     size_t RefStepLoc;
194     if (!getRefinementStep(Val, D, *A, RefStepLoc))
195       return;
196     StringRef ValBase = Val.slice(0, RefStepLoc);
197     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
198       OutStrings.push_back(Args.MakeArgString(Out + Val));
199       return;
200     }
201   }
202 
203   // Each reciprocal type may be enabled or disabled individually.
204   // Check each input value for validity, concatenate them all back together,
205   // and pass through.
206 
207   llvm::StringMap<bool> OptionStrings;
208   OptionStrings.insert(std::make_pair("divd", false));
209   OptionStrings.insert(std::make_pair("divf", false));
210   OptionStrings.insert(std::make_pair("divh", false));
211   OptionStrings.insert(std::make_pair("vec-divd", false));
212   OptionStrings.insert(std::make_pair("vec-divf", false));
213   OptionStrings.insert(std::make_pair("vec-divh", false));
214   OptionStrings.insert(std::make_pair("sqrtd", false));
215   OptionStrings.insert(std::make_pair("sqrtf", false));
216   OptionStrings.insert(std::make_pair("sqrth", false));
217   OptionStrings.insert(std::make_pair("vec-sqrtd", false));
218   OptionStrings.insert(std::make_pair("vec-sqrtf", false));
219   OptionStrings.insert(std::make_pair("vec-sqrth", false));
220 
221   for (unsigned i = 0; i != NumOptions; ++i) {
222     StringRef Val = A->getValue(i);
223 
224     bool IsDisabled = Val.startswith(DisabledPrefixIn);
225     // Ignore the disablement token for string matching.
226     if (IsDisabled)
227       Val = Val.substr(1);
228 
229     size_t RefStep;
230     if (!getRefinementStep(Val, D, *A, RefStep))
231       return;
232 
233     StringRef ValBase = Val.slice(0, RefStep);
234     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
235     if (OptionIter == OptionStrings.end()) {
236       // Try again specifying float suffix.
237       OptionIter = OptionStrings.find(ValBase.str() + 'f');
238       if (OptionIter == OptionStrings.end()) {
239         // The input name did not match any known option string.
240         D.Diag(diag::err_drv_unknown_argument) << Val;
241         return;
242       }
243       // The option was specified without a half or float or double suffix.
244       // Make sure that the double or half entry was not already specified.
245       // The float entry will be checked below.
246       if (OptionStrings[ValBase.str() + 'd'] ||
247           OptionStrings[ValBase.str() + 'h']) {
248         D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
249         return;
250       }
251     }
252 
253     if (OptionIter->second == true) {
254       // Duplicate option specified.
255       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
256       return;
257     }
258 
259     // Mark the matched option as found. Do not allow duplicate specifiers.
260     OptionIter->second = true;
261 
262     // If the precision was not specified, also mark the double and half entry
263     // as found.
264     if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
265       OptionStrings[ValBase.str() + 'd'] = true;
266       OptionStrings[ValBase.str() + 'h'] = true;
267     }
268 
269     // Build the output string.
270     StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
271     Out = Args.MakeArgString(Out + Prefix + Val);
272     if (i != NumOptions - 1)
273       Out = Args.MakeArgString(Out + ",");
274   }
275 
276   OutStrings.push_back(Args.MakeArgString(Out));
277 }
278 
279 /// The -mprefer-vector-width option accepts either a positive integer
280 /// or the string "none".
281 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
282                                     ArgStringList &CmdArgs) {
283   Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
284   if (!A)
285     return;
286 
287   StringRef Value = A->getValue();
288   if (Value == "none") {
289     CmdArgs.push_back("-mprefer-vector-width=none");
290   } else {
291     unsigned Width;
292     if (Value.getAsInteger(10, Width)) {
293       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
294       return;
295     }
296     CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
297   }
298 }
299 
300 static bool
301 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
302                                           const llvm::Triple &Triple) {
303   // We use the zero-cost exception tables for Objective-C if the non-fragile
304   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
305   // later.
306   if (runtime.isNonFragile())
307     return true;
308 
309   if (!Triple.isMacOSX())
310     return false;
311 
312   return (!Triple.isMacOSXVersionLT(10, 5) &&
313           (Triple.getArch() == llvm::Triple::x86_64 ||
314            Triple.getArch() == llvm::Triple::arm));
315 }
316 
317 /// Adds exception related arguments to the driver command arguments. There's a
318 /// main flag, -fexceptions and also language specific flags to enable/disable
319 /// C++ and Objective-C exceptions. This makes it possible to for example
320 /// disable C++ exceptions but enable Objective-C exceptions.
321 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
322                              const ToolChain &TC, bool KernelOrKext,
323                              const ObjCRuntime &objcRuntime,
324                              ArgStringList &CmdArgs) {
325   const llvm::Triple &Triple = TC.getTriple();
326 
327   if (KernelOrKext) {
328     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
329     // arguments now to avoid warnings about unused arguments.
330     Args.ClaimAllArgs(options::OPT_fexceptions);
331     Args.ClaimAllArgs(options::OPT_fno_exceptions);
332     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
333     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
334     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
335     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
336     Args.ClaimAllArgs(options::OPT_fasync_exceptions);
337     Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
338     return false;
339   }
340 
341   // See if the user explicitly enabled exceptions.
342   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
343                          false);
344 
345   bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
346                           options::OPT_fno_async_exceptions, false);
347   if (EHa) {
348     CmdArgs.push_back("-fasync-exceptions");
349     EH = true;
350   }
351 
352   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
353   // is not necessarily sensible, but follows GCC.
354   if (types::isObjC(InputType) &&
355       Args.hasFlag(options::OPT_fobjc_exceptions,
356                    options::OPT_fno_objc_exceptions, true)) {
357     CmdArgs.push_back("-fobjc-exceptions");
358 
359     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
360   }
361 
362   if (types::isCXX(InputType)) {
363     // Disable C++ EH by default on XCore and PS4/PS5.
364     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
365                                 !Triple.isPS() && !Triple.isDriverKit();
366     Arg *ExceptionArg = Args.getLastArg(
367         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
368         options::OPT_fexceptions, options::OPT_fno_exceptions);
369     if (ExceptionArg)
370       CXXExceptionsEnabled =
371           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
372           ExceptionArg->getOption().matches(options::OPT_fexceptions);
373 
374     if (CXXExceptionsEnabled) {
375       CmdArgs.push_back("-fcxx-exceptions");
376 
377       EH = true;
378     }
379   }
380 
381   // OPT_fignore_exceptions means exception could still be thrown,
382   // but no clean up or catch would happen in current module.
383   // So we do not set EH to false.
384   Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
385 
386   if (EH)
387     CmdArgs.push_back("-fexceptions");
388   return EH;
389 }
390 
391 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
392                                  const JobAction &JA) {
393   bool Default = true;
394   if (TC.getTriple().isOSDarwin()) {
395     // The native darwin assembler doesn't support the linker_option directives,
396     // so we disable them if we think the .s file will be passed to it.
397     Default = TC.useIntegratedAs();
398   }
399   // The linker_option directives are intended for host compilation.
400   if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
401       JA.isDeviceOffloading(Action::OFK_HIP))
402     Default = false;
403   return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
404                       Default);
405 }
406 
407 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
408   switch (Triple.getArch()){
409   default:
410     return false;
411   case llvm::Triple::arm:
412   case llvm::Triple::thumb:
413     // ARM Darwin targets require a frame pointer to be always present to aid
414     // offline debugging via backtraces.
415     return Triple.isOSDarwin();
416   }
417 }
418 
419 static bool useFramePointerForTargetByDefault(const ArgList &Args,
420                                               const llvm::Triple &Triple) {
421   if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
422     return true;
423 
424   if (Triple.isAndroid()) {
425     switch (Triple.getArch()) {
426     case llvm::Triple::aarch64:
427     case llvm::Triple::arm:
428     case llvm::Triple::armeb:
429     case llvm::Triple::thumb:
430     case llvm::Triple::thumbeb:
431     case llvm::Triple::riscv64:
432       return true;
433     default:
434       break;
435     }
436   }
437 
438   switch (Triple.getArch()) {
439   case llvm::Triple::xcore:
440   case llvm::Triple::wasm32:
441   case llvm::Triple::wasm64:
442   case llvm::Triple::msp430:
443     // XCore never wants frame pointers, regardless of OS.
444     // WebAssembly never wants frame pointers.
445     return false;
446   case llvm::Triple::ppc:
447   case llvm::Triple::ppcle:
448   case llvm::Triple::ppc64:
449   case llvm::Triple::ppc64le:
450   case llvm::Triple::riscv32:
451   case llvm::Triple::riscv64:
452   case llvm::Triple::sparc:
453   case llvm::Triple::sparcel:
454   case llvm::Triple::sparcv9:
455   case llvm::Triple::amdgcn:
456   case llvm::Triple::r600:
457   case llvm::Triple::csky:
458   case llvm::Triple::loongarch32:
459   case llvm::Triple::loongarch64:
460     return !areOptimizationsEnabled(Args);
461   default:
462     break;
463   }
464 
465   if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
466     return !areOptimizationsEnabled(Args);
467   }
468 
469   if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
470       Triple.isOSHurd()) {
471     switch (Triple.getArch()) {
472     // Don't use a frame pointer on linux if optimizing for certain targets.
473     case llvm::Triple::arm:
474     case llvm::Triple::armeb:
475     case llvm::Triple::thumb:
476     case llvm::Triple::thumbeb:
477     case llvm::Triple::mips64:
478     case llvm::Triple::mips64el:
479     case llvm::Triple::mips:
480     case llvm::Triple::mipsel:
481     case llvm::Triple::systemz:
482     case llvm::Triple::x86:
483     case llvm::Triple::x86_64:
484       return !areOptimizationsEnabled(Args);
485     default:
486       return true;
487     }
488   }
489 
490   if (Triple.isOSWindows()) {
491     switch (Triple.getArch()) {
492     case llvm::Triple::x86:
493       return !areOptimizationsEnabled(Args);
494     case llvm::Triple::x86_64:
495       return Triple.isOSBinFormatMachO();
496     case llvm::Triple::arm:
497     case llvm::Triple::thumb:
498       // Windows on ARM builds with FPO disabled to aid fast stack walking
499       return true;
500     default:
501       // All other supported Windows ISAs use xdata unwind information, so frame
502       // pointers are not generally useful.
503       return false;
504     }
505   }
506 
507   return true;
508 }
509 
510 static CodeGenOptions::FramePointerKind
511 getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
512   // We have 4 states:
513   //
514   //  00) leaf retained, non-leaf retained
515   //  01) leaf retained, non-leaf omitted (this is invalid)
516   //  10) leaf omitted, non-leaf retained
517   //      (what -momit-leaf-frame-pointer was designed for)
518   //  11) leaf omitted, non-leaf omitted
519   //
520   //  "omit" options taking precedence over "no-omit" options is the only way
521   //  to make 3 valid states representable
522   Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
523                            options::OPT_fno_omit_frame_pointer);
524   bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
525   bool NoOmitFP =
526       A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
527   bool OmitLeafFP =
528       Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
529                    options::OPT_mno_omit_leaf_frame_pointer,
530                    Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
531                    (Triple.isAndroid() && Triple.isRISCV64()));
532   if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
533       (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
534     if (OmitLeafFP)
535       return CodeGenOptions::FramePointerKind::NonLeaf;
536     return CodeGenOptions::FramePointerKind::All;
537   }
538   return CodeGenOptions::FramePointerKind::None;
539 }
540 
541 /// Add a CC1 option to specify the debug compilation directory.
542 static const char *addDebugCompDirArg(const ArgList &Args,
543                                       ArgStringList &CmdArgs,
544                                       const llvm::vfs::FileSystem &VFS) {
545   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
546                                options::OPT_fdebug_compilation_dir_EQ)) {
547     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
548       CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
549                                            A->getValue()));
550     else
551       A->render(Args, CmdArgs);
552   } else if (llvm::ErrorOr<std::string> CWD =
553                  VFS.getCurrentWorkingDirectory()) {
554     CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
555   }
556   StringRef Path(CmdArgs.back());
557   return Path.substr(Path.find('=') + 1).data();
558 }
559 
560 static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
561                                const char *DebugCompilationDir,
562                                const char *OutputFileName) {
563   // No need to generate a value for -object-file-name if it was provided.
564   for (auto *Arg : Args.filtered(options::OPT_Xclang))
565     if (StringRef(Arg->getValue()).startswith("-object-file-name"))
566       return;
567 
568   if (Args.hasArg(options::OPT_object_file_name_EQ))
569     return;
570 
571   SmallString<128> ObjFileNameForDebug(OutputFileName);
572   if (ObjFileNameForDebug != "-" &&
573       !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
574       (!DebugCompilationDir ||
575        llvm::sys::path::is_absolute(DebugCompilationDir))) {
576     // Make the path absolute in the debug infos like MSVC does.
577     llvm::sys::fs::make_absolute(ObjFileNameForDebug);
578   }
579   // If the object file name is a relative path, then always use Windows
580   // backslash style as -object-file-name is used for embedding object file path
581   // in codeview and it can only be generated when targeting on Windows.
582   // Otherwise, just use native absolute path.
583   llvm::sys::path::Style Style =
584       llvm::sys::path::is_absolute(ObjFileNameForDebug)
585           ? llvm::sys::path::Style::native
586           : llvm::sys::path::Style::windows_backslash;
587   llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
588                                Style);
589   CmdArgs.push_back(
590       Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
591 }
592 
593 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
594 static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
595                                  const ArgList &Args, ArgStringList &CmdArgs) {
596   auto AddOneArg = [&](StringRef Map, StringRef Name) {
597     if (!Map.contains('='))
598       D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
599     else
600       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
601   };
602 
603   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
604                                     options::OPT_fdebug_prefix_map_EQ)) {
605     AddOneArg(A->getValue(), A->getOption().getName());
606     A->claim();
607   }
608   std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
609   if (GlobalRemapEntry.empty())
610     return;
611   AddOneArg(GlobalRemapEntry, "environment");
612 }
613 
614 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
615 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
616                                  ArgStringList &CmdArgs) {
617   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
618                                     options::OPT_fmacro_prefix_map_EQ)) {
619     StringRef Map = A->getValue();
620     if (!Map.contains('='))
621       D.Diag(diag::err_drv_invalid_argument_to_option)
622           << Map << A->getOption().getName();
623     else
624       CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
625     A->claim();
626   }
627 }
628 
629 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
630 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
631                                    ArgStringList &CmdArgs) {
632   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
633                                     options::OPT_fcoverage_prefix_map_EQ)) {
634     StringRef Map = A->getValue();
635     if (!Map.contains('='))
636       D.Diag(diag::err_drv_invalid_argument_to_option)
637           << Map << A->getOption().getName();
638     else
639       CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
640     A->claim();
641   }
642 }
643 
644 /// Vectorize at all optimization levels greater than 1 except for -Oz.
645 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
646 /// enabled.
647 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
648   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
649     if (A->getOption().matches(options::OPT_O4) ||
650         A->getOption().matches(options::OPT_Ofast))
651       return true;
652 
653     if (A->getOption().matches(options::OPT_O0))
654       return false;
655 
656     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
657 
658     // Vectorize -Os.
659     StringRef S(A->getValue());
660     if (S == "s")
661       return true;
662 
663     // Don't vectorize -Oz, unless it's the slp vectorizer.
664     if (S == "z")
665       return isSlpVec;
666 
667     unsigned OptLevel = 0;
668     if (S.getAsInteger(10, OptLevel))
669       return false;
670 
671     return OptLevel > 1;
672   }
673 
674   return false;
675 }
676 
677 /// Add -x lang to \p CmdArgs for \p Input.
678 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
679                              ArgStringList &CmdArgs) {
680   // When using -verify-pch, we don't want to provide the type
681   // 'precompiled-header' if it was inferred from the file extension
682   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
683     return;
684 
685   CmdArgs.push_back("-x");
686   if (Args.hasArg(options::OPT_rewrite_objc))
687     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
688   else {
689     // Map the driver type to the frontend type. This is mostly an identity
690     // mapping, except that the distinction between module interface units
691     // and other source files does not exist at the frontend layer.
692     const char *ClangType;
693     switch (Input.getType()) {
694     case types::TY_CXXModule:
695       ClangType = "c++";
696       break;
697     case types::TY_PP_CXXModule:
698       ClangType = "c++-cpp-output";
699       break;
700     default:
701       ClangType = types::getTypeName(Input.getType());
702       break;
703     }
704     CmdArgs.push_back(ClangType);
705   }
706 }
707 
708 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
709                                    const JobAction &JA, const InputInfo &Output,
710                                    const ArgList &Args, SanitizerArgs &SanArgs,
711                                    ArgStringList &CmdArgs) {
712   const Driver &D = TC.getDriver();
713   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
714                                          options::OPT_fprofile_generate_EQ,
715                                          options::OPT_fno_profile_generate);
716   if (PGOGenerateArg &&
717       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
718     PGOGenerateArg = nullptr;
719 
720   auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
721 
722   auto *ProfileGenerateArg = Args.getLastArg(
723       options::OPT_fprofile_instr_generate,
724       options::OPT_fprofile_instr_generate_EQ,
725       options::OPT_fno_profile_instr_generate);
726   if (ProfileGenerateArg &&
727       ProfileGenerateArg->getOption().matches(
728           options::OPT_fno_profile_instr_generate))
729     ProfileGenerateArg = nullptr;
730 
731   if (PGOGenerateArg && ProfileGenerateArg)
732     D.Diag(diag::err_drv_argument_not_allowed_with)
733         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
734 
735   auto *ProfileUseArg = getLastProfileUseArg(Args);
736 
737   if (PGOGenerateArg && ProfileUseArg)
738     D.Diag(diag::err_drv_argument_not_allowed_with)
739         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
740 
741   if (ProfileGenerateArg && ProfileUseArg)
742     D.Diag(diag::err_drv_argument_not_allowed_with)
743         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
744 
745   if (CSPGOGenerateArg && PGOGenerateArg) {
746     D.Diag(diag::err_drv_argument_not_allowed_with)
747         << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
748     PGOGenerateArg = nullptr;
749   }
750 
751   if (TC.getTriple().isOSAIX()) {
752     if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
753       D.Diag(diag::err_drv_unsupported_opt_for_target)
754           << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
755   }
756 
757   if (ProfileGenerateArg) {
758     if (ProfileGenerateArg->getOption().matches(
759             options::OPT_fprofile_instr_generate_EQ))
760       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
761                                            ProfileGenerateArg->getValue()));
762     // The default is to use Clang Instrumentation.
763     CmdArgs.push_back("-fprofile-instrument=clang");
764     if (TC.getTriple().isWindowsMSVCEnvironment()) {
765       // Add dependent lib for clang_rt.profile
766       CmdArgs.push_back(Args.MakeArgString(
767           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
768     }
769   }
770 
771   Arg *PGOGenArg = nullptr;
772   if (PGOGenerateArg) {
773     assert(!CSPGOGenerateArg);
774     PGOGenArg = PGOGenerateArg;
775     CmdArgs.push_back("-fprofile-instrument=llvm");
776   }
777   if (CSPGOGenerateArg) {
778     assert(!PGOGenerateArg);
779     PGOGenArg = CSPGOGenerateArg;
780     CmdArgs.push_back("-fprofile-instrument=csllvm");
781   }
782   if (PGOGenArg) {
783     if (TC.getTriple().isWindowsMSVCEnvironment()) {
784       // Add dependent lib for clang_rt.profile
785       CmdArgs.push_back(Args.MakeArgString(
786           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
787     }
788     if (PGOGenArg->getOption().matches(
789             PGOGenerateArg ? options::OPT_fprofile_generate_EQ
790                            : options::OPT_fcs_profile_generate_EQ)) {
791       SmallString<128> Path(PGOGenArg->getValue());
792       llvm::sys::path::append(Path, "default_%m.profraw");
793       CmdArgs.push_back(
794           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
795     }
796   }
797 
798   if (ProfileUseArg) {
799     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
800       CmdArgs.push_back(Args.MakeArgString(
801           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
802     else if ((ProfileUseArg->getOption().matches(
803                   options::OPT_fprofile_use_EQ) ||
804               ProfileUseArg->getOption().matches(
805                   options::OPT_fprofile_instr_use))) {
806       SmallString<128> Path(
807           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
808       if (Path.empty() || llvm::sys::fs::is_directory(Path))
809         llvm::sys::path::append(Path, "default.profdata");
810       CmdArgs.push_back(
811           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
812     }
813   }
814 
815   bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
816                                    options::OPT_fno_test_coverage, false) ||
817                       Args.hasArg(options::OPT_coverage);
818   bool EmitCovData = TC.needsGCovInstrumentation(Args);
819 
820   if (Args.hasFlag(options::OPT_fcoverage_mapping,
821                    options::OPT_fno_coverage_mapping, false)) {
822     if (!ProfileGenerateArg)
823       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
824           << "-fcoverage-mapping"
825           << "-fprofile-instr-generate";
826 
827     CmdArgs.push_back("-fcoverage-mapping");
828   }
829 
830   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
831                                options::OPT_fcoverage_compilation_dir_EQ)) {
832     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
833       CmdArgs.push_back(Args.MakeArgString(
834           Twine("-fcoverage-compilation-dir=") + A->getValue()));
835     else
836       A->render(Args, CmdArgs);
837   } else if (llvm::ErrorOr<std::string> CWD =
838                  D.getVFS().getCurrentWorkingDirectory()) {
839     CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
840   }
841 
842   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
843     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
844     if (!Args.hasArg(options::OPT_coverage))
845       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
846           << "-fprofile-exclude-files="
847           << "--coverage";
848 
849     StringRef v = Arg->getValue();
850     CmdArgs.push_back(
851         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
852   }
853 
854   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
855     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
856     if (!Args.hasArg(options::OPT_coverage))
857       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
858           << "-fprofile-filter-files="
859           << "--coverage";
860 
861     StringRef v = Arg->getValue();
862     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
863   }
864 
865   if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
866     StringRef Val = A->getValue();
867     if (Val == "atomic" || Val == "prefer-atomic")
868       CmdArgs.push_back("-fprofile-update=atomic");
869     else if (Val != "single")
870       D.Diag(diag::err_drv_unsupported_option_argument)
871           << A->getSpelling() << Val;
872   } else if (SanArgs.needsTsanRt()) {
873     CmdArgs.push_back("-fprofile-update=atomic");
874   }
875 
876   int FunctionGroups = 1;
877   int SelectedFunctionGroup = 0;
878   if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
879     StringRef Val = A->getValue();
880     if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
881       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
882   }
883   if (const auto *A =
884           Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
885     StringRef Val = A->getValue();
886     if (Val.getAsInteger(0, SelectedFunctionGroup) ||
887         SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
888       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
889   }
890   if (FunctionGroups != 1)
891     CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
892                                          Twine(FunctionGroups)));
893   if (SelectedFunctionGroup != 0)
894     CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
895                                          Twine(SelectedFunctionGroup)));
896 
897   // Leave -fprofile-dir= an unused argument unless .gcda emission is
898   // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
899   // the flag used. There is no -fno-profile-dir, so the user has no
900   // targeted way to suppress the warning.
901   Arg *FProfileDir = nullptr;
902   if (Args.hasArg(options::OPT_fprofile_arcs) ||
903       Args.hasArg(options::OPT_coverage))
904     FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
905 
906   // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
907   // like we warn about -fsyntax-only -E.
908   (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
909 
910   // Put the .gcno and .gcda files (if needed) next to the primary output file,
911   // or fall back to a file in the current directory for `clang -c --coverage
912   // d/a.c` in the absence of -o.
913   if (EmitCovNotes || EmitCovData) {
914     SmallString<128> CoverageFilename;
915     if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
916       // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
917       // path separator.
918       CoverageFilename = DumpDir->getValue();
919       CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
920     } else if (Arg *FinalOutput =
921                    C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
922       CoverageFilename = FinalOutput->getValue();
923     } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
924       CoverageFilename = FinalOutput->getValue();
925     } else {
926       CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
927     }
928     if (llvm::sys::path::is_relative(CoverageFilename))
929       (void)D.getVFS().makeAbsolute(CoverageFilename);
930     llvm::sys::path::replace_extension(CoverageFilename, "gcno");
931     if (EmitCovNotes) {
932       CmdArgs.push_back("-coverage-notes-file");
933       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
934     }
935 
936     if (EmitCovData) {
937       if (FProfileDir) {
938         SmallString<128> Gcno = std::move(CoverageFilename);
939         CoverageFilename = FProfileDir->getValue();
940         llvm::sys::path::append(CoverageFilename, Gcno);
941       }
942       llvm::sys::path::replace_extension(CoverageFilename, "gcda");
943       CmdArgs.push_back("-coverage-data-file");
944       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
945     }
946   }
947 }
948 
949 /// Check whether the given input tree contains any compilation actions.
950 static bool ContainsCompileAction(const Action *A) {
951   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
952     return true;
953 
954   return llvm::any_of(A->inputs(), ContainsCompileAction);
955 }
956 
957 /// Check if -relax-all should be passed to the internal assembler.
958 /// This is done by default when compiling non-assembler source with -O0.
959 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
960   bool RelaxDefault = true;
961 
962   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
963     RelaxDefault = A->getOption().matches(options::OPT_O0);
964 
965   if (RelaxDefault) {
966     RelaxDefault = false;
967     for (const auto &Act : C.getActions()) {
968       if (ContainsCompileAction(Act)) {
969         RelaxDefault = true;
970         break;
971       }
972     }
973   }
974 
975   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
976                       RelaxDefault);
977 }
978 
979 static void
980 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
981                         llvm::codegenoptions::DebugInfoKind DebugInfoKind,
982                         unsigned DwarfVersion,
983                         llvm::DebuggerKind DebuggerTuning) {
984   addDebugInfoKind(CmdArgs, DebugInfoKind);
985   if (DwarfVersion > 0)
986     CmdArgs.push_back(
987         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
988   switch (DebuggerTuning) {
989   case llvm::DebuggerKind::GDB:
990     CmdArgs.push_back("-debugger-tuning=gdb");
991     break;
992   case llvm::DebuggerKind::LLDB:
993     CmdArgs.push_back("-debugger-tuning=lldb");
994     break;
995   case llvm::DebuggerKind::SCE:
996     CmdArgs.push_back("-debugger-tuning=sce");
997     break;
998   case llvm::DebuggerKind::DBX:
999     CmdArgs.push_back("-debugger-tuning=dbx");
1000     break;
1001   default:
1002     break;
1003   }
1004 }
1005 
1006 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1007                                  const Driver &D, const ToolChain &TC) {
1008   assert(A && "Expected non-nullptr argument.");
1009   if (TC.supportsDebugInfoOption(A))
1010     return true;
1011   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1012       << A->getAsString(Args) << TC.getTripleString();
1013   return false;
1014 }
1015 
1016 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1017                                            ArgStringList &CmdArgs,
1018                                            const Driver &D,
1019                                            const ToolChain &TC) {
1020   const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1021   if (!A)
1022     return;
1023   if (checkDebugInfoOption(A, Args, D, TC)) {
1024     StringRef Value = A->getValue();
1025     if (Value == "none") {
1026       CmdArgs.push_back("--compress-debug-sections=none");
1027     } else if (Value == "zlib") {
1028       if (llvm::compression::zlib::isAvailable()) {
1029         CmdArgs.push_back(
1030             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1031       } else {
1032         D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
1033       }
1034     } else if (Value == "zstd") {
1035       if (llvm::compression::zstd::isAvailable()) {
1036         CmdArgs.push_back(
1037             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1038       } else {
1039         D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
1040       }
1041     } else {
1042       D.Diag(diag::err_drv_unsupported_option_argument)
1043           << A->getSpelling() << Value;
1044     }
1045   }
1046 }
1047 
1048 static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
1049                                                  const ArgList &Args,
1050                                                  ArgStringList &CmdArgs,
1051                                                  bool IsCC1As = false) {
1052   // If no version was requested by the user, use the default value from the
1053   // back end. This is consistent with the value returned from
1054   // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
1055   // requiring the corresponding llvm to have the AMDGPU target enabled,
1056   // provided the user (e.g. front end tests) can use the default.
1057   if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
1058     unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
1059     CmdArgs.insert(CmdArgs.begin() + 1,
1060                    Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1061                                       Twine(CodeObjVer)));
1062     CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
1063     // -cc1as does not accept -mcode-object-version option.
1064     if (!IsCC1As)
1065       CmdArgs.insert(CmdArgs.begin() + 1,
1066                      Args.MakeArgString(Twine("-mcode-object-version=") +
1067                                         Twine(CodeObjVer)));
1068   }
1069 }
1070 
1071 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1072                                     const Driver &D, const ArgList &Args,
1073                                     ArgStringList &CmdArgs,
1074                                     const InputInfo &Output,
1075                                     const InputInfoList &Inputs) const {
1076   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1077 
1078   CheckPreprocessingOptions(D, Args);
1079 
1080   Args.AddLastArg(CmdArgs, options::OPT_C);
1081   Args.AddLastArg(CmdArgs, options::OPT_CC);
1082 
1083   // Handle dependency file generation.
1084   Arg *ArgM = Args.getLastArg(options::OPT_MM);
1085   if (!ArgM)
1086     ArgM = Args.getLastArg(options::OPT_M);
1087   Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1088   if (!ArgMD)
1089     ArgMD = Args.getLastArg(options::OPT_MD);
1090 
1091   // -M and -MM imply -w.
1092   if (ArgM)
1093     CmdArgs.push_back("-w");
1094   else
1095     ArgM = ArgMD;
1096 
1097   if (ArgM) {
1098     // Determine the output location.
1099     const char *DepFile;
1100     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1101       DepFile = MF->getValue();
1102       C.addFailureResultFile(DepFile, &JA);
1103     } else if (Output.getType() == types::TY_Dependencies) {
1104       DepFile = Output.getFilename();
1105     } else if (!ArgMD) {
1106       DepFile = "-";
1107     } else {
1108       DepFile = getDependencyFileName(Args, Inputs);
1109       C.addFailureResultFile(DepFile, &JA);
1110     }
1111     CmdArgs.push_back("-dependency-file");
1112     CmdArgs.push_back(DepFile);
1113 
1114     bool HasTarget = false;
1115     for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1116       HasTarget = true;
1117       A->claim();
1118       if (A->getOption().matches(options::OPT_MT)) {
1119         A->render(Args, CmdArgs);
1120       } else {
1121         CmdArgs.push_back("-MT");
1122         SmallString<128> Quoted;
1123         quoteMakeTarget(A->getValue(), Quoted);
1124         CmdArgs.push_back(Args.MakeArgString(Quoted));
1125       }
1126     }
1127 
1128     // Add a default target if one wasn't specified.
1129     if (!HasTarget) {
1130       const char *DepTarget;
1131 
1132       // If user provided -o, that is the dependency target, except
1133       // when we are only generating a dependency file.
1134       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1135       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1136         DepTarget = OutputOpt->getValue();
1137       } else {
1138         // Otherwise derive from the base input.
1139         //
1140         // FIXME: This should use the computed output file location.
1141         SmallString<128> P(Inputs[0].getBaseInput());
1142         llvm::sys::path::replace_extension(P, "o");
1143         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1144       }
1145 
1146       CmdArgs.push_back("-MT");
1147       SmallString<128> Quoted;
1148       quoteMakeTarget(DepTarget, Quoted);
1149       CmdArgs.push_back(Args.MakeArgString(Quoted));
1150     }
1151 
1152     if (ArgM->getOption().matches(options::OPT_M) ||
1153         ArgM->getOption().matches(options::OPT_MD))
1154       CmdArgs.push_back("-sys-header-deps");
1155     if (Args.hasFlag(options::OPT_canonical_prefixes,
1156                      options::OPT_no_canonical_prefixes, true))
1157       CmdArgs.push_back("-canonical-system-headers");
1158     if ((isa<PrecompileJobAction>(JA) &&
1159          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1160         Args.hasArg(options::OPT_fmodule_file_deps))
1161       CmdArgs.push_back("-module-file-deps");
1162   }
1163 
1164   if (Args.hasArg(options::OPT_MG)) {
1165     if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1166         ArgM->getOption().matches(options::OPT_MMD))
1167       D.Diag(diag::err_drv_mg_requires_m_or_mm);
1168     CmdArgs.push_back("-MG");
1169   }
1170 
1171   Args.AddLastArg(CmdArgs, options::OPT_MP);
1172   Args.AddLastArg(CmdArgs, options::OPT_MV);
1173 
1174   // Add offload include arguments specific for CUDA/HIP.  This must happen
1175   // before we -I or -include anything else, because we must pick up the
1176   // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1177   // from e.g. /usr/local/include.
1178   if (JA.isOffloading(Action::OFK_Cuda))
1179     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1180   if (JA.isOffloading(Action::OFK_HIP))
1181     getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1182 
1183   // If we are compiling for a GPU target we want to override the system headers
1184   // with ones created by the 'libc' project if present.
1185   if (!Args.hasArg(options::OPT_nostdinc) &&
1186       !Args.hasArg(options::OPT_nogpuinc) &&
1187       !Args.hasArg(options::OPT_nobuiltininc) &&
1188       (getToolChain().getTriple().isNVPTX() ||
1189        getToolChain().getTriple().isAMDGCN())) {
1190 
1191     // Without an offloading language we will include these headers directly.
1192     // Offloading languages will instead only use the declarations stored in
1193     // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1194     if (C.getActiveOffloadKinds() == Action::OFK_None) {
1195       SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
1196       llvm::sys::path::append(P, "include");
1197       llvm::sys::path::append(P, "gpu-none-llvm");
1198       CmdArgs.push_back("-c-isystem");
1199       CmdArgs.push_back(Args.MakeArgString(P));
1200     } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1201       // TODO: CUDA / HIP include their own headers for some common functions
1202       // implemented here. We'll need to clean those up so they do not conflict.
1203       SmallString<128> P(D.ResourceDir);
1204       llvm::sys::path::append(P, "include");
1205       llvm::sys::path::append(P, "llvm_libc_wrappers");
1206       CmdArgs.push_back("-internal-isystem");
1207       CmdArgs.push_back(Args.MakeArgString(P));
1208     }
1209   }
1210 
1211   // If we are offloading to a target via OpenMP we need to include the
1212   // openmp_wrappers folder which contains alternative system headers.
1213   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1214       !Args.hasArg(options::OPT_nostdinc) &&
1215       !Args.hasArg(options::OPT_nogpuinc) &&
1216       (getToolChain().getTriple().isNVPTX() ||
1217        getToolChain().getTriple().isAMDGCN())) {
1218     if (!Args.hasArg(options::OPT_nobuiltininc)) {
1219       // Add openmp_wrappers/* to our system include path.  This lets us wrap
1220       // standard library headers.
1221       SmallString<128> P(D.ResourceDir);
1222       llvm::sys::path::append(P, "include");
1223       llvm::sys::path::append(P, "openmp_wrappers");
1224       CmdArgs.push_back("-internal-isystem");
1225       CmdArgs.push_back(Args.MakeArgString(P));
1226     }
1227 
1228     CmdArgs.push_back("-include");
1229     CmdArgs.push_back("__clang_openmp_device_functions.h");
1230   }
1231 
1232   // Add -i* options, and automatically translate to
1233   // -include-pch/-include-pth for transparent PCH support. It's
1234   // wonky, but we include looking for .gch so we can support seamless
1235   // replacement into a build system already set up to be generating
1236   // .gch files.
1237 
1238   if (getToolChain().getDriver().IsCLMode()) {
1239     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1240     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1241     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1242         JA.getKind() <= Action::AssembleJobClass) {
1243       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1244       // -fpch-instantiate-templates is the default when creating
1245       // precomp using /Yc
1246       if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1247                        options::OPT_fno_pch_instantiate_templates, true))
1248         CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1249     }
1250     if (YcArg || YuArg) {
1251       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1252       if (!isa<PrecompileJobAction>(JA)) {
1253         CmdArgs.push_back("-include-pch");
1254         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1255             C, !ThroughHeader.empty()
1256                    ? ThroughHeader
1257                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1258       }
1259 
1260       if (ThroughHeader.empty()) {
1261         CmdArgs.push_back(Args.MakeArgString(
1262             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1263       } else {
1264         CmdArgs.push_back(
1265             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1266       }
1267     }
1268   }
1269 
1270   bool RenderedImplicitInclude = false;
1271   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1272     if (A->getOption().matches(options::OPT_include) &&
1273         D.getProbePrecompiled()) {
1274       // Handling of gcc-style gch precompiled headers.
1275       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1276       RenderedImplicitInclude = true;
1277 
1278       bool FoundPCH = false;
1279       SmallString<128> P(A->getValue());
1280       // We want the files to have a name like foo.h.pch. Add a dummy extension
1281       // so that replace_extension does the right thing.
1282       P += ".dummy";
1283       llvm::sys::path::replace_extension(P, "pch");
1284       if (D.getVFS().exists(P))
1285         FoundPCH = true;
1286 
1287       if (!FoundPCH) {
1288         llvm::sys::path::replace_extension(P, "gch");
1289         if (D.getVFS().exists(P)) {
1290           FoundPCH = true;
1291         }
1292       }
1293 
1294       if (FoundPCH) {
1295         if (IsFirstImplicitInclude) {
1296           A->claim();
1297           CmdArgs.push_back("-include-pch");
1298           CmdArgs.push_back(Args.MakeArgString(P));
1299           continue;
1300         } else {
1301           // Ignore the PCH if not first on command line and emit warning.
1302           D.Diag(diag::warn_drv_pch_not_first_include) << P
1303                                                        << A->getAsString(Args);
1304         }
1305       }
1306     } else if (A->getOption().matches(options::OPT_isystem_after)) {
1307       // Handling of paths which must come late.  These entries are handled by
1308       // the toolchain itself after the resource dir is inserted in the right
1309       // search order.
1310       // Do not claim the argument so that the use of the argument does not
1311       // silently go unnoticed on toolchains which do not honour the option.
1312       continue;
1313     } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1314       // Translated to -internal-isystem by the driver, no need to pass to cc1.
1315       continue;
1316     } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1317       // This is used only by the driver. No need to pass to cc1.
1318       continue;
1319     }
1320 
1321     // Not translated, render as usual.
1322     A->claim();
1323     A->render(Args, CmdArgs);
1324   }
1325 
1326   Args.AddAllArgs(CmdArgs,
1327                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1328                    options::OPT_F, options::OPT_index_header_map});
1329 
1330   // Add -Wp, and -Xpreprocessor if using the preprocessor.
1331 
1332   // FIXME: There is a very unfortunate problem here, some troubled
1333   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1334   // really support that we would have to parse and then translate
1335   // those options. :(
1336   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1337                        options::OPT_Xpreprocessor);
1338 
1339   // -I- is a deprecated GCC feature, reject it.
1340   if (Arg *A = Args.getLastArg(options::OPT_I_))
1341     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1342 
1343   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1344   // -isysroot to the CC1 invocation.
1345   StringRef sysroot = C.getSysRoot();
1346   if (sysroot != "") {
1347     if (!Args.hasArg(options::OPT_isysroot)) {
1348       CmdArgs.push_back("-isysroot");
1349       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1350     }
1351   }
1352 
1353   // Parse additional include paths from environment variables.
1354   // FIXME: We should probably sink the logic for handling these from the
1355   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1356   // CPATH - included following the user specified includes (but prior to
1357   // builtin and standard includes).
1358   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1359   // C_INCLUDE_PATH - system includes enabled when compiling C.
1360   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1361   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1362   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1363   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1364   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1365   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1366   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1367 
1368   // While adding the include arguments, we also attempt to retrieve the
1369   // arguments of related offloading toolchains or arguments that are specific
1370   // of an offloading programming model.
1371 
1372   // Add C++ include arguments, if needed.
1373   if (types::isCXX(Inputs[0].getType())) {
1374     bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1375     forAllAssociatedToolChains(
1376         C, JA, getToolChain(),
1377         [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1378           HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1379                              : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1380         });
1381   }
1382 
1383   // Add system include arguments for all targets but IAMCU.
1384   if (!IsIAMCU)
1385     forAllAssociatedToolChains(C, JA, getToolChain(),
1386                                [&Args, &CmdArgs](const ToolChain &TC) {
1387                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1388                                });
1389   else {
1390     // For IAMCU add special include arguments.
1391     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1392   }
1393 
1394   addMacroPrefixMapArg(D, Args, CmdArgs);
1395   addCoveragePrefixMapArg(D, Args, CmdArgs);
1396 
1397   Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1398                   options::OPT_fno_file_reproducible);
1399 
1400   if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1401     CmdArgs.push_back("-source-date-epoch");
1402     CmdArgs.push_back(Args.MakeArgString(Epoch));
1403   }
1404 }
1405 
1406 // FIXME: Move to target hook.
1407 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1408   switch (Triple.getArch()) {
1409   default:
1410     return true;
1411 
1412   case llvm::Triple::aarch64:
1413   case llvm::Triple::aarch64_32:
1414   case llvm::Triple::aarch64_be:
1415   case llvm::Triple::arm:
1416   case llvm::Triple::armeb:
1417   case llvm::Triple::thumb:
1418   case llvm::Triple::thumbeb:
1419     if (Triple.isOSDarwin() || Triple.isOSWindows())
1420       return true;
1421     return false;
1422 
1423   case llvm::Triple::ppc:
1424   case llvm::Triple::ppc64:
1425     if (Triple.isOSDarwin())
1426       return true;
1427     return false;
1428 
1429   case llvm::Triple::hexagon:
1430   case llvm::Triple::ppcle:
1431   case llvm::Triple::ppc64le:
1432   case llvm::Triple::riscv32:
1433   case llvm::Triple::riscv64:
1434   case llvm::Triple::systemz:
1435   case llvm::Triple::xcore:
1436     return false;
1437   }
1438 }
1439 
1440 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1441                                    const ArgList &Args) {
1442   // Supported only on Darwin where we invoke the compiler multiple times
1443   // followed by an invocation to lipo.
1444   if (!Triple.isOSDarwin())
1445     return false;
1446   // If more than one "-arch <arch>" is specified, we're targeting multiple
1447   // architectures resulting in a fat binary.
1448   return Args.getAllArgValues(options::OPT_arch).size() > 1;
1449 }
1450 
1451 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1452                                 const llvm::Triple &Triple) {
1453   // When enabling remarks, we need to error if:
1454   // * The remark file is specified but we're targeting multiple architectures,
1455   // which means more than one remark file is being generated.
1456   bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1457   bool hasExplicitOutputFile =
1458       Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1459   if (hasMultipleInvocations && hasExplicitOutputFile) {
1460     D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1461         << "-foptimization-record-file";
1462     return false;
1463   }
1464   return true;
1465 }
1466 
1467 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1468                                  const llvm::Triple &Triple,
1469                                  const InputInfo &Input,
1470                                  const InputInfo &Output, const JobAction &JA) {
1471   StringRef Format = "yaml";
1472   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1473     Format = A->getValue();
1474 
1475   CmdArgs.push_back("-opt-record-file");
1476 
1477   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1478   if (A) {
1479     CmdArgs.push_back(A->getValue());
1480   } else {
1481     bool hasMultipleArchs =
1482         Triple.isOSDarwin() && // Only supported on Darwin platforms.
1483         Args.getAllArgValues(options::OPT_arch).size() > 1;
1484 
1485     SmallString<128> F;
1486 
1487     if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1488       if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1489         F = FinalOutput->getValue();
1490     } else {
1491       if (Format != "yaml" && // For YAML, keep the original behavior.
1492           Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1493           Output.isFilename())
1494         F = Output.getFilename();
1495     }
1496 
1497     if (F.empty()) {
1498       // Use the input filename.
1499       F = llvm::sys::path::stem(Input.getBaseInput());
1500 
1501       // If we're compiling for an offload architecture (i.e. a CUDA device),
1502       // we need to make the file name for the device compilation different
1503       // from the host compilation.
1504       if (!JA.isDeviceOffloading(Action::OFK_None) &&
1505           !JA.isDeviceOffloading(Action::OFK_Host)) {
1506         llvm::sys::path::replace_extension(F, "");
1507         F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1508                                                  Triple.normalize());
1509         F += "-";
1510         F += JA.getOffloadingArch();
1511       }
1512     }
1513 
1514     // If we're having more than one "-arch", we should name the files
1515     // differently so that every cc1 invocation writes to a different file.
1516     // We're doing that by appending "-<arch>" with "<arch>" being the arch
1517     // name from the triple.
1518     if (hasMultipleArchs) {
1519       // First, remember the extension.
1520       SmallString<64> OldExtension = llvm::sys::path::extension(F);
1521       // then, remove it.
1522       llvm::sys::path::replace_extension(F, "");
1523       // attach -<arch> to it.
1524       F += "-";
1525       F += Triple.getArchName();
1526       // put back the extension.
1527       llvm::sys::path::replace_extension(F, OldExtension);
1528     }
1529 
1530     SmallString<32> Extension;
1531     Extension += "opt.";
1532     Extension += Format;
1533 
1534     llvm::sys::path::replace_extension(F, Extension);
1535     CmdArgs.push_back(Args.MakeArgString(F));
1536   }
1537 
1538   if (const Arg *A =
1539           Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1540     CmdArgs.push_back("-opt-record-passes");
1541     CmdArgs.push_back(A->getValue());
1542   }
1543 
1544   if (!Format.empty()) {
1545     CmdArgs.push_back("-opt-record-format");
1546     CmdArgs.push_back(Format.data());
1547   }
1548 }
1549 
1550 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1551   if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1552                     options::OPT_fno_aapcs_bitfield_width, true))
1553     CmdArgs.push_back("-fno-aapcs-bitfield-width");
1554 
1555   if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1556     CmdArgs.push_back("-faapcs-bitfield-load");
1557 }
1558 
1559 namespace {
1560 void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1561                   const ArgList &Args, ArgStringList &CmdArgs) {
1562   // Select the ABI to use.
1563   // FIXME: Support -meabi.
1564   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1565   const char *ABIName = nullptr;
1566   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1567     ABIName = A->getValue();
1568   } else {
1569     std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1570     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1571   }
1572 
1573   CmdArgs.push_back("-target-abi");
1574   CmdArgs.push_back(ABIName);
1575 }
1576 
1577 void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1578   auto StrictAlignIter =
1579       llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1580         return Arg == "+strict-align" || Arg == "-strict-align";
1581       });
1582   if (StrictAlignIter != CmdArgs.rend() &&
1583       StringRef(*StrictAlignIter) == "+strict-align")
1584     CmdArgs.push_back("-Wunaligned-access");
1585 }
1586 }
1587 
1588 static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1589                                     ArgStringList &CmdArgs, bool isAArch64) {
1590   const Arg *A = isAArch64
1591                      ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1592                                        options::OPT_mbranch_protection_EQ)
1593                      : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1594   if (!A)
1595     return;
1596 
1597   const Driver &D = TC.getDriver();
1598   const llvm::Triple &Triple = TC.getEffectiveTriple();
1599   if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1600     D.Diag(diag::warn_incompatible_branch_protection_option)
1601         << Triple.getArchName();
1602 
1603   StringRef Scope, Key;
1604   bool IndirectBranches;
1605 
1606   if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1607     Scope = A->getValue();
1608     if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1609       D.Diag(diag::err_drv_unsupported_option_argument)
1610           << A->getSpelling() << Scope;
1611     Key = "a_key";
1612     IndirectBranches = false;
1613   } else {
1614     StringRef DiagMsg;
1615     llvm::ARM::ParsedBranchProtection PBP;
1616     if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
1617       D.Diag(diag::err_drv_unsupported_option_argument)
1618           << A->getSpelling() << DiagMsg;
1619     if (!isAArch64 && PBP.Key == "b_key")
1620       D.Diag(diag::warn_unsupported_branch_protection)
1621           << "b-key" << A->getAsString(Args);
1622     Scope = PBP.Scope;
1623     Key = PBP.Key;
1624     IndirectBranches = PBP.BranchTargetEnforcement;
1625   }
1626 
1627   CmdArgs.push_back(
1628       Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1629   if (!Scope.equals("none"))
1630     CmdArgs.push_back(
1631         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1632   if (IndirectBranches)
1633     CmdArgs.push_back("-mbranch-target-enforce");
1634 }
1635 
1636 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1637                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1638   RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1639 
1640   // Determine floating point ABI from the options & target defaults.
1641   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1642   if (ABI == arm::FloatABI::Soft) {
1643     // Floating point operations and argument passing are soft.
1644     // FIXME: This changes CPP defines, we need -target-soft-float.
1645     CmdArgs.push_back("-msoft-float");
1646     CmdArgs.push_back("-mfloat-abi");
1647     CmdArgs.push_back("soft");
1648   } else if (ABI == arm::FloatABI::SoftFP) {
1649     // Floating point operations are hard, but argument passing is soft.
1650     CmdArgs.push_back("-mfloat-abi");
1651     CmdArgs.push_back("soft");
1652   } else {
1653     // Floating point operations and argument passing are hard.
1654     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1655     CmdArgs.push_back("-mfloat-abi");
1656     CmdArgs.push_back("hard");
1657   }
1658 
1659   // Forward the -mglobal-merge option for explicit control over the pass.
1660   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1661                                options::OPT_mno_global_merge)) {
1662     CmdArgs.push_back("-mllvm");
1663     if (A->getOption().matches(options::OPT_mno_global_merge))
1664       CmdArgs.push_back("-arm-global-merge=false");
1665     else
1666       CmdArgs.push_back("-arm-global-merge=true");
1667   }
1668 
1669   if (!Args.hasFlag(options::OPT_mimplicit_float,
1670                     options::OPT_mno_implicit_float, true))
1671     CmdArgs.push_back("-no-implicit-float");
1672 
1673   if (Args.getLastArg(options::OPT_mcmse))
1674     CmdArgs.push_back("-mcmse");
1675 
1676   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1677 
1678   // Enable/disable return address signing and indirect branch targets.
1679   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1680 
1681   AddUnalignedAccessWarning(CmdArgs);
1682 }
1683 
1684 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1685                                 const ArgList &Args, bool KernelOrKext,
1686                                 ArgStringList &CmdArgs) const {
1687   const ToolChain &TC = getToolChain();
1688 
1689   // Add the target features
1690   getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1691 
1692   // Add target specific flags.
1693   switch (TC.getArch()) {
1694   default:
1695     break;
1696 
1697   case llvm::Triple::arm:
1698   case llvm::Triple::armeb:
1699   case llvm::Triple::thumb:
1700   case llvm::Triple::thumbeb:
1701     // Use the effective triple, which takes into account the deployment target.
1702     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1703     break;
1704 
1705   case llvm::Triple::aarch64:
1706   case llvm::Triple::aarch64_32:
1707   case llvm::Triple::aarch64_be:
1708     AddAArch64TargetArgs(Args, CmdArgs);
1709     break;
1710 
1711   case llvm::Triple::loongarch32:
1712   case llvm::Triple::loongarch64:
1713     AddLoongArchTargetArgs(Args, CmdArgs);
1714     break;
1715 
1716   case llvm::Triple::mips:
1717   case llvm::Triple::mipsel:
1718   case llvm::Triple::mips64:
1719   case llvm::Triple::mips64el:
1720     AddMIPSTargetArgs(Args, CmdArgs);
1721     break;
1722 
1723   case llvm::Triple::ppc:
1724   case llvm::Triple::ppcle:
1725   case llvm::Triple::ppc64:
1726   case llvm::Triple::ppc64le:
1727     AddPPCTargetArgs(Args, CmdArgs);
1728     break;
1729 
1730   case llvm::Triple::riscv32:
1731   case llvm::Triple::riscv64:
1732     AddRISCVTargetArgs(Args, CmdArgs);
1733     break;
1734 
1735   case llvm::Triple::sparc:
1736   case llvm::Triple::sparcel:
1737   case llvm::Triple::sparcv9:
1738     AddSparcTargetArgs(Args, CmdArgs);
1739     break;
1740 
1741   case llvm::Triple::systemz:
1742     AddSystemZTargetArgs(Args, CmdArgs);
1743     break;
1744 
1745   case llvm::Triple::x86:
1746   case llvm::Triple::x86_64:
1747     AddX86TargetArgs(Args, CmdArgs);
1748     break;
1749 
1750   case llvm::Triple::lanai:
1751     AddLanaiTargetArgs(Args, CmdArgs);
1752     break;
1753 
1754   case llvm::Triple::hexagon:
1755     AddHexagonTargetArgs(Args, CmdArgs);
1756     break;
1757 
1758   case llvm::Triple::wasm32:
1759   case llvm::Triple::wasm64:
1760     AddWebAssemblyTargetArgs(Args, CmdArgs);
1761     break;
1762 
1763   case llvm::Triple::ve:
1764     AddVETargetArgs(Args, CmdArgs);
1765     break;
1766   }
1767 }
1768 
1769 namespace {
1770 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1771                       ArgStringList &CmdArgs) {
1772   const char *ABIName = nullptr;
1773   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1774     ABIName = A->getValue();
1775   else if (Triple.isOSDarwin())
1776     ABIName = "darwinpcs";
1777   else
1778     ABIName = "aapcs";
1779 
1780   CmdArgs.push_back("-target-abi");
1781   CmdArgs.push_back(ABIName);
1782 }
1783 }
1784 
1785 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1786                                  ArgStringList &CmdArgs) const {
1787   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1788 
1789   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1790       Args.hasArg(options::OPT_mkernel) ||
1791       Args.hasArg(options::OPT_fapple_kext))
1792     CmdArgs.push_back("-disable-red-zone");
1793 
1794   if (!Args.hasFlag(options::OPT_mimplicit_float,
1795                     options::OPT_mno_implicit_float, true))
1796     CmdArgs.push_back("-no-implicit-float");
1797 
1798   RenderAArch64ABI(Triple, Args, CmdArgs);
1799 
1800   // Forward the -mglobal-merge option for explicit control over the pass.
1801   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1802                                options::OPT_mno_global_merge)) {
1803     CmdArgs.push_back("-mllvm");
1804     if (A->getOption().matches(options::OPT_mno_global_merge))
1805       CmdArgs.push_back("-aarch64-enable-global-merge=false");
1806     else
1807       CmdArgs.push_back("-aarch64-enable-global-merge=true");
1808   }
1809 
1810   // Enable/disable return address signing and indirect branch targets.
1811   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1812 
1813   // Handle -msve_vector_bits=<bits>
1814   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1815     StringRef Val = A->getValue();
1816     const Driver &D = getToolChain().getDriver();
1817     if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1818         Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1819         Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1820         Val.equals("2048+")) {
1821       unsigned Bits = 0;
1822       if (Val.endswith("+"))
1823         Val = Val.substr(0, Val.size() - 1);
1824       else {
1825         bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1826         assert(!Invalid && "Failed to parse value");
1827         CmdArgs.push_back(
1828             Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1829       }
1830 
1831       bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1832       assert(!Invalid && "Failed to parse value");
1833       CmdArgs.push_back(
1834           Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1835     // Silently drop requests for vector-length agnostic code as it's implied.
1836     } else if (!Val.equals("scalable"))
1837       // Handle the unsupported values passed to msve-vector-bits.
1838       D.Diag(diag::err_drv_unsupported_option_argument)
1839           << A->getSpelling() << Val;
1840   }
1841 
1842   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1843 
1844   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1845     CmdArgs.push_back("-tune-cpu");
1846     if (strcmp(A->getValue(), "native") == 0)
1847       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1848     else
1849       CmdArgs.push_back(A->getValue());
1850   }
1851 
1852   AddUnalignedAccessWarning(CmdArgs);
1853 }
1854 
1855 void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1856                                    ArgStringList &CmdArgs) const {
1857   const llvm::Triple &Triple = getToolChain().getTriple();
1858 
1859   CmdArgs.push_back("-target-abi");
1860   CmdArgs.push_back(
1861       loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1862           .data());
1863 
1864   // Handle -mtune.
1865   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1866     std::string TuneCPU = A->getValue();
1867     TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1868     CmdArgs.push_back("-tune-cpu");
1869     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1870   }
1871 }
1872 
1873 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1874                               ArgStringList &CmdArgs) const {
1875   const Driver &D = getToolChain().getDriver();
1876   StringRef CPUName;
1877   StringRef ABIName;
1878   const llvm::Triple &Triple = getToolChain().getTriple();
1879   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1880 
1881   CmdArgs.push_back("-target-abi");
1882   CmdArgs.push_back(ABIName.data());
1883 
1884   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1885   if (ABI == mips::FloatABI::Soft) {
1886     // Floating point operations and argument passing are soft.
1887     CmdArgs.push_back("-msoft-float");
1888     CmdArgs.push_back("-mfloat-abi");
1889     CmdArgs.push_back("soft");
1890   } else {
1891     // Floating point operations and argument passing are hard.
1892     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1893     CmdArgs.push_back("-mfloat-abi");
1894     CmdArgs.push_back("hard");
1895   }
1896 
1897   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1898                                options::OPT_mno_ldc1_sdc1)) {
1899     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1900       CmdArgs.push_back("-mllvm");
1901       CmdArgs.push_back("-mno-ldc1-sdc1");
1902     }
1903   }
1904 
1905   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1906                                options::OPT_mno_check_zero_division)) {
1907     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1908       CmdArgs.push_back("-mllvm");
1909       CmdArgs.push_back("-mno-check-zero-division");
1910     }
1911   }
1912 
1913   if (Args.getLastArg(options::OPT_mfix4300)) {
1914     CmdArgs.push_back("-mllvm");
1915     CmdArgs.push_back("-mfix4300");
1916   }
1917 
1918   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1919     StringRef v = A->getValue();
1920     CmdArgs.push_back("-mllvm");
1921     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1922     A->claim();
1923   }
1924 
1925   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1926   Arg *ABICalls =
1927       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1928 
1929   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1930   // -mgpopt is the default for static, -fno-pic environments but these two
1931   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1932   // the only case where -mllvm -mgpopt is passed.
1933   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1934   //       passed explicitly when compiling something with -mabicalls
1935   //       (implictly) in affect. Currently the warning is in the backend.
1936   //
1937   // When the ABI in use is  N64, we also need to determine the PIC mode that
1938   // is in use, as -fno-pic for N64 implies -mno-abicalls.
1939   bool NoABICalls =
1940       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1941 
1942   llvm::Reloc::Model RelocationModel;
1943   unsigned PICLevel;
1944   bool IsPIE;
1945   std::tie(RelocationModel, PICLevel, IsPIE) =
1946       ParsePICArgs(getToolChain(), Args);
1947 
1948   NoABICalls = NoABICalls ||
1949                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1950 
1951   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1952   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1953   if (NoABICalls && (!GPOpt || WantGPOpt)) {
1954     CmdArgs.push_back("-mllvm");
1955     CmdArgs.push_back("-mgpopt");
1956 
1957     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1958                                       options::OPT_mno_local_sdata);
1959     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1960                                        options::OPT_mno_extern_sdata);
1961     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1962                                         options::OPT_mno_embedded_data);
1963     if (LocalSData) {
1964       CmdArgs.push_back("-mllvm");
1965       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1966         CmdArgs.push_back("-mlocal-sdata=1");
1967       } else {
1968         CmdArgs.push_back("-mlocal-sdata=0");
1969       }
1970       LocalSData->claim();
1971     }
1972 
1973     if (ExternSData) {
1974       CmdArgs.push_back("-mllvm");
1975       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1976         CmdArgs.push_back("-mextern-sdata=1");
1977       } else {
1978         CmdArgs.push_back("-mextern-sdata=0");
1979       }
1980       ExternSData->claim();
1981     }
1982 
1983     if (EmbeddedData) {
1984       CmdArgs.push_back("-mllvm");
1985       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1986         CmdArgs.push_back("-membedded-data=1");
1987       } else {
1988         CmdArgs.push_back("-membedded-data=0");
1989       }
1990       EmbeddedData->claim();
1991     }
1992 
1993   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1994     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1995 
1996   if (GPOpt)
1997     GPOpt->claim();
1998 
1999   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
2000     StringRef Val = StringRef(A->getValue());
2001     if (mips::hasCompactBranches(CPUName)) {
2002       if (Val == "never" || Val == "always" || Val == "optimal") {
2003         CmdArgs.push_back("-mllvm");
2004         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
2005       } else
2006         D.Diag(diag::err_drv_unsupported_option_argument)
2007             << A->getSpelling() << Val;
2008     } else
2009       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
2010   }
2011 
2012   if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
2013                                options::OPT_mno_relax_pic_calls)) {
2014     if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
2015       CmdArgs.push_back("-mllvm");
2016       CmdArgs.push_back("-mips-jalr-reloc=0");
2017     }
2018   }
2019 }
2020 
2021 void Clang::AddPPCTargetArgs(const ArgList &Args,
2022                              ArgStringList &CmdArgs) const {
2023   const Driver &D = getToolChain().getDriver();
2024   const llvm::Triple &T = getToolChain().getTriple();
2025   if (Args.getLastArg(options::OPT_mtune_EQ)) {
2026     CmdArgs.push_back("-tune-cpu");
2027     std::string CPU = ppc::getPPCTuneCPU(Args, T);
2028     CmdArgs.push_back(Args.MakeArgString(CPU));
2029   }
2030 
2031   // Select the ABI to use.
2032   const char *ABIName = nullptr;
2033   if (T.isOSBinFormatELF()) {
2034     switch (getToolChain().getArch()) {
2035     case llvm::Triple::ppc64: {
2036       if (T.isPPC64ELFv2ABI())
2037         ABIName = "elfv2";
2038       else
2039         ABIName = "elfv1";
2040       break;
2041     }
2042     case llvm::Triple::ppc64le:
2043       ABIName = "elfv2";
2044       break;
2045     default:
2046       break;
2047     }
2048   }
2049 
2050   bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2051   bool VecExtabi = false;
2052   for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2053     StringRef V = A->getValue();
2054     if (V == "ieeelongdouble") {
2055       IEEELongDouble = true;
2056       A->claim();
2057     } else if (V == "ibmlongdouble") {
2058       IEEELongDouble = false;
2059       A->claim();
2060     } else if (V == "vec-default") {
2061       VecExtabi = false;
2062       A->claim();
2063     } else if (V == "vec-extabi") {
2064       VecExtabi = true;
2065       A->claim();
2066     } else if (V == "elfv1") {
2067       ABIName = "elfv1";
2068       A->claim();
2069     } else if (V == "elfv2") {
2070       ABIName = "elfv2";
2071       A->claim();
2072     } else if (V != "altivec")
2073       // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2074       // the option if given as we don't have backend support for any targets
2075       // that don't use the altivec abi.
2076       ABIName = A->getValue();
2077   }
2078   if (IEEELongDouble)
2079     CmdArgs.push_back("-mabi=ieeelongdouble");
2080   if (VecExtabi) {
2081     if (!T.isOSAIX())
2082       D.Diag(diag::err_drv_unsupported_opt_for_target)
2083           << "-mabi=vec-extabi" << T.str();
2084     CmdArgs.push_back("-mabi=vec-extabi");
2085   }
2086 
2087   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2088   if (FloatABI == ppc::FloatABI::Soft) {
2089     // Floating point operations and argument passing are soft.
2090     CmdArgs.push_back("-msoft-float");
2091     CmdArgs.push_back("-mfloat-abi");
2092     CmdArgs.push_back("soft");
2093   } else {
2094     // Floating point operations and argument passing are hard.
2095     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2096     CmdArgs.push_back("-mfloat-abi");
2097     CmdArgs.push_back("hard");
2098   }
2099 
2100   if (ABIName) {
2101     CmdArgs.push_back("-target-abi");
2102     CmdArgs.push_back(ABIName);
2103   }
2104 }
2105 
2106 static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2107                                    ArgStringList &CmdArgs) {
2108   const Driver &D = TC.getDriver();
2109   const llvm::Triple &Triple = TC.getTriple();
2110   // Default small data limitation is eight.
2111   const char *SmallDataLimit = "8";
2112   // Get small data limitation.
2113   if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2114                       options::OPT_fPIC)) {
2115     // Not support linker relaxation for PIC.
2116     SmallDataLimit = "0";
2117     if (Args.hasArg(options::OPT_G)) {
2118       D.Diag(diag::warn_drv_unsupported_sdata);
2119     }
2120   } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2121                  .equals_insensitive("large") &&
2122              (Triple.getArch() == llvm::Triple::riscv64)) {
2123     // Not support linker relaxation for RV64 with large code model.
2124     SmallDataLimit = "0";
2125     if (Args.hasArg(options::OPT_G)) {
2126       D.Diag(diag::warn_drv_unsupported_sdata);
2127     }
2128   } else if (Triple.isAndroid()) {
2129     // GP relaxation is not supported on Android.
2130     SmallDataLimit = "0";
2131     if (Args.hasArg(options::OPT_G)) {
2132       D.Diag(diag::warn_drv_unsupported_sdata);
2133     }
2134   } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2135     SmallDataLimit = A->getValue();
2136   }
2137   // Forward the -msmall-data-limit= option.
2138   CmdArgs.push_back("-msmall-data-limit");
2139   CmdArgs.push_back(SmallDataLimit);
2140 }
2141 
2142 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2143                                ArgStringList &CmdArgs) const {
2144   const llvm::Triple &Triple = getToolChain().getTriple();
2145   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2146 
2147   CmdArgs.push_back("-target-abi");
2148   CmdArgs.push_back(ABIName.data());
2149 
2150   SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2151 
2152   if (!Args.hasFlag(options::OPT_mimplicit_float,
2153                     options::OPT_mno_implicit_float, true))
2154     CmdArgs.push_back("-no-implicit-float");
2155 
2156   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2157     CmdArgs.push_back("-tune-cpu");
2158     if (strcmp(A->getValue(), "native") == 0)
2159       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2160     else
2161       CmdArgs.push_back(A->getValue());
2162   }
2163 
2164   // Handle -mrvv-vector-bits=<bits>
2165   if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2166     StringRef Val = A->getValue();
2167     const Driver &D = getToolChain().getDriver();
2168 
2169     // Get minimum VLen from march.
2170     unsigned MinVLen = 0;
2171     StringRef Arch = riscv::getRISCVArch(Args, Triple);
2172     auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2173         Arch, /*EnableExperimentalExtensions*/ true);
2174     if (!ISAInfo) {
2175       // Ignore parsing error.
2176       consumeError(ISAInfo.takeError());
2177     } else {
2178       MinVLen = (*ISAInfo)->getMinVLen();
2179     }
2180 
2181     // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2182     // as integer as long as we have a MinVLen.
2183     unsigned Bits = 0;
2184     if (Val.equals("zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2185       Bits = MinVLen;
2186     } else if (!Val.getAsInteger(10, Bits)) {
2187       // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2188       // at least MinVLen.
2189       if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2190           Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2191         Bits = 0;
2192     }
2193 
2194     // If we got a valid value try to use it.
2195     if (Bits != 0) {
2196       unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2197       CmdArgs.push_back(
2198           Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2199       CmdArgs.push_back(
2200           Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2201     } else if (!Val.equals("scalable")) {
2202       // Handle the unsupported values passed to mrvv-vector-bits.
2203       D.Diag(diag::err_drv_unsupported_option_argument)
2204           << A->getSpelling() << Val;
2205     }
2206   }
2207 }
2208 
2209 void Clang::AddSparcTargetArgs(const ArgList &Args,
2210                                ArgStringList &CmdArgs) const {
2211   sparc::FloatABI FloatABI =
2212       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2213 
2214   if (FloatABI == sparc::FloatABI::Soft) {
2215     // Floating point operations and argument passing are soft.
2216     CmdArgs.push_back("-msoft-float");
2217     CmdArgs.push_back("-mfloat-abi");
2218     CmdArgs.push_back("soft");
2219   } else {
2220     // Floating point operations and argument passing are hard.
2221     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2222     CmdArgs.push_back("-mfloat-abi");
2223     CmdArgs.push_back("hard");
2224   }
2225 
2226   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2227     StringRef Name = A->getValue();
2228     std::string TuneCPU;
2229     if (Name == "native")
2230       TuneCPU = std::string(llvm::sys::getHostCPUName());
2231     else
2232       TuneCPU = std::string(Name);
2233 
2234     CmdArgs.push_back("-tune-cpu");
2235     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2236   }
2237 }
2238 
2239 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2240                                  ArgStringList &CmdArgs) const {
2241   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2242     CmdArgs.push_back("-tune-cpu");
2243     if (strcmp(A->getValue(), "native") == 0)
2244       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2245     else
2246       CmdArgs.push_back(A->getValue());
2247   }
2248 
2249   bool HasBackchain =
2250       Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2251   bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2252                                      options::OPT_mno_packed_stack, false);
2253   systemz::FloatABI FloatABI =
2254       systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2255   bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2256   if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2257     const Driver &D = getToolChain().getDriver();
2258     D.Diag(diag::err_drv_unsupported_opt)
2259       << "-mpacked-stack -mbackchain -mhard-float";
2260   }
2261   if (HasBackchain)
2262     CmdArgs.push_back("-mbackchain");
2263   if (HasPackedStack)
2264     CmdArgs.push_back("-mpacked-stack");
2265   if (HasSoftFloat) {
2266     // Floating point operations and argument passing are soft.
2267     CmdArgs.push_back("-msoft-float");
2268     CmdArgs.push_back("-mfloat-abi");
2269     CmdArgs.push_back("soft");
2270   }
2271 }
2272 
2273 void Clang::AddX86TargetArgs(const ArgList &Args,
2274                              ArgStringList &CmdArgs) const {
2275   const Driver &D = getToolChain().getDriver();
2276   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2277 
2278   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2279       Args.hasArg(options::OPT_mkernel) ||
2280       Args.hasArg(options::OPT_fapple_kext))
2281     CmdArgs.push_back("-disable-red-zone");
2282 
2283   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2284                     options::OPT_mno_tls_direct_seg_refs, true))
2285     CmdArgs.push_back("-mno-tls-direct-seg-refs");
2286 
2287   // Default to avoid implicit floating-point for kernel/kext code, but allow
2288   // that to be overridden with -mno-soft-float.
2289   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2290                           Args.hasArg(options::OPT_fapple_kext));
2291   if (Arg *A = Args.getLastArg(
2292           options::OPT_msoft_float, options::OPT_mno_soft_float,
2293           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2294     const Option &O = A->getOption();
2295     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2296                        O.matches(options::OPT_msoft_float));
2297   }
2298   if (NoImplicitFloat)
2299     CmdArgs.push_back("-no-implicit-float");
2300 
2301   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2302     StringRef Value = A->getValue();
2303     if (Value == "intel" || Value == "att") {
2304       CmdArgs.push_back("-mllvm");
2305       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2306       CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2307     } else {
2308       D.Diag(diag::err_drv_unsupported_option_argument)
2309           << A->getSpelling() << Value;
2310     }
2311   } else if (D.IsCLMode()) {
2312     CmdArgs.push_back("-mllvm");
2313     CmdArgs.push_back("-x86-asm-syntax=intel");
2314   }
2315 
2316   if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2317                                options::OPT_mno_skip_rax_setup))
2318     if (A->getOption().matches(options::OPT_mskip_rax_setup))
2319       CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2320 
2321   // Set flags to support MCU ABI.
2322   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2323     CmdArgs.push_back("-mfloat-abi");
2324     CmdArgs.push_back("soft");
2325     CmdArgs.push_back("-mstack-alignment=4");
2326   }
2327 
2328   // Handle -mtune.
2329 
2330   // Default to "generic" unless -march is present or targetting the PS4/PS5.
2331   std::string TuneCPU;
2332   if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2333       !getToolChain().getTriple().isPS())
2334     TuneCPU = "generic";
2335 
2336   // Override based on -mtune.
2337   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2338     StringRef Name = A->getValue();
2339 
2340     if (Name == "native") {
2341       Name = llvm::sys::getHostCPUName();
2342       if (!Name.empty())
2343         TuneCPU = std::string(Name);
2344     } else
2345       TuneCPU = std::string(Name);
2346   }
2347 
2348   if (!TuneCPU.empty()) {
2349     CmdArgs.push_back("-tune-cpu");
2350     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2351   }
2352 }
2353 
2354 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2355                                  ArgStringList &CmdArgs) const {
2356   CmdArgs.push_back("-mqdsp6-compat");
2357   CmdArgs.push_back("-Wreturn-type");
2358 
2359   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2360     CmdArgs.push_back("-mllvm");
2361     CmdArgs.push_back(
2362         Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2363   }
2364 
2365   if (!Args.hasArg(options::OPT_fno_short_enums))
2366     CmdArgs.push_back("-fshort-enums");
2367   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2368     CmdArgs.push_back("-mllvm");
2369     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2370   }
2371   CmdArgs.push_back("-mllvm");
2372   CmdArgs.push_back("-machine-sink-split=0");
2373 }
2374 
2375 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2376                                ArgStringList &CmdArgs) const {
2377   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2378     StringRef CPUName = A->getValue();
2379 
2380     CmdArgs.push_back("-target-cpu");
2381     CmdArgs.push_back(Args.MakeArgString(CPUName));
2382   }
2383   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2384     StringRef Value = A->getValue();
2385     // Only support mregparm=4 to support old usage. Report error for all other
2386     // cases.
2387     int Mregparm;
2388     if (Value.getAsInteger(10, Mregparm)) {
2389       if (Mregparm != 4) {
2390         getToolChain().getDriver().Diag(
2391             diag::err_drv_unsupported_option_argument)
2392             << A->getSpelling() << Value;
2393       }
2394     }
2395   }
2396 }
2397 
2398 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2399                                      ArgStringList &CmdArgs) const {
2400   // Default to "hidden" visibility.
2401   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2402                    options::OPT_fvisibility_ms_compat))
2403     CmdArgs.push_back("-fvisibility=hidden");
2404 }
2405 
2406 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2407   // Floating point operations and argument passing are hard.
2408   CmdArgs.push_back("-mfloat-abi");
2409   CmdArgs.push_back("hard");
2410 }
2411 
2412 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2413                                     StringRef Target, const InputInfo &Output,
2414                                     const InputInfo &Input, const ArgList &Args) const {
2415   // If this is a dry run, do not create the compilation database file.
2416   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2417     return;
2418 
2419   using llvm::yaml::escape;
2420   const Driver &D = getToolChain().getDriver();
2421 
2422   if (!CompilationDatabase) {
2423     std::error_code EC;
2424     auto File = std::make_unique<llvm::raw_fd_ostream>(
2425         Filename, EC,
2426         llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2427     if (EC) {
2428       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2429                                                        << EC.message();
2430       return;
2431     }
2432     CompilationDatabase = std::move(File);
2433   }
2434   auto &CDB = *CompilationDatabase;
2435   auto CWD = D.getVFS().getCurrentWorkingDirectory();
2436   if (!CWD)
2437     CWD = ".";
2438   CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2439   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2440   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2441   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2442   SmallString<128> Buf;
2443   Buf = "-x";
2444   Buf += types::getTypeName(Input.getType());
2445   CDB << ", \"" << escape(Buf) << "\"";
2446   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2447     Buf = "--sysroot=";
2448     Buf += D.SysRoot;
2449     CDB << ", \"" << escape(Buf) << "\"";
2450   }
2451   CDB << ", \"" << escape(Input.getFilename()) << "\"";
2452   CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2453   for (auto &A: Args) {
2454     auto &O = A->getOption();
2455     // Skip language selection, which is positional.
2456     if (O.getID() == options::OPT_x)
2457       continue;
2458     // Skip writing dependency output and the compilation database itself.
2459     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2460       continue;
2461     if (O.getID() == options::OPT_gen_cdb_fragment_path)
2462       continue;
2463     // Skip inputs.
2464     if (O.getKind() == Option::InputClass)
2465       continue;
2466     // Skip output.
2467     if (O.getID() == options::OPT_o)
2468       continue;
2469     // All other arguments are quoted and appended.
2470     ArgStringList ASL;
2471     A->render(Args, ASL);
2472     for (auto &it: ASL)
2473       CDB << ", \"" << escape(it) << "\"";
2474   }
2475   Buf = "--target=";
2476   Buf += Target;
2477   CDB << ", \"" << escape(Buf) << "\"]},\n";
2478 }
2479 
2480 void Clang::DumpCompilationDatabaseFragmentToDir(
2481     StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2482     const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2483   // If this is a dry run, do not create the compilation database file.
2484   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2485     return;
2486 
2487   if (CompilationDatabase)
2488     DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2489 
2490   SmallString<256> Path = Dir;
2491   const auto &Driver = C.getDriver();
2492   Driver.getVFS().makeAbsolute(Path);
2493   auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2494   if (Err) {
2495     Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2496     return;
2497   }
2498 
2499   llvm::sys::path::append(
2500       Path,
2501       Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2502   int FD;
2503   SmallString<256> TempPath;
2504   Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2505                                         llvm::sys::fs::OF_Text);
2506   if (Err) {
2507     Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2508     return;
2509   }
2510   CompilationDatabase =
2511       std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2512   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2513 }
2514 
2515 static bool CheckARMImplicitITArg(StringRef Value) {
2516   return Value == "always" || Value == "never" || Value == "arm" ||
2517          Value == "thumb";
2518 }
2519 
2520 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2521                                  StringRef Value) {
2522   CmdArgs.push_back("-mllvm");
2523   CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2524 }
2525 
2526 static void CollectArgsForIntegratedAssembler(Compilation &C,
2527                                               const ArgList &Args,
2528                                               ArgStringList &CmdArgs,
2529                                               const Driver &D) {
2530   if (UseRelaxAll(C, Args))
2531     CmdArgs.push_back("-mrelax-all");
2532 
2533   // Only default to -mincremental-linker-compatible if we think we are
2534   // targeting the MSVC linker.
2535   bool DefaultIncrementalLinkerCompatible =
2536       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2537   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2538                    options::OPT_mno_incremental_linker_compatible,
2539                    DefaultIncrementalLinkerCompatible))
2540     CmdArgs.push_back("-mincremental-linker-compatible");
2541 
2542   Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2543 
2544   Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2545                     options::OPT_fno_emit_compact_unwind_non_canonical);
2546 
2547   // If you add more args here, also add them to the block below that
2548   // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2549 
2550   // When passing -I arguments to the assembler we sometimes need to
2551   // unconditionally take the next argument.  For example, when parsing
2552   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2553   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2554   // arg after parsing the '-I' arg.
2555   bool TakeNextArg = false;
2556 
2557   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2558   bool UseNoExecStack = false;
2559   const char *MipsTargetFeature = nullptr;
2560   StringRef ImplicitIt;
2561   for (const Arg *A :
2562        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2563                      options::OPT_mimplicit_it_EQ)) {
2564     A->claim();
2565 
2566     if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2567       switch (C.getDefaultToolChain().getArch()) {
2568       case llvm::Triple::arm:
2569       case llvm::Triple::armeb:
2570       case llvm::Triple::thumb:
2571       case llvm::Triple::thumbeb:
2572         // Only store the value; the last value set takes effect.
2573         ImplicitIt = A->getValue();
2574         if (!CheckARMImplicitITArg(ImplicitIt))
2575           D.Diag(diag::err_drv_unsupported_option_argument)
2576               << A->getSpelling() << ImplicitIt;
2577         continue;
2578       default:
2579         break;
2580       }
2581     }
2582 
2583     for (StringRef Value : A->getValues()) {
2584       if (TakeNextArg) {
2585         CmdArgs.push_back(Value.data());
2586         TakeNextArg = false;
2587         continue;
2588       }
2589 
2590       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2591           Value == "-mbig-obj")
2592         continue; // LLVM handles bigobj automatically
2593 
2594       switch (C.getDefaultToolChain().getArch()) {
2595       default:
2596         break;
2597       case llvm::Triple::wasm32:
2598       case llvm::Triple::wasm64:
2599         if (Value == "--no-type-check") {
2600           CmdArgs.push_back("-mno-type-check");
2601           continue;
2602         }
2603         break;
2604       case llvm::Triple::thumb:
2605       case llvm::Triple::thumbeb:
2606       case llvm::Triple::arm:
2607       case llvm::Triple::armeb:
2608         if (Value.startswith("-mimplicit-it=")) {
2609           // Only store the value; the last value set takes effect.
2610           ImplicitIt = Value.split("=").second;
2611           if (CheckARMImplicitITArg(ImplicitIt))
2612             continue;
2613         }
2614         if (Value == "-mthumb")
2615           // -mthumb has already been processed in ComputeLLVMTriple()
2616           // recognize but skip over here.
2617           continue;
2618         break;
2619       case llvm::Triple::mips:
2620       case llvm::Triple::mipsel:
2621       case llvm::Triple::mips64:
2622       case llvm::Triple::mips64el:
2623         if (Value == "--trap") {
2624           CmdArgs.push_back("-target-feature");
2625           CmdArgs.push_back("+use-tcc-in-div");
2626           continue;
2627         }
2628         if (Value == "--break") {
2629           CmdArgs.push_back("-target-feature");
2630           CmdArgs.push_back("-use-tcc-in-div");
2631           continue;
2632         }
2633         if (Value.startswith("-msoft-float")) {
2634           CmdArgs.push_back("-target-feature");
2635           CmdArgs.push_back("+soft-float");
2636           continue;
2637         }
2638         if (Value.startswith("-mhard-float")) {
2639           CmdArgs.push_back("-target-feature");
2640           CmdArgs.push_back("-soft-float");
2641           continue;
2642         }
2643 
2644         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2645                                 .Case("-mips1", "+mips1")
2646                                 .Case("-mips2", "+mips2")
2647                                 .Case("-mips3", "+mips3")
2648                                 .Case("-mips4", "+mips4")
2649                                 .Case("-mips5", "+mips5")
2650                                 .Case("-mips32", "+mips32")
2651                                 .Case("-mips32r2", "+mips32r2")
2652                                 .Case("-mips32r3", "+mips32r3")
2653                                 .Case("-mips32r5", "+mips32r5")
2654                                 .Case("-mips32r6", "+mips32r6")
2655                                 .Case("-mips64", "+mips64")
2656                                 .Case("-mips64r2", "+mips64r2")
2657                                 .Case("-mips64r3", "+mips64r3")
2658                                 .Case("-mips64r5", "+mips64r5")
2659                                 .Case("-mips64r6", "+mips64r6")
2660                                 .Default(nullptr);
2661         if (MipsTargetFeature)
2662           continue;
2663       }
2664 
2665       if (Value == "-force_cpusubtype_ALL") {
2666         // Do nothing, this is the default and we don't support anything else.
2667       } else if (Value == "-L") {
2668         CmdArgs.push_back("-msave-temp-labels");
2669       } else if (Value == "--fatal-warnings") {
2670         CmdArgs.push_back("-massembler-fatal-warnings");
2671       } else if (Value == "--no-warn" || Value == "-W") {
2672         CmdArgs.push_back("-massembler-no-warn");
2673       } else if (Value == "--noexecstack") {
2674         UseNoExecStack = true;
2675       } else if (Value.startswith("-compress-debug-sections") ||
2676                  Value.startswith("--compress-debug-sections") ||
2677                  Value == "-nocompress-debug-sections" ||
2678                  Value == "--nocompress-debug-sections") {
2679         CmdArgs.push_back(Value.data());
2680       } else if (Value == "-mrelax-relocations=yes" ||
2681                  Value == "--mrelax-relocations=yes") {
2682         UseRelaxRelocations = true;
2683       } else if (Value == "-mrelax-relocations=no" ||
2684                  Value == "--mrelax-relocations=no") {
2685         UseRelaxRelocations = false;
2686       } else if (Value.startswith("-I")) {
2687         CmdArgs.push_back(Value.data());
2688         // We need to consume the next argument if the current arg is a plain
2689         // -I. The next arg will be the include directory.
2690         if (Value == "-I")
2691           TakeNextArg = true;
2692       } else if (Value.startswith("-gdwarf-")) {
2693         // "-gdwarf-N" options are not cc1as options.
2694         unsigned DwarfVersion = DwarfVersionNum(Value);
2695         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2696           CmdArgs.push_back(Value.data());
2697         } else {
2698           RenderDebugEnablingArgs(Args, CmdArgs,
2699                                   llvm::codegenoptions::DebugInfoConstructor,
2700                                   DwarfVersion, llvm::DebuggerKind::Default);
2701         }
2702       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2703                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2704         // Do nothing, we'll validate it later.
2705       } else if (Value == "-defsym") {
2706           if (A->getNumValues() != 2) {
2707             D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2708             break;
2709           }
2710           const char *S = A->getValue(1);
2711           auto Pair = StringRef(S).split('=');
2712           auto Sym = Pair.first;
2713           auto SVal = Pair.second;
2714 
2715           if (Sym.empty() || SVal.empty()) {
2716             D.Diag(diag::err_drv_defsym_invalid_format) << S;
2717             break;
2718           }
2719           int64_t IVal;
2720           if (SVal.getAsInteger(0, IVal)) {
2721             D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2722             break;
2723           }
2724           CmdArgs.push_back(Value.data());
2725           TakeNextArg = true;
2726       } else if (Value == "-fdebug-compilation-dir") {
2727         CmdArgs.push_back("-fdebug-compilation-dir");
2728         TakeNextArg = true;
2729       } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2730         // The flag is a -Wa / -Xassembler argument and Options doesn't
2731         // parse the argument, so this isn't automatically aliased to
2732         // -fdebug-compilation-dir (without '=') here.
2733         CmdArgs.push_back("-fdebug-compilation-dir");
2734         CmdArgs.push_back(Value.data());
2735       } else if (Value == "--version") {
2736         D.PrintVersion(C, llvm::outs());
2737       } else {
2738         D.Diag(diag::err_drv_unsupported_option_argument)
2739             << A->getSpelling() << Value;
2740       }
2741     }
2742   }
2743   if (ImplicitIt.size())
2744     AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2745   if (!UseRelaxRelocations)
2746     CmdArgs.push_back("-mrelax-relocations=no");
2747   if (UseNoExecStack)
2748     CmdArgs.push_back("-mnoexecstack");
2749   if (MipsTargetFeature != nullptr) {
2750     CmdArgs.push_back("-target-feature");
2751     CmdArgs.push_back(MipsTargetFeature);
2752   }
2753 
2754   // forward -fembed-bitcode to assmebler
2755   if (C.getDriver().embedBitcodeEnabled() ||
2756       C.getDriver().embedBitcodeMarkerOnly())
2757     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2758 
2759   if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2760     CmdArgs.push_back("-as-secure-log-file");
2761     CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2762   }
2763 }
2764 
2765 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2766                                        bool OFastEnabled, const ArgList &Args,
2767                                        ArgStringList &CmdArgs,
2768                                        const JobAction &JA) {
2769   // Handle various floating point optimization flags, mapping them to the
2770   // appropriate LLVM code generation flags. This is complicated by several
2771   // "umbrella" flags, so we do this by stepping through the flags incrementally
2772   // adjusting what we think is enabled/disabled, then at the end setting the
2773   // LLVM flags based on the final state.
2774   bool HonorINFs = true;
2775   bool HonorNaNs = true;
2776   bool ApproxFunc = false;
2777   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2778   bool MathErrno = TC.IsMathErrnoDefault();
2779   bool AssociativeMath = false;
2780   bool ReciprocalMath = false;
2781   bool SignedZeros = true;
2782   bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2783   bool TrappingMathPresent = false; // Is trapping-math in args, and not
2784                                     // overriden by ffp-exception-behavior?
2785   bool RoundingFPMath = false;
2786   bool RoundingMathPresent = false; // Is rounding-math in args?
2787   // -ffp-model values: strict, fast, precise
2788   StringRef FPModel = "";
2789   // -ffp-exception-behavior options: strict, maytrap, ignore
2790   StringRef FPExceptionBehavior = "";
2791   // -ffp-eval-method options: double, extended, source
2792   StringRef FPEvalMethod = "";
2793   const llvm::DenormalMode DefaultDenormalFPMath =
2794       TC.getDefaultDenormalModeForType(Args, JA);
2795   const llvm::DenormalMode DefaultDenormalFP32Math =
2796       TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2797 
2798   llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2799   llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2800   // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2801   // If one wasn't given by the user, don't pass it here.
2802   StringRef FPContract;
2803   StringRef LastSeenFfpContractOption;
2804   bool SeenUnsafeMathModeOption = false;
2805   if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2806       !JA.isOffloading(Action::OFK_HIP))
2807     FPContract = "on";
2808   bool StrictFPModel = false;
2809   StringRef Float16ExcessPrecision = "";
2810   StringRef BFloat16ExcessPrecision = "";
2811 
2812   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2813     CmdArgs.push_back("-mlimit-float-precision");
2814     CmdArgs.push_back(A->getValue());
2815   }
2816 
2817   for (const Arg *A : Args) {
2818     auto optID = A->getOption().getID();
2819     bool PreciseFPModel = false;
2820     switch (optID) {
2821     default:
2822       break;
2823     case options::OPT_ffp_model_EQ: {
2824       // If -ffp-model= is seen, reset to fno-fast-math
2825       HonorINFs = true;
2826       HonorNaNs = true;
2827       ApproxFunc = false;
2828       // Turning *off* -ffast-math restores the toolchain default.
2829       MathErrno = TC.IsMathErrnoDefault();
2830       AssociativeMath = false;
2831       ReciprocalMath = false;
2832       SignedZeros = true;
2833       // -fno_fast_math restores default denormal and fpcontract handling
2834       FPContract = "on";
2835       DenormalFPMath = llvm::DenormalMode::getIEEE();
2836 
2837       // FIXME: The target may have picked a non-IEEE default mode here based on
2838       // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2839       DenormalFP32Math = llvm::DenormalMode::getIEEE();
2840 
2841       StringRef Val = A->getValue();
2842       if (OFastEnabled && !Val.equals("fast")) {
2843           // Only -ffp-model=fast is compatible with OFast, ignore.
2844         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2845           << Args.MakeArgString("-ffp-model=" + Val)
2846           << "-Ofast";
2847         break;
2848       }
2849       StrictFPModel = false;
2850       PreciseFPModel = true;
2851       // ffp-model= is a Driver option, it is entirely rewritten into more
2852       // granular options before being passed into cc1.
2853       // Use the gcc option in the switch below.
2854       if (!FPModel.empty() && !FPModel.equals(Val))
2855         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2856             << Args.MakeArgString("-ffp-model=" + FPModel)
2857             << Args.MakeArgString("-ffp-model=" + Val);
2858       if (Val.equals("fast")) {
2859         optID = options::OPT_ffast_math;
2860         FPModel = Val;
2861         FPContract = "fast";
2862       } else if (Val.equals("precise")) {
2863         optID = options::OPT_ffp_contract;
2864         FPModel = Val;
2865         FPContract = "on";
2866         PreciseFPModel = true;
2867       } else if (Val.equals("strict")) {
2868         StrictFPModel = true;
2869         optID = options::OPT_frounding_math;
2870         FPExceptionBehavior = "strict";
2871         FPModel = Val;
2872         FPContract = "off";
2873         TrappingMath = true;
2874       } else
2875         D.Diag(diag::err_drv_unsupported_option_argument)
2876             << A->getSpelling() << Val;
2877       break;
2878       }
2879     }
2880 
2881     switch (optID) {
2882     // If this isn't an FP option skip the claim below
2883     default: continue;
2884 
2885     // Options controlling individual features
2886     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2887     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2888     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2889     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2890     case options::OPT_fapprox_func:         ApproxFunc = true;        break;
2891     case options::OPT_fno_approx_func:      ApproxFunc = false;       break;
2892     case options::OPT_fmath_errno:          MathErrno = true;         break;
2893     case options::OPT_fno_math_errno:       MathErrno = false;        break;
2894     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2895     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2896     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2897     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2898     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2899     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2900     case options::OPT_ftrapping_math:
2901       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2902           !FPExceptionBehavior.equals("strict"))
2903         // Warn that previous value of option is overridden.
2904         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2905           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2906           << "-ftrapping-math";
2907       TrappingMath = true;
2908       TrappingMathPresent = true;
2909       FPExceptionBehavior = "strict";
2910       break;
2911     case options::OPT_fno_trapping_math:
2912       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2913           !FPExceptionBehavior.equals("ignore"))
2914         // Warn that previous value of option is overridden.
2915         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2916           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2917           << "-fno-trapping-math";
2918       TrappingMath = false;
2919       TrappingMathPresent = true;
2920       FPExceptionBehavior = "ignore";
2921       break;
2922 
2923     case options::OPT_frounding_math:
2924       RoundingFPMath = true;
2925       RoundingMathPresent = true;
2926       break;
2927 
2928     case options::OPT_fno_rounding_math:
2929       RoundingFPMath = false;
2930       RoundingMathPresent = false;
2931       break;
2932 
2933     case options::OPT_fdenormal_fp_math_EQ:
2934       DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2935       DenormalFP32Math = DenormalFPMath;
2936       if (!DenormalFPMath.isValid()) {
2937         D.Diag(diag::err_drv_invalid_value)
2938             << A->getAsString(Args) << A->getValue();
2939       }
2940       break;
2941 
2942     case options::OPT_fdenormal_fp_math_f32_EQ:
2943       DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2944       if (!DenormalFP32Math.isValid()) {
2945         D.Diag(diag::err_drv_invalid_value)
2946             << A->getAsString(Args) << A->getValue();
2947       }
2948       break;
2949 
2950     // Validate and pass through -ffp-contract option.
2951     case options::OPT_ffp_contract: {
2952       StringRef Val = A->getValue();
2953       if (PreciseFPModel) {
2954         // -ffp-model=precise enables ffp-contract=on.
2955         // -ffp-model=precise sets PreciseFPModel to on and Val to
2956         // "precise". FPContract is set.
2957         ;
2958       } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off")) {
2959         FPContract = Val;
2960         LastSeenFfpContractOption = Val;
2961       } else
2962         D.Diag(diag::err_drv_unsupported_option_argument)
2963             << A->getSpelling() << Val;
2964       break;
2965     }
2966 
2967     // Validate and pass through -ffp-model option.
2968     case options::OPT_ffp_model_EQ:
2969       // This should only occur in the error case
2970       // since the optID has been replaced by a more granular
2971       // floating point option.
2972       break;
2973 
2974     // Validate and pass through -ffp-exception-behavior option.
2975     case options::OPT_ffp_exception_behavior_EQ: {
2976       StringRef Val = A->getValue();
2977       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2978           !FPExceptionBehavior.equals(Val))
2979         // Warn that previous value of option is overridden.
2980         D.Diag(clang::diag::warn_drv_overriding_flag_option)
2981           << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2982           << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2983       TrappingMath = TrappingMathPresent = false;
2984       if (Val.equals("ignore") || Val.equals("maytrap"))
2985         FPExceptionBehavior = Val;
2986       else if (Val.equals("strict")) {
2987         FPExceptionBehavior = Val;
2988         TrappingMath = TrappingMathPresent = true;
2989       } else
2990         D.Diag(diag::err_drv_unsupported_option_argument)
2991             << A->getSpelling() << Val;
2992       break;
2993     }
2994 
2995     // Validate and pass through -ffp-eval-method option.
2996     case options::OPT_ffp_eval_method_EQ: {
2997       StringRef Val = A->getValue();
2998       if (Val.equals("double") || Val.equals("extended") ||
2999           Val.equals("source"))
3000         FPEvalMethod = Val;
3001       else
3002         D.Diag(diag::err_drv_unsupported_option_argument)
3003             << A->getSpelling() << Val;
3004       break;
3005     }
3006 
3007     case options::OPT_fexcess_precision_EQ: {
3008       StringRef Val = A->getValue();
3009       const llvm::Triple::ArchType Arch = TC.getArch();
3010       if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3011         if (Val.equals("standard") || Val.equals("fast"))
3012           Float16ExcessPrecision = Val;
3013         // To make it GCC compatible, allow the value of "16" which
3014         // means disable excess precision, the same meaning than clang's
3015         // equivalent value "none".
3016         else if (Val.equals("16"))
3017           Float16ExcessPrecision = "none";
3018         else
3019           D.Diag(diag::err_drv_unsupported_option_argument)
3020               << A->getSpelling() << Val;
3021       } else {
3022         if (!(Val.equals("standard") || Val.equals("fast")))
3023           D.Diag(diag::err_drv_unsupported_option_argument)
3024               << A->getSpelling() << Val;
3025       }
3026       BFloat16ExcessPrecision = Float16ExcessPrecision;
3027       break;
3028     }
3029     case options::OPT_ffinite_math_only:
3030       HonorINFs = false;
3031       HonorNaNs = false;
3032       break;
3033     case options::OPT_fno_finite_math_only:
3034       HonorINFs = true;
3035       HonorNaNs = true;
3036       break;
3037 
3038     case options::OPT_funsafe_math_optimizations:
3039       AssociativeMath = true;
3040       ReciprocalMath = true;
3041       SignedZeros = false;
3042       ApproxFunc = true;
3043       TrappingMath = false;
3044       FPExceptionBehavior = "";
3045       FPContract = "fast";
3046       SeenUnsafeMathModeOption = true;
3047       break;
3048     case options::OPT_fno_unsafe_math_optimizations:
3049       AssociativeMath = false;
3050       ReciprocalMath = false;
3051       SignedZeros = true;
3052       ApproxFunc = false;
3053       TrappingMath = true;
3054       FPExceptionBehavior = "strict";
3055 
3056       // The target may have opted to flush by default, so force IEEE.
3057       DenormalFPMath = llvm::DenormalMode::getIEEE();
3058       DenormalFP32Math = llvm::DenormalMode::getIEEE();
3059       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3060           !JA.isOffloading(Action::OFK_HIP)) {
3061         if (LastSeenFfpContractOption != "") {
3062           FPContract = LastSeenFfpContractOption;
3063         } else if (SeenUnsafeMathModeOption)
3064           FPContract = "on";
3065       }
3066       break;
3067 
3068     case options::OPT_Ofast:
3069       // If -Ofast is the optimization level, then -ffast-math should be enabled
3070       if (!OFastEnabled)
3071         continue;
3072       [[fallthrough]];
3073     case options::OPT_ffast_math:
3074       HonorINFs = false;
3075       HonorNaNs = false;
3076       MathErrno = false;
3077       AssociativeMath = true;
3078       ReciprocalMath = true;
3079       ApproxFunc = true;
3080       SignedZeros = false;
3081       TrappingMath = false;
3082       RoundingFPMath = false;
3083       FPExceptionBehavior = "";
3084       // If fast-math is set then set the fp-contract mode to fast.
3085       FPContract = "fast";
3086       SeenUnsafeMathModeOption = true;
3087       break;
3088     case options::OPT_fno_fast_math:
3089       HonorINFs = true;
3090       HonorNaNs = true;
3091       // Turning on -ffast-math (with either flag) removes the need for
3092       // MathErrno. However, turning *off* -ffast-math merely restores the
3093       // toolchain default (which may be false).
3094       MathErrno = TC.IsMathErrnoDefault();
3095       AssociativeMath = false;
3096       ReciprocalMath = false;
3097       ApproxFunc = false;
3098       SignedZeros = true;
3099       // -fno_fast_math restores default denormal and fpcontract handling
3100       DenormalFPMath = DefaultDenormalFPMath;
3101       DenormalFP32Math = llvm::DenormalMode::getIEEE();
3102       if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3103           !JA.isOffloading(Action::OFK_HIP)) {
3104         if (LastSeenFfpContractOption != "") {
3105           FPContract = LastSeenFfpContractOption;
3106         } else if (SeenUnsafeMathModeOption)
3107           FPContract = "on";
3108       }
3109       break;
3110     }
3111     if (StrictFPModel) {
3112       // If -ffp-model=strict has been specified on command line but
3113       // subsequent options conflict then emit warning diagnostic.
3114       if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3115           SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3116           DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3117           DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3118           FPContract.equals("off"))
3119         // OK: Current Arg doesn't conflict with -ffp-model=strict
3120         ;
3121       else {
3122         StrictFPModel = false;
3123         FPModel = "";
3124         auto RHS = (A->getNumValues() == 0)
3125                        ? A->getSpelling()
3126                        : Args.MakeArgString(A->getSpelling() + A->getValue());
3127         if (RHS != "-ffp-model=strict")
3128           D.Diag(clang::diag::warn_drv_overriding_flag_option)
3129               << "-ffp-model=strict" << RHS;
3130       }
3131     }
3132 
3133     // If we handled this option claim it
3134     A->claim();
3135   }
3136 
3137   if (!HonorINFs)
3138     CmdArgs.push_back("-menable-no-infs");
3139 
3140   if (!HonorNaNs)
3141     CmdArgs.push_back("-menable-no-nans");
3142 
3143   if (ApproxFunc)
3144     CmdArgs.push_back("-fapprox-func");
3145 
3146   if (MathErrno)
3147     CmdArgs.push_back("-fmath-errno");
3148 
3149  if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3150      !TrappingMath)
3151     CmdArgs.push_back("-funsafe-math-optimizations");
3152 
3153   if (!SignedZeros)
3154     CmdArgs.push_back("-fno-signed-zeros");
3155 
3156   if (AssociativeMath && !SignedZeros && !TrappingMath)
3157     CmdArgs.push_back("-mreassociate");
3158 
3159   if (ReciprocalMath)
3160     CmdArgs.push_back("-freciprocal-math");
3161 
3162   if (TrappingMath) {
3163     // FP Exception Behavior is also set to strict
3164     assert(FPExceptionBehavior.equals("strict"));
3165   }
3166 
3167   // The default is IEEE.
3168   if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3169     llvm::SmallString<64> DenormFlag;
3170     llvm::raw_svector_ostream ArgStr(DenormFlag);
3171     ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3172     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3173   }
3174 
3175   // Add f32 specific denormal mode flag if it's different.
3176   if (DenormalFP32Math != DenormalFPMath) {
3177     llvm::SmallString<64> DenormFlag;
3178     llvm::raw_svector_ostream ArgStr(DenormFlag);
3179     ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3180     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3181   }
3182 
3183   if (!FPContract.empty())
3184     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3185 
3186   if (!RoundingFPMath)
3187     CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3188 
3189   if (RoundingFPMath && RoundingMathPresent)
3190     CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3191 
3192   if (!FPExceptionBehavior.empty())
3193     CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3194                       FPExceptionBehavior));
3195 
3196   if (!FPEvalMethod.empty())
3197     CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3198 
3199   if (!Float16ExcessPrecision.empty())
3200     CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3201                                          Float16ExcessPrecision));
3202   if (!BFloat16ExcessPrecision.empty())
3203     CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3204                                          BFloat16ExcessPrecision));
3205 
3206   ParseMRecip(D, Args, CmdArgs);
3207 
3208   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3209   // individual features enabled by -ffast-math instead of the option itself as
3210   // that's consistent with gcc's behaviour.
3211   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3212       ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3213     CmdArgs.push_back("-ffast-math");
3214     if (FPModel.equals("fast")) {
3215       if (FPContract.equals("fast"))
3216         // All set, do nothing.
3217         ;
3218       else if (FPContract.empty())
3219         // Enable -ffp-contract=fast
3220         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3221       else
3222         D.Diag(clang::diag::warn_drv_overriding_flag_option)
3223           << "-ffp-model=fast"
3224           << Args.MakeArgString("-ffp-contract=" + FPContract);
3225     }
3226   }
3227 
3228   // Handle __FINITE_MATH_ONLY__ similarly.
3229   if (!HonorINFs && !HonorNaNs)
3230     CmdArgs.push_back("-ffinite-math-only");
3231 
3232   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3233     CmdArgs.push_back("-mfpmath");
3234     CmdArgs.push_back(A->getValue());
3235   }
3236 
3237   // Disable a codegen optimization for floating-point casts.
3238   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3239                    options::OPT_fstrict_float_cast_overflow, false))
3240     CmdArgs.push_back("-fno-strict-float-cast-overflow");
3241 }
3242 
3243 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3244                                   const llvm::Triple &Triple,
3245                                   const InputInfo &Input) {
3246   // Add default argument set.
3247   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3248     CmdArgs.push_back("-analyzer-checker=core");
3249     CmdArgs.push_back("-analyzer-checker=apiModeling");
3250 
3251     if (!Triple.isWindowsMSVCEnvironment()) {
3252       CmdArgs.push_back("-analyzer-checker=unix");
3253     } else {
3254       // Enable "unix" checkers that also work on Windows.
3255       CmdArgs.push_back("-analyzer-checker=unix.API");
3256       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3257       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3258       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3259       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3260       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3261     }
3262 
3263     // Disable some unix checkers for PS4/PS5.
3264     if (Triple.isPS()) {
3265       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3266       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3267     }
3268 
3269     if (Triple.isOSDarwin()) {
3270       CmdArgs.push_back("-analyzer-checker=osx");
3271       CmdArgs.push_back(
3272           "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3273     }
3274     else if (Triple.isOSFuchsia())
3275       CmdArgs.push_back("-analyzer-checker=fuchsia");
3276 
3277     CmdArgs.push_back("-analyzer-checker=deadcode");
3278 
3279     if (types::isCXX(Input.getType()))
3280       CmdArgs.push_back("-analyzer-checker=cplusplus");
3281 
3282     if (!Triple.isPS()) {
3283       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3284       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3285       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3286       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3287       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3288       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3289     }
3290 
3291     // Default nullability checks.
3292     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3293     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3294   }
3295 
3296   // Set the output format. The default is plist, for (lame) historical reasons.
3297   CmdArgs.push_back("-analyzer-output");
3298   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3299     CmdArgs.push_back(A->getValue());
3300   else
3301     CmdArgs.push_back("plist");
3302 
3303   // Disable the presentation of standard compiler warnings when using
3304   // --analyze.  We only want to show static analyzer diagnostics or frontend
3305   // errors.
3306   CmdArgs.push_back("-w");
3307 
3308   // Add -Xanalyzer arguments when running as analyzer.
3309   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3310 }
3311 
3312 static bool isValidSymbolName(StringRef S) {
3313   if (S.empty())
3314     return false;
3315 
3316   if (std::isdigit(S[0]))
3317     return false;
3318 
3319   return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3320 }
3321 
3322 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3323                              const ArgList &Args, ArgStringList &CmdArgs,
3324                              bool KernelOrKext) {
3325   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3326 
3327   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3328   // doesn't even have a stack!
3329   if (EffectiveTriple.isNVPTX())
3330     return;
3331 
3332   // -stack-protector=0 is default.
3333   LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3334   LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3335       TC.GetDefaultStackProtectorLevel(KernelOrKext);
3336 
3337   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3338                                options::OPT_fstack_protector_all,
3339                                options::OPT_fstack_protector_strong,
3340                                options::OPT_fstack_protector)) {
3341     if (A->getOption().matches(options::OPT_fstack_protector))
3342       StackProtectorLevel =
3343           std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3344     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3345       StackProtectorLevel = LangOptions::SSPStrong;
3346     else if (A->getOption().matches(options::OPT_fstack_protector_all))
3347       StackProtectorLevel = LangOptions::SSPReq;
3348 
3349     if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3350       D.Diag(diag::warn_drv_unsupported_option_for_target)
3351           << A->getSpelling() << EffectiveTriple.getTriple();
3352       StackProtectorLevel = DefaultStackProtectorLevel;
3353     }
3354   } else {
3355     StackProtectorLevel = DefaultStackProtectorLevel;
3356   }
3357 
3358   if (StackProtectorLevel) {
3359     CmdArgs.push_back("-stack-protector");
3360     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3361   }
3362 
3363   // --param ssp-buffer-size=
3364   for (const Arg *A : Args.filtered(options::OPT__param)) {
3365     StringRef Str(A->getValue());
3366     if (Str.startswith("ssp-buffer-size=")) {
3367       if (StackProtectorLevel) {
3368         CmdArgs.push_back("-stack-protector-buffer-size");
3369         // FIXME: Verify the argument is a valid integer.
3370         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3371       }
3372       A->claim();
3373     }
3374   }
3375 
3376   const std::string &TripleStr = EffectiveTriple.getTriple();
3377   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3378     StringRef Value = A->getValue();
3379     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3380         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3381       D.Diag(diag::err_drv_unsupported_opt_for_target)
3382           << A->getAsString(Args) << TripleStr;
3383     if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3384          EffectiveTriple.isThumb()) &&
3385         Value != "tls" && Value != "global") {
3386       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3387           << A->getOption().getName() << Value << "tls global";
3388       return;
3389     }
3390     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3391         Value == "tls") {
3392       if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3393         D.Diag(diag::err_drv_ssp_missing_offset_argument)
3394             << A->getAsString(Args);
3395         return;
3396       }
3397       // Check whether the target subarch supports the hardware TLS register
3398       if (!arm::isHardTPSupported(EffectiveTriple)) {
3399         D.Diag(diag::err_target_unsupported_tp_hard)
3400             << EffectiveTriple.getArchName();
3401         return;
3402       }
3403       // Check whether the user asked for something other than -mtp=cp15
3404       if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3405         StringRef Value = A->getValue();
3406         if (Value != "cp15") {
3407           D.Diag(diag::err_drv_argument_not_allowed_with)
3408               << A->getAsString(Args) << "-mstack-protector-guard=tls";
3409           return;
3410         }
3411       }
3412       CmdArgs.push_back("-target-feature");
3413       CmdArgs.push_back("+read-tp-tpidruro");
3414     }
3415     if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3416       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3417           << A->getOption().getName() << Value << "sysreg global";
3418       return;
3419     }
3420     A->render(Args, CmdArgs);
3421   }
3422 
3423   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3424     StringRef Value = A->getValue();
3425     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3426         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3427       D.Diag(diag::err_drv_unsupported_opt_for_target)
3428           << A->getAsString(Args) << TripleStr;
3429     int Offset;
3430     if (Value.getAsInteger(10, Offset)) {
3431       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3432       return;
3433     }
3434     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3435         (Offset < 0 || Offset > 0xfffff)) {
3436       D.Diag(diag::err_drv_invalid_int_value)
3437           << A->getOption().getName() << Value;
3438       return;
3439     }
3440     A->render(Args, CmdArgs);
3441   }
3442 
3443   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3444     StringRef Value = A->getValue();
3445     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3446       D.Diag(diag::err_drv_unsupported_opt_for_target)
3447           << A->getAsString(Args) << TripleStr;
3448     if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3449       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3450           << A->getOption().getName() << Value << "fs gs";
3451       return;
3452     }
3453     if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3454       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3455       return;
3456     }
3457     A->render(Args, CmdArgs);
3458   }
3459 
3460   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3461     StringRef Value = A->getValue();
3462     if (!isValidSymbolName(Value)) {
3463       D.Diag(diag::err_drv_argument_only_allowed_with)
3464           << A->getOption().getName() << "legal symbol name";
3465       return;
3466     }
3467     A->render(Args, CmdArgs);
3468   }
3469 }
3470 
3471 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3472                              ArgStringList &CmdArgs) {
3473   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3474 
3475   if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3476     return;
3477 
3478   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3479       !EffectiveTriple.isPPC64())
3480     return;
3481 
3482   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3483                     options::OPT_fno_stack_clash_protection);
3484 }
3485 
3486 static void RenderTrivialAutoVarInitOptions(const Driver &D,
3487                                             const ToolChain &TC,
3488                                             const ArgList &Args,
3489                                             ArgStringList &CmdArgs) {
3490   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3491   StringRef TrivialAutoVarInit = "";
3492 
3493   for (const Arg *A : Args) {
3494     switch (A->getOption().getID()) {
3495     default:
3496       continue;
3497     case options::OPT_ftrivial_auto_var_init: {
3498       A->claim();
3499       StringRef Val = A->getValue();
3500       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3501         TrivialAutoVarInit = Val;
3502       else
3503         D.Diag(diag::err_drv_unsupported_option_argument)
3504             << A->getSpelling() << Val;
3505       break;
3506     }
3507     }
3508   }
3509 
3510   if (TrivialAutoVarInit.empty())
3511     switch (DefaultTrivialAutoVarInit) {
3512     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3513       break;
3514     case LangOptions::TrivialAutoVarInitKind::Pattern:
3515       TrivialAutoVarInit = "pattern";
3516       break;
3517     case LangOptions::TrivialAutoVarInitKind::Zero:
3518       TrivialAutoVarInit = "zero";
3519       break;
3520     }
3521 
3522   if (!TrivialAutoVarInit.empty()) {
3523     CmdArgs.push_back(
3524         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3525   }
3526 
3527   if (Arg *A =
3528           Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3529     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3530         StringRef(
3531             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3532             "uninitialized")
3533       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3534     A->claim();
3535     StringRef Val = A->getValue();
3536     if (std::stoi(Val.str()) <= 0)
3537       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3538     CmdArgs.push_back(
3539         Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3540   }
3541 }
3542 
3543 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3544                                 types::ID InputType) {
3545   // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3546   // for denormal flushing handling based on the target.
3547   const unsigned ForwardedArguments[] = {
3548       options::OPT_cl_opt_disable,
3549       options::OPT_cl_strict_aliasing,
3550       options::OPT_cl_single_precision_constant,
3551       options::OPT_cl_finite_math_only,
3552       options::OPT_cl_kernel_arg_info,
3553       options::OPT_cl_unsafe_math_optimizations,
3554       options::OPT_cl_fast_relaxed_math,
3555       options::OPT_cl_mad_enable,
3556       options::OPT_cl_no_signed_zeros,
3557       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3558       options::OPT_cl_uniform_work_group_size
3559   };
3560 
3561   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3562     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3563     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3564   } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3565     std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3566     CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3567   }
3568 
3569   for (const auto &Arg : ForwardedArguments)
3570     if (const auto *A = Args.getLastArg(Arg))
3571       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3572 
3573   // Only add the default headers if we are compiling OpenCL sources.
3574   if ((types::isOpenCL(InputType) ||
3575        (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3576       !Args.hasArg(options::OPT_cl_no_stdinc)) {
3577     CmdArgs.push_back("-finclude-default-header");
3578     CmdArgs.push_back("-fdeclare-opencl-builtins");
3579   }
3580 }
3581 
3582 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3583                               types::ID InputType) {
3584   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3585                                          options::OPT_D,
3586                                          options::OPT_I,
3587                                          options::OPT_S,
3588                                          options::OPT_O,
3589                                          options::OPT_emit_llvm,
3590                                          options::OPT_emit_obj,
3591                                          options::OPT_disable_llvm_passes,
3592                                          options::OPT_fnative_half_type,
3593                                          options::OPT_hlsl_entrypoint};
3594   if (!types::isHLSL(InputType))
3595     return;
3596   for (const auto &Arg : ForwardedArguments)
3597     if (const auto *A = Args.getLastArg(Arg))
3598       A->renderAsInput(Args, CmdArgs);
3599   // Add the default headers if dxc_no_stdinc is not set.
3600   if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3601       !Args.hasArg(options::OPT_nostdinc))
3602     CmdArgs.push_back("-finclude-default-header");
3603 }
3604 
3605 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3606                                         ArgStringList &CmdArgs) {
3607   bool ARCMTEnabled = false;
3608   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3609     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3610                                        options::OPT_ccc_arcmt_modify,
3611                                        options::OPT_ccc_arcmt_migrate)) {
3612       ARCMTEnabled = true;
3613       switch (A->getOption().getID()) {
3614       default: llvm_unreachable("missed a case");
3615       case options::OPT_ccc_arcmt_check:
3616         CmdArgs.push_back("-arcmt-action=check");
3617         break;
3618       case options::OPT_ccc_arcmt_modify:
3619         CmdArgs.push_back("-arcmt-action=modify");
3620         break;
3621       case options::OPT_ccc_arcmt_migrate:
3622         CmdArgs.push_back("-arcmt-action=migrate");
3623         CmdArgs.push_back("-mt-migrate-directory");
3624         CmdArgs.push_back(A->getValue());
3625 
3626         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3627         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3628         break;
3629       }
3630     }
3631   } else {
3632     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3633     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3634     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3635   }
3636 
3637   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3638     if (ARCMTEnabled)
3639       D.Diag(diag::err_drv_argument_not_allowed_with)
3640           << A->getAsString(Args) << "-ccc-arcmt-migrate";
3641 
3642     CmdArgs.push_back("-mt-migrate-directory");
3643     CmdArgs.push_back(A->getValue());
3644 
3645     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3646                      options::OPT_objcmt_migrate_subscripting,
3647                      options::OPT_objcmt_migrate_property)) {
3648       // None specified, means enable them all.
3649       CmdArgs.push_back("-objcmt-migrate-literals");
3650       CmdArgs.push_back("-objcmt-migrate-subscripting");
3651       CmdArgs.push_back("-objcmt-migrate-property");
3652     } else {
3653       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3654       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3655       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3656     }
3657   } else {
3658     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3659     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3660     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3661     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3662     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3663     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3664     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3665     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3666     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3667     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3668     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3669     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3670     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3671     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3672     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3673     Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3674   }
3675 }
3676 
3677 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3678                                  const ArgList &Args, ArgStringList &CmdArgs) {
3679   // -fbuiltin is default unless -mkernel is used.
3680   bool UseBuiltins =
3681       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3682                    !Args.hasArg(options::OPT_mkernel));
3683   if (!UseBuiltins)
3684     CmdArgs.push_back("-fno-builtin");
3685 
3686   // -ffreestanding implies -fno-builtin.
3687   if (Args.hasArg(options::OPT_ffreestanding))
3688     UseBuiltins = false;
3689 
3690   // Process the -fno-builtin-* options.
3691   for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3692     A->claim();
3693 
3694     // If -fno-builtin is specified, then there's no need to pass the option to
3695     // the frontend.
3696     if (UseBuiltins)
3697       A->render(Args, CmdArgs);
3698   }
3699 
3700   // le32-specific flags:
3701   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3702   //                     by default.
3703   if (TC.getArch() == llvm::Triple::le32)
3704     CmdArgs.push_back("-fno-math-builtin");
3705 }
3706 
3707 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3708   if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3709     Twine Path{Str};
3710     Path.toVector(Result);
3711     return Path.getSingleStringRef() != "";
3712   }
3713   if (llvm::sys::path::cache_directory(Result)) {
3714     llvm::sys::path::append(Result, "clang");
3715     llvm::sys::path::append(Result, "ModuleCache");
3716     return true;
3717   }
3718   return false;
3719 }
3720 
3721 static bool RenderModulesOptions(Compilation &C, const Driver &D,
3722                                  const ArgList &Args, const InputInfo &Input,
3723                                  const InputInfo &Output, const Arg *Std,
3724                                  ArgStringList &CmdArgs) {
3725   bool IsCXX = types::isCXX(Input.getType());
3726   // FIXME: Find a better way to determine whether the input has standard c++
3727   // modules support by default.
3728   bool HaveStdCXXModules =
3729       IsCXX && Std &&
3730       (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
3731        Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
3732        Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
3733        Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
3734        Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
3735        Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
3736        Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
3737   bool HaveModules = HaveStdCXXModules;
3738 
3739   // -fmodules enables the use of precompiled modules (off by default).
3740   // Users can pass -fno-cxx-modules to turn off modules support for
3741   // C++/Objective-C++ programs.
3742   bool HaveClangModules = false;
3743   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3744     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3745                                      options::OPT_fno_cxx_modules, true);
3746     if (AllowedInCXX || !IsCXX) {
3747       CmdArgs.push_back("-fmodules");
3748       HaveClangModules = true;
3749     }
3750   }
3751 
3752   HaveModules |= HaveClangModules;
3753 
3754   // -fmodule-maps enables implicit reading of module map files. By default,
3755   // this is enabled if we are using Clang's flavor of precompiled modules.
3756   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3757                    options::OPT_fno_implicit_module_maps, HaveClangModules))
3758     CmdArgs.push_back("-fimplicit-module-maps");
3759 
3760   // -fmodules-decluse checks that modules used are declared so (off by default)
3761   Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3762                     options::OPT_fno_modules_decluse);
3763 
3764   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3765   // all #included headers are part of modules.
3766   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3767                    options::OPT_fno_modules_strict_decluse, false))
3768     CmdArgs.push_back("-fmodules-strict-decluse");
3769 
3770   // -fno-implicit-modules turns off implicitly compiling modules on demand.
3771   bool ImplicitModules = false;
3772   if (!Args.hasFlag(options::OPT_fimplicit_modules,
3773                     options::OPT_fno_implicit_modules, HaveClangModules)) {
3774     if (HaveModules)
3775       CmdArgs.push_back("-fno-implicit-modules");
3776   } else if (HaveModules) {
3777     ImplicitModules = true;
3778     // -fmodule-cache-path specifies where our implicitly-built module files
3779     // should be written.
3780     SmallString<128> Path;
3781     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3782       Path = A->getValue();
3783 
3784     bool HasPath = true;
3785     if (C.isForDiagnostics()) {
3786       // When generating crash reports, we want to emit the modules along with
3787       // the reproduction sources, so we ignore any provided module path.
3788       Path = Output.getFilename();
3789       llvm::sys::path::replace_extension(Path, ".cache");
3790       llvm::sys::path::append(Path, "modules");
3791     } else if (Path.empty()) {
3792       // No module path was provided: use the default.
3793       HasPath = Driver::getDefaultModuleCachePath(Path);
3794     }
3795 
3796     // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3797     // That being said, that failure is unlikely and not caching is harmless.
3798     if (HasPath) {
3799       const char Arg[] = "-fmodules-cache-path=";
3800       Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3801       CmdArgs.push_back(Args.MakeArgString(Path));
3802     }
3803   }
3804 
3805   if (HaveModules) {
3806     if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3807                      options::OPT_fno_prebuilt_implicit_modules, false))
3808       CmdArgs.push_back("-fprebuilt-implicit-modules");
3809     if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3810                      options::OPT_fno_modules_validate_input_files_content,
3811                      false))
3812       CmdArgs.push_back("-fvalidate-ast-input-files-content");
3813   }
3814 
3815   // -fmodule-name specifies the module that is currently being built (or
3816   // used for header checking by -fmodule-maps).
3817   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3818 
3819   // -fmodule-map-file can be used to specify files containing module
3820   // definitions.
3821   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3822 
3823   // -fbuiltin-module-map can be used to load the clang
3824   // builtin headers modulemap file.
3825   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3826     SmallString<128> BuiltinModuleMap(D.ResourceDir);
3827     llvm::sys::path::append(BuiltinModuleMap, "include");
3828     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3829     if (llvm::sys::fs::exists(BuiltinModuleMap))
3830       CmdArgs.push_back(
3831           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3832   }
3833 
3834   // The -fmodule-file=<name>=<file> form specifies the mapping of module
3835   // names to precompiled module files (the module is loaded only if used).
3836   // The -fmodule-file=<file> form can be used to unconditionally load
3837   // precompiled module files (whether used or not).
3838   if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3839     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3840 
3841     // -fprebuilt-module-path specifies where to load the prebuilt module files.
3842     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3843       CmdArgs.push_back(Args.MakeArgString(
3844           std::string("-fprebuilt-module-path=") + A->getValue()));
3845       A->claim();
3846     }
3847   } else
3848     Args.ClaimAllArgs(options::OPT_fmodule_file);
3849 
3850   // When building modules and generating crashdumps, we need to dump a module
3851   // dependency VFS alongside the output.
3852   if (HaveClangModules && C.isForDiagnostics()) {
3853     SmallString<128> VFSDir(Output.getFilename());
3854     llvm::sys::path::replace_extension(VFSDir, ".cache");
3855     // Add the cache directory as a temp so the crash diagnostics pick it up.
3856     C.addTempFile(Args.MakeArgString(VFSDir));
3857 
3858     llvm::sys::path::append(VFSDir, "vfs");
3859     CmdArgs.push_back("-module-dependency-dir");
3860     CmdArgs.push_back(Args.MakeArgString(VFSDir));
3861   }
3862 
3863   if (HaveClangModules)
3864     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3865 
3866   // Pass through all -fmodules-ignore-macro arguments.
3867   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3868   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3869   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3870 
3871   if (HaveClangModules) {
3872     Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3873 
3874     if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3875       if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3876         D.Diag(diag::err_drv_argument_not_allowed_with)
3877             << A->getAsString(Args) << "-fbuild-session-timestamp";
3878 
3879       llvm::sys::fs::file_status Status;
3880       if (llvm::sys::fs::status(A->getValue(), Status))
3881         D.Diag(diag::err_drv_no_such_file) << A->getValue();
3882       CmdArgs.push_back(Args.MakeArgString(
3883           "-fbuild-session-timestamp=" +
3884           Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3885                     Status.getLastModificationTime().time_since_epoch())
3886                     .count())));
3887     }
3888 
3889     if (Args.getLastArg(
3890             options::OPT_fmodules_validate_once_per_build_session)) {
3891       if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3892                            options::OPT_fbuild_session_file))
3893         D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3894 
3895       Args.AddLastArg(CmdArgs,
3896                       options::OPT_fmodules_validate_once_per_build_session);
3897     }
3898 
3899     if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3900                      options::OPT_fno_modules_validate_system_headers,
3901                      ImplicitModules))
3902       CmdArgs.push_back("-fmodules-validate-system-headers");
3903 
3904     Args.AddLastArg(CmdArgs,
3905                     options::OPT_fmodules_disable_diagnostic_validation);
3906   } else {
3907     Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3908     Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3909     Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3910     Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3911     Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3912     Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3913   }
3914 
3915   // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
3916   Args.ClaimAllArgs(options::OPT_fmodule_output);
3917   Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
3918 
3919   return HaveModules;
3920 }
3921 
3922 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3923                                    ArgStringList &CmdArgs) {
3924   // -fsigned-char is default.
3925   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3926                                      options::OPT_fno_signed_char,
3927                                      options::OPT_funsigned_char,
3928                                      options::OPT_fno_unsigned_char)) {
3929     if (A->getOption().matches(options::OPT_funsigned_char) ||
3930         A->getOption().matches(options::OPT_fno_signed_char)) {
3931       CmdArgs.push_back("-fno-signed-char");
3932     }
3933   } else if (!isSignedCharDefault(T)) {
3934     CmdArgs.push_back("-fno-signed-char");
3935   }
3936 
3937   // The default depends on the language standard.
3938   Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3939 
3940   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3941                                      options::OPT_fno_short_wchar)) {
3942     if (A->getOption().matches(options::OPT_fshort_wchar)) {
3943       CmdArgs.push_back("-fwchar-type=short");
3944       CmdArgs.push_back("-fno-signed-wchar");
3945     } else {
3946       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3947       CmdArgs.push_back("-fwchar-type=int");
3948       if (T.isOSzOS() ||
3949           (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3950         CmdArgs.push_back("-fno-signed-wchar");
3951       else
3952         CmdArgs.push_back("-fsigned-wchar");
3953     }
3954   } else if (T.isOSzOS())
3955     CmdArgs.push_back("-fno-signed-wchar");
3956 }
3957 
3958 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3959                               const llvm::Triple &T, const ArgList &Args,
3960                               ObjCRuntime &Runtime, bool InferCovariantReturns,
3961                               const InputInfo &Input, ArgStringList &CmdArgs) {
3962   const llvm::Triple::ArchType Arch = TC.getArch();
3963 
3964   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3965   // is the default. Except for deployment target of 10.5, next runtime is
3966   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3967   if (Runtime.isNonFragile()) {
3968     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3969                       options::OPT_fno_objc_legacy_dispatch,
3970                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3971       if (TC.UseObjCMixedDispatch())
3972         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3973       else
3974         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3975     }
3976   }
3977 
3978   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3979   // to do Array/Dictionary subscripting by default.
3980   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3981       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3982     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3983 
3984   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3985   // NOTE: This logic is duplicated in ToolChains.cpp.
3986   if (isObjCAutoRefCount(Args)) {
3987     TC.CheckObjCARC();
3988 
3989     CmdArgs.push_back("-fobjc-arc");
3990 
3991     // FIXME: It seems like this entire block, and several around it should be
3992     // wrapped in isObjC, but for now we just use it here as this is where it
3993     // was being used previously.
3994     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3995       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3996         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3997       else
3998         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3999     }
4000 
4001     // Allow the user to enable full exceptions code emission.
4002     // We default off for Objective-C, on for Objective-C++.
4003     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4004                      options::OPT_fno_objc_arc_exceptions,
4005                      /*Default=*/types::isCXX(Input.getType())))
4006       CmdArgs.push_back("-fobjc-arc-exceptions");
4007   }
4008 
4009   // Silence warning for full exception code emission options when explicitly
4010   // set to use no ARC.
4011   if (Args.hasArg(options::OPT_fno_objc_arc)) {
4012     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4013     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4014   }
4015 
4016   // Allow the user to control whether messages can be converted to runtime
4017   // functions.
4018   if (types::isObjC(Input.getType())) {
4019     auto *Arg = Args.getLastArg(
4020         options::OPT_fobjc_convert_messages_to_runtime_calls,
4021         options::OPT_fno_objc_convert_messages_to_runtime_calls);
4022     if (Arg &&
4023         Arg->getOption().matches(
4024             options::OPT_fno_objc_convert_messages_to_runtime_calls))
4025       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4026   }
4027 
4028   // -fobjc-infer-related-result-type is the default, except in the Objective-C
4029   // rewriter.
4030   if (InferCovariantReturns)
4031     CmdArgs.push_back("-fno-objc-infer-related-result-type");
4032 
4033   // Pass down -fobjc-weak or -fno-objc-weak if present.
4034   if (types::isObjC(Input.getType())) {
4035     auto WeakArg =
4036         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4037     if (!WeakArg) {
4038       // nothing to do
4039     } else if (!Runtime.allowsWeak()) {
4040       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4041         D.Diag(diag::err_objc_weak_unsupported);
4042     } else {
4043       WeakArg->render(Args, CmdArgs);
4044     }
4045   }
4046 
4047   if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4048     CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4049 }
4050 
4051 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4052                                      ArgStringList &CmdArgs) {
4053   bool CaretDefault = true;
4054   bool ColumnDefault = true;
4055 
4056   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4057                                      options::OPT__SLASH_diagnostics_column,
4058                                      options::OPT__SLASH_diagnostics_caret)) {
4059     switch (A->getOption().getID()) {
4060     case options::OPT__SLASH_diagnostics_caret:
4061       CaretDefault = true;
4062       ColumnDefault = true;
4063       break;
4064     case options::OPT__SLASH_diagnostics_column:
4065       CaretDefault = false;
4066       ColumnDefault = true;
4067       break;
4068     case options::OPT__SLASH_diagnostics_classic:
4069       CaretDefault = false;
4070       ColumnDefault = false;
4071       break;
4072     }
4073   }
4074 
4075   // -fcaret-diagnostics is default.
4076   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4077                     options::OPT_fno_caret_diagnostics, CaretDefault))
4078     CmdArgs.push_back("-fno-caret-diagnostics");
4079 
4080   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4081                      options::OPT_fno_diagnostics_fixit_info);
4082   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4083                      options::OPT_fno_diagnostics_show_option);
4084 
4085   if (const Arg *A =
4086           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4087     CmdArgs.push_back("-fdiagnostics-show-category");
4088     CmdArgs.push_back(A->getValue());
4089   }
4090 
4091   Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4092                     options::OPT_fno_diagnostics_show_hotness);
4093 
4094   if (const Arg *A =
4095           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4096     std::string Opt =
4097         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4098     CmdArgs.push_back(Args.MakeArgString(Opt));
4099   }
4100 
4101   if (const Arg *A =
4102           Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4103     std::string Opt =
4104         std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4105     CmdArgs.push_back(Args.MakeArgString(Opt));
4106   }
4107 
4108   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4109     CmdArgs.push_back("-fdiagnostics-format");
4110     CmdArgs.push_back(A->getValue());
4111     if (StringRef(A->getValue()) == "sarif" ||
4112         StringRef(A->getValue()) == "SARIF")
4113       D.Diag(diag::warn_drv_sarif_format_unstable);
4114   }
4115 
4116   if (const Arg *A = Args.getLastArg(
4117           options::OPT_fdiagnostics_show_note_include_stack,
4118           options::OPT_fno_diagnostics_show_note_include_stack)) {
4119     const Option &O = A->getOption();
4120     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4121       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4122     else
4123       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4124   }
4125 
4126   // Color diagnostics are parsed by the driver directly from argv and later
4127   // re-parsed to construct this job; claim any possible color diagnostic here
4128   // to avoid warn_drv_unused_argument and diagnose bad
4129   // OPT_fdiagnostics_color_EQ values.
4130   Args.getLastArg(options::OPT_fcolor_diagnostics,
4131                   options::OPT_fno_color_diagnostics);
4132   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4133     StringRef Value(A->getValue());
4134     if (Value != "always" && Value != "never" && Value != "auto")
4135       D.Diag(diag::err_drv_invalid_argument_to_option)
4136           << Value << A->getOption().getName();
4137   }
4138 
4139   if (D.getDiags().getDiagnosticOptions().ShowColors)
4140     CmdArgs.push_back("-fcolor-diagnostics");
4141 
4142   if (Args.hasArg(options::OPT_fansi_escape_codes))
4143     CmdArgs.push_back("-fansi-escape-codes");
4144 
4145   Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4146                      options::OPT_fno_show_source_location);
4147 
4148   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4149                      options::OPT_fno_diagnostics_show_line_numbers);
4150 
4151   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4152     CmdArgs.push_back("-fdiagnostics-absolute-paths");
4153 
4154   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4155                     ColumnDefault))
4156     CmdArgs.push_back("-fno-show-column");
4157 
4158   Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4159                      options::OPT_fno_spell_checking);
4160 }
4161 
4162 DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4163                                             const ArgList &Args, Arg *&Arg) {
4164   Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4165                         options::OPT_gno_split_dwarf);
4166   if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4167     return DwarfFissionKind::None;
4168 
4169   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4170     return DwarfFissionKind::Split;
4171 
4172   StringRef Value = Arg->getValue();
4173   if (Value == "split")
4174     return DwarfFissionKind::Split;
4175   if (Value == "single")
4176     return DwarfFissionKind::Single;
4177 
4178   D.Diag(diag::err_drv_unsupported_option_argument)
4179       << Arg->getSpelling() << Arg->getValue();
4180   return DwarfFissionKind::None;
4181 }
4182 
4183 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4184                               const ArgList &Args, ArgStringList &CmdArgs,
4185                               unsigned DwarfVersion) {
4186   auto *DwarfFormatArg =
4187       Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4188   if (!DwarfFormatArg)
4189     return;
4190 
4191   if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4192     if (DwarfVersion < 3)
4193       D.Diag(diag::err_drv_argument_only_allowed_with)
4194           << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4195     else if (!T.isArch64Bit())
4196       D.Diag(diag::err_drv_argument_only_allowed_with)
4197           << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4198     else if (!T.isOSBinFormatELF())
4199       D.Diag(diag::err_drv_argument_only_allowed_with)
4200           << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4201   }
4202 
4203   DwarfFormatArg->render(Args, CmdArgs);
4204 }
4205 
4206 static void
4207 renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4208                    const ArgList &Args, bool EmitCodeView, bool IRInput,
4209                    ArgStringList &CmdArgs,
4210                    llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4211                    DwarfFissionKind &DwarfFission) {
4212   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4213                    options::OPT_fno_debug_info_for_profiling, false) &&
4214       checkDebugInfoOption(
4215           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4216     CmdArgs.push_back("-fdebug-info-for-profiling");
4217 
4218   // The 'g' groups options involve a somewhat intricate sequence of decisions
4219   // about what to pass from the driver to the frontend, but by the time they
4220   // reach cc1 they've been factored into three well-defined orthogonal choices:
4221   //  * what level of debug info to generate
4222   //  * what dwarf version to write
4223   //  * what debugger tuning to use
4224   // This avoids having to monkey around further in cc1 other than to disable
4225   // codeview if not running in a Windows environment. Perhaps even that
4226   // decision should be made in the driver as well though.
4227   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4228 
4229   bool SplitDWARFInlining =
4230       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4231                    options::OPT_fno_split_dwarf_inlining, false);
4232 
4233   // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4234   // object file generation and no IR generation, -gN should not be needed. So
4235   // allow -gsplit-dwarf with either -gN or IR input.
4236   if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4237     Arg *SplitDWARFArg;
4238     DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4239     if (DwarfFission != DwarfFissionKind::None &&
4240         !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4241       DwarfFission = DwarfFissionKind::None;
4242       SplitDWARFInlining = false;
4243     }
4244   }
4245   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4246     DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4247 
4248     // If the last option explicitly specified a debug-info level, use it.
4249     if (checkDebugInfoOption(A, Args, D, TC) &&
4250         A->getOption().matches(options::OPT_gN_Group)) {
4251       DebugInfoKind = debugLevelToInfoKind(*A);
4252       // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4253       // complicated if you've disabled inline info in the skeleton CUs
4254       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4255       // line-tables-only, so let those compose naturally in that case.
4256       if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4257           DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4258           (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4259            SplitDWARFInlining))
4260         DwarfFission = DwarfFissionKind::None;
4261     }
4262   }
4263 
4264   // If a debugger tuning argument appeared, remember it.
4265   bool HasDebuggerTuning = false;
4266   if (const Arg *A =
4267           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4268     HasDebuggerTuning = true;
4269     if (checkDebugInfoOption(A, Args, D, TC)) {
4270       if (A->getOption().matches(options::OPT_glldb))
4271         DebuggerTuning = llvm::DebuggerKind::LLDB;
4272       else if (A->getOption().matches(options::OPT_gsce))
4273         DebuggerTuning = llvm::DebuggerKind::SCE;
4274       else if (A->getOption().matches(options::OPT_gdbx))
4275         DebuggerTuning = llvm::DebuggerKind::DBX;
4276       else
4277         DebuggerTuning = llvm::DebuggerKind::GDB;
4278     }
4279   }
4280 
4281   // If a -gdwarf argument appeared, remember it.
4282   bool EmitDwarf = false;
4283   if (const Arg *A = getDwarfNArg(Args))
4284     EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4285 
4286   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4287     EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4288 
4289   // If the user asked for debug info but did not explicitly specify -gcodeview
4290   // or -gdwarf, ask the toolchain for the default format.
4291   if (!EmitCodeView && !EmitDwarf &&
4292       DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4293     switch (TC.getDefaultDebugFormat()) {
4294     case llvm::codegenoptions::DIF_CodeView:
4295       EmitCodeView = true;
4296       break;
4297     case llvm::codegenoptions::DIF_DWARF:
4298       EmitDwarf = true;
4299       break;
4300     }
4301   }
4302 
4303   unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4304   unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4305                                       // be lower than what the user wanted.
4306   if (EmitDwarf) {
4307     RequestedDWARFVersion = getDwarfVersion(TC, Args);
4308     // Clamp effective DWARF version to the max supported by the toolchain.
4309     EffectiveDWARFVersion =
4310         std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4311   } else {
4312     Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4313   }
4314 
4315   // -gline-directives-only supported only for the DWARF debug info.
4316   if (RequestedDWARFVersion == 0 &&
4317       DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4318     DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4319 
4320   // strict DWARF is set to false by default. But for DBX, we need it to be set
4321   // as true by default.
4322   if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4323     (void)checkDebugInfoOption(A, Args, D, TC);
4324   if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4325                    DebuggerTuning == llvm::DebuggerKind::DBX))
4326     CmdArgs.push_back("-gstrict-dwarf");
4327 
4328   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4329   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4330 
4331   // Column info is included by default for everything except SCE and
4332   // CodeView. Clang doesn't track end columns, just starting columns, which,
4333   // in theory, is fine for CodeView (and PDB).  In practice, however, the
4334   // Microsoft debuggers don't handle missing end columns well, and the AIX
4335   // debugger DBX also doesn't handle the columns well, so it's better not to
4336   // include any column info.
4337   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4338     (void)checkDebugInfoOption(A, Args, D, TC);
4339   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4340                     !EmitCodeView &&
4341                         (DebuggerTuning != llvm::DebuggerKind::SCE &&
4342                          DebuggerTuning != llvm::DebuggerKind::DBX)))
4343     CmdArgs.push_back("-gno-column-info");
4344 
4345   // FIXME: Move backend command line options to the module.
4346   if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4347     // If -gline-tables-only or -gline-directives-only is the last option it
4348     // wins.
4349     if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4350                              TC)) {
4351       if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4352           DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4353         DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4354         CmdArgs.push_back("-dwarf-ext-refs");
4355         CmdArgs.push_back("-fmodule-format=obj");
4356       }
4357     }
4358   }
4359 
4360   if (T.isOSBinFormatELF() && SplitDWARFInlining)
4361     CmdArgs.push_back("-fsplit-dwarf-inlining");
4362 
4363   // After we've dealt with all combinations of things that could
4364   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4365   // figure out if we need to "upgrade" it to standalone debug info.
4366   // We parse these two '-f' options whether or not they will be used,
4367   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4368   bool NeedFullDebug = Args.hasFlag(
4369       options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4370       DebuggerTuning == llvm::DebuggerKind::LLDB ||
4371           TC.GetDefaultStandaloneDebug());
4372   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4373     (void)checkDebugInfoOption(A, Args, D, TC);
4374 
4375   if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4376       DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4377     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4378                      options::OPT_feliminate_unused_debug_types, false))
4379       DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4380     else if (NeedFullDebug)
4381       DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4382   }
4383 
4384   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4385                    false)) {
4386     // Source embedding is a vendor extension to DWARF v5. By now we have
4387     // checked if a DWARF version was stated explicitly, and have otherwise
4388     // fallen back to the target default, so if this is still not at least 5
4389     // we emit an error.
4390     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4391     if (RequestedDWARFVersion < 5)
4392       D.Diag(diag::err_drv_argument_only_allowed_with)
4393           << A->getAsString(Args) << "-gdwarf-5";
4394     else if (EffectiveDWARFVersion < 5)
4395       // The toolchain has reduced allowed dwarf version, so we can't enable
4396       // -gembed-source.
4397       D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4398           << A->getAsString(Args) << TC.getTripleString() << 5
4399           << EffectiveDWARFVersion;
4400     else if (checkDebugInfoOption(A, Args, D, TC))
4401       CmdArgs.push_back("-gembed-source");
4402   }
4403 
4404   if (EmitCodeView) {
4405     CmdArgs.push_back("-gcodeview");
4406 
4407     Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4408                       options::OPT_gno_codeview_ghash);
4409 
4410     Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4411                        options::OPT_gno_codeview_command_line);
4412   }
4413 
4414   Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4415                      options::OPT_gno_inline_line_tables);
4416 
4417   // When emitting remarks, we need at least debug lines in the output.
4418   if (willEmitRemarks(Args) &&
4419       DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4420     DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4421 
4422   // Adjust the debug info kind for the given toolchain.
4423   TC.adjustDebugInfoKind(DebugInfoKind, Args);
4424 
4425   // On AIX, the debugger tuning option can be omitted if it is not explicitly
4426   // set.
4427   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4428                           T.isOSAIX() && !HasDebuggerTuning
4429                               ? llvm::DebuggerKind::Default
4430                               : DebuggerTuning);
4431 
4432   // -fdebug-macro turns on macro debug info generation.
4433   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4434                    false))
4435     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4436                              D, TC))
4437       CmdArgs.push_back("-debug-info-macro");
4438 
4439   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4440   const auto *PubnamesArg =
4441       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4442                       options::OPT_gpubnames, options::OPT_gno_pubnames);
4443   if (DwarfFission != DwarfFissionKind::None ||
4444       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4445     if (!PubnamesArg ||
4446         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4447          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4448       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4449                                            options::OPT_gpubnames)
4450                             ? "-gpubnames"
4451                             : "-ggnu-pubnames");
4452   const auto *SimpleTemplateNamesArg =
4453       Args.getLastArg(options::OPT_gsimple_template_names,
4454                       options::OPT_gno_simple_template_names);
4455   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4456   if (SimpleTemplateNamesArg &&
4457       checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4458     const auto &Opt = SimpleTemplateNamesArg->getOption();
4459     if (Opt.matches(options::OPT_gsimple_template_names)) {
4460       ForwardTemplateParams = true;
4461       CmdArgs.push_back("-gsimple-template-names=simple");
4462     }
4463   }
4464 
4465   if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4466     StringRef v = A->getValue();
4467     CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4468   }
4469 
4470   Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4471                     options::OPT_fno_debug_ranges_base_address);
4472 
4473   // -gdwarf-aranges turns on the emission of the aranges section in the
4474   // backend.
4475   // Always enabled for SCE tuning.
4476   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4477   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4478     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4479   if (NeedAranges) {
4480     CmdArgs.push_back("-mllvm");
4481     CmdArgs.push_back("-generate-arange-section");
4482   }
4483 
4484   Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4485                     options::OPT_fno_force_dwarf_frame);
4486 
4487   if (Args.hasFlag(options::OPT_fdebug_types_section,
4488                    options::OPT_fno_debug_types_section, false)) {
4489     if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4490       D.Diag(diag::err_drv_unsupported_opt_for_target)
4491           << Args.getLastArg(options::OPT_fdebug_types_section)
4492                  ->getAsString(Args)
4493           << T.getTriple();
4494     } else if (checkDebugInfoOption(
4495                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4496                    TC)) {
4497       CmdArgs.push_back("-mllvm");
4498       CmdArgs.push_back("-generate-type-units");
4499     }
4500   }
4501 
4502   // To avoid join/split of directory+filename, the integrated assembler prefers
4503   // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4504   // form before DWARF v5.
4505   if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4506                     options::OPT_fno_dwarf_directory_asm,
4507                     TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4508     CmdArgs.push_back("-fno-dwarf-directory-asm");
4509 
4510   // Decide how to render forward declarations of template instantiations.
4511   // SCE wants full descriptions, others just get them in the name.
4512   if (ForwardTemplateParams)
4513     CmdArgs.push_back("-debug-forward-template-params");
4514 
4515   // Do we need to explicitly import anonymous namespaces into the parent
4516   // scope?
4517   if (DebuggerTuning == llvm::DebuggerKind::SCE)
4518     CmdArgs.push_back("-dwarf-explicit-import");
4519 
4520   renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4521   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4522 }
4523 
4524 static void ProcessVSRuntimeLibrary(const ArgList &Args,
4525                                     ArgStringList &CmdArgs) {
4526   unsigned RTOptionID = options::OPT__SLASH_MT;
4527 
4528   if (Args.hasArg(options::OPT__SLASH_LDd))
4529     // The /LDd option implies /MTd. The dependent lib part can be overridden,
4530     // but defining _DEBUG is sticky.
4531     RTOptionID = options::OPT__SLASH_MTd;
4532 
4533   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4534     RTOptionID = A->getOption().getID();
4535 
4536   if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4537     RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4538                      .Case("static", options::OPT__SLASH_MT)
4539                      .Case("static_dbg", options::OPT__SLASH_MTd)
4540                      .Case("dll", options::OPT__SLASH_MD)
4541                      .Case("dll_dbg", options::OPT__SLASH_MDd)
4542                      .Default(options::OPT__SLASH_MT);
4543   }
4544 
4545   StringRef FlagForCRT;
4546   switch (RTOptionID) {
4547   case options::OPT__SLASH_MD:
4548     if (Args.hasArg(options::OPT__SLASH_LDd))
4549       CmdArgs.push_back("-D_DEBUG");
4550     CmdArgs.push_back("-D_MT");
4551     CmdArgs.push_back("-D_DLL");
4552     FlagForCRT = "--dependent-lib=msvcrt";
4553     break;
4554   case options::OPT__SLASH_MDd:
4555     CmdArgs.push_back("-D_DEBUG");
4556     CmdArgs.push_back("-D_MT");
4557     CmdArgs.push_back("-D_DLL");
4558     FlagForCRT = "--dependent-lib=msvcrtd";
4559     break;
4560   case options::OPT__SLASH_MT:
4561     if (Args.hasArg(options::OPT__SLASH_LDd))
4562       CmdArgs.push_back("-D_DEBUG");
4563     CmdArgs.push_back("-D_MT");
4564     CmdArgs.push_back("-flto-visibility-public-std");
4565     FlagForCRT = "--dependent-lib=libcmt";
4566     break;
4567   case options::OPT__SLASH_MTd:
4568     CmdArgs.push_back("-D_DEBUG");
4569     CmdArgs.push_back("-D_MT");
4570     CmdArgs.push_back("-flto-visibility-public-std");
4571     FlagForCRT = "--dependent-lib=libcmtd";
4572     break;
4573   default:
4574     llvm_unreachable("Unexpected option ID.");
4575   }
4576 
4577   if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4578     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4579   } else {
4580     CmdArgs.push_back(FlagForCRT.data());
4581 
4582     // This provides POSIX compatibility (maps 'open' to '_open'), which most
4583     // users want.  The /Za flag to cl.exe turns this off, but it's not
4584     // implemented in clang.
4585     CmdArgs.push_back("--dependent-lib=oldnames");
4586   }
4587 }
4588 
4589 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4590                          const InputInfo &Output, const InputInfoList &Inputs,
4591                          const ArgList &Args, const char *LinkingOutput) const {
4592   const auto &TC = getToolChain();
4593   const llvm::Triple &RawTriple = TC.getTriple();
4594   const llvm::Triple &Triple = TC.getEffectiveTriple();
4595   const std::string &TripleStr = Triple.getTriple();
4596 
4597   bool KernelOrKext =
4598       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4599   const Driver &D = TC.getDriver();
4600   ArgStringList CmdArgs;
4601 
4602   assert(Inputs.size() >= 1 && "Must have at least one input.");
4603   // CUDA/HIP compilation may have multiple inputs (source file + results of
4604   // device-side compilations). OpenMP device jobs also take the host IR as a
4605   // second input. Module precompilation accepts a list of header files to
4606   // include as part of the module. API extraction accepts a list of header
4607   // files whose API information is emitted in the output. All other jobs are
4608   // expected to have exactly one input.
4609   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4610   bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4611   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4612   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4613   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4614   bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4615   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4616                                  JA.isDeviceOffloading(Action::OFK_Host));
4617   bool IsHostOffloadingAction =
4618       JA.isHostOffloading(Action::OFK_OpenMP) ||
4619       (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4620        Args.hasFlag(options::OPT_offload_new_driver,
4621                     options::OPT_no_offload_new_driver, false));
4622 
4623   bool IsRDCMode =
4624       Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4625   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4626   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4627 
4628   // Extract API doesn't have a main input file, so invent a fake one as a
4629   // placeholder.
4630   InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4631                                        "extract-api");
4632 
4633   const InputInfo &Input =
4634       IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4635 
4636   InputInfoList ExtractAPIInputs;
4637   InputInfoList HostOffloadingInputs;
4638   const InputInfo *CudaDeviceInput = nullptr;
4639   const InputInfo *OpenMPDeviceInput = nullptr;
4640   for (const InputInfo &I : Inputs) {
4641     if (&I == &Input || I.getType() == types::TY_Nothing) {
4642       // This is the primary input or contains nothing.
4643     } else if (IsExtractAPI) {
4644       auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4645       if (I.getType() != ExpectedInputType) {
4646         D.Diag(diag::err_drv_extract_api_wrong_kind)
4647             << I.getFilename() << types::getTypeName(I.getType())
4648             << types::getTypeName(ExpectedInputType);
4649       }
4650       ExtractAPIInputs.push_back(I);
4651     } else if (IsHostOffloadingAction) {
4652       HostOffloadingInputs.push_back(I);
4653     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4654       CudaDeviceInput = &I;
4655     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4656       OpenMPDeviceInput = &I;
4657     } else {
4658       llvm_unreachable("unexpectedly given multiple inputs");
4659     }
4660   }
4661 
4662   const llvm::Triple *AuxTriple =
4663       (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4664   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4665   bool IsIAMCU = RawTriple.isOSIAMCU();
4666 
4667   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
4668   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4669   // Windows), we need to pass Windows-specific flags to cc1.
4670   if (IsCuda || IsHIP)
4671     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4672 
4673   // C++ is not supported for IAMCU.
4674   if (IsIAMCU && types::isCXX(Input.getType()))
4675     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4676 
4677   // Invoke ourselves in -cc1 mode.
4678   //
4679   // FIXME: Implement custom jobs for internal actions.
4680   CmdArgs.push_back("-cc1");
4681 
4682   // Add the "effective" target triple.
4683   CmdArgs.push_back("-triple");
4684   CmdArgs.push_back(Args.MakeArgString(TripleStr));
4685 
4686   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4687     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4688     Args.ClaimAllArgs(options::OPT_MJ);
4689   } else if (const Arg *GenCDBFragment =
4690                  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4691     DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4692                                          TripleStr, Output, Input, Args);
4693     Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4694   }
4695 
4696   if (IsCuda || IsHIP) {
4697     // We have to pass the triple of the host if compiling for a CUDA/HIP device
4698     // and vice-versa.
4699     std::string NormalizedTriple;
4700     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4701         JA.isDeviceOffloading(Action::OFK_HIP))
4702       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4703                              ->getTriple()
4704                              .normalize();
4705     else {
4706       // Host-side compilation.
4707       NormalizedTriple =
4708           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4709                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4710               ->getTriple()
4711               .normalize();
4712       if (IsCuda) {
4713         // We need to figure out which CUDA version we're compiling for, as that
4714         // determines how we load and launch GPU kernels.
4715         auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4716             C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4717         assert(CTC && "Expected valid CUDA Toolchain.");
4718         if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4719           CmdArgs.push_back(Args.MakeArgString(
4720               Twine("-target-sdk-version=") +
4721               CudaVersionToString(CTC->CudaInstallation.version())));
4722         // Unsized function arguments used for variadics were introduced in
4723         // CUDA-9.0. We still do not support generating code that actually uses
4724         // variadic arguments yet, but we do need to allow parsing them as
4725         // recent CUDA headers rely on that.
4726         // https://github.com/llvm/llvm-project/issues/58410
4727         if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
4728           CmdArgs.push_back("-fcuda-allow-variadic-functions");
4729       }
4730     }
4731     CmdArgs.push_back("-aux-triple");
4732     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4733 
4734     if (JA.isDeviceOffloading(Action::OFK_HIP) &&
4735         getToolChain().getTriple().isAMDGPU()) {
4736       // Device side compilation printf
4737       if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
4738         CmdArgs.push_back(Args.MakeArgString(
4739             "-mprintf-kind=" +
4740             Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
4741         // Force compiler error on invalid conversion specifiers
4742         CmdArgs.push_back(
4743             Args.MakeArgString("-Werror=format-invalid-specifier"));
4744       }
4745     }
4746   }
4747 
4748   // Unconditionally claim the printf option now to avoid unused diagnostic.
4749   if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
4750     PF->claim();
4751 
4752   if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4753     CmdArgs.push_back("-fsycl-is-device");
4754 
4755     if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4756       A->render(Args, CmdArgs);
4757     } else {
4758       // Ensure the default version in SYCL mode is 2020.
4759       CmdArgs.push_back("-sycl-std=2020");
4760     }
4761   }
4762 
4763   if (IsOpenMPDevice) {
4764     // We have to pass the triple of the host if compiling for an OpenMP device.
4765     std::string NormalizedTriple =
4766         C.getSingleOffloadToolChain<Action::OFK_Host>()
4767             ->getTriple()
4768             .normalize();
4769     CmdArgs.push_back("-aux-triple");
4770     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4771   }
4772 
4773   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4774                                Triple.getArch() == llvm::Triple::thumb)) {
4775     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4776     unsigned Version = 0;
4777     bool Failure =
4778         Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4779     if (Failure || Version < 7)
4780       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4781                                                 << TripleStr;
4782   }
4783 
4784   // Push all default warning arguments that are specific to
4785   // the given target.  These come before user provided warning options
4786   // are provided.
4787   TC.addClangWarningOptions(CmdArgs);
4788 
4789   // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4790   if (Triple.isSPIR() || Triple.isSPIRV())
4791     CmdArgs.push_back("-Wspir-compat");
4792 
4793   // Select the appropriate action.
4794   RewriteKind rewriteKind = RK_None;
4795 
4796   bool UnifiedLTO = false;
4797   if (IsUsingLTO) {
4798     UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
4799                               options::OPT_fno_unified_lto, Triple.isPS());
4800     if (UnifiedLTO)
4801       CmdArgs.push_back("-funified-lto");
4802   }
4803 
4804   // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4805   // it claims when not running an assembler. Otherwise, clang would emit
4806   // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4807   // flags while debugging something. That'd be somewhat inconvenient, and it's
4808   // also inconsistent with most other flags -- we don't warn on
4809   // -ffunction-sections not being used in -E mode either for example, even
4810   // though it's not really used either.
4811   if (!isa<AssembleJobAction>(JA)) {
4812     // The args claimed here should match the args used in
4813     // CollectArgsForIntegratedAssembler().
4814     if (TC.useIntegratedAs()) {
4815       Args.ClaimAllArgs(options::OPT_mrelax_all);
4816       Args.ClaimAllArgs(options::OPT_mno_relax_all);
4817       Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4818       Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4819       switch (C.getDefaultToolChain().getArch()) {
4820       case llvm::Triple::arm:
4821       case llvm::Triple::armeb:
4822       case llvm::Triple::thumb:
4823       case llvm::Triple::thumbeb:
4824         Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4825         break;
4826       default:
4827         break;
4828       }
4829     }
4830     Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4831     Args.ClaimAllArgs(options::OPT_Xassembler);
4832     Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4833   }
4834 
4835   if (isa<AnalyzeJobAction>(JA)) {
4836     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4837     CmdArgs.push_back("-analyze");
4838   } else if (isa<MigrateJobAction>(JA)) {
4839     CmdArgs.push_back("-migrate");
4840   } else if (isa<PreprocessJobAction>(JA)) {
4841     if (Output.getType() == types::TY_Dependencies)
4842       CmdArgs.push_back("-Eonly");
4843     else {
4844       CmdArgs.push_back("-E");
4845       if (Args.hasArg(options::OPT_rewrite_objc) &&
4846           !Args.hasArg(options::OPT_g_Group))
4847         CmdArgs.push_back("-P");
4848       else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
4849         CmdArgs.push_back("-fdirectives-only");
4850     }
4851   } else if (isa<AssembleJobAction>(JA)) {
4852     CmdArgs.push_back("-emit-obj");
4853 
4854     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4855 
4856     // Also ignore explicit -force_cpusubtype_ALL option.
4857     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4858   } else if (isa<PrecompileJobAction>(JA)) {
4859     if (JA.getType() == types::TY_Nothing)
4860       CmdArgs.push_back("-fsyntax-only");
4861     else if (JA.getType() == types::TY_ModuleFile)
4862       CmdArgs.push_back("-emit-module-interface");
4863     else if (JA.getType() == types::TY_HeaderUnit)
4864       CmdArgs.push_back("-emit-header-unit");
4865     else
4866       CmdArgs.push_back("-emit-pch");
4867   } else if (isa<VerifyPCHJobAction>(JA)) {
4868     CmdArgs.push_back("-verify-pch");
4869   } else if (isa<ExtractAPIJobAction>(JA)) {
4870     assert(JA.getType() == types::TY_API_INFO &&
4871            "Extract API actions must generate a API information.");
4872     CmdArgs.push_back("-extract-api");
4873     if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
4874       ProductNameArg->render(Args, CmdArgs);
4875     if (Arg *ExtractAPIIgnoresFileArg =
4876             Args.getLastArg(options::OPT_extract_api_ignores_EQ))
4877       ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
4878   } else {
4879     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4880            "Invalid action for clang tool.");
4881     if (JA.getType() == types::TY_Nothing) {
4882       CmdArgs.push_back("-fsyntax-only");
4883     } else if (JA.getType() == types::TY_LLVM_IR ||
4884                JA.getType() == types::TY_LTO_IR) {
4885       CmdArgs.push_back("-emit-llvm");
4886     } else if (JA.getType() == types::TY_LLVM_BC ||
4887                JA.getType() == types::TY_LTO_BC) {
4888       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4889       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4890           Args.hasArg(options::OPT_emit_llvm)) {
4891         CmdArgs.push_back("-emit-llvm");
4892       } else {
4893         CmdArgs.push_back("-emit-llvm-bc");
4894       }
4895     } else if (JA.getType() == types::TY_IFS ||
4896                JA.getType() == types::TY_IFS_CPP) {
4897       StringRef ArgStr =
4898           Args.hasArg(options::OPT_interface_stub_version_EQ)
4899               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4900               : "ifs-v1";
4901       CmdArgs.push_back("-emit-interface-stubs");
4902       CmdArgs.push_back(
4903           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4904     } else if (JA.getType() == types::TY_PP_Asm) {
4905       CmdArgs.push_back("-S");
4906     } else if (JA.getType() == types::TY_AST) {
4907       CmdArgs.push_back("-emit-pch");
4908     } else if (JA.getType() == types::TY_ModuleFile) {
4909       CmdArgs.push_back("-module-file-info");
4910     } else if (JA.getType() == types::TY_RewrittenObjC) {
4911       CmdArgs.push_back("-rewrite-objc");
4912       rewriteKind = RK_NonFragile;
4913     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4914       CmdArgs.push_back("-rewrite-objc");
4915       rewriteKind = RK_Fragile;
4916     } else {
4917       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4918     }
4919 
4920     // Preserve use-list order by default when emitting bitcode, so that
4921     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4922     // same result as running passes here.  For LTO, we don't need to preserve
4923     // the use-list order, since serialization to bitcode is part of the flow.
4924     if (JA.getType() == types::TY_LLVM_BC)
4925       CmdArgs.push_back("-emit-llvm-uselists");
4926 
4927     if (IsUsingLTO) {
4928       if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
4929           !Args.hasFlag(options::OPT_offload_new_driver,
4930                         options::OPT_no_offload_new_driver, false) &&
4931           !Triple.isAMDGPU()) {
4932         D.Diag(diag::err_drv_unsupported_opt_for_target)
4933             << Args.getLastArg(options::OPT_foffload_lto,
4934                                options::OPT_foffload_lto_EQ)
4935                    ->getAsString(Args)
4936             << Triple.getTriple();
4937       } else if (Triple.isNVPTX() && !IsRDCMode &&
4938                  JA.isDeviceOffloading(Action::OFK_Cuda)) {
4939         D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
4940             << Args.getLastArg(options::OPT_foffload_lto,
4941                                options::OPT_foffload_lto_EQ)
4942                    ->getAsString(Args)
4943             << "-fno-gpu-rdc";
4944       } else {
4945         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4946         CmdArgs.push_back(Args.MakeArgString(
4947             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4948         // PS4 uses the legacy LTO API, which does not support some of the
4949         // features enabled by -flto-unit.
4950         if (!RawTriple.isPS4() ||
4951             (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
4952           CmdArgs.push_back("-flto-unit");
4953       }
4954     }
4955   }
4956 
4957   Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
4958 
4959   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4960     if (!types::isLLVMIR(Input.getType()))
4961       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4962     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4963   }
4964 
4965   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4966     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4967 
4968   if (Args.getLastArg(options::OPT_save_temps_EQ))
4969     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4970 
4971   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4972                                      options::OPT_fmemory_profile_EQ,
4973                                      options::OPT_fno_memory_profile);
4974   if (MemProfArg &&
4975       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4976     MemProfArg->render(Args, CmdArgs);
4977 
4978   if (auto *MemProfUseArg =
4979           Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
4980     if (MemProfArg)
4981       D.Diag(diag::err_drv_argument_not_allowed_with)
4982           << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
4983     if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
4984                                             options::OPT_fprofile_generate_EQ))
4985       D.Diag(diag::err_drv_argument_not_allowed_with)
4986           << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
4987     MemProfUseArg->render(Args, CmdArgs);
4988   }
4989 
4990   // Embed-bitcode option.
4991   // Only white-listed flags below are allowed to be embedded.
4992   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
4993       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4994     // Add flags implied by -fembed-bitcode.
4995     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4996     // Disable all llvm IR level optimizations.
4997     CmdArgs.push_back("-disable-llvm-passes");
4998 
4999     // Render target options.
5000     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5001 
5002     // reject options that shouldn't be supported in bitcode
5003     // also reject kernel/kext
5004     static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5005         options::OPT_mkernel,
5006         options::OPT_fapple_kext,
5007         options::OPT_ffunction_sections,
5008         options::OPT_fno_function_sections,
5009         options::OPT_fdata_sections,
5010         options::OPT_fno_data_sections,
5011         options::OPT_fbasic_block_sections_EQ,
5012         options::OPT_funique_internal_linkage_names,
5013         options::OPT_fno_unique_internal_linkage_names,
5014         options::OPT_funique_section_names,
5015         options::OPT_fno_unique_section_names,
5016         options::OPT_funique_basic_block_section_names,
5017         options::OPT_fno_unique_basic_block_section_names,
5018         options::OPT_mrestrict_it,
5019         options::OPT_mno_restrict_it,
5020         options::OPT_mstackrealign,
5021         options::OPT_mno_stackrealign,
5022         options::OPT_mstack_alignment,
5023         options::OPT_mcmodel_EQ,
5024         options::OPT_mlong_calls,
5025         options::OPT_mno_long_calls,
5026         options::OPT_ggnu_pubnames,
5027         options::OPT_gdwarf_aranges,
5028         options::OPT_fdebug_types_section,
5029         options::OPT_fno_debug_types_section,
5030         options::OPT_fdwarf_directory_asm,
5031         options::OPT_fno_dwarf_directory_asm,
5032         options::OPT_mrelax_all,
5033         options::OPT_mno_relax_all,
5034         options::OPT_ftrap_function_EQ,
5035         options::OPT_ffixed_r9,
5036         options::OPT_mfix_cortex_a53_835769,
5037         options::OPT_mno_fix_cortex_a53_835769,
5038         options::OPT_ffixed_x18,
5039         options::OPT_mglobal_merge,
5040         options::OPT_mno_global_merge,
5041         options::OPT_mred_zone,
5042         options::OPT_mno_red_zone,
5043         options::OPT_Wa_COMMA,
5044         options::OPT_Xassembler,
5045         options::OPT_mllvm,
5046     };
5047     for (const auto &A : Args)
5048       if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5049         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5050 
5051     // Render the CodeGen options that need to be passed.
5052     Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5053                        options::OPT_fno_optimize_sibling_calls);
5054 
5055     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
5056                                CmdArgs, JA);
5057 
5058     // Render ABI arguments
5059     switch (TC.getArch()) {
5060     default: break;
5061     case llvm::Triple::arm:
5062     case llvm::Triple::armeb:
5063     case llvm::Triple::thumbeb:
5064       RenderARMABI(D, Triple, Args, CmdArgs);
5065       break;
5066     case llvm::Triple::aarch64:
5067     case llvm::Triple::aarch64_32:
5068     case llvm::Triple::aarch64_be:
5069       RenderAArch64ABI(Triple, Args, CmdArgs);
5070       break;
5071     }
5072 
5073     // Optimization level for CodeGen.
5074     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5075       if (A->getOption().matches(options::OPT_O4)) {
5076         CmdArgs.push_back("-O3");
5077         D.Diag(diag::warn_O4_is_O3);
5078       } else {
5079         A->render(Args, CmdArgs);
5080       }
5081     }
5082 
5083     // Input/Output file.
5084     if (Output.getType() == types::TY_Dependencies) {
5085       // Handled with other dependency code.
5086     } else if (Output.isFilename()) {
5087       CmdArgs.push_back("-o");
5088       CmdArgs.push_back(Output.getFilename());
5089     } else {
5090       assert(Output.isNothing() && "Input output.");
5091     }
5092 
5093     for (const auto &II : Inputs) {
5094       addDashXForInput(Args, II, CmdArgs);
5095       if (II.isFilename())
5096         CmdArgs.push_back(II.getFilename());
5097       else
5098         II.getInputArg().renderAsInput(Args, CmdArgs);
5099     }
5100 
5101     C.addCommand(std::make_unique<Command>(
5102         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5103         CmdArgs, Inputs, Output, D.getPrependArg()));
5104     return;
5105   }
5106 
5107   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5108     CmdArgs.push_back("-fembed-bitcode=marker");
5109 
5110   // We normally speed up the clang process a bit by skipping destructors at
5111   // exit, but when we're generating diagnostics we can rely on some of the
5112   // cleanup.
5113   if (!C.isForDiagnostics())
5114     CmdArgs.push_back("-disable-free");
5115   CmdArgs.push_back("-clear-ast-before-backend");
5116 
5117 #ifdef NDEBUG
5118   const bool IsAssertBuild = false;
5119 #else
5120   const bool IsAssertBuild = true;
5121 #endif
5122 
5123   // Disable the verification pass in -asserts builds.
5124   if (!IsAssertBuild)
5125     CmdArgs.push_back("-disable-llvm-verifier");
5126 
5127   // Discard value names in assert builds unless otherwise specified.
5128   if (Args.hasFlag(options::OPT_fdiscard_value_names,
5129                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5130     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5131         llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5132           return types::isLLVMIR(II.getType());
5133         })) {
5134       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5135     }
5136     CmdArgs.push_back("-discard-value-names");
5137   }
5138 
5139   // Set the main file name, so that debug info works even with
5140   // -save-temps.
5141   CmdArgs.push_back("-main-file-name");
5142   CmdArgs.push_back(getBaseInputName(Args, Input));
5143 
5144   // Some flags which affect the language (via preprocessor
5145   // defines).
5146   if (Args.hasArg(options::OPT_static))
5147     CmdArgs.push_back("-static-define");
5148 
5149   if (Args.hasArg(options::OPT_municode))
5150     CmdArgs.push_back("-DUNICODE");
5151 
5152   if (isa<AnalyzeJobAction>(JA))
5153     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5154 
5155   if (isa<AnalyzeJobAction>(JA) ||
5156       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5157     CmdArgs.push_back("-setup-static-analyzer");
5158 
5159   // Enable compatilibily mode to avoid analyzer-config related errors.
5160   // Since we can't access frontend flags through hasArg, let's manually iterate
5161   // through them.
5162   bool FoundAnalyzerConfig = false;
5163   for (auto *Arg : Args.filtered(options::OPT_Xclang))
5164     if (StringRef(Arg->getValue()) == "-analyzer-config") {
5165       FoundAnalyzerConfig = true;
5166       break;
5167     }
5168   if (!FoundAnalyzerConfig)
5169     for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5170       if (StringRef(Arg->getValue()) == "-analyzer-config") {
5171         FoundAnalyzerConfig = true;
5172         break;
5173       }
5174   if (FoundAnalyzerConfig)
5175     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5176 
5177   CheckCodeGenerationOptions(D, Args);
5178 
5179   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5180   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5181   if (FunctionAlignment) {
5182     CmdArgs.push_back("-function-alignment");
5183     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5184   }
5185 
5186   // We support -falign-loops=N where N is a power of 2. GCC supports more
5187   // forms.
5188   if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5189     unsigned Value = 0;
5190     if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5191       TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5192           << A->getAsString(Args) << A->getValue();
5193     else if (Value & (Value - 1))
5194       TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5195           << A->getAsString(Args) << A->getValue();
5196     // Treat =0 as unspecified (use the target preference).
5197     if (Value)
5198       CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5199                                            Twine(std::min(Value, 65536u))));
5200   }
5201 
5202   if (Triple.isOSzOS()) {
5203     // On z/OS some of the system header feature macros need to
5204     // be defined to enable most cross platform projects to build
5205     // successfully.  Ths include the libc++ library.  A
5206     // complicating factor is that users can define these
5207     // macros to the same or different values.  We need to add
5208     // the definition for these macros to the compilation command
5209     // if the user hasn't already defined them.
5210 
5211     auto findMacroDefinition = [&](const std::string &Macro) {
5212       auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5213       return std::find_if(MacroDefs.begin(), MacroDefs.end(),
5214                           [&](const std::string &M) {
5215                             return M == Macro ||
5216                                    M.find(Macro + '=') != std::string::npos;
5217                           }) != MacroDefs.end();
5218     };
5219 
5220     // _UNIX03_WITHDRAWN is required for libcxx & porting.
5221     if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5222       CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5223     // _OPEN_DEFAULT is required for XL compat
5224     if (!findMacroDefinition("_OPEN_DEFAULT"))
5225       CmdArgs.push_back("-D_OPEN_DEFAULT");
5226     if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5227       // _XOPEN_SOURCE=600 is required for libcxx.
5228       if (!findMacroDefinition("_XOPEN_SOURCE"))
5229         CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5230     }
5231   }
5232 
5233   llvm::Reloc::Model RelocationModel;
5234   unsigned PICLevel;
5235   bool IsPIE;
5236   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5237   Arg *LastPICDataRelArg =
5238       Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5239                       options::OPT_mpic_data_is_text_relative);
5240   bool NoPICDataIsTextRelative = false;
5241   if (LastPICDataRelArg) {
5242     if (LastPICDataRelArg->getOption().matches(
5243             options::OPT_mno_pic_data_is_text_relative)) {
5244       NoPICDataIsTextRelative = true;
5245       if (!PICLevel)
5246         D.Diag(diag::err_drv_argument_only_allowed_with)
5247             << "-mno-pic-data-is-text-relative"
5248             << "-fpic/-fpie";
5249     }
5250     if (!Triple.isSystemZ())
5251       D.Diag(diag::err_drv_unsupported_opt_for_target)
5252           << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5253                                       : "-mpic-data-is-text-relative")
5254           << RawTriple.str();
5255   }
5256 
5257   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5258                 RelocationModel == llvm::Reloc::ROPI_RWPI;
5259   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5260                 RelocationModel == llvm::Reloc::ROPI_RWPI;
5261 
5262   if (Args.hasArg(options::OPT_mcmse) &&
5263       !Args.hasArg(options::OPT_fallow_unsupported)) {
5264     if (IsROPI)
5265       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5266     if (IsRWPI)
5267       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5268   }
5269 
5270   if (IsROPI && types::isCXX(Input.getType()) &&
5271       !Args.hasArg(options::OPT_fallow_unsupported))
5272     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5273 
5274   const char *RMName = RelocationModelName(RelocationModel);
5275   if (RMName) {
5276     CmdArgs.push_back("-mrelocation-model");
5277     CmdArgs.push_back(RMName);
5278   }
5279   if (PICLevel > 0) {
5280     CmdArgs.push_back("-pic-level");
5281     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5282     if (IsPIE)
5283       CmdArgs.push_back("-pic-is-pie");
5284     if (NoPICDataIsTextRelative)
5285       CmdArgs.push_back("-mcmodel=medium");
5286   }
5287 
5288   if (RelocationModel == llvm::Reloc::ROPI ||
5289       RelocationModel == llvm::Reloc::ROPI_RWPI)
5290     CmdArgs.push_back("-fropi");
5291   if (RelocationModel == llvm::Reloc::RWPI ||
5292       RelocationModel == llvm::Reloc::ROPI_RWPI)
5293     CmdArgs.push_back("-frwpi");
5294 
5295   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5296     CmdArgs.push_back("-meabi");
5297     CmdArgs.push_back(A->getValue());
5298   }
5299 
5300   // -fsemantic-interposition is forwarded to CC1: set the
5301   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5302   // make default visibility external linkage definitions dso_preemptable.
5303   //
5304   // -fno-semantic-interposition: if the target supports .Lfoo$local local
5305   // aliases (make default visibility external linkage definitions dso_local).
5306   // This is the CC1 default for ELF to match COFF/Mach-O.
5307   //
5308   // Otherwise use Clang's traditional behavior: like
5309   // -fno-semantic-interposition but local aliases are not used. So references
5310   // can be interposed if not optimized out.
5311   if (Triple.isOSBinFormatELF()) {
5312     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5313                              options::OPT_fno_semantic_interposition);
5314     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5315       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5316       bool SupportsLocalAlias =
5317           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5318       if (!A)
5319         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5320       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5321         A->render(Args, CmdArgs);
5322       else if (!SupportsLocalAlias)
5323         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5324     }
5325   }
5326 
5327   {
5328     std::string Model;
5329     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5330       if (!TC.isThreadModelSupported(A->getValue()))
5331         D.Diag(diag::err_drv_invalid_thread_model_for_target)
5332             << A->getValue() << A->getAsString(Args);
5333       Model = A->getValue();
5334     } else
5335       Model = TC.getThreadModel();
5336     if (Model != "posix") {
5337       CmdArgs.push_back("-mthread-model");
5338       CmdArgs.push_back(Args.MakeArgString(Model));
5339     }
5340   }
5341 
5342   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5343     StringRef Name = A->getValue();
5344     if (Name == "SVML") {
5345       if (Triple.getArch() != llvm::Triple::x86 &&
5346           Triple.getArch() != llvm::Triple::x86_64)
5347         D.Diag(diag::err_drv_unsupported_opt_for_target)
5348             << Name << Triple.getArchName();
5349     } else if (Name == "LIBMVEC-X86") {
5350       if (Triple.getArch() != llvm::Triple::x86 &&
5351           Triple.getArch() != llvm::Triple::x86_64)
5352         D.Diag(diag::err_drv_unsupported_opt_for_target)
5353             << Name << Triple.getArchName();
5354     } else if (Name == "SLEEF" || Name == "ArmPL") {
5355       if (Triple.getArch() != llvm::Triple::aarch64 &&
5356           Triple.getArch() != llvm::Triple::aarch64_be)
5357         D.Diag(diag::err_drv_unsupported_opt_for_target)
5358             << Name << Triple.getArchName();
5359     }
5360     A->render(Args, CmdArgs);
5361   }
5362 
5363   if (Args.hasFlag(options::OPT_fmerge_all_constants,
5364                    options::OPT_fno_merge_all_constants, false))
5365     CmdArgs.push_back("-fmerge-all-constants");
5366 
5367   Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5368                      options::OPT_fno_delete_null_pointer_checks);
5369 
5370   // LLVM Code Generator Options.
5371 
5372   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5373     if (!Triple.isOSAIX() || Triple.isPPC32())
5374       D.Diag(diag::err_drv_unsupported_opt_for_target)
5375         << A->getSpelling() << RawTriple.str();
5376     CmdArgs.push_back("-mabi=quadword-atomics");
5377   }
5378 
5379   if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5380     // Emit the unsupported option error until the Clang's library integration
5381     // support for 128-bit long double is available for AIX.
5382     if (Triple.isOSAIX())
5383       D.Diag(diag::err_drv_unsupported_opt_for_target)
5384           << A->getSpelling() << RawTriple.str();
5385   }
5386 
5387   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5388     StringRef V = A->getValue(), V1 = V;
5389     unsigned Size;
5390     if (V1.consumeInteger(10, Size) || !V1.empty())
5391       D.Diag(diag::err_drv_invalid_argument_to_option)
5392           << V << A->getOption().getName();
5393     else
5394       CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5395   }
5396 
5397   Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5398                      options::OPT_fno_jump_tables);
5399   Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5400                     options::OPT_fno_profile_sample_accurate);
5401   Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5402                      options::OPT_fno_preserve_as_comments);
5403 
5404   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5405     CmdArgs.push_back("-mregparm");
5406     CmdArgs.push_back(A->getValue());
5407   }
5408 
5409   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5410                                options::OPT_msvr4_struct_return)) {
5411     if (!TC.getTriple().isPPC32()) {
5412       D.Diag(diag::err_drv_unsupported_opt_for_target)
5413           << A->getSpelling() << RawTriple.str();
5414     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5415       CmdArgs.push_back("-maix-struct-return");
5416     } else {
5417       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5418       CmdArgs.push_back("-msvr4-struct-return");
5419     }
5420   }
5421 
5422   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5423                                options::OPT_freg_struct_return)) {
5424     if (TC.getArch() != llvm::Triple::x86) {
5425       D.Diag(diag::err_drv_unsupported_opt_for_target)
5426           << A->getSpelling() << RawTriple.str();
5427     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5428       CmdArgs.push_back("-fpcc-struct-return");
5429     } else {
5430       assert(A->getOption().matches(options::OPT_freg_struct_return));
5431       CmdArgs.push_back("-freg-struct-return");
5432     }
5433   }
5434 
5435   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
5436     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5437 
5438   if (Args.hasArg(options::OPT_fenable_matrix)) {
5439     // enable-matrix is needed by both the LangOpts and by LLVM.
5440     CmdArgs.push_back("-fenable-matrix");
5441     CmdArgs.push_back("-mllvm");
5442     CmdArgs.push_back("-enable-matrix");
5443   }
5444 
5445   CodeGenOptions::FramePointerKind FPKeepKind =
5446                   getFramePointerKind(Args, RawTriple);
5447   const char *FPKeepKindStr = nullptr;
5448   switch (FPKeepKind) {
5449   case CodeGenOptions::FramePointerKind::None:
5450     FPKeepKindStr = "-mframe-pointer=none";
5451     break;
5452   case CodeGenOptions::FramePointerKind::NonLeaf:
5453     FPKeepKindStr = "-mframe-pointer=non-leaf";
5454     break;
5455   case CodeGenOptions::FramePointerKind::All:
5456     FPKeepKindStr = "-mframe-pointer=all";
5457     break;
5458   }
5459   assert(FPKeepKindStr && "unknown FramePointerKind");
5460   CmdArgs.push_back(FPKeepKindStr);
5461 
5462   Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5463                      options::OPT_fno_zero_initialized_in_bss);
5464 
5465   bool OFastEnabled = isOptimizationLevelFast(Args);
5466   // If -Ofast is the optimization level, then -fstrict-aliasing should be
5467   // enabled.  This alias option is being used to simplify the hasFlag logic.
5468   OptSpecifier StrictAliasingAliasOption =
5469       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5470   // We turn strict aliasing off by default if we're in CL mode, since MSVC
5471   // doesn't do any TBAA.
5472   bool TBAAOnByDefault = !D.IsCLMode();
5473   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5474                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
5475     CmdArgs.push_back("-relaxed-aliasing");
5476   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5477                     options::OPT_fno_struct_path_tbaa, true))
5478     CmdArgs.push_back("-no-struct-path-tbaa");
5479   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5480                     options::OPT_fno_strict_enums);
5481   Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5482                      options::OPT_fno_strict_return);
5483   Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5484                     options::OPT_fno_allow_editor_placeholders);
5485   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5486                     options::OPT_fno_strict_vtable_pointers);
5487   Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5488                     options::OPT_fno_force_emit_vtables);
5489   Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5490                      options::OPT_fno_optimize_sibling_calls);
5491   Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5492                      options::OPT_fno_escaping_block_tail_calls);
5493 
5494   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5495                   options::OPT_fno_fine_grained_bitfield_accesses);
5496 
5497   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5498                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5499 
5500   // Handle segmented stacks.
5501   Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5502                     options::OPT_fno_split_stack);
5503 
5504   // -fprotect-parens=0 is default.
5505   if (Args.hasFlag(options::OPT_fprotect_parens,
5506                    options::OPT_fno_protect_parens, false))
5507     CmdArgs.push_back("-fprotect-parens");
5508 
5509   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5510 
5511   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5512     const llvm::Triple::ArchType Arch = TC.getArch();
5513     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5514       StringRef V = A->getValue();
5515       if (V == "64")
5516         CmdArgs.push_back("-fextend-arguments=64");
5517       else if (V != "32")
5518         D.Diag(diag::err_drv_invalid_argument_to_option)
5519             << A->getValue() << A->getOption().getName();
5520     } else
5521       D.Diag(diag::err_drv_unsupported_opt_for_target)
5522           << A->getOption().getName() << TripleStr;
5523   }
5524 
5525   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5526     if (TC.getArch() == llvm::Triple::avr)
5527       A->render(Args, CmdArgs);
5528     else
5529       D.Diag(diag::err_drv_unsupported_opt_for_target)
5530           << A->getAsString(Args) << TripleStr;
5531   }
5532 
5533   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5534     if (TC.getTriple().isX86())
5535       A->render(Args, CmdArgs);
5536     else if (TC.getTriple().isPPC() &&
5537              (A->getOption().getID() != options::OPT_mlong_double_80))
5538       A->render(Args, CmdArgs);
5539     else
5540       D.Diag(diag::err_drv_unsupported_opt_for_target)
5541           << A->getAsString(Args) << TripleStr;
5542   }
5543 
5544   // Decide whether to use verbose asm. Verbose assembly is the default on
5545   // toolchains which have the integrated assembler on by default.
5546   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5547   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5548                     IsIntegratedAssemblerDefault))
5549     CmdArgs.push_back("-fno-verbose-asm");
5550 
5551   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5552   // use that to indicate the MC default in the backend.
5553   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5554     StringRef V = A->getValue();
5555     unsigned Num;
5556     if (V == "none")
5557       A->render(Args, CmdArgs);
5558     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5559              (V.empty() || (V.consume_front(".") &&
5560                             !V.consumeInteger(10, Num) && V.empty())))
5561       A->render(Args, CmdArgs);
5562     else
5563       D.Diag(diag::err_drv_invalid_argument_to_option)
5564           << A->getValue() << A->getOption().getName();
5565   }
5566 
5567   // If toolchain choose to use MCAsmParser for inline asm don't pass the
5568   // option to disable integrated-as explictly.
5569   if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5570     CmdArgs.push_back("-no-integrated-as");
5571 
5572   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5573     CmdArgs.push_back("-mdebug-pass");
5574     CmdArgs.push_back("Structure");
5575   }
5576   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5577     CmdArgs.push_back("-mdebug-pass");
5578     CmdArgs.push_back("Arguments");
5579   }
5580 
5581   // Enable -mconstructor-aliases except on darwin, where we have to work around
5582   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
5583   // aliases aren't supported.
5584   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5585     CmdArgs.push_back("-mconstructor-aliases");
5586 
5587   // Darwin's kernel doesn't support guard variables; just die if we
5588   // try to use them.
5589   if (KernelOrKext && RawTriple.isOSDarwin())
5590     CmdArgs.push_back("-fforbid-guard-variables");
5591 
5592   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5593                    Triple.isWindowsGNUEnvironment())) {
5594     CmdArgs.push_back("-mms-bitfields");
5595   }
5596 
5597   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5598   // defaults to -fno-direct-access-external-data. Pass the option if different
5599   // from the default.
5600   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5601                                options::OPT_fno_direct_access_external_data))
5602     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5603         (PICLevel == 0))
5604       A->render(Args, CmdArgs);
5605 
5606   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5607     CmdArgs.push_back("-fno-plt");
5608   }
5609 
5610   // -fhosted is default.
5611   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5612   // use Freestanding.
5613   bool Freestanding =
5614       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5615       KernelOrKext;
5616   if (Freestanding)
5617     CmdArgs.push_back("-ffreestanding");
5618 
5619   Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5620 
5621   // This is a coarse approximation of what llvm-gcc actually does, both
5622   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5623   // complicated ways.
5624   auto SanitizeArgs = TC.getSanitizerArgs(Args);
5625 
5626   bool IsAsyncUnwindTablesDefault =
5627       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5628   bool IsSyncUnwindTablesDefault =
5629       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5630 
5631   bool AsyncUnwindTables = Args.hasFlag(
5632       options::OPT_fasynchronous_unwind_tables,
5633       options::OPT_fno_asynchronous_unwind_tables,
5634       (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5635           !Freestanding);
5636   bool UnwindTables =
5637       Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5638                    IsSyncUnwindTablesDefault && !Freestanding);
5639   if (AsyncUnwindTables)
5640     CmdArgs.push_back("-funwind-tables=2");
5641   else if (UnwindTables)
5642      CmdArgs.push_back("-funwind-tables=1");
5643 
5644   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5645   // `--gpu-use-aux-triple-only` is specified.
5646   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5647       (IsCudaDevice || IsHIPDevice)) {
5648     const ArgList &HostArgs =
5649         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5650     std::string HostCPU =
5651         getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5652     if (!HostCPU.empty()) {
5653       CmdArgs.push_back("-aux-target-cpu");
5654       CmdArgs.push_back(Args.MakeArgString(HostCPU));
5655     }
5656     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5657                       /*ForAS*/ false, /*IsAux*/ true);
5658   }
5659 
5660   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5661 
5662   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5663     StringRef CM = A->getValue();
5664     if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
5665         CM == "tiny") {
5666       if (Triple.isOSAIX() && CM == "medium")
5667         CmdArgs.push_back("-mcmodel=large");
5668       else if (Triple.isAArch64() && (CM == "kernel" || CM == "medium"))
5669         D.Diag(diag::err_drv_invalid_argument_to_option)
5670             << CM << A->getOption().getName();
5671       else
5672         A->render(Args, CmdArgs);
5673     } else {
5674       D.Diag(diag::err_drv_invalid_argument_to_option)
5675           << CM << A->getOption().getName();
5676     }
5677   }
5678 
5679   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5680     StringRef Value = A->getValue();
5681     unsigned TLSSize = 0;
5682     Value.getAsInteger(10, TLSSize);
5683     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5684       D.Diag(diag::err_drv_unsupported_opt_for_target)
5685           << A->getOption().getName() << TripleStr;
5686     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5687       D.Diag(diag::err_drv_invalid_int_value)
5688           << A->getOption().getName() << Value;
5689     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5690   }
5691 
5692   // Add the target cpu
5693   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5694   if (!CPU.empty()) {
5695     CmdArgs.push_back("-target-cpu");
5696     CmdArgs.push_back(Args.MakeArgString(CPU));
5697   }
5698 
5699   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5700 
5701   // These two are potentially updated by AddClangCLArgs.
5702   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
5703       llvm::codegenoptions::NoDebugInfo;
5704   bool EmitCodeView = false;
5705 
5706   // Add clang-cl arguments.
5707   types::ID InputType = Input.getType();
5708   if (D.IsCLMode())
5709     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5710 
5711   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5712   renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5713                      types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5714                      DwarfFission);
5715 
5716   // This controls whether or not we perform JustMyCode instrumentation.
5717   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5718     if (TC.getTriple().isOSBinFormatELF()) {
5719       if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5720         CmdArgs.push_back("-fjmc");
5721       else
5722         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5723                                                              << "-g";
5724     } else {
5725       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5726     }
5727   }
5728 
5729   // Add the split debug info name to the command lines here so we
5730   // can propagate it to the backend.
5731   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5732                     (TC.getTriple().isOSBinFormatELF() ||
5733                      TC.getTriple().isOSBinFormatWasm() ||
5734                      TC.getTriple().isOSBinFormatCOFF()) &&
5735                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5736                      isa<BackendJobAction>(JA));
5737   if (SplitDWARF) {
5738     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5739     CmdArgs.push_back("-split-dwarf-file");
5740     CmdArgs.push_back(SplitDWARFOut);
5741     if (DwarfFission == DwarfFissionKind::Split) {
5742       CmdArgs.push_back("-split-dwarf-output");
5743       CmdArgs.push_back(SplitDWARFOut);
5744     }
5745   }
5746 
5747   // Pass the linker version in use.
5748   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5749     CmdArgs.push_back("-target-linker-version");
5750     CmdArgs.push_back(A->getValue());
5751   }
5752 
5753   // Explicitly error on some things we know we don't support and can't just
5754   // ignore.
5755   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5756     Arg *Unsupported;
5757     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5758         TC.getArch() == llvm::Triple::x86) {
5759       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5760           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5761         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5762             << Unsupported->getOption().getName();
5763     }
5764     // The faltivec option has been superseded by the maltivec option.
5765     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5766       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5767           << Unsupported->getOption().getName()
5768           << "please use -maltivec and include altivec.h explicitly";
5769     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5770       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5771           << Unsupported->getOption().getName() << "please use -mno-altivec";
5772   }
5773 
5774   Args.AddAllArgs(CmdArgs, options::OPT_v);
5775 
5776   if (Args.getLastArg(options::OPT_H)) {
5777     CmdArgs.push_back("-H");
5778     CmdArgs.push_back("-sys-header-deps");
5779   }
5780   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5781 
5782   if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
5783     CmdArgs.push_back("-header-include-file");
5784     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5785                           ? D.CCPrintHeadersFilename.c_str()
5786                           : "-");
5787     CmdArgs.push_back("-sys-header-deps");
5788     CmdArgs.push_back(Args.MakeArgString(
5789         "-header-include-format=" +
5790         std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
5791     CmdArgs.push_back(
5792         Args.MakeArgString("-header-include-filtering=" +
5793                            std::string(headerIncludeFilteringKindToString(
5794                                D.CCPrintHeadersFiltering))));
5795   }
5796   Args.AddLastArg(CmdArgs, options::OPT_P);
5797   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5798 
5799   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5800     CmdArgs.push_back("-diagnostic-log-file");
5801     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5802                           ? D.CCLogDiagnosticsFilename.c_str()
5803                           : "-");
5804   }
5805 
5806   // Give the gen diagnostics more chances to succeed, by avoiding intentional
5807   // crashes.
5808   if (D.CCGenDiagnostics)
5809     CmdArgs.push_back("-disable-pragma-debug-crash");
5810 
5811   // Allow backend to put its diagnostic files in the same place as frontend
5812   // crash diagnostics files.
5813   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5814     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5815     CmdArgs.push_back("-mllvm");
5816     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5817   }
5818 
5819   bool UseSeparateSections = isUseSeparateSections(Triple);
5820 
5821   if (Args.hasFlag(options::OPT_ffunction_sections,
5822                    options::OPT_fno_function_sections, UseSeparateSections)) {
5823     CmdArgs.push_back("-ffunction-sections");
5824   }
5825 
5826   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5827     StringRef Val = A->getValue();
5828     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5829       if (Val != "all" && Val != "labels" && Val != "none" &&
5830           !Val.startswith("list="))
5831         D.Diag(diag::err_drv_invalid_value)
5832             << A->getAsString(Args) << A->getValue();
5833       else
5834         A->render(Args, CmdArgs);
5835     } else if (Triple.isNVPTX()) {
5836       // Do not pass the option to the GPU compilation. We still want it enabled
5837       // for the host-side compilation, so seeing it here is not an error.
5838     } else if (Val != "none") {
5839       // =none is allowed everywhere. It's useful for overriding the option
5840       // and is the same as not specifying the option.
5841       D.Diag(diag::err_drv_unsupported_opt_for_target)
5842           << A->getAsString(Args) << TripleStr;
5843     }
5844   }
5845 
5846   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5847   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5848                    UseSeparateSections || HasDefaultDataSections)) {
5849     CmdArgs.push_back("-fdata-sections");
5850   }
5851 
5852   Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
5853                      options::OPT_fno_unique_section_names);
5854   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
5855                     options::OPT_fno_unique_internal_linkage_names);
5856   Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
5857                     options::OPT_fno_unique_basic_block_section_names);
5858   Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
5859                     options::OPT_fno_convergent_functions);
5860 
5861   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5862                                options::OPT_fno_split_machine_functions)) {
5863     // This codegen pass is only available on x86-elf targets.
5864     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5865       if (A->getOption().matches(options::OPT_fsplit_machine_functions))
5866         A->render(Args, CmdArgs);
5867     } else {
5868       D.Diag(diag::err_drv_unsupported_opt_for_target)
5869           << A->getAsString(Args) << TripleStr;
5870     }
5871   }
5872 
5873   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5874                   options::OPT_finstrument_functions_after_inlining,
5875                   options::OPT_finstrument_function_entry_bare);
5876 
5877   // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5878   // for sampling, overhead of call arc collection is way too high and there's
5879   // no way to collect the output.
5880   if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5881     addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
5882 
5883   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5884 
5885   if (getLastProfileSampleUseArg(Args) &&
5886       Args.hasArg(options::OPT_fsample_profile_use_profi)) {
5887     CmdArgs.push_back("-mllvm");
5888     CmdArgs.push_back("-sample-profile-use-profi");
5889   }
5890 
5891   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
5892   if (RawTriple.isPS() &&
5893       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5894     PScpu::addProfileRTArgs(TC, Args, CmdArgs);
5895     PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5896   }
5897 
5898   // Pass options for controlling the default header search paths.
5899   if (Args.hasArg(options::OPT_nostdinc)) {
5900     CmdArgs.push_back("-nostdsysteminc");
5901     CmdArgs.push_back("-nobuiltininc");
5902   } else {
5903     if (Args.hasArg(options::OPT_nostdlibinc))
5904       CmdArgs.push_back("-nostdsysteminc");
5905     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5906     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5907   }
5908 
5909   // Pass the path to compiler resource files.
5910   CmdArgs.push_back("-resource-dir");
5911   CmdArgs.push_back(D.ResourceDir.c_str());
5912 
5913   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5914 
5915   RenderARCMigrateToolOptions(D, Args, CmdArgs);
5916 
5917   // Add preprocessing options like -I, -D, etc. if we are using the
5918   // preprocessor.
5919   //
5920   // FIXME: Support -fpreprocessed
5921   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5922     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5923 
5924   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5925   // that "The compiler can only warn and ignore the option if not recognized".
5926   // When building with ccache, it will pass -D options to clang even on
5927   // preprocessed inputs and configure concludes that -fPIC is not supported.
5928   Args.ClaimAllArgs(options::OPT_D);
5929 
5930   // Manually translate -O4 to -O3; let clang reject others.
5931   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5932     if (A->getOption().matches(options::OPT_O4)) {
5933       CmdArgs.push_back("-O3");
5934       D.Diag(diag::warn_O4_is_O3);
5935     } else {
5936       A->render(Args, CmdArgs);
5937     }
5938   }
5939 
5940   // Warn about ignored options to clang.
5941   for (const Arg *A :
5942        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5943     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5944     A->claim();
5945   }
5946 
5947   for (const Arg *A :
5948        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
5949     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
5950     A->claim();
5951   }
5952 
5953   claimNoWarnArgs(Args);
5954 
5955   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5956 
5957   for (const Arg *A :
5958        Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
5959     A->claim();
5960     if (A->getOption().getID() == options::OPT__SLASH_wd) {
5961       unsigned WarningNumber;
5962       if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
5963         D.Diag(diag::err_drv_invalid_int_value)
5964             << A->getAsString(Args) << A->getValue();
5965         continue;
5966       }
5967 
5968       if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
5969         CmdArgs.push_back(Args.MakeArgString(
5970             "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
5971       }
5972       continue;
5973     }
5974     A->render(Args, CmdArgs);
5975   }
5976 
5977   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5978     CmdArgs.push_back("-pedantic");
5979   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5980   Args.AddLastArg(CmdArgs, options::OPT_w);
5981 
5982   Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
5983                     options::OPT_fno_fixed_point);
5984 
5985   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
5986     A->render(Args, CmdArgs);
5987 
5988   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5989                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5990 
5991   if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
5992     A->render(Args, CmdArgs);
5993 
5994   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5995   // (-ansi is equivalent to -std=c89 or -std=c++98).
5996   //
5997   // If a std is supplied, only add -trigraphs if it follows the
5998   // option.
5999   bool ImplyVCPPCVer = false;
6000   bool ImplyVCPPCXXVer = false;
6001   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6002   if (Std) {
6003     if (Std->getOption().matches(options::OPT_ansi))
6004       if (types::isCXX(InputType))
6005         CmdArgs.push_back("-std=c++98");
6006       else
6007         CmdArgs.push_back("-std=c89");
6008     else
6009       Std->render(Args, CmdArgs);
6010 
6011     // If -f(no-)trigraphs appears after the language standard flag, honor it.
6012     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6013                                  options::OPT_ftrigraphs,
6014                                  options::OPT_fno_trigraphs))
6015       if (A != Std)
6016         A->render(Args, CmdArgs);
6017   } else {
6018     // Honor -std-default.
6019     //
6020     // FIXME: Clang doesn't correctly handle -std= when the input language
6021     // doesn't match. For the time being just ignore this for C++ inputs;
6022     // eventually we want to do all the standard defaulting here instead of
6023     // splitting it between the driver and clang -cc1.
6024     if (!types::isCXX(InputType)) {
6025       if (!Args.hasArg(options::OPT__SLASH_std)) {
6026         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6027                                   /*Joined=*/true);
6028       } else
6029         ImplyVCPPCVer = true;
6030     }
6031     else if (IsWindowsMSVC)
6032       ImplyVCPPCXXVer = true;
6033 
6034     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6035                     options::OPT_fno_trigraphs);
6036   }
6037 
6038   // GCC's behavior for -Wwrite-strings is a bit strange:
6039   //  * In C, this "warning flag" changes the types of string literals from
6040   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6041   //    for the discarded qualifier.
6042   //  * In C++, this is just a normal warning flag.
6043   //
6044   // Implementing this warning correctly in C is hard, so we follow GCC's
6045   // behavior for now. FIXME: Directly diagnose uses of a string literal as
6046   // a non-const char* in C, rather than using this crude hack.
6047   if (!types::isCXX(InputType)) {
6048     // FIXME: This should behave just like a warning flag, and thus should also
6049     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6050     Arg *WriteStrings =
6051         Args.getLastArg(options::OPT_Wwrite_strings,
6052                         options::OPT_Wno_write_strings, options::OPT_w);
6053     if (WriteStrings &&
6054         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6055       CmdArgs.push_back("-fconst-strings");
6056   }
6057 
6058   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6059   // during C++ compilation, which it is by default. GCC keeps this define even
6060   // in the presence of '-w', match this behavior bug-for-bug.
6061   if (types::isCXX(InputType) &&
6062       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6063                    true)) {
6064     CmdArgs.push_back("-fdeprecated-macro");
6065   }
6066 
6067   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6068   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6069     if (Asm->getOption().matches(options::OPT_fasm))
6070       CmdArgs.push_back("-fgnu-keywords");
6071     else
6072       CmdArgs.push_back("-fno-gnu-keywords");
6073   }
6074 
6075   if (!ShouldEnableAutolink(Args, TC, JA))
6076     CmdArgs.push_back("-fno-autolink");
6077 
6078   // Add in -fdebug-compilation-dir if necessary.
6079   const char *DebugCompilationDir =
6080       addDebugCompDirArg(Args, CmdArgs, D.getVFS());
6081 
6082   addDebugPrefixMapArg(D, TC, Args, CmdArgs);
6083 
6084   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6085   Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6086   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6087   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6088 
6089   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6090 
6091   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6092     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6093 
6094   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6095     CmdArgs.push_back("-fbracket-depth");
6096     CmdArgs.push_back(A->getValue());
6097   }
6098 
6099   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6100                                options::OPT_Wlarge_by_value_copy_def)) {
6101     if (A->getNumValues()) {
6102       StringRef bytes = A->getValue();
6103       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6104     } else
6105       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6106   }
6107 
6108   if (Args.hasArg(options::OPT_relocatable_pch))
6109     CmdArgs.push_back("-relocatable-pch");
6110 
6111   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6112     static const char *kCFABIs[] = {
6113       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6114     };
6115 
6116     if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6117       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6118     else
6119       A->render(Args, CmdArgs);
6120   }
6121 
6122   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6123     CmdArgs.push_back("-fconstant-string-class");
6124     CmdArgs.push_back(A->getValue());
6125   }
6126 
6127   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6128     CmdArgs.push_back("-ftabstop");
6129     CmdArgs.push_back(A->getValue());
6130   }
6131 
6132   Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6133                     options::OPT_fno_stack_size_section);
6134 
6135   if (Args.hasArg(options::OPT_fstack_usage)) {
6136     CmdArgs.push_back("-stack-usage-file");
6137 
6138     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6139       SmallString<128> OutputFilename(OutputOpt->getValue());
6140       llvm::sys::path::replace_extension(OutputFilename, "su");
6141       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6142     } else
6143       CmdArgs.push_back(
6144           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6145   }
6146 
6147   CmdArgs.push_back("-ferror-limit");
6148   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6149     CmdArgs.push_back(A->getValue());
6150   else
6151     CmdArgs.push_back("19");
6152 
6153   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6154   Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6155   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6156   Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6157   Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6158 
6159   // Pass -fmessage-length=.
6160   unsigned MessageLength = 0;
6161   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6162     StringRef V(A->getValue());
6163     if (V.getAsInteger(0, MessageLength))
6164       D.Diag(diag::err_drv_invalid_argument_to_option)
6165           << V << A->getOption().getName();
6166   } else {
6167     // If -fmessage-length=N was not specified, determine whether this is a
6168     // terminal and, if so, implicitly define -fmessage-length appropriately.
6169     MessageLength = llvm::sys::Process::StandardErrColumns();
6170   }
6171   if (MessageLength != 0)
6172     CmdArgs.push_back(
6173         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6174 
6175   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6176     CmdArgs.push_back(
6177         Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6178 
6179   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6180     CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6181                                          Twine(A->getValue(0))));
6182 
6183   // -fvisibility= and -fvisibility-ms-compat are of a piece.
6184   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6185                                      options::OPT_fvisibility_ms_compat)) {
6186     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6187       A->render(Args, CmdArgs);
6188     } else {
6189       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6190       CmdArgs.push_back("-fvisibility=hidden");
6191       CmdArgs.push_back("-ftype-visibility=default");
6192     }
6193   } else if (IsOpenMPDevice) {
6194     // When compiling for the OpenMP device we want protected visibility by
6195     // default. This prevents the device from accidentally preempting code on
6196     // the host, makes the system more robust, and improves performance.
6197     CmdArgs.push_back("-fvisibility=protected");
6198   }
6199 
6200   // PS4/PS5 process these options in addClangTargetOptions.
6201   if (!RawTriple.isPS()) {
6202     if (const Arg *A =
6203             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6204                             options::OPT_fno_visibility_from_dllstorageclass)) {
6205       if (A->getOption().matches(
6206               options::OPT_fvisibility_from_dllstorageclass)) {
6207         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6208         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6209         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6210         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6211         Args.AddLastArg(CmdArgs,
6212                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6213       }
6214     }
6215   }
6216 
6217   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6218                     options::OPT_fno_visibility_inlines_hidden, false))
6219     CmdArgs.push_back("-fvisibility-inlines-hidden");
6220 
6221   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6222                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
6223   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
6224   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6225 
6226   if (Args.hasFlag(options::OPT_fnew_infallible,
6227                    options::OPT_fno_new_infallible, false))
6228     CmdArgs.push_back("-fnew-infallible");
6229 
6230   if (Args.hasFlag(options::OPT_fno_operator_names,
6231                    options::OPT_foperator_names, false))
6232     CmdArgs.push_back("-fno-operator-names");
6233 
6234   // Forward -f (flag) options which we can pass directly.
6235   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6236   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6237   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6238   Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6239 
6240   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6241                    Triple.hasDefaultEmulatedTLS()))
6242     CmdArgs.push_back("-femulated-tls");
6243 
6244   Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6245                     options::OPT_fno_check_new);
6246 
6247   if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6248     // FIXME: There's no reason for this to be restricted to X86. The backend
6249     // code needs to be changed to include the appropriate function calls
6250     // automatically.
6251     if (!Triple.isX86() && !Triple.isAArch64())
6252       D.Diag(diag::err_drv_unsupported_opt_for_target)
6253           << A->getAsString(Args) << TripleStr;
6254   }
6255 
6256   // AltiVec-like language extensions aren't relevant for assembling.
6257   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6258     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6259 
6260   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6261   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6262 
6263   // Forward flags for OpenMP. We don't do this if the current action is an
6264   // device offloading action other than OpenMP.
6265   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6266                    options::OPT_fno_openmp, false) &&
6267       (JA.isDeviceOffloading(Action::OFK_None) ||
6268        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6269     switch (D.getOpenMPRuntime(Args)) {
6270     case Driver::OMPRT_OMP:
6271     case Driver::OMPRT_IOMP5:
6272       // Clang can generate useful OpenMP code for these two runtime libraries.
6273       CmdArgs.push_back("-fopenmp");
6274 
6275       // If no option regarding the use of TLS in OpenMP codegeneration is
6276       // given, decide a default based on the target. Otherwise rely on the
6277       // options and pass the right information to the frontend.
6278       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6279                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6280         CmdArgs.push_back("-fnoopenmp-use-tls");
6281       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6282                       options::OPT_fno_openmp_simd);
6283       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6284       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6285       if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6286                         options::OPT_fno_openmp_extensions, /*Default=*/true))
6287         CmdArgs.push_back("-fno-openmp-extensions");
6288       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6289       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6290       Args.AddAllArgs(CmdArgs,
6291                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6292       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6293                        options::OPT_fno_openmp_optimistic_collapse,
6294                        /*Default=*/false))
6295         CmdArgs.push_back("-fopenmp-optimistic-collapse");
6296 
6297       // When in OpenMP offloading mode with NVPTX target, forward
6298       // cuda-mode flag
6299       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6300                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6301         CmdArgs.push_back("-fopenmp-cuda-mode");
6302 
6303       // When in OpenMP offloading mode, enable debugging on the device.
6304       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6305       if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6306                        options::OPT_fno_openmp_target_debug, /*Default=*/false))
6307         CmdArgs.push_back("-fopenmp-target-debug");
6308 
6309       // When in OpenMP offloading mode, forward assumptions information about
6310       // thread and team counts in the device.
6311       if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6312                        options::OPT_fno_openmp_assume_teams_oversubscription,
6313                        /*Default=*/false))
6314         CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6315       if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6316                        options::OPT_fno_openmp_assume_threads_oversubscription,
6317                        /*Default=*/false))
6318         CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6319       if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6320         CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6321       if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6322         CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6323       if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6324         CmdArgs.push_back("-fopenmp-offload-mandatory");
6325       break;
6326     default:
6327       // By default, if Clang doesn't know how to generate useful OpenMP code
6328       // for a specific runtime library, we just don't pass the '-fopenmp' flag
6329       // down to the actual compilation.
6330       // FIXME: It would be better to have a mode which *only* omits IR
6331       // generation based on the OpenMP support so that we get consistent
6332       // semantic analysis, etc.
6333       break;
6334     }
6335   } else {
6336     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6337                     options::OPT_fno_openmp_simd);
6338     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6339     Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6340                        options::OPT_fno_openmp_extensions);
6341   }
6342 
6343   // Forward the new driver to change offloading code generation.
6344   if (Args.hasFlag(options::OPT_offload_new_driver,
6345                    options::OPT_no_offload_new_driver, false))
6346     CmdArgs.push_back("--offload-new-driver");
6347 
6348   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6349 
6350   const XRayArgs &XRay = TC.getXRayArgs();
6351   XRay.addArgs(TC, Args, CmdArgs, InputType);
6352 
6353   for (const auto &Filename :
6354        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6355     if (D.getVFS().exists(Filename))
6356       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6357     else
6358       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6359   }
6360 
6361   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6362     StringRef S0 = A->getValue(), S = S0;
6363     unsigned Size, Offset = 0;
6364     if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6365         !Triple.isX86())
6366       D.Diag(diag::err_drv_unsupported_opt_for_target)
6367           << A->getAsString(Args) << TripleStr;
6368     else if (S.consumeInteger(10, Size) ||
6369              (!S.empty() && (!S.consume_front(",") ||
6370                              S.consumeInteger(10, Offset) || !S.empty())))
6371       D.Diag(diag::err_drv_invalid_argument_to_option)
6372           << S0 << A->getOption().getName();
6373     else if (Size < Offset)
6374       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6375     else {
6376       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6377       CmdArgs.push_back(Args.MakeArgString(
6378           "-fpatchable-function-entry-offset=" + Twine(Offset)));
6379     }
6380   }
6381 
6382   Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6383 
6384   if (TC.SupportsProfiling()) {
6385     Args.AddLastArg(CmdArgs, options::OPT_pg);
6386 
6387     llvm::Triple::ArchType Arch = TC.getArch();
6388     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6389       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6390         A->render(Args, CmdArgs);
6391       else
6392         D.Diag(diag::err_drv_unsupported_opt_for_target)
6393             << A->getAsString(Args) << TripleStr;
6394     }
6395     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6396       if (Arch == llvm::Triple::systemz)
6397         A->render(Args, CmdArgs);
6398       else
6399         D.Diag(diag::err_drv_unsupported_opt_for_target)
6400             << A->getAsString(Args) << TripleStr;
6401     }
6402     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6403       if (Arch == llvm::Triple::systemz)
6404         A->render(Args, CmdArgs);
6405       else
6406         D.Diag(diag::err_drv_unsupported_opt_for_target)
6407             << A->getAsString(Args) << TripleStr;
6408     }
6409   }
6410 
6411   if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6412     if (TC.getTriple().isOSzOS()) {
6413       D.Diag(diag::err_drv_unsupported_opt_for_target)
6414           << A->getAsString(Args) << TripleStr;
6415     }
6416   }
6417   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6418     if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6419       D.Diag(diag::err_drv_unsupported_opt_for_target)
6420           << A->getAsString(Args) << TripleStr;
6421     }
6422   }
6423   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6424     if (A->getOption().matches(options::OPT_p)) {
6425       A->claim();
6426       if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6427         CmdArgs.push_back("-pg");
6428     }
6429   }
6430 
6431   // Reject AIX-specific link options on other targets.
6432   if (!TC.getTriple().isOSAIX()) {
6433     for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6434                                       options::OPT_mxcoff_build_id_EQ)) {
6435       D.Diag(diag::err_drv_unsupported_opt_for_target)
6436           << A->getSpelling() << TripleStr;
6437     }
6438   }
6439 
6440   if (Args.getLastArg(options::OPT_fapple_kext) ||
6441       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6442     CmdArgs.push_back("-fapple-kext");
6443 
6444   Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6445   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6446   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6447   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6448   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6449   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6450   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6451   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6452   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6453   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6454 
6455   if (const char *Name = C.getTimeTraceFile(&JA)) {
6456     CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
6457     Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6458   }
6459 
6460   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6461     CmdArgs.push_back("-ftrapv-handler");
6462     CmdArgs.push_back(A->getValue());
6463   }
6464 
6465   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6466 
6467   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
6468   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
6469   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
6470     if (A->getOption().matches(options::OPT_fwrapv))
6471       CmdArgs.push_back("-fwrapv");
6472   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
6473                                       options::OPT_fno_strict_overflow)) {
6474     if (A->getOption().matches(options::OPT_fno_strict_overflow))
6475       CmdArgs.push_back("-fwrapv");
6476   }
6477 
6478   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
6479                                options::OPT_fno_reroll_loops))
6480     if (A->getOption().matches(options::OPT_freroll_loops))
6481       CmdArgs.push_back("-freroll-loops");
6482 
6483   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6484                   options::OPT_fno_finite_loops);
6485 
6486   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6487   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6488                   options::OPT_fno_unroll_loops);
6489 
6490   Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6491 
6492   Args.AddLastArg(CmdArgs, options::OPT_pthread);
6493 
6494   Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6495                     options::OPT_mno_speculative_load_hardening);
6496 
6497   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6498   RenderSCPOptions(TC, Args, CmdArgs);
6499   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6500 
6501   Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6502 
6503   Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6504                     options::OPT_mno_stackrealign);
6505 
6506   if (Args.hasArg(options::OPT_mstack_alignment)) {
6507     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6508     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
6509   }
6510 
6511   if (Args.hasArg(options::OPT_mstack_probe_size)) {
6512     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6513 
6514     if (!Size.empty())
6515       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6516     else
6517       CmdArgs.push_back("-mstack-probe-size=0");
6518   }
6519 
6520   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6521                      options::OPT_mno_stack_arg_probe);
6522 
6523   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6524                                options::OPT_mno_restrict_it)) {
6525     if (A->getOption().matches(options::OPT_mrestrict_it)) {
6526       CmdArgs.push_back("-mllvm");
6527       CmdArgs.push_back("-arm-restrict-it");
6528     } else {
6529       CmdArgs.push_back("-mllvm");
6530       CmdArgs.push_back("-arm-default-it");
6531     }
6532   }
6533 
6534   // Forward -cl options to -cc1
6535   RenderOpenCLOptions(Args, CmdArgs, InputType);
6536 
6537   // Forward hlsl options to -cc1
6538   RenderHLSLOptions(Args, CmdArgs, InputType);
6539 
6540   if (IsHIP) {
6541     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6542                      options::OPT_fno_hip_new_launch_api, true))
6543       CmdArgs.push_back("-fhip-new-launch-api");
6544     if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
6545                      options::OPT_fno_gpu_allow_device_init, false))
6546       CmdArgs.push_back("-fgpu-allow-device-init");
6547     Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
6548                       options::OPT_fno_hip_kernel_arg_name);
6549   }
6550 
6551   if (IsCuda || IsHIP) {
6552     if (IsRDCMode)
6553       CmdArgs.push_back("-fgpu-rdc");
6554     if (Args.hasFlag(options::OPT_fgpu_defer_diag,
6555                      options::OPT_fno_gpu_defer_diag, false))
6556       CmdArgs.push_back("-fgpu-defer-diag");
6557     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6558                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
6559                      false)) {
6560       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6561       CmdArgs.push_back("-fgpu-defer-diag");
6562     }
6563   }
6564 
6565   // Forward -nogpulib to -cc1.
6566   if (Args.hasArg(options::OPT_nogpulib))
6567     CmdArgs.push_back("-nogpulib");
6568 
6569   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6570     CmdArgs.push_back(
6571         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6572   }
6573 
6574   if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6575     CmdArgs.push_back(
6576         Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6577 
6578   Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6579 
6580   // Forward -f options with positive and negative forms; we translate these by
6581   // hand.  Do not propagate PGO options to the GPU-side compilations as the
6582   // profile info is for the host-side compilation only.
6583   if (!(IsCudaDevice || IsHIPDevice)) {
6584     if (Arg *A = getLastProfileSampleUseArg(Args)) {
6585       auto *PGOArg = Args.getLastArg(
6586           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6587           options::OPT_fcs_profile_generate,
6588           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6589           options::OPT_fprofile_use_EQ);
6590       if (PGOArg)
6591         D.Diag(diag::err_drv_argument_not_allowed_with)
6592             << "SampleUse with PGO options";
6593 
6594       StringRef fname = A->getValue();
6595       if (!llvm::sys::fs::exists(fname))
6596         D.Diag(diag::err_drv_no_such_file) << fname;
6597       else
6598         A->render(Args, CmdArgs);
6599     }
6600     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6601 
6602     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6603                      options::OPT_fno_pseudo_probe_for_profiling, false)) {
6604       CmdArgs.push_back("-fpseudo-probe-for-profiling");
6605       // Enforce -funique-internal-linkage-names if it's not explicitly turned
6606       // off.
6607       if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6608                        options::OPT_fno_unique_internal_linkage_names, true))
6609         CmdArgs.push_back("-funique-internal-linkage-names");
6610     }
6611   }
6612   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
6613 
6614   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6615                      options::OPT_fno_assume_sane_operator_new);
6616 
6617   // -fblocks=0 is default.
6618   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6619                    TC.IsBlocksDefault()) ||
6620       (Args.hasArg(options::OPT_fgnu_runtime) &&
6621        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6622        !Args.hasArg(options::OPT_fno_blocks))) {
6623     CmdArgs.push_back("-fblocks");
6624 
6625     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6626       CmdArgs.push_back("-fblocks-runtime-optional");
6627   }
6628 
6629   // -fencode-extended-block-signature=1 is default.
6630   if (TC.IsEncodeExtendedBlockSignatureDefault())
6631     CmdArgs.push_back("-fencode-extended-block-signature");
6632 
6633   if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
6634                    options::OPT_fno_coro_aligned_allocation, false) &&
6635       types::isCXX(InputType))
6636     CmdArgs.push_back("-fcoro-aligned-allocation");
6637 
6638   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6639                   options::OPT_fno_double_square_bracket_attributes);
6640 
6641   Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
6642                      options::OPT_fno_access_control);
6643   Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
6644                      options::OPT_fno_elide_constructors);
6645 
6646   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6647 
6648   if (KernelOrKext || (types::isCXX(InputType) &&
6649                        (RTTIMode == ToolChain::RM_Disabled)))
6650     CmdArgs.push_back("-fno-rtti");
6651 
6652   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6653   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6654                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6655     CmdArgs.push_back("-fshort-enums");
6656 
6657   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6658 
6659   // -fuse-cxa-atexit is default.
6660   if (!Args.hasFlag(
6661           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6662           !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6663               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6664                RawTriple.hasEnvironment())) ||
6665       KernelOrKext)
6666     CmdArgs.push_back("-fno-use-cxa-atexit");
6667 
6668   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6669                    options::OPT_fno_register_global_dtors_with_atexit,
6670                    RawTriple.isOSDarwin() && !KernelOrKext))
6671     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6672 
6673   Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
6674                     options::OPT_fno_use_line_directives);
6675 
6676   // -fno-minimize-whitespace is default.
6677   if (Args.hasFlag(options::OPT_fminimize_whitespace,
6678                    options::OPT_fno_minimize_whitespace, false)) {
6679     types::ID InputType = Inputs[0].getType();
6680     if (!isDerivedFromC(InputType))
6681       D.Diag(diag::err_drv_minws_unsupported_input_type)
6682           << types::getTypeName(InputType);
6683     CmdArgs.push_back("-fminimize-whitespace");
6684   }
6685 
6686   // -fms-extensions=0 is default.
6687   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6688                    IsWindowsMSVC))
6689     CmdArgs.push_back("-fms-extensions");
6690 
6691   // -fms-compatibility=0 is default.
6692   bool IsMSVCCompat = Args.hasFlag(
6693       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6694       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6695                                      options::OPT_fno_ms_extensions, true)));
6696   if (IsMSVCCompat)
6697     CmdArgs.push_back("-fms-compatibility");
6698 
6699   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
6700       Args.hasArg(options::OPT_fms_runtime_lib_EQ))
6701     ProcessVSRuntimeLibrary(Args, CmdArgs);
6702 
6703   // Handle -fgcc-version, if present.
6704   VersionTuple GNUCVer;
6705   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6706     // Check that the version has 1 to 3 components and the minor and patch
6707     // versions fit in two decimal digits.
6708     StringRef Val = A->getValue();
6709     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6710     bool Invalid = GNUCVer.tryParse(Val);
6711     unsigned Minor = GNUCVer.getMinor().value_or(0);
6712     unsigned Patch = GNUCVer.getSubminor().value_or(0);
6713     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6714       D.Diag(diag::err_drv_invalid_value)
6715           << A->getAsString(Args) << A->getValue();
6716     }
6717   } else if (!IsMSVCCompat) {
6718     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6719     GNUCVer = VersionTuple(4, 2, 1);
6720   }
6721   if (!GNUCVer.empty()) {
6722     CmdArgs.push_back(
6723         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6724   }
6725 
6726   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6727   if (!MSVT.empty())
6728     CmdArgs.push_back(
6729         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6730 
6731   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6732   if (ImplyVCPPCVer) {
6733     StringRef LanguageStandard;
6734     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6735       Std = StdArg;
6736       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6737                              .Case("c11", "-std=c11")
6738                              .Case("c17", "-std=c17")
6739                              .Default("");
6740       if (LanguageStandard.empty())
6741         D.Diag(clang::diag::warn_drv_unused_argument)
6742             << StdArg->getAsString(Args);
6743     }
6744     CmdArgs.push_back(LanguageStandard.data());
6745   }
6746   if (ImplyVCPPCXXVer) {
6747     StringRef LanguageStandard;
6748     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6749       Std = StdArg;
6750       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6751                              .Case("c++14", "-std=c++14")
6752                              .Case("c++17", "-std=c++17")
6753                              .Case("c++20", "-std=c++20")
6754                              // TODO add c++23 and c++26 when MSVC supports it.
6755                              .Case("c++latest", "-std=c++26")
6756                              .Default("");
6757       if (LanguageStandard.empty())
6758         D.Diag(clang::diag::warn_drv_unused_argument)
6759             << StdArg->getAsString(Args);
6760     }
6761 
6762     if (LanguageStandard.empty()) {
6763       if (IsMSVC2015Compatible)
6764         LanguageStandard = "-std=c++14";
6765       else
6766         LanguageStandard = "-std=c++11";
6767     }
6768 
6769     CmdArgs.push_back(LanguageStandard.data());
6770   }
6771 
6772   Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
6773                     options::OPT_fno_borland_extensions);
6774 
6775   // -fno-declspec is default, except for PS4/PS5.
6776   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6777                    RawTriple.isPS()))
6778     CmdArgs.push_back("-fdeclspec");
6779   else if (Args.hasArg(options::OPT_fno_declspec))
6780     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6781 
6782   // -fthreadsafe-static is default, except for MSVC compatibility versions less
6783   // than 19.
6784   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6785                     options::OPT_fno_threadsafe_statics,
6786                     !types::isOpenCL(InputType) &&
6787                         (!IsWindowsMSVC || IsMSVC2015Compatible)))
6788     CmdArgs.push_back("-fno-threadsafe-statics");
6789 
6790   // -fno-delayed-template-parsing is default, except when targeting MSVC.
6791   // Many old Windows SDK versions require this to parse.
6792   // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
6793   // compiler. We should be able to disable this by default at some point.
6794   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6795                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
6796     CmdArgs.push_back("-fdelayed-template-parsing");
6797 
6798   // -fgnu-keywords default varies depending on language; only pass if
6799   // specified.
6800   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6801                   options::OPT_fno_gnu_keywords);
6802 
6803   Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
6804                     options::OPT_fno_gnu89_inline);
6805 
6806   const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
6807                                          options::OPT_finline_hint_functions,
6808                                          options::OPT_fno_inline_functions);
6809   if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
6810     if (A->getOption().matches(options::OPT_fno_inline))
6811       A->render(Args, CmdArgs);
6812   } else if (InlineArg) {
6813     InlineArg->render(Args, CmdArgs);
6814   }
6815 
6816   Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
6817 
6818   bool HaveModules =
6819       RenderModulesOptions(C, D, Args, Input, Output, Std, CmdArgs);
6820 
6821   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6822                    options::OPT_fno_pch_validate_input_files_content, false))
6823     CmdArgs.push_back("-fvalidate-ast-input-files-content");
6824   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6825                    options::OPT_fno_pch_instantiate_templates, false))
6826     CmdArgs.push_back("-fpch-instantiate-templates");
6827   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6828                    false))
6829     CmdArgs.push_back("-fmodules-codegen");
6830   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6831                    false))
6832     CmdArgs.push_back("-fmodules-debuginfo");
6833 
6834   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6835   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6836                     Input, CmdArgs);
6837 
6838   if (types::isObjC(Input.getType()) &&
6839       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6840                    options::OPT_fno_objc_encode_cxx_class_template_spec,
6841                    !Runtime.isNeXTFamily()))
6842     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6843 
6844   if (Args.hasFlag(options::OPT_fapplication_extension,
6845                    options::OPT_fno_application_extension, false))
6846     CmdArgs.push_back("-fapplication-extension");
6847 
6848   // Handle GCC-style exception args.
6849   bool EH = false;
6850   if (!C.getDriver().IsCLMode())
6851     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6852 
6853   // Handle exception personalities
6854   Arg *A = Args.getLastArg(
6855       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6856       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6857   if (A) {
6858     const Option &Opt = A->getOption();
6859     if (Opt.matches(options::OPT_fsjlj_exceptions))
6860       CmdArgs.push_back("-exception-model=sjlj");
6861     if (Opt.matches(options::OPT_fseh_exceptions))
6862       CmdArgs.push_back("-exception-model=seh");
6863     if (Opt.matches(options::OPT_fdwarf_exceptions))
6864       CmdArgs.push_back("-exception-model=dwarf");
6865     if (Opt.matches(options::OPT_fwasm_exceptions))
6866       CmdArgs.push_back("-exception-model=wasm");
6867   } else {
6868     switch (TC.GetExceptionModel(Args)) {
6869     default:
6870       break;
6871     case llvm::ExceptionHandling::DwarfCFI:
6872       CmdArgs.push_back("-exception-model=dwarf");
6873       break;
6874     case llvm::ExceptionHandling::SjLj:
6875       CmdArgs.push_back("-exception-model=sjlj");
6876       break;
6877     case llvm::ExceptionHandling::WinEH:
6878       CmdArgs.push_back("-exception-model=seh");
6879       break;
6880     }
6881   }
6882 
6883   // C++ "sane" operator new.
6884   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6885                      options::OPT_fno_assume_sane_operator_new);
6886 
6887   // -fassume-unique-vtables is on by default.
6888   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
6889                      options::OPT_fno_assume_unique_vtables);
6890 
6891   // -frelaxed-template-template-args is off by default, as it is a severe
6892   // breaking change until a corresponding change to template partial ordering
6893   // is provided.
6894   Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
6895                     options::OPT_fno_relaxed_template_template_args);
6896 
6897   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
6898   // most platforms.
6899   Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
6900                     options::OPT_fno_sized_deallocation);
6901 
6902   // -faligned-allocation is on by default in C++17 onwards and otherwise off
6903   // by default.
6904   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
6905                                options::OPT_fno_aligned_allocation,
6906                                options::OPT_faligned_new_EQ)) {
6907     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
6908       CmdArgs.push_back("-fno-aligned-allocation");
6909     else
6910       CmdArgs.push_back("-faligned-allocation");
6911   }
6912 
6913   // The default new alignment can be specified using a dedicated option or via
6914   // a GCC-compatible option that also turns on aligned allocation.
6915   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
6916                                options::OPT_faligned_new_EQ))
6917     CmdArgs.push_back(
6918         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
6919 
6920   // -fconstant-cfstrings is default, and may be subject to argument translation
6921   // on Darwin.
6922   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
6923                     options::OPT_fno_constant_cfstrings, true) ||
6924       !Args.hasFlag(options::OPT_mconstant_cfstrings,
6925                     options::OPT_mno_constant_cfstrings, true))
6926     CmdArgs.push_back("-fno-constant-cfstrings");
6927 
6928   Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
6929                     options::OPT_fno_pascal_strings);
6930 
6931   // Honor -fpack-struct= and -fpack-struct, if given. Note that
6932   // -fno-pack-struct doesn't apply to -fpack-struct=.
6933   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
6934     std::string PackStructStr = "-fpack-struct=";
6935     PackStructStr += A->getValue();
6936     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
6937   } else if (Args.hasFlag(options::OPT_fpack_struct,
6938                           options::OPT_fno_pack_struct, false)) {
6939     CmdArgs.push_back("-fpack-struct=1");
6940   }
6941 
6942   // Handle -fmax-type-align=N and -fno-type-align
6943   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
6944   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
6945     if (!SkipMaxTypeAlign) {
6946       std::string MaxTypeAlignStr = "-fmax-type-align=";
6947       MaxTypeAlignStr += A->getValue();
6948       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6949     }
6950   } else if (RawTriple.isOSDarwin()) {
6951     if (!SkipMaxTypeAlign) {
6952       std::string MaxTypeAlignStr = "-fmax-type-align=16";
6953       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6954     }
6955   }
6956 
6957   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
6958     CmdArgs.push_back("-Qn");
6959 
6960   // -fno-common is the default, set -fcommon only when that flag is set.
6961   Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
6962 
6963   // -fsigned-bitfields is default, and clang doesn't yet support
6964   // -funsigned-bitfields.
6965   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
6966                     options::OPT_funsigned_bitfields, true))
6967     D.Diag(diag::warn_drv_clang_unsupported)
6968         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
6969 
6970   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
6971   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
6972     D.Diag(diag::err_drv_clang_unsupported)
6973         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
6974 
6975   // -finput_charset=UTF-8 is default. Reject others
6976   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
6977     StringRef value = inputCharset->getValue();
6978     if (!value.equals_insensitive("utf-8"))
6979       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
6980                                           << value;
6981   }
6982 
6983   // -fexec_charset=UTF-8 is default. Reject others
6984   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
6985     StringRef value = execCharset->getValue();
6986     if (!value.equals_insensitive("utf-8"))
6987       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
6988                                           << value;
6989   }
6990 
6991   RenderDiagnosticsOptions(D, Args, CmdArgs);
6992 
6993   Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
6994                     options::OPT_fno_asm_blocks);
6995 
6996   Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
6997                      options::OPT_fno_gnu_inline_asm);
6998 
6999   // Enable vectorization per default according to the optimization level
7000   // selected. For optimization levels that want vectorization we use the alias
7001   // option to simplify the hasFlag logic.
7002   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
7003   OptSpecifier VectorizeAliasOption =
7004       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
7005   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
7006                    options::OPT_fno_vectorize, EnableVec))
7007     CmdArgs.push_back("-vectorize-loops");
7008 
7009   // -fslp-vectorize is enabled based on the optimization level selected.
7010   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
7011   OptSpecifier SLPVectAliasOption =
7012       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
7013   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
7014                    options::OPT_fno_slp_vectorize, EnableSLPVec))
7015     CmdArgs.push_back("-vectorize-slp");
7016 
7017   ParseMPreferVectorWidth(D, Args, CmdArgs);
7018 
7019   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7020   Args.AddLastArg(CmdArgs,
7021                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
7022 
7023   // -fdollars-in-identifiers default varies depending on platform and
7024   // language; only pass if specified.
7025   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7026                                options::OPT_fno_dollars_in_identifiers)) {
7027     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7028       CmdArgs.push_back("-fdollars-in-identifiers");
7029     else
7030       CmdArgs.push_back("-fno-dollars-in-identifiers");
7031   }
7032 
7033   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7034                     options::OPT_fno_apple_pragma_pack);
7035 
7036   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7037   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7038     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7039 
7040   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7041                                      options::OPT_fno_rewrite_imports, false);
7042   if (RewriteImports)
7043     CmdArgs.push_back("-frewrite-imports");
7044 
7045   Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7046                     options::OPT_fno_directives_only);
7047 
7048   // Enable rewrite includes if the user's asked for it or if we're generating
7049   // diagnostics.
7050   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7051   // nice to enable this when doing a crashdump for modules as well.
7052   if (Args.hasFlag(options::OPT_frewrite_includes,
7053                    options::OPT_fno_rewrite_includes, false) ||
7054       (C.isForDiagnostics() && !HaveModules))
7055     CmdArgs.push_back("-frewrite-includes");
7056 
7057   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7058   if (Arg *A = Args.getLastArg(options::OPT_traditional,
7059                                options::OPT_traditional_cpp)) {
7060     if (isa<PreprocessJobAction>(JA))
7061       CmdArgs.push_back("-traditional-cpp");
7062     else
7063       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7064   }
7065 
7066   Args.AddLastArg(CmdArgs, options::OPT_dM);
7067   Args.AddLastArg(CmdArgs, options::OPT_dD);
7068   Args.AddLastArg(CmdArgs, options::OPT_dI);
7069 
7070   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7071 
7072   // Handle serialized diagnostics.
7073   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7074     CmdArgs.push_back("-serialize-diagnostic-file");
7075     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7076   }
7077 
7078   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7079     CmdArgs.push_back("-fretain-comments-from-system-headers");
7080 
7081   // Forward -fcomment-block-commands to -cc1.
7082   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7083   // Forward -fparse-all-comments to -cc1.
7084   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7085 
7086   // Turn -fplugin=name.so into -load name.so
7087   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7088     CmdArgs.push_back("-load");
7089     CmdArgs.push_back(A->getValue());
7090     A->claim();
7091   }
7092 
7093   // Turn -fplugin-arg-pluginname-key=value into
7094   // -plugin-arg-pluginname key=value
7095   // GCC has an actual plugin_argument struct with key/value pairs that it
7096   // passes to its plugins, but we don't, so just pass it on as-is.
7097   //
7098   // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7099   // argument key are allowed to contain dashes. GCC therefore only
7100   // allows dashes in the key. We do the same.
7101   for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7102     auto ArgValue = StringRef(A->getValue());
7103     auto FirstDashIndex = ArgValue.find('-');
7104     StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7105     StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7106 
7107     A->claim();
7108     if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7109       if (PluginName.empty()) {
7110         D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7111       } else {
7112         D.Diag(diag::warn_drv_missing_plugin_arg)
7113             << PluginName << A->getAsString(Args);
7114       }
7115       continue;
7116     }
7117 
7118     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7119     CmdArgs.push_back(Args.MakeArgString(Arg));
7120   }
7121 
7122   // Forward -fpass-plugin=name.so to -cc1.
7123   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7124     CmdArgs.push_back(
7125         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7126     A->claim();
7127   }
7128 
7129   // Forward --vfsoverlay to -cc1.
7130   for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7131     CmdArgs.push_back("--vfsoverlay");
7132     CmdArgs.push_back(A->getValue());
7133     A->claim();
7134   }
7135 
7136   Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7137                     options::OPT_fno_safe_buffer_usage_suggestions);
7138 
7139   // Setup statistics file output.
7140   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7141   if (!StatsFile.empty()) {
7142     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7143     if (D.CCPrintInternalStats)
7144       CmdArgs.push_back("-stats-file-append");
7145   }
7146 
7147   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7148   // parser.
7149   for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7150     Arg->claim();
7151     // -finclude-default-header flag is for preprocessor,
7152     // do not pass it to other cc1 commands when save-temps is enabled
7153     if (C.getDriver().isSaveTempsEnabled() &&
7154         !isa<PreprocessJobAction>(JA)) {
7155       if (StringRef(Arg->getValue()) == "-finclude-default-header")
7156         continue;
7157     }
7158     CmdArgs.push_back(Arg->getValue());
7159   }
7160   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7161     A->claim();
7162 
7163     // We translate this by hand to the -cc1 argument, since nightly test uses
7164     // it and developers have been trained to spell it with -mllvm. Both
7165     // spellings are now deprecated and should be removed.
7166     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7167       CmdArgs.push_back("-disable-llvm-optzns");
7168     } else {
7169       A->render(Args, CmdArgs);
7170     }
7171   }
7172 
7173   // With -save-temps, we want to save the unoptimized bitcode output from the
7174   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7175   // by the frontend.
7176   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7177   // has slightly different breakdown between stages.
7178   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7179   // pristine IR generated by the frontend. Ideally, a new compile action should
7180   // be added so both IR can be captured.
7181   if ((C.getDriver().isSaveTempsEnabled() ||
7182        JA.isHostOffloading(Action::OFK_OpenMP)) &&
7183       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7184       isa<CompileJobAction>(JA))
7185     CmdArgs.push_back("-disable-llvm-passes");
7186 
7187   Args.AddAllArgs(CmdArgs, options::OPT_undef);
7188 
7189   const char *Exec = D.getClangProgramPath();
7190 
7191   // Optionally embed the -cc1 level arguments into the debug info or a
7192   // section, for build analysis.
7193   // Also record command line arguments into the debug info if
7194   // -grecord-gcc-switches options is set on.
7195   // By default, -gno-record-gcc-switches is set on and no recording.
7196   auto GRecordSwitches =
7197       Args.hasFlag(options::OPT_grecord_command_line,
7198                    options::OPT_gno_record_command_line, false);
7199   auto FRecordSwitches =
7200       Args.hasFlag(options::OPT_frecord_command_line,
7201                    options::OPT_fno_record_command_line, false);
7202   if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
7203       !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
7204     D.Diag(diag::err_drv_unsupported_opt_for_target)
7205         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
7206         << TripleStr;
7207   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
7208     ArgStringList OriginalArgs;
7209     for (const auto &Arg : Args)
7210       Arg->render(Args, OriginalArgs);
7211 
7212     SmallString<256> Flags;
7213     EscapeSpacesAndBackslashes(Exec, Flags);
7214     for (const char *OriginalArg : OriginalArgs) {
7215       SmallString<128> EscapedArg;
7216       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7217       Flags += " ";
7218       Flags += EscapedArg;
7219     }
7220     auto FlagsArgString = Args.MakeArgString(Flags);
7221     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7222       CmdArgs.push_back("-dwarf-debug-flags");
7223       CmdArgs.push_back(FlagsArgString);
7224     }
7225     if (FRecordSwitches) {
7226       CmdArgs.push_back("-record-command-line");
7227       CmdArgs.push_back(FlagsArgString);
7228     }
7229   }
7230 
7231   // Host-side offloading compilation receives all device-side outputs. Include
7232   // them in the host compilation depending on the target. If the host inputs
7233   // are not empty we use the new-driver scheme, otherwise use the old scheme.
7234   if ((IsCuda || IsHIP) && CudaDeviceInput) {
7235     CmdArgs.push_back("-fcuda-include-gpubinary");
7236     CmdArgs.push_back(CudaDeviceInput->getFilename());
7237   } else if (!HostOffloadingInputs.empty()) {
7238     if ((IsCuda || IsHIP) && !IsRDCMode) {
7239       assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7240       CmdArgs.push_back("-fcuda-include-gpubinary");
7241       CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7242     } else {
7243       for (const InputInfo Input : HostOffloadingInputs)
7244         CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7245                                              TC.getInputFilename(Input)));
7246     }
7247   }
7248 
7249   if (IsCuda) {
7250     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7251                      options::OPT_fno_cuda_short_ptr, false))
7252       CmdArgs.push_back("-fcuda-short-ptr");
7253   }
7254 
7255   if (IsCuda || IsHIP) {
7256     // Determine the original source input.
7257     const Action *SourceAction = &JA;
7258     while (SourceAction->getKind() != Action::InputClass) {
7259       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7260       SourceAction = SourceAction->getInputs()[0];
7261     }
7262     auto CUID = cast<InputAction>(SourceAction)->getId();
7263     if (!CUID.empty())
7264       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7265   }
7266 
7267   if (IsHIP) {
7268     CmdArgs.push_back("-fcuda-allow-variadic-functions");
7269     Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7270   }
7271 
7272   if (IsCudaDevice || IsHIPDevice) {
7273     StringRef InlineThresh =
7274         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7275     if (!InlineThresh.empty()) {
7276       std::string ArgStr =
7277           std::string("-inline-threshold=") + InlineThresh.str();
7278       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7279     }
7280   }
7281 
7282   if (IsHIPDevice)
7283     Args.addOptOutFlag(CmdArgs,
7284                        options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7285                        options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7286 
7287   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7288   // to specify the result of the compile phase on the host, so the meaningful
7289   // device declarations can be identified. Also, -fopenmp-is-target-device is
7290   // passed along to tell the frontend that it is generating code for a device,
7291   // so that only the relevant declarations are emitted.
7292   if (IsOpenMPDevice) {
7293     CmdArgs.push_back("-fopenmp-is-target-device");
7294     if (OpenMPDeviceInput) {
7295       CmdArgs.push_back("-fopenmp-host-ir-file-path");
7296       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7297     }
7298   }
7299 
7300   if (Triple.isAMDGPU()) {
7301     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7302 
7303     Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7304                       options::OPT_mno_unsafe_fp_atomics);
7305     Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7306                        options::OPT_mno_amdgpu_ieee);
7307   }
7308 
7309   // For all the host OpenMP offloading compile jobs we need to pass the targets
7310   // information using -fopenmp-targets= option.
7311   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
7312     SmallString<128> Targets("-fopenmp-targets=");
7313 
7314     SmallVector<std::string, 4> Triples;
7315     auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
7316     std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
7317                    [](auto TC) { return TC.second->getTripleString(); });
7318     CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
7319   }
7320 
7321   bool VirtualFunctionElimination =
7322       Args.hasFlag(options::OPT_fvirtual_function_elimination,
7323                    options::OPT_fno_virtual_function_elimination, false);
7324   if (VirtualFunctionElimination) {
7325     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7326     // in the future).
7327     if (LTOMode != LTOK_Full)
7328       D.Diag(diag::err_drv_argument_only_allowed_with)
7329           << "-fvirtual-function-elimination"
7330           << "-flto=full";
7331 
7332     CmdArgs.push_back("-fvirtual-function-elimination");
7333   }
7334 
7335   // VFE requires whole-program-vtables, and enables it by default.
7336   bool WholeProgramVTables = Args.hasFlag(
7337       options::OPT_fwhole_program_vtables,
7338       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7339   if (VirtualFunctionElimination && !WholeProgramVTables) {
7340     D.Diag(diag::err_drv_argument_not_allowed_with)
7341         << "-fno-whole-program-vtables"
7342         << "-fvirtual-function-elimination";
7343   }
7344 
7345   if (WholeProgramVTables) {
7346     // PS4 uses the legacy LTO API, which does not support this feature in
7347     // ThinLTO mode.
7348     bool IsPS4 = getToolChain().getTriple().isPS4();
7349 
7350     // Check if we passed LTO options but they were suppressed because this is a
7351     // device offloading action, or we passed device offload LTO options which
7352     // were suppressed because this is not the device offload action.
7353     // Check if we are using PS4 in regular LTO mode.
7354     // Otherwise, issue an error.
7355     if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
7356         (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7357       D.Diag(diag::err_drv_argument_only_allowed_with)
7358           << "-fwhole-program-vtables"
7359           << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7360 
7361     // Propagate -fwhole-program-vtables if this is an LTO compile.
7362     if (IsUsingLTO)
7363       CmdArgs.push_back("-fwhole-program-vtables");
7364   }
7365 
7366   bool DefaultsSplitLTOUnit =
7367       ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7368           (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7369       (!Triple.isPS4() && UnifiedLTO);
7370   bool SplitLTOUnit =
7371       Args.hasFlag(options::OPT_fsplit_lto_unit,
7372                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7373   if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7374     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7375                                                     << "-fsanitize=cfi";
7376   if (SplitLTOUnit)
7377     CmdArgs.push_back("-fsplit-lto-unit");
7378 
7379   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7380                                options::OPT_fno_global_isel)) {
7381     CmdArgs.push_back("-mllvm");
7382     if (A->getOption().matches(options::OPT_fglobal_isel)) {
7383       CmdArgs.push_back("-global-isel=1");
7384 
7385       // GISel is on by default on AArch64 -O0, so don't bother adding
7386       // the fallback remarks for it. Other combinations will add a warning of
7387       // some kind.
7388       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7389       bool IsOptLevelSupported = false;
7390 
7391       Arg *A = Args.getLastArg(options::OPT_O_Group);
7392       if (Triple.getArch() == llvm::Triple::aarch64) {
7393         if (!A || A->getOption().matches(options::OPT_O0))
7394           IsOptLevelSupported = true;
7395       }
7396       if (!IsArchSupported || !IsOptLevelSupported) {
7397         CmdArgs.push_back("-mllvm");
7398         CmdArgs.push_back("-global-isel-abort=2");
7399 
7400         if (!IsArchSupported)
7401           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7402         else
7403           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7404       }
7405     } else {
7406       CmdArgs.push_back("-global-isel=0");
7407     }
7408   }
7409 
7410   if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
7411      CmdArgs.push_back("-forder-file-instrumentation");
7412      // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
7413      // on, we need to pass these flags as linker flags and that will be handled
7414      // outside of the compiler.
7415      if (!IsUsingLTO) {
7416        CmdArgs.push_back("-mllvm");
7417        CmdArgs.push_back("-enable-order-file-instrumentation");
7418      }
7419   }
7420 
7421   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7422                                options::OPT_fno_force_enable_int128)) {
7423     if (A->getOption().matches(options::OPT_fforce_enable_int128))
7424       CmdArgs.push_back("-fforce-enable-int128");
7425   }
7426 
7427   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7428                     options::OPT_fno_keep_static_consts);
7429   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
7430                     options::OPT_fno_keep_persistent_storage_variables);
7431   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7432                     options::OPT_fno_complete_member_pointers);
7433   Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7434                      options::OPT_fno_cxx_static_destructors);
7435 
7436   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7437 
7438   if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7439                                options::OPT_mno_outline_atomics)) {
7440     // Option -moutline-atomics supported for AArch64 target only.
7441     if (!Triple.isAArch64()) {
7442       D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
7443           << Triple.getArchName() << A->getOption().getName();
7444     } else {
7445       if (A->getOption().matches(options::OPT_moutline_atomics)) {
7446         CmdArgs.push_back("-target-feature");
7447         CmdArgs.push_back("+outline-atomics");
7448       } else {
7449         CmdArgs.push_back("-target-feature");
7450         CmdArgs.push_back("-outline-atomics");
7451       }
7452     }
7453   } else if (Triple.isAArch64() &&
7454              getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7455     CmdArgs.push_back("-target-feature");
7456     CmdArgs.push_back("+outline-atomics");
7457   }
7458 
7459   if (Triple.isAArch64() &&
7460       (Args.hasArg(options::OPT_mno_fmv) ||
7461        getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7462     // Disable Function Multiversioning on AArch64 target.
7463     CmdArgs.push_back("-target-feature");
7464     CmdArgs.push_back("-fmv");
7465   }
7466 
7467   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7468                    (TC.getTriple().isOSBinFormatELF() ||
7469                     TC.getTriple().isOSBinFormatCOFF()) &&
7470                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7471                        !TC.getTriple().isOSNetBSD() &&
7472                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7473                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7474     CmdArgs.push_back("-faddrsig");
7475 
7476   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7477       (EH || UnwindTables || AsyncUnwindTables ||
7478        DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7479     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7480 
7481   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7482     std::string Str = A->getAsString(Args);
7483     if (!TC.getTriple().isOSBinFormatELF())
7484       D.Diag(diag::err_drv_unsupported_opt_for_target)
7485           << Str << TC.getTripleString();
7486     CmdArgs.push_back(Args.MakeArgString(Str));
7487   }
7488 
7489   // Add the output path to the object file for CodeView debug infos.
7490   if (EmitCodeView && Output.isFilename())
7491     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
7492                        Output.getFilename());
7493 
7494   // Add the "-o out -x type src.c" flags last. This is done primarily to make
7495   // the -cc1 command easier to edit when reproducing compiler crashes.
7496   if (Output.getType() == types::TY_Dependencies) {
7497     // Handled with other dependency code.
7498   } else if (Output.isFilename()) {
7499     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7500         Output.getType() == clang::driver::types::TY_IFS) {
7501       SmallString<128> OutputFilename(Output.getFilename());
7502       llvm::sys::path::replace_extension(OutputFilename, "ifs");
7503       CmdArgs.push_back("-o");
7504       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7505     } else {
7506       CmdArgs.push_back("-o");
7507       CmdArgs.push_back(Output.getFilename());
7508     }
7509   } else {
7510     assert(Output.isNothing() && "Invalid output.");
7511   }
7512 
7513   addDashXForInput(Args, Input, CmdArgs);
7514 
7515   ArrayRef<InputInfo> FrontendInputs = Input;
7516   if (IsExtractAPI)
7517     FrontendInputs = ExtractAPIInputs;
7518   else if (Input.isNothing())
7519     FrontendInputs = {};
7520 
7521   for (const InputInfo &Input : FrontendInputs) {
7522     if (Input.isFilename())
7523       CmdArgs.push_back(Input.getFilename());
7524     else
7525       Input.getInputArg().renderAsInput(Args, CmdArgs);
7526   }
7527 
7528   if (D.CC1Main && !D.CCGenDiagnostics) {
7529     // Invoke the CC1 directly in this process
7530     C.addCommand(std::make_unique<CC1Command>(
7531         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7532         Output, D.getPrependArg()));
7533   } else {
7534     C.addCommand(std::make_unique<Command>(
7535         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7536         Output, D.getPrependArg()));
7537   }
7538 
7539   // Make the compile command echo its inputs for /showFilenames.
7540   if (Output.getType() == types::TY_Object &&
7541       Args.hasFlag(options::OPT__SLASH_showFilenames,
7542                    options::OPT__SLASH_showFilenames_, false)) {
7543     C.getJobs().getJobs().back()->PrintInputFilenames = true;
7544   }
7545 
7546   if (Arg *A = Args.getLastArg(options::OPT_pg))
7547     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7548         !Args.hasArg(options::OPT_mfentry))
7549       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
7550                                                       << A->getAsString(Args);
7551 
7552   // Claim some arguments which clang supports automatically.
7553 
7554   // -fpch-preprocess is used with gcc to add a special marker in the output to
7555   // include the PCH file.
7556   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
7557 
7558   // Claim some arguments which clang doesn't support, but we don't
7559   // care to warn the user about.
7560   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
7561   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
7562 
7563   // Disable warnings for clang -E -emit-llvm foo.c
7564   Args.ClaimAllArgs(options::OPT_emit_llvm);
7565 }
7566 
7567 Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
7568     // CAUTION! The first constructor argument ("clang") is not arbitrary,
7569     // as it is for other tools. Some operations on a Tool actually test
7570     // whether that tool is Clang based on the Tool's Name as a string.
7571     : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
7572 
7573 Clang::~Clang() {}
7574 
7575 /// Add options related to the Objective-C runtime/ABI.
7576 ///
7577 /// Returns true if the runtime is non-fragile.
7578 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
7579                                       const InputInfoList &inputs,
7580                                       ArgStringList &cmdArgs,
7581                                       RewriteKind rewriteKind) const {
7582   // Look for the controlling runtime option.
7583   Arg *runtimeArg =
7584       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
7585                       options::OPT_fobjc_runtime_EQ);
7586 
7587   // Just forward -fobjc-runtime= to the frontend.  This supercedes
7588   // options about fragility.
7589   if (runtimeArg &&
7590       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
7591     ObjCRuntime runtime;
7592     StringRef value = runtimeArg->getValue();
7593     if (runtime.tryParse(value)) {
7594       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
7595           << value;
7596     }
7597     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
7598         (runtime.getVersion() >= VersionTuple(2, 0)))
7599       if (!getToolChain().getTriple().isOSBinFormatELF() &&
7600           !getToolChain().getTriple().isOSBinFormatCOFF()) {
7601         getToolChain().getDriver().Diag(
7602             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
7603           << runtime.getVersion().getMajor();
7604       }
7605 
7606     runtimeArg->render(args, cmdArgs);
7607     return runtime;
7608   }
7609 
7610   // Otherwise, we'll need the ABI "version".  Version numbers are
7611   // slightly confusing for historical reasons:
7612   //   1 - Traditional "fragile" ABI
7613   //   2 - Non-fragile ABI, version 1
7614   //   3 - Non-fragile ABI, version 2
7615   unsigned objcABIVersion = 1;
7616   // If -fobjc-abi-version= is present, use that to set the version.
7617   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
7618     StringRef value = abiArg->getValue();
7619     if (value == "1")
7620       objcABIVersion = 1;
7621     else if (value == "2")
7622       objcABIVersion = 2;
7623     else if (value == "3")
7624       objcABIVersion = 3;
7625     else
7626       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
7627   } else {
7628     // Otherwise, determine if we are using the non-fragile ABI.
7629     bool nonFragileABIIsDefault =
7630         (rewriteKind == RK_NonFragile ||
7631          (rewriteKind == RK_None &&
7632           getToolChain().IsObjCNonFragileABIDefault()));
7633     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
7634                      options::OPT_fno_objc_nonfragile_abi,
7635                      nonFragileABIIsDefault)) {
7636 // Determine the non-fragile ABI version to use.
7637 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
7638       unsigned nonFragileABIVersion = 1;
7639 #else
7640       unsigned nonFragileABIVersion = 2;
7641 #endif
7642 
7643       if (Arg *abiArg =
7644               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
7645         StringRef value = abiArg->getValue();
7646         if (value == "1")
7647           nonFragileABIVersion = 1;
7648         else if (value == "2")
7649           nonFragileABIVersion = 2;
7650         else
7651           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
7652               << value;
7653       }
7654 
7655       objcABIVersion = 1 + nonFragileABIVersion;
7656     } else {
7657       objcABIVersion = 1;
7658     }
7659   }
7660 
7661   // We don't actually care about the ABI version other than whether
7662   // it's non-fragile.
7663   bool isNonFragile = objcABIVersion != 1;
7664 
7665   // If we have no runtime argument, ask the toolchain for its default runtime.
7666   // However, the rewriter only really supports the Mac runtime, so assume that.
7667   ObjCRuntime runtime;
7668   if (!runtimeArg) {
7669     switch (rewriteKind) {
7670     case RK_None:
7671       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7672       break;
7673     case RK_Fragile:
7674       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7675       break;
7676     case RK_NonFragile:
7677       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7678       break;
7679     }
7680 
7681     // -fnext-runtime
7682   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7683     // On Darwin, make this use the default behavior for the toolchain.
7684     if (getToolChain().getTriple().isOSDarwin()) {
7685       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7686 
7687       // Otherwise, build for a generic macosx port.
7688     } else {
7689       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7690     }
7691 
7692     // -fgnu-runtime
7693   } else {
7694     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7695     // Legacy behaviour is to target the gnustep runtime if we are in
7696     // non-fragile mode or the GCC runtime in fragile mode.
7697     if (isNonFragile)
7698       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7699     else
7700       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7701   }
7702 
7703   if (llvm::any_of(inputs, [](const InputInfo &input) {
7704         return types::isObjC(input.getType());
7705       }))
7706     cmdArgs.push_back(
7707         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7708   return runtime;
7709 }
7710 
7711 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7712   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7713   I += HaveDash;
7714   return !HaveDash;
7715 }
7716 
7717 namespace {
7718 struct EHFlags {
7719   bool Synch = false;
7720   bool Asynch = false;
7721   bool NoUnwindC = false;
7722 };
7723 } // end anonymous namespace
7724 
7725 /// /EH controls whether to run destructor cleanups when exceptions are
7726 /// thrown.  There are three modifiers:
7727 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7728 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7729 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7730 /// - c: Assume that extern "C" functions are implicitly nounwind.
7731 /// The default is /EHs-c-, meaning cleanups are disabled.
7732 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7733   EHFlags EH;
7734 
7735   std::vector<std::string> EHArgs =
7736       Args.getAllArgValues(options::OPT__SLASH_EH);
7737   for (auto EHVal : EHArgs) {
7738     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7739       switch (EHVal[I]) {
7740       case 'a':
7741         EH.Asynch = maybeConsumeDash(EHVal, I);
7742         if (EH.Asynch)
7743           EH.Synch = false;
7744         continue;
7745       case 'c':
7746         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7747         continue;
7748       case 's':
7749         EH.Synch = maybeConsumeDash(EHVal, I);
7750         if (EH.Synch)
7751           EH.Asynch = false;
7752         continue;
7753       default:
7754         break;
7755       }
7756       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7757       break;
7758     }
7759   }
7760   // The /GX, /GX- flags are only processed if there are not /EH flags.
7761   // The default is that /GX is not specified.
7762   if (EHArgs.empty() &&
7763       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7764                    /*Default=*/false)) {
7765     EH.Synch = true;
7766     EH.NoUnwindC = true;
7767   }
7768 
7769   if (Args.hasArg(options::OPT__SLASH_kernel)) {
7770     EH.Synch = false;
7771     EH.NoUnwindC = false;
7772     EH.Asynch = false;
7773   }
7774 
7775   return EH;
7776 }
7777 
7778 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7779                            ArgStringList &CmdArgs,
7780                            llvm::codegenoptions::DebugInfoKind *DebugInfoKind,
7781                            bool *EmitCodeView) const {
7782   bool isNVPTX = getToolChain().getTriple().isNVPTX();
7783 
7784   ProcessVSRuntimeLibrary(Args, CmdArgs);
7785 
7786   if (Arg *ShowIncludes =
7787           Args.getLastArg(options::OPT__SLASH_showIncludes,
7788                           options::OPT__SLASH_showIncludes_user)) {
7789     CmdArgs.push_back("--show-includes");
7790     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7791       CmdArgs.push_back("-sys-header-deps");
7792   }
7793 
7794   // This controls whether or not we emit RTTI data for polymorphic types.
7795   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7796                    /*Default=*/false))
7797     CmdArgs.push_back("-fno-rtti-data");
7798 
7799   // This controls whether or not we emit stack-protector instrumentation.
7800   // In MSVC, Buffer Security Check (/GS) is on by default.
7801   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7802                                /*Default=*/true)) {
7803     CmdArgs.push_back("-stack-protector");
7804     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7805   }
7806 
7807   // Emit CodeView if -Z7 or -gline-tables-only are present.
7808   if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7,
7809                                           options::OPT_gline_tables_only)) {
7810     *EmitCodeView = true;
7811     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
7812       *DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
7813     else
7814       *DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
7815   } else {
7816     *EmitCodeView = false;
7817   }
7818 
7819   const Driver &D = getToolChain().getDriver();
7820 
7821   // This controls whether or not we perform JustMyCode instrumentation.
7822   if (Args.hasFlag(options::OPT__SLASH_JMC, options::OPT__SLASH_JMC_,
7823                    /*Default=*/false)) {
7824     if (*EmitCodeView &&
7825         *DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
7826       CmdArgs.push_back("-fjmc");
7827     else
7828       D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
7829                                                            << "'/Zi', '/Z7'";
7830   }
7831 
7832   EHFlags EH = parseClangCLEHFlags(D, Args);
7833   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7834     if (types::isCXX(InputType))
7835       CmdArgs.push_back("-fcxx-exceptions");
7836     CmdArgs.push_back("-fexceptions");
7837     if (EH.Asynch)
7838       CmdArgs.push_back("-fasync-exceptions");
7839   }
7840   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7841     CmdArgs.push_back("-fexternc-nounwind");
7842 
7843   // /EP should expand to -E -P.
7844   if (Args.hasArg(options::OPT__SLASH_EP)) {
7845     CmdArgs.push_back("-E");
7846     CmdArgs.push_back("-P");
7847   }
7848 
7849   unsigned VolatileOptionID;
7850   if (getToolChain().getTriple().isX86())
7851     VolatileOptionID = options::OPT__SLASH_volatile_ms;
7852   else
7853     VolatileOptionID = options::OPT__SLASH_volatile_iso;
7854 
7855   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
7856     VolatileOptionID = A->getOption().getID();
7857 
7858   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
7859     CmdArgs.push_back("-fms-volatile");
7860 
7861  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7862                   options::OPT__SLASH_Zc_dllexportInlines,
7863                   false)) {
7864   CmdArgs.push_back("-fno-dllexport-inlines");
7865  }
7866 
7867  if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
7868                   options::OPT__SLASH_Zc_wchar_t, false)) {
7869    CmdArgs.push_back("-fno-wchar");
7870  }
7871 
7872  if (Args.hasArg(options::OPT__SLASH_kernel)) {
7873    llvm::Triple::ArchType Arch = getToolChain().getArch();
7874    std::vector<std::string> Values =
7875        Args.getAllArgValues(options::OPT__SLASH_arch);
7876    if (!Values.empty()) {
7877      llvm::SmallSet<std::string, 4> SupportedArches;
7878      if (Arch == llvm::Triple::x86)
7879        SupportedArches.insert("IA32");
7880 
7881      for (auto &V : Values)
7882        if (!SupportedArches.contains(V))
7883          D.Diag(diag::err_drv_argument_not_allowed_with)
7884              << std::string("/arch:").append(V) << "/kernel";
7885    }
7886 
7887    CmdArgs.push_back("-fno-rtti");
7888    if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
7889      D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
7890                                                      << "/kernel";
7891  }
7892 
7893   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
7894   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
7895   if (MostGeneralArg && BestCaseArg)
7896     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7897         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
7898 
7899   if (MostGeneralArg) {
7900     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
7901     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
7902     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
7903 
7904     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
7905     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
7906     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
7907       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7908           << FirstConflict->getAsString(Args)
7909           << SecondConflict->getAsString(Args);
7910 
7911     if (SingleArg)
7912       CmdArgs.push_back("-fms-memptr-rep=single");
7913     else if (MultipleArg)
7914       CmdArgs.push_back("-fms-memptr-rep=multiple");
7915     else
7916       CmdArgs.push_back("-fms-memptr-rep=virtual");
7917   }
7918 
7919   // Parse the default calling convention options.
7920   if (Arg *CCArg =
7921           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
7922                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
7923                           options::OPT__SLASH_Gregcall)) {
7924     unsigned DCCOptId = CCArg->getOption().getID();
7925     const char *DCCFlag = nullptr;
7926     bool ArchSupported = !isNVPTX;
7927     llvm::Triple::ArchType Arch = getToolChain().getArch();
7928     switch (DCCOptId) {
7929     case options::OPT__SLASH_Gd:
7930       DCCFlag = "-fdefault-calling-conv=cdecl";
7931       break;
7932     case options::OPT__SLASH_Gr:
7933       ArchSupported = Arch == llvm::Triple::x86;
7934       DCCFlag = "-fdefault-calling-conv=fastcall";
7935       break;
7936     case options::OPT__SLASH_Gz:
7937       ArchSupported = Arch == llvm::Triple::x86;
7938       DCCFlag = "-fdefault-calling-conv=stdcall";
7939       break;
7940     case options::OPT__SLASH_Gv:
7941       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7942       DCCFlag = "-fdefault-calling-conv=vectorcall";
7943       break;
7944     case options::OPT__SLASH_Gregcall:
7945       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7946       DCCFlag = "-fdefault-calling-conv=regcall";
7947       break;
7948     }
7949 
7950     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
7951     if (ArchSupported && DCCFlag)
7952       CmdArgs.push_back(DCCFlag);
7953   }
7954 
7955   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
7956 
7957   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
7958     CmdArgs.push_back("-fdiagnostics-format");
7959     CmdArgs.push_back("msvc");
7960   }
7961 
7962   if (Args.hasArg(options::OPT__SLASH_kernel))
7963     CmdArgs.push_back("-fms-kernel");
7964 
7965   for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
7966     StringRef GuardArgs = A->getValue();
7967     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
7968     // "ehcont-".
7969     if (GuardArgs.equals_insensitive("cf")) {
7970       // Emit CFG instrumentation and the table of address-taken functions.
7971       CmdArgs.push_back("-cfguard");
7972     } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
7973       // Emit only the table of address-taken functions.
7974       CmdArgs.push_back("-cfguard-no-checks");
7975     } else if (GuardArgs.equals_insensitive("ehcont")) {
7976       // Emit EH continuation table.
7977       CmdArgs.push_back("-ehcontguard");
7978     } else if (GuardArgs.equals_insensitive("cf-") ||
7979                GuardArgs.equals_insensitive("ehcont-")) {
7980       // Do nothing, but we might want to emit a security warning in future.
7981     } else {
7982       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
7983     }
7984     A->claim();
7985   }
7986 }
7987 
7988 const char *Clang::getBaseInputName(const ArgList &Args,
7989                                     const InputInfo &Input) {
7990   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7991 }
7992 
7993 const char *Clang::getBaseInputStem(const ArgList &Args,
7994                                     const InputInfoList &Inputs) {
7995   const char *Str = getBaseInputName(Args, Inputs[0]);
7996 
7997   if (const char *End = strrchr(Str, '.'))
7998     return Args.MakeArgString(std::string(Str, End));
7999 
8000   return Str;
8001 }
8002 
8003 const char *Clang::getDependencyFileName(const ArgList &Args,
8004                                          const InputInfoList &Inputs) {
8005   // FIXME: Think about this more.
8006 
8007   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8008     SmallString<128> OutputFilename(OutputOpt->getValue());
8009     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8010     return Args.MakeArgString(OutputFilename);
8011   }
8012 
8013   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8014 }
8015 
8016 // Begin ClangAs
8017 
8018 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8019                                 ArgStringList &CmdArgs) const {
8020   StringRef CPUName;
8021   StringRef ABIName;
8022   const llvm::Triple &Triple = getToolChain().getTriple();
8023   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8024 
8025   CmdArgs.push_back("-target-abi");
8026   CmdArgs.push_back(ABIName.data());
8027 }
8028 
8029 void ClangAs::AddX86TargetArgs(const ArgList &Args,
8030                                ArgStringList &CmdArgs) const {
8031   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8032                         /*IsLTO=*/false);
8033 
8034   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8035     StringRef Value = A->getValue();
8036     if (Value == "intel" || Value == "att") {
8037       CmdArgs.push_back("-mllvm");
8038       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8039     } else {
8040       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8041           << A->getSpelling() << Value;
8042     }
8043   }
8044 }
8045 
8046 void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8047                                      ArgStringList &CmdArgs) const {
8048   CmdArgs.push_back("-target-abi");
8049   CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8050                                                getToolChain().getTriple())
8051                         .data());
8052 }
8053 
8054 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8055                                ArgStringList &CmdArgs) const {
8056   const llvm::Triple &Triple = getToolChain().getTriple();
8057   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8058 
8059   CmdArgs.push_back("-target-abi");
8060   CmdArgs.push_back(ABIName.data());
8061 
8062   if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8063                    options::OPT_mno_default_build_attributes, true)) {
8064       CmdArgs.push_back("-mllvm");
8065       CmdArgs.push_back("-riscv-add-build-attributes");
8066   }
8067 }
8068 
8069 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8070                            const InputInfo &Output, const InputInfoList &Inputs,
8071                            const ArgList &Args,
8072                            const char *LinkingOutput) const {
8073   ArgStringList CmdArgs;
8074 
8075   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8076   const InputInfo &Input = Inputs[0];
8077 
8078   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8079   const std::string &TripleStr = Triple.getTriple();
8080   const auto &D = getToolChain().getDriver();
8081 
8082   // Don't warn about "clang -w -c foo.s"
8083   Args.ClaimAllArgs(options::OPT_w);
8084   // and "clang -emit-llvm -c foo.s"
8085   Args.ClaimAllArgs(options::OPT_emit_llvm);
8086 
8087   claimNoWarnArgs(Args);
8088 
8089   // Invoke ourselves in -cc1as mode.
8090   //
8091   // FIXME: Implement custom jobs for internal actions.
8092   CmdArgs.push_back("-cc1as");
8093 
8094   // Add the "effective" target triple.
8095   CmdArgs.push_back("-triple");
8096   CmdArgs.push_back(Args.MakeArgString(TripleStr));
8097 
8098   getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
8099 
8100   // Set the output mode, we currently only expect to be used as a real
8101   // assembler.
8102   CmdArgs.push_back("-filetype");
8103   CmdArgs.push_back("obj");
8104 
8105   // Set the main file name, so that debug info works even with
8106   // -save-temps or preprocessed assembly.
8107   CmdArgs.push_back("-main-file-name");
8108   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8109 
8110   // Add the target cpu
8111   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8112   if (!CPU.empty()) {
8113     CmdArgs.push_back("-target-cpu");
8114     CmdArgs.push_back(Args.MakeArgString(CPU));
8115   }
8116 
8117   // Add the target features
8118   getTargetFeatures(D, Triple, Args, CmdArgs, true);
8119 
8120   // Ignore explicit -force_cpusubtype_ALL option.
8121   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8122 
8123   // Pass along any -I options so we get proper .include search paths.
8124   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8125 
8126   // Determine the original source input.
8127   auto FindSource = [](const Action *S) -> const Action * {
8128     while (S->getKind() != Action::InputClass) {
8129       assert(!S->getInputs().empty() && "unexpected root action!");
8130       S = S->getInputs()[0];
8131     }
8132     return S;
8133   };
8134   const Action *SourceAction = FindSource(&JA);
8135 
8136   // Forward -g and handle debug info related flags, assuming we are dealing
8137   // with an actual assembly file.
8138   bool WantDebug = false;
8139   Args.ClaimAllArgs(options::OPT_g_Group);
8140   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8141     WantDebug = !A->getOption().matches(options::OPT_g0) &&
8142                 !A->getOption().matches(options::OPT_ggdb0);
8143 
8144   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8145       llvm::codegenoptions::NoDebugInfo;
8146 
8147   // Add the -fdebug-compilation-dir flag if needed.
8148   const char *DebugCompilationDir =
8149       addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
8150 
8151   if (SourceAction->getType() == types::TY_Asm ||
8152       SourceAction->getType() == types::TY_PP_Asm) {
8153     // You might think that it would be ok to set DebugInfoKind outside of
8154     // the guard for source type, however there is a test which asserts
8155     // that some assembler invocation receives no -debug-info-kind,
8156     // and it's not clear whether that test is just overly restrictive.
8157     DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8158                                : llvm::codegenoptions::NoDebugInfo);
8159 
8160     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
8161                          CmdArgs);
8162 
8163     // Set the AT_producer to the clang version when using the integrated
8164     // assembler on assembly source files.
8165     CmdArgs.push_back("-dwarf-debug-producer");
8166     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8167 
8168     // And pass along -I options
8169     Args.AddAllArgs(CmdArgs, options::OPT_I);
8170   }
8171   const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8172   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8173                           llvm::DebuggerKind::Default);
8174   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8175   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
8176 
8177   // Handle -fPIC et al -- the relocation-model affects the assembler
8178   // for some targets.
8179   llvm::Reloc::Model RelocationModel;
8180   unsigned PICLevel;
8181   bool IsPIE;
8182   std::tie(RelocationModel, PICLevel, IsPIE) =
8183       ParsePICArgs(getToolChain(), Args);
8184 
8185   const char *RMName = RelocationModelName(RelocationModel);
8186   if (RMName) {
8187     CmdArgs.push_back("-mrelocation-model");
8188     CmdArgs.push_back(RMName);
8189   }
8190 
8191   // Optionally embed the -cc1as level arguments into the debug info, for build
8192   // analysis.
8193   if (getToolChain().UseDwarfDebugFlags()) {
8194     ArgStringList OriginalArgs;
8195     for (const auto &Arg : Args)
8196       Arg->render(Args, OriginalArgs);
8197 
8198     SmallString<256> Flags;
8199     const char *Exec = getToolChain().getDriver().getClangProgramPath();
8200     EscapeSpacesAndBackslashes(Exec, Flags);
8201     for (const char *OriginalArg : OriginalArgs) {
8202       SmallString<128> EscapedArg;
8203       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8204       Flags += " ";
8205       Flags += EscapedArg;
8206     }
8207     CmdArgs.push_back("-dwarf-debug-flags");
8208     CmdArgs.push_back(Args.MakeArgString(Flags));
8209   }
8210 
8211   // FIXME: Add -static support, once we have it.
8212 
8213   // Add target specific flags.
8214   switch (getToolChain().getArch()) {
8215   default:
8216     break;
8217 
8218   case llvm::Triple::mips:
8219   case llvm::Triple::mipsel:
8220   case llvm::Triple::mips64:
8221   case llvm::Triple::mips64el:
8222     AddMIPSTargetArgs(Args, CmdArgs);
8223     break;
8224 
8225   case llvm::Triple::x86:
8226   case llvm::Triple::x86_64:
8227     AddX86TargetArgs(Args, CmdArgs);
8228     break;
8229 
8230   case llvm::Triple::arm:
8231   case llvm::Triple::armeb:
8232   case llvm::Triple::thumb:
8233   case llvm::Triple::thumbeb:
8234     // This isn't in AddARMTargetArgs because we want to do this for assembly
8235     // only, not C/C++.
8236     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8237                      options::OPT_mno_default_build_attributes, true)) {
8238         CmdArgs.push_back("-mllvm");
8239         CmdArgs.push_back("-arm-add-build-attributes");
8240     }
8241     break;
8242 
8243   case llvm::Triple::aarch64:
8244   case llvm::Triple::aarch64_32:
8245   case llvm::Triple::aarch64_be:
8246     if (Args.hasArg(options::OPT_mmark_bti_property)) {
8247       CmdArgs.push_back("-mllvm");
8248       CmdArgs.push_back("-aarch64-mark-bti-property");
8249     }
8250     break;
8251 
8252   case llvm::Triple::loongarch32:
8253   case llvm::Triple::loongarch64:
8254     AddLoongArchTargetArgs(Args, CmdArgs);
8255     break;
8256 
8257   case llvm::Triple::riscv32:
8258   case llvm::Triple::riscv64:
8259     AddRISCVTargetArgs(Args, CmdArgs);
8260     break;
8261   }
8262 
8263   // Consume all the warning flags. Usually this would be handled more
8264   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8265   // doesn't handle that so rather than warning about unused flags that are
8266   // actually used, we'll lie by omission instead.
8267   // FIXME: Stop lying and consume only the appropriate driver flags
8268   Args.ClaimAllArgs(options::OPT_W_Group);
8269 
8270   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8271                                     getToolChain().getDriver());
8272 
8273   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8274 
8275   if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8276     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8277                        Output.getFilename());
8278 
8279   // Fixup any previous commands that use -object-file-name because when we
8280   // generated them, the final .obj name wasn't yet known.
8281   for (Command &J : C.getJobs()) {
8282     if (SourceAction != FindSource(&J.getSource()))
8283       continue;
8284     auto &JArgs = J.getArguments();
8285     for (unsigned I = 0; I < JArgs.size(); ++I) {
8286       if (StringRef(JArgs[I]).startswith("-object-file-name=") &&
8287           Output.isFilename()) {
8288         ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8289         addDebugObjectName(Args, NewArgs, DebugCompilationDir,
8290                            Output.getFilename());
8291         NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
8292         J.replaceArguments(NewArgs);
8293         break;
8294       }
8295     }
8296   }
8297 
8298   assert(Output.isFilename() && "Unexpected lipo output.");
8299   CmdArgs.push_back("-o");
8300   CmdArgs.push_back(Output.getFilename());
8301 
8302   const llvm::Triple &T = getToolChain().getTriple();
8303   Arg *A;
8304   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
8305       T.isOSBinFormatELF()) {
8306     CmdArgs.push_back("-split-dwarf-output");
8307     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8308   }
8309 
8310   if (Triple.isAMDGPU())
8311     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8312 
8313   assert(Input.isFilename() && "Invalid input.");
8314   CmdArgs.push_back(Input.getFilename());
8315 
8316   const char *Exec = getToolChain().getDriver().getClangProgramPath();
8317   if (D.CC1Main && !D.CCGenDiagnostics) {
8318     // Invoke cc1as directly in this process.
8319     C.addCommand(std::make_unique<CC1Command>(
8320         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8321         Output, D.getPrependArg()));
8322   } else {
8323     C.addCommand(std::make_unique<Command>(
8324         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8325         Output, D.getPrependArg()));
8326   }
8327 }
8328 
8329 // Begin OffloadBundler
8330 
8331 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8332                                   const InputInfo &Output,
8333                                   const InputInfoList &Inputs,
8334                                   const llvm::opt::ArgList &TCArgs,
8335                                   const char *LinkingOutput) const {
8336   // The version with only one output is expected to refer to a bundling job.
8337   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8338 
8339   // The bundling command looks like this:
8340   // clang-offload-bundler -type=bc
8341   //   -targets=host-triple,openmp-triple1,openmp-triple2
8342   //   -output=output_file
8343   //   -input=unbundle_file_host
8344   //   -input=unbundle_file_tgt1
8345   //   -input=unbundle_file_tgt2
8346 
8347   ArgStringList CmdArgs;
8348 
8349   // Get the type.
8350   CmdArgs.push_back(TCArgs.MakeArgString(
8351       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8352 
8353   assert(JA.getInputs().size() == Inputs.size() &&
8354          "Not have inputs for all dependence actions??");
8355 
8356   // Get the targets.
8357   SmallString<128> Triples;
8358   Triples += "-targets=";
8359   for (unsigned I = 0; I < Inputs.size(); ++I) {
8360     if (I)
8361       Triples += ',';
8362 
8363     // Find ToolChain for this input.
8364     Action::OffloadKind CurKind = Action::OFK_Host;
8365     const ToolChain *CurTC = &getToolChain();
8366     const Action *CurDep = JA.getInputs()[I];
8367 
8368     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8369       CurTC = nullptr;
8370       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8371         assert(CurTC == nullptr && "Expected one dependence!");
8372         CurKind = A->getOffloadingDeviceKind();
8373         CurTC = TC;
8374       });
8375     }
8376     Triples += Action::GetOffloadKindName(CurKind);
8377     Triples += '-';
8378     Triples += CurTC->getTriple().normalize();
8379     if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8380         !StringRef(CurDep->getOffloadingArch()).empty()) {
8381       Triples += '-';
8382       Triples += CurDep->getOffloadingArch();
8383     }
8384 
8385     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8386     //       with each toolchain.
8387     StringRef GPUArchName;
8388     if (CurKind == Action::OFK_OpenMP) {
8389       // Extract GPUArch from -march argument in TC argument list.
8390       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8391         auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8392         auto Arch = ArchStr.starts_with_insensitive("-march=");
8393         if (Arch) {
8394           GPUArchName = ArchStr.substr(7);
8395           Triples += "-";
8396           break;
8397         }
8398       }
8399       Triples += GPUArchName.str();
8400     }
8401   }
8402   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8403 
8404   // Get bundled file command.
8405   CmdArgs.push_back(
8406       TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8407 
8408   // Get unbundled files command.
8409   for (unsigned I = 0; I < Inputs.size(); ++I) {
8410     SmallString<128> UB;
8411     UB += "-input=";
8412 
8413     // Find ToolChain for this input.
8414     const ToolChain *CurTC = &getToolChain();
8415     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8416       CurTC = nullptr;
8417       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8418         assert(CurTC == nullptr && "Expected one dependence!");
8419         CurTC = TC;
8420       });
8421       UB += C.addTempFile(
8422           C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8423     } else {
8424       UB += CurTC->getInputFilename(Inputs[I]);
8425     }
8426     CmdArgs.push_back(TCArgs.MakeArgString(UB));
8427   }
8428   // All the inputs are encoded as commands.
8429   C.addCommand(std::make_unique<Command>(
8430       JA, *this, ResponseFileSupport::None(),
8431       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8432       CmdArgs, std::nullopt, Output));
8433 }
8434 
8435 void OffloadBundler::ConstructJobMultipleOutputs(
8436     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8437     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8438     const char *LinkingOutput) const {
8439   // The version with multiple outputs is expected to refer to a unbundling job.
8440   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8441 
8442   // The unbundling command looks like this:
8443   // clang-offload-bundler -type=bc
8444   //   -targets=host-triple,openmp-triple1,openmp-triple2
8445   //   -input=input_file
8446   //   -output=unbundle_file_host
8447   //   -output=unbundle_file_tgt1
8448   //   -output=unbundle_file_tgt2
8449   //   -unbundle
8450 
8451   ArgStringList CmdArgs;
8452 
8453   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8454   InputInfo Input = Inputs.front();
8455 
8456   // Get the type.
8457   CmdArgs.push_back(TCArgs.MakeArgString(
8458       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8459 
8460   // Get the targets.
8461   SmallString<128> Triples;
8462   Triples += "-targets=";
8463   auto DepInfo = UA.getDependentActionsInfo();
8464   for (unsigned I = 0; I < DepInfo.size(); ++I) {
8465     if (I)
8466       Triples += ',';
8467 
8468     auto &Dep = DepInfo[I];
8469     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8470     Triples += '-';
8471     Triples += Dep.DependentToolChain->getTriple().normalize();
8472     if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8473          Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8474         !Dep.DependentBoundArch.empty()) {
8475       Triples += '-';
8476       Triples += Dep.DependentBoundArch;
8477     }
8478     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8479     //       with each toolchain.
8480     StringRef GPUArchName;
8481     if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8482       // Extract GPUArch from -march argument in TC argument list.
8483       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8484         StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8485         auto Arch = ArchStr.starts_with_insensitive("-march=");
8486         if (Arch) {
8487           GPUArchName = ArchStr.substr(7);
8488           Triples += "-";
8489           break;
8490         }
8491       }
8492       Triples += GPUArchName.str();
8493     }
8494   }
8495 
8496   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8497 
8498   // Get bundled file command.
8499   CmdArgs.push_back(
8500       TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
8501 
8502   // Get unbundled files command.
8503   for (unsigned I = 0; I < Outputs.size(); ++I) {
8504     SmallString<128> UB;
8505     UB += "-output=";
8506     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
8507     CmdArgs.push_back(TCArgs.MakeArgString(UB));
8508   }
8509   CmdArgs.push_back("-unbundle");
8510   CmdArgs.push_back("-allow-missing-bundles");
8511 
8512   // All the inputs are encoded as commands.
8513   C.addCommand(std::make_unique<Command>(
8514       JA, *this, ResponseFileSupport::None(),
8515       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8516       CmdArgs, std::nullopt, Outputs));
8517 }
8518 
8519 void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
8520                                    const InputInfo &Output,
8521                                    const InputInfoList &Inputs,
8522                                    const llvm::opt::ArgList &Args,
8523                                    const char *LinkingOutput) const {
8524   ArgStringList CmdArgs;
8525 
8526   // Add the output file name.
8527   assert(Output.isFilename() && "Invalid output.");
8528   CmdArgs.push_back("-o");
8529   CmdArgs.push_back(Output.getFilename());
8530 
8531   // Create the inputs to bundle the needed metadata.
8532   for (const InputInfo &Input : Inputs) {
8533     const Action *OffloadAction = Input.getAction();
8534     const ToolChain *TC = OffloadAction->getOffloadingToolChain();
8535     const ArgList &TCArgs =
8536         C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
8537                               OffloadAction->getOffloadingDeviceKind());
8538     StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
8539     StringRef Arch = OffloadAction->getOffloadingArch()
8540                          ? OffloadAction->getOffloadingArch()
8541                          : TCArgs.getLastArgValue(options::OPT_march_EQ);
8542     StringRef Kind =
8543       Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
8544 
8545     ArgStringList Features;
8546     SmallVector<StringRef> FeatureArgs;
8547     getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
8548                       false);
8549     llvm::copy_if(Features, std::back_inserter(FeatureArgs),
8550                   [](StringRef Arg) { return !Arg.startswith("-target"); });
8551 
8552     if (TC->getTriple().isAMDGPU()) {
8553       for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
8554         FeatureArgs.emplace_back(
8555             Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
8556       }
8557     }
8558 
8559     // TODO: We need to pass in the full target-id and handle it properly in the
8560     // linker wrapper.
8561     SmallVector<std::string> Parts{
8562         "file=" + File.str(),
8563         "triple=" + TC->getTripleString(),
8564         "arch=" + getProcessorFromTargetID(TC->getTriple(), Arch).str(),
8565         "kind=" + Kind.str(),
8566     };
8567 
8568     if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
8569         TC->getTriple().isAMDGPU())
8570       for (StringRef Feature : FeatureArgs)
8571         Parts.emplace_back("feature=" + Feature.str());
8572 
8573     CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
8574   }
8575 
8576   C.addCommand(std::make_unique<Command>(
8577       JA, *this, ResponseFileSupport::None(),
8578       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8579       CmdArgs, Inputs, Output));
8580 }
8581 
8582 void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
8583                                  const InputInfo &Output,
8584                                  const InputInfoList &Inputs,
8585                                  const ArgList &Args,
8586                                  const char *LinkingOutput) const {
8587   const Driver &D = getToolChain().getDriver();
8588   const llvm::Triple TheTriple = getToolChain().getTriple();
8589   ArgStringList CmdArgs;
8590 
8591   // Pass the CUDA path to the linker wrapper tool.
8592   for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
8593     auto TCRange = C.getOffloadToolChains(Kind);
8594     for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
8595       const ToolChain *TC = I.second;
8596       if (TC->getTriple().isNVPTX()) {
8597         CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8598         if (CudaInstallation.isValid())
8599           CmdArgs.push_back(Args.MakeArgString(
8600               "--cuda-path=" + CudaInstallation.getInstallPath()));
8601         break;
8602       }
8603     }
8604   }
8605 
8606   if (D.isUsingLTO(/* IsOffload */ true)) {
8607     // Pass in the optimization level to use for LTO.
8608     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
8609       StringRef OOpt;
8610       if (A->getOption().matches(options::OPT_O4) ||
8611           A->getOption().matches(options::OPT_Ofast))
8612         OOpt = "3";
8613       else if (A->getOption().matches(options::OPT_O)) {
8614         OOpt = A->getValue();
8615         if (OOpt == "g")
8616           OOpt = "1";
8617         else if (OOpt == "s" || OOpt == "z")
8618           OOpt = "2";
8619       } else if (A->getOption().matches(options::OPT_O0))
8620         OOpt = "0";
8621       if (!OOpt.empty())
8622         CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
8623     }
8624   }
8625 
8626   CmdArgs.push_back(
8627       Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
8628   if (Args.hasArg(options::OPT_v))
8629     CmdArgs.push_back("--wrapper-verbose");
8630 
8631   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8632     if (!A->getOption().matches(options::OPT_g0))
8633       CmdArgs.push_back("--device-debug");
8634   }
8635 
8636   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8637     CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
8638 
8639   // Forward remarks passes to the LLVM backend in the wrapper.
8640   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8641     CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
8642                                          A->getValue()));
8643   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8644     CmdArgs.push_back(Args.MakeArgString(
8645         Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
8646   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8647     CmdArgs.push_back(Args.MakeArgString(
8648         Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
8649   if (Args.getLastArg(options::OPT_save_temps_EQ))
8650     CmdArgs.push_back("--save-temps");
8651 
8652   // Construct the link job so we can wrap around it.
8653   Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8654   const auto &LinkCommand = C.getJobs().getJobs().back();
8655 
8656   // Forward -Xoffload-linker<-triple> arguments to the device link job.
8657   for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
8658     StringRef Val = A->getValue(0);
8659     if (Val.empty())
8660       CmdArgs.push_back(
8661           Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
8662     else
8663       CmdArgs.push_back(Args.MakeArgString(
8664           "--device-linker=" +
8665           ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
8666           A->getValue(1)));
8667   }
8668   Args.ClaimAllArgs(options::OPT_Xoffload_linker);
8669 
8670   // Embed bitcode instead of an object in JIT mode.
8671   if (Args.hasFlag(options::OPT_fopenmp_target_jit,
8672                    options::OPT_fno_openmp_target_jit, false))
8673     CmdArgs.push_back("--embed-bitcode");
8674 
8675   // Forward `-mllvm` arguments to the LLVM invocations if present.
8676   for (Arg *A : Args.filtered(options::OPT_mllvm)) {
8677     CmdArgs.push_back("-mllvm");
8678     CmdArgs.push_back(A->getValue());
8679     A->claim();
8680   }
8681 
8682   // Add the linker arguments to be forwarded by the wrapper.
8683   CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
8684                                        LinkCommand->getExecutable()));
8685   CmdArgs.push_back("--");
8686   for (const char *LinkArg : LinkCommand->getArguments())
8687     CmdArgs.push_back(LinkArg);
8688 
8689   const char *Exec =
8690       Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
8691 
8692   // Replace the executable and arguments of the link job with the
8693   // wrapper.
8694   LinkCommand->replaceExecutable(Exec);
8695   LinkCommand->replaceArguments(CmdArgs);
8696 }
8697