1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
11 #include "Arch/AArch64.h"
13 #include "Arch/CSKY.h"
14 #include "Arch/LoongArch.h"
15 #include "Arch/M68k.h"
16 #include "Arch/Mips.h"
18 #include "Arch/RISCV.h"
19 #include "Arch/Sparc.h"
20 #include "Arch/SystemZ.h"
23 #include "CommonArgs.h"
27 #include "clang/Basic/CLWarnings.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/CodeGenOptions.h"
30 #include "clang/Basic/HeaderInclude.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/MakeSupport.h"
33 #include "clang/Basic/ObjCRuntime.h"
34 #include "clang/Basic/Version.h"
35 #include "clang/Config/config.h"
36 #include "clang/Driver/Action.h"
37 #include "clang/Driver/Distro.h"
38 #include "clang/Driver/DriverDiagnostic.h"
39 #include "clang/Driver/InputInfo.h"
40 #include "clang/Driver/Options.h"
41 #include "clang/Driver/SanitizerArgs.h"
42 #include "clang/Driver/Types.h"
43 #include "clang/Driver/XRayArgs.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Config/llvm-config.h"
47 #include "llvm/Option/ArgList.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Compression.h"
51 #include "llvm/Support/Error.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/Process.h"
55 #include "llvm/Support/RISCVISAInfo.h"
56 #include "llvm/Support/YAMLParser.h"
57 #include "llvm/TargetParser/ARMTargetParserCommon.h"
58 #include "llvm/TargetParser/Host.h"
59 #include "llvm/TargetParser/LoongArchTargetParser.h"
60 #include "llvm/TargetParser/RISCVTargetParser.h"
63 using namespace clang::driver;
64 using namespace clang::driver::tools;
65 using namespace clang;
66 using namespace llvm::opt;
68 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
69 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
70 options::OPT_fminimize_whitespace,
71 options::OPT_fno_minimize_whitespace)) {
72 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
73 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
74 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
75 << A->getBaseArg().getAsString(Args)
76 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
81 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
82 // In gcc, only ARM checks this, but it seems reasonable to check universally.
83 if (Args.hasArg(options::OPT_static))
85 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
86 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
90 // Add backslashes to escape spaces and other backslashes.
91 // This is used for the space-separated argument list specified with
92 // the -dwarf-debug-flags option.
93 static void EscapeSpacesAndBackslashes(const char *Arg,
94 SmallVectorImpl<char> &Res) {
108 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
109 /// offloading tool chain that is associated with the current action \a JA.
111 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
112 const ToolChain &RegularToolChain,
113 llvm::function_ref<void(const ToolChain &)> Work) {
114 // Apply Work on the current/regular tool chain.
115 Work(RegularToolChain);
117 // Apply Work on all the offloading tool chains associated with the current
119 if (JA.isHostOffloading(Action::OFK_Cuda))
120 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
121 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
122 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
123 else if (JA.isHostOffloading(Action::OFK_HIP))
124 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
125 else if (JA.isDeviceOffloading(Action::OFK_HIP))
126 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
128 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
129 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
130 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
132 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
136 // TODO: Add support for other offloading programming models here.
140 /// This is a helper function for validating the optional refinement step
141 /// parameter in reciprocal argument strings. Return false if there is an error
142 /// parsing the refinement step. Otherwise, return true and set the Position
143 /// of the refinement step in the input string.
144 static bool getRefinementStep(StringRef In, const Driver &D,
145 const Arg &A, size_t &Position) {
146 const char RefinementStepToken = ':';
147 Position = In.find(RefinementStepToken);
148 if (Position != StringRef::npos) {
149 StringRef Option = A.getOption().getName();
150 StringRef RefStep = In.substr(Position + 1);
151 // Allow exactly one numeric character for the additional refinement
152 // step parameter. This is reasonable for all currently-supported
153 // operations and architectures because we would expect that a larger value
154 // of refinement steps would cause the estimate "optimization" to
155 // under-perform the native operation. Also, if the estimate does not
156 // converge quickly, it probably will not ever converge, so further
157 // refinement steps will not produce a better answer.
158 if (RefStep.size() != 1) {
159 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
162 char RefStepChar = RefStep[0];
163 if (RefStepChar < '0' || RefStepChar > '9') {
164 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
171 /// The -mrecip flag requires processing of many optional parameters.
172 static void ParseMRecip(const Driver &D, const ArgList &Args,
173 ArgStringList &OutStrings) {
174 StringRef DisabledPrefixIn = "!";
175 StringRef DisabledPrefixOut = "!";
176 StringRef EnabledPrefixOut = "";
177 StringRef Out = "-mrecip=";
179 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
183 unsigned NumOptions = A->getNumValues();
184 if (NumOptions == 0) {
185 // No option is the same as "all".
186 OutStrings.push_back(Args.MakeArgString(Out + "all"));
190 // Pass through "all", "none", or "default" with an optional refinement step.
191 if (NumOptions == 1) {
192 StringRef Val = A->getValue(0);
194 if (!getRefinementStep(Val, D, *A, RefStepLoc))
196 StringRef ValBase = Val.slice(0, RefStepLoc);
197 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
198 OutStrings.push_back(Args.MakeArgString(Out + Val));
203 // Each reciprocal type may be enabled or disabled individually.
204 // Check each input value for validity, concatenate them all back together,
207 llvm::StringMap<bool> OptionStrings;
208 OptionStrings.insert(std::make_pair("divd", false));
209 OptionStrings.insert(std::make_pair("divf", false));
210 OptionStrings.insert(std::make_pair("divh", false));
211 OptionStrings.insert(std::make_pair("vec-divd", false));
212 OptionStrings.insert(std::make_pair("vec-divf", false));
213 OptionStrings.insert(std::make_pair("vec-divh", false));
214 OptionStrings.insert(std::make_pair("sqrtd", false));
215 OptionStrings.insert(std::make_pair("sqrtf", false));
216 OptionStrings.insert(std::make_pair("sqrth", false));
217 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
218 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
219 OptionStrings.insert(std::make_pair("vec-sqrth", false));
221 for (unsigned i = 0; i != NumOptions; ++i) {
222 StringRef Val = A->getValue(i);
224 bool IsDisabled = Val.startswith(DisabledPrefixIn);
225 // Ignore the disablement token for string matching.
230 if (!getRefinementStep(Val, D, *A, RefStep))
233 StringRef ValBase = Val.slice(0, RefStep);
234 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
235 if (OptionIter == OptionStrings.end()) {
236 // Try again specifying float suffix.
237 OptionIter = OptionStrings.find(ValBase.str() + 'f');
238 if (OptionIter == OptionStrings.end()) {
239 // The input name did not match any known option string.
240 D.Diag(diag::err_drv_unknown_argument) << Val;
243 // The option was specified without a half or float or double suffix.
244 // Make sure that the double or half entry was not already specified.
245 // The float entry will be checked below.
246 if (OptionStrings[ValBase.str() + 'd'] ||
247 OptionStrings[ValBase.str() + 'h']) {
248 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
253 if (OptionIter->second == true) {
254 // Duplicate option specified.
255 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
259 // Mark the matched option as found. Do not allow duplicate specifiers.
260 OptionIter->second = true;
262 // If the precision was not specified, also mark the double and half entry
264 if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
265 OptionStrings[ValBase.str() + 'd'] = true;
266 OptionStrings[ValBase.str() + 'h'] = true;
269 // Build the output string.
270 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
271 Out = Args.MakeArgString(Out + Prefix + Val);
272 if (i != NumOptions - 1)
273 Out = Args.MakeArgString(Out + ",");
276 OutStrings.push_back(Args.MakeArgString(Out));
279 /// The -mprefer-vector-width option accepts either a positive integer
280 /// or the string "none".
281 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
282 ArgStringList &CmdArgs) {
283 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
287 StringRef Value = A->getValue();
288 if (Value == "none") {
289 CmdArgs.push_back("-mprefer-vector-width=none");
292 if (Value.getAsInteger(10, Width)) {
293 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
296 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
301 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
302 const llvm::Triple &Triple) {
303 // We use the zero-cost exception tables for Objective-C if the non-fragile
304 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
306 if (runtime.isNonFragile())
309 if (!Triple.isMacOSX())
312 return (!Triple.isMacOSXVersionLT(10, 5) &&
313 (Triple.getArch() == llvm::Triple::x86_64 ||
314 Triple.getArch() == llvm::Triple::arm));
317 /// Adds exception related arguments to the driver command arguments. There's a
318 /// main flag, -fexceptions and also language specific flags to enable/disable
319 /// C++ and Objective-C exceptions. This makes it possible to for example
320 /// disable C++ exceptions but enable Objective-C exceptions.
321 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
322 const ToolChain &TC, bool KernelOrKext,
323 const ObjCRuntime &objcRuntime,
324 ArgStringList &CmdArgs) {
325 const llvm::Triple &Triple = TC.getTriple();
328 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
329 // arguments now to avoid warnings about unused arguments.
330 Args.ClaimAllArgs(options::OPT_fexceptions);
331 Args.ClaimAllArgs(options::OPT_fno_exceptions);
332 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
333 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
334 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
335 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
336 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
337 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
341 // See if the user explicitly enabled exceptions.
342 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
345 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
346 options::OPT_fno_async_exceptions, false);
348 CmdArgs.push_back("-fasync-exceptions");
352 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
353 // is not necessarily sensible, but follows GCC.
354 if (types::isObjC(InputType) &&
355 Args.hasFlag(options::OPT_fobjc_exceptions,
356 options::OPT_fno_objc_exceptions, true)) {
357 CmdArgs.push_back("-fobjc-exceptions");
359 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
362 if (types::isCXX(InputType)) {
363 // Disable C++ EH by default on XCore and PS4/PS5.
364 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
365 !Triple.isPS() && !Triple.isDriverKit();
366 Arg *ExceptionArg = Args.getLastArg(
367 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
368 options::OPT_fexceptions, options::OPT_fno_exceptions);
370 CXXExceptionsEnabled =
371 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
372 ExceptionArg->getOption().matches(options::OPT_fexceptions);
374 if (CXXExceptionsEnabled) {
375 CmdArgs.push_back("-fcxx-exceptions");
381 // OPT_fignore_exceptions means exception could still be thrown,
382 // but no clean up or catch would happen in current module.
383 // So we do not set EH to false.
384 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
387 CmdArgs.push_back("-fexceptions");
391 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
392 const JobAction &JA) {
394 if (TC.getTriple().isOSDarwin()) {
395 // The native darwin assembler doesn't support the linker_option directives,
396 // so we disable them if we think the .s file will be passed to it.
397 Default = TC.useIntegratedAs();
399 // The linker_option directives are intended for host compilation.
400 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
401 JA.isDeviceOffloading(Action::OFK_HIP))
403 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
407 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
408 switch (Triple.getArch()){
411 case llvm::Triple::arm:
412 case llvm::Triple::thumb:
413 // ARM Darwin targets require a frame pointer to be always present to aid
414 // offline debugging via backtraces.
415 return Triple.isOSDarwin();
419 static bool useFramePointerForTargetByDefault(const ArgList &Args,
420 const llvm::Triple &Triple) {
421 if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
424 if (Triple.isAndroid()) {
425 switch (Triple.getArch()) {
426 case llvm::Triple::aarch64:
427 case llvm::Triple::arm:
428 case llvm::Triple::armeb:
429 case llvm::Triple::thumb:
430 case llvm::Triple::thumbeb:
431 case llvm::Triple::riscv64:
438 switch (Triple.getArch()) {
439 case llvm::Triple::xcore:
440 case llvm::Triple::wasm32:
441 case llvm::Triple::wasm64:
442 case llvm::Triple::msp430:
443 // XCore never wants frame pointers, regardless of OS.
444 // WebAssembly never wants frame pointers.
446 case llvm::Triple::ppc:
447 case llvm::Triple::ppcle:
448 case llvm::Triple::ppc64:
449 case llvm::Triple::ppc64le:
450 case llvm::Triple::riscv32:
451 case llvm::Triple::riscv64:
452 case llvm::Triple::sparc:
453 case llvm::Triple::sparcel:
454 case llvm::Triple::sparcv9:
455 case llvm::Triple::amdgcn:
456 case llvm::Triple::r600:
457 case llvm::Triple::csky:
458 case llvm::Triple::loongarch32:
459 case llvm::Triple::loongarch64:
460 return !areOptimizationsEnabled(Args);
465 if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
466 return !areOptimizationsEnabled(Args);
469 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
471 switch (Triple.getArch()) {
472 // Don't use a frame pointer on linux if optimizing for certain targets.
473 case llvm::Triple::arm:
474 case llvm::Triple::armeb:
475 case llvm::Triple::thumb:
476 case llvm::Triple::thumbeb:
477 case llvm::Triple::mips64:
478 case llvm::Triple::mips64el:
479 case llvm::Triple::mips:
480 case llvm::Triple::mipsel:
481 case llvm::Triple::systemz:
482 case llvm::Triple::x86:
483 case llvm::Triple::x86_64:
484 return !areOptimizationsEnabled(Args);
490 if (Triple.isOSWindows()) {
491 switch (Triple.getArch()) {
492 case llvm::Triple::x86:
493 return !areOptimizationsEnabled(Args);
494 case llvm::Triple::x86_64:
495 return Triple.isOSBinFormatMachO();
496 case llvm::Triple::arm:
497 case llvm::Triple::thumb:
498 // Windows on ARM builds with FPO disabled to aid fast stack walking
501 // All other supported Windows ISAs use xdata unwind information, so frame
502 // pointers are not generally useful.
510 static CodeGenOptions::FramePointerKind
511 getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
514 // 00) leaf retained, non-leaf retained
515 // 01) leaf retained, non-leaf omitted (this is invalid)
516 // 10) leaf omitted, non-leaf retained
517 // (what -momit-leaf-frame-pointer was designed for)
518 // 11) leaf omitted, non-leaf omitted
520 // "omit" options taking precedence over "no-omit" options is the only way
521 // to make 3 valid states representable
522 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
523 options::OPT_fno_omit_frame_pointer);
524 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
526 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
528 Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
529 options::OPT_mno_omit_leaf_frame_pointer,
530 Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
531 (Triple.isAndroid() && Triple.isRISCV64()));
532 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
533 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
535 return CodeGenOptions::FramePointerKind::NonLeaf;
536 return CodeGenOptions::FramePointerKind::All;
538 return CodeGenOptions::FramePointerKind::None;
541 /// Add a CC1 option to specify the debug compilation directory.
542 static const char *addDebugCompDirArg(const ArgList &Args,
543 ArgStringList &CmdArgs,
544 const llvm::vfs::FileSystem &VFS) {
545 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
546 options::OPT_fdebug_compilation_dir_EQ)) {
547 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
548 CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
551 A->render(Args, CmdArgs);
552 } else if (llvm::ErrorOr<std::string> CWD =
553 VFS.getCurrentWorkingDirectory()) {
554 CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
556 StringRef Path(CmdArgs.back());
557 return Path.substr(Path.find('=') + 1).data();
560 static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
561 const char *DebugCompilationDir,
562 const char *OutputFileName) {
563 // No need to generate a value for -object-file-name if it was provided.
564 for (auto *Arg : Args.filtered(options::OPT_Xclang))
565 if (StringRef(Arg->getValue()).startswith("-object-file-name"))
568 if (Args.hasArg(options::OPT_object_file_name_EQ))
571 SmallString<128> ObjFileNameForDebug(OutputFileName);
572 if (ObjFileNameForDebug != "-" &&
573 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
574 (!DebugCompilationDir ||
575 llvm::sys::path::is_absolute(DebugCompilationDir))) {
576 // Make the path absolute in the debug infos like MSVC does.
577 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
579 // If the object file name is a relative path, then always use Windows
580 // backslash style as -object-file-name is used for embedding object file path
581 // in codeview and it can only be generated when targeting on Windows.
582 // Otherwise, just use native absolute path.
583 llvm::sys::path::Style Style =
584 llvm::sys::path::is_absolute(ObjFileNameForDebug)
585 ? llvm::sys::path::Style::native
586 : llvm::sys::path::Style::windows_backslash;
587 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
590 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
593 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
594 static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
595 const ArgList &Args, ArgStringList &CmdArgs) {
596 auto AddOneArg = [&](StringRef Map, StringRef Name) {
597 if (!Map.contains('='))
598 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
600 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
603 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
604 options::OPT_fdebug_prefix_map_EQ)) {
605 AddOneArg(A->getValue(), A->getOption().getName());
608 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
609 if (GlobalRemapEntry.empty())
611 AddOneArg(GlobalRemapEntry, "environment");
614 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
615 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
616 ArgStringList &CmdArgs) {
617 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
618 options::OPT_fmacro_prefix_map_EQ)) {
619 StringRef Map = A->getValue();
620 if (!Map.contains('='))
621 D.Diag(diag::err_drv_invalid_argument_to_option)
622 << Map << A->getOption().getName();
624 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
629 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
630 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
631 ArgStringList &CmdArgs) {
632 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
633 options::OPT_fcoverage_prefix_map_EQ)) {
634 StringRef Map = A->getValue();
635 if (!Map.contains('='))
636 D.Diag(diag::err_drv_invalid_argument_to_option)
637 << Map << A->getOption().getName();
639 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
644 /// Vectorize at all optimization levels greater than 1 except for -Oz.
645 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
647 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
648 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
649 if (A->getOption().matches(options::OPT_O4) ||
650 A->getOption().matches(options::OPT_Ofast))
653 if (A->getOption().matches(options::OPT_O0))
656 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
659 StringRef S(A->getValue());
663 // Don't vectorize -Oz, unless it's the slp vectorizer.
667 unsigned OptLevel = 0;
668 if (S.getAsInteger(10, OptLevel))
677 /// Add -x lang to \p CmdArgs for \p Input.
678 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
679 ArgStringList &CmdArgs) {
680 // When using -verify-pch, we don't want to provide the type
681 // 'precompiled-header' if it was inferred from the file extension
682 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
685 CmdArgs.push_back("-x");
686 if (Args.hasArg(options::OPT_rewrite_objc))
687 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
689 // Map the driver type to the frontend type. This is mostly an identity
690 // mapping, except that the distinction between module interface units
691 // and other source files does not exist at the frontend layer.
692 const char *ClangType;
693 switch (Input.getType()) {
694 case types::TY_CXXModule:
697 case types::TY_PP_CXXModule:
698 ClangType = "c++-cpp-output";
701 ClangType = types::getTypeName(Input.getType());
704 CmdArgs.push_back(ClangType);
708 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
709 const JobAction &JA, const InputInfo &Output,
710 const ArgList &Args, SanitizerArgs &SanArgs,
711 ArgStringList &CmdArgs) {
712 const Driver &D = TC.getDriver();
713 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
714 options::OPT_fprofile_generate_EQ,
715 options::OPT_fno_profile_generate);
716 if (PGOGenerateArg &&
717 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
718 PGOGenerateArg = nullptr;
720 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
722 auto *ProfileGenerateArg = Args.getLastArg(
723 options::OPT_fprofile_instr_generate,
724 options::OPT_fprofile_instr_generate_EQ,
725 options::OPT_fno_profile_instr_generate);
726 if (ProfileGenerateArg &&
727 ProfileGenerateArg->getOption().matches(
728 options::OPT_fno_profile_instr_generate))
729 ProfileGenerateArg = nullptr;
731 if (PGOGenerateArg && ProfileGenerateArg)
732 D.Diag(diag::err_drv_argument_not_allowed_with)
733 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
735 auto *ProfileUseArg = getLastProfileUseArg(Args);
737 if (PGOGenerateArg && ProfileUseArg)
738 D.Diag(diag::err_drv_argument_not_allowed_with)
739 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
741 if (ProfileGenerateArg && ProfileUseArg)
742 D.Diag(diag::err_drv_argument_not_allowed_with)
743 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
745 if (CSPGOGenerateArg && PGOGenerateArg) {
746 D.Diag(diag::err_drv_argument_not_allowed_with)
747 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
748 PGOGenerateArg = nullptr;
751 if (TC.getTriple().isOSAIX()) {
752 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
753 D.Diag(diag::err_drv_unsupported_opt_for_target)
754 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
757 if (ProfileGenerateArg) {
758 if (ProfileGenerateArg->getOption().matches(
759 options::OPT_fprofile_instr_generate_EQ))
760 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
761 ProfileGenerateArg->getValue()));
762 // The default is to use Clang Instrumentation.
763 CmdArgs.push_back("-fprofile-instrument=clang");
764 if (TC.getTriple().isWindowsMSVCEnvironment()) {
765 // Add dependent lib for clang_rt.profile
766 CmdArgs.push_back(Args.MakeArgString(
767 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
771 Arg *PGOGenArg = nullptr;
772 if (PGOGenerateArg) {
773 assert(!CSPGOGenerateArg);
774 PGOGenArg = PGOGenerateArg;
775 CmdArgs.push_back("-fprofile-instrument=llvm");
777 if (CSPGOGenerateArg) {
778 assert(!PGOGenerateArg);
779 PGOGenArg = CSPGOGenerateArg;
780 CmdArgs.push_back("-fprofile-instrument=csllvm");
783 if (TC.getTriple().isWindowsMSVCEnvironment()) {
784 // Add dependent lib for clang_rt.profile
785 CmdArgs.push_back(Args.MakeArgString(
786 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
788 if (PGOGenArg->getOption().matches(
789 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
790 : options::OPT_fcs_profile_generate_EQ)) {
791 SmallString<128> Path(PGOGenArg->getValue());
792 llvm::sys::path::append(Path, "default_%m.profraw");
794 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
799 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
800 CmdArgs.push_back(Args.MakeArgString(
801 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
802 else if ((ProfileUseArg->getOption().matches(
803 options::OPT_fprofile_use_EQ) ||
804 ProfileUseArg->getOption().matches(
805 options::OPT_fprofile_instr_use))) {
806 SmallString<128> Path(
807 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
808 if (Path.empty() || llvm::sys::fs::is_directory(Path))
809 llvm::sys::path::append(Path, "default.profdata");
811 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
815 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
816 options::OPT_fno_test_coverage, false) ||
817 Args.hasArg(options::OPT_coverage);
818 bool EmitCovData = TC.needsGCovInstrumentation(Args);
820 if (Args.hasFlag(options::OPT_fcoverage_mapping,
821 options::OPT_fno_coverage_mapping, false)) {
822 if (!ProfileGenerateArg)
823 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
824 << "-fcoverage-mapping"
825 << "-fprofile-instr-generate";
827 CmdArgs.push_back("-fcoverage-mapping");
830 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
831 options::OPT_fcoverage_compilation_dir_EQ)) {
832 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
833 CmdArgs.push_back(Args.MakeArgString(
834 Twine("-fcoverage-compilation-dir=") + A->getValue()));
836 A->render(Args, CmdArgs);
837 } else if (llvm::ErrorOr<std::string> CWD =
838 D.getVFS().getCurrentWorkingDirectory()) {
839 CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
842 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
843 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
844 if (!Args.hasArg(options::OPT_coverage))
845 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
846 << "-fprofile-exclude-files="
849 StringRef v = Arg->getValue();
851 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
854 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
855 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
856 if (!Args.hasArg(options::OPT_coverage))
857 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
858 << "-fprofile-filter-files="
861 StringRef v = Arg->getValue();
862 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
865 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
866 StringRef Val = A->getValue();
867 if (Val == "atomic" || Val == "prefer-atomic")
868 CmdArgs.push_back("-fprofile-update=atomic");
869 else if (Val != "single")
870 D.Diag(diag::err_drv_unsupported_option_argument)
871 << A->getSpelling() << Val;
872 } else if (SanArgs.needsTsanRt()) {
873 CmdArgs.push_back("-fprofile-update=atomic");
876 int FunctionGroups = 1;
877 int SelectedFunctionGroup = 0;
878 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
879 StringRef Val = A->getValue();
880 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
881 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
884 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
885 StringRef Val = A->getValue();
886 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
887 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
888 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
890 if (FunctionGroups != 1)
891 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
892 Twine(FunctionGroups)));
893 if (SelectedFunctionGroup != 0)
894 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
895 Twine(SelectedFunctionGroup)));
897 // Leave -fprofile-dir= an unused argument unless .gcda emission is
898 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
899 // the flag used. There is no -fno-profile-dir, so the user has no
900 // targeted way to suppress the warning.
901 Arg *FProfileDir = nullptr;
902 if (Args.hasArg(options::OPT_fprofile_arcs) ||
903 Args.hasArg(options::OPT_coverage))
904 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
906 // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
907 // like we warn about -fsyntax-only -E.
908 (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
910 // Put the .gcno and .gcda files (if needed) next to the primary output file,
911 // or fall back to a file in the current directory for `clang -c --coverage
912 // d/a.c` in the absence of -o.
913 if (EmitCovNotes || EmitCovData) {
914 SmallString<128> CoverageFilename;
915 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
916 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
918 CoverageFilename = DumpDir->getValue();
919 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
920 } else if (Arg *FinalOutput =
921 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
922 CoverageFilename = FinalOutput->getValue();
923 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
924 CoverageFilename = FinalOutput->getValue();
926 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
928 if (llvm::sys::path::is_relative(CoverageFilename))
929 (void)D.getVFS().makeAbsolute(CoverageFilename);
930 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
932 CmdArgs.push_back("-coverage-notes-file");
933 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
938 SmallString<128> Gcno = std::move(CoverageFilename);
939 CoverageFilename = FProfileDir->getValue();
940 llvm::sys::path::append(CoverageFilename, Gcno);
942 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
943 CmdArgs.push_back("-coverage-data-file");
944 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
949 /// Check whether the given input tree contains any compilation actions.
950 static bool ContainsCompileAction(const Action *A) {
951 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
954 return llvm::any_of(A->inputs(), ContainsCompileAction);
957 /// Check if -relax-all should be passed to the internal assembler.
958 /// This is done by default when compiling non-assembler source with -O0.
959 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
960 bool RelaxDefault = true;
962 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
963 RelaxDefault = A->getOption().matches(options::OPT_O0);
966 RelaxDefault = false;
967 for (const auto &Act : C.getActions()) {
968 if (ContainsCompileAction(Act)) {
975 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
980 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
981 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
982 unsigned DwarfVersion,
983 llvm::DebuggerKind DebuggerTuning) {
984 addDebugInfoKind(CmdArgs, DebugInfoKind);
985 if (DwarfVersion > 0)
987 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
988 switch (DebuggerTuning) {
989 case llvm::DebuggerKind::GDB:
990 CmdArgs.push_back("-debugger-tuning=gdb");
992 case llvm::DebuggerKind::LLDB:
993 CmdArgs.push_back("-debugger-tuning=lldb");
995 case llvm::DebuggerKind::SCE:
996 CmdArgs.push_back("-debugger-tuning=sce");
998 case llvm::DebuggerKind::DBX:
999 CmdArgs.push_back("-debugger-tuning=dbx");
1006 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1007 const Driver &D, const ToolChain &TC) {
1008 assert(A && "Expected non-nullptr argument.");
1009 if (TC.supportsDebugInfoOption(A))
1011 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1012 << A->getAsString(Args) << TC.getTripleString();
1016 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1017 ArgStringList &CmdArgs,
1019 const ToolChain &TC) {
1020 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1023 if (checkDebugInfoOption(A, Args, D, TC)) {
1024 StringRef Value = A->getValue();
1025 if (Value == "none") {
1026 CmdArgs.push_back("--compress-debug-sections=none");
1027 } else if (Value == "zlib") {
1028 if (llvm::compression::zlib::isAvailable()) {
1030 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1032 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
1034 } else if (Value == "zstd") {
1035 if (llvm::compression::zstd::isAvailable()) {
1037 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1039 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
1042 D.Diag(diag::err_drv_unsupported_option_argument)
1043 << A->getSpelling() << Value;
1048 static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
1049 const ArgList &Args,
1050 ArgStringList &CmdArgs,
1051 bool IsCC1As = false) {
1052 // If no version was requested by the user, use the default value from the
1053 // back end. This is consistent with the value returned from
1054 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
1055 // requiring the corresponding llvm to have the AMDGPU target enabled,
1056 // provided the user (e.g. front end tests) can use the default.
1057 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
1058 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
1059 CmdArgs.insert(CmdArgs.begin() + 1,
1060 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1061 Twine(CodeObjVer)));
1062 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
1063 // -cc1as does not accept -mcode-object-version option.
1065 CmdArgs.insert(CmdArgs.begin() + 1,
1066 Args.MakeArgString(Twine("-mcode-object-version=") +
1067 Twine(CodeObjVer)));
1071 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1072 const Driver &D, const ArgList &Args,
1073 ArgStringList &CmdArgs,
1074 const InputInfo &Output,
1075 const InputInfoList &Inputs) const {
1076 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1078 CheckPreprocessingOptions(D, Args);
1080 Args.AddLastArg(CmdArgs, options::OPT_C);
1081 Args.AddLastArg(CmdArgs, options::OPT_CC);
1083 // Handle dependency file generation.
1084 Arg *ArgM = Args.getLastArg(options::OPT_MM);
1086 ArgM = Args.getLastArg(options::OPT_M);
1087 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1089 ArgMD = Args.getLastArg(options::OPT_MD);
1091 // -M and -MM imply -w.
1093 CmdArgs.push_back("-w");
1098 // Determine the output location.
1099 const char *DepFile;
1100 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1101 DepFile = MF->getValue();
1102 C.addFailureResultFile(DepFile, &JA);
1103 } else if (Output.getType() == types::TY_Dependencies) {
1104 DepFile = Output.getFilename();
1105 } else if (!ArgMD) {
1108 DepFile = getDependencyFileName(Args, Inputs);
1109 C.addFailureResultFile(DepFile, &JA);
1111 CmdArgs.push_back("-dependency-file");
1112 CmdArgs.push_back(DepFile);
1114 bool HasTarget = false;
1115 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1118 if (A->getOption().matches(options::OPT_MT)) {
1119 A->render(Args, CmdArgs);
1121 CmdArgs.push_back("-MT");
1122 SmallString<128> Quoted;
1123 quoteMakeTarget(A->getValue(), Quoted);
1124 CmdArgs.push_back(Args.MakeArgString(Quoted));
1128 // Add a default target if one wasn't specified.
1130 const char *DepTarget;
1132 // If user provided -o, that is the dependency target, except
1133 // when we are only generating a dependency file.
1134 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1135 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1136 DepTarget = OutputOpt->getValue();
1138 // Otherwise derive from the base input.
1140 // FIXME: This should use the computed output file location.
1141 SmallString<128> P(Inputs[0].getBaseInput());
1142 llvm::sys::path::replace_extension(P, "o");
1143 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1146 CmdArgs.push_back("-MT");
1147 SmallString<128> Quoted;
1148 quoteMakeTarget(DepTarget, Quoted);
1149 CmdArgs.push_back(Args.MakeArgString(Quoted));
1152 if (ArgM->getOption().matches(options::OPT_M) ||
1153 ArgM->getOption().matches(options::OPT_MD))
1154 CmdArgs.push_back("-sys-header-deps");
1155 if ((isa<PrecompileJobAction>(JA) &&
1156 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1157 Args.hasArg(options::OPT_fmodule_file_deps))
1158 CmdArgs.push_back("-module-file-deps");
1161 if (Args.hasArg(options::OPT_MG)) {
1162 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1163 ArgM->getOption().matches(options::OPT_MMD))
1164 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1165 CmdArgs.push_back("-MG");
1168 Args.AddLastArg(CmdArgs, options::OPT_MP);
1169 Args.AddLastArg(CmdArgs, options::OPT_MV);
1171 // Add offload include arguments specific for CUDA/HIP. This must happen
1172 // before we -I or -include anything else, because we must pick up the
1173 // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1174 // from e.g. /usr/local/include.
1175 if (JA.isOffloading(Action::OFK_Cuda))
1176 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1177 if (JA.isOffloading(Action::OFK_HIP))
1178 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1180 // If we are compiling for a GPU target we want to override the system headers
1181 // with ones created by the 'libc' project if present.
1182 if (!Args.hasArg(options::OPT_nostdinc) &&
1183 !Args.hasArg(options::OPT_nogpuinc) &&
1184 !Args.hasArg(options::OPT_nobuiltininc) &&
1185 (getToolChain().getTriple().isNVPTX() ||
1186 getToolChain().getTriple().isAMDGCN())) {
1188 // Without an offloading language we will include these headers directly.
1189 // Offloading languages will instead only use the declarations stored in
1190 // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1191 if (C.getActiveOffloadKinds() == Action::OFK_None) {
1192 SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
1193 llvm::sys::path::append(P, "include");
1194 llvm::sys::path::append(P, "gpu-none-llvm");
1195 CmdArgs.push_back("-c-isystem");
1196 CmdArgs.push_back(Args.MakeArgString(P));
1197 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1198 // TODO: CUDA / HIP include their own headers for some common functions
1199 // implemented here. We'll need to clean those up so they do not conflict.
1200 SmallString<128> P(D.ResourceDir);
1201 llvm::sys::path::append(P, "include");
1202 llvm::sys::path::append(P, "llvm_libc_wrappers");
1203 CmdArgs.push_back("-internal-isystem");
1204 CmdArgs.push_back(Args.MakeArgString(P));
1208 // If we are offloading to a target via OpenMP we need to include the
1209 // openmp_wrappers folder which contains alternative system headers.
1210 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1211 !Args.hasArg(options::OPT_nostdinc) &&
1212 !Args.hasArg(options::OPT_nogpuinc) &&
1213 (getToolChain().getTriple().isNVPTX() ||
1214 getToolChain().getTriple().isAMDGCN())) {
1215 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1216 // Add openmp_wrappers/* to our system include path. This lets us wrap
1217 // standard library headers.
1218 SmallString<128> P(D.ResourceDir);
1219 llvm::sys::path::append(P, "include");
1220 llvm::sys::path::append(P, "openmp_wrappers");
1221 CmdArgs.push_back("-internal-isystem");
1222 CmdArgs.push_back(Args.MakeArgString(P));
1225 CmdArgs.push_back("-include");
1226 CmdArgs.push_back("__clang_openmp_device_functions.h");
1229 // Add -i* options, and automatically translate to
1230 // -include-pch/-include-pth for transparent PCH support. It's
1231 // wonky, but we include looking for .gch so we can support seamless
1232 // replacement into a build system already set up to be generating
1235 if (getToolChain().getDriver().IsCLMode()) {
1236 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1237 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1238 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1239 JA.getKind() <= Action::AssembleJobClass) {
1240 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1241 // -fpch-instantiate-templates is the default when creating
1242 // precomp using /Yc
1243 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1244 options::OPT_fno_pch_instantiate_templates, true))
1245 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1247 if (YcArg || YuArg) {
1248 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1249 if (!isa<PrecompileJobAction>(JA)) {
1250 CmdArgs.push_back("-include-pch");
1251 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1252 C, !ThroughHeader.empty()
1254 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1257 if (ThroughHeader.empty()) {
1258 CmdArgs.push_back(Args.MakeArgString(
1259 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1262 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1267 bool RenderedImplicitInclude = false;
1268 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1269 if (A->getOption().matches(options::OPT_include) &&
1270 D.getProbePrecompiled()) {
1271 // Handling of gcc-style gch precompiled headers.
1272 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1273 RenderedImplicitInclude = true;
1275 bool FoundPCH = false;
1276 SmallString<128> P(A->getValue());
1277 // We want the files to have a name like foo.h.pch. Add a dummy extension
1278 // so that replace_extension does the right thing.
1280 llvm::sys::path::replace_extension(P, "pch");
1281 if (D.getVFS().exists(P))
1285 llvm::sys::path::replace_extension(P, "gch");
1286 if (D.getVFS().exists(P)) {
1292 if (IsFirstImplicitInclude) {
1294 CmdArgs.push_back("-include-pch");
1295 CmdArgs.push_back(Args.MakeArgString(P));
1298 // Ignore the PCH if not first on command line and emit warning.
1299 D.Diag(diag::warn_drv_pch_not_first_include) << P
1300 << A->getAsString(Args);
1303 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1304 // Handling of paths which must come late. These entries are handled by
1305 // the toolchain itself after the resource dir is inserted in the right
1307 // Do not claim the argument so that the use of the argument does not
1308 // silently go unnoticed on toolchains which do not honour the option.
1310 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1311 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1313 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1314 // This is used only by the driver. No need to pass to cc1.
1318 // Not translated, render as usual.
1320 A->render(Args, CmdArgs);
1323 Args.AddAllArgs(CmdArgs,
1324 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1325 options::OPT_F, options::OPT_index_header_map});
1327 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1329 // FIXME: There is a very unfortunate problem here, some troubled
1330 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1331 // really support that we would have to parse and then translate
1332 // those options. :(
1333 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1334 options::OPT_Xpreprocessor);
1336 // -I- is a deprecated GCC feature, reject it.
1337 if (Arg *A = Args.getLastArg(options::OPT_I_))
1338 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1340 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1341 // -isysroot to the CC1 invocation.
1342 StringRef sysroot = C.getSysRoot();
1343 if (sysroot != "") {
1344 if (!Args.hasArg(options::OPT_isysroot)) {
1345 CmdArgs.push_back("-isysroot");
1346 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1350 // Parse additional include paths from environment variables.
1351 // FIXME: We should probably sink the logic for handling these from the
1352 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1353 // CPATH - included following the user specified includes (but prior to
1354 // builtin and standard includes).
1355 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1356 // C_INCLUDE_PATH - system includes enabled when compiling C.
1357 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1358 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1359 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1360 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1361 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1362 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1363 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1365 // While adding the include arguments, we also attempt to retrieve the
1366 // arguments of related offloading toolchains or arguments that are specific
1367 // of an offloading programming model.
1369 // Add C++ include arguments, if needed.
1370 if (types::isCXX(Inputs[0].getType())) {
1371 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1372 forAllAssociatedToolChains(
1373 C, JA, getToolChain(),
1374 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1375 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1376 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1380 // Add system include arguments for all targets but IAMCU.
1382 forAllAssociatedToolChains(C, JA, getToolChain(),
1383 [&Args, &CmdArgs](const ToolChain &TC) {
1384 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1387 // For IAMCU add special include arguments.
1388 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1391 addMacroPrefixMapArg(D, Args, CmdArgs);
1392 addCoveragePrefixMapArg(D, Args, CmdArgs);
1394 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1395 options::OPT_fno_file_reproducible);
1397 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1398 CmdArgs.push_back("-source-date-epoch");
1399 CmdArgs.push_back(Args.MakeArgString(Epoch));
1403 // FIXME: Move to target hook.
1404 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1405 switch (Triple.getArch()) {
1409 case llvm::Triple::aarch64:
1410 case llvm::Triple::aarch64_32:
1411 case llvm::Triple::aarch64_be:
1412 case llvm::Triple::arm:
1413 case llvm::Triple::armeb:
1414 case llvm::Triple::thumb:
1415 case llvm::Triple::thumbeb:
1416 if (Triple.isOSDarwin() || Triple.isOSWindows())
1420 case llvm::Triple::ppc:
1421 case llvm::Triple::ppc64:
1422 if (Triple.isOSDarwin())
1426 case llvm::Triple::hexagon:
1427 case llvm::Triple::ppcle:
1428 case llvm::Triple::ppc64le:
1429 case llvm::Triple::riscv32:
1430 case llvm::Triple::riscv64:
1431 case llvm::Triple::systemz:
1432 case llvm::Triple::xcore:
1437 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1438 const ArgList &Args) {
1439 // Supported only on Darwin where we invoke the compiler multiple times
1440 // followed by an invocation to lipo.
1441 if (!Triple.isOSDarwin())
1443 // If more than one "-arch <arch>" is specified, we're targeting multiple
1444 // architectures resulting in a fat binary.
1445 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1448 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1449 const llvm::Triple &Triple) {
1450 // When enabling remarks, we need to error if:
1451 // * The remark file is specified but we're targeting multiple architectures,
1452 // which means more than one remark file is being generated.
1453 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1454 bool hasExplicitOutputFile =
1455 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1456 if (hasMultipleInvocations && hasExplicitOutputFile) {
1457 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1458 << "-foptimization-record-file";
1464 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1465 const llvm::Triple &Triple,
1466 const InputInfo &Input,
1467 const InputInfo &Output, const JobAction &JA) {
1468 StringRef Format = "yaml";
1469 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1470 Format = A->getValue();
1472 CmdArgs.push_back("-opt-record-file");
1474 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1476 CmdArgs.push_back(A->getValue());
1478 bool hasMultipleArchs =
1479 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1480 Args.getAllArgValues(options::OPT_arch).size() > 1;
1484 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1485 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1486 F = FinalOutput->getValue();
1488 if (Format != "yaml" && // For YAML, keep the original behavior.
1489 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1490 Output.isFilename())
1491 F = Output.getFilename();
1495 // Use the input filename.
1496 F = llvm::sys::path::stem(Input.getBaseInput());
1498 // If we're compiling for an offload architecture (i.e. a CUDA device),
1499 // we need to make the file name for the device compilation different
1500 // from the host compilation.
1501 if (!JA.isDeviceOffloading(Action::OFK_None) &&
1502 !JA.isDeviceOffloading(Action::OFK_Host)) {
1503 llvm::sys::path::replace_extension(F, "");
1504 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1505 Triple.normalize());
1507 F += JA.getOffloadingArch();
1511 // If we're having more than one "-arch", we should name the files
1512 // differently so that every cc1 invocation writes to a different file.
1513 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1514 // name from the triple.
1515 if (hasMultipleArchs) {
1516 // First, remember the extension.
1517 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1519 llvm::sys::path::replace_extension(F, "");
1520 // attach -<arch> to it.
1522 F += Triple.getArchName();
1523 // put back the extension.
1524 llvm::sys::path::replace_extension(F, OldExtension);
1527 SmallString<32> Extension;
1528 Extension += "opt.";
1529 Extension += Format;
1531 llvm::sys::path::replace_extension(F, Extension);
1532 CmdArgs.push_back(Args.MakeArgString(F));
1536 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1537 CmdArgs.push_back("-opt-record-passes");
1538 CmdArgs.push_back(A->getValue());
1541 if (!Format.empty()) {
1542 CmdArgs.push_back("-opt-record-format");
1543 CmdArgs.push_back(Format.data());
1547 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1548 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1549 options::OPT_fno_aapcs_bitfield_width, true))
1550 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1552 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1553 CmdArgs.push_back("-faapcs-bitfield-load");
1557 void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1558 const ArgList &Args, ArgStringList &CmdArgs) {
1559 // Select the ABI to use.
1560 // FIXME: Support -meabi.
1561 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1562 const char *ABIName = nullptr;
1563 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1564 ABIName = A->getValue();
1566 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1567 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1570 CmdArgs.push_back("-target-abi");
1571 CmdArgs.push_back(ABIName);
1574 void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1575 auto StrictAlignIter =
1576 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1577 return Arg == "+strict-align" || Arg == "-strict-align";
1579 if (StrictAlignIter != CmdArgs.rend() &&
1580 StringRef(*StrictAlignIter) == "+strict-align")
1581 CmdArgs.push_back("-Wunaligned-access");
1585 static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1586 ArgStringList &CmdArgs, bool isAArch64) {
1587 const Arg *A = isAArch64
1588 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1589 options::OPT_mbranch_protection_EQ)
1590 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1594 const Driver &D = TC.getDriver();
1595 const llvm::Triple &Triple = TC.getEffectiveTriple();
1596 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1597 D.Diag(diag::warn_incompatible_branch_protection_option)
1598 << Triple.getArchName();
1600 StringRef Scope, Key;
1601 bool IndirectBranches;
1603 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1604 Scope = A->getValue();
1605 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1606 D.Diag(diag::err_drv_unsupported_option_argument)
1607 << A->getSpelling() << Scope;
1609 IndirectBranches = false;
1612 llvm::ARM::ParsedBranchProtection PBP;
1613 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
1614 D.Diag(diag::err_drv_unsupported_option_argument)
1615 << A->getSpelling() << DiagMsg;
1616 if (!isAArch64 && PBP.Key == "b_key")
1617 D.Diag(diag::warn_unsupported_branch_protection)
1618 << "b-key" << A->getAsString(Args);
1621 IndirectBranches = PBP.BranchTargetEnforcement;
1625 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1626 if (!Scope.equals("none"))
1628 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1629 if (IndirectBranches)
1630 CmdArgs.push_back("-mbranch-target-enforce");
1633 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1634 ArgStringList &CmdArgs, bool KernelOrKext) const {
1635 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1637 // Determine floating point ABI from the options & target defaults.
1638 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1639 if (ABI == arm::FloatABI::Soft) {
1640 // Floating point operations and argument passing are soft.
1641 // FIXME: This changes CPP defines, we need -target-soft-float.
1642 CmdArgs.push_back("-msoft-float");
1643 CmdArgs.push_back("-mfloat-abi");
1644 CmdArgs.push_back("soft");
1645 } else if (ABI == arm::FloatABI::SoftFP) {
1646 // Floating point operations are hard, but argument passing is soft.
1647 CmdArgs.push_back("-mfloat-abi");
1648 CmdArgs.push_back("soft");
1650 // Floating point operations and argument passing are hard.
1651 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1652 CmdArgs.push_back("-mfloat-abi");
1653 CmdArgs.push_back("hard");
1656 // Forward the -mglobal-merge option for explicit control over the pass.
1657 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1658 options::OPT_mno_global_merge)) {
1659 CmdArgs.push_back("-mllvm");
1660 if (A->getOption().matches(options::OPT_mno_global_merge))
1661 CmdArgs.push_back("-arm-global-merge=false");
1663 CmdArgs.push_back("-arm-global-merge=true");
1666 if (!Args.hasFlag(options::OPT_mimplicit_float,
1667 options::OPT_mno_implicit_float, true))
1668 CmdArgs.push_back("-no-implicit-float");
1670 if (Args.getLastArg(options::OPT_mcmse))
1671 CmdArgs.push_back("-mcmse");
1673 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1675 // Enable/disable return address signing and indirect branch targets.
1676 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1678 AddUnalignedAccessWarning(CmdArgs);
1681 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1682 const ArgList &Args, bool KernelOrKext,
1683 ArgStringList &CmdArgs) const {
1684 const ToolChain &TC = getToolChain();
1686 // Add the target features
1687 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1689 // Add target specific flags.
1690 switch (TC.getArch()) {
1694 case llvm::Triple::arm:
1695 case llvm::Triple::armeb:
1696 case llvm::Triple::thumb:
1697 case llvm::Triple::thumbeb:
1698 // Use the effective triple, which takes into account the deployment target.
1699 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1702 case llvm::Triple::aarch64:
1703 case llvm::Triple::aarch64_32:
1704 case llvm::Triple::aarch64_be:
1705 AddAArch64TargetArgs(Args, CmdArgs);
1708 case llvm::Triple::loongarch32:
1709 case llvm::Triple::loongarch64:
1710 AddLoongArchTargetArgs(Args, CmdArgs);
1713 case llvm::Triple::mips:
1714 case llvm::Triple::mipsel:
1715 case llvm::Triple::mips64:
1716 case llvm::Triple::mips64el:
1717 AddMIPSTargetArgs(Args, CmdArgs);
1720 case llvm::Triple::ppc:
1721 case llvm::Triple::ppcle:
1722 case llvm::Triple::ppc64:
1723 case llvm::Triple::ppc64le:
1724 AddPPCTargetArgs(Args, CmdArgs);
1727 case llvm::Triple::riscv32:
1728 case llvm::Triple::riscv64:
1729 AddRISCVTargetArgs(Args, CmdArgs);
1732 case llvm::Triple::sparc:
1733 case llvm::Triple::sparcel:
1734 case llvm::Triple::sparcv9:
1735 AddSparcTargetArgs(Args, CmdArgs);
1738 case llvm::Triple::systemz:
1739 AddSystemZTargetArgs(Args, CmdArgs);
1742 case llvm::Triple::x86:
1743 case llvm::Triple::x86_64:
1744 AddX86TargetArgs(Args, CmdArgs);
1747 case llvm::Triple::lanai:
1748 AddLanaiTargetArgs(Args, CmdArgs);
1751 case llvm::Triple::hexagon:
1752 AddHexagonTargetArgs(Args, CmdArgs);
1755 case llvm::Triple::wasm32:
1756 case llvm::Triple::wasm64:
1757 AddWebAssemblyTargetArgs(Args, CmdArgs);
1760 case llvm::Triple::ve:
1761 AddVETargetArgs(Args, CmdArgs);
1767 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1768 ArgStringList &CmdArgs) {
1769 const char *ABIName = nullptr;
1770 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1771 ABIName = A->getValue();
1772 else if (Triple.isOSDarwin())
1773 ABIName = "darwinpcs";
1777 CmdArgs.push_back("-target-abi");
1778 CmdArgs.push_back(ABIName);
1782 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1783 ArgStringList &CmdArgs) const {
1784 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1786 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1787 Args.hasArg(options::OPT_mkernel) ||
1788 Args.hasArg(options::OPT_fapple_kext))
1789 CmdArgs.push_back("-disable-red-zone");
1791 if (!Args.hasFlag(options::OPT_mimplicit_float,
1792 options::OPT_mno_implicit_float, true))
1793 CmdArgs.push_back("-no-implicit-float");
1795 RenderAArch64ABI(Triple, Args, CmdArgs);
1797 // Forward the -mglobal-merge option for explicit control over the pass.
1798 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1799 options::OPT_mno_global_merge)) {
1800 CmdArgs.push_back("-mllvm");
1801 if (A->getOption().matches(options::OPT_mno_global_merge))
1802 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1804 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1807 // Enable/disable return address signing and indirect branch targets.
1808 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1810 // Handle -msve_vector_bits=<bits>
1811 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1812 StringRef Val = A->getValue();
1813 const Driver &D = getToolChain().getDriver();
1814 if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1815 Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1816 Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1817 Val.equals("2048+")) {
1819 if (Val.endswith("+"))
1820 Val = Val.substr(0, Val.size() - 1);
1822 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1823 assert(!Invalid && "Failed to parse value");
1825 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1828 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1829 assert(!Invalid && "Failed to parse value");
1831 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1832 // Silently drop requests for vector-length agnostic code as it's implied.
1833 } else if (!Val.equals("scalable"))
1834 // Handle the unsupported values passed to msve-vector-bits.
1835 D.Diag(diag::err_drv_unsupported_option_argument)
1836 << A->getSpelling() << Val;
1839 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1841 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1842 CmdArgs.push_back("-tune-cpu");
1843 if (strcmp(A->getValue(), "native") == 0)
1844 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1846 CmdArgs.push_back(A->getValue());
1849 AddUnalignedAccessWarning(CmdArgs);
1852 void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1853 ArgStringList &CmdArgs) const {
1854 const llvm::Triple &Triple = getToolChain().getTriple();
1856 CmdArgs.push_back("-target-abi");
1858 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1862 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1863 std::string TuneCPU = A->getValue();
1864 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1865 CmdArgs.push_back("-tune-cpu");
1866 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1870 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1871 ArgStringList &CmdArgs) const {
1872 const Driver &D = getToolChain().getDriver();
1875 const llvm::Triple &Triple = getToolChain().getTriple();
1876 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1878 CmdArgs.push_back("-target-abi");
1879 CmdArgs.push_back(ABIName.data());
1881 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1882 if (ABI == mips::FloatABI::Soft) {
1883 // Floating point operations and argument passing are soft.
1884 CmdArgs.push_back("-msoft-float");
1885 CmdArgs.push_back("-mfloat-abi");
1886 CmdArgs.push_back("soft");
1888 // Floating point operations and argument passing are hard.
1889 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1890 CmdArgs.push_back("-mfloat-abi");
1891 CmdArgs.push_back("hard");
1894 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1895 options::OPT_mno_ldc1_sdc1)) {
1896 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1897 CmdArgs.push_back("-mllvm");
1898 CmdArgs.push_back("-mno-ldc1-sdc1");
1902 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1903 options::OPT_mno_check_zero_division)) {
1904 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1905 CmdArgs.push_back("-mllvm");
1906 CmdArgs.push_back("-mno-check-zero-division");
1910 if (Args.getLastArg(options::OPT_mfix4300)) {
1911 CmdArgs.push_back("-mllvm");
1912 CmdArgs.push_back("-mfix4300");
1915 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1916 StringRef v = A->getValue();
1917 CmdArgs.push_back("-mllvm");
1918 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1922 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1924 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1926 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1927 // -mgpopt is the default for static, -fno-pic environments but these two
1928 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1929 // the only case where -mllvm -mgpopt is passed.
1930 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1931 // passed explicitly when compiling something with -mabicalls
1932 // (implictly) in affect. Currently the warning is in the backend.
1934 // When the ABI in use is N64, we also need to determine the PIC mode that
1935 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1937 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1939 llvm::Reloc::Model RelocationModel;
1942 std::tie(RelocationModel, PICLevel, IsPIE) =
1943 ParsePICArgs(getToolChain(), Args);
1945 NoABICalls = NoABICalls ||
1946 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1948 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1949 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1950 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1951 CmdArgs.push_back("-mllvm");
1952 CmdArgs.push_back("-mgpopt");
1954 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1955 options::OPT_mno_local_sdata);
1956 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1957 options::OPT_mno_extern_sdata);
1958 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1959 options::OPT_mno_embedded_data);
1961 CmdArgs.push_back("-mllvm");
1962 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1963 CmdArgs.push_back("-mlocal-sdata=1");
1965 CmdArgs.push_back("-mlocal-sdata=0");
1967 LocalSData->claim();
1971 CmdArgs.push_back("-mllvm");
1972 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1973 CmdArgs.push_back("-mextern-sdata=1");
1975 CmdArgs.push_back("-mextern-sdata=0");
1977 ExternSData->claim();
1981 CmdArgs.push_back("-mllvm");
1982 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1983 CmdArgs.push_back("-membedded-data=1");
1985 CmdArgs.push_back("-membedded-data=0");
1987 EmbeddedData->claim();
1990 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1991 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1996 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1997 StringRef Val = StringRef(A->getValue());
1998 if (mips::hasCompactBranches(CPUName)) {
1999 if (Val == "never" || Val == "always" || Val == "optimal") {
2000 CmdArgs.push_back("-mllvm");
2001 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
2003 D.Diag(diag::err_drv_unsupported_option_argument)
2004 << A->getSpelling() << Val;
2006 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
2009 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
2010 options::OPT_mno_relax_pic_calls)) {
2011 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
2012 CmdArgs.push_back("-mllvm");
2013 CmdArgs.push_back("-mips-jalr-reloc=0");
2018 void Clang::AddPPCTargetArgs(const ArgList &Args,
2019 ArgStringList &CmdArgs) const {
2020 const Driver &D = getToolChain().getDriver();
2021 const llvm::Triple &T = getToolChain().getTriple();
2022 if (Args.getLastArg(options::OPT_mtune_EQ)) {
2023 CmdArgs.push_back("-tune-cpu");
2024 std::string CPU = ppc::getPPCTuneCPU(Args, T);
2025 CmdArgs.push_back(Args.MakeArgString(CPU));
2028 // Select the ABI to use.
2029 const char *ABIName = nullptr;
2030 if (T.isOSBinFormatELF()) {
2031 switch (getToolChain().getArch()) {
2032 case llvm::Triple::ppc64: {
2033 if (T.isPPC64ELFv2ABI())
2039 case llvm::Triple::ppc64le:
2047 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2048 bool VecExtabi = false;
2049 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2050 StringRef V = A->getValue();
2051 if (V == "ieeelongdouble") {
2052 IEEELongDouble = true;
2054 } else if (V == "ibmlongdouble") {
2055 IEEELongDouble = false;
2057 } else if (V == "vec-default") {
2060 } else if (V == "vec-extabi") {
2063 } else if (V == "elfv1") {
2066 } else if (V == "elfv2") {
2069 } else if (V != "altivec")
2070 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2071 // the option if given as we don't have backend support for any targets
2072 // that don't use the altivec abi.
2073 ABIName = A->getValue();
2076 CmdArgs.push_back("-mabi=ieeelongdouble");
2079 D.Diag(diag::err_drv_unsupported_opt_for_target)
2080 << "-mabi=vec-extabi" << T.str();
2081 CmdArgs.push_back("-mabi=vec-extabi");
2084 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2085 if (FloatABI == ppc::FloatABI::Soft) {
2086 // Floating point operations and argument passing are soft.
2087 CmdArgs.push_back("-msoft-float");
2088 CmdArgs.push_back("-mfloat-abi");
2089 CmdArgs.push_back("soft");
2091 // Floating point operations and argument passing are hard.
2092 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2093 CmdArgs.push_back("-mfloat-abi");
2094 CmdArgs.push_back("hard");
2098 CmdArgs.push_back("-target-abi");
2099 CmdArgs.push_back(ABIName);
2103 static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2104 ArgStringList &CmdArgs) {
2105 const Driver &D = TC.getDriver();
2106 const llvm::Triple &Triple = TC.getTriple();
2107 // Default small data limitation is eight.
2108 const char *SmallDataLimit = "8";
2109 // Get small data limitation.
2110 if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2111 options::OPT_fPIC)) {
2112 // Not support linker relaxation for PIC.
2113 SmallDataLimit = "0";
2114 if (Args.hasArg(options::OPT_G)) {
2115 D.Diag(diag::warn_drv_unsupported_sdata);
2117 } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2118 .equals_insensitive("large") &&
2119 (Triple.getArch() == llvm::Triple::riscv64)) {
2120 // Not support linker relaxation for RV64 with large code model.
2121 SmallDataLimit = "0";
2122 if (Args.hasArg(options::OPT_G)) {
2123 D.Diag(diag::warn_drv_unsupported_sdata);
2125 } else if (Triple.isAndroid()) {
2126 // GP relaxation is not supported on Android.
2127 SmallDataLimit = "0";
2128 if (Args.hasArg(options::OPT_G)) {
2129 D.Diag(diag::warn_drv_unsupported_sdata);
2131 } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2132 SmallDataLimit = A->getValue();
2134 // Forward the -msmall-data-limit= option.
2135 CmdArgs.push_back("-msmall-data-limit");
2136 CmdArgs.push_back(SmallDataLimit);
2139 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2140 ArgStringList &CmdArgs) const {
2141 const llvm::Triple &Triple = getToolChain().getTriple();
2142 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2144 CmdArgs.push_back("-target-abi");
2145 CmdArgs.push_back(ABIName.data());
2147 SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2149 if (!Args.hasFlag(options::OPT_mimplicit_float,
2150 options::OPT_mno_implicit_float, true))
2151 CmdArgs.push_back("-no-implicit-float");
2153 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2154 CmdArgs.push_back("-tune-cpu");
2155 if (strcmp(A->getValue(), "native") == 0)
2156 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2158 CmdArgs.push_back(A->getValue());
2161 // Handle -mrvv-vector-bits=<bits>
2162 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2163 StringRef Val = A->getValue();
2164 const Driver &D = getToolChain().getDriver();
2166 // Get minimum VLen from march.
2167 unsigned MinVLen = 0;
2168 StringRef Arch = riscv::getRISCVArch(Args, Triple);
2169 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2170 Arch, /*EnableExperimentalExtensions*/ true);
2172 // Ignore parsing error.
2173 consumeError(ISAInfo.takeError());
2175 MinVLen = (*ISAInfo)->getMinVLen();
2178 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2179 // as integer as long as we have a MinVLen.
2181 if (Val.equals("zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2183 } else if (!Val.getAsInteger(10, Bits)) {
2184 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2185 // at least MinVLen.
2186 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2187 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2191 // If we got a valid value try to use it.
2193 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2195 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2197 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2198 } else if (!Val.equals("scalable")) {
2199 // Handle the unsupported values passed to mrvv-vector-bits.
2200 D.Diag(diag::err_drv_unsupported_option_argument)
2201 << A->getSpelling() << Val;
2206 void Clang::AddSparcTargetArgs(const ArgList &Args,
2207 ArgStringList &CmdArgs) const {
2208 sparc::FloatABI FloatABI =
2209 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2211 if (FloatABI == sparc::FloatABI::Soft) {
2212 // Floating point operations and argument passing are soft.
2213 CmdArgs.push_back("-msoft-float");
2214 CmdArgs.push_back("-mfloat-abi");
2215 CmdArgs.push_back("soft");
2217 // Floating point operations and argument passing are hard.
2218 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2219 CmdArgs.push_back("-mfloat-abi");
2220 CmdArgs.push_back("hard");
2223 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2224 StringRef Name = A->getValue();
2225 std::string TuneCPU;
2226 if (Name == "native")
2227 TuneCPU = std::string(llvm::sys::getHostCPUName());
2229 TuneCPU = std::string(Name);
2231 CmdArgs.push_back("-tune-cpu");
2232 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2236 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2237 ArgStringList &CmdArgs) const {
2238 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2239 CmdArgs.push_back("-tune-cpu");
2240 if (strcmp(A->getValue(), "native") == 0)
2241 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2243 CmdArgs.push_back(A->getValue());
2247 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2248 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2249 options::OPT_mno_packed_stack, false);
2250 systemz::FloatABI FloatABI =
2251 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2252 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2253 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2254 const Driver &D = getToolChain().getDriver();
2255 D.Diag(diag::err_drv_unsupported_opt)
2256 << "-mpacked-stack -mbackchain -mhard-float";
2259 CmdArgs.push_back("-mbackchain");
2261 CmdArgs.push_back("-mpacked-stack");
2263 // Floating point operations and argument passing are soft.
2264 CmdArgs.push_back("-msoft-float");
2265 CmdArgs.push_back("-mfloat-abi");
2266 CmdArgs.push_back("soft");
2270 void Clang::AddX86TargetArgs(const ArgList &Args,
2271 ArgStringList &CmdArgs) const {
2272 const Driver &D = getToolChain().getDriver();
2273 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2275 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2276 Args.hasArg(options::OPT_mkernel) ||
2277 Args.hasArg(options::OPT_fapple_kext))
2278 CmdArgs.push_back("-disable-red-zone");
2280 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2281 options::OPT_mno_tls_direct_seg_refs, true))
2282 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2284 // Default to avoid implicit floating-point for kernel/kext code, but allow
2285 // that to be overridden with -mno-soft-float.
2286 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2287 Args.hasArg(options::OPT_fapple_kext));
2288 if (Arg *A = Args.getLastArg(
2289 options::OPT_msoft_float, options::OPT_mno_soft_float,
2290 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2291 const Option &O = A->getOption();
2292 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2293 O.matches(options::OPT_msoft_float));
2295 if (NoImplicitFloat)
2296 CmdArgs.push_back("-no-implicit-float");
2298 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2299 StringRef Value = A->getValue();
2300 if (Value == "intel" || Value == "att") {
2301 CmdArgs.push_back("-mllvm");
2302 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2303 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2305 D.Diag(diag::err_drv_unsupported_option_argument)
2306 << A->getSpelling() << Value;
2308 } else if (D.IsCLMode()) {
2309 CmdArgs.push_back("-mllvm");
2310 CmdArgs.push_back("-x86-asm-syntax=intel");
2313 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2314 options::OPT_mno_skip_rax_setup))
2315 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2316 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2318 // Set flags to support MCU ABI.
2319 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2320 CmdArgs.push_back("-mfloat-abi");
2321 CmdArgs.push_back("soft");
2322 CmdArgs.push_back("-mstack-alignment=4");
2327 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2328 std::string TuneCPU;
2329 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2330 !getToolChain().getTriple().isPS())
2331 TuneCPU = "generic";
2333 // Override based on -mtune.
2334 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2335 StringRef Name = A->getValue();
2337 if (Name == "native") {
2338 Name = llvm::sys::getHostCPUName();
2340 TuneCPU = std::string(Name);
2342 TuneCPU = std::string(Name);
2345 if (!TuneCPU.empty()) {
2346 CmdArgs.push_back("-tune-cpu");
2347 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2351 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2352 ArgStringList &CmdArgs) const {
2353 CmdArgs.push_back("-mqdsp6-compat");
2354 CmdArgs.push_back("-Wreturn-type");
2356 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2357 CmdArgs.push_back("-mllvm");
2359 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2362 if (!Args.hasArg(options::OPT_fno_short_enums))
2363 CmdArgs.push_back("-fshort-enums");
2364 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2365 CmdArgs.push_back("-mllvm");
2366 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2368 CmdArgs.push_back("-mllvm");
2369 CmdArgs.push_back("-machine-sink-split=0");
2372 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2373 ArgStringList &CmdArgs) const {
2374 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2375 StringRef CPUName = A->getValue();
2377 CmdArgs.push_back("-target-cpu");
2378 CmdArgs.push_back(Args.MakeArgString(CPUName));
2380 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2381 StringRef Value = A->getValue();
2382 // Only support mregparm=4 to support old usage. Report error for all other
2385 if (Value.getAsInteger(10, Mregparm)) {
2386 if (Mregparm != 4) {
2387 getToolChain().getDriver().Diag(
2388 diag::err_drv_unsupported_option_argument)
2389 << A->getSpelling() << Value;
2395 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2396 ArgStringList &CmdArgs) const {
2397 // Default to "hidden" visibility.
2398 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2399 options::OPT_fvisibility_ms_compat))
2400 CmdArgs.push_back("-fvisibility=hidden");
2403 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2404 // Floating point operations and argument passing are hard.
2405 CmdArgs.push_back("-mfloat-abi");
2406 CmdArgs.push_back("hard");
2409 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2410 StringRef Target, const InputInfo &Output,
2411 const InputInfo &Input, const ArgList &Args) const {
2412 // If this is a dry run, do not create the compilation database file.
2413 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2416 using llvm::yaml::escape;
2417 const Driver &D = getToolChain().getDriver();
2419 if (!CompilationDatabase) {
2421 auto File = std::make_unique<llvm::raw_fd_ostream>(
2423 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2425 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2429 CompilationDatabase = std::move(File);
2431 auto &CDB = *CompilationDatabase;
2432 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2435 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2436 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2437 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2438 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2439 SmallString<128> Buf;
2441 Buf += types::getTypeName(Input.getType());
2442 CDB << ", \"" << escape(Buf) << "\"";
2443 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2446 CDB << ", \"" << escape(Buf) << "\"";
2448 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2449 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2450 for (auto &A: Args) {
2451 auto &O = A->getOption();
2452 // Skip language selection, which is positional.
2453 if (O.getID() == options::OPT_x)
2455 // Skip writing dependency output and the compilation database itself.
2456 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2458 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2461 if (O.getKind() == Option::InputClass)
2464 if (O.getID() == options::OPT_o)
2466 // All other arguments are quoted and appended.
2468 A->render(Args, ASL);
2470 CDB << ", \"" << escape(it) << "\"";
2474 CDB << ", \"" << escape(Buf) << "\"]},\n";
2477 void Clang::DumpCompilationDatabaseFragmentToDir(
2478 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2479 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2480 // If this is a dry run, do not create the compilation database file.
2481 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2484 if (CompilationDatabase)
2485 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2487 SmallString<256> Path = Dir;
2488 const auto &Driver = C.getDriver();
2489 Driver.getVFS().makeAbsolute(Path);
2490 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2492 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2496 llvm::sys::path::append(
2498 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2500 SmallString<256> TempPath;
2501 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2502 llvm::sys::fs::OF_Text);
2504 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2507 CompilationDatabase =
2508 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2509 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2512 static bool CheckARMImplicitITArg(StringRef Value) {
2513 return Value == "always" || Value == "never" || Value == "arm" ||
2517 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2519 CmdArgs.push_back("-mllvm");
2520 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2523 static void CollectArgsForIntegratedAssembler(Compilation &C,
2524 const ArgList &Args,
2525 ArgStringList &CmdArgs,
2527 if (UseRelaxAll(C, Args))
2528 CmdArgs.push_back("-mrelax-all");
2530 // Only default to -mincremental-linker-compatible if we think we are
2531 // targeting the MSVC linker.
2532 bool DefaultIncrementalLinkerCompatible =
2533 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2534 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2535 options::OPT_mno_incremental_linker_compatible,
2536 DefaultIncrementalLinkerCompatible))
2537 CmdArgs.push_back("-mincremental-linker-compatible");
2539 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2541 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2542 options::OPT_fno_emit_compact_unwind_non_canonical);
2544 // If you add more args here, also add them to the block below that
2545 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2547 // When passing -I arguments to the assembler we sometimes need to
2548 // unconditionally take the next argument. For example, when parsing
2549 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2550 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2551 // arg after parsing the '-I' arg.
2552 bool TakeNextArg = false;
2554 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2555 bool UseNoExecStack = false;
2556 const char *MipsTargetFeature = nullptr;
2557 StringRef ImplicitIt;
2559 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2560 options::OPT_mimplicit_it_EQ)) {
2563 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2564 switch (C.getDefaultToolChain().getArch()) {
2565 case llvm::Triple::arm:
2566 case llvm::Triple::armeb:
2567 case llvm::Triple::thumb:
2568 case llvm::Triple::thumbeb:
2569 // Only store the value; the last value set takes effect.
2570 ImplicitIt = A->getValue();
2571 if (!CheckARMImplicitITArg(ImplicitIt))
2572 D.Diag(diag::err_drv_unsupported_option_argument)
2573 << A->getSpelling() << ImplicitIt;
2580 for (StringRef Value : A->getValues()) {
2582 CmdArgs.push_back(Value.data());
2583 TakeNextArg = false;
2587 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2588 Value == "-mbig-obj")
2589 continue; // LLVM handles bigobj automatically
2591 switch (C.getDefaultToolChain().getArch()) {
2594 case llvm::Triple::wasm32:
2595 case llvm::Triple::wasm64:
2596 if (Value == "--no-type-check") {
2597 CmdArgs.push_back("-mno-type-check");
2601 case llvm::Triple::thumb:
2602 case llvm::Triple::thumbeb:
2603 case llvm::Triple::arm:
2604 case llvm::Triple::armeb:
2605 if (Value.startswith("-mimplicit-it=")) {
2606 // Only store the value; the last value set takes effect.
2607 ImplicitIt = Value.split("=").second;
2608 if (CheckARMImplicitITArg(ImplicitIt))
2611 if (Value == "-mthumb")
2612 // -mthumb has already been processed in ComputeLLVMTriple()
2613 // recognize but skip over here.
2616 case llvm::Triple::mips:
2617 case llvm::Triple::mipsel:
2618 case llvm::Triple::mips64:
2619 case llvm::Triple::mips64el:
2620 if (Value == "--trap") {
2621 CmdArgs.push_back("-target-feature");
2622 CmdArgs.push_back("+use-tcc-in-div");
2625 if (Value == "--break") {
2626 CmdArgs.push_back("-target-feature");
2627 CmdArgs.push_back("-use-tcc-in-div");
2630 if (Value.startswith("-msoft-float")) {
2631 CmdArgs.push_back("-target-feature");
2632 CmdArgs.push_back("+soft-float");
2635 if (Value.startswith("-mhard-float")) {
2636 CmdArgs.push_back("-target-feature");
2637 CmdArgs.push_back("-soft-float");
2641 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2642 .Case("-mips1", "+mips1")
2643 .Case("-mips2", "+mips2")
2644 .Case("-mips3", "+mips3")
2645 .Case("-mips4", "+mips4")
2646 .Case("-mips5", "+mips5")
2647 .Case("-mips32", "+mips32")
2648 .Case("-mips32r2", "+mips32r2")
2649 .Case("-mips32r3", "+mips32r3")
2650 .Case("-mips32r5", "+mips32r5")
2651 .Case("-mips32r6", "+mips32r6")
2652 .Case("-mips64", "+mips64")
2653 .Case("-mips64r2", "+mips64r2")
2654 .Case("-mips64r3", "+mips64r3")
2655 .Case("-mips64r5", "+mips64r5")
2656 .Case("-mips64r6", "+mips64r6")
2658 if (MipsTargetFeature)
2662 if (Value == "-force_cpusubtype_ALL") {
2663 // Do nothing, this is the default and we don't support anything else.
2664 } else if (Value == "-L") {
2665 CmdArgs.push_back("-msave-temp-labels");
2666 } else if (Value == "--fatal-warnings") {
2667 CmdArgs.push_back("-massembler-fatal-warnings");
2668 } else if (Value == "--no-warn" || Value == "-W") {
2669 CmdArgs.push_back("-massembler-no-warn");
2670 } else if (Value == "--noexecstack") {
2671 UseNoExecStack = true;
2672 } else if (Value.startswith("-compress-debug-sections") ||
2673 Value.startswith("--compress-debug-sections") ||
2674 Value == "-nocompress-debug-sections" ||
2675 Value == "--nocompress-debug-sections") {
2676 CmdArgs.push_back(Value.data());
2677 } else if (Value == "-mrelax-relocations=yes" ||
2678 Value == "--mrelax-relocations=yes") {
2679 UseRelaxRelocations = true;
2680 } else if (Value == "-mrelax-relocations=no" ||
2681 Value == "--mrelax-relocations=no") {
2682 UseRelaxRelocations = false;
2683 } else if (Value.startswith("-I")) {
2684 CmdArgs.push_back(Value.data());
2685 // We need to consume the next argument if the current arg is a plain
2686 // -I. The next arg will be the include directory.
2689 } else if (Value.startswith("-gdwarf-")) {
2690 // "-gdwarf-N" options are not cc1as options.
2691 unsigned DwarfVersion = DwarfVersionNum(Value);
2692 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2693 CmdArgs.push_back(Value.data());
2695 RenderDebugEnablingArgs(Args, CmdArgs,
2696 llvm::codegenoptions::DebugInfoConstructor,
2697 DwarfVersion, llvm::DebuggerKind::Default);
2699 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2700 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2701 // Do nothing, we'll validate it later.
2702 } else if (Value == "-defsym") {
2703 if (A->getNumValues() != 2) {
2704 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2707 const char *S = A->getValue(1);
2708 auto Pair = StringRef(S).split('=');
2709 auto Sym = Pair.first;
2710 auto SVal = Pair.second;
2712 if (Sym.empty() || SVal.empty()) {
2713 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2717 if (SVal.getAsInteger(0, IVal)) {
2718 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2721 CmdArgs.push_back(Value.data());
2723 } else if (Value == "-fdebug-compilation-dir") {
2724 CmdArgs.push_back("-fdebug-compilation-dir");
2726 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2727 // The flag is a -Wa / -Xassembler argument and Options doesn't
2728 // parse the argument, so this isn't automatically aliased to
2729 // -fdebug-compilation-dir (without '=') here.
2730 CmdArgs.push_back("-fdebug-compilation-dir");
2731 CmdArgs.push_back(Value.data());
2732 } else if (Value == "--version") {
2733 D.PrintVersion(C, llvm::outs());
2735 D.Diag(diag::err_drv_unsupported_option_argument)
2736 << A->getSpelling() << Value;
2740 if (ImplicitIt.size())
2741 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2742 if (!UseRelaxRelocations)
2743 CmdArgs.push_back("-mrelax-relocations=no");
2745 CmdArgs.push_back("-mnoexecstack");
2746 if (MipsTargetFeature != nullptr) {
2747 CmdArgs.push_back("-target-feature");
2748 CmdArgs.push_back(MipsTargetFeature);
2751 // forward -fembed-bitcode to assmebler
2752 if (C.getDriver().embedBitcodeEnabled() ||
2753 C.getDriver().embedBitcodeMarkerOnly())
2754 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2756 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2757 CmdArgs.push_back("-as-secure-log-file");
2758 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2762 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2763 bool OFastEnabled, const ArgList &Args,
2764 ArgStringList &CmdArgs,
2765 const JobAction &JA) {
2766 // Handle various floating point optimization flags, mapping them to the
2767 // appropriate LLVM code generation flags. This is complicated by several
2768 // "umbrella" flags, so we do this by stepping through the flags incrementally
2769 // adjusting what we think is enabled/disabled, then at the end setting the
2770 // LLVM flags based on the final state.
2771 bool HonorINFs = true;
2772 bool HonorNaNs = true;
2773 bool ApproxFunc = false;
2774 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2775 bool MathErrno = TC.IsMathErrnoDefault();
2776 bool AssociativeMath = false;
2777 bool ReciprocalMath = false;
2778 bool SignedZeros = true;
2779 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2780 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2781 // overriden by ffp-exception-behavior?
2782 bool RoundingFPMath = false;
2783 bool RoundingMathPresent = false; // Is rounding-math in args?
2784 // -ffp-model values: strict, fast, precise
2785 StringRef FPModel = "";
2786 // -ffp-exception-behavior options: strict, maytrap, ignore
2787 StringRef FPExceptionBehavior = "";
2788 // -ffp-eval-method options: double, extended, source
2789 StringRef FPEvalMethod = "";
2790 const llvm::DenormalMode DefaultDenormalFPMath =
2791 TC.getDefaultDenormalModeForType(Args, JA);
2792 const llvm::DenormalMode DefaultDenormalFP32Math =
2793 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2795 llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2796 llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2797 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2798 // If one wasn't given by the user, don't pass it here.
2799 StringRef FPContract;
2800 StringRef LastSeenFfpContractOption;
2801 bool SeenUnsafeMathModeOption = false;
2802 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2803 !JA.isOffloading(Action::OFK_HIP))
2805 bool StrictFPModel = false;
2806 StringRef Float16ExcessPrecision = "";
2807 StringRef BFloat16ExcessPrecision = "";
2809 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2810 CmdArgs.push_back("-mlimit-float-precision");
2811 CmdArgs.push_back(A->getValue());
2814 for (const Arg *A : Args) {
2815 auto optID = A->getOption().getID();
2816 bool PreciseFPModel = false;
2820 case options::OPT_ffp_model_EQ: {
2821 // If -ffp-model= is seen, reset to fno-fast-math
2825 // Turning *off* -ffast-math restores the toolchain default.
2826 MathErrno = TC.IsMathErrnoDefault();
2827 AssociativeMath = false;
2828 ReciprocalMath = false;
2830 // -fno_fast_math restores default denormal and fpcontract handling
2832 DenormalFPMath = llvm::DenormalMode::getIEEE();
2834 // FIXME: The target may have picked a non-IEEE default mode here based on
2835 // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2836 DenormalFP32Math = llvm::DenormalMode::getIEEE();
2838 StringRef Val = A->getValue();
2839 if (OFastEnabled && !Val.equals("fast")) {
2840 // Only -ffp-model=fast is compatible with OFast, ignore.
2841 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2842 << Args.MakeArgString("-ffp-model=" + Val)
2846 StrictFPModel = false;
2847 PreciseFPModel = true;
2848 // ffp-model= is a Driver option, it is entirely rewritten into more
2849 // granular options before being passed into cc1.
2850 // Use the gcc option in the switch below.
2851 if (!FPModel.empty() && !FPModel.equals(Val))
2852 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2853 << Args.MakeArgString("-ffp-model=" + FPModel)
2854 << Args.MakeArgString("-ffp-model=" + Val);
2855 if (Val.equals("fast")) {
2856 optID = options::OPT_ffast_math;
2858 FPContract = "fast";
2859 } else if (Val.equals("precise")) {
2860 optID = options::OPT_ffp_contract;
2863 PreciseFPModel = true;
2864 } else if (Val.equals("strict")) {
2865 StrictFPModel = true;
2866 optID = options::OPT_frounding_math;
2867 FPExceptionBehavior = "strict";
2870 TrappingMath = true;
2872 D.Diag(diag::err_drv_unsupported_option_argument)
2873 << A->getSpelling() << Val;
2879 // If this isn't an FP option skip the claim below
2882 // Options controlling individual features
2883 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2884 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2885 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2886 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2887 case options::OPT_fapprox_func: ApproxFunc = true; break;
2888 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2889 case options::OPT_fmath_errno: MathErrno = true; break;
2890 case options::OPT_fno_math_errno: MathErrno = false; break;
2891 case options::OPT_fassociative_math: AssociativeMath = true; break;
2892 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2893 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2894 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2895 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2896 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2897 case options::OPT_ftrapping_math:
2898 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2899 !FPExceptionBehavior.equals("strict"))
2900 // Warn that previous value of option is overridden.
2901 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2902 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2903 << "-ftrapping-math";
2904 TrappingMath = true;
2905 TrappingMathPresent = true;
2906 FPExceptionBehavior = "strict";
2908 case options::OPT_fno_trapping_math:
2909 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2910 !FPExceptionBehavior.equals("ignore"))
2911 // Warn that previous value of option is overridden.
2912 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2913 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2914 << "-fno-trapping-math";
2915 TrappingMath = false;
2916 TrappingMathPresent = true;
2917 FPExceptionBehavior = "ignore";
2920 case options::OPT_frounding_math:
2921 RoundingFPMath = true;
2922 RoundingMathPresent = true;
2925 case options::OPT_fno_rounding_math:
2926 RoundingFPMath = false;
2927 RoundingMathPresent = false;
2930 case options::OPT_fdenormal_fp_math_EQ:
2931 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2932 DenormalFP32Math = DenormalFPMath;
2933 if (!DenormalFPMath.isValid()) {
2934 D.Diag(diag::err_drv_invalid_value)
2935 << A->getAsString(Args) << A->getValue();
2939 case options::OPT_fdenormal_fp_math_f32_EQ:
2940 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2941 if (!DenormalFP32Math.isValid()) {
2942 D.Diag(diag::err_drv_invalid_value)
2943 << A->getAsString(Args) << A->getValue();
2947 // Validate and pass through -ffp-contract option.
2948 case options::OPT_ffp_contract: {
2949 StringRef Val = A->getValue();
2950 if (PreciseFPModel) {
2951 // -ffp-model=precise enables ffp-contract=on.
2952 // -ffp-model=precise sets PreciseFPModel to on and Val to
2953 // "precise". FPContract is set.
2955 } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off")) {
2957 LastSeenFfpContractOption = Val;
2959 D.Diag(diag::err_drv_unsupported_option_argument)
2960 << A->getSpelling() << Val;
2964 // Validate and pass through -ffp-model option.
2965 case options::OPT_ffp_model_EQ:
2966 // This should only occur in the error case
2967 // since the optID has been replaced by a more granular
2968 // floating point option.
2971 // Validate and pass through -ffp-exception-behavior option.
2972 case options::OPT_ffp_exception_behavior_EQ: {
2973 StringRef Val = A->getValue();
2974 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2975 !FPExceptionBehavior.equals(Val))
2976 // Warn that previous value of option is overridden.
2977 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2978 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2979 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2980 TrappingMath = TrappingMathPresent = false;
2981 if (Val.equals("ignore") || Val.equals("maytrap"))
2982 FPExceptionBehavior = Val;
2983 else if (Val.equals("strict")) {
2984 FPExceptionBehavior = Val;
2985 TrappingMath = TrappingMathPresent = true;
2987 D.Diag(diag::err_drv_unsupported_option_argument)
2988 << A->getSpelling() << Val;
2992 // Validate and pass through -ffp-eval-method option.
2993 case options::OPT_ffp_eval_method_EQ: {
2994 StringRef Val = A->getValue();
2995 if (Val.equals("double") || Val.equals("extended") ||
2996 Val.equals("source"))
2999 D.Diag(diag::err_drv_unsupported_option_argument)
3000 << A->getSpelling() << Val;
3004 case options::OPT_fexcess_precision_EQ: {
3005 StringRef Val = A->getValue();
3006 const llvm::Triple::ArchType Arch = TC.getArch();
3007 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3008 if (Val.equals("standard") || Val.equals("fast"))
3009 Float16ExcessPrecision = Val;
3010 // To make it GCC compatible, allow the value of "16" which
3011 // means disable excess precision, the same meaning than clang's
3012 // equivalent value "none".
3013 else if (Val.equals("16"))
3014 Float16ExcessPrecision = "none";
3016 D.Diag(diag::err_drv_unsupported_option_argument)
3017 << A->getSpelling() << Val;
3019 if (!(Val.equals("standard") || Val.equals("fast")))
3020 D.Diag(diag::err_drv_unsupported_option_argument)
3021 << A->getSpelling() << Val;
3023 BFloat16ExcessPrecision = Float16ExcessPrecision;
3026 case options::OPT_ffinite_math_only:
3030 case options::OPT_fno_finite_math_only:
3035 case options::OPT_funsafe_math_optimizations:
3036 AssociativeMath = true;
3037 ReciprocalMath = true;
3038 SignedZeros = false;
3040 TrappingMath = false;
3041 FPExceptionBehavior = "";
3042 FPContract = "fast";
3043 SeenUnsafeMathModeOption = true;
3045 case options::OPT_fno_unsafe_math_optimizations:
3046 AssociativeMath = false;
3047 ReciprocalMath = false;
3050 TrappingMath = true;
3051 FPExceptionBehavior = "strict";
3053 // The target may have opted to flush by default, so force IEEE.
3054 DenormalFPMath = llvm::DenormalMode::getIEEE();
3055 DenormalFP32Math = llvm::DenormalMode::getIEEE();
3056 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3057 !JA.isOffloading(Action::OFK_HIP)) {
3058 if (LastSeenFfpContractOption != "") {
3059 FPContract = LastSeenFfpContractOption;
3060 } else if (SeenUnsafeMathModeOption)
3065 case options::OPT_Ofast:
3066 // If -Ofast is the optimization level, then -ffast-math should be enabled
3070 case options::OPT_ffast_math:
3074 AssociativeMath = true;
3075 ReciprocalMath = true;
3077 SignedZeros = false;
3078 TrappingMath = false;
3079 RoundingFPMath = false;
3080 FPExceptionBehavior = "";
3081 // If fast-math is set then set the fp-contract mode to fast.
3082 FPContract = "fast";
3083 SeenUnsafeMathModeOption = true;
3085 case options::OPT_fno_fast_math:
3088 // Turning on -ffast-math (with either flag) removes the need for
3089 // MathErrno. However, turning *off* -ffast-math merely restores the
3090 // toolchain default (which may be false).
3091 MathErrno = TC.IsMathErrnoDefault();
3092 AssociativeMath = false;
3093 ReciprocalMath = false;
3096 // -fno_fast_math restores default denormal and fpcontract handling
3097 DenormalFPMath = DefaultDenormalFPMath;
3098 DenormalFP32Math = llvm::DenormalMode::getIEEE();
3099 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3100 !JA.isOffloading(Action::OFK_HIP)) {
3101 if (LastSeenFfpContractOption != "") {
3102 FPContract = LastSeenFfpContractOption;
3103 } else if (SeenUnsafeMathModeOption)
3108 if (StrictFPModel) {
3109 // If -ffp-model=strict has been specified on command line but
3110 // subsequent options conflict then emit warning diagnostic.
3111 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3112 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3113 DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3114 DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3115 FPContract.equals("off"))
3116 // OK: Current Arg doesn't conflict with -ffp-model=strict
3119 StrictFPModel = false;
3121 auto RHS = (A->getNumValues() == 0)
3123 : Args.MakeArgString(A->getSpelling() + A->getValue());
3124 if (RHS != "-ffp-model=strict")
3125 D.Diag(clang::diag::warn_drv_overriding_flag_option)
3126 << "-ffp-model=strict" << RHS;
3130 // If we handled this option claim it
3135 CmdArgs.push_back("-menable-no-infs");
3138 CmdArgs.push_back("-menable-no-nans");
3141 CmdArgs.push_back("-fapprox-func");
3144 CmdArgs.push_back("-fmath-errno");
3146 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3148 CmdArgs.push_back("-funsafe-math-optimizations");
3151 CmdArgs.push_back("-fno-signed-zeros");
3153 if (AssociativeMath && !SignedZeros && !TrappingMath)
3154 CmdArgs.push_back("-mreassociate");
3157 CmdArgs.push_back("-freciprocal-math");
3160 // FP Exception Behavior is also set to strict
3161 assert(FPExceptionBehavior.equals("strict"));
3164 // The default is IEEE.
3165 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3166 llvm::SmallString<64> DenormFlag;
3167 llvm::raw_svector_ostream ArgStr(DenormFlag);
3168 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3169 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3172 // Add f32 specific denormal mode flag if it's different.
3173 if (DenormalFP32Math != DenormalFPMath) {
3174 llvm::SmallString<64> DenormFlag;
3175 llvm::raw_svector_ostream ArgStr(DenormFlag);
3176 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3177 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3180 if (!FPContract.empty())
3181 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3183 if (!RoundingFPMath)
3184 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3186 if (RoundingFPMath && RoundingMathPresent)
3187 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3189 if (!FPExceptionBehavior.empty())
3190 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3191 FPExceptionBehavior));
3193 if (!FPEvalMethod.empty())
3194 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3196 if (!Float16ExcessPrecision.empty())
3197 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3198 Float16ExcessPrecision));
3199 if (!BFloat16ExcessPrecision.empty())
3200 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3201 BFloat16ExcessPrecision));
3203 ParseMRecip(D, Args, CmdArgs);
3205 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3206 // individual features enabled by -ffast-math instead of the option itself as
3207 // that's consistent with gcc's behaviour.
3208 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3209 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3210 CmdArgs.push_back("-ffast-math");
3211 if (FPModel.equals("fast")) {
3212 if (FPContract.equals("fast"))
3213 // All set, do nothing.
3215 else if (FPContract.empty())
3216 // Enable -ffp-contract=fast
3217 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3219 D.Diag(clang::diag::warn_drv_overriding_flag_option)
3220 << "-ffp-model=fast"
3221 << Args.MakeArgString("-ffp-contract=" + FPContract);
3225 // Handle __FINITE_MATH_ONLY__ similarly.
3226 if (!HonorINFs && !HonorNaNs)
3227 CmdArgs.push_back("-ffinite-math-only");
3229 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3230 CmdArgs.push_back("-mfpmath");
3231 CmdArgs.push_back(A->getValue());
3234 // Disable a codegen optimization for floating-point casts.
3235 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3236 options::OPT_fstrict_float_cast_overflow, false))
3237 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3240 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3241 const llvm::Triple &Triple,
3242 const InputInfo &Input) {
3243 // Add default argument set.
3244 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3245 CmdArgs.push_back("-analyzer-checker=core");
3246 CmdArgs.push_back("-analyzer-checker=apiModeling");
3248 if (!Triple.isWindowsMSVCEnvironment()) {
3249 CmdArgs.push_back("-analyzer-checker=unix");
3251 // Enable "unix" checkers that also work on Windows.
3252 CmdArgs.push_back("-analyzer-checker=unix.API");
3253 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3254 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3255 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3256 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3257 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3260 // Disable some unix checkers for PS4/PS5.
3261 if (Triple.isPS()) {
3262 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3263 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3266 if (Triple.isOSDarwin()) {
3267 CmdArgs.push_back("-analyzer-checker=osx");
3269 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3271 else if (Triple.isOSFuchsia())
3272 CmdArgs.push_back("-analyzer-checker=fuchsia");
3274 CmdArgs.push_back("-analyzer-checker=deadcode");
3276 if (types::isCXX(Input.getType()))
3277 CmdArgs.push_back("-analyzer-checker=cplusplus");
3279 if (!Triple.isPS()) {
3280 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3281 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3282 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3283 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3284 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3285 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3288 // Default nullability checks.
3289 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3290 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3293 // Set the output format. The default is plist, for (lame) historical reasons.
3294 CmdArgs.push_back("-analyzer-output");
3295 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3296 CmdArgs.push_back(A->getValue());
3298 CmdArgs.push_back("plist");
3300 // Disable the presentation of standard compiler warnings when using
3301 // --analyze. We only want to show static analyzer diagnostics or frontend
3303 CmdArgs.push_back("-w");
3305 // Add -Xanalyzer arguments when running as analyzer.
3306 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3309 static bool isValidSymbolName(StringRef S) {
3313 if (std::isdigit(S[0]))
3316 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3319 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3320 const ArgList &Args, ArgStringList &CmdArgs,
3321 bool KernelOrKext) {
3322 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3324 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3325 // doesn't even have a stack!
3326 if (EffectiveTriple.isNVPTX())
3329 // -stack-protector=0 is default.
3330 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3331 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3332 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3334 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3335 options::OPT_fstack_protector_all,
3336 options::OPT_fstack_protector_strong,
3337 options::OPT_fstack_protector)) {
3338 if (A->getOption().matches(options::OPT_fstack_protector))
3339 StackProtectorLevel =
3340 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3341 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3342 StackProtectorLevel = LangOptions::SSPStrong;
3343 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3344 StackProtectorLevel = LangOptions::SSPReq;
3346 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3347 D.Diag(diag::warn_drv_unsupported_option_for_target)
3348 << A->getSpelling() << EffectiveTriple.getTriple();
3349 StackProtectorLevel = DefaultStackProtectorLevel;
3352 StackProtectorLevel = DefaultStackProtectorLevel;
3355 if (StackProtectorLevel) {
3356 CmdArgs.push_back("-stack-protector");
3357 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3360 // --param ssp-buffer-size=
3361 for (const Arg *A : Args.filtered(options::OPT__param)) {
3362 StringRef Str(A->getValue());
3363 if (Str.startswith("ssp-buffer-size=")) {
3364 if (StackProtectorLevel) {
3365 CmdArgs.push_back("-stack-protector-buffer-size");
3366 // FIXME: Verify the argument is a valid integer.
3367 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3373 const std::string &TripleStr = EffectiveTriple.getTriple();
3374 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3375 StringRef Value = A->getValue();
3376 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3377 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3378 D.Diag(diag::err_drv_unsupported_opt_for_target)
3379 << A->getAsString(Args) << TripleStr;
3380 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3381 EffectiveTriple.isThumb()) &&
3382 Value != "tls" && Value != "global") {
3383 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3384 << A->getOption().getName() << Value << "tls global";
3387 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3389 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3390 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3391 << A->getAsString(Args);
3394 // Check whether the target subarch supports the hardware TLS register
3395 if (!arm::isHardTPSupported(EffectiveTriple)) {
3396 D.Diag(diag::err_target_unsupported_tp_hard)
3397 << EffectiveTriple.getArchName();
3400 // Check whether the user asked for something other than -mtp=cp15
3401 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3402 StringRef Value = A->getValue();
3403 if (Value != "cp15") {
3404 D.Diag(diag::err_drv_argument_not_allowed_with)
3405 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3409 CmdArgs.push_back("-target-feature");
3410 CmdArgs.push_back("+read-tp-tpidruro");
3412 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3413 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3414 << A->getOption().getName() << Value << "sysreg global";
3417 A->render(Args, CmdArgs);
3420 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3421 StringRef Value = A->getValue();
3422 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3423 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3424 D.Diag(diag::err_drv_unsupported_opt_for_target)
3425 << A->getAsString(Args) << TripleStr;
3427 if (Value.getAsInteger(10, Offset)) {
3428 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3431 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3432 (Offset < 0 || Offset > 0xfffff)) {
3433 D.Diag(diag::err_drv_invalid_int_value)
3434 << A->getOption().getName() << Value;
3437 A->render(Args, CmdArgs);
3440 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3441 StringRef Value = A->getValue();
3442 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3443 D.Diag(diag::err_drv_unsupported_opt_for_target)
3444 << A->getAsString(Args) << TripleStr;
3445 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3446 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3447 << A->getOption().getName() << Value << "fs gs";
3450 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3451 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3454 A->render(Args, CmdArgs);
3457 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3458 StringRef Value = A->getValue();
3459 if (!isValidSymbolName(Value)) {
3460 D.Diag(diag::err_drv_argument_only_allowed_with)
3461 << A->getOption().getName() << "legal symbol name";
3464 A->render(Args, CmdArgs);
3468 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3469 ArgStringList &CmdArgs) {
3470 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3472 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3475 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3476 !EffectiveTriple.isPPC64())
3479 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3480 options::OPT_fno_stack_clash_protection);
3483 static void RenderTrivialAutoVarInitOptions(const Driver &D,
3484 const ToolChain &TC,
3485 const ArgList &Args,
3486 ArgStringList &CmdArgs) {
3487 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3488 StringRef TrivialAutoVarInit = "";
3490 for (const Arg *A : Args) {
3491 switch (A->getOption().getID()) {
3494 case options::OPT_ftrivial_auto_var_init: {
3496 StringRef Val = A->getValue();
3497 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3498 TrivialAutoVarInit = Val;
3500 D.Diag(diag::err_drv_unsupported_option_argument)
3501 << A->getSpelling() << Val;
3507 if (TrivialAutoVarInit.empty())
3508 switch (DefaultTrivialAutoVarInit) {
3509 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3511 case LangOptions::TrivialAutoVarInitKind::Pattern:
3512 TrivialAutoVarInit = "pattern";
3514 case LangOptions::TrivialAutoVarInitKind::Zero:
3515 TrivialAutoVarInit = "zero";
3519 if (!TrivialAutoVarInit.empty()) {
3521 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3525 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3526 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3528 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3530 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3532 StringRef Val = A->getValue();
3533 if (std::stoi(Val.str()) <= 0)
3534 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3536 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3540 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3541 types::ID InputType) {
3542 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3543 // for denormal flushing handling based on the target.
3544 const unsigned ForwardedArguments[] = {
3545 options::OPT_cl_opt_disable,
3546 options::OPT_cl_strict_aliasing,
3547 options::OPT_cl_single_precision_constant,
3548 options::OPT_cl_finite_math_only,
3549 options::OPT_cl_kernel_arg_info,
3550 options::OPT_cl_unsafe_math_optimizations,
3551 options::OPT_cl_fast_relaxed_math,
3552 options::OPT_cl_mad_enable,
3553 options::OPT_cl_no_signed_zeros,
3554 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3555 options::OPT_cl_uniform_work_group_size
3558 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3559 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3560 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3561 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3562 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3563 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3566 for (const auto &Arg : ForwardedArguments)
3567 if (const auto *A = Args.getLastArg(Arg))
3568 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3570 // Only add the default headers if we are compiling OpenCL sources.
3571 if ((types::isOpenCL(InputType) ||
3572 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3573 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3574 CmdArgs.push_back("-finclude-default-header");
3575 CmdArgs.push_back("-fdeclare-opencl-builtins");
3579 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3580 types::ID InputType) {
3581 const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3586 options::OPT_emit_llvm,
3587 options::OPT_emit_obj,
3588 options::OPT_disable_llvm_passes,
3589 options::OPT_fnative_half_type,
3590 options::OPT_hlsl_entrypoint};
3591 if (!types::isHLSL(InputType))
3593 for (const auto &Arg : ForwardedArguments)
3594 if (const auto *A = Args.getLastArg(Arg))
3595 A->renderAsInput(Args, CmdArgs);
3596 // Add the default headers if dxc_no_stdinc is not set.
3597 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3598 !Args.hasArg(options::OPT_nostdinc))
3599 CmdArgs.push_back("-finclude-default-header");
3602 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3603 ArgStringList &CmdArgs) {
3604 bool ARCMTEnabled = false;
3605 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3606 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3607 options::OPT_ccc_arcmt_modify,
3608 options::OPT_ccc_arcmt_migrate)) {
3609 ARCMTEnabled = true;
3610 switch (A->getOption().getID()) {
3611 default: llvm_unreachable("missed a case");
3612 case options::OPT_ccc_arcmt_check:
3613 CmdArgs.push_back("-arcmt-action=check");
3615 case options::OPT_ccc_arcmt_modify:
3616 CmdArgs.push_back("-arcmt-action=modify");
3618 case options::OPT_ccc_arcmt_migrate:
3619 CmdArgs.push_back("-arcmt-action=migrate");
3620 CmdArgs.push_back("-mt-migrate-directory");
3621 CmdArgs.push_back(A->getValue());
3623 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3624 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3629 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3630 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3631 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3634 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3636 D.Diag(diag::err_drv_argument_not_allowed_with)
3637 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3639 CmdArgs.push_back("-mt-migrate-directory");
3640 CmdArgs.push_back(A->getValue());
3642 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3643 options::OPT_objcmt_migrate_subscripting,
3644 options::OPT_objcmt_migrate_property)) {
3645 // None specified, means enable them all.
3646 CmdArgs.push_back("-objcmt-migrate-literals");
3647 CmdArgs.push_back("-objcmt-migrate-subscripting");
3648 CmdArgs.push_back("-objcmt-migrate-property");
3650 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3651 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3652 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3655 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3656 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3657 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3658 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3659 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3660 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3661 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3662 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3663 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3664 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3665 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3666 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3667 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3668 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3669 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3670 Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3674 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3675 const ArgList &Args, ArgStringList &CmdArgs) {
3676 // -fbuiltin is default unless -mkernel is used.
3678 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3679 !Args.hasArg(options::OPT_mkernel));
3681 CmdArgs.push_back("-fno-builtin");
3683 // -ffreestanding implies -fno-builtin.
3684 if (Args.hasArg(options::OPT_ffreestanding))
3685 UseBuiltins = false;
3687 // Process the -fno-builtin-* options.
3688 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3691 // If -fno-builtin is specified, then there's no need to pass the option to
3694 A->render(Args, CmdArgs);
3697 // le32-specific flags:
3698 // -fno-math-builtin: clang should not convert math builtins to intrinsics
3700 if (TC.getArch() == llvm::Triple::le32)
3701 CmdArgs.push_back("-fno-math-builtin");
3704 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3705 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3707 Path.toVector(Result);
3708 return Path.getSingleStringRef() != "";
3710 if (llvm::sys::path::cache_directory(Result)) {
3711 llvm::sys::path::append(Result, "clang");
3712 llvm::sys::path::append(Result, "ModuleCache");
3718 static bool RenderModulesOptions(Compilation &C, const Driver &D,
3719 const ArgList &Args, const InputInfo &Input,
3720 const InputInfo &Output, const Arg *Std,
3721 ArgStringList &CmdArgs) {
3722 bool IsCXX = types::isCXX(Input.getType());
3723 // FIXME: Find a better way to determine whether the input has standard c++
3724 // modules support by default.
3725 bool HaveStdCXXModules =
3727 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
3728 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
3729 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
3730 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
3731 Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
3732 Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
3733 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
3734 bool HaveModules = HaveStdCXXModules;
3736 // -fmodules enables the use of precompiled modules (off by default).
3737 // Users can pass -fno-cxx-modules to turn off modules support for
3738 // C++/Objective-C++ programs.
3739 bool HaveClangModules = false;
3740 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3741 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3742 options::OPT_fno_cxx_modules, true);
3743 if (AllowedInCXX || !IsCXX) {
3744 CmdArgs.push_back("-fmodules");
3745 HaveClangModules = true;
3749 HaveModules |= HaveClangModules;
3751 // -fmodule-maps enables implicit reading of module map files. By default,
3752 // this is enabled if we are using Clang's flavor of precompiled modules.
3753 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3754 options::OPT_fno_implicit_module_maps, HaveClangModules))
3755 CmdArgs.push_back("-fimplicit-module-maps");
3757 // -fmodules-decluse checks that modules used are declared so (off by default)
3758 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3759 options::OPT_fno_modules_decluse);
3761 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3762 // all #included headers are part of modules.
3763 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3764 options::OPT_fno_modules_strict_decluse, false))
3765 CmdArgs.push_back("-fmodules-strict-decluse");
3767 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3768 bool ImplicitModules = false;
3769 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3770 options::OPT_fno_implicit_modules, HaveClangModules)) {
3772 CmdArgs.push_back("-fno-implicit-modules");
3773 } else if (HaveModules) {
3774 ImplicitModules = true;
3775 // -fmodule-cache-path specifies where our implicitly-built module files
3776 // should be written.
3777 SmallString<128> Path;
3778 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3779 Path = A->getValue();
3781 bool HasPath = true;
3782 if (C.isForDiagnostics()) {
3783 // When generating crash reports, we want to emit the modules along with
3784 // the reproduction sources, so we ignore any provided module path.
3785 Path = Output.getFilename();
3786 llvm::sys::path::replace_extension(Path, ".cache");
3787 llvm::sys::path::append(Path, "modules");
3788 } else if (Path.empty()) {
3789 // No module path was provided: use the default.
3790 HasPath = Driver::getDefaultModuleCachePath(Path);
3793 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3794 // That being said, that failure is unlikely and not caching is harmless.
3796 const char Arg[] = "-fmodules-cache-path=";
3797 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3798 CmdArgs.push_back(Args.MakeArgString(Path));
3803 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3804 options::OPT_fno_prebuilt_implicit_modules, false))
3805 CmdArgs.push_back("-fprebuilt-implicit-modules");
3806 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3807 options::OPT_fno_modules_validate_input_files_content,
3809 CmdArgs.push_back("-fvalidate-ast-input-files-content");
3812 // -fmodule-name specifies the module that is currently being built (or
3813 // used for header checking by -fmodule-maps).
3814 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3816 // -fmodule-map-file can be used to specify files containing module
3818 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3820 // -fbuiltin-module-map can be used to load the clang
3821 // builtin headers modulemap file.
3822 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3823 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3824 llvm::sys::path::append(BuiltinModuleMap, "include");
3825 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3826 if (llvm::sys::fs::exists(BuiltinModuleMap))
3828 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3831 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3832 // names to precompiled module files (the module is loaded only if used).
3833 // The -fmodule-file=<file> form can be used to unconditionally load
3834 // precompiled module files (whether used or not).
3835 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3836 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3838 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3839 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3840 CmdArgs.push_back(Args.MakeArgString(
3841 std::string("-fprebuilt-module-path=") + A->getValue()));
3845 Args.ClaimAllArgs(options::OPT_fmodule_file);
3847 // When building modules and generating crashdumps, we need to dump a module
3848 // dependency VFS alongside the output.
3849 if (HaveClangModules && C.isForDiagnostics()) {
3850 SmallString<128> VFSDir(Output.getFilename());
3851 llvm::sys::path::replace_extension(VFSDir, ".cache");
3852 // Add the cache directory as a temp so the crash diagnostics pick it up.
3853 C.addTempFile(Args.MakeArgString(VFSDir));
3855 llvm::sys::path::append(VFSDir, "vfs");
3856 CmdArgs.push_back("-module-dependency-dir");
3857 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3860 if (HaveClangModules)
3861 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3863 // Pass through all -fmodules-ignore-macro arguments.
3864 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3865 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3866 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3868 if (HaveClangModules) {
3869 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3871 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3872 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3873 D.Diag(diag::err_drv_argument_not_allowed_with)
3874 << A->getAsString(Args) << "-fbuild-session-timestamp";
3876 llvm::sys::fs::file_status Status;
3877 if (llvm::sys::fs::status(A->getValue(), Status))
3878 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3879 CmdArgs.push_back(Args.MakeArgString(
3880 "-fbuild-session-timestamp=" +
3881 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3882 Status.getLastModificationTime().time_since_epoch())
3886 if (Args.getLastArg(
3887 options::OPT_fmodules_validate_once_per_build_session)) {
3888 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3889 options::OPT_fbuild_session_file))
3890 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3892 Args.AddLastArg(CmdArgs,
3893 options::OPT_fmodules_validate_once_per_build_session);
3896 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3897 options::OPT_fno_modules_validate_system_headers,
3899 CmdArgs.push_back("-fmodules-validate-system-headers");
3901 Args.AddLastArg(CmdArgs,
3902 options::OPT_fmodules_disable_diagnostic_validation);
3904 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3905 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3906 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3907 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3908 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3909 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3912 // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
3913 Args.ClaimAllArgs(options::OPT_fmodule_output);
3914 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
3919 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3920 ArgStringList &CmdArgs) {
3921 // -fsigned-char is default.
3922 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3923 options::OPT_fno_signed_char,
3924 options::OPT_funsigned_char,
3925 options::OPT_fno_unsigned_char)) {
3926 if (A->getOption().matches(options::OPT_funsigned_char) ||
3927 A->getOption().matches(options::OPT_fno_signed_char)) {
3928 CmdArgs.push_back("-fno-signed-char");
3930 } else if (!isSignedCharDefault(T)) {
3931 CmdArgs.push_back("-fno-signed-char");
3934 // The default depends on the language standard.
3935 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3937 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3938 options::OPT_fno_short_wchar)) {
3939 if (A->getOption().matches(options::OPT_fshort_wchar)) {
3940 CmdArgs.push_back("-fwchar-type=short");
3941 CmdArgs.push_back("-fno-signed-wchar");
3943 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3944 CmdArgs.push_back("-fwchar-type=int");
3946 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3947 CmdArgs.push_back("-fno-signed-wchar");
3949 CmdArgs.push_back("-fsigned-wchar");
3951 } else if (T.isOSzOS())
3952 CmdArgs.push_back("-fno-signed-wchar");
3955 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3956 const llvm::Triple &T, const ArgList &Args,
3957 ObjCRuntime &Runtime, bool InferCovariantReturns,
3958 const InputInfo &Input, ArgStringList &CmdArgs) {
3959 const llvm::Triple::ArchType Arch = TC.getArch();
3961 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3962 // is the default. Except for deployment target of 10.5, next runtime is
3963 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3964 if (Runtime.isNonFragile()) {
3965 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3966 options::OPT_fno_objc_legacy_dispatch,
3967 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3968 if (TC.UseObjCMixedDispatch())
3969 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3971 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3975 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3976 // to do Array/Dictionary subscripting by default.
3977 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3978 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3979 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3981 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3982 // NOTE: This logic is duplicated in ToolChains.cpp.
3983 if (isObjCAutoRefCount(Args)) {
3986 CmdArgs.push_back("-fobjc-arc");
3988 // FIXME: It seems like this entire block, and several around it should be
3989 // wrapped in isObjC, but for now we just use it here as this is where it
3990 // was being used previously.
3991 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3992 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3993 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3995 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3998 // Allow the user to enable full exceptions code emission.
3999 // We default off for Objective-C, on for Objective-C++.
4000 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4001 options::OPT_fno_objc_arc_exceptions,
4002 /*Default=*/types::isCXX(Input.getType())))
4003 CmdArgs.push_back("-fobjc-arc-exceptions");
4006 // Silence warning for full exception code emission options when explicitly
4007 // set to use no ARC.
4008 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4009 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4010 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4013 // Allow the user to control whether messages can be converted to runtime
4015 if (types::isObjC(Input.getType())) {
4016 auto *Arg = Args.getLastArg(
4017 options::OPT_fobjc_convert_messages_to_runtime_calls,
4018 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4020 Arg->getOption().matches(
4021 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4022 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4025 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4027 if (InferCovariantReturns)
4028 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4030 // Pass down -fobjc-weak or -fno-objc-weak if present.
4031 if (types::isObjC(Input.getType())) {
4033 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4036 } else if (!Runtime.allowsWeak()) {
4037 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4038 D.Diag(diag::err_objc_weak_unsupported);
4040 WeakArg->render(Args, CmdArgs);
4044 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4045 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4048 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4049 ArgStringList &CmdArgs) {
4050 bool CaretDefault = true;
4051 bool ColumnDefault = true;
4053 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4054 options::OPT__SLASH_diagnostics_column,
4055 options::OPT__SLASH_diagnostics_caret)) {
4056 switch (A->getOption().getID()) {
4057 case options::OPT__SLASH_diagnostics_caret:
4058 CaretDefault = true;
4059 ColumnDefault = true;
4061 case options::OPT__SLASH_diagnostics_column:
4062 CaretDefault = false;
4063 ColumnDefault = true;
4065 case options::OPT__SLASH_diagnostics_classic:
4066 CaretDefault = false;
4067 ColumnDefault = false;
4072 // -fcaret-diagnostics is default.
4073 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4074 options::OPT_fno_caret_diagnostics, CaretDefault))
4075 CmdArgs.push_back("-fno-caret-diagnostics");
4077 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4078 options::OPT_fno_diagnostics_fixit_info);
4079 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4080 options::OPT_fno_diagnostics_show_option);
4083 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4084 CmdArgs.push_back("-fdiagnostics-show-category");
4085 CmdArgs.push_back(A->getValue());
4088 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4089 options::OPT_fno_diagnostics_show_hotness);
4092 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4094 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4095 CmdArgs.push_back(Args.MakeArgString(Opt));
4099 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4101 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4102 CmdArgs.push_back(Args.MakeArgString(Opt));
4105 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4106 CmdArgs.push_back("-fdiagnostics-format");
4107 CmdArgs.push_back(A->getValue());
4108 if (StringRef(A->getValue()) == "sarif" ||
4109 StringRef(A->getValue()) == "SARIF")
4110 D.Diag(diag::warn_drv_sarif_format_unstable);
4113 if (const Arg *A = Args.getLastArg(
4114 options::OPT_fdiagnostics_show_note_include_stack,
4115 options::OPT_fno_diagnostics_show_note_include_stack)) {
4116 const Option &O = A->getOption();
4117 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4118 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4120 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4123 // Color diagnostics are parsed by the driver directly from argv and later
4124 // re-parsed to construct this job; claim any possible color diagnostic here
4125 // to avoid warn_drv_unused_argument and diagnose bad
4126 // OPT_fdiagnostics_color_EQ values.
4127 Args.getLastArg(options::OPT_fcolor_diagnostics,
4128 options::OPT_fno_color_diagnostics);
4129 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4130 StringRef Value(A->getValue());
4131 if (Value != "always" && Value != "never" && Value != "auto")
4132 D.Diag(diag::err_drv_invalid_argument_to_option)
4133 << Value << A->getOption().getName();
4136 if (D.getDiags().getDiagnosticOptions().ShowColors)
4137 CmdArgs.push_back("-fcolor-diagnostics");
4139 if (Args.hasArg(options::OPT_fansi_escape_codes))
4140 CmdArgs.push_back("-fansi-escape-codes");
4142 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4143 options::OPT_fno_show_source_location);
4145 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4146 options::OPT_fno_diagnostics_show_line_numbers);
4148 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4149 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4151 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4153 CmdArgs.push_back("-fno-show-column");
4155 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4156 options::OPT_fno_spell_checking);
4159 DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4160 const ArgList &Args, Arg *&Arg) {
4161 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4162 options::OPT_gno_split_dwarf);
4163 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4164 return DwarfFissionKind::None;
4166 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4167 return DwarfFissionKind::Split;
4169 StringRef Value = Arg->getValue();
4170 if (Value == "split")
4171 return DwarfFissionKind::Split;
4172 if (Value == "single")
4173 return DwarfFissionKind::Single;
4175 D.Diag(diag::err_drv_unsupported_option_argument)
4176 << Arg->getSpelling() << Arg->getValue();
4177 return DwarfFissionKind::None;
4180 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4181 const ArgList &Args, ArgStringList &CmdArgs,
4182 unsigned DwarfVersion) {
4183 auto *DwarfFormatArg =
4184 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4185 if (!DwarfFormatArg)
4188 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4189 if (DwarfVersion < 3)
4190 D.Diag(diag::err_drv_argument_only_allowed_with)
4191 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4192 else if (!T.isArch64Bit())
4193 D.Diag(diag::err_drv_argument_only_allowed_with)
4194 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4195 else if (!T.isOSBinFormatELF())
4196 D.Diag(diag::err_drv_argument_only_allowed_with)
4197 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4200 DwarfFormatArg->render(Args, CmdArgs);
4204 renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4205 const ArgList &Args, bool EmitCodeView, bool IRInput,
4206 ArgStringList &CmdArgs,
4207 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4208 DwarfFissionKind &DwarfFission) {
4209 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4210 options::OPT_fno_debug_info_for_profiling, false) &&
4211 checkDebugInfoOption(
4212 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4213 CmdArgs.push_back("-fdebug-info-for-profiling");
4215 // The 'g' groups options involve a somewhat intricate sequence of decisions
4216 // about what to pass from the driver to the frontend, but by the time they
4217 // reach cc1 they've been factored into three well-defined orthogonal choices:
4218 // * what level of debug info to generate
4219 // * what dwarf version to write
4220 // * what debugger tuning to use
4221 // This avoids having to monkey around further in cc1 other than to disable
4222 // codeview if not running in a Windows environment. Perhaps even that
4223 // decision should be made in the driver as well though.
4224 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4226 bool SplitDWARFInlining =
4227 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4228 options::OPT_fno_split_dwarf_inlining, false);
4230 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4231 // object file generation and no IR generation, -gN should not be needed. So
4232 // allow -gsplit-dwarf with either -gN or IR input.
4233 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4235 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4236 if (DwarfFission != DwarfFissionKind::None &&
4237 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4238 DwarfFission = DwarfFissionKind::None;
4239 SplitDWARFInlining = false;
4242 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4243 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4245 // If the last option explicitly specified a debug-info level, use it.
4246 if (checkDebugInfoOption(A, Args, D, TC) &&
4247 A->getOption().matches(options::OPT_gN_Group)) {
4248 DebugInfoKind = debugLevelToInfoKind(*A);
4249 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4250 // complicated if you've disabled inline info in the skeleton CUs
4251 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4252 // line-tables-only, so let those compose naturally in that case.
4253 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4254 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4255 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4256 SplitDWARFInlining))
4257 DwarfFission = DwarfFissionKind::None;
4261 // If a debugger tuning argument appeared, remember it.
4262 bool HasDebuggerTuning = false;
4264 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4265 HasDebuggerTuning = true;
4266 if (checkDebugInfoOption(A, Args, D, TC)) {
4267 if (A->getOption().matches(options::OPT_glldb))
4268 DebuggerTuning = llvm::DebuggerKind::LLDB;
4269 else if (A->getOption().matches(options::OPT_gsce))
4270 DebuggerTuning = llvm::DebuggerKind::SCE;
4271 else if (A->getOption().matches(options::OPT_gdbx))
4272 DebuggerTuning = llvm::DebuggerKind::DBX;
4274 DebuggerTuning = llvm::DebuggerKind::GDB;
4278 // If a -gdwarf argument appeared, remember it.
4279 bool EmitDwarf = false;
4280 if (const Arg *A = getDwarfNArg(Args))
4281 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4283 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4284 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4286 // If the user asked for debug info but did not explicitly specify -gcodeview
4287 // or -gdwarf, ask the toolchain for the default format.
4288 if (!EmitCodeView && !EmitDwarf &&
4289 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4290 switch (TC.getDefaultDebugFormat()) {
4291 case llvm::codegenoptions::DIF_CodeView:
4292 EmitCodeView = true;
4294 case llvm::codegenoptions::DIF_DWARF:
4300 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4301 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4302 // be lower than what the user wanted.
4304 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4305 // Clamp effective DWARF version to the max supported by the toolchain.
4306 EffectiveDWARFVersion =
4307 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4309 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4312 // -gline-directives-only supported only for the DWARF debug info.
4313 if (RequestedDWARFVersion == 0 &&
4314 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4315 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4317 // strict DWARF is set to false by default. But for DBX, we need it to be set
4318 // as true by default.
4319 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4320 (void)checkDebugInfoOption(A, Args, D, TC);
4321 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4322 DebuggerTuning == llvm::DebuggerKind::DBX))
4323 CmdArgs.push_back("-gstrict-dwarf");
4325 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4326 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4328 // Column info is included by default for everything except SCE and
4329 // CodeView. Clang doesn't track end columns, just starting columns, which,
4330 // in theory, is fine for CodeView (and PDB). In practice, however, the
4331 // Microsoft debuggers don't handle missing end columns well, and the AIX
4332 // debugger DBX also doesn't handle the columns well, so it's better not to
4333 // include any column info.
4334 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4335 (void)checkDebugInfoOption(A, Args, D, TC);
4336 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4338 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4339 DebuggerTuning != llvm::DebuggerKind::DBX)))
4340 CmdArgs.push_back("-gno-column-info");
4342 // FIXME: Move backend command line options to the module.
4343 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4344 // If -gline-tables-only or -gline-directives-only is the last option it
4346 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4348 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4349 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4350 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4351 CmdArgs.push_back("-dwarf-ext-refs");
4352 CmdArgs.push_back("-fmodule-format=obj");
4357 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4358 CmdArgs.push_back("-fsplit-dwarf-inlining");
4360 // After we've dealt with all combinations of things that could
4361 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4362 // figure out if we need to "upgrade" it to standalone debug info.
4363 // We parse these two '-f' options whether or not they will be used,
4364 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4365 bool NeedFullDebug = Args.hasFlag(
4366 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4367 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4368 TC.GetDefaultStandaloneDebug());
4369 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4370 (void)checkDebugInfoOption(A, Args, D, TC);
4372 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4373 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4374 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4375 options::OPT_feliminate_unused_debug_types, false))
4376 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4377 else if (NeedFullDebug)
4378 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4381 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4383 // Source embedding is a vendor extension to DWARF v5. By now we have
4384 // checked if a DWARF version was stated explicitly, and have otherwise
4385 // fallen back to the target default, so if this is still not at least 5
4386 // we emit an error.
4387 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4388 if (RequestedDWARFVersion < 5)
4389 D.Diag(diag::err_drv_argument_only_allowed_with)
4390 << A->getAsString(Args) << "-gdwarf-5";
4391 else if (EffectiveDWARFVersion < 5)
4392 // The toolchain has reduced allowed dwarf version, so we can't enable
4394 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4395 << A->getAsString(Args) << TC.getTripleString() << 5
4396 << EffectiveDWARFVersion;
4397 else if (checkDebugInfoOption(A, Args, D, TC))
4398 CmdArgs.push_back("-gembed-source");
4402 CmdArgs.push_back("-gcodeview");
4404 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4405 options::OPT_gno_codeview_ghash);
4407 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4408 options::OPT_gno_codeview_command_line);
4411 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4412 options::OPT_gno_inline_line_tables);
4414 // When emitting remarks, we need at least debug lines in the output.
4415 if (willEmitRemarks(Args) &&
4416 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4417 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4419 // Adjust the debug info kind for the given toolchain.
4420 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4422 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4424 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4425 T.isOSAIX() && !HasDebuggerTuning
4426 ? llvm::DebuggerKind::Default
4429 // -fdebug-macro turns on macro debug info generation.
4430 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4432 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4434 CmdArgs.push_back("-debug-info-macro");
4436 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4437 const auto *PubnamesArg =
4438 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4439 options::OPT_gpubnames, options::OPT_gno_pubnames);
4440 if (DwarfFission != DwarfFissionKind::None ||
4441 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4443 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4444 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4445 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4446 options::OPT_gpubnames)
4448 : "-ggnu-pubnames");
4449 const auto *SimpleTemplateNamesArg =
4450 Args.getLastArg(options::OPT_gsimple_template_names,
4451 options::OPT_gno_simple_template_names);
4452 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4453 if (SimpleTemplateNamesArg &&
4454 checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4455 const auto &Opt = SimpleTemplateNamesArg->getOption();
4456 if (Opt.matches(options::OPT_gsimple_template_names)) {
4457 ForwardTemplateParams = true;
4458 CmdArgs.push_back("-gsimple-template-names=simple");
4462 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4463 StringRef v = A->getValue();
4464 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4467 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4468 options::OPT_fno_debug_ranges_base_address);
4470 // -gdwarf-aranges turns on the emission of the aranges section in the
4472 // Always enabled for SCE tuning.
4473 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4474 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4475 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4477 CmdArgs.push_back("-mllvm");
4478 CmdArgs.push_back("-generate-arange-section");
4481 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4482 options::OPT_fno_force_dwarf_frame);
4484 if (Args.hasFlag(options::OPT_fdebug_types_section,
4485 options::OPT_fno_debug_types_section, false)) {
4486 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4487 D.Diag(diag::err_drv_unsupported_opt_for_target)
4488 << Args.getLastArg(options::OPT_fdebug_types_section)
4491 } else if (checkDebugInfoOption(
4492 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4494 CmdArgs.push_back("-mllvm");
4495 CmdArgs.push_back("-generate-type-units");
4499 // To avoid join/split of directory+filename, the integrated assembler prefers
4500 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4501 // form before DWARF v5.
4502 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4503 options::OPT_fno_dwarf_directory_asm,
4504 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4505 CmdArgs.push_back("-fno-dwarf-directory-asm");
4507 // Decide how to render forward declarations of template instantiations.
4508 // SCE wants full descriptions, others just get them in the name.
4509 if (ForwardTemplateParams)
4510 CmdArgs.push_back("-debug-forward-template-params");
4512 // Do we need to explicitly import anonymous namespaces into the parent
4514 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4515 CmdArgs.push_back("-dwarf-explicit-import");
4517 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4518 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4521 static void ProcessVSRuntimeLibrary(const ArgList &Args,
4522 ArgStringList &CmdArgs) {
4523 unsigned RTOptionID = options::OPT__SLASH_MT;
4525 if (Args.hasArg(options::OPT__SLASH_LDd))
4526 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4527 // but defining _DEBUG is sticky.
4528 RTOptionID = options::OPT__SLASH_MTd;
4530 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4531 RTOptionID = A->getOption().getID();
4533 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4534 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4535 .Case("static", options::OPT__SLASH_MT)
4536 .Case("static_dbg", options::OPT__SLASH_MTd)
4537 .Case("dll", options::OPT__SLASH_MD)
4538 .Case("dll_dbg", options::OPT__SLASH_MDd)
4539 .Default(options::OPT__SLASH_MT);
4542 StringRef FlagForCRT;
4543 switch (RTOptionID) {
4544 case options::OPT__SLASH_MD:
4545 if (Args.hasArg(options::OPT__SLASH_LDd))
4546 CmdArgs.push_back("-D_DEBUG");
4547 CmdArgs.push_back("-D_MT");
4548 CmdArgs.push_back("-D_DLL");
4549 FlagForCRT = "--dependent-lib=msvcrt";
4551 case options::OPT__SLASH_MDd:
4552 CmdArgs.push_back("-D_DEBUG");
4553 CmdArgs.push_back("-D_MT");
4554 CmdArgs.push_back("-D_DLL");
4555 FlagForCRT = "--dependent-lib=msvcrtd";
4557 case options::OPT__SLASH_MT:
4558 if (Args.hasArg(options::OPT__SLASH_LDd))
4559 CmdArgs.push_back("-D_DEBUG");
4560 CmdArgs.push_back("-D_MT");
4561 CmdArgs.push_back("-flto-visibility-public-std");
4562 FlagForCRT = "--dependent-lib=libcmt";
4564 case options::OPT__SLASH_MTd:
4565 CmdArgs.push_back("-D_DEBUG");
4566 CmdArgs.push_back("-D_MT");
4567 CmdArgs.push_back("-flto-visibility-public-std");
4568 FlagForCRT = "--dependent-lib=libcmtd";
4571 llvm_unreachable("Unexpected option ID.");
4574 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4575 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4577 CmdArgs.push_back(FlagForCRT.data());
4579 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4580 // users want. The /Za flag to cl.exe turns this off, but it's not
4581 // implemented in clang.
4582 CmdArgs.push_back("--dependent-lib=oldnames");
4586 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4587 const InputInfo &Output, const InputInfoList &Inputs,
4588 const ArgList &Args, const char *LinkingOutput) const {
4589 const auto &TC = getToolChain();
4590 const llvm::Triple &RawTriple = TC.getTriple();
4591 const llvm::Triple &Triple = TC.getEffectiveTriple();
4592 const std::string &TripleStr = Triple.getTriple();
4595 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4596 const Driver &D = TC.getDriver();
4597 ArgStringList CmdArgs;
4599 assert(Inputs.size() >= 1 && "Must have at least one input.");
4600 // CUDA/HIP compilation may have multiple inputs (source file + results of
4601 // device-side compilations). OpenMP device jobs also take the host IR as a
4602 // second input. Module precompilation accepts a list of header files to
4603 // include as part of the module. API extraction accepts a list of header
4604 // files whose API information is emitted in the output. All other jobs are
4605 // expected to have exactly one input.
4606 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4607 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4608 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4609 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4610 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4611 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4612 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4613 JA.isDeviceOffloading(Action::OFK_Host));
4614 bool IsHostOffloadingAction =
4615 JA.isHostOffloading(Action::OFK_OpenMP) ||
4616 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4617 Args.hasFlag(options::OPT_offload_new_driver,
4618 options::OPT_no_offload_new_driver, false));
4621 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4622 bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4623 auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4625 // Extract API doesn't have a main input file, so invent a fake one as a
4627 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4630 const InputInfo &Input =
4631 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4633 InputInfoList ExtractAPIInputs;
4634 InputInfoList HostOffloadingInputs;
4635 const InputInfo *CudaDeviceInput = nullptr;
4636 const InputInfo *OpenMPDeviceInput = nullptr;
4637 for (const InputInfo &I : Inputs) {
4638 if (&I == &Input || I.getType() == types::TY_Nothing) {
4639 // This is the primary input or contains nothing.
4640 } else if (IsExtractAPI) {
4641 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4642 if (I.getType() != ExpectedInputType) {
4643 D.Diag(diag::err_drv_extract_api_wrong_kind)
4644 << I.getFilename() << types::getTypeName(I.getType())
4645 << types::getTypeName(ExpectedInputType);
4647 ExtractAPIInputs.push_back(I);
4648 } else if (IsHostOffloadingAction) {
4649 HostOffloadingInputs.push_back(I);
4650 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4651 CudaDeviceInput = &I;
4652 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4653 OpenMPDeviceInput = &I;
4655 llvm_unreachable("unexpectedly given multiple inputs");
4659 const llvm::Triple *AuxTriple =
4660 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4661 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4662 bool IsIAMCU = RawTriple.isOSIAMCU();
4664 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
4665 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4666 // Windows), we need to pass Windows-specific flags to cc1.
4667 if (IsCuda || IsHIP)
4668 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4670 // C++ is not supported for IAMCU.
4671 if (IsIAMCU && types::isCXX(Input.getType()))
4672 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4674 // Invoke ourselves in -cc1 mode.
4676 // FIXME: Implement custom jobs for internal actions.
4677 CmdArgs.push_back("-cc1");
4679 // Add the "effective" target triple.
4680 CmdArgs.push_back("-triple");
4681 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4683 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4684 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4685 Args.ClaimAllArgs(options::OPT_MJ);
4686 } else if (const Arg *GenCDBFragment =
4687 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4688 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4689 TripleStr, Output, Input, Args);
4690 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4693 if (IsCuda || IsHIP) {
4694 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4696 std::string NormalizedTriple;
4697 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4698 JA.isDeviceOffloading(Action::OFK_HIP))
4699 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4703 // Host-side compilation.
4705 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4706 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4710 // We need to figure out which CUDA version we're compiling for, as that
4711 // determines how we load and launch GPU kernels.
4712 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4713 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4714 assert(CTC && "Expected valid CUDA Toolchain.");
4715 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4716 CmdArgs.push_back(Args.MakeArgString(
4717 Twine("-target-sdk-version=") +
4718 CudaVersionToString(CTC->CudaInstallation.version())));
4719 // Unsized function arguments used for variadics were introduced in
4720 // CUDA-9.0. We still do not support generating code that actually uses
4721 // variadic arguments yet, but we do need to allow parsing them as
4722 // recent CUDA headers rely on that.
4723 // https://github.com/llvm/llvm-project/issues/58410
4724 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
4725 CmdArgs.push_back("-fcuda-allow-variadic-functions");
4728 CmdArgs.push_back("-aux-triple");
4729 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4731 if (JA.isDeviceOffloading(Action::OFK_HIP) &&
4732 getToolChain().getTriple().isAMDGPU()) {
4733 // Device side compilation printf
4734 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
4735 CmdArgs.push_back(Args.MakeArgString(
4737 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
4738 // Force compiler error on invalid conversion specifiers
4740 Args.MakeArgString("-Werror=format-invalid-specifier"));
4745 // Unconditionally claim the printf option now to avoid unused diagnostic.
4746 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
4749 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4750 CmdArgs.push_back("-fsycl-is-device");
4752 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4753 A->render(Args, CmdArgs);
4755 // Ensure the default version in SYCL mode is 2020.
4756 CmdArgs.push_back("-sycl-std=2020");
4760 if (IsOpenMPDevice) {
4761 // We have to pass the triple of the host if compiling for an OpenMP device.
4762 std::string NormalizedTriple =
4763 C.getSingleOffloadToolChain<Action::OFK_Host>()
4766 CmdArgs.push_back("-aux-triple");
4767 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4770 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4771 Triple.getArch() == llvm::Triple::thumb)) {
4772 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4773 unsigned Version = 0;
4775 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4776 if (Failure || Version < 7)
4777 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4781 // Push all default warning arguments that are specific to
4782 // the given target. These come before user provided warning options
4784 TC.addClangWarningOptions(CmdArgs);
4786 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4787 if (Triple.isSPIR() || Triple.isSPIRV())
4788 CmdArgs.push_back("-Wspir-compat");
4790 // Select the appropriate action.
4791 RewriteKind rewriteKind = RK_None;
4793 bool UnifiedLTO = false;
4795 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
4796 options::OPT_fno_unified_lto, Triple.isPS());
4798 CmdArgs.push_back("-funified-lto");
4801 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4802 // it claims when not running an assembler. Otherwise, clang would emit
4803 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4804 // flags while debugging something. That'd be somewhat inconvenient, and it's
4805 // also inconsistent with most other flags -- we don't warn on
4806 // -ffunction-sections not being used in -E mode either for example, even
4807 // though it's not really used either.
4808 if (!isa<AssembleJobAction>(JA)) {
4809 // The args claimed here should match the args used in
4810 // CollectArgsForIntegratedAssembler().
4811 if (TC.useIntegratedAs()) {
4812 Args.ClaimAllArgs(options::OPT_mrelax_all);
4813 Args.ClaimAllArgs(options::OPT_mno_relax_all);
4814 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4815 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4816 switch (C.getDefaultToolChain().getArch()) {
4817 case llvm::Triple::arm:
4818 case llvm::Triple::armeb:
4819 case llvm::Triple::thumb:
4820 case llvm::Triple::thumbeb:
4821 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4827 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4828 Args.ClaimAllArgs(options::OPT_Xassembler);
4829 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4832 if (isa<AnalyzeJobAction>(JA)) {
4833 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4834 CmdArgs.push_back("-analyze");
4835 } else if (isa<MigrateJobAction>(JA)) {
4836 CmdArgs.push_back("-migrate");
4837 } else if (isa<PreprocessJobAction>(JA)) {
4838 if (Output.getType() == types::TY_Dependencies)
4839 CmdArgs.push_back("-Eonly");
4841 CmdArgs.push_back("-E");
4842 if (Args.hasArg(options::OPT_rewrite_objc) &&
4843 !Args.hasArg(options::OPT_g_Group))
4844 CmdArgs.push_back("-P");
4845 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
4846 CmdArgs.push_back("-fdirectives-only");
4848 } else if (isa<AssembleJobAction>(JA)) {
4849 CmdArgs.push_back("-emit-obj");
4851 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4853 // Also ignore explicit -force_cpusubtype_ALL option.
4854 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4855 } else if (isa<PrecompileJobAction>(JA)) {
4856 if (JA.getType() == types::TY_Nothing)
4857 CmdArgs.push_back("-fsyntax-only");
4858 else if (JA.getType() == types::TY_ModuleFile)
4859 CmdArgs.push_back("-emit-module-interface");
4860 else if (JA.getType() == types::TY_HeaderUnit)
4861 CmdArgs.push_back("-emit-header-unit");
4863 CmdArgs.push_back("-emit-pch");
4864 } else if (isa<VerifyPCHJobAction>(JA)) {
4865 CmdArgs.push_back("-verify-pch");
4866 } else if (isa<ExtractAPIJobAction>(JA)) {
4867 assert(JA.getType() == types::TY_API_INFO &&
4868 "Extract API actions must generate a API information.");
4869 CmdArgs.push_back("-extract-api");
4870 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
4871 ProductNameArg->render(Args, CmdArgs);
4872 if (Arg *ExtractAPIIgnoresFileArg =
4873 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
4874 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
4876 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4877 "Invalid action for clang tool.");
4878 if (JA.getType() == types::TY_Nothing) {
4879 CmdArgs.push_back("-fsyntax-only");
4880 } else if (JA.getType() == types::TY_LLVM_IR ||
4881 JA.getType() == types::TY_LTO_IR) {
4882 CmdArgs.push_back("-emit-llvm");
4883 } else if (JA.getType() == types::TY_LLVM_BC ||
4884 JA.getType() == types::TY_LTO_BC) {
4885 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4886 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4887 Args.hasArg(options::OPT_emit_llvm)) {
4888 CmdArgs.push_back("-emit-llvm");
4890 CmdArgs.push_back("-emit-llvm-bc");
4892 } else if (JA.getType() == types::TY_IFS ||
4893 JA.getType() == types::TY_IFS_CPP) {
4895 Args.hasArg(options::OPT_interface_stub_version_EQ)
4896 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4898 CmdArgs.push_back("-emit-interface-stubs");
4900 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4901 } else if (JA.getType() == types::TY_PP_Asm) {
4902 CmdArgs.push_back("-S");
4903 } else if (JA.getType() == types::TY_AST) {
4904 CmdArgs.push_back("-emit-pch");
4905 } else if (JA.getType() == types::TY_ModuleFile) {
4906 CmdArgs.push_back("-module-file-info");
4907 } else if (JA.getType() == types::TY_RewrittenObjC) {
4908 CmdArgs.push_back("-rewrite-objc");
4909 rewriteKind = RK_NonFragile;
4910 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4911 CmdArgs.push_back("-rewrite-objc");
4912 rewriteKind = RK_Fragile;
4914 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4917 // Preserve use-list order by default when emitting bitcode, so that
4918 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4919 // same result as running passes here. For LTO, we don't need to preserve
4920 // the use-list order, since serialization to bitcode is part of the flow.
4921 if (JA.getType() == types::TY_LLVM_BC)
4922 CmdArgs.push_back("-emit-llvm-uselists");
4925 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
4926 !Args.hasFlag(options::OPT_offload_new_driver,
4927 options::OPT_no_offload_new_driver, false) &&
4928 !Triple.isAMDGPU()) {
4929 D.Diag(diag::err_drv_unsupported_opt_for_target)
4930 << Args.getLastArg(options::OPT_foffload_lto,
4931 options::OPT_foffload_lto_EQ)
4933 << Triple.getTriple();
4934 } else if (Triple.isNVPTX() && !IsRDCMode &&
4935 JA.isDeviceOffloading(Action::OFK_Cuda)) {
4936 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
4937 << Args.getLastArg(options::OPT_foffload_lto,
4938 options::OPT_foffload_lto_EQ)
4942 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4943 CmdArgs.push_back(Args.MakeArgString(
4944 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4945 // PS4 uses the legacy LTO API, which does not support some of the
4946 // features enabled by -flto-unit.
4947 if (!RawTriple.isPS4() ||
4948 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
4949 CmdArgs.push_back("-flto-unit");
4954 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
4956 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4957 if (!types::isLLVMIR(Input.getType()))
4958 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4959 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4962 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4963 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4965 if (Args.getLastArg(options::OPT_save_temps_EQ))
4966 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4968 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4969 options::OPT_fmemory_profile_EQ,
4970 options::OPT_fno_memory_profile);
4972 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4973 MemProfArg->render(Args, CmdArgs);
4975 if (auto *MemProfUseArg =
4976 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
4978 D.Diag(diag::err_drv_argument_not_allowed_with)
4979 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
4980 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
4981 options::OPT_fprofile_generate_EQ))
4982 D.Diag(diag::err_drv_argument_not_allowed_with)
4983 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
4984 MemProfUseArg->render(Args, CmdArgs);
4987 // Embed-bitcode option.
4988 // Only white-listed flags below are allowed to be embedded.
4989 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
4990 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4991 // Add flags implied by -fembed-bitcode.
4992 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4993 // Disable all llvm IR level optimizations.
4994 CmdArgs.push_back("-disable-llvm-passes");
4996 // Render target options.
4997 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4999 // reject options that shouldn't be supported in bitcode
5000 // also reject kernel/kext
5001 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5002 options::OPT_mkernel,
5003 options::OPT_fapple_kext,
5004 options::OPT_ffunction_sections,
5005 options::OPT_fno_function_sections,
5006 options::OPT_fdata_sections,
5007 options::OPT_fno_data_sections,
5008 options::OPT_fbasic_block_sections_EQ,
5009 options::OPT_funique_internal_linkage_names,
5010 options::OPT_fno_unique_internal_linkage_names,
5011 options::OPT_funique_section_names,
5012 options::OPT_fno_unique_section_names,
5013 options::OPT_funique_basic_block_section_names,
5014 options::OPT_fno_unique_basic_block_section_names,
5015 options::OPT_mrestrict_it,
5016 options::OPT_mno_restrict_it,
5017 options::OPT_mstackrealign,
5018 options::OPT_mno_stackrealign,
5019 options::OPT_mstack_alignment,
5020 options::OPT_mcmodel_EQ,
5021 options::OPT_mlong_calls,
5022 options::OPT_mno_long_calls,
5023 options::OPT_ggnu_pubnames,
5024 options::OPT_gdwarf_aranges,
5025 options::OPT_fdebug_types_section,
5026 options::OPT_fno_debug_types_section,
5027 options::OPT_fdwarf_directory_asm,
5028 options::OPT_fno_dwarf_directory_asm,
5029 options::OPT_mrelax_all,
5030 options::OPT_mno_relax_all,
5031 options::OPT_ftrap_function_EQ,
5032 options::OPT_ffixed_r9,
5033 options::OPT_mfix_cortex_a53_835769,
5034 options::OPT_mno_fix_cortex_a53_835769,
5035 options::OPT_ffixed_x18,
5036 options::OPT_mglobal_merge,
5037 options::OPT_mno_global_merge,
5038 options::OPT_mred_zone,
5039 options::OPT_mno_red_zone,
5040 options::OPT_Wa_COMMA,
5041 options::OPT_Xassembler,
5044 for (const auto &A : Args)
5045 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5046 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5048 // Render the CodeGen options that need to be passed.
5049 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5050 options::OPT_fno_optimize_sibling_calls);
5052 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
5055 // Render ABI arguments
5056 switch (TC.getArch()) {
5058 case llvm::Triple::arm:
5059 case llvm::Triple::armeb:
5060 case llvm::Triple::thumbeb:
5061 RenderARMABI(D, Triple, Args, CmdArgs);
5063 case llvm::Triple::aarch64:
5064 case llvm::Triple::aarch64_32:
5065 case llvm::Triple::aarch64_be:
5066 RenderAArch64ABI(Triple, Args, CmdArgs);
5070 // Optimization level for CodeGen.
5071 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5072 if (A->getOption().matches(options::OPT_O4)) {
5073 CmdArgs.push_back("-O3");
5074 D.Diag(diag::warn_O4_is_O3);
5076 A->render(Args, CmdArgs);
5080 // Input/Output file.
5081 if (Output.getType() == types::TY_Dependencies) {
5082 // Handled with other dependency code.
5083 } else if (Output.isFilename()) {
5084 CmdArgs.push_back("-o");
5085 CmdArgs.push_back(Output.getFilename());
5087 assert(Output.isNothing() && "Input output.");
5090 for (const auto &II : Inputs) {
5091 addDashXForInput(Args, II, CmdArgs);
5092 if (II.isFilename())
5093 CmdArgs.push_back(II.getFilename());
5095 II.getInputArg().renderAsInput(Args, CmdArgs);
5098 C.addCommand(std::make_unique<Command>(
5099 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5100 CmdArgs, Inputs, Output, D.getPrependArg()));
5104 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5105 CmdArgs.push_back("-fembed-bitcode=marker");
5107 // We normally speed up the clang process a bit by skipping destructors at
5108 // exit, but when we're generating diagnostics we can rely on some of the
5110 if (!C.isForDiagnostics())
5111 CmdArgs.push_back("-disable-free");
5112 CmdArgs.push_back("-clear-ast-before-backend");
5115 const bool IsAssertBuild = false;
5117 const bool IsAssertBuild = true;
5120 // Disable the verification pass in -asserts builds.
5122 CmdArgs.push_back("-disable-llvm-verifier");
5124 // Discard value names in assert builds unless otherwise specified.
5125 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5126 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5127 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5128 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5129 return types::isLLVMIR(II.getType());
5131 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5133 CmdArgs.push_back("-discard-value-names");
5136 // Set the main file name, so that debug info works even with
5138 CmdArgs.push_back("-main-file-name");
5139 CmdArgs.push_back(getBaseInputName(Args, Input));
5141 // Some flags which affect the language (via preprocessor
5143 if (Args.hasArg(options::OPT_static))
5144 CmdArgs.push_back("-static-define");
5146 if (Args.hasArg(options::OPT_municode))
5147 CmdArgs.push_back("-DUNICODE");
5149 if (isa<AnalyzeJobAction>(JA))
5150 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5152 if (isa<AnalyzeJobAction>(JA) ||
5153 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5154 CmdArgs.push_back("-setup-static-analyzer");
5156 // Enable compatilibily mode to avoid analyzer-config related errors.
5157 // Since we can't access frontend flags through hasArg, let's manually iterate
5159 bool FoundAnalyzerConfig = false;
5160 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5161 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5162 FoundAnalyzerConfig = true;
5165 if (!FoundAnalyzerConfig)
5166 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5167 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5168 FoundAnalyzerConfig = true;
5171 if (FoundAnalyzerConfig)
5172 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5174 CheckCodeGenerationOptions(D, Args);
5176 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5177 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5178 if (FunctionAlignment) {
5179 CmdArgs.push_back("-function-alignment");
5180 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5183 // We support -falign-loops=N where N is a power of 2. GCC supports more
5185 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5187 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5188 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5189 << A->getAsString(Args) << A->getValue();
5190 else if (Value & (Value - 1))
5191 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5192 << A->getAsString(Args) << A->getValue();
5193 // Treat =0 as unspecified (use the target preference).
5195 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5196 Twine(std::min(Value, 65536u))));
5199 if (Triple.isOSzOS()) {
5200 // On z/OS some of the system header feature macros need to
5201 // be defined to enable most cross platform projects to build
5202 // successfully. Ths include the libc++ library. A
5203 // complicating factor is that users can define these
5204 // macros to the same or different values. We need to add
5205 // the definition for these macros to the compilation command
5206 // if the user hasn't already defined them.
5208 auto findMacroDefinition = [&](const std::string &Macro) {
5209 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5210 return std::find_if(MacroDefs.begin(), MacroDefs.end(),
5211 [&](const std::string &M) {
5212 return M == Macro ||
5213 M.find(Macro + '=') != std::string::npos;
5214 }) != MacroDefs.end();
5217 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5218 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5219 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5220 // _OPEN_DEFAULT is required for XL compat
5221 if (!findMacroDefinition("_OPEN_DEFAULT"))
5222 CmdArgs.push_back("-D_OPEN_DEFAULT");
5223 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5224 // _XOPEN_SOURCE=600 is required for libcxx.
5225 if (!findMacroDefinition("_XOPEN_SOURCE"))
5226 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5230 llvm::Reloc::Model RelocationModel;
5233 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5234 Arg *LastPICDataRelArg =
5235 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5236 options::OPT_mpic_data_is_text_relative);
5237 bool NoPICDataIsTextRelative = false;
5238 if (LastPICDataRelArg) {
5239 if (LastPICDataRelArg->getOption().matches(
5240 options::OPT_mno_pic_data_is_text_relative)) {
5241 NoPICDataIsTextRelative = true;
5243 D.Diag(diag::err_drv_argument_only_allowed_with)
5244 << "-mno-pic-data-is-text-relative"
5247 if (!Triple.isSystemZ())
5248 D.Diag(diag::err_drv_unsupported_opt_for_target)
5249 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5250 : "-mpic-data-is-text-relative")
5254 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5255 RelocationModel == llvm::Reloc::ROPI_RWPI;
5256 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5257 RelocationModel == llvm::Reloc::ROPI_RWPI;
5259 if (Args.hasArg(options::OPT_mcmse) &&
5260 !Args.hasArg(options::OPT_fallow_unsupported)) {
5262 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5264 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5267 if (IsROPI && types::isCXX(Input.getType()) &&
5268 !Args.hasArg(options::OPT_fallow_unsupported))
5269 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5271 const char *RMName = RelocationModelName(RelocationModel);
5273 CmdArgs.push_back("-mrelocation-model");
5274 CmdArgs.push_back(RMName);
5277 CmdArgs.push_back("-pic-level");
5278 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5280 CmdArgs.push_back("-pic-is-pie");
5281 if (NoPICDataIsTextRelative)
5282 CmdArgs.push_back("-mcmodel=medium");
5285 if (RelocationModel == llvm::Reloc::ROPI ||
5286 RelocationModel == llvm::Reloc::ROPI_RWPI)
5287 CmdArgs.push_back("-fropi");
5288 if (RelocationModel == llvm::Reloc::RWPI ||
5289 RelocationModel == llvm::Reloc::ROPI_RWPI)
5290 CmdArgs.push_back("-frwpi");
5292 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5293 CmdArgs.push_back("-meabi");
5294 CmdArgs.push_back(A->getValue());
5297 // -fsemantic-interposition is forwarded to CC1: set the
5298 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5299 // make default visibility external linkage definitions dso_preemptable.
5301 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5302 // aliases (make default visibility external linkage definitions dso_local).
5303 // This is the CC1 default for ELF to match COFF/Mach-O.
5305 // Otherwise use Clang's traditional behavior: like
5306 // -fno-semantic-interposition but local aliases are not used. So references
5307 // can be interposed if not optimized out.
5308 if (Triple.isOSBinFormatELF()) {
5309 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5310 options::OPT_fno_semantic_interposition);
5311 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5312 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5313 bool SupportsLocalAlias =
5314 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5316 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5317 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5318 A->render(Args, CmdArgs);
5319 else if (!SupportsLocalAlias)
5320 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5326 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5327 if (!TC.isThreadModelSupported(A->getValue()))
5328 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5329 << A->getValue() << A->getAsString(Args);
5330 Model = A->getValue();
5332 Model = TC.getThreadModel();
5333 if (Model != "posix") {
5334 CmdArgs.push_back("-mthread-model");
5335 CmdArgs.push_back(Args.MakeArgString(Model));
5339 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5340 StringRef Name = A->getValue();
5341 if (Name == "SVML") {
5342 if (Triple.getArch() != llvm::Triple::x86 &&
5343 Triple.getArch() != llvm::Triple::x86_64)
5344 D.Diag(diag::err_drv_unsupported_opt_for_target)
5345 << Name << Triple.getArchName();
5346 } else if (Name == "LIBMVEC-X86") {
5347 if (Triple.getArch() != llvm::Triple::x86 &&
5348 Triple.getArch() != llvm::Triple::x86_64)
5349 D.Diag(diag::err_drv_unsupported_opt_for_target)
5350 << Name << Triple.getArchName();
5351 } else if (Name == "SLEEF" || Name == "ArmPL") {
5352 if (Triple.getArch() != llvm::Triple::aarch64 &&
5353 Triple.getArch() != llvm::Triple::aarch64_be)
5354 D.Diag(diag::err_drv_unsupported_opt_for_target)
5355 << Name << Triple.getArchName();
5357 A->render(Args, CmdArgs);
5360 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5361 options::OPT_fno_merge_all_constants, false))
5362 CmdArgs.push_back("-fmerge-all-constants");
5364 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5365 options::OPT_fno_delete_null_pointer_checks);
5367 // LLVM Code Generator Options.
5369 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5370 if (!Triple.isOSAIX() || Triple.isPPC32())
5371 D.Diag(diag::err_drv_unsupported_opt_for_target)
5372 << A->getSpelling() << RawTriple.str();
5373 CmdArgs.push_back("-mabi=quadword-atomics");
5376 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5377 // Emit the unsupported option error until the Clang's library integration
5378 // support for 128-bit long double is available for AIX.
5379 if (Triple.isOSAIX())
5380 D.Diag(diag::err_drv_unsupported_opt_for_target)
5381 << A->getSpelling() << RawTriple.str();
5384 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5385 StringRef V = A->getValue(), V1 = V;
5387 if (V1.consumeInteger(10, Size) || !V1.empty())
5388 D.Diag(diag::err_drv_invalid_argument_to_option)
5389 << V << A->getOption().getName();
5391 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5394 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5395 options::OPT_fno_jump_tables);
5396 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5397 options::OPT_fno_profile_sample_accurate);
5398 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5399 options::OPT_fno_preserve_as_comments);
5401 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5402 CmdArgs.push_back("-mregparm");
5403 CmdArgs.push_back(A->getValue());
5406 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5407 options::OPT_msvr4_struct_return)) {
5408 if (!TC.getTriple().isPPC32()) {
5409 D.Diag(diag::err_drv_unsupported_opt_for_target)
5410 << A->getSpelling() << RawTriple.str();
5411 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5412 CmdArgs.push_back("-maix-struct-return");
5414 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5415 CmdArgs.push_back("-msvr4-struct-return");
5419 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5420 options::OPT_freg_struct_return)) {
5421 if (TC.getArch() != llvm::Triple::x86) {
5422 D.Diag(diag::err_drv_unsupported_opt_for_target)
5423 << A->getSpelling() << RawTriple.str();
5424 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5425 CmdArgs.push_back("-fpcc-struct-return");
5427 assert(A->getOption().matches(options::OPT_freg_struct_return));
5428 CmdArgs.push_back("-freg-struct-return");
5432 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
5433 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5435 if (Args.hasArg(options::OPT_fenable_matrix)) {
5436 // enable-matrix is needed by both the LangOpts and by LLVM.
5437 CmdArgs.push_back("-fenable-matrix");
5438 CmdArgs.push_back("-mllvm");
5439 CmdArgs.push_back("-enable-matrix");
5442 CodeGenOptions::FramePointerKind FPKeepKind =
5443 getFramePointerKind(Args, RawTriple);
5444 const char *FPKeepKindStr = nullptr;
5445 switch (FPKeepKind) {
5446 case CodeGenOptions::FramePointerKind::None:
5447 FPKeepKindStr = "-mframe-pointer=none";
5449 case CodeGenOptions::FramePointerKind::NonLeaf:
5450 FPKeepKindStr = "-mframe-pointer=non-leaf";
5452 case CodeGenOptions::FramePointerKind::All:
5453 FPKeepKindStr = "-mframe-pointer=all";
5456 assert(FPKeepKindStr && "unknown FramePointerKind");
5457 CmdArgs.push_back(FPKeepKindStr);
5459 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5460 options::OPT_fno_zero_initialized_in_bss);
5462 bool OFastEnabled = isOptimizationLevelFast(Args);
5463 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5464 // enabled. This alias option is being used to simplify the hasFlag logic.
5465 OptSpecifier StrictAliasingAliasOption =
5466 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5467 // We turn strict aliasing off by default if we're in CL mode, since MSVC
5468 // doesn't do any TBAA.
5469 bool TBAAOnByDefault = !D.IsCLMode();
5470 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5471 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
5472 CmdArgs.push_back("-relaxed-aliasing");
5473 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5474 options::OPT_fno_struct_path_tbaa, true))
5475 CmdArgs.push_back("-no-struct-path-tbaa");
5476 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5477 options::OPT_fno_strict_enums);
5478 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5479 options::OPT_fno_strict_return);
5480 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5481 options::OPT_fno_allow_editor_placeholders);
5482 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5483 options::OPT_fno_strict_vtable_pointers);
5484 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5485 options::OPT_fno_force_emit_vtables);
5486 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5487 options::OPT_fno_optimize_sibling_calls);
5488 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5489 options::OPT_fno_escaping_block_tail_calls);
5491 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5492 options::OPT_fno_fine_grained_bitfield_accesses);
5494 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5495 options::OPT_fno_experimental_relative_cxx_abi_vtables);
5497 // Handle segmented stacks.
5498 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5499 options::OPT_fno_split_stack);
5501 // -fprotect-parens=0 is default.
5502 if (Args.hasFlag(options::OPT_fprotect_parens,
5503 options::OPT_fno_protect_parens, false))
5504 CmdArgs.push_back("-fprotect-parens");
5506 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5508 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5509 const llvm::Triple::ArchType Arch = TC.getArch();
5510 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5511 StringRef V = A->getValue();
5513 CmdArgs.push_back("-fextend-arguments=64");
5515 D.Diag(diag::err_drv_invalid_argument_to_option)
5516 << A->getValue() << A->getOption().getName();
5518 D.Diag(diag::err_drv_unsupported_opt_for_target)
5519 << A->getOption().getName() << TripleStr;
5522 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5523 if (TC.getArch() == llvm::Triple::avr)
5524 A->render(Args, CmdArgs);
5526 D.Diag(diag::err_drv_unsupported_opt_for_target)
5527 << A->getAsString(Args) << TripleStr;
5530 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5531 if (TC.getTriple().isX86())
5532 A->render(Args, CmdArgs);
5533 else if (TC.getTriple().isPPC() &&
5534 (A->getOption().getID() != options::OPT_mlong_double_80))
5535 A->render(Args, CmdArgs);
5537 D.Diag(diag::err_drv_unsupported_opt_for_target)
5538 << A->getAsString(Args) << TripleStr;
5541 // Decide whether to use verbose asm. Verbose assembly is the default on
5542 // toolchains which have the integrated assembler on by default.
5543 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5544 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5545 IsIntegratedAssemblerDefault))
5546 CmdArgs.push_back("-fno-verbose-asm");
5548 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5549 // use that to indicate the MC default in the backend.
5550 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5551 StringRef V = A->getValue();
5554 A->render(Args, CmdArgs);
5555 else if (!V.consumeInteger(10, Num) && Num > 0 &&
5556 (V.empty() || (V.consume_front(".") &&
5557 !V.consumeInteger(10, Num) && V.empty())))
5558 A->render(Args, CmdArgs);
5560 D.Diag(diag::err_drv_invalid_argument_to_option)
5561 << A->getValue() << A->getOption().getName();
5564 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5565 // option to disable integrated-as explictly.
5566 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5567 CmdArgs.push_back("-no-integrated-as");
5569 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5570 CmdArgs.push_back("-mdebug-pass");
5571 CmdArgs.push_back("Structure");
5573 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5574 CmdArgs.push_back("-mdebug-pass");
5575 CmdArgs.push_back("Arguments");
5578 // Enable -mconstructor-aliases except on darwin, where we have to work around
5579 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
5580 // aliases aren't supported.
5581 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5582 CmdArgs.push_back("-mconstructor-aliases");
5584 // Darwin's kernel doesn't support guard variables; just die if we
5586 if (KernelOrKext && RawTriple.isOSDarwin())
5587 CmdArgs.push_back("-fforbid-guard-variables");
5589 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5590 Triple.isWindowsGNUEnvironment())) {
5591 CmdArgs.push_back("-mms-bitfields");
5594 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5595 // defaults to -fno-direct-access-external-data. Pass the option if different
5596 // from the default.
5597 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5598 options::OPT_fno_direct_access_external_data))
5599 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5601 A->render(Args, CmdArgs);
5603 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5604 CmdArgs.push_back("-fno-plt");
5607 // -fhosted is default.
5608 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5609 // use Freestanding.
5611 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5614 CmdArgs.push_back("-ffreestanding");
5616 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5618 // This is a coarse approximation of what llvm-gcc actually does, both
5619 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5620 // complicated ways.
5621 auto SanitizeArgs = TC.getSanitizerArgs(Args);
5623 bool IsAsyncUnwindTablesDefault =
5624 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5625 bool IsSyncUnwindTablesDefault =
5626 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5628 bool AsyncUnwindTables = Args.hasFlag(
5629 options::OPT_fasynchronous_unwind_tables,
5630 options::OPT_fno_asynchronous_unwind_tables,
5631 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5634 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5635 IsSyncUnwindTablesDefault && !Freestanding);
5636 if (AsyncUnwindTables)
5637 CmdArgs.push_back("-funwind-tables=2");
5638 else if (UnwindTables)
5639 CmdArgs.push_back("-funwind-tables=1");
5641 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5642 // `--gpu-use-aux-triple-only` is specified.
5643 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5644 (IsCudaDevice || IsHIPDevice)) {
5645 const ArgList &HostArgs =
5646 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5647 std::string HostCPU =
5648 getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5649 if (!HostCPU.empty()) {
5650 CmdArgs.push_back("-aux-target-cpu");
5651 CmdArgs.push_back(Args.MakeArgString(HostCPU));
5653 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5654 /*ForAS*/ false, /*IsAux*/ true);
5657 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5659 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5660 StringRef CM = A->getValue();
5661 if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
5663 if (Triple.isOSAIX() && CM == "medium")
5664 CmdArgs.push_back("-mcmodel=large");
5665 else if (Triple.isAArch64() && (CM == "kernel" || CM == "medium"))
5666 D.Diag(diag::err_drv_invalid_argument_to_option)
5667 << CM << A->getOption().getName();
5669 A->render(Args, CmdArgs);
5671 D.Diag(diag::err_drv_invalid_argument_to_option)
5672 << CM << A->getOption().getName();
5676 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5677 StringRef Value = A->getValue();
5678 unsigned TLSSize = 0;
5679 Value.getAsInteger(10, TLSSize);
5680 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5681 D.Diag(diag::err_drv_unsupported_opt_for_target)
5682 << A->getOption().getName() << TripleStr;
5683 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5684 D.Diag(diag::err_drv_invalid_int_value)
5685 << A->getOption().getName() << Value;
5686 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5689 // Add the target cpu
5690 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5692 CmdArgs.push_back("-target-cpu");
5693 CmdArgs.push_back(Args.MakeArgString(CPU));
5696 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5698 // These two are potentially updated by AddClangCLArgs.
5699 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
5700 llvm::codegenoptions::NoDebugInfo;
5701 bool EmitCodeView = false;
5703 // Add clang-cl arguments.
5704 types::ID InputType = Input.getType();
5706 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5708 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5709 renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5710 types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5713 // This controls whether or not we perform JustMyCode instrumentation.
5714 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5715 if (TC.getTriple().isOSBinFormatELF()) {
5716 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5717 CmdArgs.push_back("-fjmc");
5719 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5722 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5726 // Add the split debug info name to the command lines here so we
5727 // can propagate it to the backend.
5728 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5729 (TC.getTriple().isOSBinFormatELF() ||
5730 TC.getTriple().isOSBinFormatWasm() ||
5731 TC.getTriple().isOSBinFormatCOFF()) &&
5732 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5733 isa<BackendJobAction>(JA));
5735 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5736 CmdArgs.push_back("-split-dwarf-file");
5737 CmdArgs.push_back(SplitDWARFOut);
5738 if (DwarfFission == DwarfFissionKind::Split) {
5739 CmdArgs.push_back("-split-dwarf-output");
5740 CmdArgs.push_back(SplitDWARFOut);
5744 // Pass the linker version in use.
5745 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5746 CmdArgs.push_back("-target-linker-version");
5747 CmdArgs.push_back(A->getValue());
5750 // Explicitly error on some things we know we don't support and can't just
5752 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5754 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5755 TC.getArch() == llvm::Triple::x86) {
5756 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5757 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5758 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5759 << Unsupported->getOption().getName();
5761 // The faltivec option has been superseded by the maltivec option.
5762 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5763 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5764 << Unsupported->getOption().getName()
5765 << "please use -maltivec and include altivec.h explicitly";
5766 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5767 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5768 << Unsupported->getOption().getName() << "please use -mno-altivec";
5771 Args.AddAllArgs(CmdArgs, options::OPT_v);
5773 if (Args.getLastArg(options::OPT_H)) {
5774 CmdArgs.push_back("-H");
5775 CmdArgs.push_back("-sys-header-deps");
5777 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5779 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
5780 CmdArgs.push_back("-header-include-file");
5781 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5782 ? D.CCPrintHeadersFilename.c_str()
5784 CmdArgs.push_back("-sys-header-deps");
5785 CmdArgs.push_back(Args.MakeArgString(
5786 "-header-include-format=" +
5787 std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
5789 Args.MakeArgString("-header-include-filtering=" +
5790 std::string(headerIncludeFilteringKindToString(
5791 D.CCPrintHeadersFiltering))));
5793 Args.AddLastArg(CmdArgs, options::OPT_P);
5794 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5796 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5797 CmdArgs.push_back("-diagnostic-log-file");
5798 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5799 ? D.CCLogDiagnosticsFilename.c_str()
5803 // Give the gen diagnostics more chances to succeed, by avoiding intentional
5805 if (D.CCGenDiagnostics)
5806 CmdArgs.push_back("-disable-pragma-debug-crash");
5808 // Allow backend to put its diagnostic files in the same place as frontend
5809 // crash diagnostics files.
5810 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5811 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5812 CmdArgs.push_back("-mllvm");
5813 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5816 bool UseSeparateSections = isUseSeparateSections(Triple);
5818 if (Args.hasFlag(options::OPT_ffunction_sections,
5819 options::OPT_fno_function_sections, UseSeparateSections)) {
5820 CmdArgs.push_back("-ffunction-sections");
5823 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5824 StringRef Val = A->getValue();
5825 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5826 if (Val != "all" && Val != "labels" && Val != "none" &&
5827 !Val.startswith("list="))
5828 D.Diag(diag::err_drv_invalid_value)
5829 << A->getAsString(Args) << A->getValue();
5831 A->render(Args, CmdArgs);
5832 } else if (Triple.isNVPTX()) {
5833 // Do not pass the option to the GPU compilation. We still want it enabled
5834 // for the host-side compilation, so seeing it here is not an error.
5835 } else if (Val != "none") {
5836 // =none is allowed everywhere. It's useful for overriding the option
5837 // and is the same as not specifying the option.
5838 D.Diag(diag::err_drv_unsupported_opt_for_target)
5839 << A->getAsString(Args) << TripleStr;
5843 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5844 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5845 UseSeparateSections || HasDefaultDataSections)) {
5846 CmdArgs.push_back("-fdata-sections");
5849 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
5850 options::OPT_fno_unique_section_names);
5851 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
5852 options::OPT_fno_unique_internal_linkage_names);
5853 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
5854 options::OPT_fno_unique_basic_block_section_names);
5855 Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
5856 options::OPT_fno_convergent_functions);
5858 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5859 options::OPT_fno_split_machine_functions)) {
5860 // This codegen pass is only available on x86-elf targets.
5861 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5862 if (A->getOption().matches(options::OPT_fsplit_machine_functions))
5863 A->render(Args, CmdArgs);
5865 D.Diag(diag::err_drv_unsupported_opt_for_target)
5866 << A->getAsString(Args) << TripleStr;
5870 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5871 options::OPT_finstrument_functions_after_inlining,
5872 options::OPT_finstrument_function_entry_bare);
5874 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5875 // for sampling, overhead of call arc collection is way too high and there's
5876 // no way to collect the output.
5877 if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5878 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
5880 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5882 if (getLastProfileSampleUseArg(Args) &&
5883 Args.hasArg(options::OPT_fsample_profile_use_profi)) {
5884 CmdArgs.push_back("-mllvm");
5885 CmdArgs.push_back("-sample-profile-use-profi");
5888 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
5889 if (RawTriple.isPS() &&
5890 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5891 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
5892 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5895 // Pass options for controlling the default header search paths.
5896 if (Args.hasArg(options::OPT_nostdinc)) {
5897 CmdArgs.push_back("-nostdsysteminc");
5898 CmdArgs.push_back("-nobuiltininc");
5900 if (Args.hasArg(options::OPT_nostdlibinc))
5901 CmdArgs.push_back("-nostdsysteminc");
5902 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5903 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5906 // Pass the path to compiler resource files.
5907 CmdArgs.push_back("-resource-dir");
5908 CmdArgs.push_back(D.ResourceDir.c_str());
5910 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5912 RenderARCMigrateToolOptions(D, Args, CmdArgs);
5914 // Add preprocessing options like -I, -D, etc. if we are using the
5917 // FIXME: Support -fpreprocessed
5918 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5919 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5921 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5922 // that "The compiler can only warn and ignore the option if not recognized".
5923 // When building with ccache, it will pass -D options to clang even on
5924 // preprocessed inputs and configure concludes that -fPIC is not supported.
5925 Args.ClaimAllArgs(options::OPT_D);
5927 // Manually translate -O4 to -O3; let clang reject others.
5928 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5929 if (A->getOption().matches(options::OPT_O4)) {
5930 CmdArgs.push_back("-O3");
5931 D.Diag(diag::warn_O4_is_O3);
5933 A->render(Args, CmdArgs);
5937 // Warn about ignored options to clang.
5939 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5940 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5945 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
5946 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
5950 claimNoWarnArgs(Args);
5952 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5955 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
5957 if (A->getOption().getID() == options::OPT__SLASH_wd) {
5958 unsigned WarningNumber;
5959 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
5960 D.Diag(diag::err_drv_invalid_int_value)
5961 << A->getAsString(Args) << A->getValue();
5965 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
5966 CmdArgs.push_back(Args.MakeArgString(
5967 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
5971 A->render(Args, CmdArgs);
5974 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5975 CmdArgs.push_back("-pedantic");
5976 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5977 Args.AddLastArg(CmdArgs, options::OPT_w);
5979 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
5980 options::OPT_fno_fixed_point);
5982 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
5983 A->render(Args, CmdArgs);
5985 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5986 options::OPT_fno_experimental_relative_cxx_abi_vtables);
5988 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
5989 A->render(Args, CmdArgs);
5991 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5992 // (-ansi is equivalent to -std=c89 or -std=c++98).
5994 // If a std is supplied, only add -trigraphs if it follows the
5996 bool ImplyVCPPCVer = false;
5997 bool ImplyVCPPCXXVer = false;
5998 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6000 if (Std->getOption().matches(options::OPT_ansi))
6001 if (types::isCXX(InputType))
6002 CmdArgs.push_back("-std=c++98");
6004 CmdArgs.push_back("-std=c89");
6006 Std->render(Args, CmdArgs);
6008 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6009 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6010 options::OPT_ftrigraphs,
6011 options::OPT_fno_trigraphs))
6013 A->render(Args, CmdArgs);
6015 // Honor -std-default.
6017 // FIXME: Clang doesn't correctly handle -std= when the input language
6018 // doesn't match. For the time being just ignore this for C++ inputs;
6019 // eventually we want to do all the standard defaulting here instead of
6020 // splitting it between the driver and clang -cc1.
6021 if (!types::isCXX(InputType)) {
6022 if (!Args.hasArg(options::OPT__SLASH_std)) {
6023 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6026 ImplyVCPPCVer = true;
6028 else if (IsWindowsMSVC)
6029 ImplyVCPPCXXVer = true;
6031 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6032 options::OPT_fno_trigraphs);
6035 // GCC's behavior for -Wwrite-strings is a bit strange:
6036 // * In C, this "warning flag" changes the types of string literals from
6037 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6038 // for the discarded qualifier.
6039 // * In C++, this is just a normal warning flag.
6041 // Implementing this warning correctly in C is hard, so we follow GCC's
6042 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6043 // a non-const char* in C, rather than using this crude hack.
6044 if (!types::isCXX(InputType)) {
6045 // FIXME: This should behave just like a warning flag, and thus should also
6046 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6048 Args.getLastArg(options::OPT_Wwrite_strings,
6049 options::OPT_Wno_write_strings, options::OPT_w);
6051 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6052 CmdArgs.push_back("-fconst-strings");
6055 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6056 // during C++ compilation, which it is by default. GCC keeps this define even
6057 // in the presence of '-w', match this behavior bug-for-bug.
6058 if (types::isCXX(InputType) &&
6059 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6061 CmdArgs.push_back("-fdeprecated-macro");
6064 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6065 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6066 if (Asm->getOption().matches(options::OPT_fasm))
6067 CmdArgs.push_back("-fgnu-keywords");
6069 CmdArgs.push_back("-fno-gnu-keywords");
6072 if (!ShouldEnableAutolink(Args, TC, JA))
6073 CmdArgs.push_back("-fno-autolink");
6075 // Add in -fdebug-compilation-dir if necessary.
6076 const char *DebugCompilationDir =
6077 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
6079 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
6081 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6082 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6083 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6084 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6086 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6088 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6089 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6091 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6092 CmdArgs.push_back("-fbracket-depth");
6093 CmdArgs.push_back(A->getValue());
6096 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6097 options::OPT_Wlarge_by_value_copy_def)) {
6098 if (A->getNumValues()) {
6099 StringRef bytes = A->getValue();
6100 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6102 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6105 if (Args.hasArg(options::OPT_relocatable_pch))
6106 CmdArgs.push_back("-relocatable-pch");
6108 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6109 static const char *kCFABIs[] = {
6110 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6113 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6114 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6116 A->render(Args, CmdArgs);
6119 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6120 CmdArgs.push_back("-fconstant-string-class");
6121 CmdArgs.push_back(A->getValue());
6124 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6125 CmdArgs.push_back("-ftabstop");
6126 CmdArgs.push_back(A->getValue());
6129 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6130 options::OPT_fno_stack_size_section);
6132 if (Args.hasArg(options::OPT_fstack_usage)) {
6133 CmdArgs.push_back("-stack-usage-file");
6135 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6136 SmallString<128> OutputFilename(OutputOpt->getValue());
6137 llvm::sys::path::replace_extension(OutputFilename, "su");
6138 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6141 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6144 CmdArgs.push_back("-ferror-limit");
6145 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6146 CmdArgs.push_back(A->getValue());
6148 CmdArgs.push_back("19");
6150 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6151 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6152 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6153 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6154 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6156 // Pass -fmessage-length=.
6157 unsigned MessageLength = 0;
6158 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6159 StringRef V(A->getValue());
6160 if (V.getAsInteger(0, MessageLength))
6161 D.Diag(diag::err_drv_invalid_argument_to_option)
6162 << V << A->getOption().getName();
6164 // If -fmessage-length=N was not specified, determine whether this is a
6165 // terminal and, if so, implicitly define -fmessage-length appropriately.
6166 MessageLength = llvm::sys::Process::StandardErrColumns();
6168 if (MessageLength != 0)
6170 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6172 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6174 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6176 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6177 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6178 Twine(A->getValue(0))));
6180 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6181 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6182 options::OPT_fvisibility_ms_compat)) {
6183 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6184 A->render(Args, CmdArgs);
6186 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6187 CmdArgs.push_back("-fvisibility=hidden");
6188 CmdArgs.push_back("-ftype-visibility=default");
6190 } else if (IsOpenMPDevice) {
6191 // When compiling for the OpenMP device we want protected visibility by
6192 // default. This prevents the device from accidentally preempting code on
6193 // the host, makes the system more robust, and improves performance.
6194 CmdArgs.push_back("-fvisibility=protected");
6197 // PS4/PS5 process these options in addClangTargetOptions.
6198 if (!RawTriple.isPS()) {
6200 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6201 options::OPT_fno_visibility_from_dllstorageclass)) {
6202 if (A->getOption().matches(
6203 options::OPT_fvisibility_from_dllstorageclass)) {
6204 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6205 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6206 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6207 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6208 Args.AddLastArg(CmdArgs,
6209 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6214 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6215 options::OPT_fno_visibility_inlines_hidden, false))
6216 CmdArgs.push_back("-fvisibility-inlines-hidden");
6218 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6219 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6220 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
6221 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6223 if (Args.hasFlag(options::OPT_fnew_infallible,
6224 options::OPT_fno_new_infallible, false))
6225 CmdArgs.push_back("-fnew-infallible");
6227 if (Args.hasFlag(options::OPT_fno_operator_names,
6228 options::OPT_foperator_names, false))
6229 CmdArgs.push_back("-fno-operator-names");
6231 // Forward -f (flag) options which we can pass directly.
6232 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6233 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6234 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6235 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6237 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6238 Triple.hasDefaultEmulatedTLS()))
6239 CmdArgs.push_back("-femulated-tls");
6241 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6242 options::OPT_fno_check_new);
6244 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6245 // FIXME: There's no reason for this to be restricted to X86. The backend
6246 // code needs to be changed to include the appropriate function calls
6248 if (!Triple.isX86() && !Triple.isAArch64())
6249 D.Diag(diag::err_drv_unsupported_opt_for_target)
6250 << A->getAsString(Args) << TripleStr;
6253 // AltiVec-like language extensions aren't relevant for assembling.
6254 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6255 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6257 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6258 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6260 // Forward flags for OpenMP. We don't do this if the current action is an
6261 // device offloading action other than OpenMP.
6262 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6263 options::OPT_fno_openmp, false) &&
6264 (JA.isDeviceOffloading(Action::OFK_None) ||
6265 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6266 switch (D.getOpenMPRuntime(Args)) {
6267 case Driver::OMPRT_OMP:
6268 case Driver::OMPRT_IOMP5:
6269 // Clang can generate useful OpenMP code for these two runtime libraries.
6270 CmdArgs.push_back("-fopenmp");
6272 // If no option regarding the use of TLS in OpenMP codegeneration is
6273 // given, decide a default based on the target. Otherwise rely on the
6274 // options and pass the right information to the frontend.
6275 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6276 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6277 CmdArgs.push_back("-fnoopenmp-use-tls");
6278 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6279 options::OPT_fno_openmp_simd);
6280 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6281 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6282 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6283 options::OPT_fno_openmp_extensions, /*Default=*/true))
6284 CmdArgs.push_back("-fno-openmp-extensions");
6285 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6286 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6287 Args.AddAllArgs(CmdArgs,
6288 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6289 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6290 options::OPT_fno_openmp_optimistic_collapse,
6292 CmdArgs.push_back("-fopenmp-optimistic-collapse");
6294 // When in OpenMP offloading mode with NVPTX target, forward
6296 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6297 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6298 CmdArgs.push_back("-fopenmp-cuda-mode");
6300 // When in OpenMP offloading mode, enable debugging on the device.
6301 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6302 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6303 options::OPT_fno_openmp_target_debug, /*Default=*/false))
6304 CmdArgs.push_back("-fopenmp-target-debug");
6306 // When in OpenMP offloading mode, forward assumptions information about
6307 // thread and team counts in the device.
6308 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6309 options::OPT_fno_openmp_assume_teams_oversubscription,
6311 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6312 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6313 options::OPT_fno_openmp_assume_threads_oversubscription,
6315 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6316 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6317 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6318 if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6319 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6320 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6321 CmdArgs.push_back("-fopenmp-offload-mandatory");
6324 // By default, if Clang doesn't know how to generate useful OpenMP code
6325 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6326 // down to the actual compilation.
6327 // FIXME: It would be better to have a mode which *only* omits IR
6328 // generation based on the OpenMP support so that we get consistent
6329 // semantic analysis, etc.
6333 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6334 options::OPT_fno_openmp_simd);
6335 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6336 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6337 options::OPT_fno_openmp_extensions);
6340 // Forward the new driver to change offloading code generation.
6341 if (Args.hasFlag(options::OPT_offload_new_driver,
6342 options::OPT_no_offload_new_driver, false))
6343 CmdArgs.push_back("--offload-new-driver");
6345 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6347 const XRayArgs &XRay = TC.getXRayArgs();
6348 XRay.addArgs(TC, Args, CmdArgs, InputType);
6350 for (const auto &Filename :
6351 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6352 if (D.getVFS().exists(Filename))
6353 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6355 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6358 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6359 StringRef S0 = A->getValue(), S = S0;
6360 unsigned Size, Offset = 0;
6361 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6363 D.Diag(diag::err_drv_unsupported_opt_for_target)
6364 << A->getAsString(Args) << TripleStr;
6365 else if (S.consumeInteger(10, Size) ||
6366 (!S.empty() && (!S.consume_front(",") ||
6367 S.consumeInteger(10, Offset) || !S.empty())))
6368 D.Diag(diag::err_drv_invalid_argument_to_option)
6369 << S0 << A->getOption().getName();
6370 else if (Size < Offset)
6371 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6373 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6374 CmdArgs.push_back(Args.MakeArgString(
6375 "-fpatchable-function-entry-offset=" + Twine(Offset)));
6379 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6381 if (TC.SupportsProfiling()) {
6382 Args.AddLastArg(CmdArgs, options::OPT_pg);
6384 llvm::Triple::ArchType Arch = TC.getArch();
6385 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6386 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6387 A->render(Args, CmdArgs);
6389 D.Diag(diag::err_drv_unsupported_opt_for_target)
6390 << A->getAsString(Args) << TripleStr;
6392 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6393 if (Arch == llvm::Triple::systemz)
6394 A->render(Args, CmdArgs);
6396 D.Diag(diag::err_drv_unsupported_opt_for_target)
6397 << A->getAsString(Args) << TripleStr;
6399 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6400 if (Arch == llvm::Triple::systemz)
6401 A->render(Args, CmdArgs);
6403 D.Diag(diag::err_drv_unsupported_opt_for_target)
6404 << A->getAsString(Args) << TripleStr;
6408 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6409 if (TC.getTriple().isOSzOS()) {
6410 D.Diag(diag::err_drv_unsupported_opt_for_target)
6411 << A->getAsString(Args) << TripleStr;
6414 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6415 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6416 D.Diag(diag::err_drv_unsupported_opt_for_target)
6417 << A->getAsString(Args) << TripleStr;
6420 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6421 if (A->getOption().matches(options::OPT_p)) {
6423 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6424 CmdArgs.push_back("-pg");
6428 // Reject AIX-specific link options on other targets.
6429 if (!TC.getTriple().isOSAIX()) {
6430 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6431 options::OPT_mxcoff_build_id_EQ)) {
6432 D.Diag(diag::err_drv_unsupported_opt_for_target)
6433 << A->getSpelling() << TripleStr;
6437 if (Args.getLastArg(options::OPT_fapple_kext) ||
6438 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6439 CmdArgs.push_back("-fapple-kext");
6441 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6442 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6443 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6444 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6445 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6446 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6447 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6448 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6449 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6450 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6452 if (const char *Name = C.getTimeTraceFile(&JA)) {
6453 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
6454 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6457 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6458 CmdArgs.push_back("-ftrapv-handler");
6459 CmdArgs.push_back(A->getValue());
6462 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6464 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
6465 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
6466 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
6467 if (A->getOption().matches(options::OPT_fwrapv))
6468 CmdArgs.push_back("-fwrapv");
6469 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
6470 options::OPT_fno_strict_overflow)) {
6471 if (A->getOption().matches(options::OPT_fno_strict_overflow))
6472 CmdArgs.push_back("-fwrapv");
6475 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
6476 options::OPT_fno_reroll_loops))
6477 if (A->getOption().matches(options::OPT_freroll_loops))
6478 CmdArgs.push_back("-freroll-loops");
6480 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6481 options::OPT_fno_finite_loops);
6483 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6484 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6485 options::OPT_fno_unroll_loops);
6487 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6489 Args.AddLastArg(CmdArgs, options::OPT_pthread);
6491 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6492 options::OPT_mno_speculative_load_hardening);
6494 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6495 RenderSCPOptions(TC, Args, CmdArgs);
6496 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6498 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6500 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6501 options::OPT_mno_stackrealign);
6503 if (Args.hasArg(options::OPT_mstack_alignment)) {
6504 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6505 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
6508 if (Args.hasArg(options::OPT_mstack_probe_size)) {
6509 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6512 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6514 CmdArgs.push_back("-mstack-probe-size=0");
6517 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6518 options::OPT_mno_stack_arg_probe);
6520 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6521 options::OPT_mno_restrict_it)) {
6522 if (A->getOption().matches(options::OPT_mrestrict_it)) {
6523 CmdArgs.push_back("-mllvm");
6524 CmdArgs.push_back("-arm-restrict-it");
6526 CmdArgs.push_back("-mllvm");
6527 CmdArgs.push_back("-arm-default-it");
6531 // Forward -cl options to -cc1
6532 RenderOpenCLOptions(Args, CmdArgs, InputType);
6534 // Forward hlsl options to -cc1
6535 RenderHLSLOptions(Args, CmdArgs, InputType);
6538 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6539 options::OPT_fno_hip_new_launch_api, true))
6540 CmdArgs.push_back("-fhip-new-launch-api");
6541 if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
6542 options::OPT_fno_gpu_allow_device_init, false))
6543 CmdArgs.push_back("-fgpu-allow-device-init");
6544 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
6545 options::OPT_fno_hip_kernel_arg_name);
6548 if (IsCuda || IsHIP) {
6550 CmdArgs.push_back("-fgpu-rdc");
6551 if (Args.hasFlag(options::OPT_fgpu_defer_diag,
6552 options::OPT_fno_gpu_defer_diag, false))
6553 CmdArgs.push_back("-fgpu-defer-diag");
6554 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6555 options::OPT_fno_gpu_exclude_wrong_side_overloads,
6557 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6558 CmdArgs.push_back("-fgpu-defer-diag");
6562 // Forward -nogpulib to -cc1.
6563 if (Args.hasArg(options::OPT_nogpulib))
6564 CmdArgs.push_back("-nogpulib");
6566 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6568 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6571 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6573 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6575 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6577 // Forward -f options with positive and negative forms; we translate these by
6578 // hand. Do not propagate PGO options to the GPU-side compilations as the
6579 // profile info is for the host-side compilation only.
6580 if (!(IsCudaDevice || IsHIPDevice)) {
6581 if (Arg *A = getLastProfileSampleUseArg(Args)) {
6582 auto *PGOArg = Args.getLastArg(
6583 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6584 options::OPT_fcs_profile_generate,
6585 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6586 options::OPT_fprofile_use_EQ);
6588 D.Diag(diag::err_drv_argument_not_allowed_with)
6589 << "SampleUse with PGO options";
6591 StringRef fname = A->getValue();
6592 if (!llvm::sys::fs::exists(fname))
6593 D.Diag(diag::err_drv_no_such_file) << fname;
6595 A->render(Args, CmdArgs);
6597 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6599 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6600 options::OPT_fno_pseudo_probe_for_profiling, false)) {
6601 CmdArgs.push_back("-fpseudo-probe-for-profiling");
6602 // Enforce -funique-internal-linkage-names if it's not explicitly turned
6604 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6605 options::OPT_fno_unique_internal_linkage_names, true))
6606 CmdArgs.push_back("-funique-internal-linkage-names");
6609 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
6611 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6612 options::OPT_fno_assume_sane_operator_new);
6614 // -fblocks=0 is default.
6615 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6616 TC.IsBlocksDefault()) ||
6617 (Args.hasArg(options::OPT_fgnu_runtime) &&
6618 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6619 !Args.hasArg(options::OPT_fno_blocks))) {
6620 CmdArgs.push_back("-fblocks");
6622 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6623 CmdArgs.push_back("-fblocks-runtime-optional");
6626 // -fencode-extended-block-signature=1 is default.
6627 if (TC.IsEncodeExtendedBlockSignatureDefault())
6628 CmdArgs.push_back("-fencode-extended-block-signature");
6630 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
6631 options::OPT_fno_coro_aligned_allocation, false) &&
6632 types::isCXX(InputType))
6633 CmdArgs.push_back("-fcoro-aligned-allocation");
6635 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6636 options::OPT_fno_double_square_bracket_attributes);
6638 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
6639 options::OPT_fno_access_control);
6640 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
6641 options::OPT_fno_elide_constructors);
6643 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6645 if (KernelOrKext || (types::isCXX(InputType) &&
6646 (RTTIMode == ToolChain::RM_Disabled)))
6647 CmdArgs.push_back("-fno-rtti");
6649 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6650 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6651 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6652 CmdArgs.push_back("-fshort-enums");
6654 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6656 // -fuse-cxa-atexit is default.
6658 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6659 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6660 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6661 RawTriple.hasEnvironment())) ||
6663 CmdArgs.push_back("-fno-use-cxa-atexit");
6665 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6666 options::OPT_fno_register_global_dtors_with_atexit,
6667 RawTriple.isOSDarwin() && !KernelOrKext))
6668 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6670 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
6671 options::OPT_fno_use_line_directives);
6673 // -fno-minimize-whitespace is default.
6674 if (Args.hasFlag(options::OPT_fminimize_whitespace,
6675 options::OPT_fno_minimize_whitespace, false)) {
6676 types::ID InputType = Inputs[0].getType();
6677 if (!isDerivedFromC(InputType))
6678 D.Diag(diag::err_drv_minws_unsupported_input_type)
6679 << types::getTypeName(InputType);
6680 CmdArgs.push_back("-fminimize-whitespace");
6683 // -fms-extensions=0 is default.
6684 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6686 CmdArgs.push_back("-fms-extensions");
6688 // -fms-compatibility=0 is default.
6689 bool IsMSVCCompat = Args.hasFlag(
6690 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6691 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6692 options::OPT_fno_ms_extensions, true)));
6694 CmdArgs.push_back("-fms-compatibility");
6696 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
6697 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
6698 ProcessVSRuntimeLibrary(Args, CmdArgs);
6700 // Handle -fgcc-version, if present.
6701 VersionTuple GNUCVer;
6702 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6703 // Check that the version has 1 to 3 components and the minor and patch
6704 // versions fit in two decimal digits.
6705 StringRef Val = A->getValue();
6706 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6707 bool Invalid = GNUCVer.tryParse(Val);
6708 unsigned Minor = GNUCVer.getMinor().value_or(0);
6709 unsigned Patch = GNUCVer.getSubminor().value_or(0);
6710 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6711 D.Diag(diag::err_drv_invalid_value)
6712 << A->getAsString(Args) << A->getValue();
6714 } else if (!IsMSVCCompat) {
6715 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6716 GNUCVer = VersionTuple(4, 2, 1);
6718 if (!GNUCVer.empty()) {
6720 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6723 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6726 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6728 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6729 if (ImplyVCPPCVer) {
6730 StringRef LanguageStandard;
6731 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6733 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6734 .Case("c11", "-std=c11")
6735 .Case("c17", "-std=c17")
6737 if (LanguageStandard.empty())
6738 D.Diag(clang::diag::warn_drv_unused_argument)
6739 << StdArg->getAsString(Args);
6741 CmdArgs.push_back(LanguageStandard.data());
6743 if (ImplyVCPPCXXVer) {
6744 StringRef LanguageStandard;
6745 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6747 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6748 .Case("c++14", "-std=c++14")
6749 .Case("c++17", "-std=c++17")
6750 .Case("c++20", "-std=c++20")
6751 // TODO add c++23 and c++26 when MSVC supports it.
6752 .Case("c++latest", "-std=c++26")
6754 if (LanguageStandard.empty())
6755 D.Diag(clang::diag::warn_drv_unused_argument)
6756 << StdArg->getAsString(Args);
6759 if (LanguageStandard.empty()) {
6760 if (IsMSVC2015Compatible)
6761 LanguageStandard = "-std=c++14";
6763 LanguageStandard = "-std=c++11";
6766 CmdArgs.push_back(LanguageStandard.data());
6769 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
6770 options::OPT_fno_borland_extensions);
6772 // -fno-declspec is default, except for PS4/PS5.
6773 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6775 CmdArgs.push_back("-fdeclspec");
6776 else if (Args.hasArg(options::OPT_fno_declspec))
6777 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6779 // -fthreadsafe-static is default, except for MSVC compatibility versions less
6781 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6782 options::OPT_fno_threadsafe_statics,
6783 !types::isOpenCL(InputType) &&
6784 (!IsWindowsMSVC || IsMSVC2015Compatible)))
6785 CmdArgs.push_back("-fno-threadsafe-statics");
6787 // -fno-delayed-template-parsing is default, except when targeting MSVC.
6788 // Many old Windows SDK versions require this to parse.
6789 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
6790 // compiler. We should be able to disable this by default at some point.
6791 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6792 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
6793 CmdArgs.push_back("-fdelayed-template-parsing");
6795 // -fgnu-keywords default varies depending on language; only pass if
6797 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6798 options::OPT_fno_gnu_keywords);
6800 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
6801 options::OPT_fno_gnu89_inline);
6803 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
6804 options::OPT_finline_hint_functions,
6805 options::OPT_fno_inline_functions);
6806 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
6807 if (A->getOption().matches(options::OPT_fno_inline))
6808 A->render(Args, CmdArgs);
6809 } else if (InlineArg) {
6810 InlineArg->render(Args, CmdArgs);
6813 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
6816 RenderModulesOptions(C, D, Args, Input, Output, Std, CmdArgs);
6818 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6819 options::OPT_fno_pch_validate_input_files_content, false))
6820 CmdArgs.push_back("-fvalidate-ast-input-files-content");
6821 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6822 options::OPT_fno_pch_instantiate_templates, false))
6823 CmdArgs.push_back("-fpch-instantiate-templates");
6824 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6826 CmdArgs.push_back("-fmodules-codegen");
6827 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6829 CmdArgs.push_back("-fmodules-debuginfo");
6831 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6832 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6835 if (types::isObjC(Input.getType()) &&
6836 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6837 options::OPT_fno_objc_encode_cxx_class_template_spec,
6838 !Runtime.isNeXTFamily()))
6839 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6841 if (Args.hasFlag(options::OPT_fapplication_extension,
6842 options::OPT_fno_application_extension, false))
6843 CmdArgs.push_back("-fapplication-extension");
6845 // Handle GCC-style exception args.
6847 if (!C.getDriver().IsCLMode())
6848 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6850 // Handle exception personalities
6851 Arg *A = Args.getLastArg(
6852 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6853 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6855 const Option &Opt = A->getOption();
6856 if (Opt.matches(options::OPT_fsjlj_exceptions))
6857 CmdArgs.push_back("-exception-model=sjlj");
6858 if (Opt.matches(options::OPT_fseh_exceptions))
6859 CmdArgs.push_back("-exception-model=seh");
6860 if (Opt.matches(options::OPT_fdwarf_exceptions))
6861 CmdArgs.push_back("-exception-model=dwarf");
6862 if (Opt.matches(options::OPT_fwasm_exceptions))
6863 CmdArgs.push_back("-exception-model=wasm");
6865 switch (TC.GetExceptionModel(Args)) {
6868 case llvm::ExceptionHandling::DwarfCFI:
6869 CmdArgs.push_back("-exception-model=dwarf");
6871 case llvm::ExceptionHandling::SjLj:
6872 CmdArgs.push_back("-exception-model=sjlj");
6874 case llvm::ExceptionHandling::WinEH:
6875 CmdArgs.push_back("-exception-model=seh");
6880 // C++ "sane" operator new.
6881 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6882 options::OPT_fno_assume_sane_operator_new);
6884 // -fassume-unique-vtables is on by default.
6885 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
6886 options::OPT_fno_assume_unique_vtables);
6888 // -frelaxed-template-template-args is off by default, as it is a severe
6889 // breaking change until a corresponding change to template partial ordering
6891 Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
6892 options::OPT_fno_relaxed_template_template_args);
6894 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
6896 Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
6897 options::OPT_fno_sized_deallocation);
6899 // -faligned-allocation is on by default in C++17 onwards and otherwise off
6901 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
6902 options::OPT_fno_aligned_allocation,
6903 options::OPT_faligned_new_EQ)) {
6904 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
6905 CmdArgs.push_back("-fno-aligned-allocation");
6907 CmdArgs.push_back("-faligned-allocation");
6910 // The default new alignment can be specified using a dedicated option or via
6911 // a GCC-compatible option that also turns on aligned allocation.
6912 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
6913 options::OPT_faligned_new_EQ))
6915 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
6917 // -fconstant-cfstrings is default, and may be subject to argument translation
6919 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
6920 options::OPT_fno_constant_cfstrings, true) ||
6921 !Args.hasFlag(options::OPT_mconstant_cfstrings,
6922 options::OPT_mno_constant_cfstrings, true))
6923 CmdArgs.push_back("-fno-constant-cfstrings");
6925 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
6926 options::OPT_fno_pascal_strings);
6928 // Honor -fpack-struct= and -fpack-struct, if given. Note that
6929 // -fno-pack-struct doesn't apply to -fpack-struct=.
6930 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
6931 std::string PackStructStr = "-fpack-struct=";
6932 PackStructStr += A->getValue();
6933 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
6934 } else if (Args.hasFlag(options::OPT_fpack_struct,
6935 options::OPT_fno_pack_struct, false)) {
6936 CmdArgs.push_back("-fpack-struct=1");
6939 // Handle -fmax-type-align=N and -fno-type-align
6940 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
6941 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
6942 if (!SkipMaxTypeAlign) {
6943 std::string MaxTypeAlignStr = "-fmax-type-align=";
6944 MaxTypeAlignStr += A->getValue();
6945 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6947 } else if (RawTriple.isOSDarwin()) {
6948 if (!SkipMaxTypeAlign) {
6949 std::string MaxTypeAlignStr = "-fmax-type-align=16";
6950 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6954 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
6955 CmdArgs.push_back("-Qn");
6957 // -fno-common is the default, set -fcommon only when that flag is set.
6958 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
6960 // -fsigned-bitfields is default, and clang doesn't yet support
6961 // -funsigned-bitfields.
6962 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
6963 options::OPT_funsigned_bitfields, true))
6964 D.Diag(diag::warn_drv_clang_unsupported)
6965 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
6967 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
6968 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
6969 D.Diag(diag::err_drv_clang_unsupported)
6970 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
6972 // -finput_charset=UTF-8 is default. Reject others
6973 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
6974 StringRef value = inputCharset->getValue();
6975 if (!value.equals_insensitive("utf-8"))
6976 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
6980 // -fexec_charset=UTF-8 is default. Reject others
6981 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
6982 StringRef value = execCharset->getValue();
6983 if (!value.equals_insensitive("utf-8"))
6984 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
6988 RenderDiagnosticsOptions(D, Args, CmdArgs);
6990 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
6991 options::OPT_fno_asm_blocks);
6993 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
6994 options::OPT_fno_gnu_inline_asm);
6996 // Enable vectorization per default according to the optimization level
6997 // selected. For optimization levels that want vectorization we use the alias
6998 // option to simplify the hasFlag logic.
6999 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
7000 OptSpecifier VectorizeAliasOption =
7001 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
7002 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
7003 options::OPT_fno_vectorize, EnableVec))
7004 CmdArgs.push_back("-vectorize-loops");
7006 // -fslp-vectorize is enabled based on the optimization level selected.
7007 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
7008 OptSpecifier SLPVectAliasOption =
7009 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
7010 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
7011 options::OPT_fno_slp_vectorize, EnableSLPVec))
7012 CmdArgs.push_back("-vectorize-slp");
7014 ParseMPreferVectorWidth(D, Args, CmdArgs);
7016 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7017 Args.AddLastArg(CmdArgs,
7018 options::OPT_fsanitize_undefined_strip_path_components_EQ);
7020 // -fdollars-in-identifiers default varies depending on platform and
7021 // language; only pass if specified.
7022 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7023 options::OPT_fno_dollars_in_identifiers)) {
7024 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7025 CmdArgs.push_back("-fdollars-in-identifiers");
7027 CmdArgs.push_back("-fno-dollars-in-identifiers");
7030 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7031 options::OPT_fno_apple_pragma_pack);
7033 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7034 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7035 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7037 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7038 options::OPT_fno_rewrite_imports, false);
7040 CmdArgs.push_back("-frewrite-imports");
7042 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7043 options::OPT_fno_directives_only);
7045 // Enable rewrite includes if the user's asked for it or if we're generating
7047 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7048 // nice to enable this when doing a crashdump for modules as well.
7049 if (Args.hasFlag(options::OPT_frewrite_includes,
7050 options::OPT_fno_rewrite_includes, false) ||
7051 (C.isForDiagnostics() && !HaveModules))
7052 CmdArgs.push_back("-frewrite-includes");
7054 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7055 if (Arg *A = Args.getLastArg(options::OPT_traditional,
7056 options::OPT_traditional_cpp)) {
7057 if (isa<PreprocessJobAction>(JA))
7058 CmdArgs.push_back("-traditional-cpp");
7060 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7063 Args.AddLastArg(CmdArgs, options::OPT_dM);
7064 Args.AddLastArg(CmdArgs, options::OPT_dD);
7065 Args.AddLastArg(CmdArgs, options::OPT_dI);
7067 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7069 // Handle serialized diagnostics.
7070 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7071 CmdArgs.push_back("-serialize-diagnostic-file");
7072 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7075 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7076 CmdArgs.push_back("-fretain-comments-from-system-headers");
7078 // Forward -fcomment-block-commands to -cc1.
7079 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7080 // Forward -fparse-all-comments to -cc1.
7081 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7083 // Turn -fplugin=name.so into -load name.so
7084 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7085 CmdArgs.push_back("-load");
7086 CmdArgs.push_back(A->getValue());
7090 // Turn -fplugin-arg-pluginname-key=value into
7091 // -plugin-arg-pluginname key=value
7092 // GCC has an actual plugin_argument struct with key/value pairs that it
7093 // passes to its plugins, but we don't, so just pass it on as-is.
7095 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7096 // argument key are allowed to contain dashes. GCC therefore only
7097 // allows dashes in the key. We do the same.
7098 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7099 auto ArgValue = StringRef(A->getValue());
7100 auto FirstDashIndex = ArgValue.find('-');
7101 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7102 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7105 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7106 if (PluginName.empty()) {
7107 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7109 D.Diag(diag::warn_drv_missing_plugin_arg)
7110 << PluginName << A->getAsString(Args);
7115 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7116 CmdArgs.push_back(Args.MakeArgString(Arg));
7119 // Forward -fpass-plugin=name.so to -cc1.
7120 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7122 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7126 // Forward --vfsoverlay to -cc1.
7127 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7128 CmdArgs.push_back("--vfsoverlay");
7129 CmdArgs.push_back(A->getValue());
7133 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7134 options::OPT_fno_safe_buffer_usage_suggestions);
7136 // Setup statistics file output.
7137 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7138 if (!StatsFile.empty()) {
7139 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7140 if (D.CCPrintInternalStats)
7141 CmdArgs.push_back("-stats-file-append");
7144 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7146 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7148 // -finclude-default-header flag is for preprocessor,
7149 // do not pass it to other cc1 commands when save-temps is enabled
7150 if (C.getDriver().isSaveTempsEnabled() &&
7151 !isa<PreprocessJobAction>(JA)) {
7152 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7155 CmdArgs.push_back(Arg->getValue());
7157 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7160 // We translate this by hand to the -cc1 argument, since nightly test uses
7161 // it and developers have been trained to spell it with -mllvm. Both
7162 // spellings are now deprecated and should be removed.
7163 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7164 CmdArgs.push_back("-disable-llvm-optzns");
7166 A->render(Args, CmdArgs);
7170 // With -save-temps, we want to save the unoptimized bitcode output from the
7171 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7173 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7174 // has slightly different breakdown between stages.
7175 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7176 // pristine IR generated by the frontend. Ideally, a new compile action should
7177 // be added so both IR can be captured.
7178 if ((C.getDriver().isSaveTempsEnabled() ||
7179 JA.isHostOffloading(Action::OFK_OpenMP)) &&
7180 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7181 isa<CompileJobAction>(JA))
7182 CmdArgs.push_back("-disable-llvm-passes");
7184 Args.AddAllArgs(CmdArgs, options::OPT_undef);
7186 const char *Exec = D.getClangProgramPath();
7188 // Optionally embed the -cc1 level arguments into the debug info or a
7189 // section, for build analysis.
7190 // Also record command line arguments into the debug info if
7191 // -grecord-gcc-switches options is set on.
7192 // By default, -gno-record-gcc-switches is set on and no recording.
7193 auto GRecordSwitches =
7194 Args.hasFlag(options::OPT_grecord_command_line,
7195 options::OPT_gno_record_command_line, false);
7196 auto FRecordSwitches =
7197 Args.hasFlag(options::OPT_frecord_command_line,
7198 options::OPT_fno_record_command_line, false);
7199 if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
7200 !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
7201 D.Diag(diag::err_drv_unsupported_opt_for_target)
7202 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
7204 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
7205 ArgStringList OriginalArgs;
7206 for (const auto &Arg : Args)
7207 Arg->render(Args, OriginalArgs);
7209 SmallString<256> Flags;
7210 EscapeSpacesAndBackslashes(Exec, Flags);
7211 for (const char *OriginalArg : OriginalArgs) {
7212 SmallString<128> EscapedArg;
7213 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7215 Flags += EscapedArg;
7217 auto FlagsArgString = Args.MakeArgString(Flags);
7218 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7219 CmdArgs.push_back("-dwarf-debug-flags");
7220 CmdArgs.push_back(FlagsArgString);
7222 if (FRecordSwitches) {
7223 CmdArgs.push_back("-record-command-line");
7224 CmdArgs.push_back(FlagsArgString);
7228 // Host-side offloading compilation receives all device-side outputs. Include
7229 // them in the host compilation depending on the target. If the host inputs
7230 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7231 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7232 CmdArgs.push_back("-fcuda-include-gpubinary");
7233 CmdArgs.push_back(CudaDeviceInput->getFilename());
7234 } else if (!HostOffloadingInputs.empty()) {
7235 if ((IsCuda || IsHIP) && !IsRDCMode) {
7236 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7237 CmdArgs.push_back("-fcuda-include-gpubinary");
7238 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7240 for (const InputInfo Input : HostOffloadingInputs)
7241 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7242 TC.getInputFilename(Input)));
7247 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7248 options::OPT_fno_cuda_short_ptr, false))
7249 CmdArgs.push_back("-fcuda-short-ptr");
7252 if (IsCuda || IsHIP) {
7253 // Determine the original source input.
7254 const Action *SourceAction = &JA;
7255 while (SourceAction->getKind() != Action::InputClass) {
7256 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7257 SourceAction = SourceAction->getInputs()[0];
7259 auto CUID = cast<InputAction>(SourceAction)->getId();
7261 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7265 CmdArgs.push_back("-fcuda-allow-variadic-functions");
7266 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7269 if (IsCudaDevice || IsHIPDevice) {
7270 StringRef InlineThresh =
7271 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7272 if (!InlineThresh.empty()) {
7273 std::string ArgStr =
7274 std::string("-inline-threshold=") + InlineThresh.str();
7275 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7280 Args.addOptOutFlag(CmdArgs,
7281 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7282 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7284 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7285 // to specify the result of the compile phase on the host, so the meaningful
7286 // device declarations can be identified. Also, -fopenmp-is-target-device is
7287 // passed along to tell the frontend that it is generating code for a device,
7288 // so that only the relevant declarations are emitted.
7289 if (IsOpenMPDevice) {
7290 CmdArgs.push_back("-fopenmp-is-target-device");
7291 if (OpenMPDeviceInput) {
7292 CmdArgs.push_back("-fopenmp-host-ir-file-path");
7293 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7297 if (Triple.isAMDGPU()) {
7298 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7300 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7301 options::OPT_mno_unsafe_fp_atomics);
7302 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7303 options::OPT_mno_amdgpu_ieee);
7306 // For all the host OpenMP offloading compile jobs we need to pass the targets
7307 // information using -fopenmp-targets= option.
7308 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
7309 SmallString<128> Targets("-fopenmp-targets=");
7311 SmallVector<std::string, 4> Triples;
7312 auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
7313 std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
7314 [](auto TC) { return TC.second->getTripleString(); });
7315 CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
7318 bool VirtualFunctionElimination =
7319 Args.hasFlag(options::OPT_fvirtual_function_elimination,
7320 options::OPT_fno_virtual_function_elimination, false);
7321 if (VirtualFunctionElimination) {
7322 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7324 if (LTOMode != LTOK_Full)
7325 D.Diag(diag::err_drv_argument_only_allowed_with)
7326 << "-fvirtual-function-elimination"
7329 CmdArgs.push_back("-fvirtual-function-elimination");
7332 // VFE requires whole-program-vtables, and enables it by default.
7333 bool WholeProgramVTables = Args.hasFlag(
7334 options::OPT_fwhole_program_vtables,
7335 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7336 if (VirtualFunctionElimination && !WholeProgramVTables) {
7337 D.Diag(diag::err_drv_argument_not_allowed_with)
7338 << "-fno-whole-program-vtables"
7339 << "-fvirtual-function-elimination";
7342 if (WholeProgramVTables) {
7343 // PS4 uses the legacy LTO API, which does not support this feature in
7345 bool IsPS4 = getToolChain().getTriple().isPS4();
7347 // Check if we passed LTO options but they were suppressed because this is a
7348 // device offloading action, or we passed device offload LTO options which
7349 // were suppressed because this is not the device offload action.
7350 // Check if we are using PS4 in regular LTO mode.
7351 // Otherwise, issue an error.
7352 if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
7353 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7354 D.Diag(diag::err_drv_argument_only_allowed_with)
7355 << "-fwhole-program-vtables"
7356 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7358 // Propagate -fwhole-program-vtables if this is an LTO compile.
7360 CmdArgs.push_back("-fwhole-program-vtables");
7363 bool DefaultsSplitLTOUnit =
7364 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7365 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7366 (!Triple.isPS4() && UnifiedLTO);
7368 Args.hasFlag(options::OPT_fsplit_lto_unit,
7369 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7370 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7371 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7372 << "-fsanitize=cfi";
7374 CmdArgs.push_back("-fsplit-lto-unit");
7376 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7377 options::OPT_fno_global_isel)) {
7378 CmdArgs.push_back("-mllvm");
7379 if (A->getOption().matches(options::OPT_fglobal_isel)) {
7380 CmdArgs.push_back("-global-isel=1");
7382 // GISel is on by default on AArch64 -O0, so don't bother adding
7383 // the fallback remarks for it. Other combinations will add a warning of
7385 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7386 bool IsOptLevelSupported = false;
7388 Arg *A = Args.getLastArg(options::OPT_O_Group);
7389 if (Triple.getArch() == llvm::Triple::aarch64) {
7390 if (!A || A->getOption().matches(options::OPT_O0))
7391 IsOptLevelSupported = true;
7393 if (!IsArchSupported || !IsOptLevelSupported) {
7394 CmdArgs.push_back("-mllvm");
7395 CmdArgs.push_back("-global-isel-abort=2");
7397 if (!IsArchSupported)
7398 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7400 D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7403 CmdArgs.push_back("-global-isel=0");
7407 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
7408 CmdArgs.push_back("-forder-file-instrumentation");
7409 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
7410 // on, we need to pass these flags as linker flags and that will be handled
7411 // outside of the compiler.
7413 CmdArgs.push_back("-mllvm");
7414 CmdArgs.push_back("-enable-order-file-instrumentation");
7418 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7419 options::OPT_fno_force_enable_int128)) {
7420 if (A->getOption().matches(options::OPT_fforce_enable_int128))
7421 CmdArgs.push_back("-fforce-enable-int128");
7424 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7425 options::OPT_fno_keep_static_consts);
7426 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
7427 options::OPT_fno_keep_persistent_storage_variables);
7428 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7429 options::OPT_fno_complete_member_pointers);
7430 Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7431 options::OPT_fno_cxx_static_destructors);
7433 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7435 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7436 options::OPT_mno_outline_atomics)) {
7437 // Option -moutline-atomics supported for AArch64 target only.
7438 if (!Triple.isAArch64()) {
7439 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
7440 << Triple.getArchName() << A->getOption().getName();
7442 if (A->getOption().matches(options::OPT_moutline_atomics)) {
7443 CmdArgs.push_back("-target-feature");
7444 CmdArgs.push_back("+outline-atomics");
7446 CmdArgs.push_back("-target-feature");
7447 CmdArgs.push_back("-outline-atomics");
7450 } else if (Triple.isAArch64() &&
7451 getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7452 CmdArgs.push_back("-target-feature");
7453 CmdArgs.push_back("+outline-atomics");
7456 if (Triple.isAArch64() &&
7457 (Args.hasArg(options::OPT_mno_fmv) ||
7458 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7459 // Disable Function Multiversioning on AArch64 target.
7460 CmdArgs.push_back("-target-feature");
7461 CmdArgs.push_back("-fmv");
7464 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7465 (TC.getTriple().isOSBinFormatELF() ||
7466 TC.getTriple().isOSBinFormatCOFF()) &&
7467 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7468 !TC.getTriple().isOSNetBSD() &&
7469 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7470 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7471 CmdArgs.push_back("-faddrsig");
7473 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7474 (EH || UnwindTables || AsyncUnwindTables ||
7475 DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7476 CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7478 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7479 std::string Str = A->getAsString(Args);
7480 if (!TC.getTriple().isOSBinFormatELF())
7481 D.Diag(diag::err_drv_unsupported_opt_for_target)
7482 << Str << TC.getTripleString();
7483 CmdArgs.push_back(Args.MakeArgString(Str));
7486 // Add the output path to the object file for CodeView debug infos.
7487 if (EmitCodeView && Output.isFilename())
7488 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
7489 Output.getFilename());
7491 // Add the "-o out -x type src.c" flags last. This is done primarily to make
7492 // the -cc1 command easier to edit when reproducing compiler crashes.
7493 if (Output.getType() == types::TY_Dependencies) {
7494 // Handled with other dependency code.
7495 } else if (Output.isFilename()) {
7496 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7497 Output.getType() == clang::driver::types::TY_IFS) {
7498 SmallString<128> OutputFilename(Output.getFilename());
7499 llvm::sys::path::replace_extension(OutputFilename, "ifs");
7500 CmdArgs.push_back("-o");
7501 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7503 CmdArgs.push_back("-o");
7504 CmdArgs.push_back(Output.getFilename());
7507 assert(Output.isNothing() && "Invalid output.");
7510 addDashXForInput(Args, Input, CmdArgs);
7512 ArrayRef<InputInfo> FrontendInputs = Input;
7514 FrontendInputs = ExtractAPIInputs;
7515 else if (Input.isNothing())
7516 FrontendInputs = {};
7518 for (const InputInfo &Input : FrontendInputs) {
7519 if (Input.isFilename())
7520 CmdArgs.push_back(Input.getFilename());
7522 Input.getInputArg().renderAsInput(Args, CmdArgs);
7525 if (D.CC1Main && !D.CCGenDiagnostics) {
7526 // Invoke the CC1 directly in this process
7527 C.addCommand(std::make_unique<CC1Command>(
7528 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7529 Output, D.getPrependArg()));
7531 C.addCommand(std::make_unique<Command>(
7532 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7533 Output, D.getPrependArg()));
7536 // Make the compile command echo its inputs for /showFilenames.
7537 if (Output.getType() == types::TY_Object &&
7538 Args.hasFlag(options::OPT__SLASH_showFilenames,
7539 options::OPT__SLASH_showFilenames_, false)) {
7540 C.getJobs().getJobs().back()->PrintInputFilenames = true;
7543 if (Arg *A = Args.getLastArg(options::OPT_pg))
7544 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7545 !Args.hasArg(options::OPT_mfentry))
7546 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
7547 << A->getAsString(Args);
7549 // Claim some arguments which clang supports automatically.
7551 // -fpch-preprocess is used with gcc to add a special marker in the output to
7552 // include the PCH file.
7553 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
7555 // Claim some arguments which clang doesn't support, but we don't
7556 // care to warn the user about.
7557 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
7558 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
7560 // Disable warnings for clang -E -emit-llvm foo.c
7561 Args.ClaimAllArgs(options::OPT_emit_llvm);
7564 Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
7565 // CAUTION! The first constructor argument ("clang") is not arbitrary,
7566 // as it is for other tools. Some operations on a Tool actually test
7567 // whether that tool is Clang based on the Tool's Name as a string.
7568 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
7572 /// Add options related to the Objective-C runtime/ABI.
7574 /// Returns true if the runtime is non-fragile.
7575 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
7576 const InputInfoList &inputs,
7577 ArgStringList &cmdArgs,
7578 RewriteKind rewriteKind) const {
7579 // Look for the controlling runtime option.
7581 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
7582 options::OPT_fobjc_runtime_EQ);
7584 // Just forward -fobjc-runtime= to the frontend. This supercedes
7585 // options about fragility.
7587 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
7588 ObjCRuntime runtime;
7589 StringRef value = runtimeArg->getValue();
7590 if (runtime.tryParse(value)) {
7591 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
7594 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
7595 (runtime.getVersion() >= VersionTuple(2, 0)))
7596 if (!getToolChain().getTriple().isOSBinFormatELF() &&
7597 !getToolChain().getTriple().isOSBinFormatCOFF()) {
7598 getToolChain().getDriver().Diag(
7599 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
7600 << runtime.getVersion().getMajor();
7603 runtimeArg->render(args, cmdArgs);
7607 // Otherwise, we'll need the ABI "version". Version numbers are
7608 // slightly confusing for historical reasons:
7609 // 1 - Traditional "fragile" ABI
7610 // 2 - Non-fragile ABI, version 1
7611 // 3 - Non-fragile ABI, version 2
7612 unsigned objcABIVersion = 1;
7613 // If -fobjc-abi-version= is present, use that to set the version.
7614 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
7615 StringRef value = abiArg->getValue();
7618 else if (value == "2")
7620 else if (value == "3")
7623 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
7625 // Otherwise, determine if we are using the non-fragile ABI.
7626 bool nonFragileABIIsDefault =
7627 (rewriteKind == RK_NonFragile ||
7628 (rewriteKind == RK_None &&
7629 getToolChain().IsObjCNonFragileABIDefault()));
7630 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
7631 options::OPT_fno_objc_nonfragile_abi,
7632 nonFragileABIIsDefault)) {
7633 // Determine the non-fragile ABI version to use.
7634 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
7635 unsigned nonFragileABIVersion = 1;
7637 unsigned nonFragileABIVersion = 2;
7641 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
7642 StringRef value = abiArg->getValue();
7644 nonFragileABIVersion = 1;
7645 else if (value == "2")
7646 nonFragileABIVersion = 2;
7648 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
7652 objcABIVersion = 1 + nonFragileABIVersion;
7658 // We don't actually care about the ABI version other than whether
7659 // it's non-fragile.
7660 bool isNonFragile = objcABIVersion != 1;
7662 // If we have no runtime argument, ask the toolchain for its default runtime.
7663 // However, the rewriter only really supports the Mac runtime, so assume that.
7664 ObjCRuntime runtime;
7666 switch (rewriteKind) {
7668 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7671 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7674 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7679 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7680 // On Darwin, make this use the default behavior for the toolchain.
7681 if (getToolChain().getTriple().isOSDarwin()) {
7682 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7684 // Otherwise, build for a generic macosx port.
7686 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7691 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7692 // Legacy behaviour is to target the gnustep runtime if we are in
7693 // non-fragile mode or the GCC runtime in fragile mode.
7695 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7697 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7700 if (llvm::any_of(inputs, [](const InputInfo &input) {
7701 return types::isObjC(input.getType());
7704 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7708 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7709 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7717 bool Asynch = false;
7718 bool NoUnwindC = false;
7720 } // end anonymous namespace
7722 /// /EH controls whether to run destructor cleanups when exceptions are
7723 /// thrown. There are three modifiers:
7724 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7725 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7726 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7727 /// - c: Assume that extern "C" functions are implicitly nounwind.
7728 /// The default is /EHs-c-, meaning cleanups are disabled.
7729 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7732 std::vector<std::string> EHArgs =
7733 Args.getAllArgValues(options::OPT__SLASH_EH);
7734 for (auto EHVal : EHArgs) {
7735 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7738 EH.Asynch = maybeConsumeDash(EHVal, I);
7743 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7746 EH.Synch = maybeConsumeDash(EHVal, I);
7753 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7757 // The /GX, /GX- flags are only processed if there are not /EH flags.
7758 // The default is that /GX is not specified.
7759 if (EHArgs.empty() &&
7760 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7761 /*Default=*/false)) {
7763 EH.NoUnwindC = true;
7766 if (Args.hasArg(options::OPT__SLASH_kernel)) {
7768 EH.NoUnwindC = false;
7775 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7776 ArgStringList &CmdArgs,
7777 llvm::codegenoptions::DebugInfoKind *DebugInfoKind,
7778 bool *EmitCodeView) const {
7779 bool isNVPTX = getToolChain().getTriple().isNVPTX();
7781 ProcessVSRuntimeLibrary(Args, CmdArgs);
7783 if (Arg *ShowIncludes =
7784 Args.getLastArg(options::OPT__SLASH_showIncludes,
7785 options::OPT__SLASH_showIncludes_user)) {
7786 CmdArgs.push_back("--show-includes");
7787 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7788 CmdArgs.push_back("-sys-header-deps");
7791 // This controls whether or not we emit RTTI data for polymorphic types.
7792 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7794 CmdArgs.push_back("-fno-rtti-data");
7796 // This controls whether or not we emit stack-protector instrumentation.
7797 // In MSVC, Buffer Security Check (/GS) is on by default.
7798 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7799 /*Default=*/true)) {
7800 CmdArgs.push_back("-stack-protector");
7801 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7804 // Emit CodeView if -Z7 or -gline-tables-only are present.
7805 if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7,
7806 options::OPT_gline_tables_only)) {
7807 *EmitCodeView = true;
7808 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
7809 *DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
7811 *DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
7813 *EmitCodeView = false;
7816 const Driver &D = getToolChain().getDriver();
7818 // This controls whether or not we perform JustMyCode instrumentation.
7819 if (Args.hasFlag(options::OPT__SLASH_JMC, options::OPT__SLASH_JMC_,
7820 /*Default=*/false)) {
7821 if (*EmitCodeView &&
7822 *DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
7823 CmdArgs.push_back("-fjmc");
7825 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
7829 EHFlags EH = parseClangCLEHFlags(D, Args);
7830 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7831 if (types::isCXX(InputType))
7832 CmdArgs.push_back("-fcxx-exceptions");
7833 CmdArgs.push_back("-fexceptions");
7835 CmdArgs.push_back("-fasync-exceptions");
7837 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7838 CmdArgs.push_back("-fexternc-nounwind");
7840 // /EP should expand to -E -P.
7841 if (Args.hasArg(options::OPT__SLASH_EP)) {
7842 CmdArgs.push_back("-E");
7843 CmdArgs.push_back("-P");
7846 unsigned VolatileOptionID;
7847 if (getToolChain().getTriple().isX86())
7848 VolatileOptionID = options::OPT__SLASH_volatile_ms;
7850 VolatileOptionID = options::OPT__SLASH_volatile_iso;
7852 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
7853 VolatileOptionID = A->getOption().getID();
7855 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
7856 CmdArgs.push_back("-fms-volatile");
7858 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7859 options::OPT__SLASH_Zc_dllexportInlines,
7861 CmdArgs.push_back("-fno-dllexport-inlines");
7864 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
7865 options::OPT__SLASH_Zc_wchar_t, false)) {
7866 CmdArgs.push_back("-fno-wchar");
7869 if (Args.hasArg(options::OPT__SLASH_kernel)) {
7870 llvm::Triple::ArchType Arch = getToolChain().getArch();
7871 std::vector<std::string> Values =
7872 Args.getAllArgValues(options::OPT__SLASH_arch);
7873 if (!Values.empty()) {
7874 llvm::SmallSet<std::string, 4> SupportedArches;
7875 if (Arch == llvm::Triple::x86)
7876 SupportedArches.insert("IA32");
7878 for (auto &V : Values)
7879 if (!SupportedArches.contains(V))
7880 D.Diag(diag::err_drv_argument_not_allowed_with)
7881 << std::string("/arch:").append(V) << "/kernel";
7884 CmdArgs.push_back("-fno-rtti");
7885 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
7886 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
7890 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
7891 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
7892 if (MostGeneralArg && BestCaseArg)
7893 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7894 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
7896 if (MostGeneralArg) {
7897 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
7898 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
7899 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
7901 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
7902 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
7903 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
7904 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7905 << FirstConflict->getAsString(Args)
7906 << SecondConflict->getAsString(Args);
7909 CmdArgs.push_back("-fms-memptr-rep=single");
7910 else if (MultipleArg)
7911 CmdArgs.push_back("-fms-memptr-rep=multiple");
7913 CmdArgs.push_back("-fms-memptr-rep=virtual");
7916 // Parse the default calling convention options.
7918 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
7919 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
7920 options::OPT__SLASH_Gregcall)) {
7921 unsigned DCCOptId = CCArg->getOption().getID();
7922 const char *DCCFlag = nullptr;
7923 bool ArchSupported = !isNVPTX;
7924 llvm::Triple::ArchType Arch = getToolChain().getArch();
7926 case options::OPT__SLASH_Gd:
7927 DCCFlag = "-fdefault-calling-conv=cdecl";
7929 case options::OPT__SLASH_Gr:
7930 ArchSupported = Arch == llvm::Triple::x86;
7931 DCCFlag = "-fdefault-calling-conv=fastcall";
7933 case options::OPT__SLASH_Gz:
7934 ArchSupported = Arch == llvm::Triple::x86;
7935 DCCFlag = "-fdefault-calling-conv=stdcall";
7937 case options::OPT__SLASH_Gv:
7938 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7939 DCCFlag = "-fdefault-calling-conv=vectorcall";
7941 case options::OPT__SLASH_Gregcall:
7942 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7943 DCCFlag = "-fdefault-calling-conv=regcall";
7947 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
7948 if (ArchSupported && DCCFlag)
7949 CmdArgs.push_back(DCCFlag);
7952 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
7954 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
7955 CmdArgs.push_back("-fdiagnostics-format");
7956 CmdArgs.push_back("msvc");
7959 if (Args.hasArg(options::OPT__SLASH_kernel))
7960 CmdArgs.push_back("-fms-kernel");
7962 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
7963 StringRef GuardArgs = A->getValue();
7964 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
7966 if (GuardArgs.equals_insensitive("cf")) {
7967 // Emit CFG instrumentation and the table of address-taken functions.
7968 CmdArgs.push_back("-cfguard");
7969 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
7970 // Emit only the table of address-taken functions.
7971 CmdArgs.push_back("-cfguard-no-checks");
7972 } else if (GuardArgs.equals_insensitive("ehcont")) {
7973 // Emit EH continuation table.
7974 CmdArgs.push_back("-ehcontguard");
7975 } else if (GuardArgs.equals_insensitive("cf-") ||
7976 GuardArgs.equals_insensitive("ehcont-")) {
7977 // Do nothing, but we might want to emit a security warning in future.
7979 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
7985 const char *Clang::getBaseInputName(const ArgList &Args,
7986 const InputInfo &Input) {
7987 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7990 const char *Clang::getBaseInputStem(const ArgList &Args,
7991 const InputInfoList &Inputs) {
7992 const char *Str = getBaseInputName(Args, Inputs[0]);
7994 if (const char *End = strrchr(Str, '.'))
7995 return Args.MakeArgString(std::string(Str, End));
8000 const char *Clang::getDependencyFileName(const ArgList &Args,
8001 const InputInfoList &Inputs) {
8002 // FIXME: Think about this more.
8004 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8005 SmallString<128> OutputFilename(OutputOpt->getValue());
8006 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8007 return Args.MakeArgString(OutputFilename);
8010 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8015 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8016 ArgStringList &CmdArgs) const {
8019 const llvm::Triple &Triple = getToolChain().getTriple();
8020 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8022 CmdArgs.push_back("-target-abi");
8023 CmdArgs.push_back(ABIName.data());
8026 void ClangAs::AddX86TargetArgs(const ArgList &Args,
8027 ArgStringList &CmdArgs) const {
8028 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8031 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8032 StringRef Value = A->getValue();
8033 if (Value == "intel" || Value == "att") {
8034 CmdArgs.push_back("-mllvm");
8035 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8037 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8038 << A->getSpelling() << Value;
8043 void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8044 ArgStringList &CmdArgs) const {
8045 CmdArgs.push_back("-target-abi");
8046 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8047 getToolChain().getTriple())
8051 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8052 ArgStringList &CmdArgs) const {
8053 const llvm::Triple &Triple = getToolChain().getTriple();
8054 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8056 CmdArgs.push_back("-target-abi");
8057 CmdArgs.push_back(ABIName.data());
8059 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8060 options::OPT_mno_default_build_attributes, true)) {
8061 CmdArgs.push_back("-mllvm");
8062 CmdArgs.push_back("-riscv-add-build-attributes");
8066 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8067 const InputInfo &Output, const InputInfoList &Inputs,
8068 const ArgList &Args,
8069 const char *LinkingOutput) const {
8070 ArgStringList CmdArgs;
8072 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8073 const InputInfo &Input = Inputs[0];
8075 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8076 const std::string &TripleStr = Triple.getTriple();
8077 const auto &D = getToolChain().getDriver();
8079 // Don't warn about "clang -w -c foo.s"
8080 Args.ClaimAllArgs(options::OPT_w);
8081 // and "clang -emit-llvm -c foo.s"
8082 Args.ClaimAllArgs(options::OPT_emit_llvm);
8084 claimNoWarnArgs(Args);
8086 // Invoke ourselves in -cc1as mode.
8088 // FIXME: Implement custom jobs for internal actions.
8089 CmdArgs.push_back("-cc1as");
8091 // Add the "effective" target triple.
8092 CmdArgs.push_back("-triple");
8093 CmdArgs.push_back(Args.MakeArgString(TripleStr));
8095 getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
8097 // Set the output mode, we currently only expect to be used as a real
8099 CmdArgs.push_back("-filetype");
8100 CmdArgs.push_back("obj");
8102 // Set the main file name, so that debug info works even with
8103 // -save-temps or preprocessed assembly.
8104 CmdArgs.push_back("-main-file-name");
8105 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8107 // Add the target cpu
8108 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8110 CmdArgs.push_back("-target-cpu");
8111 CmdArgs.push_back(Args.MakeArgString(CPU));
8114 // Add the target features
8115 getTargetFeatures(D, Triple, Args, CmdArgs, true);
8117 // Ignore explicit -force_cpusubtype_ALL option.
8118 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8120 // Pass along any -I options so we get proper .include search paths.
8121 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8123 // Determine the original source input.
8124 auto FindSource = [](const Action *S) -> const Action * {
8125 while (S->getKind() != Action::InputClass) {
8126 assert(!S->getInputs().empty() && "unexpected root action!");
8127 S = S->getInputs()[0];
8131 const Action *SourceAction = FindSource(&JA);
8133 // Forward -g and handle debug info related flags, assuming we are dealing
8134 // with an actual assembly file.
8135 bool WantDebug = false;
8136 Args.ClaimAllArgs(options::OPT_g_Group);
8137 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8138 WantDebug = !A->getOption().matches(options::OPT_g0) &&
8139 !A->getOption().matches(options::OPT_ggdb0);
8141 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8142 llvm::codegenoptions::NoDebugInfo;
8144 // Add the -fdebug-compilation-dir flag if needed.
8145 const char *DebugCompilationDir =
8146 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
8148 if (SourceAction->getType() == types::TY_Asm ||
8149 SourceAction->getType() == types::TY_PP_Asm) {
8150 // You might think that it would be ok to set DebugInfoKind outside of
8151 // the guard for source type, however there is a test which asserts
8152 // that some assembler invocation receives no -debug-info-kind,
8153 // and it's not clear whether that test is just overly restrictive.
8154 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8155 : llvm::codegenoptions::NoDebugInfo);
8157 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
8160 // Set the AT_producer to the clang version when using the integrated
8161 // assembler on assembly source files.
8162 CmdArgs.push_back("-dwarf-debug-producer");
8163 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8165 // And pass along -I options
8166 Args.AddAllArgs(CmdArgs, options::OPT_I);
8168 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8169 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8170 llvm::DebuggerKind::Default);
8171 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8172 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
8174 // Handle -fPIC et al -- the relocation-model affects the assembler
8175 // for some targets.
8176 llvm::Reloc::Model RelocationModel;
8179 std::tie(RelocationModel, PICLevel, IsPIE) =
8180 ParsePICArgs(getToolChain(), Args);
8182 const char *RMName = RelocationModelName(RelocationModel);
8184 CmdArgs.push_back("-mrelocation-model");
8185 CmdArgs.push_back(RMName);
8188 // Optionally embed the -cc1as level arguments into the debug info, for build
8190 if (getToolChain().UseDwarfDebugFlags()) {
8191 ArgStringList OriginalArgs;
8192 for (const auto &Arg : Args)
8193 Arg->render(Args, OriginalArgs);
8195 SmallString<256> Flags;
8196 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8197 EscapeSpacesAndBackslashes(Exec, Flags);
8198 for (const char *OriginalArg : OriginalArgs) {
8199 SmallString<128> EscapedArg;
8200 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8202 Flags += EscapedArg;
8204 CmdArgs.push_back("-dwarf-debug-flags");
8205 CmdArgs.push_back(Args.MakeArgString(Flags));
8208 // FIXME: Add -static support, once we have it.
8210 // Add target specific flags.
8211 switch (getToolChain().getArch()) {
8215 case llvm::Triple::mips:
8216 case llvm::Triple::mipsel:
8217 case llvm::Triple::mips64:
8218 case llvm::Triple::mips64el:
8219 AddMIPSTargetArgs(Args, CmdArgs);
8222 case llvm::Triple::x86:
8223 case llvm::Triple::x86_64:
8224 AddX86TargetArgs(Args, CmdArgs);
8227 case llvm::Triple::arm:
8228 case llvm::Triple::armeb:
8229 case llvm::Triple::thumb:
8230 case llvm::Triple::thumbeb:
8231 // This isn't in AddARMTargetArgs because we want to do this for assembly
8233 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8234 options::OPT_mno_default_build_attributes, true)) {
8235 CmdArgs.push_back("-mllvm");
8236 CmdArgs.push_back("-arm-add-build-attributes");
8240 case llvm::Triple::aarch64:
8241 case llvm::Triple::aarch64_32:
8242 case llvm::Triple::aarch64_be:
8243 if (Args.hasArg(options::OPT_mmark_bti_property)) {
8244 CmdArgs.push_back("-mllvm");
8245 CmdArgs.push_back("-aarch64-mark-bti-property");
8249 case llvm::Triple::loongarch32:
8250 case llvm::Triple::loongarch64:
8251 AddLoongArchTargetArgs(Args, CmdArgs);
8254 case llvm::Triple::riscv32:
8255 case llvm::Triple::riscv64:
8256 AddRISCVTargetArgs(Args, CmdArgs);
8260 // Consume all the warning flags. Usually this would be handled more
8261 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8262 // doesn't handle that so rather than warning about unused flags that are
8263 // actually used, we'll lie by omission instead.
8264 // FIXME: Stop lying and consume only the appropriate driver flags
8265 Args.ClaimAllArgs(options::OPT_W_Group);
8267 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8268 getToolChain().getDriver());
8270 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8272 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8273 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8274 Output.getFilename());
8276 // Fixup any previous commands that use -object-file-name because when we
8277 // generated them, the final .obj name wasn't yet known.
8278 for (Command &J : C.getJobs()) {
8279 if (SourceAction != FindSource(&J.getSource()))
8281 auto &JArgs = J.getArguments();
8282 for (unsigned I = 0; I < JArgs.size(); ++I) {
8283 if (StringRef(JArgs[I]).startswith("-object-file-name=") &&
8284 Output.isFilename()) {
8285 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8286 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
8287 Output.getFilename());
8288 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
8289 J.replaceArguments(NewArgs);
8295 assert(Output.isFilename() && "Unexpected lipo output.");
8296 CmdArgs.push_back("-o");
8297 CmdArgs.push_back(Output.getFilename());
8299 const llvm::Triple &T = getToolChain().getTriple();
8301 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
8302 T.isOSBinFormatELF()) {
8303 CmdArgs.push_back("-split-dwarf-output");
8304 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8307 if (Triple.isAMDGPU())
8308 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8310 assert(Input.isFilename() && "Invalid input.");
8311 CmdArgs.push_back(Input.getFilename());
8313 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8314 if (D.CC1Main && !D.CCGenDiagnostics) {
8315 // Invoke cc1as directly in this process.
8316 C.addCommand(std::make_unique<CC1Command>(
8317 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8318 Output, D.getPrependArg()));
8320 C.addCommand(std::make_unique<Command>(
8321 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8322 Output, D.getPrependArg()));
8326 // Begin OffloadBundler
8328 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8329 const InputInfo &Output,
8330 const InputInfoList &Inputs,
8331 const llvm::opt::ArgList &TCArgs,
8332 const char *LinkingOutput) const {
8333 // The version with only one output is expected to refer to a bundling job.
8334 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8336 // The bundling command looks like this:
8337 // clang-offload-bundler -type=bc
8338 // -targets=host-triple,openmp-triple1,openmp-triple2
8339 // -output=output_file
8340 // -input=unbundle_file_host
8341 // -input=unbundle_file_tgt1
8342 // -input=unbundle_file_tgt2
8344 ArgStringList CmdArgs;
8347 CmdArgs.push_back(TCArgs.MakeArgString(
8348 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8350 assert(JA.getInputs().size() == Inputs.size() &&
8351 "Not have inputs for all dependence actions??");
8354 SmallString<128> Triples;
8355 Triples += "-targets=";
8356 for (unsigned I = 0; I < Inputs.size(); ++I) {
8360 // Find ToolChain for this input.
8361 Action::OffloadKind CurKind = Action::OFK_Host;
8362 const ToolChain *CurTC = &getToolChain();
8363 const Action *CurDep = JA.getInputs()[I];
8365 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8367 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8368 assert(CurTC == nullptr && "Expected one dependence!");
8369 CurKind = A->getOffloadingDeviceKind();
8373 Triples += Action::GetOffloadKindName(CurKind);
8375 Triples += CurTC->getTriple().normalize();
8376 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8377 !StringRef(CurDep->getOffloadingArch()).empty()) {
8379 Triples += CurDep->getOffloadingArch();
8382 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8383 // with each toolchain.
8384 StringRef GPUArchName;
8385 if (CurKind == Action::OFK_OpenMP) {
8386 // Extract GPUArch from -march argument in TC argument list.
8387 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8388 auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8389 auto Arch = ArchStr.starts_with_insensitive("-march=");
8391 GPUArchName = ArchStr.substr(7);
8396 Triples += GPUArchName.str();
8399 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8401 // Get bundled file command.
8403 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8405 // Get unbundled files command.
8406 for (unsigned I = 0; I < Inputs.size(); ++I) {
8407 SmallString<128> UB;
8410 // Find ToolChain for this input.
8411 const ToolChain *CurTC = &getToolChain();
8412 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8414 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8415 assert(CurTC == nullptr && "Expected one dependence!");
8418 UB += C.addTempFile(
8419 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8421 UB += CurTC->getInputFilename(Inputs[I]);
8423 CmdArgs.push_back(TCArgs.MakeArgString(UB));
8425 // All the inputs are encoded as commands.
8426 C.addCommand(std::make_unique<Command>(
8427 JA, *this, ResponseFileSupport::None(),
8428 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8429 CmdArgs, std::nullopt, Output));
8432 void OffloadBundler::ConstructJobMultipleOutputs(
8433 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8434 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8435 const char *LinkingOutput) const {
8436 // The version with multiple outputs is expected to refer to a unbundling job.
8437 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8439 // The unbundling command looks like this:
8440 // clang-offload-bundler -type=bc
8441 // -targets=host-triple,openmp-triple1,openmp-triple2
8442 // -input=input_file
8443 // -output=unbundle_file_host
8444 // -output=unbundle_file_tgt1
8445 // -output=unbundle_file_tgt2
8448 ArgStringList CmdArgs;
8450 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8451 InputInfo Input = Inputs.front();
8454 CmdArgs.push_back(TCArgs.MakeArgString(
8455 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8458 SmallString<128> Triples;
8459 Triples += "-targets=";
8460 auto DepInfo = UA.getDependentActionsInfo();
8461 for (unsigned I = 0; I < DepInfo.size(); ++I) {
8465 auto &Dep = DepInfo[I];
8466 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8468 Triples += Dep.DependentToolChain->getTriple().normalize();
8469 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8470 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8471 !Dep.DependentBoundArch.empty()) {
8473 Triples += Dep.DependentBoundArch;
8475 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8476 // with each toolchain.
8477 StringRef GPUArchName;
8478 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8479 // Extract GPUArch from -march argument in TC argument list.
8480 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8481 StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8482 auto Arch = ArchStr.starts_with_insensitive("-march=");
8484 GPUArchName = ArchStr.substr(7);
8489 Triples += GPUArchName.str();
8493 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8495 // Get bundled file command.
8497 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
8499 // Get unbundled files command.
8500 for (unsigned I = 0; I < Outputs.size(); ++I) {
8501 SmallString<128> UB;
8503 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
8504 CmdArgs.push_back(TCArgs.MakeArgString(UB));
8506 CmdArgs.push_back("-unbundle");
8507 CmdArgs.push_back("-allow-missing-bundles");
8509 // All the inputs are encoded as commands.
8510 C.addCommand(std::make_unique<Command>(
8511 JA, *this, ResponseFileSupport::None(),
8512 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8513 CmdArgs, std::nullopt, Outputs));
8516 void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
8517 const InputInfo &Output,
8518 const InputInfoList &Inputs,
8519 const llvm::opt::ArgList &Args,
8520 const char *LinkingOutput) const {
8521 ArgStringList CmdArgs;
8523 // Add the output file name.
8524 assert(Output.isFilename() && "Invalid output.");
8525 CmdArgs.push_back("-o");
8526 CmdArgs.push_back(Output.getFilename());
8528 // Create the inputs to bundle the needed metadata.
8529 for (const InputInfo &Input : Inputs) {
8530 const Action *OffloadAction = Input.getAction();
8531 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
8532 const ArgList &TCArgs =
8533 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
8534 OffloadAction->getOffloadingDeviceKind());
8535 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
8536 StringRef Arch = OffloadAction->getOffloadingArch()
8537 ? OffloadAction->getOffloadingArch()
8538 : TCArgs.getLastArgValue(options::OPT_march_EQ);
8540 Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
8542 ArgStringList Features;
8543 SmallVector<StringRef> FeatureArgs;
8544 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
8546 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
8547 [](StringRef Arg) { return !Arg.startswith("-target"); });
8549 if (TC->getTriple().isAMDGPU()) {
8550 for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
8551 FeatureArgs.emplace_back(
8552 Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
8556 // TODO: We need to pass in the full target-id and handle it properly in the
8558 SmallVector<std::string> Parts{
8559 "file=" + File.str(),
8560 "triple=" + TC->getTripleString(),
8561 "arch=" + getProcessorFromTargetID(TC->getTriple(), Arch).str(),
8562 "kind=" + Kind.str(),
8565 if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
8566 TC->getTriple().isAMDGPU())
8567 for (StringRef Feature : FeatureArgs)
8568 Parts.emplace_back("feature=" + Feature.str());
8570 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
8573 C.addCommand(std::make_unique<Command>(
8574 JA, *this, ResponseFileSupport::None(),
8575 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8576 CmdArgs, Inputs, Output));
8579 void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
8580 const InputInfo &Output,
8581 const InputInfoList &Inputs,
8582 const ArgList &Args,
8583 const char *LinkingOutput) const {
8584 const Driver &D = getToolChain().getDriver();
8585 const llvm::Triple TheTriple = getToolChain().getTriple();
8586 ArgStringList CmdArgs;
8588 // Pass the CUDA path to the linker wrapper tool.
8589 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
8590 auto TCRange = C.getOffloadToolChains(Kind);
8591 for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
8592 const ToolChain *TC = I.second;
8593 if (TC->getTriple().isNVPTX()) {
8594 CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8595 if (CudaInstallation.isValid())
8596 CmdArgs.push_back(Args.MakeArgString(
8597 "--cuda-path=" + CudaInstallation.getInstallPath()));
8603 if (D.isUsingLTO(/* IsOffload */ true)) {
8604 // Pass in the optimization level to use for LTO.
8605 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
8607 if (A->getOption().matches(options::OPT_O4) ||
8608 A->getOption().matches(options::OPT_Ofast))
8610 else if (A->getOption().matches(options::OPT_O)) {
8611 OOpt = A->getValue();
8614 else if (OOpt == "s" || OOpt == "z")
8616 } else if (A->getOption().matches(options::OPT_O0))
8619 CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
8624 Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
8625 if (Args.hasArg(options::OPT_v))
8626 CmdArgs.push_back("--wrapper-verbose");
8628 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8629 if (!A->getOption().matches(options::OPT_g0))
8630 CmdArgs.push_back("--device-debug");
8633 for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8634 CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
8636 // Forward remarks passes to the LLVM backend in the wrapper.
8637 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8638 CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
8640 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8641 CmdArgs.push_back(Args.MakeArgString(
8642 Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
8643 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8644 CmdArgs.push_back(Args.MakeArgString(
8645 Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
8646 if (Args.getLastArg(options::OPT_save_temps_EQ))
8647 CmdArgs.push_back("--save-temps");
8649 // Construct the link job so we can wrap around it.
8650 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8651 const auto &LinkCommand = C.getJobs().getJobs().back();
8653 // Forward -Xoffload-linker<-triple> arguments to the device link job.
8654 for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
8655 StringRef Val = A->getValue(0);
8658 Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
8660 CmdArgs.push_back(Args.MakeArgString(
8661 "--device-linker=" +
8662 ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
8665 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
8667 // Embed bitcode instead of an object in JIT mode.
8668 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
8669 options::OPT_fno_openmp_target_jit, false))
8670 CmdArgs.push_back("--embed-bitcode");
8672 // Forward `-mllvm` arguments to the LLVM invocations if present.
8673 for (Arg *A : Args.filtered(options::OPT_mllvm)) {
8674 CmdArgs.push_back("-mllvm");
8675 CmdArgs.push_back(A->getValue());
8679 // Add the linker arguments to be forwarded by the wrapper.
8680 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
8681 LinkCommand->getExecutable()));
8682 CmdArgs.push_back("--");
8683 for (const char *LinkArg : LinkCommand->getArguments())
8684 CmdArgs.push_back(LinkArg);
8687 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
8689 // Replace the executable and arguments of the link job with the
8691 LinkCommand->replaceExecutable(Exec);
8692 LinkCommand->replaceArguments(CmdArgs);