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