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