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