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