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