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