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