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