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