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