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