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