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