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