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