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