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