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