[Flang] remove whole-archive option for AIX linker (#76039)
[llvm-project.git] / clang / lib / Driver / ToolChains / Clang.cpp
blob4783affd3220bc924317a6d5db54f1121ba32faf
1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "Clang.h"
10 #include "AMDGPU.h"
11 #include "Arch/AArch64.h"
12 #include "Arch/ARM.h"
13 #include "Arch/CSKY.h"
14 #include "Arch/LoongArch.h"
15 #include "Arch/M68k.h"
16 #include "Arch/Mips.h"
17 #include "Arch/PPC.h"
18 #include "Arch/RISCV.h"
19 #include "Arch/Sparc.h"
20 #include "Arch/SystemZ.h"
21 #include "Arch/VE.h"
22 #include "Arch/X86.h"
23 #include "CommonArgs.h"
24 #include "Hexagon.h"
25 #include "MSP430.h"
26 #include "PS4CPU.h"
27 #include "clang/Basic/CLWarnings.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/CodeGenOptions.h"
30 #include "clang/Basic/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"
61 #include <cctype>
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 options::OPT_fkeep_system_includes,
73 options::OPT_fno_keep_system_includes)) {
74 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
75 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
76 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
77 << A->getBaseArg().getAsString(Args)
78 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
83 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
84 // In gcc, only ARM checks this, but it seems reasonable to check universally.
85 if (Args.hasArg(options::OPT_static))
86 if (const Arg *A =
87 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
88 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
89 << "-static";
92 // Add backslashes to escape spaces and other backslashes.
93 // This is used for the space-separated argument list specified with
94 // the -dwarf-debug-flags option.
95 static void EscapeSpacesAndBackslashes(const char *Arg,
96 SmallVectorImpl<char> &Res) {
97 for (; *Arg; ++Arg) {
98 switch (*Arg) {
99 default:
100 break;
101 case ' ':
102 case '\\':
103 Res.push_back('\\');
104 break;
106 Res.push_back(*Arg);
110 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
111 /// offloading tool chain that is associated with the current action \a JA.
112 static void
113 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
114 const ToolChain &RegularToolChain,
115 llvm::function_ref<void(const ToolChain &)> Work) {
116 // Apply Work on the current/regular tool chain.
117 Work(RegularToolChain);
119 // Apply Work on all the offloading tool chains associated with the current
120 // action.
121 if (JA.isHostOffloading(Action::OFK_Cuda))
122 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
123 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
124 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
125 else if (JA.isHostOffloading(Action::OFK_HIP))
126 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
127 else if (JA.isDeviceOffloading(Action::OFK_HIP))
128 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
130 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
131 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
132 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
133 Work(*II->second);
134 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
138 // TODO: Add support for other offloading programming models here.
142 /// This is a helper function for validating the optional refinement step
143 /// parameter in reciprocal argument strings. Return false if there is an error
144 /// parsing the refinement step. Otherwise, return true and set the Position
145 /// of the refinement step in the input string.
146 static bool getRefinementStep(StringRef In, const Driver &D,
147 const Arg &A, size_t &Position) {
148 const char RefinementStepToken = ':';
149 Position = In.find(RefinementStepToken);
150 if (Position != StringRef::npos) {
151 StringRef Option = A.getOption().getName();
152 StringRef RefStep = In.substr(Position + 1);
153 // Allow exactly one numeric character for the additional refinement
154 // step parameter. This is reasonable for all currently-supported
155 // operations and architectures because we would expect that a larger value
156 // of refinement steps would cause the estimate "optimization" to
157 // under-perform the native operation. Also, if the estimate does not
158 // converge quickly, it probably will not ever converge, so further
159 // refinement steps will not produce a better answer.
160 if (RefStep.size() != 1) {
161 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
162 return false;
164 char RefStepChar = RefStep[0];
165 if (RefStepChar < '0' || RefStepChar > '9') {
166 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
167 return false;
170 return true;
173 /// The -mrecip flag requires processing of many optional parameters.
174 static void ParseMRecip(const Driver &D, const ArgList &Args,
175 ArgStringList &OutStrings) {
176 StringRef DisabledPrefixIn = "!";
177 StringRef DisabledPrefixOut = "!";
178 StringRef EnabledPrefixOut = "";
179 StringRef Out = "-mrecip=";
181 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
182 if (!A)
183 return;
185 unsigned NumOptions = A->getNumValues();
186 if (NumOptions == 0) {
187 // No option is the same as "all".
188 OutStrings.push_back(Args.MakeArgString(Out + "all"));
189 return;
192 // Pass through "all", "none", or "default" with an optional refinement step.
193 if (NumOptions == 1) {
194 StringRef Val = A->getValue(0);
195 size_t RefStepLoc;
196 if (!getRefinementStep(Val, D, *A, RefStepLoc))
197 return;
198 StringRef ValBase = Val.slice(0, RefStepLoc);
199 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
200 OutStrings.push_back(Args.MakeArgString(Out + Val));
201 return;
205 // Each reciprocal type may be enabled or disabled individually.
206 // Check each input value for validity, concatenate them all back together,
207 // and pass through.
209 llvm::StringMap<bool> OptionStrings;
210 OptionStrings.insert(std::make_pair("divd", false));
211 OptionStrings.insert(std::make_pair("divf", false));
212 OptionStrings.insert(std::make_pair("divh", false));
213 OptionStrings.insert(std::make_pair("vec-divd", false));
214 OptionStrings.insert(std::make_pair("vec-divf", false));
215 OptionStrings.insert(std::make_pair("vec-divh", false));
216 OptionStrings.insert(std::make_pair("sqrtd", false));
217 OptionStrings.insert(std::make_pair("sqrtf", false));
218 OptionStrings.insert(std::make_pair("sqrth", false));
219 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
220 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
221 OptionStrings.insert(std::make_pair("vec-sqrth", false));
223 for (unsigned i = 0; i != NumOptions; ++i) {
224 StringRef Val = A->getValue(i);
226 bool IsDisabled = Val.starts_with(DisabledPrefixIn);
227 // Ignore the disablement token for string matching.
228 if (IsDisabled)
229 Val = Val.substr(1);
231 size_t RefStep;
232 if (!getRefinementStep(Val, D, *A, RefStep))
233 return;
235 StringRef ValBase = Val.slice(0, RefStep);
236 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
237 if (OptionIter == OptionStrings.end()) {
238 // Try again specifying float suffix.
239 OptionIter = OptionStrings.find(ValBase.str() + 'f');
240 if (OptionIter == OptionStrings.end()) {
241 // The input name did not match any known option string.
242 D.Diag(diag::err_drv_unknown_argument) << Val;
243 return;
245 // The option was specified without a half or float or double suffix.
246 // Make sure that the double or half entry was not already specified.
247 // The float entry will be checked below.
248 if (OptionStrings[ValBase.str() + 'd'] ||
249 OptionStrings[ValBase.str() + 'h']) {
250 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
251 return;
255 if (OptionIter->second == true) {
256 // Duplicate option specified.
257 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
258 return;
261 // Mark the matched option as found. Do not allow duplicate specifiers.
262 OptionIter->second = true;
264 // If the precision was not specified, also mark the double and half entry
265 // as found.
266 if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
267 OptionStrings[ValBase.str() + 'd'] = true;
268 OptionStrings[ValBase.str() + 'h'] = true;
271 // Build the output string.
272 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
273 Out = Args.MakeArgString(Out + Prefix + Val);
274 if (i != NumOptions - 1)
275 Out = Args.MakeArgString(Out + ",");
278 OutStrings.push_back(Args.MakeArgString(Out));
281 /// The -mprefer-vector-width option accepts either a positive integer
282 /// or the string "none".
283 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
284 ArgStringList &CmdArgs) {
285 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
286 if (!A)
287 return;
289 StringRef Value = A->getValue();
290 if (Value == "none") {
291 CmdArgs.push_back("-mprefer-vector-width=none");
292 } else {
293 unsigned Width;
294 if (Value.getAsInteger(10, Width)) {
295 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
296 return;
298 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
302 static bool
303 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
304 const llvm::Triple &Triple) {
305 // We use the zero-cost exception tables for Objective-C if the non-fragile
306 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
307 // later.
308 if (runtime.isNonFragile())
309 return true;
311 if (!Triple.isMacOSX())
312 return false;
314 return (!Triple.isMacOSXVersionLT(10, 5) &&
315 (Triple.getArch() == llvm::Triple::x86_64 ||
316 Triple.getArch() == llvm::Triple::arm));
319 /// Adds exception related arguments to the driver command arguments. There's a
320 /// main flag, -fexceptions and also language specific flags to enable/disable
321 /// C++ and Objective-C exceptions. This makes it possible to for example
322 /// disable C++ exceptions but enable Objective-C exceptions.
323 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
324 const ToolChain &TC, bool KernelOrKext,
325 const ObjCRuntime &objcRuntime,
326 ArgStringList &CmdArgs) {
327 const llvm::Triple &Triple = TC.getTriple();
329 if (KernelOrKext) {
330 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
331 // arguments now to avoid warnings about unused arguments.
332 Args.ClaimAllArgs(options::OPT_fexceptions);
333 Args.ClaimAllArgs(options::OPT_fno_exceptions);
334 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
335 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
336 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
337 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
338 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
339 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
340 return false;
343 // See if the user explicitly enabled exceptions.
344 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
345 false);
347 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
348 options::OPT_fno_async_exceptions, false);
349 if (EHa) {
350 CmdArgs.push_back("-fasync-exceptions");
351 EH = true;
354 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
355 // is not necessarily sensible, but follows GCC.
356 if (types::isObjC(InputType) &&
357 Args.hasFlag(options::OPT_fobjc_exceptions,
358 options::OPT_fno_objc_exceptions, true)) {
359 CmdArgs.push_back("-fobjc-exceptions");
361 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
364 if (types::isCXX(InputType)) {
365 // Disable C++ EH by default on XCore and PS4/PS5.
366 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
367 !Triple.isPS() && !Triple.isDriverKit();
368 Arg *ExceptionArg = Args.getLastArg(
369 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
370 options::OPT_fexceptions, options::OPT_fno_exceptions);
371 if (ExceptionArg)
372 CXXExceptionsEnabled =
373 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
374 ExceptionArg->getOption().matches(options::OPT_fexceptions);
376 if (CXXExceptionsEnabled) {
377 CmdArgs.push_back("-fcxx-exceptions");
379 EH = true;
383 // OPT_fignore_exceptions means exception could still be thrown,
384 // but no clean up or catch would happen in current module.
385 // So we do not set EH to false.
386 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
388 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
389 options::OPT_fno_assume_nothrow_exception_dtor);
391 if (EH)
392 CmdArgs.push_back("-fexceptions");
393 return EH;
396 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
397 const JobAction &JA) {
398 bool Default = true;
399 if (TC.getTriple().isOSDarwin()) {
400 // The native darwin assembler doesn't support the linker_option directives,
401 // so we disable them if we think the .s file will be passed to it.
402 Default = TC.useIntegratedAs();
404 // The linker_option directives are intended for host compilation.
405 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
406 JA.isDeviceOffloading(Action::OFK_HIP))
407 Default = false;
408 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
409 Default);
412 /// Add a CC1 option to specify the debug compilation directory.
413 static const char *addDebugCompDirArg(const ArgList &Args,
414 ArgStringList &CmdArgs,
415 const llvm::vfs::FileSystem &VFS) {
416 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
417 options::OPT_fdebug_compilation_dir_EQ)) {
418 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
419 CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
420 A->getValue()));
421 else
422 A->render(Args, CmdArgs);
423 } else if (llvm::ErrorOr<std::string> CWD =
424 VFS.getCurrentWorkingDirectory()) {
425 CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
427 StringRef Path(CmdArgs.back());
428 return Path.substr(Path.find('=') + 1).data();
431 static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
432 const char *DebugCompilationDir,
433 const char *OutputFileName) {
434 // No need to generate a value for -object-file-name if it was provided.
435 for (auto *Arg : Args.filtered(options::OPT_Xclang))
436 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
437 return;
439 if (Args.hasArg(options::OPT_object_file_name_EQ))
440 return;
442 SmallString<128> ObjFileNameForDebug(OutputFileName);
443 if (ObjFileNameForDebug != "-" &&
444 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
445 (!DebugCompilationDir ||
446 llvm::sys::path::is_absolute(DebugCompilationDir))) {
447 // Make the path absolute in the debug infos like MSVC does.
448 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
450 // If the object file name is a relative path, then always use Windows
451 // backslash style as -object-file-name is used for embedding object file path
452 // in codeview and it can only be generated when targeting on Windows.
453 // Otherwise, just use native absolute path.
454 llvm::sys::path::Style Style =
455 llvm::sys::path::is_absolute(ObjFileNameForDebug)
456 ? llvm::sys::path::Style::native
457 : llvm::sys::path::Style::windows_backslash;
458 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
459 Style);
460 CmdArgs.push_back(
461 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
464 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
465 static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
466 const ArgList &Args, ArgStringList &CmdArgs) {
467 auto AddOneArg = [&](StringRef Map, StringRef Name) {
468 if (!Map.contains('='))
469 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
470 else
471 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
474 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
475 options::OPT_fdebug_prefix_map_EQ)) {
476 AddOneArg(A->getValue(), A->getOption().getName());
477 A->claim();
479 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
480 if (GlobalRemapEntry.empty())
481 return;
482 AddOneArg(GlobalRemapEntry, "environment");
485 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
486 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
487 ArgStringList &CmdArgs) {
488 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
489 options::OPT_fmacro_prefix_map_EQ)) {
490 StringRef Map = A->getValue();
491 if (!Map.contains('='))
492 D.Diag(diag::err_drv_invalid_argument_to_option)
493 << Map << A->getOption().getName();
494 else
495 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
496 A->claim();
500 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
501 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
502 ArgStringList &CmdArgs) {
503 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
504 options::OPT_fcoverage_prefix_map_EQ)) {
505 StringRef Map = A->getValue();
506 if (!Map.contains('='))
507 D.Diag(diag::err_drv_invalid_argument_to_option)
508 << Map << A->getOption().getName();
509 else
510 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
511 A->claim();
515 /// Vectorize at all optimization levels greater than 1 except for -Oz.
516 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
517 /// enabled.
518 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
519 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
520 if (A->getOption().matches(options::OPT_O4) ||
521 A->getOption().matches(options::OPT_Ofast))
522 return true;
524 if (A->getOption().matches(options::OPT_O0))
525 return false;
527 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
529 // Vectorize -Os.
530 StringRef S(A->getValue());
531 if (S == "s")
532 return true;
534 // Don't vectorize -Oz, unless it's the slp vectorizer.
535 if (S == "z")
536 return isSlpVec;
538 unsigned OptLevel = 0;
539 if (S.getAsInteger(10, OptLevel))
540 return false;
542 return OptLevel > 1;
545 return false;
548 /// Add -x lang to \p CmdArgs for \p Input.
549 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
550 ArgStringList &CmdArgs) {
551 // When using -verify-pch, we don't want to provide the type
552 // 'precompiled-header' if it was inferred from the file extension
553 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
554 return;
556 CmdArgs.push_back("-x");
557 if (Args.hasArg(options::OPT_rewrite_objc))
558 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
559 else {
560 // Map the driver type to the frontend type. This is mostly an identity
561 // mapping, except that the distinction between module interface units
562 // and other source files does not exist at the frontend layer.
563 const char *ClangType;
564 switch (Input.getType()) {
565 case types::TY_CXXModule:
566 ClangType = "c++";
567 break;
568 case types::TY_PP_CXXModule:
569 ClangType = "c++-cpp-output";
570 break;
571 default:
572 ClangType = types::getTypeName(Input.getType());
573 break;
575 CmdArgs.push_back(ClangType);
579 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
580 const JobAction &JA, const InputInfo &Output,
581 const ArgList &Args, SanitizerArgs &SanArgs,
582 ArgStringList &CmdArgs) {
583 const Driver &D = TC.getDriver();
584 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
585 options::OPT_fprofile_generate_EQ,
586 options::OPT_fno_profile_generate);
587 if (PGOGenerateArg &&
588 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
589 PGOGenerateArg = nullptr;
591 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
593 auto *ProfileGenerateArg = Args.getLastArg(
594 options::OPT_fprofile_instr_generate,
595 options::OPT_fprofile_instr_generate_EQ,
596 options::OPT_fno_profile_instr_generate);
597 if (ProfileGenerateArg &&
598 ProfileGenerateArg->getOption().matches(
599 options::OPT_fno_profile_instr_generate))
600 ProfileGenerateArg = nullptr;
602 if (PGOGenerateArg && ProfileGenerateArg)
603 D.Diag(diag::err_drv_argument_not_allowed_with)
604 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
606 auto *ProfileUseArg = getLastProfileUseArg(Args);
608 if (PGOGenerateArg && ProfileUseArg)
609 D.Diag(diag::err_drv_argument_not_allowed_with)
610 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
612 if (ProfileGenerateArg && ProfileUseArg)
613 D.Diag(diag::err_drv_argument_not_allowed_with)
614 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
616 if (CSPGOGenerateArg && PGOGenerateArg) {
617 D.Diag(diag::err_drv_argument_not_allowed_with)
618 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
619 PGOGenerateArg = nullptr;
622 if (TC.getTriple().isOSAIX()) {
623 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
624 D.Diag(diag::err_drv_unsupported_opt_for_target)
625 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
628 if (ProfileGenerateArg) {
629 if (ProfileGenerateArg->getOption().matches(
630 options::OPT_fprofile_instr_generate_EQ))
631 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
632 ProfileGenerateArg->getValue()));
633 // The default is to use Clang Instrumentation.
634 CmdArgs.push_back("-fprofile-instrument=clang");
635 if (TC.getTriple().isWindowsMSVCEnvironment()) {
636 // Add dependent lib for clang_rt.profile
637 CmdArgs.push_back(Args.MakeArgString(
638 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
642 Arg *PGOGenArg = nullptr;
643 if (PGOGenerateArg) {
644 assert(!CSPGOGenerateArg);
645 PGOGenArg = PGOGenerateArg;
646 CmdArgs.push_back("-fprofile-instrument=llvm");
648 if (CSPGOGenerateArg) {
649 assert(!PGOGenerateArg);
650 PGOGenArg = CSPGOGenerateArg;
651 CmdArgs.push_back("-fprofile-instrument=csllvm");
653 if (PGOGenArg) {
654 if (TC.getTriple().isWindowsMSVCEnvironment()) {
655 // Add dependent lib for clang_rt.profile
656 CmdArgs.push_back(Args.MakeArgString(
657 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
659 if (PGOGenArg->getOption().matches(
660 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
661 : options::OPT_fcs_profile_generate_EQ)) {
662 SmallString<128> Path(PGOGenArg->getValue());
663 llvm::sys::path::append(Path, "default_%m.profraw");
664 CmdArgs.push_back(
665 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
669 if (ProfileUseArg) {
670 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
671 CmdArgs.push_back(Args.MakeArgString(
672 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
673 else if ((ProfileUseArg->getOption().matches(
674 options::OPT_fprofile_use_EQ) ||
675 ProfileUseArg->getOption().matches(
676 options::OPT_fprofile_instr_use))) {
677 SmallString<128> Path(
678 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
679 if (Path.empty() || llvm::sys::fs::is_directory(Path))
680 llvm::sys::path::append(Path, "default.profdata");
681 CmdArgs.push_back(
682 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
686 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
687 options::OPT_fno_test_coverage, false) ||
688 Args.hasArg(options::OPT_coverage);
689 bool EmitCovData = TC.needsGCovInstrumentation(Args);
691 if (Args.hasFlag(options::OPT_fcoverage_mapping,
692 options::OPT_fno_coverage_mapping, false)) {
693 if (!ProfileGenerateArg)
694 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
695 << "-fcoverage-mapping"
696 << "-fprofile-instr-generate";
698 CmdArgs.push_back("-fcoverage-mapping");
701 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
702 options::OPT_fcoverage_compilation_dir_EQ)) {
703 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
704 CmdArgs.push_back(Args.MakeArgString(
705 Twine("-fcoverage-compilation-dir=") + A->getValue()));
706 else
707 A->render(Args, CmdArgs);
708 } else if (llvm::ErrorOr<std::string> CWD =
709 D.getVFS().getCurrentWorkingDirectory()) {
710 CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
713 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
714 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
715 if (!Args.hasArg(options::OPT_coverage))
716 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
717 << "-fprofile-exclude-files="
718 << "--coverage";
720 StringRef v = Arg->getValue();
721 CmdArgs.push_back(
722 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
725 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
726 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
727 if (!Args.hasArg(options::OPT_coverage))
728 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
729 << "-fprofile-filter-files="
730 << "--coverage";
732 StringRef v = Arg->getValue();
733 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
736 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
737 StringRef Val = A->getValue();
738 if (Val == "atomic" || Val == "prefer-atomic")
739 CmdArgs.push_back("-fprofile-update=atomic");
740 else if (Val != "single")
741 D.Diag(diag::err_drv_unsupported_option_argument)
742 << A->getSpelling() << Val;
745 int FunctionGroups = 1;
746 int SelectedFunctionGroup = 0;
747 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
748 StringRef Val = A->getValue();
749 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
750 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
752 if (const auto *A =
753 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
754 StringRef Val = A->getValue();
755 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
756 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
757 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
759 if (FunctionGroups != 1)
760 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
761 Twine(FunctionGroups)));
762 if (SelectedFunctionGroup != 0)
763 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
764 Twine(SelectedFunctionGroup)));
766 // Leave -fprofile-dir= an unused argument unless .gcda emission is
767 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
768 // the flag used. There is no -fno-profile-dir, so the user has no
769 // targeted way to suppress the warning.
770 Arg *FProfileDir = nullptr;
771 if (Args.hasArg(options::OPT_fprofile_arcs) ||
772 Args.hasArg(options::OPT_coverage))
773 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
775 // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
776 // like we warn about -fsyntax-only -E.
777 (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
779 // Put the .gcno and .gcda files (if needed) next to the primary output file,
780 // or fall back to a file in the current directory for `clang -c --coverage
781 // d/a.c` in the absence of -o.
782 if (EmitCovNotes || EmitCovData) {
783 SmallString<128> CoverageFilename;
784 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
785 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
786 // path separator.
787 CoverageFilename = DumpDir->getValue();
788 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
789 } else if (Arg *FinalOutput =
790 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
791 CoverageFilename = FinalOutput->getValue();
792 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
793 CoverageFilename = FinalOutput->getValue();
794 } else {
795 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
797 if (llvm::sys::path::is_relative(CoverageFilename))
798 (void)D.getVFS().makeAbsolute(CoverageFilename);
799 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
800 if (EmitCovNotes) {
801 CmdArgs.push_back(
802 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
805 if (EmitCovData) {
806 if (FProfileDir) {
807 SmallString<128> Gcno = std::move(CoverageFilename);
808 CoverageFilename = FProfileDir->getValue();
809 llvm::sys::path::append(CoverageFilename, Gcno);
811 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
812 CmdArgs.push_back(
813 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
818 /// Check whether the given input tree contains any compilation actions.
819 static bool ContainsCompileAction(const Action *A) {
820 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
821 return true;
823 return llvm::any_of(A->inputs(), ContainsCompileAction);
826 /// Check if -relax-all should be passed to the internal assembler.
827 /// This is done by default when compiling non-assembler source with -O0.
828 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
829 bool RelaxDefault = true;
831 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
832 RelaxDefault = A->getOption().matches(options::OPT_O0);
834 if (RelaxDefault) {
835 RelaxDefault = false;
836 for (const auto &Act : C.getActions()) {
837 if (ContainsCompileAction(Act)) {
838 RelaxDefault = true;
839 break;
844 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
845 RelaxDefault);
848 static void
849 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
850 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
851 unsigned DwarfVersion,
852 llvm::DebuggerKind DebuggerTuning) {
853 addDebugInfoKind(CmdArgs, DebugInfoKind);
854 if (DwarfVersion > 0)
855 CmdArgs.push_back(
856 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
857 switch (DebuggerTuning) {
858 case llvm::DebuggerKind::GDB:
859 CmdArgs.push_back("-debugger-tuning=gdb");
860 break;
861 case llvm::DebuggerKind::LLDB:
862 CmdArgs.push_back("-debugger-tuning=lldb");
863 break;
864 case llvm::DebuggerKind::SCE:
865 CmdArgs.push_back("-debugger-tuning=sce");
866 break;
867 case llvm::DebuggerKind::DBX:
868 CmdArgs.push_back("-debugger-tuning=dbx");
869 break;
870 default:
871 break;
875 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
876 const Driver &D, const ToolChain &TC) {
877 assert(A && "Expected non-nullptr argument.");
878 if (TC.supportsDebugInfoOption(A))
879 return true;
880 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
881 << A->getAsString(Args) << TC.getTripleString();
882 return false;
885 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
886 ArgStringList &CmdArgs,
887 const Driver &D,
888 const ToolChain &TC) {
889 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
890 if (!A)
891 return;
892 if (checkDebugInfoOption(A, Args, D, TC)) {
893 StringRef Value = A->getValue();
894 if (Value == "none") {
895 CmdArgs.push_back("--compress-debug-sections=none");
896 } else if (Value == "zlib") {
897 if (llvm::compression::zlib::isAvailable()) {
898 CmdArgs.push_back(
899 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
900 } else {
901 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
903 } else if (Value == "zstd") {
904 if (llvm::compression::zstd::isAvailable()) {
905 CmdArgs.push_back(
906 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
907 } else {
908 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
910 } else {
911 D.Diag(diag::err_drv_unsupported_option_argument)
912 << A->getSpelling() << Value;
917 static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
918 const ArgList &Args,
919 ArgStringList &CmdArgs,
920 bool IsCC1As = false) {
921 // If no version was requested by the user, use the default value from the
922 // back end. This is consistent with the value returned from
923 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
924 // requiring the corresponding llvm to have the AMDGPU target enabled,
925 // provided the user (e.g. front end tests) can use the default.
926 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
927 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
928 CmdArgs.insert(CmdArgs.begin() + 1,
929 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
930 Twine(CodeObjVer)));
931 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
932 // -cc1as does not accept -mcode-object-version option.
933 if (!IsCC1As)
934 CmdArgs.insert(CmdArgs.begin() + 1,
935 Args.MakeArgString(Twine("-mcode-object-version=") +
936 Twine(CodeObjVer)));
940 static bool hasClangPchSignature(const Driver &D, StringRef Path) {
941 if (llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
942 D.getVFS().getBufferForFile(Path))
943 return (*MemBuf)->getBuffer().starts_with("CPCH");
944 return false;
947 static bool gchProbe(const Driver &D, StringRef Path) {
948 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
949 if (!Status)
950 return false;
952 if (Status->isDirectory()) {
953 std::error_code EC;
954 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
955 !EC && DI != DE; DI = DI.increment(EC)) {
956 if (hasClangPchSignature(D, DI->path()))
957 return true;
959 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
960 return false;
963 if (hasClangPchSignature(D, Path))
964 return true;
965 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
966 return false;
969 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
970 const Driver &D, const ArgList &Args,
971 ArgStringList &CmdArgs,
972 const InputInfo &Output,
973 const InputInfoList &Inputs) const {
974 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
976 CheckPreprocessingOptions(D, Args);
978 Args.AddLastArg(CmdArgs, options::OPT_C);
979 Args.AddLastArg(CmdArgs, options::OPT_CC);
981 // Handle dependency file generation.
982 Arg *ArgM = Args.getLastArg(options::OPT_MM);
983 if (!ArgM)
984 ArgM = Args.getLastArg(options::OPT_M);
985 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
986 if (!ArgMD)
987 ArgMD = Args.getLastArg(options::OPT_MD);
989 // -M and -MM imply -w.
990 if (ArgM)
991 CmdArgs.push_back("-w");
992 else
993 ArgM = ArgMD;
995 if (ArgM) {
996 // Determine the output location.
997 const char *DepFile;
998 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
999 DepFile = MF->getValue();
1000 C.addFailureResultFile(DepFile, &JA);
1001 } else if (Output.getType() == types::TY_Dependencies) {
1002 DepFile = Output.getFilename();
1003 } else if (!ArgMD) {
1004 DepFile = "-";
1005 } else {
1006 DepFile = getDependencyFileName(Args, Inputs);
1007 C.addFailureResultFile(DepFile, &JA);
1009 CmdArgs.push_back("-dependency-file");
1010 CmdArgs.push_back(DepFile);
1012 bool HasTarget = false;
1013 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1014 HasTarget = true;
1015 A->claim();
1016 if (A->getOption().matches(options::OPT_MT)) {
1017 A->render(Args, CmdArgs);
1018 } else {
1019 CmdArgs.push_back("-MT");
1020 SmallString<128> Quoted;
1021 quoteMakeTarget(A->getValue(), Quoted);
1022 CmdArgs.push_back(Args.MakeArgString(Quoted));
1026 // Add a default target if one wasn't specified.
1027 if (!HasTarget) {
1028 const char *DepTarget;
1030 // If user provided -o, that is the dependency target, except
1031 // when we are only generating a dependency file.
1032 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1033 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1034 DepTarget = OutputOpt->getValue();
1035 } else {
1036 // Otherwise derive from the base input.
1038 // FIXME: This should use the computed output file location.
1039 SmallString<128> P(Inputs[0].getBaseInput());
1040 llvm::sys::path::replace_extension(P, "o");
1041 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1044 CmdArgs.push_back("-MT");
1045 SmallString<128> Quoted;
1046 quoteMakeTarget(DepTarget, Quoted);
1047 CmdArgs.push_back(Args.MakeArgString(Quoted));
1050 if (ArgM->getOption().matches(options::OPT_M) ||
1051 ArgM->getOption().matches(options::OPT_MD))
1052 CmdArgs.push_back("-sys-header-deps");
1053 if ((isa<PrecompileJobAction>(JA) &&
1054 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1055 Args.hasArg(options::OPT_fmodule_file_deps))
1056 CmdArgs.push_back("-module-file-deps");
1059 if (Args.hasArg(options::OPT_MG)) {
1060 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1061 ArgM->getOption().matches(options::OPT_MMD))
1062 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1063 CmdArgs.push_back("-MG");
1066 Args.AddLastArg(CmdArgs, options::OPT_MP);
1067 Args.AddLastArg(CmdArgs, options::OPT_MV);
1069 // Add offload include arguments specific for CUDA/HIP. This must happen
1070 // before we -I or -include anything else, because we must pick up the
1071 // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1072 // from e.g. /usr/local/include.
1073 if (JA.isOffloading(Action::OFK_Cuda))
1074 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1075 if (JA.isOffloading(Action::OFK_HIP))
1076 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1078 // If we are compiling for a GPU target we want to override the system headers
1079 // with ones created by the 'libc' project if present.
1080 if (!Args.hasArg(options::OPT_nostdinc) &&
1081 !Args.hasArg(options::OPT_nogpuinc) &&
1082 !Args.hasArg(options::OPT_nobuiltininc)) {
1083 // Without an offloading language we will include these headers directly.
1084 // Offloading languages will instead only use the declarations stored in
1085 // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1086 if ((getToolChain().getTriple().isNVPTX() ||
1087 getToolChain().getTriple().isAMDGCN()) &&
1088 C.getActiveOffloadKinds() == Action::OFK_None) {
1089 SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
1090 llvm::sys::path::append(P, "include");
1091 llvm::sys::path::append(P, "gpu-none-llvm");
1092 CmdArgs.push_back("-c-isystem");
1093 CmdArgs.push_back(Args.MakeArgString(P));
1094 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1095 // TODO: CUDA / HIP include their own headers for some common functions
1096 // implemented here. We'll need to clean those up so they do not conflict.
1097 SmallString<128> P(D.ResourceDir);
1098 llvm::sys::path::append(P, "include");
1099 llvm::sys::path::append(P, "llvm_libc_wrappers");
1100 CmdArgs.push_back("-internal-isystem");
1101 CmdArgs.push_back(Args.MakeArgString(P));
1105 // If we are offloading to a target via OpenMP we need to include the
1106 // openmp_wrappers folder which contains alternative system headers.
1107 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1108 !Args.hasArg(options::OPT_nostdinc) &&
1109 !Args.hasArg(options::OPT_nogpuinc) &&
1110 (getToolChain().getTriple().isNVPTX() ||
1111 getToolChain().getTriple().isAMDGCN())) {
1112 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1113 // Add openmp_wrappers/* to our system include path. This lets us wrap
1114 // standard library headers.
1115 SmallString<128> P(D.ResourceDir);
1116 llvm::sys::path::append(P, "include");
1117 llvm::sys::path::append(P, "openmp_wrappers");
1118 CmdArgs.push_back("-internal-isystem");
1119 CmdArgs.push_back(Args.MakeArgString(P));
1122 CmdArgs.push_back("-include");
1123 CmdArgs.push_back("__clang_openmp_device_functions.h");
1126 // Add -i* options, and automatically translate to
1127 // -include-pch/-include-pth for transparent PCH support. It's
1128 // wonky, but we include looking for .gch so we can support seamless
1129 // replacement into a build system already set up to be generating
1130 // .gch files.
1132 if (getToolChain().getDriver().IsCLMode()) {
1133 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1134 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1135 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1136 JA.getKind() <= Action::AssembleJobClass) {
1137 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1138 // -fpch-instantiate-templates is the default when creating
1139 // precomp using /Yc
1140 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1141 options::OPT_fno_pch_instantiate_templates, true))
1142 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1144 if (YcArg || YuArg) {
1145 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1146 if (!isa<PrecompileJobAction>(JA)) {
1147 CmdArgs.push_back("-include-pch");
1148 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1149 C, !ThroughHeader.empty()
1150 ? ThroughHeader
1151 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1154 if (ThroughHeader.empty()) {
1155 CmdArgs.push_back(Args.MakeArgString(
1156 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1157 } else {
1158 CmdArgs.push_back(
1159 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1164 bool RenderedImplicitInclude = false;
1165 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1166 if (A->getOption().matches(options::OPT_include) &&
1167 D.getProbePrecompiled()) {
1168 // Handling of gcc-style gch precompiled headers.
1169 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1170 RenderedImplicitInclude = true;
1172 bool FoundPCH = false;
1173 SmallString<128> P(A->getValue());
1174 // We want the files to have a name like foo.h.pch. Add a dummy extension
1175 // so that replace_extension does the right thing.
1176 P += ".dummy";
1177 llvm::sys::path::replace_extension(P, "pch");
1178 if (D.getVFS().exists(P))
1179 FoundPCH = true;
1181 if (!FoundPCH) {
1182 // For GCC compat, probe for a file or directory ending in .gch instead.
1183 llvm::sys::path::replace_extension(P, "gch");
1184 FoundPCH = gchProbe(D, P.str());
1187 if (FoundPCH) {
1188 if (IsFirstImplicitInclude) {
1189 A->claim();
1190 CmdArgs.push_back("-include-pch");
1191 CmdArgs.push_back(Args.MakeArgString(P));
1192 continue;
1193 } else {
1194 // Ignore the PCH if not first on command line and emit warning.
1195 D.Diag(diag::warn_drv_pch_not_first_include) << P
1196 << A->getAsString(Args);
1199 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1200 // Handling of paths which must come late. These entries are handled by
1201 // the toolchain itself after the resource dir is inserted in the right
1202 // search order.
1203 // Do not claim the argument so that the use of the argument does not
1204 // silently go unnoticed on toolchains which do not honour the option.
1205 continue;
1206 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1207 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1208 continue;
1209 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1210 // This is used only by the driver. No need to pass to cc1.
1211 continue;
1214 // Not translated, render as usual.
1215 A->claim();
1216 A->render(Args, CmdArgs);
1219 Args.addAllArgs(CmdArgs,
1220 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1221 options::OPT_F, options::OPT_index_header_map});
1223 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1225 // FIXME: There is a very unfortunate problem here, some troubled
1226 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1227 // really support that we would have to parse and then translate
1228 // those options. :(
1229 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1230 options::OPT_Xpreprocessor);
1232 // -I- is a deprecated GCC feature, reject it.
1233 if (Arg *A = Args.getLastArg(options::OPT_I_))
1234 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1236 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1237 // -isysroot to the CC1 invocation.
1238 StringRef sysroot = C.getSysRoot();
1239 if (sysroot != "") {
1240 if (!Args.hasArg(options::OPT_isysroot)) {
1241 CmdArgs.push_back("-isysroot");
1242 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1246 // Parse additional include paths from environment variables.
1247 // FIXME: We should probably sink the logic for handling these from the
1248 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1249 // CPATH - included following the user specified includes (but prior to
1250 // builtin and standard includes).
1251 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1252 // C_INCLUDE_PATH - system includes enabled when compiling C.
1253 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1254 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1255 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1256 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1257 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1258 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1259 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1261 // While adding the include arguments, we also attempt to retrieve the
1262 // arguments of related offloading toolchains or arguments that are specific
1263 // of an offloading programming model.
1265 // Add C++ include arguments, if needed.
1266 if (types::isCXX(Inputs[0].getType())) {
1267 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1268 forAllAssociatedToolChains(
1269 C, JA, getToolChain(),
1270 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1271 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1272 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1276 // Add system include arguments for all targets but IAMCU.
1277 if (!IsIAMCU)
1278 forAllAssociatedToolChains(C, JA, getToolChain(),
1279 [&Args, &CmdArgs](const ToolChain &TC) {
1280 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1282 else {
1283 // For IAMCU add special include arguments.
1284 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1287 addMacroPrefixMapArg(D, Args, CmdArgs);
1288 addCoveragePrefixMapArg(D, Args, CmdArgs);
1290 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1291 options::OPT_fno_file_reproducible);
1293 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1294 CmdArgs.push_back("-source-date-epoch");
1295 CmdArgs.push_back(Args.MakeArgString(Epoch));
1298 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1299 options::OPT_fno_define_target_os_macros);
1302 // FIXME: Move to target hook.
1303 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1304 switch (Triple.getArch()) {
1305 default:
1306 return true;
1308 case llvm::Triple::aarch64:
1309 case llvm::Triple::aarch64_32:
1310 case llvm::Triple::aarch64_be:
1311 case llvm::Triple::arm:
1312 case llvm::Triple::armeb:
1313 case llvm::Triple::thumb:
1314 case llvm::Triple::thumbeb:
1315 if (Triple.isOSDarwin() || Triple.isOSWindows())
1316 return true;
1317 return false;
1319 case llvm::Triple::ppc:
1320 case llvm::Triple::ppc64:
1321 if (Triple.isOSDarwin())
1322 return true;
1323 return false;
1325 case llvm::Triple::hexagon:
1326 case llvm::Triple::ppcle:
1327 case llvm::Triple::ppc64le:
1328 case llvm::Triple::riscv32:
1329 case llvm::Triple::riscv64:
1330 case llvm::Triple::systemz:
1331 case llvm::Triple::xcore:
1332 return false;
1336 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1337 const ArgList &Args) {
1338 // Supported only on Darwin where we invoke the compiler multiple times
1339 // followed by an invocation to lipo.
1340 if (!Triple.isOSDarwin())
1341 return false;
1342 // If more than one "-arch <arch>" is specified, we're targeting multiple
1343 // architectures resulting in a fat binary.
1344 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1347 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1348 const llvm::Triple &Triple) {
1349 // When enabling remarks, we need to error if:
1350 // * The remark file is specified but we're targeting multiple architectures,
1351 // which means more than one remark file is being generated.
1352 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1353 bool hasExplicitOutputFile =
1354 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1355 if (hasMultipleInvocations && hasExplicitOutputFile) {
1356 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1357 << "-foptimization-record-file";
1358 return false;
1360 return true;
1363 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1364 const llvm::Triple &Triple,
1365 const InputInfo &Input,
1366 const InputInfo &Output, const JobAction &JA) {
1367 StringRef Format = "yaml";
1368 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1369 Format = A->getValue();
1371 CmdArgs.push_back("-opt-record-file");
1373 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1374 if (A) {
1375 CmdArgs.push_back(A->getValue());
1376 } else {
1377 bool hasMultipleArchs =
1378 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1379 Args.getAllArgValues(options::OPT_arch).size() > 1;
1381 SmallString<128> F;
1383 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1384 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1385 F = FinalOutput->getValue();
1386 } else {
1387 if (Format != "yaml" && // For YAML, keep the original behavior.
1388 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1389 Output.isFilename())
1390 F = Output.getFilename();
1393 if (F.empty()) {
1394 // Use the input filename.
1395 F = llvm::sys::path::stem(Input.getBaseInput());
1397 // If we're compiling for an offload architecture (i.e. a CUDA device),
1398 // we need to make the file name for the device compilation different
1399 // from the host compilation.
1400 if (!JA.isDeviceOffloading(Action::OFK_None) &&
1401 !JA.isDeviceOffloading(Action::OFK_Host)) {
1402 llvm::sys::path::replace_extension(F, "");
1403 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1404 Triple.normalize());
1405 F += "-";
1406 F += JA.getOffloadingArch();
1410 // If we're having more than one "-arch", we should name the files
1411 // differently so that every cc1 invocation writes to a different file.
1412 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1413 // name from the triple.
1414 if (hasMultipleArchs) {
1415 // First, remember the extension.
1416 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1417 // then, remove it.
1418 llvm::sys::path::replace_extension(F, "");
1419 // attach -<arch> to it.
1420 F += "-";
1421 F += Triple.getArchName();
1422 // put back the extension.
1423 llvm::sys::path::replace_extension(F, OldExtension);
1426 SmallString<32> Extension;
1427 Extension += "opt.";
1428 Extension += Format;
1430 llvm::sys::path::replace_extension(F, Extension);
1431 CmdArgs.push_back(Args.MakeArgString(F));
1434 if (const Arg *A =
1435 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1436 CmdArgs.push_back("-opt-record-passes");
1437 CmdArgs.push_back(A->getValue());
1440 if (!Format.empty()) {
1441 CmdArgs.push_back("-opt-record-format");
1442 CmdArgs.push_back(Format.data());
1446 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1447 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1448 options::OPT_fno_aapcs_bitfield_width, true))
1449 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1451 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1452 CmdArgs.push_back("-faapcs-bitfield-load");
1455 namespace {
1456 void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1457 const ArgList &Args, ArgStringList &CmdArgs) {
1458 // Select the ABI to use.
1459 // FIXME: Support -meabi.
1460 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1461 const char *ABIName = nullptr;
1462 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1463 ABIName = A->getValue();
1464 } else {
1465 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1466 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1469 CmdArgs.push_back("-target-abi");
1470 CmdArgs.push_back(ABIName);
1473 void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1474 auto StrictAlignIter =
1475 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1476 return Arg == "+strict-align" || Arg == "-strict-align";
1478 if (StrictAlignIter != CmdArgs.rend() &&
1479 StringRef(*StrictAlignIter) == "+strict-align")
1480 CmdArgs.push_back("-Wunaligned-access");
1484 static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1485 ArgStringList &CmdArgs, bool isAArch64) {
1486 const Arg *A = isAArch64
1487 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1488 options::OPT_mbranch_protection_EQ)
1489 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1490 if (!A)
1491 return;
1493 const Driver &D = TC.getDriver();
1494 const llvm::Triple &Triple = TC.getEffectiveTriple();
1495 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1496 D.Diag(diag::warn_incompatible_branch_protection_option)
1497 << Triple.getArchName();
1499 StringRef Scope, Key;
1500 bool IndirectBranches, BranchProtectionPAuthLR;
1502 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1503 Scope = A->getValue();
1504 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1505 D.Diag(diag::err_drv_unsupported_option_argument)
1506 << A->getSpelling() << Scope;
1507 Key = "a_key";
1508 IndirectBranches = false;
1509 BranchProtectionPAuthLR = false;
1510 } else {
1511 StringRef DiagMsg;
1512 llvm::ARM::ParsedBranchProtection PBP;
1513 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
1514 D.Diag(diag::err_drv_unsupported_option_argument)
1515 << A->getSpelling() << DiagMsg;
1516 if (!isAArch64 && PBP.Key == "b_key")
1517 D.Diag(diag::warn_unsupported_branch_protection)
1518 << "b-key" << A->getAsString(Args);
1519 Scope = PBP.Scope;
1520 Key = PBP.Key;
1521 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1522 IndirectBranches = PBP.BranchTargetEnforcement;
1525 CmdArgs.push_back(
1526 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1527 if (!Scope.equals("none"))
1528 CmdArgs.push_back(
1529 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1530 if (BranchProtectionPAuthLR)
1531 CmdArgs.push_back(
1532 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1533 if (IndirectBranches)
1534 CmdArgs.push_back("-mbranch-target-enforce");
1537 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1538 ArgStringList &CmdArgs, bool KernelOrKext) const {
1539 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1541 // Determine floating point ABI from the options & target defaults.
1542 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1543 if (ABI == arm::FloatABI::Soft) {
1544 // Floating point operations and argument passing are soft.
1545 // FIXME: This changes CPP defines, we need -target-soft-float.
1546 CmdArgs.push_back("-msoft-float");
1547 CmdArgs.push_back("-mfloat-abi");
1548 CmdArgs.push_back("soft");
1549 } else if (ABI == arm::FloatABI::SoftFP) {
1550 // Floating point operations are hard, but argument passing is soft.
1551 CmdArgs.push_back("-mfloat-abi");
1552 CmdArgs.push_back("soft");
1553 } else {
1554 // Floating point operations and argument passing are hard.
1555 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1556 CmdArgs.push_back("-mfloat-abi");
1557 CmdArgs.push_back("hard");
1560 // Forward the -mglobal-merge option for explicit control over the pass.
1561 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1562 options::OPT_mno_global_merge)) {
1563 CmdArgs.push_back("-mllvm");
1564 if (A->getOption().matches(options::OPT_mno_global_merge))
1565 CmdArgs.push_back("-arm-global-merge=false");
1566 else
1567 CmdArgs.push_back("-arm-global-merge=true");
1570 if (!Args.hasFlag(options::OPT_mimplicit_float,
1571 options::OPT_mno_implicit_float, true))
1572 CmdArgs.push_back("-no-implicit-float");
1574 if (Args.getLastArg(options::OPT_mcmse))
1575 CmdArgs.push_back("-mcmse");
1577 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1579 // Enable/disable return address signing and indirect branch targets.
1580 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1582 AddUnalignedAccessWarning(CmdArgs);
1585 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1586 const ArgList &Args, bool KernelOrKext,
1587 ArgStringList &CmdArgs) const {
1588 const ToolChain &TC = getToolChain();
1590 // Add the target features
1591 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1593 // Add target specific flags.
1594 switch (TC.getArch()) {
1595 default:
1596 break;
1598 case llvm::Triple::arm:
1599 case llvm::Triple::armeb:
1600 case llvm::Triple::thumb:
1601 case llvm::Triple::thumbeb:
1602 // Use the effective triple, which takes into account the deployment target.
1603 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1604 break;
1606 case llvm::Triple::aarch64:
1607 case llvm::Triple::aarch64_32:
1608 case llvm::Triple::aarch64_be:
1609 AddAArch64TargetArgs(Args, CmdArgs);
1610 break;
1612 case llvm::Triple::loongarch32:
1613 case llvm::Triple::loongarch64:
1614 AddLoongArchTargetArgs(Args, CmdArgs);
1615 break;
1617 case llvm::Triple::mips:
1618 case llvm::Triple::mipsel:
1619 case llvm::Triple::mips64:
1620 case llvm::Triple::mips64el:
1621 AddMIPSTargetArgs(Args, CmdArgs);
1622 break;
1624 case llvm::Triple::ppc:
1625 case llvm::Triple::ppcle:
1626 case llvm::Triple::ppc64:
1627 case llvm::Triple::ppc64le:
1628 AddPPCTargetArgs(Args, CmdArgs);
1629 break;
1631 case llvm::Triple::riscv32:
1632 case llvm::Triple::riscv64:
1633 AddRISCVTargetArgs(Args, CmdArgs);
1634 break;
1636 case llvm::Triple::sparc:
1637 case llvm::Triple::sparcel:
1638 case llvm::Triple::sparcv9:
1639 AddSparcTargetArgs(Args, CmdArgs);
1640 break;
1642 case llvm::Triple::systemz:
1643 AddSystemZTargetArgs(Args, CmdArgs);
1644 break;
1646 case llvm::Triple::x86:
1647 case llvm::Triple::x86_64:
1648 AddX86TargetArgs(Args, CmdArgs);
1649 break;
1651 case llvm::Triple::lanai:
1652 AddLanaiTargetArgs(Args, CmdArgs);
1653 break;
1655 case llvm::Triple::hexagon:
1656 AddHexagonTargetArgs(Args, CmdArgs);
1657 break;
1659 case llvm::Triple::wasm32:
1660 case llvm::Triple::wasm64:
1661 AddWebAssemblyTargetArgs(Args, CmdArgs);
1662 break;
1664 case llvm::Triple::ve:
1665 AddVETargetArgs(Args, CmdArgs);
1666 break;
1670 namespace {
1671 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1672 ArgStringList &CmdArgs) {
1673 const char *ABIName = nullptr;
1674 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1675 ABIName = A->getValue();
1676 else if (Triple.isOSDarwin())
1677 ABIName = "darwinpcs";
1678 else
1679 ABIName = "aapcs";
1681 CmdArgs.push_back("-target-abi");
1682 CmdArgs.push_back(ABIName);
1686 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1687 ArgStringList &CmdArgs) const {
1688 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1690 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1691 Args.hasArg(options::OPT_mkernel) ||
1692 Args.hasArg(options::OPT_fapple_kext))
1693 CmdArgs.push_back("-disable-red-zone");
1695 if (!Args.hasFlag(options::OPT_mimplicit_float,
1696 options::OPT_mno_implicit_float, true))
1697 CmdArgs.push_back("-no-implicit-float");
1699 RenderAArch64ABI(Triple, Args, CmdArgs);
1701 // Forward the -mglobal-merge option for explicit control over the pass.
1702 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1703 options::OPT_mno_global_merge)) {
1704 CmdArgs.push_back("-mllvm");
1705 if (A->getOption().matches(options::OPT_mno_global_merge))
1706 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1707 else
1708 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1711 // Enable/disable return address signing and indirect branch targets.
1712 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1714 // Handle -msve_vector_bits=<bits>
1715 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1716 StringRef Val = A->getValue();
1717 const Driver &D = getToolChain().getDriver();
1718 if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1719 Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1720 Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1721 Val.equals("2048+")) {
1722 unsigned Bits = 0;
1723 if (Val.ends_with("+"))
1724 Val = Val.substr(0, Val.size() - 1);
1725 else {
1726 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1727 assert(!Invalid && "Failed to parse value");
1728 CmdArgs.push_back(
1729 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1732 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1733 assert(!Invalid && "Failed to parse value");
1734 CmdArgs.push_back(
1735 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1736 // Silently drop requests for vector-length agnostic code as it's implied.
1737 } else if (!Val.equals("scalable"))
1738 // Handle the unsupported values passed to msve-vector-bits.
1739 D.Diag(diag::err_drv_unsupported_option_argument)
1740 << A->getSpelling() << Val;
1743 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1745 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1746 CmdArgs.push_back("-tune-cpu");
1747 if (strcmp(A->getValue(), "native") == 0)
1748 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1749 else
1750 CmdArgs.push_back(A->getValue());
1753 AddUnalignedAccessWarning(CmdArgs);
1756 void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1757 ArgStringList &CmdArgs) const {
1758 const llvm::Triple &Triple = getToolChain().getTriple();
1760 CmdArgs.push_back("-target-abi");
1761 CmdArgs.push_back(
1762 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1763 .data());
1765 // Handle -mtune.
1766 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1767 std::string TuneCPU = A->getValue();
1768 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1769 CmdArgs.push_back("-tune-cpu");
1770 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1774 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1775 ArgStringList &CmdArgs) const {
1776 const Driver &D = getToolChain().getDriver();
1777 StringRef CPUName;
1778 StringRef ABIName;
1779 const llvm::Triple &Triple = getToolChain().getTriple();
1780 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1782 CmdArgs.push_back("-target-abi");
1783 CmdArgs.push_back(ABIName.data());
1785 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1786 if (ABI == mips::FloatABI::Soft) {
1787 // Floating point operations and argument passing are soft.
1788 CmdArgs.push_back("-msoft-float");
1789 CmdArgs.push_back("-mfloat-abi");
1790 CmdArgs.push_back("soft");
1791 } else {
1792 // Floating point operations and argument passing are hard.
1793 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1794 CmdArgs.push_back("-mfloat-abi");
1795 CmdArgs.push_back("hard");
1798 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1799 options::OPT_mno_ldc1_sdc1)) {
1800 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1801 CmdArgs.push_back("-mllvm");
1802 CmdArgs.push_back("-mno-ldc1-sdc1");
1806 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1807 options::OPT_mno_check_zero_division)) {
1808 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1809 CmdArgs.push_back("-mllvm");
1810 CmdArgs.push_back("-mno-check-zero-division");
1814 if (Args.getLastArg(options::OPT_mfix4300)) {
1815 CmdArgs.push_back("-mllvm");
1816 CmdArgs.push_back("-mfix4300");
1819 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1820 StringRef v = A->getValue();
1821 CmdArgs.push_back("-mllvm");
1822 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1823 A->claim();
1826 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1827 Arg *ABICalls =
1828 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1830 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1831 // -mgpopt is the default for static, -fno-pic environments but these two
1832 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1833 // the only case where -mllvm -mgpopt is passed.
1834 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1835 // passed explicitly when compiling something with -mabicalls
1836 // (implictly) in affect. Currently the warning is in the backend.
1838 // When the ABI in use is N64, we also need to determine the PIC mode that
1839 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1840 bool NoABICalls =
1841 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1843 llvm::Reloc::Model RelocationModel;
1844 unsigned PICLevel;
1845 bool IsPIE;
1846 std::tie(RelocationModel, PICLevel, IsPIE) =
1847 ParsePICArgs(getToolChain(), Args);
1849 NoABICalls = NoABICalls ||
1850 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1852 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1853 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1854 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1855 CmdArgs.push_back("-mllvm");
1856 CmdArgs.push_back("-mgpopt");
1858 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1859 options::OPT_mno_local_sdata);
1860 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1861 options::OPT_mno_extern_sdata);
1862 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1863 options::OPT_mno_embedded_data);
1864 if (LocalSData) {
1865 CmdArgs.push_back("-mllvm");
1866 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1867 CmdArgs.push_back("-mlocal-sdata=1");
1868 } else {
1869 CmdArgs.push_back("-mlocal-sdata=0");
1871 LocalSData->claim();
1874 if (ExternSData) {
1875 CmdArgs.push_back("-mllvm");
1876 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1877 CmdArgs.push_back("-mextern-sdata=1");
1878 } else {
1879 CmdArgs.push_back("-mextern-sdata=0");
1881 ExternSData->claim();
1884 if (EmbeddedData) {
1885 CmdArgs.push_back("-mllvm");
1886 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1887 CmdArgs.push_back("-membedded-data=1");
1888 } else {
1889 CmdArgs.push_back("-membedded-data=0");
1891 EmbeddedData->claim();
1894 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1895 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1897 if (GPOpt)
1898 GPOpt->claim();
1900 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1901 StringRef Val = StringRef(A->getValue());
1902 if (mips::hasCompactBranches(CPUName)) {
1903 if (Val == "never" || Val == "always" || Val == "optimal") {
1904 CmdArgs.push_back("-mllvm");
1905 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1906 } else
1907 D.Diag(diag::err_drv_unsupported_option_argument)
1908 << A->getSpelling() << Val;
1909 } else
1910 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1913 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1914 options::OPT_mno_relax_pic_calls)) {
1915 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1916 CmdArgs.push_back("-mllvm");
1917 CmdArgs.push_back("-mips-jalr-reloc=0");
1922 void Clang::AddPPCTargetArgs(const ArgList &Args,
1923 ArgStringList &CmdArgs) const {
1924 const Driver &D = getToolChain().getDriver();
1925 const llvm::Triple &T = getToolChain().getTriple();
1926 if (Args.getLastArg(options::OPT_mtune_EQ)) {
1927 CmdArgs.push_back("-tune-cpu");
1928 std::string CPU = ppc::getPPCTuneCPU(Args, T);
1929 CmdArgs.push_back(Args.MakeArgString(CPU));
1932 // Select the ABI to use.
1933 const char *ABIName = nullptr;
1934 if (T.isOSBinFormatELF()) {
1935 switch (getToolChain().getArch()) {
1936 case llvm::Triple::ppc64: {
1937 if (T.isPPC64ELFv2ABI())
1938 ABIName = "elfv2";
1939 else
1940 ABIName = "elfv1";
1941 break;
1943 case llvm::Triple::ppc64le:
1944 ABIName = "elfv2";
1945 break;
1946 default:
1947 break;
1951 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1952 bool VecExtabi = false;
1953 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1954 StringRef V = A->getValue();
1955 if (V == "ieeelongdouble") {
1956 IEEELongDouble = true;
1957 A->claim();
1958 } else if (V == "ibmlongdouble") {
1959 IEEELongDouble = false;
1960 A->claim();
1961 } else if (V == "vec-default") {
1962 VecExtabi = false;
1963 A->claim();
1964 } else if (V == "vec-extabi") {
1965 VecExtabi = true;
1966 A->claim();
1967 } else if (V == "elfv1") {
1968 ABIName = "elfv1";
1969 A->claim();
1970 } else if (V == "elfv2") {
1971 ABIName = "elfv2";
1972 A->claim();
1973 } else if (V != "altivec")
1974 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1975 // the option if given as we don't have backend support for any targets
1976 // that don't use the altivec abi.
1977 ABIName = A->getValue();
1979 if (IEEELongDouble)
1980 CmdArgs.push_back("-mabi=ieeelongdouble");
1981 if (VecExtabi) {
1982 if (!T.isOSAIX())
1983 D.Diag(diag::err_drv_unsupported_opt_for_target)
1984 << "-mabi=vec-extabi" << T.str();
1985 CmdArgs.push_back("-mabi=vec-extabi");
1988 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1989 if (FloatABI == ppc::FloatABI::Soft) {
1990 // Floating point operations and argument passing are soft.
1991 CmdArgs.push_back("-msoft-float");
1992 CmdArgs.push_back("-mfloat-abi");
1993 CmdArgs.push_back("soft");
1994 } else {
1995 // Floating point operations and argument passing are hard.
1996 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1997 CmdArgs.push_back("-mfloat-abi");
1998 CmdArgs.push_back("hard");
2001 if (ABIName) {
2002 CmdArgs.push_back("-target-abi");
2003 CmdArgs.push_back(ABIName);
2007 static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2008 ArgStringList &CmdArgs) {
2009 const Driver &D = TC.getDriver();
2010 const llvm::Triple &Triple = TC.getTriple();
2011 // Default small data limitation is eight.
2012 const char *SmallDataLimit = "8";
2013 // Get small data limitation.
2014 if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2015 options::OPT_fPIC)) {
2016 // Not support linker relaxation for PIC.
2017 SmallDataLimit = "0";
2018 if (Args.hasArg(options::OPT_G)) {
2019 D.Diag(diag::warn_drv_unsupported_sdata);
2021 } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2022 .equals_insensitive("large") &&
2023 (Triple.getArch() == llvm::Triple::riscv64)) {
2024 // Not support linker relaxation for RV64 with large code model.
2025 SmallDataLimit = "0";
2026 if (Args.hasArg(options::OPT_G)) {
2027 D.Diag(diag::warn_drv_unsupported_sdata);
2029 } else if (Triple.isAndroid()) {
2030 // GP relaxation is not supported on Android.
2031 SmallDataLimit = "0";
2032 if (Args.hasArg(options::OPT_G)) {
2033 D.Diag(diag::warn_drv_unsupported_sdata);
2035 } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2036 SmallDataLimit = A->getValue();
2038 // Forward the -msmall-data-limit= option.
2039 CmdArgs.push_back("-msmall-data-limit");
2040 CmdArgs.push_back(SmallDataLimit);
2043 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2044 ArgStringList &CmdArgs) const {
2045 const llvm::Triple &Triple = getToolChain().getTriple();
2046 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2048 CmdArgs.push_back("-target-abi");
2049 CmdArgs.push_back(ABIName.data());
2051 SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2053 if (!Args.hasFlag(options::OPT_mimplicit_float,
2054 options::OPT_mno_implicit_float, true))
2055 CmdArgs.push_back("-no-implicit-float");
2057 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2058 CmdArgs.push_back("-tune-cpu");
2059 if (strcmp(A->getValue(), "native") == 0)
2060 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2061 else
2062 CmdArgs.push_back(A->getValue());
2065 // Handle -mrvv-vector-bits=<bits>
2066 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2067 StringRef Val = A->getValue();
2068 const Driver &D = getToolChain().getDriver();
2070 // Get minimum VLen from march.
2071 unsigned MinVLen = 0;
2072 StringRef Arch = riscv::getRISCVArch(Args, Triple);
2073 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2074 Arch, /*EnableExperimentalExtensions*/ true);
2075 if (!ISAInfo) {
2076 // Ignore parsing error.
2077 consumeError(ISAInfo.takeError());
2078 } else {
2079 MinVLen = (*ISAInfo)->getMinVLen();
2082 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2083 // as integer as long as we have a MinVLen.
2084 unsigned Bits = 0;
2085 if (Val.equals("zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2086 Bits = MinVLen;
2087 } else if (!Val.getAsInteger(10, Bits)) {
2088 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2089 // at least MinVLen.
2090 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2091 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2092 Bits = 0;
2095 // If we got a valid value try to use it.
2096 if (Bits != 0) {
2097 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2098 CmdArgs.push_back(
2099 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2100 CmdArgs.push_back(
2101 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2102 } else if (!Val.equals("scalable")) {
2103 // Handle the unsupported values passed to mrvv-vector-bits.
2104 D.Diag(diag::err_drv_unsupported_option_argument)
2105 << A->getSpelling() << Val;
2110 void Clang::AddSparcTargetArgs(const ArgList &Args,
2111 ArgStringList &CmdArgs) const {
2112 sparc::FloatABI FloatABI =
2113 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2115 if (FloatABI == sparc::FloatABI::Soft) {
2116 // Floating point operations and argument passing are soft.
2117 CmdArgs.push_back("-msoft-float");
2118 CmdArgs.push_back("-mfloat-abi");
2119 CmdArgs.push_back("soft");
2120 } else {
2121 // Floating point operations and argument passing are hard.
2122 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2123 CmdArgs.push_back("-mfloat-abi");
2124 CmdArgs.push_back("hard");
2127 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2128 StringRef Name = A->getValue();
2129 std::string TuneCPU;
2130 if (Name == "native")
2131 TuneCPU = std::string(llvm::sys::getHostCPUName());
2132 else
2133 TuneCPU = std::string(Name);
2135 CmdArgs.push_back("-tune-cpu");
2136 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2140 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2141 ArgStringList &CmdArgs) const {
2142 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2143 CmdArgs.push_back("-tune-cpu");
2144 if (strcmp(A->getValue(), "native") == 0)
2145 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2146 else
2147 CmdArgs.push_back(A->getValue());
2150 bool HasBackchain =
2151 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2152 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2153 options::OPT_mno_packed_stack, false);
2154 systemz::FloatABI FloatABI =
2155 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2156 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2157 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2158 const Driver &D = getToolChain().getDriver();
2159 D.Diag(diag::err_drv_unsupported_opt)
2160 << "-mpacked-stack -mbackchain -mhard-float";
2162 if (HasBackchain)
2163 CmdArgs.push_back("-mbackchain");
2164 if (HasPackedStack)
2165 CmdArgs.push_back("-mpacked-stack");
2166 if (HasSoftFloat) {
2167 // Floating point operations and argument passing are soft.
2168 CmdArgs.push_back("-msoft-float");
2169 CmdArgs.push_back("-mfloat-abi");
2170 CmdArgs.push_back("soft");
2174 void Clang::AddX86TargetArgs(const ArgList &Args,
2175 ArgStringList &CmdArgs) const {
2176 const Driver &D = getToolChain().getDriver();
2177 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2179 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2180 Args.hasArg(options::OPT_mkernel) ||
2181 Args.hasArg(options::OPT_fapple_kext))
2182 CmdArgs.push_back("-disable-red-zone");
2184 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2185 options::OPT_mno_tls_direct_seg_refs, true))
2186 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2188 // Default to avoid implicit floating-point for kernel/kext code, but allow
2189 // that to be overridden with -mno-soft-float.
2190 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2191 Args.hasArg(options::OPT_fapple_kext));
2192 if (Arg *A = Args.getLastArg(
2193 options::OPT_msoft_float, options::OPT_mno_soft_float,
2194 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2195 const Option &O = A->getOption();
2196 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2197 O.matches(options::OPT_msoft_float));
2199 if (NoImplicitFloat)
2200 CmdArgs.push_back("-no-implicit-float");
2202 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2203 StringRef Value = A->getValue();
2204 if (Value == "intel" || Value == "att") {
2205 CmdArgs.push_back("-mllvm");
2206 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2207 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2208 } else {
2209 D.Diag(diag::err_drv_unsupported_option_argument)
2210 << A->getSpelling() << Value;
2212 } else if (D.IsCLMode()) {
2213 CmdArgs.push_back("-mllvm");
2214 CmdArgs.push_back("-x86-asm-syntax=intel");
2217 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2218 options::OPT_mno_skip_rax_setup))
2219 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2220 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2222 // Set flags to support MCU ABI.
2223 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2224 CmdArgs.push_back("-mfloat-abi");
2225 CmdArgs.push_back("soft");
2226 CmdArgs.push_back("-mstack-alignment=4");
2229 // Handle -mtune.
2231 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2232 std::string TuneCPU;
2233 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2234 !getToolChain().getTriple().isPS())
2235 TuneCPU = "generic";
2237 // Override based on -mtune.
2238 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2239 StringRef Name = A->getValue();
2241 if (Name == "native") {
2242 Name = llvm::sys::getHostCPUName();
2243 if (!Name.empty())
2244 TuneCPU = std::string(Name);
2245 } else
2246 TuneCPU = std::string(Name);
2249 if (!TuneCPU.empty()) {
2250 CmdArgs.push_back("-tune-cpu");
2251 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2255 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2256 ArgStringList &CmdArgs) const {
2257 CmdArgs.push_back("-mqdsp6-compat");
2258 CmdArgs.push_back("-Wreturn-type");
2260 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2261 CmdArgs.push_back("-mllvm");
2262 CmdArgs.push_back(
2263 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2266 if (!Args.hasArg(options::OPT_fno_short_enums))
2267 CmdArgs.push_back("-fshort-enums");
2268 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2269 CmdArgs.push_back("-mllvm");
2270 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2272 CmdArgs.push_back("-mllvm");
2273 CmdArgs.push_back("-machine-sink-split=0");
2276 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2277 ArgStringList &CmdArgs) const {
2278 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2279 StringRef CPUName = A->getValue();
2281 CmdArgs.push_back("-target-cpu");
2282 CmdArgs.push_back(Args.MakeArgString(CPUName));
2284 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2285 StringRef Value = A->getValue();
2286 // Only support mregparm=4 to support old usage. Report error for all other
2287 // cases.
2288 int Mregparm;
2289 if (Value.getAsInteger(10, Mregparm)) {
2290 if (Mregparm != 4) {
2291 getToolChain().getDriver().Diag(
2292 diag::err_drv_unsupported_option_argument)
2293 << A->getSpelling() << Value;
2299 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2300 ArgStringList &CmdArgs) const {
2301 // Default to "hidden" visibility.
2302 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2303 options::OPT_fvisibility_ms_compat))
2304 CmdArgs.push_back("-fvisibility=hidden");
2307 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2308 // Floating point operations and argument passing are hard.
2309 CmdArgs.push_back("-mfloat-abi");
2310 CmdArgs.push_back("hard");
2313 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2314 StringRef Target, const InputInfo &Output,
2315 const InputInfo &Input, const ArgList &Args) const {
2316 // If this is a dry run, do not create the compilation database file.
2317 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2318 return;
2320 using llvm::yaml::escape;
2321 const Driver &D = getToolChain().getDriver();
2323 if (!CompilationDatabase) {
2324 std::error_code EC;
2325 auto File = std::make_unique<llvm::raw_fd_ostream>(
2326 Filename, EC,
2327 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2328 if (EC) {
2329 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2330 << EC.message();
2331 return;
2333 CompilationDatabase = std::move(File);
2335 auto &CDB = *CompilationDatabase;
2336 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2337 if (!CWD)
2338 CWD = ".";
2339 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2340 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2341 if (Output.isFilename())
2342 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2343 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2344 SmallString<128> Buf;
2345 Buf = "-x";
2346 Buf += types::getTypeName(Input.getType());
2347 CDB << ", \"" << escape(Buf) << "\"";
2348 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2349 Buf = "--sysroot=";
2350 Buf += D.SysRoot;
2351 CDB << ", \"" << escape(Buf) << "\"";
2353 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2354 if (Output.isFilename())
2355 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2356 for (auto &A: Args) {
2357 auto &O = A->getOption();
2358 // Skip language selection, which is positional.
2359 if (O.getID() == options::OPT_x)
2360 continue;
2361 // Skip writing dependency output and the compilation database itself.
2362 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2363 continue;
2364 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2365 continue;
2366 // Skip inputs.
2367 if (O.getKind() == Option::InputClass)
2368 continue;
2369 // Skip output.
2370 if (O.getID() == options::OPT_o)
2371 continue;
2372 // All other arguments are quoted and appended.
2373 ArgStringList ASL;
2374 A->render(Args, ASL);
2375 for (auto &it: ASL)
2376 CDB << ", \"" << escape(it) << "\"";
2378 Buf = "--target=";
2379 Buf += Target;
2380 CDB << ", \"" << escape(Buf) << "\"]},\n";
2383 void Clang::DumpCompilationDatabaseFragmentToDir(
2384 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2385 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2386 // If this is a dry run, do not create the compilation database file.
2387 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2388 return;
2390 if (CompilationDatabase)
2391 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2393 SmallString<256> Path = Dir;
2394 const auto &Driver = C.getDriver();
2395 Driver.getVFS().makeAbsolute(Path);
2396 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2397 if (Err) {
2398 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2399 return;
2402 llvm::sys::path::append(
2403 Path,
2404 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2405 int FD;
2406 SmallString<256> TempPath;
2407 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2408 llvm::sys::fs::OF_Text);
2409 if (Err) {
2410 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2411 return;
2413 CompilationDatabase =
2414 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2415 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2418 static bool CheckARMImplicitITArg(StringRef Value) {
2419 return Value == "always" || Value == "never" || Value == "arm" ||
2420 Value == "thumb";
2423 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2424 StringRef Value) {
2425 CmdArgs.push_back("-mllvm");
2426 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2429 static void CollectArgsForIntegratedAssembler(Compilation &C,
2430 const ArgList &Args,
2431 ArgStringList &CmdArgs,
2432 const Driver &D) {
2433 if (UseRelaxAll(C, Args))
2434 CmdArgs.push_back("-mrelax-all");
2436 // Only default to -mincremental-linker-compatible if we think we are
2437 // targeting the MSVC linker.
2438 bool DefaultIncrementalLinkerCompatible =
2439 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2440 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2441 options::OPT_mno_incremental_linker_compatible,
2442 DefaultIncrementalLinkerCompatible))
2443 CmdArgs.push_back("-mincremental-linker-compatible");
2445 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2447 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2448 options::OPT_fno_emit_compact_unwind_non_canonical);
2450 // If you add more args here, also add them to the block below that
2451 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2453 // When passing -I arguments to the assembler we sometimes need to
2454 // unconditionally take the next argument. For example, when parsing
2455 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2456 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2457 // arg after parsing the '-I' arg.
2458 bool TakeNextArg = false;
2460 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2461 bool UseNoExecStack = false;
2462 const char *MipsTargetFeature = nullptr;
2463 StringRef ImplicitIt;
2464 for (const Arg *A :
2465 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2466 options::OPT_mimplicit_it_EQ)) {
2467 A->claim();
2469 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2470 switch (C.getDefaultToolChain().getArch()) {
2471 case llvm::Triple::arm:
2472 case llvm::Triple::armeb:
2473 case llvm::Triple::thumb:
2474 case llvm::Triple::thumbeb:
2475 // Only store the value; the last value set takes effect.
2476 ImplicitIt = A->getValue();
2477 if (!CheckARMImplicitITArg(ImplicitIt))
2478 D.Diag(diag::err_drv_unsupported_option_argument)
2479 << A->getSpelling() << ImplicitIt;
2480 continue;
2481 default:
2482 break;
2486 for (StringRef Value : A->getValues()) {
2487 if (TakeNextArg) {
2488 CmdArgs.push_back(Value.data());
2489 TakeNextArg = false;
2490 continue;
2493 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2494 Value == "-mbig-obj")
2495 continue; // LLVM handles bigobj automatically
2497 switch (C.getDefaultToolChain().getArch()) {
2498 default:
2499 break;
2500 case llvm::Triple::wasm32:
2501 case llvm::Triple::wasm64:
2502 if (Value == "--no-type-check") {
2503 CmdArgs.push_back("-mno-type-check");
2504 continue;
2506 break;
2507 case llvm::Triple::thumb:
2508 case llvm::Triple::thumbeb:
2509 case llvm::Triple::arm:
2510 case llvm::Triple::armeb:
2511 if (Value.starts_with("-mimplicit-it=")) {
2512 // Only store the value; the last value set takes effect.
2513 ImplicitIt = Value.split("=").second;
2514 if (CheckARMImplicitITArg(ImplicitIt))
2515 continue;
2517 if (Value == "-mthumb")
2518 // -mthumb has already been processed in ComputeLLVMTriple()
2519 // recognize but skip over here.
2520 continue;
2521 break;
2522 case llvm::Triple::mips:
2523 case llvm::Triple::mipsel:
2524 case llvm::Triple::mips64:
2525 case llvm::Triple::mips64el:
2526 if (Value == "--trap") {
2527 CmdArgs.push_back("-target-feature");
2528 CmdArgs.push_back("+use-tcc-in-div");
2529 continue;
2531 if (Value == "--break") {
2532 CmdArgs.push_back("-target-feature");
2533 CmdArgs.push_back("-use-tcc-in-div");
2534 continue;
2536 if (Value.starts_with("-msoft-float")) {
2537 CmdArgs.push_back("-target-feature");
2538 CmdArgs.push_back("+soft-float");
2539 continue;
2541 if (Value.starts_with("-mhard-float")) {
2542 CmdArgs.push_back("-target-feature");
2543 CmdArgs.push_back("-soft-float");
2544 continue;
2547 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2548 .Case("-mips1", "+mips1")
2549 .Case("-mips2", "+mips2")
2550 .Case("-mips3", "+mips3")
2551 .Case("-mips4", "+mips4")
2552 .Case("-mips5", "+mips5")
2553 .Case("-mips32", "+mips32")
2554 .Case("-mips32r2", "+mips32r2")
2555 .Case("-mips32r3", "+mips32r3")
2556 .Case("-mips32r5", "+mips32r5")
2557 .Case("-mips32r6", "+mips32r6")
2558 .Case("-mips64", "+mips64")
2559 .Case("-mips64r2", "+mips64r2")
2560 .Case("-mips64r3", "+mips64r3")
2561 .Case("-mips64r5", "+mips64r5")
2562 .Case("-mips64r6", "+mips64r6")
2563 .Default(nullptr);
2564 if (MipsTargetFeature)
2565 continue;
2568 if (Value == "-force_cpusubtype_ALL") {
2569 // Do nothing, this is the default and we don't support anything else.
2570 } else if (Value == "-L") {
2571 CmdArgs.push_back("-msave-temp-labels");
2572 } else if (Value == "--fatal-warnings") {
2573 CmdArgs.push_back("-massembler-fatal-warnings");
2574 } else if (Value == "--no-warn" || Value == "-W") {
2575 CmdArgs.push_back("-massembler-no-warn");
2576 } else if (Value == "--noexecstack") {
2577 UseNoExecStack = true;
2578 } else if (Value.starts_with("-compress-debug-sections") ||
2579 Value.starts_with("--compress-debug-sections") ||
2580 Value == "-nocompress-debug-sections" ||
2581 Value == "--nocompress-debug-sections") {
2582 CmdArgs.push_back(Value.data());
2583 } else if (Value == "-mrelax-relocations=yes" ||
2584 Value == "--mrelax-relocations=yes") {
2585 UseRelaxRelocations = true;
2586 } else if (Value == "-mrelax-relocations=no" ||
2587 Value == "--mrelax-relocations=no") {
2588 UseRelaxRelocations = false;
2589 } else if (Value.starts_with("-I")) {
2590 CmdArgs.push_back(Value.data());
2591 // We need to consume the next argument if the current arg is a plain
2592 // -I. The next arg will be the include directory.
2593 if (Value == "-I")
2594 TakeNextArg = true;
2595 } else if (Value.starts_with("-gdwarf-")) {
2596 // "-gdwarf-N" options are not cc1as options.
2597 unsigned DwarfVersion = DwarfVersionNum(Value);
2598 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2599 CmdArgs.push_back(Value.data());
2600 } else {
2601 RenderDebugEnablingArgs(Args, CmdArgs,
2602 llvm::codegenoptions::DebugInfoConstructor,
2603 DwarfVersion, llvm::DebuggerKind::Default);
2605 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2606 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2607 // Do nothing, we'll validate it later.
2608 } else if (Value == "-defsym") {
2609 if (A->getNumValues() != 2) {
2610 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2611 break;
2613 const char *S = A->getValue(1);
2614 auto Pair = StringRef(S).split('=');
2615 auto Sym = Pair.first;
2616 auto SVal = Pair.second;
2618 if (Sym.empty() || SVal.empty()) {
2619 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2620 break;
2622 int64_t IVal;
2623 if (SVal.getAsInteger(0, IVal)) {
2624 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2625 break;
2627 CmdArgs.push_back(Value.data());
2628 TakeNextArg = true;
2629 } else if (Value == "-fdebug-compilation-dir") {
2630 CmdArgs.push_back("-fdebug-compilation-dir");
2631 TakeNextArg = true;
2632 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2633 // The flag is a -Wa / -Xassembler argument and Options doesn't
2634 // parse the argument, so this isn't automatically aliased to
2635 // -fdebug-compilation-dir (without '=') here.
2636 CmdArgs.push_back("-fdebug-compilation-dir");
2637 CmdArgs.push_back(Value.data());
2638 } else if (Value == "--version") {
2639 D.PrintVersion(C, llvm::outs());
2640 } else {
2641 D.Diag(diag::err_drv_unsupported_option_argument)
2642 << A->getSpelling() << Value;
2646 if (ImplicitIt.size())
2647 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2648 if (!UseRelaxRelocations)
2649 CmdArgs.push_back("-mrelax-relocations=no");
2650 if (UseNoExecStack)
2651 CmdArgs.push_back("-mnoexecstack");
2652 if (MipsTargetFeature != nullptr) {
2653 CmdArgs.push_back("-target-feature");
2654 CmdArgs.push_back(MipsTargetFeature);
2657 // forward -fembed-bitcode to assmebler
2658 if (C.getDriver().embedBitcodeEnabled() ||
2659 C.getDriver().embedBitcodeMarkerOnly())
2660 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2662 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2663 CmdArgs.push_back("-as-secure-log-file");
2664 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2668 static StringRef EnumComplexRangeToStr(LangOptions::ComplexRangeKind Range) {
2669 StringRef RangeStr = "";
2670 switch (Range) {
2671 case LangOptions::ComplexRangeKind::CX_Limited:
2672 return "-fcx-limited-range";
2673 break;
2674 case LangOptions::ComplexRangeKind::CX_Fortran:
2675 return "-fcx-fortran-rules";
2676 break;
2677 default:
2678 return RangeStr;
2679 break;
2683 static void EmitComplexRangeDiag(const Driver &D,
2684 LangOptions::ComplexRangeKind Range1,
2685 LangOptions::ComplexRangeKind Range2) {
2686 if (Range1 != LangOptions::ComplexRangeKind::CX_Full)
2687 D.Diag(clang::diag::warn_drv_overriding_option)
2688 << EnumComplexRangeToStr(Range1) << EnumComplexRangeToStr(Range2);
2691 static std::string RenderComplexRangeOption(std::string Range) {
2692 std::string ComplexRangeStr = "-complex-range=";
2693 ComplexRangeStr += Range;
2694 return ComplexRangeStr;
2697 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2698 bool OFastEnabled, const ArgList &Args,
2699 ArgStringList &CmdArgs,
2700 const JobAction &JA) {
2701 // Handle various floating point optimization flags, mapping them to the
2702 // appropriate LLVM code generation flags. This is complicated by several
2703 // "umbrella" flags, so we do this by stepping through the flags incrementally
2704 // adjusting what we think is enabled/disabled, then at the end setting the
2705 // LLVM flags based on the final state.
2706 bool HonorINFs = true;
2707 bool HonorNaNs = true;
2708 bool ApproxFunc = false;
2709 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2710 bool MathErrno = TC.IsMathErrnoDefault();
2711 bool AssociativeMath = false;
2712 bool ReciprocalMath = false;
2713 bool SignedZeros = true;
2714 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2715 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2716 // overriden by ffp-exception-behavior?
2717 bool RoundingFPMath = false;
2718 bool RoundingMathPresent = false; // Is rounding-math in args?
2719 // -ffp-model values: strict, fast, precise
2720 StringRef FPModel = "";
2721 // -ffp-exception-behavior options: strict, maytrap, ignore
2722 StringRef FPExceptionBehavior = "";
2723 // -ffp-eval-method options: double, extended, source
2724 StringRef FPEvalMethod = "";
2725 const llvm::DenormalMode DefaultDenormalFPMath =
2726 TC.getDefaultDenormalModeForType(Args, JA);
2727 const llvm::DenormalMode DefaultDenormalFP32Math =
2728 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2730 llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2731 llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2732 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2733 // If one wasn't given by the user, don't pass it here.
2734 StringRef FPContract;
2735 StringRef LastSeenFfpContractOption;
2736 bool SeenUnsafeMathModeOption = false;
2737 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2738 !JA.isOffloading(Action::OFK_HIP))
2739 FPContract = "on";
2740 bool StrictFPModel = false;
2741 StringRef Float16ExcessPrecision = "";
2742 StringRef BFloat16ExcessPrecision = "";
2743 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_Full;
2745 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2746 CmdArgs.push_back("-mlimit-float-precision");
2747 CmdArgs.push_back(A->getValue());
2750 for (const Arg *A : Args) {
2751 auto optID = A->getOption().getID();
2752 bool PreciseFPModel = false;
2753 switch (optID) {
2754 default:
2755 break;
2756 case options::OPT_fcx_limited_range: {
2757 EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Limited);
2758 Range = LangOptions::ComplexRangeKind::CX_Limited;
2759 std::string ComplexRangeStr = RenderComplexRangeOption("limited");
2760 if (!ComplexRangeStr.empty())
2761 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
2762 break;
2764 case options::OPT_fno_cx_limited_range:
2765 Range = LangOptions::ComplexRangeKind::CX_Full;
2766 break;
2767 case options::OPT_fcx_fortran_rules: {
2768 EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Fortran);
2769 Range = LangOptions::ComplexRangeKind::CX_Fortran;
2770 std::string ComplexRangeStr = RenderComplexRangeOption("fortran");
2771 if (!ComplexRangeStr.empty())
2772 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
2773 break;
2775 case options::OPT_fno_cx_fortran_rules:
2776 Range = LangOptions::ComplexRangeKind::CX_Full;
2777 break;
2778 case options::OPT_ffp_model_EQ: {
2779 // If -ffp-model= is seen, reset to fno-fast-math
2780 HonorINFs = true;
2781 HonorNaNs = true;
2782 ApproxFunc = false;
2783 // Turning *off* -ffast-math restores the toolchain default.
2784 MathErrno = TC.IsMathErrnoDefault();
2785 AssociativeMath = false;
2786 ReciprocalMath = false;
2787 SignedZeros = true;
2788 // -fno_fast_math restores default denormal and fpcontract handling
2789 FPContract = "on";
2790 DenormalFPMath = llvm::DenormalMode::getIEEE();
2792 // FIXME: The target may have picked a non-IEEE default mode here based on
2793 // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2794 DenormalFP32Math = llvm::DenormalMode::getIEEE();
2796 StringRef Val = A->getValue();
2797 if (OFastEnabled && !Val.equals("fast")) {
2798 // Only -ffp-model=fast is compatible with OFast, ignore.
2799 D.Diag(clang::diag::warn_drv_overriding_option)
2800 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2801 break;
2803 StrictFPModel = false;
2804 PreciseFPModel = true;
2805 // ffp-model= is a Driver option, it is entirely rewritten into more
2806 // granular options before being passed into cc1.
2807 // Use the gcc option in the switch below.
2808 if (!FPModel.empty() && !FPModel.equals(Val))
2809 D.Diag(clang::diag::warn_drv_overriding_option)
2810 << Args.MakeArgString("-ffp-model=" + FPModel)
2811 << Args.MakeArgString("-ffp-model=" + Val);
2812 if (Val.equals("fast")) {
2813 optID = options::OPT_ffast_math;
2814 FPModel = Val;
2815 FPContract = "fast";
2816 } else if (Val.equals("precise")) {
2817 optID = options::OPT_ffp_contract;
2818 FPModel = Val;
2819 FPContract = "on";
2820 PreciseFPModel = true;
2821 } else if (Val.equals("strict")) {
2822 StrictFPModel = true;
2823 optID = options::OPT_frounding_math;
2824 FPExceptionBehavior = "strict";
2825 FPModel = Val;
2826 FPContract = "off";
2827 TrappingMath = true;
2828 } else
2829 D.Diag(diag::err_drv_unsupported_option_argument)
2830 << A->getSpelling() << Val;
2831 break;
2835 switch (optID) {
2836 // If this isn't an FP option skip the claim below
2837 default: continue;
2839 // Options controlling individual features
2840 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2841 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2842 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2843 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2844 case options::OPT_fapprox_func: ApproxFunc = true; break;
2845 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2846 case options::OPT_fmath_errno: MathErrno = true; break;
2847 case options::OPT_fno_math_errno: MathErrno = false; break;
2848 case options::OPT_fassociative_math: AssociativeMath = true; break;
2849 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2850 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2851 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2852 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2853 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2854 case options::OPT_ftrapping_math:
2855 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2856 !FPExceptionBehavior.equals("strict"))
2857 // Warn that previous value of option is overridden.
2858 D.Diag(clang::diag::warn_drv_overriding_option)
2859 << Args.MakeArgString("-ffp-exception-behavior=" +
2860 FPExceptionBehavior)
2861 << "-ftrapping-math";
2862 TrappingMath = true;
2863 TrappingMathPresent = true;
2864 FPExceptionBehavior = "strict";
2865 break;
2866 case options::OPT_fno_trapping_math:
2867 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2868 !FPExceptionBehavior.equals("ignore"))
2869 // Warn that previous value of option is overridden.
2870 D.Diag(clang::diag::warn_drv_overriding_option)
2871 << Args.MakeArgString("-ffp-exception-behavior=" +
2872 FPExceptionBehavior)
2873 << "-fno-trapping-math";
2874 TrappingMath = false;
2875 TrappingMathPresent = true;
2876 FPExceptionBehavior = "ignore";
2877 break;
2879 case options::OPT_frounding_math:
2880 RoundingFPMath = true;
2881 RoundingMathPresent = true;
2882 break;
2884 case options::OPT_fno_rounding_math:
2885 RoundingFPMath = false;
2886 RoundingMathPresent = false;
2887 break;
2889 case options::OPT_fdenormal_fp_math_EQ:
2890 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2891 DenormalFP32Math = DenormalFPMath;
2892 if (!DenormalFPMath.isValid()) {
2893 D.Diag(diag::err_drv_invalid_value)
2894 << A->getAsString(Args) << A->getValue();
2896 break;
2898 case options::OPT_fdenormal_fp_math_f32_EQ:
2899 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2900 if (!DenormalFP32Math.isValid()) {
2901 D.Diag(diag::err_drv_invalid_value)
2902 << A->getAsString(Args) << A->getValue();
2904 break;
2906 // Validate and pass through -ffp-contract option.
2907 case options::OPT_ffp_contract: {
2908 StringRef Val = A->getValue();
2909 if (PreciseFPModel) {
2910 // -ffp-model=precise enables ffp-contract=on.
2911 // -ffp-model=precise sets PreciseFPModel to on and Val to
2912 // "precise". FPContract is set.
2914 } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off") ||
2915 Val.equals("fast-honor-pragmas")) {
2916 FPContract = Val;
2917 LastSeenFfpContractOption = Val;
2918 } else
2919 D.Diag(diag::err_drv_unsupported_option_argument)
2920 << A->getSpelling() << Val;
2921 break;
2924 // Validate and pass through -ffp-model option.
2925 case options::OPT_ffp_model_EQ:
2926 // This should only occur in the error case
2927 // since the optID has been replaced by a more granular
2928 // floating point option.
2929 break;
2931 // Validate and pass through -ffp-exception-behavior option.
2932 case options::OPT_ffp_exception_behavior_EQ: {
2933 StringRef Val = A->getValue();
2934 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2935 !FPExceptionBehavior.equals(Val))
2936 // Warn that previous value of option is overridden.
2937 D.Diag(clang::diag::warn_drv_overriding_option)
2938 << Args.MakeArgString("-ffp-exception-behavior=" +
2939 FPExceptionBehavior)
2940 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2941 TrappingMath = TrappingMathPresent = false;
2942 if (Val.equals("ignore") || Val.equals("maytrap"))
2943 FPExceptionBehavior = Val;
2944 else if (Val.equals("strict")) {
2945 FPExceptionBehavior = Val;
2946 TrappingMath = TrappingMathPresent = true;
2947 } else
2948 D.Diag(diag::err_drv_unsupported_option_argument)
2949 << A->getSpelling() << Val;
2950 break;
2953 // Validate and pass through -ffp-eval-method option.
2954 case options::OPT_ffp_eval_method_EQ: {
2955 StringRef Val = A->getValue();
2956 if (Val.equals("double") || Val.equals("extended") ||
2957 Val.equals("source"))
2958 FPEvalMethod = Val;
2959 else
2960 D.Diag(diag::err_drv_unsupported_option_argument)
2961 << A->getSpelling() << Val;
2962 break;
2965 case options::OPT_fexcess_precision_EQ: {
2966 StringRef Val = A->getValue();
2967 const llvm::Triple::ArchType Arch = TC.getArch();
2968 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
2969 if (Val.equals("standard") || Val.equals("fast"))
2970 Float16ExcessPrecision = Val;
2971 // To make it GCC compatible, allow the value of "16" which
2972 // means disable excess precision, the same meaning than clang's
2973 // equivalent value "none".
2974 else if (Val.equals("16"))
2975 Float16ExcessPrecision = "none";
2976 else
2977 D.Diag(diag::err_drv_unsupported_option_argument)
2978 << A->getSpelling() << Val;
2979 } else {
2980 if (!(Val.equals("standard") || Val.equals("fast")))
2981 D.Diag(diag::err_drv_unsupported_option_argument)
2982 << A->getSpelling() << Val;
2984 BFloat16ExcessPrecision = Float16ExcessPrecision;
2985 break;
2987 case options::OPT_ffinite_math_only:
2988 HonorINFs = false;
2989 HonorNaNs = false;
2990 break;
2991 case options::OPT_fno_finite_math_only:
2992 HonorINFs = true;
2993 HonorNaNs = true;
2994 break;
2996 case options::OPT_funsafe_math_optimizations:
2997 AssociativeMath = true;
2998 ReciprocalMath = true;
2999 SignedZeros = false;
3000 ApproxFunc = true;
3001 TrappingMath = false;
3002 FPExceptionBehavior = "";
3003 FPContract = "fast";
3004 SeenUnsafeMathModeOption = true;
3005 break;
3006 case options::OPT_fno_unsafe_math_optimizations:
3007 AssociativeMath = false;
3008 ReciprocalMath = false;
3009 SignedZeros = true;
3010 ApproxFunc = false;
3011 TrappingMath = true;
3012 FPExceptionBehavior = "strict";
3014 // The target may have opted to flush by default, so force IEEE.
3015 DenormalFPMath = llvm::DenormalMode::getIEEE();
3016 DenormalFP32Math = llvm::DenormalMode::getIEEE();
3017 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3018 !JA.isOffloading(Action::OFK_HIP)) {
3019 if (LastSeenFfpContractOption != "") {
3020 FPContract = LastSeenFfpContractOption;
3021 } else if (SeenUnsafeMathModeOption)
3022 FPContract = "on";
3024 break;
3026 case options::OPT_Ofast:
3027 // If -Ofast is the optimization level, then -ffast-math should be enabled
3028 if (!OFastEnabled)
3029 continue;
3030 [[fallthrough]];
3031 case options::OPT_ffast_math: {
3032 HonorINFs = false;
3033 HonorNaNs = false;
3034 MathErrno = false;
3035 AssociativeMath = true;
3036 ReciprocalMath = true;
3037 ApproxFunc = true;
3038 SignedZeros = false;
3039 TrappingMath = false;
3040 RoundingFPMath = false;
3041 FPExceptionBehavior = "";
3042 // If fast-math is set then set the fp-contract mode to fast.
3043 FPContract = "fast";
3044 SeenUnsafeMathModeOption = true;
3045 // ffast-math enables fortran rules for complex multiplication and
3046 // division.
3047 std::string ComplexRangeStr = RenderComplexRangeOption("limited");
3048 if (!ComplexRangeStr.empty())
3049 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3050 break;
3052 case options::OPT_fno_fast_math:
3053 HonorINFs = true;
3054 HonorNaNs = true;
3055 // Turning on -ffast-math (with either flag) removes the need for
3056 // MathErrno. However, turning *off* -ffast-math merely restores the
3057 // toolchain default (which may be false).
3058 MathErrno = TC.IsMathErrnoDefault();
3059 AssociativeMath = false;
3060 ReciprocalMath = false;
3061 ApproxFunc = false;
3062 SignedZeros = true;
3063 // -fno_fast_math restores default denormal and fpcontract handling
3064 DenormalFPMath = DefaultDenormalFPMath;
3065 DenormalFP32Math = llvm::DenormalMode::getIEEE();
3066 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3067 !JA.isOffloading(Action::OFK_HIP)) {
3068 if (LastSeenFfpContractOption != "") {
3069 FPContract = LastSeenFfpContractOption;
3070 } else if (SeenUnsafeMathModeOption)
3071 FPContract = "on";
3073 break;
3075 if (StrictFPModel) {
3076 // If -ffp-model=strict has been specified on command line but
3077 // subsequent options conflict then emit warning diagnostic.
3078 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3079 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3080 DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3081 DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3082 FPContract.equals("off"))
3083 // OK: Current Arg doesn't conflict with -ffp-model=strict
3085 else {
3086 StrictFPModel = false;
3087 FPModel = "";
3088 auto RHS = (A->getNumValues() == 0)
3089 ? A->getSpelling()
3090 : Args.MakeArgString(A->getSpelling() + A->getValue());
3091 if (RHS != "-ffp-model=strict")
3092 D.Diag(clang::diag::warn_drv_overriding_option)
3093 << "-ffp-model=strict" << RHS;
3097 // If we handled this option claim it
3098 A->claim();
3101 if (!HonorINFs)
3102 CmdArgs.push_back("-menable-no-infs");
3104 if (!HonorNaNs)
3105 CmdArgs.push_back("-menable-no-nans");
3107 if (ApproxFunc)
3108 CmdArgs.push_back("-fapprox-func");
3110 if (MathErrno)
3111 CmdArgs.push_back("-fmath-errno");
3113 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3114 !TrappingMath)
3115 CmdArgs.push_back("-funsafe-math-optimizations");
3117 if (!SignedZeros)
3118 CmdArgs.push_back("-fno-signed-zeros");
3120 if (AssociativeMath && !SignedZeros && !TrappingMath)
3121 CmdArgs.push_back("-mreassociate");
3123 if (ReciprocalMath)
3124 CmdArgs.push_back("-freciprocal-math");
3126 if (TrappingMath) {
3127 // FP Exception Behavior is also set to strict
3128 assert(FPExceptionBehavior.equals("strict"));
3131 // The default is IEEE.
3132 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3133 llvm::SmallString<64> DenormFlag;
3134 llvm::raw_svector_ostream ArgStr(DenormFlag);
3135 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3136 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3139 // Add f32 specific denormal mode flag if it's different.
3140 if (DenormalFP32Math != DenormalFPMath) {
3141 llvm::SmallString<64> DenormFlag;
3142 llvm::raw_svector_ostream ArgStr(DenormFlag);
3143 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3144 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3147 if (!FPContract.empty())
3148 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3150 if (!RoundingFPMath)
3151 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3153 if (RoundingFPMath && RoundingMathPresent)
3154 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3156 if (!FPExceptionBehavior.empty())
3157 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3158 FPExceptionBehavior));
3160 if (!FPEvalMethod.empty())
3161 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3163 if (!Float16ExcessPrecision.empty())
3164 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3165 Float16ExcessPrecision));
3166 if (!BFloat16ExcessPrecision.empty())
3167 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3168 BFloat16ExcessPrecision));
3170 ParseMRecip(D, Args, CmdArgs);
3172 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3173 // individual features enabled by -ffast-math instead of the option itself as
3174 // that's consistent with gcc's behaviour.
3175 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3176 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3177 CmdArgs.push_back("-ffast-math");
3178 if (FPModel.equals("fast")) {
3179 if (FPContract.equals("fast"))
3180 // All set, do nothing.
3182 else if (FPContract.empty())
3183 // Enable -ffp-contract=fast
3184 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3185 else
3186 D.Diag(clang::diag::warn_drv_overriding_option)
3187 << "-ffp-model=fast"
3188 << Args.MakeArgString("-ffp-contract=" + FPContract);
3192 // Handle __FINITE_MATH_ONLY__ similarly.
3193 if (!HonorINFs && !HonorNaNs)
3194 CmdArgs.push_back("-ffinite-math-only");
3196 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3197 CmdArgs.push_back("-mfpmath");
3198 CmdArgs.push_back(A->getValue());
3201 // Disable a codegen optimization for floating-point casts.
3202 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3203 options::OPT_fstrict_float_cast_overflow, false))
3204 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3206 if (const Arg *A = Args.getLastArg(options::OPT_fcx_limited_range))
3207 CmdArgs.push_back("-fcx-limited-range");
3208 if (const Arg *A = Args.getLastArg(options::OPT_fcx_fortran_rules))
3209 CmdArgs.push_back("-fcx-fortran-rules");
3210 if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_limited_range))
3211 CmdArgs.push_back("-fno-cx-limited-range");
3212 if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_fortran_rules))
3213 CmdArgs.push_back("-fno-cx-fortran-rules");
3216 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3217 const llvm::Triple &Triple,
3218 const InputInfo &Input) {
3219 // Add default argument set.
3220 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3221 CmdArgs.push_back("-analyzer-checker=core");
3222 CmdArgs.push_back("-analyzer-checker=apiModeling");
3224 if (!Triple.isWindowsMSVCEnvironment()) {
3225 CmdArgs.push_back("-analyzer-checker=unix");
3226 } else {
3227 // Enable "unix" checkers that also work on Windows.
3228 CmdArgs.push_back("-analyzer-checker=unix.API");
3229 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3230 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3231 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3232 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3233 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3236 // Disable some unix checkers for PS4/PS5.
3237 if (Triple.isPS()) {
3238 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3239 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3242 if (Triple.isOSDarwin()) {
3243 CmdArgs.push_back("-analyzer-checker=osx");
3244 CmdArgs.push_back(
3245 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3247 else if (Triple.isOSFuchsia())
3248 CmdArgs.push_back("-analyzer-checker=fuchsia");
3250 CmdArgs.push_back("-analyzer-checker=deadcode");
3252 if (types::isCXX(Input.getType()))
3253 CmdArgs.push_back("-analyzer-checker=cplusplus");
3255 if (!Triple.isPS()) {
3256 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3257 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3258 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3259 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3260 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3261 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3264 // Default nullability checks.
3265 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3266 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3269 // Set the output format. The default is plist, for (lame) historical reasons.
3270 CmdArgs.push_back("-analyzer-output");
3271 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3272 CmdArgs.push_back(A->getValue());
3273 else
3274 CmdArgs.push_back("plist");
3276 // Disable the presentation of standard compiler warnings when using
3277 // --analyze. We only want to show static analyzer diagnostics or frontend
3278 // errors.
3279 CmdArgs.push_back("-w");
3281 // Add -Xanalyzer arguments when running as analyzer.
3282 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3285 static bool isValidSymbolName(StringRef S) {
3286 if (S.empty())
3287 return false;
3289 if (std::isdigit(S[0]))
3290 return false;
3292 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3295 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3296 const ArgList &Args, ArgStringList &CmdArgs,
3297 bool KernelOrKext) {
3298 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3300 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3301 // doesn't even have a stack!
3302 if (EffectiveTriple.isNVPTX())
3303 return;
3305 // -stack-protector=0 is default.
3306 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3307 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3308 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3310 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3311 options::OPT_fstack_protector_all,
3312 options::OPT_fstack_protector_strong,
3313 options::OPT_fstack_protector)) {
3314 if (A->getOption().matches(options::OPT_fstack_protector))
3315 StackProtectorLevel =
3316 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3317 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3318 StackProtectorLevel = LangOptions::SSPStrong;
3319 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3320 StackProtectorLevel = LangOptions::SSPReq;
3322 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3323 D.Diag(diag::warn_drv_unsupported_option_for_target)
3324 << A->getSpelling() << EffectiveTriple.getTriple();
3325 StackProtectorLevel = DefaultStackProtectorLevel;
3327 } else {
3328 StackProtectorLevel = DefaultStackProtectorLevel;
3331 if (StackProtectorLevel) {
3332 CmdArgs.push_back("-stack-protector");
3333 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3336 // --param ssp-buffer-size=
3337 for (const Arg *A : Args.filtered(options::OPT__param)) {
3338 StringRef Str(A->getValue());
3339 if (Str.starts_with("ssp-buffer-size=")) {
3340 if (StackProtectorLevel) {
3341 CmdArgs.push_back("-stack-protector-buffer-size");
3342 // FIXME: Verify the argument is a valid integer.
3343 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3345 A->claim();
3349 const std::string &TripleStr = EffectiveTriple.getTriple();
3350 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3351 StringRef Value = A->getValue();
3352 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3353 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3354 D.Diag(diag::err_drv_unsupported_opt_for_target)
3355 << A->getAsString(Args) << TripleStr;
3356 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3357 EffectiveTriple.isThumb()) &&
3358 Value != "tls" && Value != "global") {
3359 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3360 << A->getOption().getName() << Value << "tls global";
3361 return;
3363 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3364 Value == "tls") {
3365 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3366 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3367 << A->getAsString(Args);
3368 return;
3370 // Check whether the target subarch supports the hardware TLS register
3371 if (!arm::isHardTPSupported(EffectiveTriple)) {
3372 D.Diag(diag::err_target_unsupported_tp_hard)
3373 << EffectiveTriple.getArchName();
3374 return;
3376 // Check whether the user asked for something other than -mtp=cp15
3377 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3378 StringRef Value = A->getValue();
3379 if (Value != "cp15") {
3380 D.Diag(diag::err_drv_argument_not_allowed_with)
3381 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3382 return;
3385 CmdArgs.push_back("-target-feature");
3386 CmdArgs.push_back("+read-tp-tpidruro");
3388 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3389 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3390 << A->getOption().getName() << Value << "sysreg global";
3391 return;
3393 A->render(Args, CmdArgs);
3396 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3397 StringRef Value = A->getValue();
3398 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3399 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3400 D.Diag(diag::err_drv_unsupported_opt_for_target)
3401 << A->getAsString(Args) << TripleStr;
3402 int Offset;
3403 if (Value.getAsInteger(10, Offset)) {
3404 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3405 return;
3407 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3408 (Offset < 0 || Offset > 0xfffff)) {
3409 D.Diag(diag::err_drv_invalid_int_value)
3410 << A->getOption().getName() << Value;
3411 return;
3413 A->render(Args, CmdArgs);
3416 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3417 StringRef Value = A->getValue();
3418 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3419 D.Diag(diag::err_drv_unsupported_opt_for_target)
3420 << A->getAsString(Args) << TripleStr;
3421 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3422 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3423 << A->getOption().getName() << Value << "fs gs";
3424 return;
3426 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3427 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3428 return;
3430 A->render(Args, CmdArgs);
3433 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3434 StringRef Value = A->getValue();
3435 if (!isValidSymbolName(Value)) {
3436 D.Diag(diag::err_drv_argument_only_allowed_with)
3437 << A->getOption().getName() << "legal symbol name";
3438 return;
3440 A->render(Args, CmdArgs);
3444 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3445 ArgStringList &CmdArgs) {
3446 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3448 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3449 return;
3451 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3452 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
3453 return;
3455 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3456 options::OPT_fno_stack_clash_protection);
3459 static void RenderTrivialAutoVarInitOptions(const Driver &D,
3460 const ToolChain &TC,
3461 const ArgList &Args,
3462 ArgStringList &CmdArgs) {
3463 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3464 StringRef TrivialAutoVarInit = "";
3466 for (const Arg *A : Args) {
3467 switch (A->getOption().getID()) {
3468 default:
3469 continue;
3470 case options::OPT_ftrivial_auto_var_init: {
3471 A->claim();
3472 StringRef Val = A->getValue();
3473 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3474 TrivialAutoVarInit = Val;
3475 else
3476 D.Diag(diag::err_drv_unsupported_option_argument)
3477 << A->getSpelling() << Val;
3478 break;
3483 if (TrivialAutoVarInit.empty())
3484 switch (DefaultTrivialAutoVarInit) {
3485 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3486 break;
3487 case LangOptions::TrivialAutoVarInitKind::Pattern:
3488 TrivialAutoVarInit = "pattern";
3489 break;
3490 case LangOptions::TrivialAutoVarInitKind::Zero:
3491 TrivialAutoVarInit = "zero";
3492 break;
3495 if (!TrivialAutoVarInit.empty()) {
3496 CmdArgs.push_back(
3497 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3500 if (Arg *A =
3501 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3502 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3503 StringRef(
3504 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3505 "uninitialized")
3506 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3507 A->claim();
3508 StringRef Val = A->getValue();
3509 if (std::stoi(Val.str()) <= 0)
3510 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3511 CmdArgs.push_back(
3512 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3516 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3517 types::ID InputType) {
3518 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3519 // for denormal flushing handling based on the target.
3520 const unsigned ForwardedArguments[] = {
3521 options::OPT_cl_opt_disable,
3522 options::OPT_cl_strict_aliasing,
3523 options::OPT_cl_single_precision_constant,
3524 options::OPT_cl_finite_math_only,
3525 options::OPT_cl_kernel_arg_info,
3526 options::OPT_cl_unsafe_math_optimizations,
3527 options::OPT_cl_fast_relaxed_math,
3528 options::OPT_cl_mad_enable,
3529 options::OPT_cl_no_signed_zeros,
3530 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3531 options::OPT_cl_uniform_work_group_size
3534 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3535 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3536 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3537 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3538 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3539 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3542 for (const auto &Arg : ForwardedArguments)
3543 if (const auto *A = Args.getLastArg(Arg))
3544 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3546 // Only add the default headers if we are compiling OpenCL sources.
3547 if ((types::isOpenCL(InputType) ||
3548 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3549 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3550 CmdArgs.push_back("-finclude-default-header");
3551 CmdArgs.push_back("-fdeclare-opencl-builtins");
3555 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3556 types::ID InputType) {
3557 const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3558 options::OPT_D,
3559 options::OPT_I,
3560 options::OPT_S,
3561 options::OPT_O,
3562 options::OPT_emit_llvm,
3563 options::OPT_emit_obj,
3564 options::OPT_disable_llvm_passes,
3565 options::OPT_fnative_half_type,
3566 options::OPT_hlsl_entrypoint};
3567 if (!types::isHLSL(InputType))
3568 return;
3569 for (const auto &Arg : ForwardedArguments)
3570 if (const auto *A = Args.getLastArg(Arg))
3571 A->renderAsInput(Args, CmdArgs);
3572 // Add the default headers if dxc_no_stdinc is not set.
3573 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3574 !Args.hasArg(options::OPT_nostdinc))
3575 CmdArgs.push_back("-finclude-default-header");
3578 static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3579 ArgStringList &CmdArgs, types::ID InputType) {
3580 if (!Args.hasArg(options::OPT_fopenacc))
3581 return;
3583 CmdArgs.push_back("-fopenacc");
3585 if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
3586 StringRef Value = A->getValue();
3587 int Version;
3588 if (!Value.getAsInteger(10, Version))
3589 A->renderAsInput(Args, CmdArgs);
3590 else
3591 D.Diag(diag::err_drv_clang_unsupported) << Value;
3595 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3596 ArgStringList &CmdArgs) {
3597 bool ARCMTEnabled = false;
3598 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3599 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3600 options::OPT_ccc_arcmt_modify,
3601 options::OPT_ccc_arcmt_migrate)) {
3602 ARCMTEnabled = true;
3603 switch (A->getOption().getID()) {
3604 default: llvm_unreachable("missed a case");
3605 case options::OPT_ccc_arcmt_check:
3606 CmdArgs.push_back("-arcmt-action=check");
3607 break;
3608 case options::OPT_ccc_arcmt_modify:
3609 CmdArgs.push_back("-arcmt-action=modify");
3610 break;
3611 case options::OPT_ccc_arcmt_migrate:
3612 CmdArgs.push_back("-arcmt-action=migrate");
3613 CmdArgs.push_back("-mt-migrate-directory");
3614 CmdArgs.push_back(A->getValue());
3616 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3617 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3618 break;
3621 } else {
3622 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3623 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3624 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3627 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3628 if (ARCMTEnabled)
3629 D.Diag(diag::err_drv_argument_not_allowed_with)
3630 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3632 CmdArgs.push_back("-mt-migrate-directory");
3633 CmdArgs.push_back(A->getValue());
3635 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3636 options::OPT_objcmt_migrate_subscripting,
3637 options::OPT_objcmt_migrate_property)) {
3638 // None specified, means enable them all.
3639 CmdArgs.push_back("-objcmt-migrate-literals");
3640 CmdArgs.push_back("-objcmt-migrate-subscripting");
3641 CmdArgs.push_back("-objcmt-migrate-property");
3642 } else {
3643 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3644 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3645 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3647 } else {
3648 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3649 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3650 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3651 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3652 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3653 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3654 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3655 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3656 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3657 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3658 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3659 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3660 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3661 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3662 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3663 Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3667 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3668 const ArgList &Args, ArgStringList &CmdArgs) {
3669 // -fbuiltin is default unless -mkernel is used.
3670 bool UseBuiltins =
3671 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3672 !Args.hasArg(options::OPT_mkernel));
3673 if (!UseBuiltins)
3674 CmdArgs.push_back("-fno-builtin");
3676 // -ffreestanding implies -fno-builtin.
3677 if (Args.hasArg(options::OPT_ffreestanding))
3678 UseBuiltins = false;
3680 // Process the -fno-builtin-* options.
3681 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3682 A->claim();
3684 // If -fno-builtin is specified, then there's no need to pass the option to
3685 // the frontend.
3686 if (UseBuiltins)
3687 A->render(Args, CmdArgs);
3690 // le32-specific flags:
3691 // -fno-math-builtin: clang should not convert math builtins to intrinsics
3692 // by default.
3693 if (TC.getArch() == llvm::Triple::le32)
3694 CmdArgs.push_back("-fno-math-builtin");
3697 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3698 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3699 Twine Path{Str};
3700 Path.toVector(Result);
3701 return Path.getSingleStringRef() != "";
3703 if (llvm::sys::path::cache_directory(Result)) {
3704 llvm::sys::path::append(Result, "clang");
3705 llvm::sys::path::append(Result, "ModuleCache");
3706 return true;
3708 return false;
3711 static bool RenderModulesOptions(Compilation &C, const Driver &D,
3712 const ArgList &Args, const InputInfo &Input,
3713 const InputInfo &Output, bool HaveStd20,
3714 ArgStringList &CmdArgs) {
3715 bool IsCXX = types::isCXX(Input.getType());
3716 bool HaveStdCXXModules = IsCXX && HaveStd20;
3717 bool HaveModules = HaveStdCXXModules;
3719 // -fmodules enables the use of precompiled modules (off by default).
3720 // Users can pass -fno-cxx-modules to turn off modules support for
3721 // C++/Objective-C++ programs.
3722 bool HaveClangModules = false;
3723 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3724 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3725 options::OPT_fno_cxx_modules, true);
3726 if (AllowedInCXX || !IsCXX) {
3727 CmdArgs.push_back("-fmodules");
3728 HaveClangModules = true;
3732 HaveModules |= HaveClangModules;
3734 // -fmodule-maps enables implicit reading of module map files. By default,
3735 // this is enabled if we are using Clang's flavor of precompiled modules.
3736 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3737 options::OPT_fno_implicit_module_maps, HaveClangModules))
3738 CmdArgs.push_back("-fimplicit-module-maps");
3740 // -fmodules-decluse checks that modules used are declared so (off by default)
3741 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3742 options::OPT_fno_modules_decluse);
3744 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3745 // all #included headers are part of modules.
3746 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3747 options::OPT_fno_modules_strict_decluse, false))
3748 CmdArgs.push_back("-fmodules-strict-decluse");
3750 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3751 bool ImplicitModules = false;
3752 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3753 options::OPT_fno_implicit_modules, HaveClangModules)) {
3754 if (HaveModules)
3755 CmdArgs.push_back("-fno-implicit-modules");
3756 } else if (HaveModules) {
3757 ImplicitModules = true;
3758 // -fmodule-cache-path specifies where our implicitly-built module files
3759 // should be written.
3760 SmallString<128> Path;
3761 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3762 Path = A->getValue();
3764 bool HasPath = true;
3765 if (C.isForDiagnostics()) {
3766 // When generating crash reports, we want to emit the modules along with
3767 // the reproduction sources, so we ignore any provided module path.
3768 Path = Output.getFilename();
3769 llvm::sys::path::replace_extension(Path, ".cache");
3770 llvm::sys::path::append(Path, "modules");
3771 } else if (Path.empty()) {
3772 // No module path was provided: use the default.
3773 HasPath = Driver::getDefaultModuleCachePath(Path);
3776 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3777 // That being said, that failure is unlikely and not caching is harmless.
3778 if (HasPath) {
3779 const char Arg[] = "-fmodules-cache-path=";
3780 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3781 CmdArgs.push_back(Args.MakeArgString(Path));
3785 if (HaveModules) {
3786 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3787 options::OPT_fno_prebuilt_implicit_modules, false))
3788 CmdArgs.push_back("-fprebuilt-implicit-modules");
3789 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3790 options::OPT_fno_modules_validate_input_files_content,
3791 false))
3792 CmdArgs.push_back("-fvalidate-ast-input-files-content");
3795 // -fmodule-name specifies the module that is currently being built (or
3796 // used for header checking by -fmodule-maps).
3797 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3799 // -fmodule-map-file can be used to specify files containing module
3800 // definitions.
3801 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3803 // -fbuiltin-module-map can be used to load the clang
3804 // builtin headers modulemap file.
3805 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3806 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3807 llvm::sys::path::append(BuiltinModuleMap, "include");
3808 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3809 if (llvm::sys::fs::exists(BuiltinModuleMap))
3810 CmdArgs.push_back(
3811 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3814 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3815 // names to precompiled module files (the module is loaded only if used).
3816 // The -fmodule-file=<file> form can be used to unconditionally load
3817 // precompiled module files (whether used or not).
3818 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3819 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3821 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3822 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3823 CmdArgs.push_back(Args.MakeArgString(
3824 std::string("-fprebuilt-module-path=") + A->getValue()));
3825 A->claim();
3827 } else
3828 Args.ClaimAllArgs(options::OPT_fmodule_file);
3830 // When building modules and generating crashdumps, we need to dump a module
3831 // dependency VFS alongside the output.
3832 if (HaveClangModules && C.isForDiagnostics()) {
3833 SmallString<128> VFSDir(Output.getFilename());
3834 llvm::sys::path::replace_extension(VFSDir, ".cache");
3835 // Add the cache directory as a temp so the crash diagnostics pick it up.
3836 C.addTempFile(Args.MakeArgString(VFSDir));
3838 llvm::sys::path::append(VFSDir, "vfs");
3839 CmdArgs.push_back("-module-dependency-dir");
3840 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3843 if (HaveClangModules)
3844 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3846 // Pass through all -fmodules-ignore-macro arguments.
3847 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3848 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3849 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3851 if (HaveClangModules) {
3852 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3854 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3855 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3856 D.Diag(diag::err_drv_argument_not_allowed_with)
3857 << A->getAsString(Args) << "-fbuild-session-timestamp";
3859 llvm::sys::fs::file_status Status;
3860 if (llvm::sys::fs::status(A->getValue(), Status))
3861 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3862 CmdArgs.push_back(Args.MakeArgString(
3863 "-fbuild-session-timestamp=" +
3864 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3865 Status.getLastModificationTime().time_since_epoch())
3866 .count())));
3869 if (Args.getLastArg(
3870 options::OPT_fmodules_validate_once_per_build_session)) {
3871 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3872 options::OPT_fbuild_session_file))
3873 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3875 Args.AddLastArg(CmdArgs,
3876 options::OPT_fmodules_validate_once_per_build_session);
3879 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3880 options::OPT_fno_modules_validate_system_headers,
3881 ImplicitModules))
3882 CmdArgs.push_back("-fmodules-validate-system-headers");
3884 Args.AddLastArg(CmdArgs,
3885 options::OPT_fmodules_disable_diagnostic_validation);
3886 } else {
3887 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3888 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3889 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3890 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3891 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3892 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3895 // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
3896 Args.ClaimAllArgs(options::OPT_fmodule_output);
3897 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
3899 return HaveModules;
3902 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3903 ArgStringList &CmdArgs) {
3904 // -fsigned-char is default.
3905 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3906 options::OPT_fno_signed_char,
3907 options::OPT_funsigned_char,
3908 options::OPT_fno_unsigned_char)) {
3909 if (A->getOption().matches(options::OPT_funsigned_char) ||
3910 A->getOption().matches(options::OPT_fno_signed_char)) {
3911 CmdArgs.push_back("-fno-signed-char");
3913 } else if (!isSignedCharDefault(T)) {
3914 CmdArgs.push_back("-fno-signed-char");
3917 // The default depends on the language standard.
3918 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3920 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3921 options::OPT_fno_short_wchar)) {
3922 if (A->getOption().matches(options::OPT_fshort_wchar)) {
3923 CmdArgs.push_back("-fwchar-type=short");
3924 CmdArgs.push_back("-fno-signed-wchar");
3925 } else {
3926 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3927 CmdArgs.push_back("-fwchar-type=int");
3928 if (T.isOSzOS() ||
3929 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3930 CmdArgs.push_back("-fno-signed-wchar");
3931 else
3932 CmdArgs.push_back("-fsigned-wchar");
3934 } else if (T.isOSzOS())
3935 CmdArgs.push_back("-fno-signed-wchar");
3938 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3939 const llvm::Triple &T, const ArgList &Args,
3940 ObjCRuntime &Runtime, bool InferCovariantReturns,
3941 const InputInfo &Input, ArgStringList &CmdArgs) {
3942 const llvm::Triple::ArchType Arch = TC.getArch();
3944 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3945 // is the default. Except for deployment target of 10.5, next runtime is
3946 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3947 if (Runtime.isNonFragile()) {
3948 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3949 options::OPT_fno_objc_legacy_dispatch,
3950 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3951 if (TC.UseObjCMixedDispatch())
3952 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3953 else
3954 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3958 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3959 // to do Array/Dictionary subscripting by default.
3960 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3961 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3962 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3964 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3965 // NOTE: This logic is duplicated in ToolChains.cpp.
3966 if (isObjCAutoRefCount(Args)) {
3967 TC.CheckObjCARC();
3969 CmdArgs.push_back("-fobjc-arc");
3971 // FIXME: It seems like this entire block, and several around it should be
3972 // wrapped in isObjC, but for now we just use it here as this is where it
3973 // was being used previously.
3974 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3975 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3976 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3977 else
3978 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3981 // Allow the user to enable full exceptions code emission.
3982 // We default off for Objective-C, on for Objective-C++.
3983 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3984 options::OPT_fno_objc_arc_exceptions,
3985 /*Default=*/types::isCXX(Input.getType())))
3986 CmdArgs.push_back("-fobjc-arc-exceptions");
3989 // Silence warning for full exception code emission options when explicitly
3990 // set to use no ARC.
3991 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3992 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3993 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3996 // Allow the user to control whether messages can be converted to runtime
3997 // functions.
3998 if (types::isObjC(Input.getType())) {
3999 auto *Arg = Args.getLastArg(
4000 options::OPT_fobjc_convert_messages_to_runtime_calls,
4001 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4002 if (Arg &&
4003 Arg->getOption().matches(
4004 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4005 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4008 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4009 // rewriter.
4010 if (InferCovariantReturns)
4011 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4013 // Pass down -fobjc-weak or -fno-objc-weak if present.
4014 if (types::isObjC(Input.getType())) {
4015 auto WeakArg =
4016 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4017 if (!WeakArg) {
4018 // nothing to do
4019 } else if (!Runtime.allowsWeak()) {
4020 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4021 D.Diag(diag::err_objc_weak_unsupported);
4022 } else {
4023 WeakArg->render(Args, CmdArgs);
4027 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4028 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4031 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4032 ArgStringList &CmdArgs) {
4033 bool CaretDefault = true;
4034 bool ColumnDefault = true;
4036 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4037 options::OPT__SLASH_diagnostics_column,
4038 options::OPT__SLASH_diagnostics_caret)) {
4039 switch (A->getOption().getID()) {
4040 case options::OPT__SLASH_diagnostics_caret:
4041 CaretDefault = true;
4042 ColumnDefault = true;
4043 break;
4044 case options::OPT__SLASH_diagnostics_column:
4045 CaretDefault = false;
4046 ColumnDefault = true;
4047 break;
4048 case options::OPT__SLASH_diagnostics_classic:
4049 CaretDefault = false;
4050 ColumnDefault = false;
4051 break;
4055 // -fcaret-diagnostics is default.
4056 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4057 options::OPT_fno_caret_diagnostics, CaretDefault))
4058 CmdArgs.push_back("-fno-caret-diagnostics");
4060 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4061 options::OPT_fno_diagnostics_fixit_info);
4062 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4063 options::OPT_fno_diagnostics_show_option);
4065 if (const Arg *A =
4066 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4067 CmdArgs.push_back("-fdiagnostics-show-category");
4068 CmdArgs.push_back(A->getValue());
4071 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4072 options::OPT_fno_diagnostics_show_hotness);
4074 if (const Arg *A =
4075 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4076 std::string Opt =
4077 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4078 CmdArgs.push_back(Args.MakeArgString(Opt));
4081 if (const Arg *A =
4082 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4083 std::string Opt =
4084 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4085 CmdArgs.push_back(Args.MakeArgString(Opt));
4088 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4089 CmdArgs.push_back("-fdiagnostics-format");
4090 CmdArgs.push_back(A->getValue());
4091 if (StringRef(A->getValue()) == "sarif" ||
4092 StringRef(A->getValue()) == "SARIF")
4093 D.Diag(diag::warn_drv_sarif_format_unstable);
4096 if (const Arg *A = Args.getLastArg(
4097 options::OPT_fdiagnostics_show_note_include_stack,
4098 options::OPT_fno_diagnostics_show_note_include_stack)) {
4099 const Option &O = A->getOption();
4100 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4101 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4102 else
4103 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4106 // Color diagnostics are parsed by the driver directly from argv and later
4107 // re-parsed to construct this job; claim any possible color diagnostic here
4108 // to avoid warn_drv_unused_argument and diagnose bad
4109 // OPT_fdiagnostics_color_EQ values.
4110 Args.getLastArg(options::OPT_fcolor_diagnostics,
4111 options::OPT_fno_color_diagnostics);
4112 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4113 StringRef Value(A->getValue());
4114 if (Value != "always" && Value != "never" && Value != "auto")
4115 D.Diag(diag::err_drv_invalid_argument_to_option)
4116 << Value << A->getOption().getName();
4119 if (D.getDiags().getDiagnosticOptions().ShowColors)
4120 CmdArgs.push_back("-fcolor-diagnostics");
4122 if (Args.hasArg(options::OPT_fansi_escape_codes))
4123 CmdArgs.push_back("-fansi-escape-codes");
4125 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4126 options::OPT_fno_show_source_location);
4128 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4129 options::OPT_fno_diagnostics_show_line_numbers);
4131 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4132 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4134 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4135 ColumnDefault))
4136 CmdArgs.push_back("-fno-show-column");
4138 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4139 options::OPT_fno_spell_checking);
4142 DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4143 const ArgList &Args, Arg *&Arg) {
4144 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4145 options::OPT_gno_split_dwarf);
4146 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4147 return DwarfFissionKind::None;
4149 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4150 return DwarfFissionKind::Split;
4152 StringRef Value = Arg->getValue();
4153 if (Value == "split")
4154 return DwarfFissionKind::Split;
4155 if (Value == "single")
4156 return DwarfFissionKind::Single;
4158 D.Diag(diag::err_drv_unsupported_option_argument)
4159 << Arg->getSpelling() << Arg->getValue();
4160 return DwarfFissionKind::None;
4163 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4164 const ArgList &Args, ArgStringList &CmdArgs,
4165 unsigned DwarfVersion) {
4166 auto *DwarfFormatArg =
4167 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4168 if (!DwarfFormatArg)
4169 return;
4171 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4172 if (DwarfVersion < 3)
4173 D.Diag(diag::err_drv_argument_only_allowed_with)
4174 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4175 else if (!T.isArch64Bit())
4176 D.Diag(diag::err_drv_argument_only_allowed_with)
4177 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4178 else if (!T.isOSBinFormatELF())
4179 D.Diag(diag::err_drv_argument_only_allowed_with)
4180 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4183 DwarfFormatArg->render(Args, CmdArgs);
4186 static void
4187 renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4188 const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4189 const InputInfo &Output,
4190 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4191 DwarfFissionKind &DwarfFission) {
4192 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4193 options::OPT_fno_debug_info_for_profiling, false) &&
4194 checkDebugInfoOption(
4195 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4196 CmdArgs.push_back("-fdebug-info-for-profiling");
4198 // The 'g' groups options involve a somewhat intricate sequence of decisions
4199 // about what to pass from the driver to the frontend, but by the time they
4200 // reach cc1 they've been factored into three well-defined orthogonal choices:
4201 // * what level of debug info to generate
4202 // * what dwarf version to write
4203 // * what debugger tuning to use
4204 // This avoids having to monkey around further in cc1 other than to disable
4205 // codeview if not running in a Windows environment. Perhaps even that
4206 // decision should be made in the driver as well though.
4207 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4209 bool SplitDWARFInlining =
4210 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4211 options::OPT_fno_split_dwarf_inlining, false);
4213 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4214 // object file generation and no IR generation, -gN should not be needed. So
4215 // allow -gsplit-dwarf with either -gN or IR input.
4216 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4217 Arg *SplitDWARFArg;
4218 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4219 if (DwarfFission != DwarfFissionKind::None &&
4220 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4221 DwarfFission = DwarfFissionKind::None;
4222 SplitDWARFInlining = false;
4225 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4226 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4228 // If the last option explicitly specified a debug-info level, use it.
4229 if (checkDebugInfoOption(A, Args, D, TC) &&
4230 A->getOption().matches(options::OPT_gN_Group)) {
4231 DebugInfoKind = debugLevelToInfoKind(*A);
4232 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4233 // complicated if you've disabled inline info in the skeleton CUs
4234 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4235 // line-tables-only, so let those compose naturally in that case.
4236 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4237 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4238 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4239 SplitDWARFInlining))
4240 DwarfFission = DwarfFissionKind::None;
4244 // If a debugger tuning argument appeared, remember it.
4245 bool HasDebuggerTuning = false;
4246 if (const Arg *A =
4247 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4248 HasDebuggerTuning = true;
4249 if (checkDebugInfoOption(A, Args, D, TC)) {
4250 if (A->getOption().matches(options::OPT_glldb))
4251 DebuggerTuning = llvm::DebuggerKind::LLDB;
4252 else if (A->getOption().matches(options::OPT_gsce))
4253 DebuggerTuning = llvm::DebuggerKind::SCE;
4254 else if (A->getOption().matches(options::OPT_gdbx))
4255 DebuggerTuning = llvm::DebuggerKind::DBX;
4256 else
4257 DebuggerTuning = llvm::DebuggerKind::GDB;
4261 // If a -gdwarf argument appeared, remember it.
4262 bool EmitDwarf = false;
4263 if (const Arg *A = getDwarfNArg(Args))
4264 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4266 bool EmitCodeView = false;
4267 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4268 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4270 // If the user asked for debug info but did not explicitly specify -gcodeview
4271 // or -gdwarf, ask the toolchain for the default format.
4272 if (!EmitCodeView && !EmitDwarf &&
4273 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4274 switch (TC.getDefaultDebugFormat()) {
4275 case llvm::codegenoptions::DIF_CodeView:
4276 EmitCodeView = true;
4277 break;
4278 case llvm::codegenoptions::DIF_DWARF:
4279 EmitDwarf = true;
4280 break;
4284 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4285 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4286 // be lower than what the user wanted.
4287 if (EmitDwarf) {
4288 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4289 // Clamp effective DWARF version to the max supported by the toolchain.
4290 EffectiveDWARFVersion =
4291 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4292 } else {
4293 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4296 // -gline-directives-only supported only for the DWARF debug info.
4297 if (RequestedDWARFVersion == 0 &&
4298 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4299 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4301 // strict DWARF is set to false by default. But for DBX, we need it to be set
4302 // as true by default.
4303 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4304 (void)checkDebugInfoOption(A, Args, D, TC);
4305 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4306 DebuggerTuning == llvm::DebuggerKind::DBX))
4307 CmdArgs.push_back("-gstrict-dwarf");
4309 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4310 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4312 // Column info is included by default for everything except SCE and
4313 // CodeView. Clang doesn't track end columns, just starting columns, which,
4314 // in theory, is fine for CodeView (and PDB). In practice, however, the
4315 // Microsoft debuggers don't handle missing end columns well, and the AIX
4316 // debugger DBX also doesn't handle the columns well, so it's better not to
4317 // include any column info.
4318 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4319 (void)checkDebugInfoOption(A, Args, D, TC);
4320 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4321 !EmitCodeView &&
4322 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4323 DebuggerTuning != llvm::DebuggerKind::DBX)))
4324 CmdArgs.push_back("-gno-column-info");
4326 // FIXME: Move backend command line options to the module.
4327 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4328 // If -gline-tables-only or -gline-directives-only is the last option it
4329 // wins.
4330 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4331 TC)) {
4332 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4333 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4334 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4335 CmdArgs.push_back("-dwarf-ext-refs");
4336 CmdArgs.push_back("-fmodule-format=obj");
4341 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4342 CmdArgs.push_back("-fsplit-dwarf-inlining");
4344 // After we've dealt with all combinations of things that could
4345 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4346 // figure out if we need to "upgrade" it to standalone debug info.
4347 // We parse these two '-f' options whether or not they will be used,
4348 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4349 bool NeedFullDebug = Args.hasFlag(
4350 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4351 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4352 TC.GetDefaultStandaloneDebug());
4353 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4354 (void)checkDebugInfoOption(A, Args, D, TC);
4356 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4357 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4358 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4359 options::OPT_feliminate_unused_debug_types, false))
4360 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4361 else if (NeedFullDebug)
4362 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4365 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4366 false)) {
4367 // Source embedding is a vendor extension to DWARF v5. By now we have
4368 // checked if a DWARF version was stated explicitly, and have otherwise
4369 // fallen back to the target default, so if this is still not at least 5
4370 // we emit an error.
4371 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4372 if (RequestedDWARFVersion < 5)
4373 D.Diag(diag::err_drv_argument_only_allowed_with)
4374 << A->getAsString(Args) << "-gdwarf-5";
4375 else if (EffectiveDWARFVersion < 5)
4376 // The toolchain has reduced allowed dwarf version, so we can't enable
4377 // -gembed-source.
4378 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4379 << A->getAsString(Args) << TC.getTripleString() << 5
4380 << EffectiveDWARFVersion;
4381 else if (checkDebugInfoOption(A, Args, D, TC))
4382 CmdArgs.push_back("-gembed-source");
4385 if (EmitCodeView) {
4386 CmdArgs.push_back("-gcodeview");
4388 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4389 options::OPT_gno_codeview_ghash);
4391 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4392 options::OPT_gno_codeview_command_line);
4395 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4396 options::OPT_gno_inline_line_tables);
4398 // When emitting remarks, we need at least debug lines in the output.
4399 if (willEmitRemarks(Args) &&
4400 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4401 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4403 // Adjust the debug info kind for the given toolchain.
4404 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4406 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4407 // set.
4408 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4409 T.isOSAIX() && !HasDebuggerTuning
4410 ? llvm::DebuggerKind::Default
4411 : DebuggerTuning);
4413 // -fdebug-macro turns on macro debug info generation.
4414 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4415 false))
4416 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4417 D, TC))
4418 CmdArgs.push_back("-debug-info-macro");
4420 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4421 const auto *PubnamesArg =
4422 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4423 options::OPT_gpubnames, options::OPT_gno_pubnames);
4424 if (DwarfFission != DwarfFissionKind::None ||
4425 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4426 if (!PubnamesArg ||
4427 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4428 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4429 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4430 options::OPT_gpubnames)
4431 ? "-gpubnames"
4432 : "-ggnu-pubnames");
4433 const auto *SimpleTemplateNamesArg =
4434 Args.getLastArg(options::OPT_gsimple_template_names,
4435 options::OPT_gno_simple_template_names);
4436 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4437 if (SimpleTemplateNamesArg &&
4438 checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4439 const auto &Opt = SimpleTemplateNamesArg->getOption();
4440 if (Opt.matches(options::OPT_gsimple_template_names)) {
4441 ForwardTemplateParams = true;
4442 CmdArgs.push_back("-gsimple-template-names=simple");
4446 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4447 StringRef v = A->getValue();
4448 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4451 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4452 options::OPT_fno_debug_ranges_base_address);
4454 // -gdwarf-aranges turns on the emission of the aranges section in the
4455 // backend.
4456 // Always enabled for SCE tuning.
4457 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4458 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4459 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4460 if (NeedAranges) {
4461 CmdArgs.push_back("-mllvm");
4462 CmdArgs.push_back("-generate-arange-section");
4465 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4466 options::OPT_fno_force_dwarf_frame);
4468 if (Args.hasFlag(options::OPT_fdebug_types_section,
4469 options::OPT_fno_debug_types_section, false)) {
4470 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4471 D.Diag(diag::err_drv_unsupported_opt_for_target)
4472 << Args.getLastArg(options::OPT_fdebug_types_section)
4473 ->getAsString(Args)
4474 << T.getTriple();
4475 } else if (checkDebugInfoOption(
4476 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4477 TC)) {
4478 CmdArgs.push_back("-mllvm");
4479 CmdArgs.push_back("-generate-type-units");
4483 // To avoid join/split of directory+filename, the integrated assembler prefers
4484 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4485 // form before DWARF v5.
4486 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4487 options::OPT_fno_dwarf_directory_asm,
4488 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4489 CmdArgs.push_back("-fno-dwarf-directory-asm");
4491 // Decide how to render forward declarations of template instantiations.
4492 // SCE wants full descriptions, others just get them in the name.
4493 if (ForwardTemplateParams)
4494 CmdArgs.push_back("-debug-forward-template-params");
4496 // Do we need to explicitly import anonymous namespaces into the parent
4497 // scope?
4498 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4499 CmdArgs.push_back("-dwarf-explicit-import");
4501 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4502 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4504 // This controls whether or not we perform JustMyCode instrumentation.
4505 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4506 if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
4507 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4508 CmdArgs.push_back("-fjmc");
4509 else if (D.IsCLMode())
4510 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4511 << "'/Zi', '/Z7'";
4512 else
4513 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4514 << "-g";
4515 } else {
4516 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4520 // Add in -fdebug-compilation-dir if necessary.
4521 const char *DebugCompilationDir =
4522 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4524 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4526 // Add the output path to the object file for CodeView debug infos.
4527 if (EmitCodeView && Output.isFilename())
4528 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4529 Output.getFilename());
4532 static void ProcessVSRuntimeLibrary(const ArgList &Args,
4533 ArgStringList &CmdArgs) {
4534 unsigned RTOptionID = options::OPT__SLASH_MT;
4536 if (Args.hasArg(options::OPT__SLASH_LDd))
4537 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4538 // but defining _DEBUG is sticky.
4539 RTOptionID = options::OPT__SLASH_MTd;
4541 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4542 RTOptionID = A->getOption().getID();
4544 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4545 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4546 .Case("static", options::OPT__SLASH_MT)
4547 .Case("static_dbg", options::OPT__SLASH_MTd)
4548 .Case("dll", options::OPT__SLASH_MD)
4549 .Case("dll_dbg", options::OPT__SLASH_MDd)
4550 .Default(options::OPT__SLASH_MT);
4553 StringRef FlagForCRT;
4554 switch (RTOptionID) {
4555 case options::OPT__SLASH_MD:
4556 if (Args.hasArg(options::OPT__SLASH_LDd))
4557 CmdArgs.push_back("-D_DEBUG");
4558 CmdArgs.push_back("-D_MT");
4559 CmdArgs.push_back("-D_DLL");
4560 FlagForCRT = "--dependent-lib=msvcrt";
4561 break;
4562 case options::OPT__SLASH_MDd:
4563 CmdArgs.push_back("-D_DEBUG");
4564 CmdArgs.push_back("-D_MT");
4565 CmdArgs.push_back("-D_DLL");
4566 FlagForCRT = "--dependent-lib=msvcrtd";
4567 break;
4568 case options::OPT__SLASH_MT:
4569 if (Args.hasArg(options::OPT__SLASH_LDd))
4570 CmdArgs.push_back("-D_DEBUG");
4571 CmdArgs.push_back("-D_MT");
4572 CmdArgs.push_back("-flto-visibility-public-std");
4573 FlagForCRT = "--dependent-lib=libcmt";
4574 break;
4575 case options::OPT__SLASH_MTd:
4576 CmdArgs.push_back("-D_DEBUG");
4577 CmdArgs.push_back("-D_MT");
4578 CmdArgs.push_back("-flto-visibility-public-std");
4579 FlagForCRT = "--dependent-lib=libcmtd";
4580 break;
4581 default:
4582 llvm_unreachable("Unexpected option ID.");
4585 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4586 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4587 } else {
4588 CmdArgs.push_back(FlagForCRT.data());
4590 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4591 // users want. The /Za flag to cl.exe turns this off, but it's not
4592 // implemented in clang.
4593 CmdArgs.push_back("--dependent-lib=oldnames");
4597 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4598 const InputInfo &Output, const InputInfoList &Inputs,
4599 const ArgList &Args, const char *LinkingOutput) const {
4600 const auto &TC = getToolChain();
4601 const llvm::Triple &RawTriple = TC.getTriple();
4602 const llvm::Triple &Triple = TC.getEffectiveTriple();
4603 const std::string &TripleStr = Triple.getTriple();
4605 bool KernelOrKext =
4606 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4607 const Driver &D = TC.getDriver();
4608 ArgStringList CmdArgs;
4610 assert(Inputs.size() >= 1 && "Must have at least one input.");
4611 // CUDA/HIP compilation may have multiple inputs (source file + results of
4612 // device-side compilations). OpenMP device jobs also take the host IR as a
4613 // second input. Module precompilation accepts a list of header files to
4614 // include as part of the module. API extraction accepts a list of header
4615 // files whose API information is emitted in the output. All other jobs are
4616 // expected to have exactly one input.
4617 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4618 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4619 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4620 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4621 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4622 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4623 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4624 JA.isDeviceOffloading(Action::OFK_Host));
4625 bool IsHostOffloadingAction =
4626 JA.isHostOffloading(Action::OFK_OpenMP) ||
4627 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4628 Args.hasFlag(options::OPT_offload_new_driver,
4629 options::OPT_no_offload_new_driver, false));
4631 bool IsRDCMode =
4632 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4633 bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4634 auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4636 // Extract API doesn't have a main input file, so invent a fake one as a
4637 // placeholder.
4638 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4639 "extract-api");
4641 const InputInfo &Input =
4642 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4644 InputInfoList ExtractAPIInputs;
4645 InputInfoList HostOffloadingInputs;
4646 const InputInfo *CudaDeviceInput = nullptr;
4647 const InputInfo *OpenMPDeviceInput = nullptr;
4648 for (const InputInfo &I : Inputs) {
4649 if (&I == &Input || I.getType() == types::TY_Nothing) {
4650 // This is the primary input or contains nothing.
4651 } else if (IsExtractAPI) {
4652 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4653 if (I.getType() != ExpectedInputType) {
4654 D.Diag(diag::err_drv_extract_api_wrong_kind)
4655 << I.getFilename() << types::getTypeName(I.getType())
4656 << types::getTypeName(ExpectedInputType);
4658 ExtractAPIInputs.push_back(I);
4659 } else if (IsHostOffloadingAction) {
4660 HostOffloadingInputs.push_back(I);
4661 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4662 CudaDeviceInput = &I;
4663 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4664 OpenMPDeviceInput = &I;
4665 } else {
4666 llvm_unreachable("unexpectedly given multiple inputs");
4670 const llvm::Triple *AuxTriple =
4671 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4672 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4673 bool IsIAMCU = RawTriple.isOSIAMCU();
4675 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
4676 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4677 // Windows), we need to pass Windows-specific flags to cc1.
4678 if (IsCuda || IsHIP)
4679 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4681 // C++ is not supported for IAMCU.
4682 if (IsIAMCU && types::isCXX(Input.getType()))
4683 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4685 // Invoke ourselves in -cc1 mode.
4687 // FIXME: Implement custom jobs for internal actions.
4688 CmdArgs.push_back("-cc1");
4690 // Add the "effective" target triple.
4691 CmdArgs.push_back("-triple");
4692 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4694 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4695 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4696 Args.ClaimAllArgs(options::OPT_MJ);
4697 } else if (const Arg *GenCDBFragment =
4698 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4699 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4700 TripleStr, Output, Input, Args);
4701 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4704 if (IsCuda || IsHIP) {
4705 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4706 // and vice-versa.
4707 std::string NormalizedTriple;
4708 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4709 JA.isDeviceOffloading(Action::OFK_HIP))
4710 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4711 ->getTriple()
4712 .normalize();
4713 else {
4714 // Host-side compilation.
4715 NormalizedTriple =
4716 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4717 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4718 ->getTriple()
4719 .normalize();
4720 if (IsCuda) {
4721 // We need to figure out which CUDA version we're compiling for, as that
4722 // determines how we load and launch GPU kernels.
4723 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4724 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4725 assert(CTC && "Expected valid CUDA Toolchain.");
4726 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4727 CmdArgs.push_back(Args.MakeArgString(
4728 Twine("-target-sdk-version=") +
4729 CudaVersionToString(CTC->CudaInstallation.version())));
4730 // Unsized function arguments used for variadics were introduced in
4731 // CUDA-9.0. We still do not support generating code that actually uses
4732 // variadic arguments yet, but we do need to allow parsing them as
4733 // recent CUDA headers rely on that.
4734 // https://github.com/llvm/llvm-project/issues/58410
4735 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
4736 CmdArgs.push_back("-fcuda-allow-variadic-functions");
4739 CmdArgs.push_back("-aux-triple");
4740 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4742 if (JA.isDeviceOffloading(Action::OFK_HIP) &&
4743 getToolChain().getTriple().isAMDGPU()) {
4744 // Device side compilation printf
4745 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
4746 CmdArgs.push_back(Args.MakeArgString(
4747 "-mprintf-kind=" +
4748 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
4749 // Force compiler error on invalid conversion specifiers
4750 CmdArgs.push_back(
4751 Args.MakeArgString("-Werror=format-invalid-specifier"));
4756 // Unconditionally claim the printf option now to avoid unused diagnostic.
4757 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
4758 PF->claim();
4760 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4761 CmdArgs.push_back("-fsycl-is-device");
4763 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4764 A->render(Args, CmdArgs);
4765 } else {
4766 // Ensure the default version in SYCL mode is 2020.
4767 CmdArgs.push_back("-sycl-std=2020");
4771 if (IsOpenMPDevice) {
4772 // We have to pass the triple of the host if compiling for an OpenMP device.
4773 std::string NormalizedTriple =
4774 C.getSingleOffloadToolChain<Action::OFK_Host>()
4775 ->getTriple()
4776 .normalize();
4777 CmdArgs.push_back("-aux-triple");
4778 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4781 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4782 Triple.getArch() == llvm::Triple::thumb)) {
4783 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4784 unsigned Version = 0;
4785 bool Failure =
4786 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4787 if (Failure || Version < 7)
4788 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4789 << TripleStr;
4792 // Push all default warning arguments that are specific to
4793 // the given target. These come before user provided warning options
4794 // are provided.
4795 TC.addClangWarningOptions(CmdArgs);
4797 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4798 if (Triple.isSPIR() || Triple.isSPIRV())
4799 CmdArgs.push_back("-Wspir-compat");
4801 // Select the appropriate action.
4802 RewriteKind rewriteKind = RK_None;
4804 bool UnifiedLTO = false;
4805 if (IsUsingLTO) {
4806 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
4807 options::OPT_fno_unified_lto, Triple.isPS()) ||
4808 Args.hasFlag(options::OPT_ffat_lto_objects,
4809 options::OPT_fno_fat_lto_objects, false);
4810 if (UnifiedLTO)
4811 CmdArgs.push_back("-funified-lto");
4814 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4815 // it claims when not running an assembler. Otherwise, clang would emit
4816 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4817 // flags while debugging something. That'd be somewhat inconvenient, and it's
4818 // also inconsistent with most other flags -- we don't warn on
4819 // -ffunction-sections not being used in -E mode either for example, even
4820 // though it's not really used either.
4821 if (!isa<AssembleJobAction>(JA)) {
4822 // The args claimed here should match the args used in
4823 // CollectArgsForIntegratedAssembler().
4824 if (TC.useIntegratedAs()) {
4825 Args.ClaimAllArgs(options::OPT_mrelax_all);
4826 Args.ClaimAllArgs(options::OPT_mno_relax_all);
4827 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4828 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4829 switch (C.getDefaultToolChain().getArch()) {
4830 case llvm::Triple::arm:
4831 case llvm::Triple::armeb:
4832 case llvm::Triple::thumb:
4833 case llvm::Triple::thumbeb:
4834 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4835 break;
4836 default:
4837 break;
4840 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4841 Args.ClaimAllArgs(options::OPT_Xassembler);
4842 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4845 if (isa<AnalyzeJobAction>(JA)) {
4846 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4847 CmdArgs.push_back("-analyze");
4848 } else if (isa<MigrateJobAction>(JA)) {
4849 CmdArgs.push_back("-migrate");
4850 } else if (isa<PreprocessJobAction>(JA)) {
4851 if (Output.getType() == types::TY_Dependencies)
4852 CmdArgs.push_back("-Eonly");
4853 else {
4854 CmdArgs.push_back("-E");
4855 if (Args.hasArg(options::OPT_rewrite_objc) &&
4856 !Args.hasArg(options::OPT_g_Group))
4857 CmdArgs.push_back("-P");
4858 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
4859 CmdArgs.push_back("-fdirectives-only");
4861 } else if (isa<AssembleJobAction>(JA)) {
4862 CmdArgs.push_back("-emit-obj");
4864 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4866 // Also ignore explicit -force_cpusubtype_ALL option.
4867 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4868 } else if (isa<PrecompileJobAction>(JA)) {
4869 if (JA.getType() == types::TY_Nothing)
4870 CmdArgs.push_back("-fsyntax-only");
4871 else if (JA.getType() == types::TY_ModuleFile)
4872 CmdArgs.push_back("-emit-module-interface");
4873 else if (JA.getType() == types::TY_HeaderUnit)
4874 CmdArgs.push_back("-emit-header-unit");
4875 else
4876 CmdArgs.push_back("-emit-pch");
4877 } else if (isa<VerifyPCHJobAction>(JA)) {
4878 CmdArgs.push_back("-verify-pch");
4879 } else if (isa<ExtractAPIJobAction>(JA)) {
4880 assert(JA.getType() == types::TY_API_INFO &&
4881 "Extract API actions must generate a API information.");
4882 CmdArgs.push_back("-extract-api");
4883 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
4884 ProductNameArg->render(Args, CmdArgs);
4885 if (Arg *ExtractAPIIgnoresFileArg =
4886 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
4887 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
4888 } else {
4889 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4890 "Invalid action for clang tool.");
4891 if (JA.getType() == types::TY_Nothing) {
4892 CmdArgs.push_back("-fsyntax-only");
4893 } else if (JA.getType() == types::TY_LLVM_IR ||
4894 JA.getType() == types::TY_LTO_IR) {
4895 CmdArgs.push_back("-emit-llvm");
4896 } else if (JA.getType() == types::TY_LLVM_BC ||
4897 JA.getType() == types::TY_LTO_BC) {
4898 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4899 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4900 Args.hasArg(options::OPT_emit_llvm)) {
4901 CmdArgs.push_back("-emit-llvm");
4902 } else {
4903 CmdArgs.push_back("-emit-llvm-bc");
4905 } else if (JA.getType() == types::TY_IFS ||
4906 JA.getType() == types::TY_IFS_CPP) {
4907 StringRef ArgStr =
4908 Args.hasArg(options::OPT_interface_stub_version_EQ)
4909 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4910 : "ifs-v1";
4911 CmdArgs.push_back("-emit-interface-stubs");
4912 CmdArgs.push_back(
4913 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4914 } else if (JA.getType() == types::TY_PP_Asm) {
4915 CmdArgs.push_back("-S");
4916 } else if (JA.getType() == types::TY_AST) {
4917 CmdArgs.push_back("-emit-pch");
4918 } else if (JA.getType() == types::TY_ModuleFile) {
4919 CmdArgs.push_back("-module-file-info");
4920 } else if (JA.getType() == types::TY_RewrittenObjC) {
4921 CmdArgs.push_back("-rewrite-objc");
4922 rewriteKind = RK_NonFragile;
4923 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4924 CmdArgs.push_back("-rewrite-objc");
4925 rewriteKind = RK_Fragile;
4926 } else {
4927 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4930 // Preserve use-list order by default when emitting bitcode, so that
4931 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4932 // same result as running passes here. For LTO, we don't need to preserve
4933 // the use-list order, since serialization to bitcode is part of the flow.
4934 if (JA.getType() == types::TY_LLVM_BC)
4935 CmdArgs.push_back("-emit-llvm-uselists");
4937 if (IsUsingLTO) {
4938 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
4939 !Args.hasFlag(options::OPT_offload_new_driver,
4940 options::OPT_no_offload_new_driver, false) &&
4941 !Triple.isAMDGPU()) {
4942 D.Diag(diag::err_drv_unsupported_opt_for_target)
4943 << Args.getLastArg(options::OPT_foffload_lto,
4944 options::OPT_foffload_lto_EQ)
4945 ->getAsString(Args)
4946 << Triple.getTriple();
4947 } else if (Triple.isNVPTX() && !IsRDCMode &&
4948 JA.isDeviceOffloading(Action::OFK_Cuda)) {
4949 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
4950 << Args.getLastArg(options::OPT_foffload_lto,
4951 options::OPT_foffload_lto_EQ)
4952 ->getAsString(Args)
4953 << "-fno-gpu-rdc";
4954 } else {
4955 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4956 CmdArgs.push_back(Args.MakeArgString(
4957 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4958 // PS4 uses the legacy LTO API, which does not support some of the
4959 // features enabled by -flto-unit.
4960 if (!RawTriple.isPS4() ||
4961 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
4962 CmdArgs.push_back("-flto-unit");
4967 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
4969 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4970 if (!types::isLLVMIR(Input.getType()))
4971 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4972 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4975 if (Triple.isPPC())
4976 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
4977 options::OPT_mno_regnames);
4979 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4980 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4982 if (Args.getLastArg(options::OPT_save_temps_EQ))
4983 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4985 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4986 options::OPT_fmemory_profile_EQ,
4987 options::OPT_fno_memory_profile);
4988 if (MemProfArg &&
4989 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4990 MemProfArg->render(Args, CmdArgs);
4992 if (auto *MemProfUseArg =
4993 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
4994 if (MemProfArg)
4995 D.Diag(diag::err_drv_argument_not_allowed_with)
4996 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
4997 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
4998 options::OPT_fprofile_generate_EQ))
4999 D.Diag(diag::err_drv_argument_not_allowed_with)
5000 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5001 MemProfUseArg->render(Args, CmdArgs);
5004 // Embed-bitcode option.
5005 // Only white-listed flags below are allowed to be embedded.
5006 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5007 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
5008 // Add flags implied by -fembed-bitcode.
5009 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5010 // Disable all llvm IR level optimizations.
5011 CmdArgs.push_back("-disable-llvm-passes");
5013 // Render target options.
5014 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5016 // reject options that shouldn't be supported in bitcode
5017 // also reject kernel/kext
5018 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5019 options::OPT_mkernel,
5020 options::OPT_fapple_kext,
5021 options::OPT_ffunction_sections,
5022 options::OPT_fno_function_sections,
5023 options::OPT_fdata_sections,
5024 options::OPT_fno_data_sections,
5025 options::OPT_fbasic_block_sections_EQ,
5026 options::OPT_funique_internal_linkage_names,
5027 options::OPT_fno_unique_internal_linkage_names,
5028 options::OPT_funique_section_names,
5029 options::OPT_fno_unique_section_names,
5030 options::OPT_funique_basic_block_section_names,
5031 options::OPT_fno_unique_basic_block_section_names,
5032 options::OPT_mrestrict_it,
5033 options::OPT_mno_restrict_it,
5034 options::OPT_mstackrealign,
5035 options::OPT_mno_stackrealign,
5036 options::OPT_mstack_alignment,
5037 options::OPT_mcmodel_EQ,
5038 options::OPT_mlong_calls,
5039 options::OPT_mno_long_calls,
5040 options::OPT_ggnu_pubnames,
5041 options::OPT_gdwarf_aranges,
5042 options::OPT_fdebug_types_section,
5043 options::OPT_fno_debug_types_section,
5044 options::OPT_fdwarf_directory_asm,
5045 options::OPT_fno_dwarf_directory_asm,
5046 options::OPT_mrelax_all,
5047 options::OPT_mno_relax_all,
5048 options::OPT_ftrap_function_EQ,
5049 options::OPT_ffixed_r9,
5050 options::OPT_mfix_cortex_a53_835769,
5051 options::OPT_mno_fix_cortex_a53_835769,
5052 options::OPT_ffixed_x18,
5053 options::OPT_mglobal_merge,
5054 options::OPT_mno_global_merge,
5055 options::OPT_mred_zone,
5056 options::OPT_mno_red_zone,
5057 options::OPT_Wa_COMMA,
5058 options::OPT_Xassembler,
5059 options::OPT_mllvm,
5061 for (const auto &A : Args)
5062 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5063 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5065 // Render the CodeGen options that need to be passed.
5066 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5067 options::OPT_fno_optimize_sibling_calls);
5069 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
5070 CmdArgs, JA);
5072 // Render ABI arguments
5073 switch (TC.getArch()) {
5074 default: break;
5075 case llvm::Triple::arm:
5076 case llvm::Triple::armeb:
5077 case llvm::Triple::thumbeb:
5078 RenderARMABI(D, Triple, Args, CmdArgs);
5079 break;
5080 case llvm::Triple::aarch64:
5081 case llvm::Triple::aarch64_32:
5082 case llvm::Triple::aarch64_be:
5083 RenderAArch64ABI(Triple, Args, CmdArgs);
5084 break;
5087 // Optimization level for CodeGen.
5088 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5089 if (A->getOption().matches(options::OPT_O4)) {
5090 CmdArgs.push_back("-O3");
5091 D.Diag(diag::warn_O4_is_O3);
5092 } else {
5093 A->render(Args, CmdArgs);
5097 // Input/Output file.
5098 if (Output.getType() == types::TY_Dependencies) {
5099 // Handled with other dependency code.
5100 } else if (Output.isFilename()) {
5101 CmdArgs.push_back("-o");
5102 CmdArgs.push_back(Output.getFilename());
5103 } else {
5104 assert(Output.isNothing() && "Input output.");
5107 for (const auto &II : Inputs) {
5108 addDashXForInput(Args, II, CmdArgs);
5109 if (II.isFilename())
5110 CmdArgs.push_back(II.getFilename());
5111 else
5112 II.getInputArg().renderAsInput(Args, CmdArgs);
5115 C.addCommand(std::make_unique<Command>(
5116 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5117 CmdArgs, Inputs, Output, D.getPrependArg()));
5118 return;
5121 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5122 CmdArgs.push_back("-fembed-bitcode=marker");
5124 // We normally speed up the clang process a bit by skipping destructors at
5125 // exit, but when we're generating diagnostics we can rely on some of the
5126 // cleanup.
5127 if (!C.isForDiagnostics())
5128 CmdArgs.push_back("-disable-free");
5129 CmdArgs.push_back("-clear-ast-before-backend");
5131 #ifdef NDEBUG
5132 const bool IsAssertBuild = false;
5133 #else
5134 const bool IsAssertBuild = true;
5135 #endif
5137 // Disable the verification pass in asserts builds unless otherwise specified.
5138 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5139 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5140 CmdArgs.push_back("-disable-llvm-verifier");
5143 // Discard value names in assert builds unless otherwise specified.
5144 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5145 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5146 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5147 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5148 return types::isLLVMIR(II.getType());
5149 })) {
5150 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5152 CmdArgs.push_back("-discard-value-names");
5155 // Set the main file name, so that debug info works even with
5156 // -save-temps.
5157 CmdArgs.push_back("-main-file-name");
5158 CmdArgs.push_back(getBaseInputName(Args, Input));
5160 // Some flags which affect the language (via preprocessor
5161 // defines).
5162 if (Args.hasArg(options::OPT_static))
5163 CmdArgs.push_back("-static-define");
5165 if (Args.hasArg(options::OPT_municode))
5166 CmdArgs.push_back("-DUNICODE");
5168 if (isa<AnalyzeJobAction>(JA))
5169 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5171 if (isa<AnalyzeJobAction>(JA) ||
5172 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5173 CmdArgs.push_back("-setup-static-analyzer");
5175 // Enable compatilibily mode to avoid analyzer-config related errors.
5176 // Since we can't access frontend flags through hasArg, let's manually iterate
5177 // through them.
5178 bool FoundAnalyzerConfig = false;
5179 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5180 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5181 FoundAnalyzerConfig = true;
5182 break;
5184 if (!FoundAnalyzerConfig)
5185 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5186 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5187 FoundAnalyzerConfig = true;
5188 break;
5190 if (FoundAnalyzerConfig)
5191 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5193 CheckCodeGenerationOptions(D, Args);
5195 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5196 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5197 if (FunctionAlignment) {
5198 CmdArgs.push_back("-function-alignment");
5199 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5202 // We support -falign-loops=N where N is a power of 2. GCC supports more
5203 // forms.
5204 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5205 unsigned Value = 0;
5206 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5207 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5208 << A->getAsString(Args) << A->getValue();
5209 else if (Value & (Value - 1))
5210 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5211 << A->getAsString(Args) << A->getValue();
5212 // Treat =0 as unspecified (use the target preference).
5213 if (Value)
5214 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5215 Twine(std::min(Value, 65536u))));
5218 if (Triple.isOSzOS()) {
5219 // On z/OS some of the system header feature macros need to
5220 // be defined to enable most cross platform projects to build
5221 // successfully. Ths include the libc++ library. A
5222 // complicating factor is that users can define these
5223 // macros to the same or different values. We need to add
5224 // the definition for these macros to the compilation command
5225 // if the user hasn't already defined them.
5227 auto findMacroDefinition = [&](const std::string &Macro) {
5228 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5229 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5230 return M == Macro || M.find(Macro + '=') != std::string::npos;
5234 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5235 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5236 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5237 // _OPEN_DEFAULT is required for XL compat
5238 if (!findMacroDefinition("_OPEN_DEFAULT"))
5239 CmdArgs.push_back("-D_OPEN_DEFAULT");
5240 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5241 // _XOPEN_SOURCE=600 is required for libcxx.
5242 if (!findMacroDefinition("_XOPEN_SOURCE"))
5243 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5247 llvm::Reloc::Model RelocationModel;
5248 unsigned PICLevel;
5249 bool IsPIE;
5250 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5251 Arg *LastPICDataRelArg =
5252 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5253 options::OPT_mpic_data_is_text_relative);
5254 bool NoPICDataIsTextRelative = false;
5255 if (LastPICDataRelArg) {
5256 if (LastPICDataRelArg->getOption().matches(
5257 options::OPT_mno_pic_data_is_text_relative)) {
5258 NoPICDataIsTextRelative = true;
5259 if (!PICLevel)
5260 D.Diag(diag::err_drv_argument_only_allowed_with)
5261 << "-mno-pic-data-is-text-relative"
5262 << "-fpic/-fpie";
5264 if (!Triple.isSystemZ())
5265 D.Diag(diag::err_drv_unsupported_opt_for_target)
5266 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5267 : "-mpic-data-is-text-relative")
5268 << RawTriple.str();
5271 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5272 RelocationModel == llvm::Reloc::ROPI_RWPI;
5273 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5274 RelocationModel == llvm::Reloc::ROPI_RWPI;
5276 if (Args.hasArg(options::OPT_mcmse) &&
5277 !Args.hasArg(options::OPT_fallow_unsupported)) {
5278 if (IsROPI)
5279 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5280 if (IsRWPI)
5281 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5284 if (IsROPI && types::isCXX(Input.getType()) &&
5285 !Args.hasArg(options::OPT_fallow_unsupported))
5286 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5288 const char *RMName = RelocationModelName(RelocationModel);
5289 if (RMName) {
5290 CmdArgs.push_back("-mrelocation-model");
5291 CmdArgs.push_back(RMName);
5293 if (PICLevel > 0) {
5294 CmdArgs.push_back("-pic-level");
5295 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5296 if (IsPIE)
5297 CmdArgs.push_back("-pic-is-pie");
5298 if (NoPICDataIsTextRelative)
5299 CmdArgs.push_back("-mcmodel=medium");
5302 if (RelocationModel == llvm::Reloc::ROPI ||
5303 RelocationModel == llvm::Reloc::ROPI_RWPI)
5304 CmdArgs.push_back("-fropi");
5305 if (RelocationModel == llvm::Reloc::RWPI ||
5306 RelocationModel == llvm::Reloc::ROPI_RWPI)
5307 CmdArgs.push_back("-frwpi");
5309 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5310 CmdArgs.push_back("-meabi");
5311 CmdArgs.push_back(A->getValue());
5314 // -fsemantic-interposition is forwarded to CC1: set the
5315 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5316 // make default visibility external linkage definitions dso_preemptable.
5318 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5319 // aliases (make default visibility external linkage definitions dso_local).
5320 // This is the CC1 default for ELF to match COFF/Mach-O.
5322 // Otherwise use Clang's traditional behavior: like
5323 // -fno-semantic-interposition but local aliases are not used. So references
5324 // can be interposed if not optimized out.
5325 if (Triple.isOSBinFormatELF()) {
5326 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5327 options::OPT_fno_semantic_interposition);
5328 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5329 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5330 bool SupportsLocalAlias =
5331 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5332 if (!A)
5333 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5334 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5335 A->render(Args, CmdArgs);
5336 else if (!SupportsLocalAlias)
5337 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5342 std::string Model;
5343 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5344 if (!TC.isThreadModelSupported(A->getValue()))
5345 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5346 << A->getValue() << A->getAsString(Args);
5347 Model = A->getValue();
5348 } else
5349 Model = TC.getThreadModel();
5350 if (Model != "posix") {
5351 CmdArgs.push_back("-mthread-model");
5352 CmdArgs.push_back(Args.MakeArgString(Model));
5356 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5357 StringRef Name = A->getValue();
5358 if (Name == "SVML") {
5359 if (Triple.getArch() != llvm::Triple::x86 &&
5360 Triple.getArch() != llvm::Triple::x86_64)
5361 D.Diag(diag::err_drv_unsupported_opt_for_target)
5362 << Name << Triple.getArchName();
5363 } else if (Name == "LIBMVEC-X86") {
5364 if (Triple.getArch() != llvm::Triple::x86 &&
5365 Triple.getArch() != llvm::Triple::x86_64)
5366 D.Diag(diag::err_drv_unsupported_opt_for_target)
5367 << Name << Triple.getArchName();
5368 } else if (Name == "SLEEF" || Name == "ArmPL") {
5369 if (Triple.getArch() != llvm::Triple::aarch64 &&
5370 Triple.getArch() != llvm::Triple::aarch64_be)
5371 D.Diag(diag::err_drv_unsupported_opt_for_target)
5372 << Name << Triple.getArchName();
5374 A->render(Args, CmdArgs);
5377 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5378 options::OPT_fno_merge_all_constants, false))
5379 CmdArgs.push_back("-fmerge-all-constants");
5381 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5382 options::OPT_fno_delete_null_pointer_checks);
5384 // LLVM Code Generator Options.
5386 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5387 if (!Triple.isOSAIX() || Triple.isPPC32())
5388 D.Diag(diag::err_drv_unsupported_opt_for_target)
5389 << A->getSpelling() << RawTriple.str();
5390 CmdArgs.push_back("-mabi=quadword-atomics");
5393 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5394 // Emit the unsupported option error until the Clang's library integration
5395 // support for 128-bit long double is available for AIX.
5396 if (Triple.isOSAIX())
5397 D.Diag(diag::err_drv_unsupported_opt_for_target)
5398 << A->getSpelling() << RawTriple.str();
5401 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5402 StringRef V = A->getValue(), V1 = V;
5403 unsigned Size;
5404 if (V1.consumeInteger(10, Size) || !V1.empty())
5405 D.Diag(diag::err_drv_invalid_argument_to_option)
5406 << V << A->getOption().getName();
5407 else
5408 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5411 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5412 options::OPT_fno_jump_tables);
5413 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5414 options::OPT_fno_profile_sample_accurate);
5415 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5416 options::OPT_fno_preserve_as_comments);
5418 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5419 CmdArgs.push_back("-mregparm");
5420 CmdArgs.push_back(A->getValue());
5423 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5424 options::OPT_msvr4_struct_return)) {
5425 if (!TC.getTriple().isPPC32()) {
5426 D.Diag(diag::err_drv_unsupported_opt_for_target)
5427 << A->getSpelling() << RawTriple.str();
5428 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5429 CmdArgs.push_back("-maix-struct-return");
5430 } else {
5431 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5432 CmdArgs.push_back("-msvr4-struct-return");
5436 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5437 options::OPT_freg_struct_return)) {
5438 if (TC.getArch() != llvm::Triple::x86) {
5439 D.Diag(diag::err_drv_unsupported_opt_for_target)
5440 << A->getSpelling() << RawTriple.str();
5441 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5442 CmdArgs.push_back("-fpcc-struct-return");
5443 } else {
5444 assert(A->getOption().matches(options::OPT_freg_struct_return));
5445 CmdArgs.push_back("-freg-struct-return");
5449 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5450 if (Triple.getArch() == llvm::Triple::m68k)
5451 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5452 else
5453 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5456 if (Args.hasArg(options::OPT_fenable_matrix)) {
5457 // enable-matrix is needed by both the LangOpts and by LLVM.
5458 CmdArgs.push_back("-fenable-matrix");
5459 CmdArgs.push_back("-mllvm");
5460 CmdArgs.push_back("-enable-matrix");
5463 CodeGenOptions::FramePointerKind FPKeepKind =
5464 getFramePointerKind(Args, RawTriple);
5465 const char *FPKeepKindStr = nullptr;
5466 switch (FPKeepKind) {
5467 case CodeGenOptions::FramePointerKind::None:
5468 FPKeepKindStr = "-mframe-pointer=none";
5469 break;
5470 case CodeGenOptions::FramePointerKind::NonLeaf:
5471 FPKeepKindStr = "-mframe-pointer=non-leaf";
5472 break;
5473 case CodeGenOptions::FramePointerKind::All:
5474 FPKeepKindStr = "-mframe-pointer=all";
5475 break;
5477 assert(FPKeepKindStr && "unknown FramePointerKind");
5478 CmdArgs.push_back(FPKeepKindStr);
5480 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5481 options::OPT_fno_zero_initialized_in_bss);
5483 bool OFastEnabled = isOptimizationLevelFast(Args);
5484 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5485 // enabled. This alias option is being used to simplify the hasFlag logic.
5486 OptSpecifier StrictAliasingAliasOption =
5487 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5488 // We turn strict aliasing off by default if we're in CL mode, since MSVC
5489 // doesn't do any TBAA.
5490 bool TBAAOnByDefault = !D.IsCLMode();
5491 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5492 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
5493 CmdArgs.push_back("-relaxed-aliasing");
5494 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5495 options::OPT_fno_struct_path_tbaa, true))
5496 CmdArgs.push_back("-no-struct-path-tbaa");
5497 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5498 options::OPT_fno_strict_enums);
5499 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5500 options::OPT_fno_strict_return);
5501 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5502 options::OPT_fno_allow_editor_placeholders);
5503 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5504 options::OPT_fno_strict_vtable_pointers);
5505 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5506 options::OPT_fno_force_emit_vtables);
5507 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5508 options::OPT_fno_optimize_sibling_calls);
5509 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5510 options::OPT_fno_escaping_block_tail_calls);
5512 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5513 options::OPT_fno_fine_grained_bitfield_accesses);
5515 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5516 options::OPT_fno_experimental_relative_cxx_abi_vtables);
5518 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
5519 options::OPT_fno_experimental_omit_vtable_rtti);
5521 // Handle segmented stacks.
5522 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5523 options::OPT_fno_split_stack);
5525 // -fprotect-parens=0 is default.
5526 if (Args.hasFlag(options::OPT_fprotect_parens,
5527 options::OPT_fno_protect_parens, false))
5528 CmdArgs.push_back("-fprotect-parens");
5530 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5532 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5533 const llvm::Triple::ArchType Arch = TC.getArch();
5534 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5535 StringRef V = A->getValue();
5536 if (V == "64")
5537 CmdArgs.push_back("-fextend-arguments=64");
5538 else if (V != "32")
5539 D.Diag(diag::err_drv_invalid_argument_to_option)
5540 << A->getValue() << A->getOption().getName();
5541 } else
5542 D.Diag(diag::err_drv_unsupported_opt_for_target)
5543 << A->getOption().getName() << TripleStr;
5546 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5547 if (TC.getArch() == llvm::Triple::avr)
5548 A->render(Args, CmdArgs);
5549 else
5550 D.Diag(diag::err_drv_unsupported_opt_for_target)
5551 << A->getAsString(Args) << TripleStr;
5554 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5555 if (TC.getTriple().isX86())
5556 A->render(Args, CmdArgs);
5557 else if (TC.getTriple().isPPC() &&
5558 (A->getOption().getID() != options::OPT_mlong_double_80))
5559 A->render(Args, CmdArgs);
5560 else
5561 D.Diag(diag::err_drv_unsupported_opt_for_target)
5562 << A->getAsString(Args) << TripleStr;
5565 // Decide whether to use verbose asm. Verbose assembly is the default on
5566 // toolchains which have the integrated assembler on by default.
5567 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5568 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5569 IsIntegratedAssemblerDefault))
5570 CmdArgs.push_back("-fno-verbose-asm");
5572 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5573 // use that to indicate the MC default in the backend.
5574 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5575 StringRef V = A->getValue();
5576 unsigned Num;
5577 if (V == "none")
5578 A->render(Args, CmdArgs);
5579 else if (!V.consumeInteger(10, Num) && Num > 0 &&
5580 (V.empty() || (V.consume_front(".") &&
5581 !V.consumeInteger(10, Num) && V.empty())))
5582 A->render(Args, CmdArgs);
5583 else
5584 D.Diag(diag::err_drv_invalid_argument_to_option)
5585 << A->getValue() << A->getOption().getName();
5588 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5589 // option to disable integrated-as explictly.
5590 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5591 CmdArgs.push_back("-no-integrated-as");
5593 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5594 CmdArgs.push_back("-mdebug-pass");
5595 CmdArgs.push_back("Structure");
5597 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5598 CmdArgs.push_back("-mdebug-pass");
5599 CmdArgs.push_back("Arguments");
5602 // Enable -mconstructor-aliases except on darwin, where we have to work around
5603 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5604 // code, where aliases aren't supported.
5605 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5606 CmdArgs.push_back("-mconstructor-aliases");
5608 // Darwin's kernel doesn't support guard variables; just die if we
5609 // try to use them.
5610 if (KernelOrKext && RawTriple.isOSDarwin())
5611 CmdArgs.push_back("-fforbid-guard-variables");
5613 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5614 Triple.isWindowsGNUEnvironment())) {
5615 CmdArgs.push_back("-mms-bitfields");
5618 if (Triple.isWindowsGNUEnvironment()) {
5619 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
5620 options::OPT_fno_auto_import);
5623 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
5624 Triple.isX86() && D.IsCLMode()))
5625 CmdArgs.push_back("-fms-volatile");
5627 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5628 // defaults to -fno-direct-access-external-data. Pass the option if different
5629 // from the default.
5630 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5631 options::OPT_fno_direct_access_external_data)) {
5632 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5633 (PICLevel == 0))
5634 A->render(Args, CmdArgs);
5635 } else if (PICLevel == 0 && Triple.isLoongArch()) {
5636 // Some targets default to -fno-direct-access-external-data even for
5637 // -fno-pic.
5638 CmdArgs.push_back("-fno-direct-access-external-data");
5641 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5642 CmdArgs.push_back("-fno-plt");
5645 // -fhosted is default.
5646 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5647 // use Freestanding.
5648 bool Freestanding =
5649 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5650 KernelOrKext;
5651 if (Freestanding)
5652 CmdArgs.push_back("-ffreestanding");
5654 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5656 // This is a coarse approximation of what llvm-gcc actually does, both
5657 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5658 // complicated ways.
5659 auto SanitizeArgs = TC.getSanitizerArgs(Args);
5661 bool IsAsyncUnwindTablesDefault =
5662 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5663 bool IsSyncUnwindTablesDefault =
5664 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5666 bool AsyncUnwindTables = Args.hasFlag(
5667 options::OPT_fasynchronous_unwind_tables,
5668 options::OPT_fno_asynchronous_unwind_tables,
5669 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5670 !Freestanding);
5671 bool UnwindTables =
5672 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5673 IsSyncUnwindTablesDefault && !Freestanding);
5674 if (AsyncUnwindTables)
5675 CmdArgs.push_back("-funwind-tables=2");
5676 else if (UnwindTables)
5677 CmdArgs.push_back("-funwind-tables=1");
5679 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5680 // `--gpu-use-aux-triple-only` is specified.
5681 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5682 (IsCudaDevice || IsHIPDevice)) {
5683 const ArgList &HostArgs =
5684 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5685 std::string HostCPU =
5686 getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5687 if (!HostCPU.empty()) {
5688 CmdArgs.push_back("-aux-target-cpu");
5689 CmdArgs.push_back(Args.MakeArgString(HostCPU));
5691 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5692 /*ForAS*/ false, /*IsAux*/ true);
5695 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5697 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5698 StringRef CM = A->getValue();
5699 bool Ok = false;
5700 if (Triple.isOSAIX() && CM == "medium")
5701 CM = "large";
5702 if (Triple.isAArch64(64)) {
5703 Ok = CM == "tiny" || CM == "small" || CM == "large";
5704 if (CM == "large" && RelocationModel != llvm::Reloc::Static)
5705 D.Diag(diag::err_drv_argument_only_allowed_with)
5706 << A->getAsString(Args) << "-fno-pic";
5707 } else if (Triple.isLoongArch()) {
5708 if (CM == "extreme" &&
5709 Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
5710 D.Diag(diag::err_drv_argument_not_allowed_with)
5711 << A->getAsString(Args) << "-fplt";
5712 Ok = CM == "normal" || CM == "medium" || CM == "extreme";
5713 // Convert to LLVM recognizable names.
5714 if (Ok)
5715 CM = llvm::StringSwitch<StringRef>(CM)
5716 .Case("normal", "small")
5717 .Case("extreme", "large")
5718 .Default(CM);
5719 } else if (Triple.isPPC64() || Triple.isOSAIX()) {
5720 Ok = CM == "small" || CM == "medium" || CM == "large";
5721 } else if (Triple.isRISCV()) {
5722 if (CM == "medlow")
5723 CM = "small";
5724 else if (CM == "medany")
5725 CM = "medium";
5726 Ok = CM == "small" || CM == "medium";
5727 } else if (Triple.getArch() == llvm::Triple::x86_64) {
5728 Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
5729 CM);
5730 } else if (Triple.isNVPTX() || Triple.isAMDGPU()) {
5731 // NVPTX/AMDGPU does not care about the code model and will accept
5732 // whatever works for the host.
5733 Ok = true;
5735 if (Ok) {
5736 CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
5737 } else {
5738 D.Diag(diag::err_drv_unsupported_option_argument_for_target)
5739 << A->getSpelling() << CM << TripleStr;
5743 if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
5744 if (!Triple.isX86()) {
5745 D.Diag(diag::err_drv_unsupported_opt_for_target)
5746 << A->getOption().getName() << TripleStr;
5747 } else {
5748 bool IsMediumCM = false;
5749 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ))
5750 IsMediumCM = StringRef(A->getValue()) == "medium";
5751 if (!IsMediumCM) {
5752 D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
5753 << A->getOption().getRenderName();
5754 } else {
5755 A->render(Args, CmdArgs);
5760 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5761 StringRef Value = A->getValue();
5762 unsigned TLSSize = 0;
5763 Value.getAsInteger(10, TLSSize);
5764 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5765 D.Diag(diag::err_drv_unsupported_opt_for_target)
5766 << A->getOption().getName() << TripleStr;
5767 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5768 D.Diag(diag::err_drv_invalid_int_value)
5769 << A->getOption().getName() << Value;
5770 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5773 // Add the target cpu
5774 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5775 if (!CPU.empty()) {
5776 CmdArgs.push_back("-target-cpu");
5777 CmdArgs.push_back(Args.MakeArgString(CPU));
5780 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5782 // Add clang-cl arguments.
5783 types::ID InputType = Input.getType();
5784 if (D.IsCLMode())
5785 AddClangCLArgs(Args, InputType, CmdArgs);
5787 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
5788 llvm::codegenoptions::NoDebugInfo;
5789 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5790 renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
5791 CmdArgs, Output, DebugInfoKind, DwarfFission);
5793 // Add the split debug info name to the command lines here so we
5794 // can propagate it to the backend.
5795 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5796 (TC.getTriple().isOSBinFormatELF() ||
5797 TC.getTriple().isOSBinFormatWasm() ||
5798 TC.getTriple().isOSBinFormatCOFF()) &&
5799 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5800 isa<BackendJobAction>(JA));
5801 if (SplitDWARF) {
5802 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5803 CmdArgs.push_back("-split-dwarf-file");
5804 CmdArgs.push_back(SplitDWARFOut);
5805 if (DwarfFission == DwarfFissionKind::Split) {
5806 CmdArgs.push_back("-split-dwarf-output");
5807 CmdArgs.push_back(SplitDWARFOut);
5811 // Pass the linker version in use.
5812 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5813 CmdArgs.push_back("-target-linker-version");
5814 CmdArgs.push_back(A->getValue());
5817 // Explicitly error on some things we know we don't support and can't just
5818 // ignore.
5819 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5820 Arg *Unsupported;
5821 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5822 TC.getArch() == llvm::Triple::x86) {
5823 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5824 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5825 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5826 << Unsupported->getOption().getName();
5828 // The faltivec option has been superseded by the maltivec option.
5829 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5830 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5831 << Unsupported->getOption().getName()
5832 << "please use -maltivec and include altivec.h explicitly";
5833 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5834 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5835 << Unsupported->getOption().getName() << "please use -mno-altivec";
5838 Args.AddAllArgs(CmdArgs, options::OPT_v);
5840 if (Args.getLastArg(options::OPT_H)) {
5841 CmdArgs.push_back("-H");
5842 CmdArgs.push_back("-sys-header-deps");
5844 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5846 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
5847 CmdArgs.push_back("-header-include-file");
5848 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5849 ? D.CCPrintHeadersFilename.c_str()
5850 : "-");
5851 CmdArgs.push_back("-sys-header-deps");
5852 CmdArgs.push_back(Args.MakeArgString(
5853 "-header-include-format=" +
5854 std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
5855 CmdArgs.push_back(
5856 Args.MakeArgString("-header-include-filtering=" +
5857 std::string(headerIncludeFilteringKindToString(
5858 D.CCPrintHeadersFiltering))));
5860 Args.AddLastArg(CmdArgs, options::OPT_P);
5861 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5863 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5864 CmdArgs.push_back("-diagnostic-log-file");
5865 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5866 ? D.CCLogDiagnosticsFilename.c_str()
5867 : "-");
5870 // Give the gen diagnostics more chances to succeed, by avoiding intentional
5871 // crashes.
5872 if (D.CCGenDiagnostics)
5873 CmdArgs.push_back("-disable-pragma-debug-crash");
5875 // Allow backend to put its diagnostic files in the same place as frontend
5876 // crash diagnostics files.
5877 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5878 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5879 CmdArgs.push_back("-mllvm");
5880 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5883 bool UseSeparateSections = isUseSeparateSections(Triple);
5885 if (Args.hasFlag(options::OPT_ffunction_sections,
5886 options::OPT_fno_function_sections, UseSeparateSections)) {
5887 CmdArgs.push_back("-ffunction-sections");
5890 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5891 StringRef Val = A->getValue();
5892 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5893 if (Val != "all" && Val != "labels" && Val != "none" &&
5894 !Val.starts_with("list="))
5895 D.Diag(diag::err_drv_invalid_value)
5896 << A->getAsString(Args) << A->getValue();
5897 else
5898 A->render(Args, CmdArgs);
5899 } else if (Triple.isNVPTX()) {
5900 // Do not pass the option to the GPU compilation. We still want it enabled
5901 // for the host-side compilation, so seeing it here is not an error.
5902 } else if (Val != "none") {
5903 // =none is allowed everywhere. It's useful for overriding the option
5904 // and is the same as not specifying the option.
5905 D.Diag(diag::err_drv_unsupported_opt_for_target)
5906 << A->getAsString(Args) << TripleStr;
5910 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5911 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5912 UseSeparateSections || HasDefaultDataSections)) {
5913 CmdArgs.push_back("-fdata-sections");
5916 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
5917 options::OPT_fno_unique_section_names);
5918 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
5919 options::OPT_fno_unique_internal_linkage_names);
5920 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
5921 options::OPT_fno_unique_basic_block_section_names);
5922 Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
5923 options::OPT_fno_convergent_functions);
5925 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5926 options::OPT_fno_split_machine_functions)) {
5927 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
5928 // This codegen pass is only available on x86 and AArch64 ELF targets.
5929 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
5930 A->render(Args, CmdArgs);
5931 else
5932 D.Diag(diag::err_drv_unsupported_opt_for_target)
5933 << A->getAsString(Args) << TripleStr;
5937 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5938 options::OPT_finstrument_functions_after_inlining,
5939 options::OPT_finstrument_function_entry_bare);
5941 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5942 // for sampling, overhead of call arc collection is way too high and there's
5943 // no way to collect the output.
5944 if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5945 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
5947 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5949 if (getLastProfileSampleUseArg(Args) &&
5950 Args.hasArg(options::OPT_fsample_profile_use_profi)) {
5951 CmdArgs.push_back("-mllvm");
5952 CmdArgs.push_back("-sample-profile-use-profi");
5955 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
5956 if (RawTriple.isPS() &&
5957 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5958 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
5959 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5962 // Pass options for controlling the default header search paths.
5963 if (Args.hasArg(options::OPT_nostdinc)) {
5964 CmdArgs.push_back("-nostdsysteminc");
5965 CmdArgs.push_back("-nobuiltininc");
5966 } else {
5967 if (Args.hasArg(options::OPT_nostdlibinc))
5968 CmdArgs.push_back("-nostdsysteminc");
5969 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5970 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5973 // Pass the path to compiler resource files.
5974 CmdArgs.push_back("-resource-dir");
5975 CmdArgs.push_back(D.ResourceDir.c_str());
5977 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5979 RenderARCMigrateToolOptions(D, Args, CmdArgs);
5981 // Add preprocessing options like -I, -D, etc. if we are using the
5982 // preprocessor.
5984 // FIXME: Support -fpreprocessed
5985 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5986 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5988 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5989 // that "The compiler can only warn and ignore the option if not recognized".
5990 // When building with ccache, it will pass -D options to clang even on
5991 // preprocessed inputs and configure concludes that -fPIC is not supported.
5992 Args.ClaimAllArgs(options::OPT_D);
5994 // Manually translate -O4 to -O3; let clang reject others.
5995 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5996 if (A->getOption().matches(options::OPT_O4)) {
5997 CmdArgs.push_back("-O3");
5998 D.Diag(diag::warn_O4_is_O3);
5999 } else {
6000 A->render(Args, CmdArgs);
6004 // Warn about ignored options to clang.
6005 for (const Arg *A :
6006 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6007 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6008 A->claim();
6011 for (const Arg *A :
6012 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6013 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6014 A->claim();
6017 claimNoWarnArgs(Args);
6019 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6021 for (const Arg *A :
6022 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6023 A->claim();
6024 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6025 unsigned WarningNumber;
6026 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6027 D.Diag(diag::err_drv_invalid_int_value)
6028 << A->getAsString(Args) << A->getValue();
6029 continue;
6032 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6033 CmdArgs.push_back(Args.MakeArgString(
6034 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6036 continue;
6038 A->render(Args, CmdArgs);
6041 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6043 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6044 CmdArgs.push_back("-pedantic");
6045 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6046 Args.AddLastArg(CmdArgs, options::OPT_w);
6048 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6049 options::OPT_fno_fixed_point);
6051 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6052 A->render(Args, CmdArgs);
6054 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6055 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6057 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6058 options::OPT_fno_experimental_omit_vtable_rtti);
6060 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6061 A->render(Args, CmdArgs);
6063 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6064 // (-ansi is equivalent to -std=c89 or -std=c++98).
6066 // If a std is supplied, only add -trigraphs if it follows the
6067 // option.
6068 bool ImplyVCPPCVer = false;
6069 bool ImplyVCPPCXXVer = false;
6070 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6071 if (Std) {
6072 if (Std->getOption().matches(options::OPT_ansi))
6073 if (types::isCXX(InputType))
6074 CmdArgs.push_back("-std=c++98");
6075 else
6076 CmdArgs.push_back("-std=c89");
6077 else
6078 Std->render(Args, CmdArgs);
6080 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6081 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6082 options::OPT_ftrigraphs,
6083 options::OPT_fno_trigraphs))
6084 if (A != Std)
6085 A->render(Args, CmdArgs);
6086 } else {
6087 // Honor -std-default.
6089 // FIXME: Clang doesn't correctly handle -std= when the input language
6090 // doesn't match. For the time being just ignore this for C++ inputs;
6091 // eventually we want to do all the standard defaulting here instead of
6092 // splitting it between the driver and clang -cc1.
6093 if (!types::isCXX(InputType)) {
6094 if (!Args.hasArg(options::OPT__SLASH_std)) {
6095 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6096 /*Joined=*/true);
6097 } else
6098 ImplyVCPPCVer = true;
6100 else if (IsWindowsMSVC)
6101 ImplyVCPPCXXVer = true;
6103 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6104 options::OPT_fno_trigraphs);
6107 // GCC's behavior for -Wwrite-strings is a bit strange:
6108 // * In C, this "warning flag" changes the types of string literals from
6109 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6110 // for the discarded qualifier.
6111 // * In C++, this is just a normal warning flag.
6113 // Implementing this warning correctly in C is hard, so we follow GCC's
6114 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6115 // a non-const char* in C, rather than using this crude hack.
6116 if (!types::isCXX(InputType)) {
6117 // FIXME: This should behave just like a warning flag, and thus should also
6118 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6119 Arg *WriteStrings =
6120 Args.getLastArg(options::OPT_Wwrite_strings,
6121 options::OPT_Wno_write_strings, options::OPT_w);
6122 if (WriteStrings &&
6123 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6124 CmdArgs.push_back("-fconst-strings");
6127 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6128 // during C++ compilation, which it is by default. GCC keeps this define even
6129 // in the presence of '-w', match this behavior bug-for-bug.
6130 if (types::isCXX(InputType) &&
6131 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6132 true)) {
6133 CmdArgs.push_back("-fdeprecated-macro");
6136 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6137 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6138 if (Asm->getOption().matches(options::OPT_fasm))
6139 CmdArgs.push_back("-fgnu-keywords");
6140 else
6141 CmdArgs.push_back("-fno-gnu-keywords");
6144 if (!ShouldEnableAutolink(Args, TC, JA))
6145 CmdArgs.push_back("-fno-autolink");
6147 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6148 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6149 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6150 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6152 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6154 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6155 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6157 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6158 CmdArgs.push_back("-fbracket-depth");
6159 CmdArgs.push_back(A->getValue());
6162 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6163 options::OPT_Wlarge_by_value_copy_def)) {
6164 if (A->getNumValues()) {
6165 StringRef bytes = A->getValue();
6166 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6167 } else
6168 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6171 if (Args.hasArg(options::OPT_relocatable_pch))
6172 CmdArgs.push_back("-relocatable-pch");
6174 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6175 static const char *kCFABIs[] = {
6176 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6179 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6180 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6181 else
6182 A->render(Args, CmdArgs);
6185 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6186 CmdArgs.push_back("-fconstant-string-class");
6187 CmdArgs.push_back(A->getValue());
6190 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6191 CmdArgs.push_back("-ftabstop");
6192 CmdArgs.push_back(A->getValue());
6195 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6196 options::OPT_fno_stack_size_section);
6198 if (Args.hasArg(options::OPT_fstack_usage)) {
6199 CmdArgs.push_back("-stack-usage-file");
6201 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6202 SmallString<128> OutputFilename(OutputOpt->getValue());
6203 llvm::sys::path::replace_extension(OutputFilename, "su");
6204 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6205 } else
6206 CmdArgs.push_back(
6207 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6210 CmdArgs.push_back("-ferror-limit");
6211 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6212 CmdArgs.push_back(A->getValue());
6213 else
6214 CmdArgs.push_back("19");
6216 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6217 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6218 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6219 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6220 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6222 // Pass -fmessage-length=.
6223 unsigned MessageLength = 0;
6224 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6225 StringRef V(A->getValue());
6226 if (V.getAsInteger(0, MessageLength))
6227 D.Diag(diag::err_drv_invalid_argument_to_option)
6228 << V << A->getOption().getName();
6229 } else {
6230 // If -fmessage-length=N was not specified, determine whether this is a
6231 // terminal and, if so, implicitly define -fmessage-length appropriately.
6232 MessageLength = llvm::sys::Process::StandardErrColumns();
6234 if (MessageLength != 0)
6235 CmdArgs.push_back(
6236 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6238 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6239 CmdArgs.push_back(
6240 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6242 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6243 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6244 Twine(A->getValue(0))));
6246 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6247 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6248 options::OPT_fvisibility_ms_compat)) {
6249 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6250 A->render(Args, CmdArgs);
6251 } else {
6252 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6253 CmdArgs.push_back("-fvisibility=hidden");
6254 CmdArgs.push_back("-ftype-visibility=default");
6256 } else if (IsOpenMPDevice) {
6257 // When compiling for the OpenMP device we want protected visibility by
6258 // default. This prevents the device from accidentally preempting code on
6259 // the host, makes the system more robust, and improves performance.
6260 CmdArgs.push_back("-fvisibility=protected");
6263 // PS4/PS5 process these options in addClangTargetOptions.
6264 if (!RawTriple.isPS()) {
6265 if (const Arg *A =
6266 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6267 options::OPT_fno_visibility_from_dllstorageclass)) {
6268 if (A->getOption().matches(
6269 options::OPT_fvisibility_from_dllstorageclass)) {
6270 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6271 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6272 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6273 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6274 Args.AddLastArg(CmdArgs,
6275 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6280 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6281 options::OPT_fno_visibility_inlines_hidden, false))
6282 CmdArgs.push_back("-fvisibility-inlines-hidden");
6284 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6285 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6286 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
6287 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6289 if (Args.hasFlag(options::OPT_fnew_infallible,
6290 options::OPT_fno_new_infallible, false))
6291 CmdArgs.push_back("-fnew-infallible");
6293 if (Args.hasFlag(options::OPT_fno_operator_names,
6294 options::OPT_foperator_names, false))
6295 CmdArgs.push_back("-fno-operator-names");
6297 // Forward -f (flag) options which we can pass directly.
6298 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6299 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6300 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6301 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6303 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6304 Triple.hasDefaultEmulatedTLS()))
6305 CmdArgs.push_back("-femulated-tls");
6307 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6308 options::OPT_fno_check_new);
6310 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6311 // FIXME: There's no reason for this to be restricted to X86. The backend
6312 // code needs to be changed to include the appropriate function calls
6313 // automatically.
6314 if (!Triple.isX86() && !Triple.isAArch64())
6315 D.Diag(diag::err_drv_unsupported_opt_for_target)
6316 << A->getAsString(Args) << TripleStr;
6319 // AltiVec-like language extensions aren't relevant for assembling.
6320 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6321 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6323 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6324 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6326 // Forward flags for OpenMP. We don't do this if the current action is an
6327 // device offloading action other than OpenMP.
6328 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6329 options::OPT_fno_openmp, false) &&
6330 (JA.isDeviceOffloading(Action::OFK_None) ||
6331 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6332 switch (D.getOpenMPRuntime(Args)) {
6333 case Driver::OMPRT_OMP:
6334 case Driver::OMPRT_IOMP5:
6335 // Clang can generate useful OpenMP code for these two runtime libraries.
6336 CmdArgs.push_back("-fopenmp");
6338 // If no option regarding the use of TLS in OpenMP codegeneration is
6339 // given, decide a default based on the target. Otherwise rely on the
6340 // options and pass the right information to the frontend.
6341 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6342 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6343 CmdArgs.push_back("-fnoopenmp-use-tls");
6344 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6345 options::OPT_fno_openmp_simd);
6346 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6347 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6348 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6349 options::OPT_fno_openmp_extensions, /*Default=*/true))
6350 CmdArgs.push_back("-fno-openmp-extensions");
6351 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6352 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6353 Args.AddAllArgs(CmdArgs,
6354 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6355 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6356 options::OPT_fno_openmp_optimistic_collapse,
6357 /*Default=*/false))
6358 CmdArgs.push_back("-fopenmp-optimistic-collapse");
6360 // When in OpenMP offloading mode with NVPTX target, forward
6361 // cuda-mode flag
6362 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6363 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6364 CmdArgs.push_back("-fopenmp-cuda-mode");
6366 // When in OpenMP offloading mode, enable debugging on the device.
6367 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6368 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6369 options::OPT_fno_openmp_target_debug, /*Default=*/false))
6370 CmdArgs.push_back("-fopenmp-target-debug");
6372 // When in OpenMP offloading mode, forward assumptions information about
6373 // thread and team counts in the device.
6374 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6375 options::OPT_fno_openmp_assume_teams_oversubscription,
6376 /*Default=*/false))
6377 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6378 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6379 options::OPT_fno_openmp_assume_threads_oversubscription,
6380 /*Default=*/false))
6381 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6382 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6383 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6384 if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6385 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6386 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6387 CmdArgs.push_back("-fopenmp-offload-mandatory");
6388 break;
6389 default:
6390 // By default, if Clang doesn't know how to generate useful OpenMP code
6391 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6392 // down to the actual compilation.
6393 // FIXME: It would be better to have a mode which *only* omits IR
6394 // generation based on the OpenMP support so that we get consistent
6395 // semantic analysis, etc.
6396 break;
6398 } else {
6399 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6400 options::OPT_fno_openmp_simd);
6401 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6402 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6403 options::OPT_fno_openmp_extensions);
6406 // Forward the new driver to change offloading code generation.
6407 if (Args.hasFlag(options::OPT_offload_new_driver,
6408 options::OPT_no_offload_new_driver, false))
6409 CmdArgs.push_back("--offload-new-driver");
6411 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6413 const XRayArgs &XRay = TC.getXRayArgs();
6414 XRay.addArgs(TC, Args, CmdArgs, InputType);
6416 for (const auto &Filename :
6417 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6418 if (D.getVFS().exists(Filename))
6419 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6420 else
6421 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6424 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6425 StringRef S0 = A->getValue(), S = S0;
6426 unsigned Size, Offset = 0;
6427 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6428 !Triple.isX86())
6429 D.Diag(diag::err_drv_unsupported_opt_for_target)
6430 << A->getAsString(Args) << TripleStr;
6431 else if (S.consumeInteger(10, Size) ||
6432 (!S.empty() && (!S.consume_front(",") ||
6433 S.consumeInteger(10, Offset) || !S.empty())))
6434 D.Diag(diag::err_drv_invalid_argument_to_option)
6435 << S0 << A->getOption().getName();
6436 else if (Size < Offset)
6437 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6438 else {
6439 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6440 CmdArgs.push_back(Args.MakeArgString(
6441 "-fpatchable-function-entry-offset=" + Twine(Offset)));
6445 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6447 if (TC.SupportsProfiling()) {
6448 Args.AddLastArg(CmdArgs, options::OPT_pg);
6450 llvm::Triple::ArchType Arch = TC.getArch();
6451 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6452 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6453 A->render(Args, CmdArgs);
6454 else
6455 D.Diag(diag::err_drv_unsupported_opt_for_target)
6456 << A->getAsString(Args) << TripleStr;
6458 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6459 if (Arch == llvm::Triple::systemz)
6460 A->render(Args, CmdArgs);
6461 else
6462 D.Diag(diag::err_drv_unsupported_opt_for_target)
6463 << A->getAsString(Args) << TripleStr;
6465 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6466 if (Arch == llvm::Triple::systemz)
6467 A->render(Args, CmdArgs);
6468 else
6469 D.Diag(diag::err_drv_unsupported_opt_for_target)
6470 << A->getAsString(Args) << TripleStr;
6474 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6475 if (TC.getTriple().isOSzOS()) {
6476 D.Diag(diag::err_drv_unsupported_opt_for_target)
6477 << A->getAsString(Args) << TripleStr;
6480 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6481 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6482 D.Diag(diag::err_drv_unsupported_opt_for_target)
6483 << A->getAsString(Args) << TripleStr;
6486 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6487 if (A->getOption().matches(options::OPT_p)) {
6488 A->claim();
6489 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6490 CmdArgs.push_back("-pg");
6494 // Reject AIX-specific link options on other targets.
6495 if (!TC.getTriple().isOSAIX()) {
6496 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6497 options::OPT_mxcoff_build_id_EQ)) {
6498 D.Diag(diag::err_drv_unsupported_opt_for_target)
6499 << A->getSpelling() << TripleStr;
6503 if (Args.getLastArg(options::OPT_fapple_kext) ||
6504 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6505 CmdArgs.push_back("-fapple-kext");
6507 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6508 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6509 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6510 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6511 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6512 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6513 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6514 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6515 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6516 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6518 if (const char *Name = C.getTimeTraceFile(&JA)) {
6519 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
6520 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6523 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6524 CmdArgs.push_back("-ftrapv-handler");
6525 CmdArgs.push_back(A->getValue());
6528 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6530 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
6531 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
6532 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
6533 if (A->getOption().matches(options::OPT_fwrapv))
6534 CmdArgs.push_back("-fwrapv");
6535 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
6536 options::OPT_fno_strict_overflow)) {
6537 if (A->getOption().matches(options::OPT_fno_strict_overflow))
6538 CmdArgs.push_back("-fwrapv");
6541 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
6542 options::OPT_fno_reroll_loops))
6543 if (A->getOption().matches(options::OPT_freroll_loops))
6544 CmdArgs.push_back("-freroll-loops");
6546 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6547 options::OPT_fno_finite_loops);
6549 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6550 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6551 options::OPT_fno_unroll_loops);
6553 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6555 Args.AddLastArg(CmdArgs, options::OPT_pthread);
6557 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6558 options::OPT_mno_speculative_load_hardening);
6560 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6561 RenderSCPOptions(TC, Args, CmdArgs);
6562 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6564 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6566 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6567 options::OPT_mno_stackrealign);
6569 if (Args.hasArg(options::OPT_mstack_alignment)) {
6570 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6571 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
6574 if (Args.hasArg(options::OPT_mstack_probe_size)) {
6575 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6577 if (!Size.empty())
6578 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6579 else
6580 CmdArgs.push_back("-mstack-probe-size=0");
6583 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6584 options::OPT_mno_stack_arg_probe);
6586 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6587 options::OPT_mno_restrict_it)) {
6588 if (A->getOption().matches(options::OPT_mrestrict_it)) {
6589 CmdArgs.push_back("-mllvm");
6590 CmdArgs.push_back("-arm-restrict-it");
6591 } else {
6592 CmdArgs.push_back("-mllvm");
6593 CmdArgs.push_back("-arm-default-it");
6597 // Forward -cl options to -cc1
6598 RenderOpenCLOptions(Args, CmdArgs, InputType);
6600 // Forward hlsl options to -cc1
6601 RenderHLSLOptions(Args, CmdArgs, InputType);
6603 // Forward OpenACC options to -cc1
6604 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
6606 if (IsHIP) {
6607 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6608 options::OPT_fno_hip_new_launch_api, true))
6609 CmdArgs.push_back("-fhip-new-launch-api");
6610 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
6611 options::OPT_fno_gpu_allow_device_init);
6612 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
6613 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
6614 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
6615 options::OPT_fno_hip_kernel_arg_name);
6618 if (IsCuda || IsHIP) {
6619 if (IsRDCMode)
6620 CmdArgs.push_back("-fgpu-rdc");
6621 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
6622 options::OPT_fno_gpu_defer_diag);
6623 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6624 options::OPT_fno_gpu_exclude_wrong_side_overloads,
6625 false)) {
6626 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6627 CmdArgs.push_back("-fgpu-defer-diag");
6631 // Forward -nogpulib to -cc1.
6632 if (Args.hasArg(options::OPT_nogpulib))
6633 CmdArgs.push_back("-nogpulib");
6635 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6636 CmdArgs.push_back(
6637 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6640 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6641 CmdArgs.push_back(
6642 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6644 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6646 // Forward -f options with positive and negative forms; we translate these by
6647 // hand. Do not propagate PGO options to the GPU-side compilations as the
6648 // profile info is for the host-side compilation only.
6649 if (!(IsCudaDevice || IsHIPDevice)) {
6650 if (Arg *A = getLastProfileSampleUseArg(Args)) {
6651 auto *PGOArg = Args.getLastArg(
6652 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6653 options::OPT_fcs_profile_generate,
6654 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6655 options::OPT_fprofile_use_EQ);
6656 if (PGOArg)
6657 D.Diag(diag::err_drv_argument_not_allowed_with)
6658 << "SampleUse with PGO options";
6660 StringRef fname = A->getValue();
6661 if (!llvm::sys::fs::exists(fname))
6662 D.Diag(diag::err_drv_no_such_file) << fname;
6663 else
6664 A->render(Args, CmdArgs);
6666 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6668 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6669 options::OPT_fno_pseudo_probe_for_profiling, false)) {
6670 CmdArgs.push_back("-fpseudo-probe-for-profiling");
6671 // Enforce -funique-internal-linkage-names if it's not explicitly turned
6672 // off.
6673 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6674 options::OPT_fno_unique_internal_linkage_names, true))
6675 CmdArgs.push_back("-funique-internal-linkage-names");
6678 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
6680 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6681 options::OPT_fno_assume_sane_operator_new);
6683 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
6684 CmdArgs.push_back("-fapinotes");
6685 if (Args.hasFlag(options::OPT_fapinotes_modules,
6686 options::OPT_fno_apinotes_modules, false))
6687 CmdArgs.push_back("-fapinotes-modules");
6688 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
6690 // -fblocks=0 is default.
6691 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6692 TC.IsBlocksDefault()) ||
6693 (Args.hasArg(options::OPT_fgnu_runtime) &&
6694 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6695 !Args.hasArg(options::OPT_fno_blocks))) {
6696 CmdArgs.push_back("-fblocks");
6698 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6699 CmdArgs.push_back("-fblocks-runtime-optional");
6702 // -fencode-extended-block-signature=1 is default.
6703 if (TC.IsEncodeExtendedBlockSignatureDefault())
6704 CmdArgs.push_back("-fencode-extended-block-signature");
6706 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
6707 options::OPT_fno_coro_aligned_allocation, false) &&
6708 types::isCXX(InputType))
6709 CmdArgs.push_back("-fcoro-aligned-allocation");
6711 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6712 options::OPT_fno_double_square_bracket_attributes);
6714 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
6715 options::OPT_fno_access_control);
6716 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
6717 options::OPT_fno_elide_constructors);
6719 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6721 if (KernelOrKext || (types::isCXX(InputType) &&
6722 (RTTIMode == ToolChain::RM_Disabled)))
6723 CmdArgs.push_back("-fno-rtti");
6725 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6726 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6727 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6728 CmdArgs.push_back("-fshort-enums");
6730 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6732 // -fuse-cxa-atexit is default.
6733 if (!Args.hasFlag(
6734 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6735 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6736 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6737 RawTriple.hasEnvironment())) ||
6738 KernelOrKext)
6739 CmdArgs.push_back("-fno-use-cxa-atexit");
6741 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6742 options::OPT_fno_register_global_dtors_with_atexit,
6743 RawTriple.isOSDarwin() && !KernelOrKext))
6744 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6746 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
6747 options::OPT_fno_use_line_directives);
6749 // -fno-minimize-whitespace is default.
6750 if (Args.hasFlag(options::OPT_fminimize_whitespace,
6751 options::OPT_fno_minimize_whitespace, false)) {
6752 types::ID InputType = Inputs[0].getType();
6753 if (!isDerivedFromC(InputType))
6754 D.Diag(diag::err_drv_opt_unsupported_input_type)
6755 << "-fminimize-whitespace" << types::getTypeName(InputType);
6756 CmdArgs.push_back("-fminimize-whitespace");
6759 // -fno-keep-system-includes is default.
6760 if (Args.hasFlag(options::OPT_fkeep_system_includes,
6761 options::OPT_fno_keep_system_includes, false)) {
6762 types::ID InputType = Inputs[0].getType();
6763 if (!isDerivedFromC(InputType))
6764 D.Diag(diag::err_drv_opt_unsupported_input_type)
6765 << "-fkeep-system-includes" << types::getTypeName(InputType);
6766 CmdArgs.push_back("-fkeep-system-includes");
6769 // -fms-extensions=0 is default.
6770 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6771 IsWindowsMSVC))
6772 CmdArgs.push_back("-fms-extensions");
6774 // -fms-compatibility=0 is default.
6775 bool IsMSVCCompat = Args.hasFlag(
6776 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6777 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6778 options::OPT_fno_ms_extensions, true)));
6779 if (IsMSVCCompat)
6780 CmdArgs.push_back("-fms-compatibility");
6782 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
6783 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
6784 ProcessVSRuntimeLibrary(Args, CmdArgs);
6786 // Handle -fgcc-version, if present.
6787 VersionTuple GNUCVer;
6788 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6789 // Check that the version has 1 to 3 components and the minor and patch
6790 // versions fit in two decimal digits.
6791 StringRef Val = A->getValue();
6792 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6793 bool Invalid = GNUCVer.tryParse(Val);
6794 unsigned Minor = GNUCVer.getMinor().value_or(0);
6795 unsigned Patch = GNUCVer.getSubminor().value_or(0);
6796 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6797 D.Diag(diag::err_drv_invalid_value)
6798 << A->getAsString(Args) << A->getValue();
6800 } else if (!IsMSVCCompat) {
6801 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6802 GNUCVer = VersionTuple(4, 2, 1);
6804 if (!GNUCVer.empty()) {
6805 CmdArgs.push_back(
6806 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6809 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6810 if (!MSVT.empty())
6811 CmdArgs.push_back(
6812 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6814 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6815 if (ImplyVCPPCVer) {
6816 StringRef LanguageStandard;
6817 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6818 Std = StdArg;
6819 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6820 .Case("c11", "-std=c11")
6821 .Case("c17", "-std=c17")
6822 .Default("");
6823 if (LanguageStandard.empty())
6824 D.Diag(clang::diag::warn_drv_unused_argument)
6825 << StdArg->getAsString(Args);
6827 CmdArgs.push_back(LanguageStandard.data());
6829 if (ImplyVCPPCXXVer) {
6830 StringRef LanguageStandard;
6831 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6832 Std = StdArg;
6833 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6834 .Case("c++14", "-std=c++14")
6835 .Case("c++17", "-std=c++17")
6836 .Case("c++20", "-std=c++20")
6837 // TODO add c++23 and c++26 when MSVC supports it.
6838 .Case("c++latest", "-std=c++26")
6839 .Default("");
6840 if (LanguageStandard.empty())
6841 D.Diag(clang::diag::warn_drv_unused_argument)
6842 << StdArg->getAsString(Args);
6845 if (LanguageStandard.empty()) {
6846 if (IsMSVC2015Compatible)
6847 LanguageStandard = "-std=c++14";
6848 else
6849 LanguageStandard = "-std=c++11";
6852 CmdArgs.push_back(LanguageStandard.data());
6855 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
6856 options::OPT_fno_borland_extensions);
6858 // -fno-declspec is default, except for PS4/PS5.
6859 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6860 RawTriple.isPS()))
6861 CmdArgs.push_back("-fdeclspec");
6862 else if (Args.hasArg(options::OPT_fno_declspec))
6863 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6865 // -fthreadsafe-static is default, except for MSVC compatibility versions less
6866 // than 19.
6867 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6868 options::OPT_fno_threadsafe_statics,
6869 !types::isOpenCL(InputType) &&
6870 (!IsWindowsMSVC || IsMSVC2015Compatible)))
6871 CmdArgs.push_back("-fno-threadsafe-statics");
6873 // -fgnu-keywords default varies depending on language; only pass if
6874 // specified.
6875 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6876 options::OPT_fno_gnu_keywords);
6878 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
6879 options::OPT_fno_gnu89_inline);
6881 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
6882 options::OPT_finline_hint_functions,
6883 options::OPT_fno_inline_functions);
6884 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
6885 if (A->getOption().matches(options::OPT_fno_inline))
6886 A->render(Args, CmdArgs);
6887 } else if (InlineArg) {
6888 InlineArg->render(Args, CmdArgs);
6891 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
6893 // FIXME: Find a better way to determine whether we are in C++20.
6894 bool HaveCxx20 =
6895 Std &&
6896 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
6897 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
6898 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
6899 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
6900 Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
6901 Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
6902 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
6903 bool HaveModules =
6904 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
6906 // -fdelayed-template-parsing is default when targeting MSVC.
6907 // Many old Windows SDK versions require this to parse.
6909 // According to
6910 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
6911 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
6912 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
6913 // not enable -fdelayed-template-parsing by default after C++20.
6915 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
6916 // able to disable this by default at some point.
6917 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6918 options::OPT_fno_delayed_template_parsing,
6919 IsWindowsMSVC && !HaveCxx20)) {
6920 if (HaveCxx20)
6921 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
6923 CmdArgs.push_back("-fdelayed-template-parsing");
6926 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6927 options::OPT_fno_pch_validate_input_files_content, false))
6928 CmdArgs.push_back("-fvalidate-ast-input-files-content");
6929 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6930 options::OPT_fno_pch_instantiate_templates, false))
6931 CmdArgs.push_back("-fpch-instantiate-templates");
6932 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6933 false))
6934 CmdArgs.push_back("-fmodules-codegen");
6935 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6936 false))
6937 CmdArgs.push_back("-fmodules-debuginfo");
6939 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6940 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6941 Input, CmdArgs);
6943 if (types::isObjC(Input.getType()) &&
6944 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6945 options::OPT_fno_objc_encode_cxx_class_template_spec,
6946 !Runtime.isNeXTFamily()))
6947 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6949 if (Args.hasFlag(options::OPT_fapplication_extension,
6950 options::OPT_fno_application_extension, false))
6951 CmdArgs.push_back("-fapplication-extension");
6953 // Handle GCC-style exception args.
6954 bool EH = false;
6955 if (!C.getDriver().IsCLMode())
6956 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6958 // Handle exception personalities
6959 Arg *A = Args.getLastArg(
6960 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6961 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6962 if (A) {
6963 const Option &Opt = A->getOption();
6964 if (Opt.matches(options::OPT_fsjlj_exceptions))
6965 CmdArgs.push_back("-exception-model=sjlj");
6966 if (Opt.matches(options::OPT_fseh_exceptions))
6967 CmdArgs.push_back("-exception-model=seh");
6968 if (Opt.matches(options::OPT_fdwarf_exceptions))
6969 CmdArgs.push_back("-exception-model=dwarf");
6970 if (Opt.matches(options::OPT_fwasm_exceptions))
6971 CmdArgs.push_back("-exception-model=wasm");
6972 } else {
6973 switch (TC.GetExceptionModel(Args)) {
6974 default:
6975 break;
6976 case llvm::ExceptionHandling::DwarfCFI:
6977 CmdArgs.push_back("-exception-model=dwarf");
6978 break;
6979 case llvm::ExceptionHandling::SjLj:
6980 CmdArgs.push_back("-exception-model=sjlj");
6981 break;
6982 case llvm::ExceptionHandling::WinEH:
6983 CmdArgs.push_back("-exception-model=seh");
6984 break;
6988 // C++ "sane" operator new.
6989 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6990 options::OPT_fno_assume_sane_operator_new);
6992 // -fassume-unique-vtables is on by default.
6993 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
6994 options::OPT_fno_assume_unique_vtables);
6996 // -frelaxed-template-template-args is off by default, as it is a severe
6997 // breaking change until a corresponding change to template partial ordering
6998 // is provided.
6999 Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
7000 options::OPT_fno_relaxed_template_template_args);
7002 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
7003 // most platforms.
7004 Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
7005 options::OPT_fno_sized_deallocation);
7007 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7008 // by default.
7009 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7010 options::OPT_fno_aligned_allocation,
7011 options::OPT_faligned_new_EQ)) {
7012 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7013 CmdArgs.push_back("-fno-aligned-allocation");
7014 else
7015 CmdArgs.push_back("-faligned-allocation");
7018 // The default new alignment can be specified using a dedicated option or via
7019 // a GCC-compatible option that also turns on aligned allocation.
7020 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7021 options::OPT_faligned_new_EQ))
7022 CmdArgs.push_back(
7023 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7025 // -fconstant-cfstrings is default, and may be subject to argument translation
7026 // on Darwin.
7027 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7028 options::OPT_fno_constant_cfstrings, true) ||
7029 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7030 options::OPT_mno_constant_cfstrings, true))
7031 CmdArgs.push_back("-fno-constant-cfstrings");
7033 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7034 options::OPT_fno_pascal_strings);
7036 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7037 // -fno-pack-struct doesn't apply to -fpack-struct=.
7038 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7039 std::string PackStructStr = "-fpack-struct=";
7040 PackStructStr += A->getValue();
7041 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
7042 } else if (Args.hasFlag(options::OPT_fpack_struct,
7043 options::OPT_fno_pack_struct, false)) {
7044 CmdArgs.push_back("-fpack-struct=1");
7047 // Handle -fmax-type-align=N and -fno-type-align
7048 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7049 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7050 if (!SkipMaxTypeAlign) {
7051 std::string MaxTypeAlignStr = "-fmax-type-align=";
7052 MaxTypeAlignStr += A->getValue();
7053 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7055 } else if (RawTriple.isOSDarwin()) {
7056 if (!SkipMaxTypeAlign) {
7057 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7058 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7062 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7063 CmdArgs.push_back("-Qn");
7065 // -fno-common is the default, set -fcommon only when that flag is set.
7066 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7068 // -fsigned-bitfields is default, and clang doesn't yet support
7069 // -funsigned-bitfields.
7070 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7071 options::OPT_funsigned_bitfields, true))
7072 D.Diag(diag::warn_drv_clang_unsupported)
7073 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7075 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7076 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7077 D.Diag(diag::err_drv_clang_unsupported)
7078 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7080 // -finput_charset=UTF-8 is default. Reject others
7081 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7082 StringRef value = inputCharset->getValue();
7083 if (!value.equals_insensitive("utf-8"))
7084 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7085 << value;
7088 // -fexec_charset=UTF-8 is default. Reject others
7089 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7090 StringRef value = execCharset->getValue();
7091 if (!value.equals_insensitive("utf-8"))
7092 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7093 << value;
7096 RenderDiagnosticsOptions(D, Args, CmdArgs);
7098 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7099 options::OPT_fno_asm_blocks);
7101 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7102 options::OPT_fno_gnu_inline_asm);
7104 // Enable vectorization per default according to the optimization level
7105 // selected. For optimization levels that want vectorization we use the alias
7106 // option to simplify the hasFlag logic.
7107 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
7108 OptSpecifier VectorizeAliasOption =
7109 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
7110 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
7111 options::OPT_fno_vectorize, EnableVec))
7112 CmdArgs.push_back("-vectorize-loops");
7114 // -fslp-vectorize is enabled based on the optimization level selected.
7115 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
7116 OptSpecifier SLPVectAliasOption =
7117 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
7118 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
7119 options::OPT_fno_slp_vectorize, EnableSLPVec))
7120 CmdArgs.push_back("-vectorize-slp");
7122 ParseMPreferVectorWidth(D, Args, CmdArgs);
7124 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7125 Args.AddLastArg(CmdArgs,
7126 options::OPT_fsanitize_undefined_strip_path_components_EQ);
7128 // -fdollars-in-identifiers default varies depending on platform and
7129 // language; only pass if specified.
7130 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7131 options::OPT_fno_dollars_in_identifiers)) {
7132 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7133 CmdArgs.push_back("-fdollars-in-identifiers");
7134 else
7135 CmdArgs.push_back("-fno-dollars-in-identifiers");
7138 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7139 options::OPT_fno_apple_pragma_pack);
7141 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7142 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7143 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7145 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7146 options::OPT_fno_rewrite_imports, false);
7147 if (RewriteImports)
7148 CmdArgs.push_back("-frewrite-imports");
7150 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7151 options::OPT_fno_directives_only);
7153 // Enable rewrite includes if the user's asked for it or if we're generating
7154 // diagnostics.
7155 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7156 // nice to enable this when doing a crashdump for modules as well.
7157 if (Args.hasFlag(options::OPT_frewrite_includes,
7158 options::OPT_fno_rewrite_includes, false) ||
7159 (C.isForDiagnostics() && !HaveModules))
7160 CmdArgs.push_back("-frewrite-includes");
7162 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7163 if (Arg *A = Args.getLastArg(options::OPT_traditional,
7164 options::OPT_traditional_cpp)) {
7165 if (isa<PreprocessJobAction>(JA))
7166 CmdArgs.push_back("-traditional-cpp");
7167 else
7168 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7171 Args.AddLastArg(CmdArgs, options::OPT_dM);
7172 Args.AddLastArg(CmdArgs, options::OPT_dD);
7173 Args.AddLastArg(CmdArgs, options::OPT_dI);
7175 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7177 // Handle serialized diagnostics.
7178 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7179 CmdArgs.push_back("-serialize-diagnostic-file");
7180 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7183 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7184 CmdArgs.push_back("-fretain-comments-from-system-headers");
7186 // Forward -fcomment-block-commands to -cc1.
7187 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7188 // Forward -fparse-all-comments to -cc1.
7189 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7191 // Turn -fplugin=name.so into -load name.so
7192 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7193 CmdArgs.push_back("-load");
7194 CmdArgs.push_back(A->getValue());
7195 A->claim();
7198 // Turn -fplugin-arg-pluginname-key=value into
7199 // -plugin-arg-pluginname key=value
7200 // GCC has an actual plugin_argument struct with key/value pairs that it
7201 // passes to its plugins, but we don't, so just pass it on as-is.
7203 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7204 // argument key are allowed to contain dashes. GCC therefore only
7205 // allows dashes in the key. We do the same.
7206 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7207 auto ArgValue = StringRef(A->getValue());
7208 auto FirstDashIndex = ArgValue.find('-');
7209 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7210 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7212 A->claim();
7213 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7214 if (PluginName.empty()) {
7215 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7216 } else {
7217 D.Diag(diag::warn_drv_missing_plugin_arg)
7218 << PluginName << A->getAsString(Args);
7220 continue;
7223 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7224 CmdArgs.push_back(Args.MakeArgString(Arg));
7227 // Forward -fpass-plugin=name.so to -cc1.
7228 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7229 CmdArgs.push_back(
7230 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7231 A->claim();
7234 // Forward --vfsoverlay to -cc1.
7235 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7236 CmdArgs.push_back("--vfsoverlay");
7237 CmdArgs.push_back(A->getValue());
7238 A->claim();
7241 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7242 options::OPT_fno_safe_buffer_usage_suggestions);
7244 // Setup statistics file output.
7245 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7246 if (!StatsFile.empty()) {
7247 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7248 if (D.CCPrintInternalStats)
7249 CmdArgs.push_back("-stats-file-append");
7252 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7253 // parser.
7254 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7255 Arg->claim();
7256 // -finclude-default-header flag is for preprocessor,
7257 // do not pass it to other cc1 commands when save-temps is enabled
7258 if (C.getDriver().isSaveTempsEnabled() &&
7259 !isa<PreprocessJobAction>(JA)) {
7260 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7261 continue;
7263 CmdArgs.push_back(Arg->getValue());
7265 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7266 A->claim();
7268 // We translate this by hand to the -cc1 argument, since nightly test uses
7269 // it and developers have been trained to spell it with -mllvm. Both
7270 // spellings are now deprecated and should be removed.
7271 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7272 CmdArgs.push_back("-disable-llvm-optzns");
7273 } else {
7274 A->render(Args, CmdArgs);
7278 // With -save-temps, we want to save the unoptimized bitcode output from the
7279 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7280 // by the frontend.
7281 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7282 // has slightly different breakdown between stages.
7283 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7284 // pristine IR generated by the frontend. Ideally, a new compile action should
7285 // be added so both IR can be captured.
7286 if ((C.getDriver().isSaveTempsEnabled() ||
7287 JA.isHostOffloading(Action::OFK_OpenMP)) &&
7288 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7289 isa<CompileJobAction>(JA))
7290 CmdArgs.push_back("-disable-llvm-passes");
7292 Args.AddAllArgs(CmdArgs, options::OPT_undef);
7294 const char *Exec = D.getClangProgramPath();
7296 // Optionally embed the -cc1 level arguments into the debug info or a
7297 // section, for build analysis.
7298 // Also record command line arguments into the debug info if
7299 // -grecord-gcc-switches options is set on.
7300 // By default, -gno-record-gcc-switches is set on and no recording.
7301 auto GRecordSwitches =
7302 Args.hasFlag(options::OPT_grecord_command_line,
7303 options::OPT_gno_record_command_line, false);
7304 auto FRecordSwitches =
7305 Args.hasFlag(options::OPT_frecord_command_line,
7306 options::OPT_fno_record_command_line, false);
7307 if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
7308 !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
7309 D.Diag(diag::err_drv_unsupported_opt_for_target)
7310 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
7311 << TripleStr;
7312 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
7313 ArgStringList OriginalArgs;
7314 for (const auto &Arg : Args)
7315 Arg->render(Args, OriginalArgs);
7317 SmallString<256> Flags;
7318 EscapeSpacesAndBackslashes(Exec, Flags);
7319 for (const char *OriginalArg : OriginalArgs) {
7320 SmallString<128> EscapedArg;
7321 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7322 Flags += " ";
7323 Flags += EscapedArg;
7325 auto FlagsArgString = Args.MakeArgString(Flags);
7326 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7327 CmdArgs.push_back("-dwarf-debug-flags");
7328 CmdArgs.push_back(FlagsArgString);
7330 if (FRecordSwitches) {
7331 CmdArgs.push_back("-record-command-line");
7332 CmdArgs.push_back(FlagsArgString);
7336 // Host-side offloading compilation receives all device-side outputs. Include
7337 // them in the host compilation depending on the target. If the host inputs
7338 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7339 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7340 CmdArgs.push_back("-fcuda-include-gpubinary");
7341 CmdArgs.push_back(CudaDeviceInput->getFilename());
7342 } else if (!HostOffloadingInputs.empty()) {
7343 if ((IsCuda || IsHIP) && !IsRDCMode) {
7344 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7345 CmdArgs.push_back("-fcuda-include-gpubinary");
7346 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7347 } else {
7348 for (const InputInfo Input : HostOffloadingInputs)
7349 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7350 TC.getInputFilename(Input)));
7354 if (IsCuda) {
7355 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7356 options::OPT_fno_cuda_short_ptr, false))
7357 CmdArgs.push_back("-fcuda-short-ptr");
7360 if (IsCuda || IsHIP) {
7361 // Determine the original source input.
7362 const Action *SourceAction = &JA;
7363 while (SourceAction->getKind() != Action::InputClass) {
7364 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7365 SourceAction = SourceAction->getInputs()[0];
7367 auto CUID = cast<InputAction>(SourceAction)->getId();
7368 if (!CUID.empty())
7369 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7371 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7372 // be overriden by -fno-gpu-approx-transcendentals.
7373 bool UseApproxTranscendentals = Args.hasFlag(
7374 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
7375 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
7376 options::OPT_fno_gpu_approx_transcendentals,
7377 UseApproxTranscendentals))
7378 CmdArgs.push_back("-fgpu-approx-transcendentals");
7379 } else {
7380 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
7381 options::OPT_fno_gpu_approx_transcendentals);
7384 if (IsHIP) {
7385 CmdArgs.push_back("-fcuda-allow-variadic-functions");
7386 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7389 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
7390 options::OPT_fno_offload_uniform_block);
7392 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
7393 options::OPT_fno_offload_implicit_host_device_templates);
7395 if (IsCudaDevice || IsHIPDevice) {
7396 StringRef InlineThresh =
7397 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7398 if (!InlineThresh.empty()) {
7399 std::string ArgStr =
7400 std::string("-inline-threshold=") + InlineThresh.str();
7401 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7405 if (IsHIPDevice)
7406 Args.addOptOutFlag(CmdArgs,
7407 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7408 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7410 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7411 // to specify the result of the compile phase on the host, so the meaningful
7412 // device declarations can be identified. Also, -fopenmp-is-target-device is
7413 // passed along to tell the frontend that it is generating code for a device,
7414 // so that only the relevant declarations are emitted.
7415 if (IsOpenMPDevice) {
7416 CmdArgs.push_back("-fopenmp-is-target-device");
7417 if (OpenMPDeviceInput) {
7418 CmdArgs.push_back("-fopenmp-host-ir-file-path");
7419 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7423 if (Triple.isAMDGPU()) {
7424 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7426 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7427 options::OPT_mno_unsafe_fp_atomics);
7428 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7429 options::OPT_mno_amdgpu_ieee);
7432 // For all the host OpenMP offloading compile jobs we need to pass the targets
7433 // information using -fopenmp-targets= option.
7434 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
7435 SmallString<128> Targets("-fopenmp-targets=");
7437 SmallVector<std::string, 4> Triples;
7438 auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
7439 std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
7440 [](auto TC) { return TC.second->getTripleString(); });
7441 CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
7444 bool VirtualFunctionElimination =
7445 Args.hasFlag(options::OPT_fvirtual_function_elimination,
7446 options::OPT_fno_virtual_function_elimination, false);
7447 if (VirtualFunctionElimination) {
7448 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7449 // in the future).
7450 if (LTOMode != LTOK_Full)
7451 D.Diag(diag::err_drv_argument_only_allowed_with)
7452 << "-fvirtual-function-elimination"
7453 << "-flto=full";
7455 CmdArgs.push_back("-fvirtual-function-elimination");
7458 // VFE requires whole-program-vtables, and enables it by default.
7459 bool WholeProgramVTables = Args.hasFlag(
7460 options::OPT_fwhole_program_vtables,
7461 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7462 if (VirtualFunctionElimination && !WholeProgramVTables) {
7463 D.Diag(diag::err_drv_argument_not_allowed_with)
7464 << "-fno-whole-program-vtables"
7465 << "-fvirtual-function-elimination";
7468 if (WholeProgramVTables) {
7469 // PS4 uses the legacy LTO API, which does not support this feature in
7470 // ThinLTO mode.
7471 bool IsPS4 = getToolChain().getTriple().isPS4();
7473 // Check if we passed LTO options but they were suppressed because this is a
7474 // device offloading action, or we passed device offload LTO options which
7475 // were suppressed because this is not the device offload action.
7476 // Check if we are using PS4 in regular LTO mode.
7477 // Otherwise, issue an error.
7478 if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
7479 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7480 D.Diag(diag::err_drv_argument_only_allowed_with)
7481 << "-fwhole-program-vtables"
7482 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7484 // Propagate -fwhole-program-vtables if this is an LTO compile.
7485 if (IsUsingLTO)
7486 CmdArgs.push_back("-fwhole-program-vtables");
7489 bool DefaultsSplitLTOUnit =
7490 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7491 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7492 (!Triple.isPS4() && UnifiedLTO);
7493 bool SplitLTOUnit =
7494 Args.hasFlag(options::OPT_fsplit_lto_unit,
7495 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7496 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7497 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7498 << "-fsanitize=cfi";
7499 if (SplitLTOUnit)
7500 CmdArgs.push_back("-fsplit-lto-unit");
7502 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
7503 options::OPT_fno_fat_lto_objects)) {
7504 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
7505 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
7506 if (!Triple.isOSBinFormatELF()) {
7507 D.Diag(diag::err_drv_unsupported_opt_for_target)
7508 << A->getAsString(Args) << TC.getTripleString();
7510 CmdArgs.push_back(Args.MakeArgString(
7511 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
7512 CmdArgs.push_back("-flto-unit");
7513 CmdArgs.push_back("-ffat-lto-objects");
7514 A->render(Args, CmdArgs);
7518 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7519 options::OPT_fno_global_isel)) {
7520 CmdArgs.push_back("-mllvm");
7521 if (A->getOption().matches(options::OPT_fglobal_isel)) {
7522 CmdArgs.push_back("-global-isel=1");
7524 // GISel is on by default on AArch64 -O0, so don't bother adding
7525 // the fallback remarks for it. Other combinations will add a warning of
7526 // some kind.
7527 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7528 bool IsOptLevelSupported = false;
7530 Arg *A = Args.getLastArg(options::OPT_O_Group);
7531 if (Triple.getArch() == llvm::Triple::aarch64) {
7532 if (!A || A->getOption().matches(options::OPT_O0))
7533 IsOptLevelSupported = true;
7535 if (!IsArchSupported || !IsOptLevelSupported) {
7536 CmdArgs.push_back("-mllvm");
7537 CmdArgs.push_back("-global-isel-abort=2");
7539 if (!IsArchSupported)
7540 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7541 else
7542 D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7544 } else {
7545 CmdArgs.push_back("-global-isel=0");
7549 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
7550 CmdArgs.push_back("-forder-file-instrumentation");
7551 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
7552 // on, we need to pass these flags as linker flags and that will be handled
7553 // outside of the compiler.
7554 if (!IsUsingLTO) {
7555 CmdArgs.push_back("-mllvm");
7556 CmdArgs.push_back("-enable-order-file-instrumentation");
7560 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7561 options::OPT_fno_force_enable_int128)) {
7562 if (A->getOption().matches(options::OPT_fforce_enable_int128))
7563 CmdArgs.push_back("-fforce-enable-int128");
7566 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7567 options::OPT_fno_keep_static_consts);
7568 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
7569 options::OPT_fno_keep_persistent_storage_variables);
7570 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7571 options::OPT_fno_complete_member_pointers);
7572 Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7573 options::OPT_fno_cxx_static_destructors);
7575 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7577 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7578 options::OPT_mno_outline_atomics)) {
7579 // Option -moutline-atomics supported for AArch64 target only.
7580 if (!Triple.isAArch64()) {
7581 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
7582 << Triple.getArchName() << A->getOption().getName();
7583 } else {
7584 if (A->getOption().matches(options::OPT_moutline_atomics)) {
7585 CmdArgs.push_back("-target-feature");
7586 CmdArgs.push_back("+outline-atomics");
7587 } else {
7588 CmdArgs.push_back("-target-feature");
7589 CmdArgs.push_back("-outline-atomics");
7592 } else if (Triple.isAArch64() &&
7593 getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7594 CmdArgs.push_back("-target-feature");
7595 CmdArgs.push_back("+outline-atomics");
7598 if (Triple.isAArch64() &&
7599 (Args.hasArg(options::OPT_mno_fmv) ||
7600 (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7601 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7602 // Disable Function Multiversioning on AArch64 target.
7603 CmdArgs.push_back("-target-feature");
7604 CmdArgs.push_back("-fmv");
7607 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7608 (TC.getTriple().isOSBinFormatELF() ||
7609 TC.getTriple().isOSBinFormatCOFF()) &&
7610 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7611 !TC.getTriple().isOSNetBSD() &&
7612 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7613 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7614 CmdArgs.push_back("-faddrsig");
7616 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7617 (EH || UnwindTables || AsyncUnwindTables ||
7618 DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7619 CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7621 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7622 std::string Str = A->getAsString(Args);
7623 if (!TC.getTriple().isOSBinFormatELF())
7624 D.Diag(diag::err_drv_unsupported_opt_for_target)
7625 << Str << TC.getTripleString();
7626 CmdArgs.push_back(Args.MakeArgString(Str));
7629 // Add the "-o out -x type src.c" flags last. This is done primarily to make
7630 // the -cc1 command easier to edit when reproducing compiler crashes.
7631 if (Output.getType() == types::TY_Dependencies) {
7632 // Handled with other dependency code.
7633 } else if (Output.isFilename()) {
7634 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7635 Output.getType() == clang::driver::types::TY_IFS) {
7636 SmallString<128> OutputFilename(Output.getFilename());
7637 llvm::sys::path::replace_extension(OutputFilename, "ifs");
7638 CmdArgs.push_back("-o");
7639 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7640 } else {
7641 CmdArgs.push_back("-o");
7642 CmdArgs.push_back(Output.getFilename());
7644 } else {
7645 assert(Output.isNothing() && "Invalid output.");
7648 addDashXForInput(Args, Input, CmdArgs);
7650 ArrayRef<InputInfo> FrontendInputs = Input;
7651 if (IsExtractAPI)
7652 FrontendInputs = ExtractAPIInputs;
7653 else if (Input.isNothing())
7654 FrontendInputs = {};
7656 for (const InputInfo &Input : FrontendInputs) {
7657 if (Input.isFilename())
7658 CmdArgs.push_back(Input.getFilename());
7659 else
7660 Input.getInputArg().renderAsInput(Args, CmdArgs);
7663 if (D.CC1Main && !D.CCGenDiagnostics) {
7664 // Invoke the CC1 directly in this process
7665 C.addCommand(std::make_unique<CC1Command>(
7666 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7667 Output, D.getPrependArg()));
7668 } else {
7669 C.addCommand(std::make_unique<Command>(
7670 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7671 Output, D.getPrependArg()));
7674 // Make the compile command echo its inputs for /showFilenames.
7675 if (Output.getType() == types::TY_Object &&
7676 Args.hasFlag(options::OPT__SLASH_showFilenames,
7677 options::OPT__SLASH_showFilenames_, false)) {
7678 C.getJobs().getJobs().back()->PrintInputFilenames = true;
7681 if (Arg *A = Args.getLastArg(options::OPT_pg))
7682 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7683 !Args.hasArg(options::OPT_mfentry))
7684 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
7685 << A->getAsString(Args);
7687 // Claim some arguments which clang supports automatically.
7689 // -fpch-preprocess is used with gcc to add a special marker in the output to
7690 // include the PCH file.
7691 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
7693 // Claim some arguments which clang doesn't support, but we don't
7694 // care to warn the user about.
7695 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
7696 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
7698 // Disable warnings for clang -E -emit-llvm foo.c
7699 Args.ClaimAllArgs(options::OPT_emit_llvm);
7702 Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
7703 // CAUTION! The first constructor argument ("clang") is not arbitrary,
7704 // as it is for other tools. Some operations on a Tool actually test
7705 // whether that tool is Clang based on the Tool's Name as a string.
7706 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
7708 Clang::~Clang() {}
7710 /// Add options related to the Objective-C runtime/ABI.
7712 /// Returns true if the runtime is non-fragile.
7713 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
7714 const InputInfoList &inputs,
7715 ArgStringList &cmdArgs,
7716 RewriteKind rewriteKind) const {
7717 // Look for the controlling runtime option.
7718 Arg *runtimeArg =
7719 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
7720 options::OPT_fobjc_runtime_EQ);
7722 // Just forward -fobjc-runtime= to the frontend. This supercedes
7723 // options about fragility.
7724 if (runtimeArg &&
7725 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
7726 ObjCRuntime runtime;
7727 StringRef value = runtimeArg->getValue();
7728 if (runtime.tryParse(value)) {
7729 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
7730 << value;
7732 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
7733 (runtime.getVersion() >= VersionTuple(2, 0)))
7734 if (!getToolChain().getTriple().isOSBinFormatELF() &&
7735 !getToolChain().getTriple().isOSBinFormatCOFF()) {
7736 getToolChain().getDriver().Diag(
7737 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
7738 << runtime.getVersion().getMajor();
7741 runtimeArg->render(args, cmdArgs);
7742 return runtime;
7745 // Otherwise, we'll need the ABI "version". Version numbers are
7746 // slightly confusing for historical reasons:
7747 // 1 - Traditional "fragile" ABI
7748 // 2 - Non-fragile ABI, version 1
7749 // 3 - Non-fragile ABI, version 2
7750 unsigned objcABIVersion = 1;
7751 // If -fobjc-abi-version= is present, use that to set the version.
7752 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
7753 StringRef value = abiArg->getValue();
7754 if (value == "1")
7755 objcABIVersion = 1;
7756 else if (value == "2")
7757 objcABIVersion = 2;
7758 else if (value == "3")
7759 objcABIVersion = 3;
7760 else
7761 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
7762 } else {
7763 // Otherwise, determine if we are using the non-fragile ABI.
7764 bool nonFragileABIIsDefault =
7765 (rewriteKind == RK_NonFragile ||
7766 (rewriteKind == RK_None &&
7767 getToolChain().IsObjCNonFragileABIDefault()));
7768 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
7769 options::OPT_fno_objc_nonfragile_abi,
7770 nonFragileABIIsDefault)) {
7771 // Determine the non-fragile ABI version to use.
7772 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
7773 unsigned nonFragileABIVersion = 1;
7774 #else
7775 unsigned nonFragileABIVersion = 2;
7776 #endif
7778 if (Arg *abiArg =
7779 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
7780 StringRef value = abiArg->getValue();
7781 if (value == "1")
7782 nonFragileABIVersion = 1;
7783 else if (value == "2")
7784 nonFragileABIVersion = 2;
7785 else
7786 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
7787 << value;
7790 objcABIVersion = 1 + nonFragileABIVersion;
7791 } else {
7792 objcABIVersion = 1;
7796 // We don't actually care about the ABI version other than whether
7797 // it's non-fragile.
7798 bool isNonFragile = objcABIVersion != 1;
7800 // If we have no runtime argument, ask the toolchain for its default runtime.
7801 // However, the rewriter only really supports the Mac runtime, so assume that.
7802 ObjCRuntime runtime;
7803 if (!runtimeArg) {
7804 switch (rewriteKind) {
7805 case RK_None:
7806 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7807 break;
7808 case RK_Fragile:
7809 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7810 break;
7811 case RK_NonFragile:
7812 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7813 break;
7816 // -fnext-runtime
7817 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7818 // On Darwin, make this use the default behavior for the toolchain.
7819 if (getToolChain().getTriple().isOSDarwin()) {
7820 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7822 // Otherwise, build for a generic macosx port.
7823 } else {
7824 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7827 // -fgnu-runtime
7828 } else {
7829 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7830 // Legacy behaviour is to target the gnustep runtime if we are in
7831 // non-fragile mode or the GCC runtime in fragile mode.
7832 if (isNonFragile)
7833 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7834 else
7835 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7838 if (llvm::any_of(inputs, [](const InputInfo &input) {
7839 return types::isObjC(input.getType());
7841 cmdArgs.push_back(
7842 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7843 return runtime;
7846 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7847 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7848 I += HaveDash;
7849 return !HaveDash;
7852 namespace {
7853 struct EHFlags {
7854 bool Synch = false;
7855 bool Asynch = false;
7856 bool NoUnwindC = false;
7858 } // end anonymous namespace
7860 /// /EH controls whether to run destructor cleanups when exceptions are
7861 /// thrown. There are three modifiers:
7862 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7863 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7864 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7865 /// - c: Assume that extern "C" functions are implicitly nounwind.
7866 /// The default is /EHs-c-, meaning cleanups are disabled.
7867 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7868 EHFlags EH;
7870 std::vector<std::string> EHArgs =
7871 Args.getAllArgValues(options::OPT__SLASH_EH);
7872 for (auto EHVal : EHArgs) {
7873 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7874 switch (EHVal[I]) {
7875 case 'a':
7876 EH.Asynch = maybeConsumeDash(EHVal, I);
7877 if (EH.Asynch)
7878 EH.Synch = false;
7879 continue;
7880 case 'c':
7881 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7882 continue;
7883 case 's':
7884 EH.Synch = maybeConsumeDash(EHVal, I);
7885 if (EH.Synch)
7886 EH.Asynch = false;
7887 continue;
7888 default:
7889 break;
7891 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7892 break;
7895 // The /GX, /GX- flags are only processed if there are not /EH flags.
7896 // The default is that /GX is not specified.
7897 if (EHArgs.empty() &&
7898 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7899 /*Default=*/false)) {
7900 EH.Synch = true;
7901 EH.NoUnwindC = true;
7904 if (Args.hasArg(options::OPT__SLASH_kernel)) {
7905 EH.Synch = false;
7906 EH.NoUnwindC = false;
7907 EH.Asynch = false;
7910 return EH;
7913 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7914 ArgStringList &CmdArgs) const {
7915 bool isNVPTX = getToolChain().getTriple().isNVPTX();
7917 ProcessVSRuntimeLibrary(Args, CmdArgs);
7919 if (Arg *ShowIncludes =
7920 Args.getLastArg(options::OPT__SLASH_showIncludes,
7921 options::OPT__SLASH_showIncludes_user)) {
7922 CmdArgs.push_back("--show-includes");
7923 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7924 CmdArgs.push_back("-sys-header-deps");
7927 // This controls whether or not we emit RTTI data for polymorphic types.
7928 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7929 /*Default=*/false))
7930 CmdArgs.push_back("-fno-rtti-data");
7932 // This controls whether or not we emit stack-protector instrumentation.
7933 // In MSVC, Buffer Security Check (/GS) is on by default.
7934 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7935 /*Default=*/true)) {
7936 CmdArgs.push_back("-stack-protector");
7937 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7940 const Driver &D = getToolChain().getDriver();
7942 EHFlags EH = parseClangCLEHFlags(D, Args);
7943 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7944 if (types::isCXX(InputType))
7945 CmdArgs.push_back("-fcxx-exceptions");
7946 CmdArgs.push_back("-fexceptions");
7947 if (EH.Asynch)
7948 CmdArgs.push_back("-fasync-exceptions");
7950 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7951 CmdArgs.push_back("-fexternc-nounwind");
7953 // /EP should expand to -E -P.
7954 if (Args.hasArg(options::OPT__SLASH_EP)) {
7955 CmdArgs.push_back("-E");
7956 CmdArgs.push_back("-P");
7959 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7960 options::OPT__SLASH_Zc_dllexportInlines,
7961 false)) {
7962 CmdArgs.push_back("-fno-dllexport-inlines");
7965 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
7966 options::OPT__SLASH_Zc_wchar_t, false)) {
7967 CmdArgs.push_back("-fno-wchar");
7970 if (Args.hasArg(options::OPT__SLASH_kernel)) {
7971 llvm::Triple::ArchType Arch = getToolChain().getArch();
7972 std::vector<std::string> Values =
7973 Args.getAllArgValues(options::OPT__SLASH_arch);
7974 if (!Values.empty()) {
7975 llvm::SmallSet<std::string, 4> SupportedArches;
7976 if (Arch == llvm::Triple::x86)
7977 SupportedArches.insert("IA32");
7979 for (auto &V : Values)
7980 if (!SupportedArches.contains(V))
7981 D.Diag(diag::err_drv_argument_not_allowed_with)
7982 << std::string("/arch:").append(V) << "/kernel";
7985 CmdArgs.push_back("-fno-rtti");
7986 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
7987 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
7988 << "/kernel";
7991 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
7992 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
7993 if (MostGeneralArg && BestCaseArg)
7994 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7995 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
7997 if (MostGeneralArg) {
7998 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
7999 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8000 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8002 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8003 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8004 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8005 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8006 << FirstConflict->getAsString(Args)
8007 << SecondConflict->getAsString(Args);
8009 if (SingleArg)
8010 CmdArgs.push_back("-fms-memptr-rep=single");
8011 else if (MultipleArg)
8012 CmdArgs.push_back("-fms-memptr-rep=multiple");
8013 else
8014 CmdArgs.push_back("-fms-memptr-rep=virtual");
8017 if (Args.hasArg(options::OPT_regcall4))
8018 CmdArgs.push_back("-regcall4");
8020 // Parse the default calling convention options.
8021 if (Arg *CCArg =
8022 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8023 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8024 options::OPT__SLASH_Gregcall)) {
8025 unsigned DCCOptId = CCArg->getOption().getID();
8026 const char *DCCFlag = nullptr;
8027 bool ArchSupported = !isNVPTX;
8028 llvm::Triple::ArchType Arch = getToolChain().getArch();
8029 switch (DCCOptId) {
8030 case options::OPT__SLASH_Gd:
8031 DCCFlag = "-fdefault-calling-conv=cdecl";
8032 break;
8033 case options::OPT__SLASH_Gr:
8034 ArchSupported = Arch == llvm::Triple::x86;
8035 DCCFlag = "-fdefault-calling-conv=fastcall";
8036 break;
8037 case options::OPT__SLASH_Gz:
8038 ArchSupported = Arch == llvm::Triple::x86;
8039 DCCFlag = "-fdefault-calling-conv=stdcall";
8040 break;
8041 case options::OPT__SLASH_Gv:
8042 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8043 DCCFlag = "-fdefault-calling-conv=vectorcall";
8044 break;
8045 case options::OPT__SLASH_Gregcall:
8046 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8047 DCCFlag = "-fdefault-calling-conv=regcall";
8048 break;
8051 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8052 if (ArchSupported && DCCFlag)
8053 CmdArgs.push_back(DCCFlag);
8056 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8057 CmdArgs.push_back("-regcall4");
8059 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8061 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8062 CmdArgs.push_back("-fdiagnostics-format");
8063 CmdArgs.push_back("msvc");
8066 if (Args.hasArg(options::OPT__SLASH_kernel))
8067 CmdArgs.push_back("-fms-kernel");
8069 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8070 StringRef GuardArgs = A->getValue();
8071 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8072 // "ehcont-".
8073 if (GuardArgs.equals_insensitive("cf")) {
8074 // Emit CFG instrumentation and the table of address-taken functions.
8075 CmdArgs.push_back("-cfguard");
8076 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8077 // Emit only the table of address-taken functions.
8078 CmdArgs.push_back("-cfguard-no-checks");
8079 } else if (GuardArgs.equals_insensitive("ehcont")) {
8080 // Emit EH continuation table.
8081 CmdArgs.push_back("-ehcontguard");
8082 } else if (GuardArgs.equals_insensitive("cf-") ||
8083 GuardArgs.equals_insensitive("ehcont-")) {
8084 // Do nothing, but we might want to emit a security warning in future.
8085 } else {
8086 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8088 A->claim();
8092 const char *Clang::getBaseInputName(const ArgList &Args,
8093 const InputInfo &Input) {
8094 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
8097 const char *Clang::getBaseInputStem(const ArgList &Args,
8098 const InputInfoList &Inputs) {
8099 const char *Str = getBaseInputName(Args, Inputs[0]);
8101 if (const char *End = strrchr(Str, '.'))
8102 return Args.MakeArgString(std::string(Str, End));
8104 return Str;
8107 const char *Clang::getDependencyFileName(const ArgList &Args,
8108 const InputInfoList &Inputs) {
8109 // FIXME: Think about this more.
8111 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8112 SmallString<128> OutputFilename(OutputOpt->getValue());
8113 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8114 return Args.MakeArgString(OutputFilename);
8117 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8120 // Begin ClangAs
8122 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8123 ArgStringList &CmdArgs) const {
8124 StringRef CPUName;
8125 StringRef ABIName;
8126 const llvm::Triple &Triple = getToolChain().getTriple();
8127 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8129 CmdArgs.push_back("-target-abi");
8130 CmdArgs.push_back(ABIName.data());
8133 void ClangAs::AddX86TargetArgs(const ArgList &Args,
8134 ArgStringList &CmdArgs) const {
8135 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8136 /*IsLTO=*/false);
8138 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8139 StringRef Value = A->getValue();
8140 if (Value == "intel" || Value == "att") {
8141 CmdArgs.push_back("-mllvm");
8142 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8143 } else {
8144 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8145 << A->getSpelling() << Value;
8150 void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8151 ArgStringList &CmdArgs) const {
8152 CmdArgs.push_back("-target-abi");
8153 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8154 getToolChain().getTriple())
8155 .data());
8158 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8159 ArgStringList &CmdArgs) const {
8160 const llvm::Triple &Triple = getToolChain().getTriple();
8161 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8163 CmdArgs.push_back("-target-abi");
8164 CmdArgs.push_back(ABIName.data());
8166 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8167 options::OPT_mno_default_build_attributes, true)) {
8168 CmdArgs.push_back("-mllvm");
8169 CmdArgs.push_back("-riscv-add-build-attributes");
8173 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8174 const InputInfo &Output, const InputInfoList &Inputs,
8175 const ArgList &Args,
8176 const char *LinkingOutput) const {
8177 ArgStringList CmdArgs;
8179 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8180 const InputInfo &Input = Inputs[0];
8182 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8183 const std::string &TripleStr = Triple.getTriple();
8184 const auto &D = getToolChain().getDriver();
8186 // Don't warn about "clang -w -c foo.s"
8187 Args.ClaimAllArgs(options::OPT_w);
8188 // and "clang -emit-llvm -c foo.s"
8189 Args.ClaimAllArgs(options::OPT_emit_llvm);
8191 claimNoWarnArgs(Args);
8193 // Invoke ourselves in -cc1as mode.
8195 // FIXME: Implement custom jobs for internal actions.
8196 CmdArgs.push_back("-cc1as");
8198 // Add the "effective" target triple.
8199 CmdArgs.push_back("-triple");
8200 CmdArgs.push_back(Args.MakeArgString(TripleStr));
8202 getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
8204 // Set the output mode, we currently only expect to be used as a real
8205 // assembler.
8206 CmdArgs.push_back("-filetype");
8207 CmdArgs.push_back("obj");
8209 // Set the main file name, so that debug info works even with
8210 // -save-temps or preprocessed assembly.
8211 CmdArgs.push_back("-main-file-name");
8212 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8214 // Add the target cpu
8215 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8216 if (!CPU.empty()) {
8217 CmdArgs.push_back("-target-cpu");
8218 CmdArgs.push_back(Args.MakeArgString(CPU));
8221 // Add the target features
8222 getTargetFeatures(D, Triple, Args, CmdArgs, true);
8224 // Ignore explicit -force_cpusubtype_ALL option.
8225 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8227 // Pass along any -I options so we get proper .include search paths.
8228 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8230 // Determine the original source input.
8231 auto FindSource = [](const Action *S) -> const Action * {
8232 while (S->getKind() != Action::InputClass) {
8233 assert(!S->getInputs().empty() && "unexpected root action!");
8234 S = S->getInputs()[0];
8236 return S;
8238 const Action *SourceAction = FindSource(&JA);
8240 // Forward -g and handle debug info related flags, assuming we are dealing
8241 // with an actual assembly file.
8242 bool WantDebug = false;
8243 Args.ClaimAllArgs(options::OPT_g_Group);
8244 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8245 WantDebug = !A->getOption().matches(options::OPT_g0) &&
8246 !A->getOption().matches(options::OPT_ggdb0);
8248 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8249 llvm::codegenoptions::NoDebugInfo;
8251 // Add the -fdebug-compilation-dir flag if needed.
8252 const char *DebugCompilationDir =
8253 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
8255 if (SourceAction->getType() == types::TY_Asm ||
8256 SourceAction->getType() == types::TY_PP_Asm) {
8257 // You might think that it would be ok to set DebugInfoKind outside of
8258 // the guard for source type, however there is a test which asserts
8259 // that some assembler invocation receives no -debug-info-kind,
8260 // and it's not clear whether that test is just overly restrictive.
8261 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8262 : llvm::codegenoptions::NoDebugInfo);
8264 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
8265 CmdArgs);
8267 // Set the AT_producer to the clang version when using the integrated
8268 // assembler on assembly source files.
8269 CmdArgs.push_back("-dwarf-debug-producer");
8270 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8272 // And pass along -I options
8273 Args.AddAllArgs(CmdArgs, options::OPT_I);
8275 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8276 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8277 llvm::DebuggerKind::Default);
8278 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8279 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
8281 // Handle -fPIC et al -- the relocation-model affects the assembler
8282 // for some targets.
8283 llvm::Reloc::Model RelocationModel;
8284 unsigned PICLevel;
8285 bool IsPIE;
8286 std::tie(RelocationModel, PICLevel, IsPIE) =
8287 ParsePICArgs(getToolChain(), Args);
8289 const char *RMName = RelocationModelName(RelocationModel);
8290 if (RMName) {
8291 CmdArgs.push_back("-mrelocation-model");
8292 CmdArgs.push_back(RMName);
8295 // Optionally embed the -cc1as level arguments into the debug info, for build
8296 // analysis.
8297 if (getToolChain().UseDwarfDebugFlags()) {
8298 ArgStringList OriginalArgs;
8299 for (const auto &Arg : Args)
8300 Arg->render(Args, OriginalArgs);
8302 SmallString<256> Flags;
8303 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8304 EscapeSpacesAndBackslashes(Exec, Flags);
8305 for (const char *OriginalArg : OriginalArgs) {
8306 SmallString<128> EscapedArg;
8307 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8308 Flags += " ";
8309 Flags += EscapedArg;
8311 CmdArgs.push_back("-dwarf-debug-flags");
8312 CmdArgs.push_back(Args.MakeArgString(Flags));
8315 // FIXME: Add -static support, once we have it.
8317 // Add target specific flags.
8318 switch (getToolChain().getArch()) {
8319 default:
8320 break;
8322 case llvm::Triple::mips:
8323 case llvm::Triple::mipsel:
8324 case llvm::Triple::mips64:
8325 case llvm::Triple::mips64el:
8326 AddMIPSTargetArgs(Args, CmdArgs);
8327 break;
8329 case llvm::Triple::x86:
8330 case llvm::Triple::x86_64:
8331 AddX86TargetArgs(Args, CmdArgs);
8332 break;
8334 case llvm::Triple::arm:
8335 case llvm::Triple::armeb:
8336 case llvm::Triple::thumb:
8337 case llvm::Triple::thumbeb:
8338 // This isn't in AddARMTargetArgs because we want to do this for assembly
8339 // only, not C/C++.
8340 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8341 options::OPT_mno_default_build_attributes, true)) {
8342 CmdArgs.push_back("-mllvm");
8343 CmdArgs.push_back("-arm-add-build-attributes");
8345 break;
8347 case llvm::Triple::aarch64:
8348 case llvm::Triple::aarch64_32:
8349 case llvm::Triple::aarch64_be:
8350 if (Args.hasArg(options::OPT_mmark_bti_property)) {
8351 CmdArgs.push_back("-mllvm");
8352 CmdArgs.push_back("-aarch64-mark-bti-property");
8354 break;
8356 case llvm::Triple::loongarch32:
8357 case llvm::Triple::loongarch64:
8358 AddLoongArchTargetArgs(Args, CmdArgs);
8359 break;
8361 case llvm::Triple::riscv32:
8362 case llvm::Triple::riscv64:
8363 AddRISCVTargetArgs(Args, CmdArgs);
8364 break;
8367 // Consume all the warning flags. Usually this would be handled more
8368 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8369 // doesn't handle that so rather than warning about unused flags that are
8370 // actually used, we'll lie by omission instead.
8371 // FIXME: Stop lying and consume only the appropriate driver flags
8372 Args.ClaimAllArgs(options::OPT_W_Group);
8374 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8375 getToolChain().getDriver());
8377 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8379 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8380 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8381 Output.getFilename());
8383 // Fixup any previous commands that use -object-file-name because when we
8384 // generated them, the final .obj name wasn't yet known.
8385 for (Command &J : C.getJobs()) {
8386 if (SourceAction != FindSource(&J.getSource()))
8387 continue;
8388 auto &JArgs = J.getArguments();
8389 for (unsigned I = 0; I < JArgs.size(); ++I) {
8390 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
8391 Output.isFilename()) {
8392 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8393 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
8394 Output.getFilename());
8395 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
8396 J.replaceArguments(NewArgs);
8397 break;
8402 assert(Output.isFilename() && "Unexpected lipo output.");
8403 CmdArgs.push_back("-o");
8404 CmdArgs.push_back(Output.getFilename());
8406 const llvm::Triple &T = getToolChain().getTriple();
8407 Arg *A;
8408 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
8409 T.isOSBinFormatELF()) {
8410 CmdArgs.push_back("-split-dwarf-output");
8411 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8414 if (Triple.isAMDGPU())
8415 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8417 assert(Input.isFilename() && "Invalid input.");
8418 CmdArgs.push_back(Input.getFilename());
8420 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8421 if (D.CC1Main && !D.CCGenDiagnostics) {
8422 // Invoke cc1as directly in this process.
8423 C.addCommand(std::make_unique<CC1Command>(
8424 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8425 Output, D.getPrependArg()));
8426 } else {
8427 C.addCommand(std::make_unique<Command>(
8428 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8429 Output, D.getPrependArg()));
8433 // Begin OffloadBundler
8435 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8436 const InputInfo &Output,
8437 const InputInfoList &Inputs,
8438 const llvm::opt::ArgList &TCArgs,
8439 const char *LinkingOutput) const {
8440 // The version with only one output is expected to refer to a bundling job.
8441 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8443 // The bundling command looks like this:
8444 // clang-offload-bundler -type=bc
8445 // -targets=host-triple,openmp-triple1,openmp-triple2
8446 // -output=output_file
8447 // -input=unbundle_file_host
8448 // -input=unbundle_file_tgt1
8449 // -input=unbundle_file_tgt2
8451 ArgStringList CmdArgs;
8453 // Get the type.
8454 CmdArgs.push_back(TCArgs.MakeArgString(
8455 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8457 assert(JA.getInputs().size() == Inputs.size() &&
8458 "Not have inputs for all dependence actions??");
8460 // Get the targets.
8461 SmallString<128> Triples;
8462 Triples += "-targets=";
8463 for (unsigned I = 0; I < Inputs.size(); ++I) {
8464 if (I)
8465 Triples += ',';
8467 // Find ToolChain for this input.
8468 Action::OffloadKind CurKind = Action::OFK_Host;
8469 const ToolChain *CurTC = &getToolChain();
8470 const Action *CurDep = JA.getInputs()[I];
8472 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8473 CurTC = nullptr;
8474 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8475 assert(CurTC == nullptr && "Expected one dependence!");
8476 CurKind = A->getOffloadingDeviceKind();
8477 CurTC = TC;
8480 Triples += Action::GetOffloadKindName(CurKind);
8481 Triples += '-';
8482 Triples += CurTC->getTriple().normalize();
8483 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8484 !StringRef(CurDep->getOffloadingArch()).empty()) {
8485 Triples += '-';
8486 Triples += CurDep->getOffloadingArch();
8489 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8490 // with each toolchain.
8491 StringRef GPUArchName;
8492 if (CurKind == Action::OFK_OpenMP) {
8493 // Extract GPUArch from -march argument in TC argument list.
8494 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8495 auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8496 auto Arch = ArchStr.starts_with_insensitive("-march=");
8497 if (Arch) {
8498 GPUArchName = ArchStr.substr(7);
8499 Triples += "-";
8500 break;
8503 Triples += GPUArchName.str();
8506 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8508 // Get bundled file command.
8509 CmdArgs.push_back(
8510 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8512 // Get unbundled files command.
8513 for (unsigned I = 0; I < Inputs.size(); ++I) {
8514 SmallString<128> UB;
8515 UB += "-input=";
8517 // Find ToolChain for this input.
8518 const ToolChain *CurTC = &getToolChain();
8519 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8520 CurTC = nullptr;
8521 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8522 assert(CurTC == nullptr && "Expected one dependence!");
8523 CurTC = TC;
8525 UB += C.addTempFile(
8526 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8527 } else {
8528 UB += CurTC->getInputFilename(Inputs[I]);
8530 CmdArgs.push_back(TCArgs.MakeArgString(UB));
8532 if (TCArgs.hasFlag(options::OPT_offload_compress,
8533 options::OPT_no_offload_compress, false))
8534 CmdArgs.push_back("-compress");
8535 if (TCArgs.hasArg(options::OPT_v))
8536 CmdArgs.push_back("-verbose");
8537 // All the inputs are encoded as commands.
8538 C.addCommand(std::make_unique<Command>(
8539 JA, *this, ResponseFileSupport::None(),
8540 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8541 CmdArgs, std::nullopt, Output));
8544 void OffloadBundler::ConstructJobMultipleOutputs(
8545 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8546 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8547 const char *LinkingOutput) const {
8548 // The version with multiple outputs is expected to refer to a unbundling job.
8549 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8551 // The unbundling command looks like this:
8552 // clang-offload-bundler -type=bc
8553 // -targets=host-triple,openmp-triple1,openmp-triple2
8554 // -input=input_file
8555 // -output=unbundle_file_host
8556 // -output=unbundle_file_tgt1
8557 // -output=unbundle_file_tgt2
8558 // -unbundle
8560 ArgStringList CmdArgs;
8562 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8563 InputInfo Input = Inputs.front();
8565 // Get the type.
8566 CmdArgs.push_back(TCArgs.MakeArgString(
8567 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8569 // Get the targets.
8570 SmallString<128> Triples;
8571 Triples += "-targets=";
8572 auto DepInfo = UA.getDependentActionsInfo();
8573 for (unsigned I = 0; I < DepInfo.size(); ++I) {
8574 if (I)
8575 Triples += ',';
8577 auto &Dep = DepInfo[I];
8578 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8579 Triples += '-';
8580 Triples += Dep.DependentToolChain->getTriple().normalize();
8581 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8582 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8583 !Dep.DependentBoundArch.empty()) {
8584 Triples += '-';
8585 Triples += Dep.DependentBoundArch;
8587 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8588 // with each toolchain.
8589 StringRef GPUArchName;
8590 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8591 // Extract GPUArch from -march argument in TC argument list.
8592 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8593 StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8594 auto Arch = ArchStr.starts_with_insensitive("-march=");
8595 if (Arch) {
8596 GPUArchName = ArchStr.substr(7);
8597 Triples += "-";
8598 break;
8601 Triples += GPUArchName.str();
8605 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8607 // Get bundled file command.
8608 CmdArgs.push_back(
8609 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
8611 // Get unbundled files command.
8612 for (unsigned I = 0; I < Outputs.size(); ++I) {
8613 SmallString<128> UB;
8614 UB += "-output=";
8615 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
8616 CmdArgs.push_back(TCArgs.MakeArgString(UB));
8618 CmdArgs.push_back("-unbundle");
8619 CmdArgs.push_back("-allow-missing-bundles");
8620 if (TCArgs.hasArg(options::OPT_v))
8621 CmdArgs.push_back("-verbose");
8623 // All the inputs are encoded as commands.
8624 C.addCommand(std::make_unique<Command>(
8625 JA, *this, ResponseFileSupport::None(),
8626 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8627 CmdArgs, std::nullopt, Outputs));
8630 void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
8631 const InputInfo &Output,
8632 const InputInfoList &Inputs,
8633 const llvm::opt::ArgList &Args,
8634 const char *LinkingOutput) const {
8635 ArgStringList CmdArgs;
8637 // Add the output file name.
8638 assert(Output.isFilename() && "Invalid output.");
8639 CmdArgs.push_back("-o");
8640 CmdArgs.push_back(Output.getFilename());
8642 // Create the inputs to bundle the needed metadata.
8643 for (const InputInfo &Input : Inputs) {
8644 const Action *OffloadAction = Input.getAction();
8645 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
8646 const ArgList &TCArgs =
8647 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
8648 OffloadAction->getOffloadingDeviceKind());
8649 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
8650 StringRef Arch = OffloadAction->getOffloadingArch()
8651 ? OffloadAction->getOffloadingArch()
8652 : TCArgs.getLastArgValue(options::OPT_march_EQ);
8653 StringRef Kind =
8654 Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
8656 ArgStringList Features;
8657 SmallVector<StringRef> FeatureArgs;
8658 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
8659 false);
8660 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
8661 [](StringRef Arg) { return !Arg.starts_with("-target"); });
8663 if (TC->getTriple().isAMDGPU()) {
8664 for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
8665 FeatureArgs.emplace_back(
8666 Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
8670 // TODO: We need to pass in the full target-id and handle it properly in the
8671 // linker wrapper.
8672 SmallVector<std::string> Parts{
8673 "file=" + File.str(),
8674 "triple=" + TC->getTripleString(),
8675 "arch=" + getProcessorFromTargetID(TC->getTriple(), Arch).str(),
8676 "kind=" + Kind.str(),
8679 if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
8680 TC->getTriple().isAMDGPU())
8681 for (StringRef Feature : FeatureArgs)
8682 Parts.emplace_back("feature=" + Feature.str());
8684 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
8687 C.addCommand(std::make_unique<Command>(
8688 JA, *this, ResponseFileSupport::None(),
8689 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8690 CmdArgs, Inputs, Output));
8693 void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
8694 const InputInfo &Output,
8695 const InputInfoList &Inputs,
8696 const ArgList &Args,
8697 const char *LinkingOutput) const {
8698 const Driver &D = getToolChain().getDriver();
8699 const llvm::Triple TheTriple = getToolChain().getTriple();
8700 ArgStringList CmdArgs;
8702 // Pass the CUDA path to the linker wrapper tool.
8703 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
8704 auto TCRange = C.getOffloadToolChains(Kind);
8705 for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
8706 const ToolChain *TC = I.second;
8707 if (TC->getTriple().isNVPTX()) {
8708 CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8709 if (CudaInstallation.isValid())
8710 CmdArgs.push_back(Args.MakeArgString(
8711 "--cuda-path=" + CudaInstallation.getInstallPath()));
8712 break;
8717 // Pass in the optimization level to use for LTO.
8718 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
8719 StringRef OOpt;
8720 if (A->getOption().matches(options::OPT_O4) ||
8721 A->getOption().matches(options::OPT_Ofast))
8722 OOpt = "3";
8723 else if (A->getOption().matches(options::OPT_O)) {
8724 OOpt = A->getValue();
8725 if (OOpt == "g")
8726 OOpt = "1";
8727 else if (OOpt == "s" || OOpt == "z")
8728 OOpt = "2";
8729 } else if (A->getOption().matches(options::OPT_O0))
8730 OOpt = "0";
8731 if (!OOpt.empty())
8732 CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
8735 CmdArgs.push_back(
8736 Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
8737 if (Args.hasArg(options::OPT_v))
8738 CmdArgs.push_back("--wrapper-verbose");
8740 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8741 if (!A->getOption().matches(options::OPT_g0))
8742 CmdArgs.push_back("--device-debug");
8745 // code-object-version=X needs to be passed to clang-linker-wrapper to ensure
8746 // that it is used by lld.
8747 if (const Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
8748 CmdArgs.push_back(Args.MakeArgString("-mllvm"));
8749 CmdArgs.push_back(Args.MakeArgString(
8750 Twine("--amdhsa-code-object-version=") + A->getValue()));
8753 for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8754 CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
8756 // Forward remarks passes to the LLVM backend in the wrapper.
8757 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8758 CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
8759 A->getValue()));
8760 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8761 CmdArgs.push_back(Args.MakeArgString(
8762 Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
8763 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8764 CmdArgs.push_back(Args.MakeArgString(
8765 Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
8766 if (Args.getLastArg(options::OPT_save_temps_EQ))
8767 CmdArgs.push_back("--save-temps");
8769 // Construct the link job so we can wrap around it.
8770 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8771 const auto &LinkCommand = C.getJobs().getJobs().back();
8773 // Forward -Xoffload-linker<-triple> arguments to the device link job.
8774 for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
8775 StringRef Val = A->getValue(0);
8776 if (Val.empty())
8777 CmdArgs.push_back(
8778 Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
8779 else
8780 CmdArgs.push_back(Args.MakeArgString(
8781 "--device-linker=" +
8782 ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
8783 A->getValue(1)));
8785 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
8787 // Embed bitcode instead of an object in JIT mode.
8788 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
8789 options::OPT_fno_openmp_target_jit, false))
8790 CmdArgs.push_back("--embed-bitcode");
8792 // Forward `-mllvm` arguments to the LLVM invocations if present.
8793 for (Arg *A : Args.filtered(options::OPT_mllvm)) {
8794 CmdArgs.push_back("-mllvm");
8795 CmdArgs.push_back(A->getValue());
8796 A->claim();
8799 // Add the linker arguments to be forwarded by the wrapper.
8800 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
8801 LinkCommand->getExecutable()));
8802 CmdArgs.push_back("--");
8803 for (const char *LinkArg : LinkCommand->getArguments())
8804 CmdArgs.push_back(LinkArg);
8806 const char *Exec =
8807 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
8809 // Replace the executable and arguments of the link job with the
8810 // wrapper.
8811 LinkCommand->replaceExecutable(Exec);
8812 LinkCommand->replaceArguments(CmdArgs);