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