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