1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/LoongArch.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
15#include "Arch/RISCV.h"
16#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Hexagon.h"
19#include "PS4CPU.h"
20#include "ToolChains/Cuda.h"
21#include "clang/Basic/CLWarnings.h"
22#include "clang/Basic/CodeGenOptions.h"
23#include "clang/Basic/HeaderInclude.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/MakeSupport.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/TargetID.h"
28#include "clang/Basic/Version.h"
29#include "clang/Config/config.h"
30#include "clang/Driver/Action.h"
31#include "clang/Driver/CommonArgs.h"
32#include "clang/Driver/Distro.h"
33#include "clang/Driver/InputInfo.h"
34#include "clang/Driver/SanitizerArgs.h"
35#include "clang/Driver/Types.h"
36#include "clang/Driver/XRayArgs.h"
37#include "clang/Options/OptionUtils.h"
38#include "clang/Options/Options.h"
39#include "llvm/ADT/ScopeExit.h"
40#include "llvm/ADT/SmallSet.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/BinaryFormat/Magic.h"
43#include "llvm/Config/llvm-config.h"
44#include "llvm/Frontend/Debug/Options.h"
45#include "llvm/Object/ObjectFile.h"
46#include "llvm/Option/ArgList.h"
47#include "llvm/ProfileData/InstrProfReader.h"
48#include "llvm/Support/CodeGen.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/Error.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/Process.h"
55#include "llvm/Support/YAMLParser.h"
56#include "llvm/TargetParser/AArch64TargetParser.h"
57#include "llvm/TargetParser/ARMTargetParserCommon.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/LoongArchTargetParser.h"
60#include "llvm/TargetParser/PPCTargetParser.h"
61#include "llvm/TargetParser/RISCVISAInfo.h"
62#include "llvm/TargetParser/RISCVTargetParser.h"
63#include <cctype>
64#include <iterator>
65#include <optional>
66
67using namespace clang::driver;
68using namespace clang::driver::tools;
69using namespace clang;
70using namespace llvm::opt;
71
72static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
73 if (Arg *A = Args.getLastArg(Ids: options::OPT_C, Ids: options::OPT_CC,
74 Ids: options::OPT_fminimize_whitespace,
75 Ids: options::OPT_fno_minimize_whitespace,
76 Ids: options::OPT_fkeep_system_includes,
77 Ids: options::OPT_fno_keep_system_includes)) {
78 if (!Args.hasArg(Ids: options::OPT_E) && !Args.hasArg(Ids: options::OPT__SLASH_P) &&
79 !Args.hasArg(Ids: options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
80 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
81 << A->getBaseArg().getAsString(Args)
82 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
83 }
84 }
85}
86
87static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
88 // In gcc, only ARM checks this, but it seems reasonable to check universally.
89 if (Args.hasArg(Ids: options::OPT_static))
90 if (const Arg *A =
91 Args.getLastArg(Ids: options::OPT_dynamic, Ids: options::OPT_mdynamic_no_pic))
92 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
93 << "-static";
94}
95
96/// Apply \a Work on the current tool chain \a RegularToolChain and any other
97/// offloading tool chain that is associated with the current action \a JA.
98static void
99forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
100 const ToolChain &RegularToolChain,
101 llvm::function_ref<void(const ToolChain &)> Work) {
102 // Apply Work on the current/regular tool chain.
103 Work(RegularToolChain);
104
105 // Apply Work on all the offloading tool chains associated with the current
106 // action.
107 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
108 Action::OFK_HIP, Action::OFK_SYCL}) {
109 if (JA.isHostOffloading(OKind: Kind)) {
110 auto TCs = C.getOffloadToolChains(Kind);
111 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
112 Work(*II->second);
113 } else if (JA.isDeviceOffloading(OKind: Kind))
114 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
115 }
116}
117
118static bool
119shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
120 const llvm::Triple &Triple) {
121 // We use the zero-cost exception tables for Objective-C if the non-fragile
122 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
123 // later.
124 if (runtime.isNonFragile())
125 return true;
126
127 if (!Triple.isMacOSX())
128 return false;
129
130 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
131 (Triple.getArch() == llvm::Triple::x86_64 ||
132 Triple.getArch() == llvm::Triple::arm));
133}
134
135/// Adds exception related arguments to the driver command arguments. There's a
136/// main flag, -fexceptions and also language specific flags to enable/disable
137/// C++ and Objective-C exceptions. This makes it possible to for example
138/// disable C++ exceptions but enable Objective-C exceptions.
139static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
140 const ToolChain &TC, bool KernelOrKext,
141 bool IsDeviceOffloadAction,
142 const ObjCRuntime &objcRuntime,
143 ArgStringList &CmdArgs) {
144 const llvm::Triple &Triple = TC.getTriple();
145
146 if (KernelOrKext) {
147 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
148 // arguments now to avoid warnings about unused arguments.
149 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
152 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
153 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
154 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
155 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
156 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
157 return false;
158 }
159
160 // See if the user explicitly enabled exceptions.
161 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
162 Default: false);
163
164 // Async exceptions are Windows MSVC only.
165 if (Triple.isWindowsMSVCEnvironment()) {
166 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
167 Neg: options::OPT_fno_async_exceptions, Default: false);
168 if (EHa) {
169 CmdArgs.push_back(Elt: "-fasync-exceptions");
170 EH = true;
171 }
172 }
173
174 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
175 // is not necessarily sensible, but follows GCC.
176 if (types::isObjC(Id: InputType) &&
177 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
178 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
179 CmdArgs.push_back(Elt: "-fobjc-exceptions");
180
181 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
182 }
183
184 if (types::isCXX(Id: InputType)) {
185 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
186 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
187 !Triple.isPS() && !Triple.isDriverKit() &&
188 !(Triple.isGPU() && !IsDeviceOffloadAction);
189 Arg *ExceptionArg = Args.getLastArg(
190 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
191 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
192 if (ExceptionArg)
193 CXXExceptionsEnabled =
194 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
195 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
196
197 if (CXXExceptionsEnabled) {
198 CmdArgs.push_back(Elt: "-fcxx-exceptions");
199
200 EH = true;
201 }
202 }
203
204 // OPT_fignore_exceptions means exception could still be thrown,
205 // but no clean up or catch would happen in current module.
206 // So we do not set EH to false.
207 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
208
209 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
210 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
211
212 if (EH)
213 CmdArgs.push_back(Elt: "-fexceptions");
214 return EH;
215}
216
217static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
218 const JobAction &JA) {
219 bool Default = true;
220 if (TC.getTriple().isOSDarwin()) {
221 // The native darwin assembler doesn't support the linker_option directives,
222 // so we disable them if we think the .s file will be passed to it.
223 Default = TC.useIntegratedAs();
224 }
225 // The linker_option directives are intended for host compilation.
226 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
227 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
228 Default = false;
229 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
230 Default);
231}
232
233/// Add a CC1 option to specify the debug compilation directory.
234static const char *addDebugCompDirArg(const ArgList &Args,
235 ArgStringList &CmdArgs,
236 const llvm::vfs::FileSystem &VFS) {
237 std::string DebugCompDir;
238 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
239 Ids: options::OPT_fdebug_compilation_dir_EQ))
240 DebugCompDir = A->getValue();
241
242 if (DebugCompDir.empty()) {
243 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
244 DebugCompDir = std::move(*CWD);
245 else
246 return nullptr;
247 }
248 CmdArgs.push_back(
249 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
250 StringRef Path(CmdArgs.back());
251 return Path.substr(Start: Path.find(C: '=') + 1).data();
252}
253
254static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
255 const char *DebugCompilationDir,
256 const char *OutputFileName) {
257 // No need to generate a value for -object-file-name if it was provided.
258 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
259 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
260 return;
261
262 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
263 return;
264
265 SmallString<128> ObjFileNameForDebug(OutputFileName);
266 if (ObjFileNameForDebug != "-" &&
267 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
268 (!DebugCompilationDir ||
269 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
270 // Make the path absolute in the debug infos like MSVC does.
271 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
272 }
273 // If the object file name is a relative path, then always use Windows
274 // backslash style as -object-file-name is used for embedding object file path
275 // in codeview and it can only be generated when targeting on Windows.
276 // Otherwise, just use native absolute path.
277 llvm::sys::path::Style Style =
278 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
279 ? llvm::sys::path::Style::native
280 : llvm::sys::path::Style::windows_backslash;
281 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
282 style: Style);
283 CmdArgs.push_back(
284 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
285}
286
287/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
288static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
289 const ArgList &Args, ArgStringList &CmdArgs) {
290 auto AddOneArg = [&](StringRef Map, StringRef Name) {
291 if (!Map.contains(C: '='))
292 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
293 else
294 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
295 };
296
297 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
298 Ids: options::OPT_fdebug_prefix_map_EQ)) {
299 AddOneArg(A->getValue(), A->getOption().getName());
300 A->claim();
301 }
302 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
303 if (GlobalRemapEntry.empty())
304 return;
305 AddOneArg(GlobalRemapEntry, "environment");
306}
307
308/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
309static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
310 ArgStringList &CmdArgs) {
311 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
312 Ids: options::OPT_fmacro_prefix_map_EQ)) {
313 StringRef Map = A->getValue();
314 if (!Map.contains(C: '='))
315 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
316 << Map << A->getOption().getName();
317 else
318 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
319 A->claim();
320 }
321}
322
323/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
324static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
325 ArgStringList &CmdArgs) {
326 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
327 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
328 StringRef Map = A->getValue();
329 if (!Map.contains(C: '='))
330 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
331 << Map << A->getOption().getName();
332 else
333 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
334 A->claim();
335 }
336}
337
338/// Add -x lang to \p CmdArgs for \p Input.
339static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
340 ArgStringList &CmdArgs) {
341 // When using -verify-pch, we don't want to provide the type
342 // 'precompiled-header' if it was inferred from the file extension
343 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
344 return;
345
346 CmdArgs.push_back(Elt: "-x");
347 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
348 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
349 else {
350 // Map the driver type to the frontend type. This is mostly an identity
351 // mapping, except that the distinction between module interface units
352 // and other source files does not exist at the frontend layer.
353 const char *ClangType;
354 switch (Input.getType()) {
355 case types::TY_CXXModule:
356 case types::TY_CXXStdModule:
357 ClangType = "c++";
358 break;
359 case types::TY_PP_CXXModule:
360 ClangType = "c++-cpp-output";
361 break;
362 case types::TY_CIRBC:
363 ClangType = "cir";
364 break;
365 default:
366 ClangType = types::getTypeName(Id: Input.getType());
367 break;
368 }
369 CmdArgs.push_back(Elt: ClangType);
370 }
371}
372
373static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
374 const JobAction &JA, const InputInfo &Output,
375 const ArgList &Args, SanitizerArgs &SanArgs,
376 ArgStringList &CmdArgs) {
377 const Driver &D = TC.getDriver();
378 const llvm::Triple &T = TC.getTriple();
379 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
380 Ids: options::OPT_fprofile_generate_EQ,
381 Ids: options::OPT_fno_profile_generate);
382 if (PGOGenerateArg &&
383 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
384 PGOGenerateArg = nullptr;
385
386 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
387
388 auto *ProfileGenerateArg = Args.getLastArg(
389 Ids: options::OPT_fprofile_instr_generate,
390 Ids: options::OPT_fprofile_instr_generate_EQ,
391 Ids: options::OPT_fno_profile_instr_generate);
392 if (ProfileGenerateArg &&
393 ProfileGenerateArg->getOption().matches(
394 ID: options::OPT_fno_profile_instr_generate))
395 ProfileGenerateArg = nullptr;
396
397 if (PGOGenerateArg && ProfileGenerateArg)
398 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
399 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
400
401 auto *ProfileUseArg = getLastProfileUseArg(Args);
402
403 if (PGOGenerateArg && ProfileUseArg)
404 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
405 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
406
407 if (ProfileGenerateArg && ProfileUseArg)
408 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
409 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
410
411 if (CSPGOGenerateArg && PGOGenerateArg) {
412 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
413 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
414 PGOGenerateArg = nullptr;
415 }
416
417 if (TC.getTriple().isOSAIX()) {
418 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
419 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
420 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
421 }
422
423 if (ProfileGenerateArg) {
424 if (ProfileGenerateArg->getOption().matches(
425 ID: options::OPT_fprofile_instr_generate_EQ))
426 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
427 ProfileGenerateArg->getValue()));
428 // The default is to use Clang Instrumentation.
429 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
430 if (TC.getTriple().isWindowsMSVCEnvironment() &&
431 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
432 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
433 // Add dependent lib for clang_rt.profile
434 CmdArgs.push_back(Elt: Args.MakeArgString(
435 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
436 }
437 }
438
439 if (auto *ColdFuncCoverageArg = Args.getLastArg(
440 Ids: options::OPT_fprofile_generate_cold_function_coverage,
441 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
442 SmallString<128> Path(
443 ColdFuncCoverageArg->getOption().matches(
444 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
445 ? ColdFuncCoverageArg->getValue()
446 : "");
447 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
448 // FIXME: Idealy the file path should be passed through
449 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
450 // shared with other profile use path(see PGOOptions), we need to refactor
451 // PGOOptions to make it work.
452 CmdArgs.push_back(Elt: "-mllvm");
453 CmdArgs.push_back(Elt: Args.MakeArgString(
454 Str: Twine("--instrument-cold-function-only-path=") + Path));
455 CmdArgs.push_back(Elt: "-mllvm");
456 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
457 CmdArgs.push_back(Elt: "-mllvm");
458 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
459 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
460 }
461
462 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
463 if (!PGOGenerateArg && !CSPGOGenerateArg)
464 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
465 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
466 CmdArgs.push_back(Elt: "-mllvm");
467 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
468 }
469
470 Arg *PGOGenArg = nullptr;
471 if (PGOGenerateArg) {
472 assert(!CSPGOGenerateArg);
473 PGOGenArg = PGOGenerateArg;
474 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
475 }
476 if (CSPGOGenerateArg) {
477 assert(!PGOGenerateArg);
478 PGOGenArg = CSPGOGenerateArg;
479 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
480 }
481 if (PGOGenArg) {
482 if (TC.getTriple().isWindowsMSVCEnvironment() &&
483 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
484 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
485 // Add dependent lib for clang_rt.profile
486 CmdArgs.push_back(Elt: Args.MakeArgString(
487 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
488 }
489 if (PGOGenArg->getOption().matches(
490 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
491 : options::OPT_fcs_profile_generate_EQ)) {
492 SmallString<128> Path(PGOGenArg->getValue());
493 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
494 CmdArgs.push_back(
495 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
496 }
497 }
498
499 if (ProfileUseArg) {
500 SmallString<128> UsePathBuf;
501 StringRef UsePath;
502 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
503 UsePath = ProfileUseArg->getValue();
504 else if ((ProfileUseArg->getOption().matches(
505 ID: options::OPT_fprofile_use_EQ) ||
506 ProfileUseArg->getOption().matches(
507 ID: options::OPT_fprofile_instr_use))) {
508 UsePathBuf =
509 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
510 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
511 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
512 UsePath = UsePathBuf;
513 }
514 auto ReaderOrErr =
515 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
516 if (auto E = ReaderOrErr.takeError()) {
517 auto DiagID = D.getDiags().getCustomDiagID(
518 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
519 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
520 D.Diag(DiagID) << UsePath.str() << EI.message();
521 });
522 } else {
523 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
524 std::move(ReaderOrErr.get());
525 StringRef UseKind;
526 // Currently memprof profiles are only added at the IR level. Mark the
527 // profile type as IR in that case as well and the subsequent matching
528 // needs to detect which is available (might be one or both).
529 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
530 if (PGOReader->hasCSIRLevelProfile())
531 UseKind = "csllvm";
532 else
533 UseKind = "llvm";
534 } else
535 UseKind = "clang";
536
537 CmdArgs.push_back(
538 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
539 CmdArgs.push_back(
540 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
541 }
542 }
543
544 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
545 Neg: options::OPT_fno_test_coverage, Default: false) ||
546 Args.hasArg(Ids: options::OPT_coverage);
547 bool EmitCovData = TC.needsGCovInstrumentation(Args);
548
549 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
550 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
551 if (!ProfileGenerateArg)
552 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
553 << "-fcoverage-mapping"
554 << "-fprofile-instr-generate";
555
556 CmdArgs.push_back(Elt: "-fcoverage-mapping");
557 }
558
559 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
560 Default: false)) {
561 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
562 Neg: options::OPT_fno_coverage_mapping, Default: false))
563 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
564 << "-fcoverage-mcdc"
565 << "-fcoverage-mapping";
566
567 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
568 }
569
570 StringRef CoverageCompDir;
571 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
572 Ids: options::OPT_fcoverage_compilation_dir_EQ))
573 CoverageCompDir = A->getValue();
574 if (CoverageCompDir.empty()) {
575 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
576 CmdArgs.push_back(
577 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
578 } else
579 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
580 CoverageCompDir));
581
582 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
583 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
584 if (!Args.hasArg(Ids: options::OPT_coverage))
585 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
586 << "-fprofile-exclude-files="
587 << "--coverage";
588
589 StringRef v = Arg->getValue();
590 CmdArgs.push_back(
591 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
592 }
593
594 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
595 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
596 if (!Args.hasArg(Ids: options::OPT_coverage))
597 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
598 << "-fprofile-filter-files="
599 << "--coverage";
600
601 StringRef v = Arg->getValue();
602 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
603 }
604
605 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
606 StringRef Val = A->getValue();
607 if (Val == "atomic" || Val == "prefer-atomic")
608 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
609 else if (Val == "single") {
610 if (SanArgs.needsTsanRt() &&
611 (PGOGenerateArg || CSPGOGenerateArg || ProfileGenerateArg)) {
612 // Under TSan, instrprof defaults to atomic counter updates to avoid
613 // data race reports on profile counters; override that default and
614 // warn.
615 D.Diag(DiagID: diag::warn_drv_tsan_profile_update_single)
616 << A->getAsString(Args);
617 CmdArgs.push_back(Elt: "-mllvm");
618 CmdArgs.push_back(Elt: "-instrprof-atomic-counter-update-all=false");
619 }
620 } else
621 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
622 << A->getSpelling() << Val;
623 }
624 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
625 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
626 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
627 << A->getSpelling()
628 << "-fprofile-generate, -fprofile-instr-generate, or "
629 "-fcs-profile-generate";
630 else {
631 CmdArgs.push_back(Elt: "-fprofile-continuous");
632 // Platforms that require a bias variable:
633 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
634 CmdArgs.push_back(Elt: "-mllvm");
635 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
636 }
637 // -fprofile-instr-generate does not decide the profile file name in the
638 // FE, and so it does not define the filename symbol
639 // (__llvm_profile_filename). Instead, the runtime uses the name
640 // "default.profraw" for the profile file. When continuous mode is ON, we
641 // will create the filename symbol so that we can insert the "%c"
642 // modifier.
643 if (ProfileGenerateArg &&
644 (ProfileGenerateArg->getOption().matches(
645 ID: options::OPT_fprofile_instr_generate) ||
646 (ProfileGenerateArg->getOption().matches(
647 ID: options::OPT_fprofile_instr_generate_EQ) &&
648 strlen(s: ProfileGenerateArg->getValue()) == 0)))
649 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
650 }
651 }
652
653 int FunctionGroups = 1;
654 int SelectedFunctionGroup = 0;
655 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
656 StringRef Val = A->getValue();
657 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
658 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
659 }
660 if (const auto *A =
661 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
662 StringRef Val = A->getValue();
663 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
664 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
665 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
666 }
667 if (FunctionGroups != 1)
668 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
669 Twine(FunctionGroups)));
670 if (SelectedFunctionGroup != 0)
671 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
672 Twine(SelectedFunctionGroup)));
673
674 // Leave -fprofile-dir= an unused argument unless .gcda emission is
675 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
676 // the flag used. There is no -fno-profile-dir, so the user has no
677 // targeted way to suppress the warning.
678 Arg *FProfileDir = nullptr;
679 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
680 Args.hasArg(Ids: options::OPT_coverage))
681 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
682
683 // Put the .gcno and .gcda files (if needed) next to the primary output file,
684 // or fall back to a file in the current directory for `clang -c --coverage
685 // d/a.c` in the absence of -o.
686 if (EmitCovNotes || EmitCovData) {
687 SmallString<128> CoverageFilename;
688 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
689 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
690 // path separator.
691 CoverageFilename = DumpDir->getValue();
692 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
693 } else if (Arg *FinalOutput =
694 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
695 CoverageFilename = FinalOutput->getValue();
696 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
697 CoverageFilename = FinalOutput->getValue();
698 } else {
699 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
700 }
701 if (llvm::sys::path::is_relative(path: CoverageFilename))
702 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
703 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
704 if (EmitCovNotes) {
705 CmdArgs.push_back(
706 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
707
708 bool UseAbsolutePathsInNotes =
709 Args.hasFlag(Pos: options::OPT_fprofile_abs_path,
710 Neg: options::OPT_fno_profile_abs_path, Default: false);
711 if (UseAbsolutePathsInNotes)
712 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-coverage-notes-abs-paths"));
713 }
714
715 if (EmitCovData) {
716 if (FProfileDir) {
717 SmallString<128> Gcno = std::move(CoverageFilename);
718 CoverageFilename = FProfileDir->getValue();
719 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
720 }
721 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
722 CmdArgs.push_back(
723 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
724 }
725 }
726}
727
728static void
729RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
730 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
731 unsigned DwarfVersion,
732 llvm::DebuggerKind DebuggerTuning) {
733 addDebugInfoKind(CmdArgs, DebugInfoKind);
734 if (DwarfVersion > 0)
735 CmdArgs.push_back(
736 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
737 switch (DebuggerTuning) {
738 case llvm::DebuggerKind::GDB:
739 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
740 break;
741 case llvm::DebuggerKind::LLDB:
742 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
743 break;
744 case llvm::DebuggerKind::SCE:
745 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
746 break;
747 case llvm::DebuggerKind::DBX:
748 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
749 break;
750 default:
751 break;
752 }
753}
754
755static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
756 const ArgList &Args,
757 ArgStringList &CmdArgs,
758 bool IsCC1As = false) {
759 // If no version was requested by the user, use the default value from the
760 // back end. This is consistent with the value returned from
761 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
762 // requiring the corresponding llvm to have the AMDGPU target enabled,
763 // provided the user (e.g. front end tests) can use the default.
764 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
765 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
766 CmdArgs.insert(I: CmdArgs.begin() + 1,
767 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
768 Twine(CodeObjVer)));
769 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
770 // -cc1as does not accept -mcode-object-version option.
771 if (!IsCC1As)
772 CmdArgs.insert(I: CmdArgs.begin() + 1,
773 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
774 Twine(CodeObjVer)));
775 }
776}
777
778static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
779 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
780 D.getVFS().getBufferForFile(Name: Path);
781 if (!MemBuf)
782 return false;
783 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
784 if (Magic == llvm::file_magic::unknown)
785 return false;
786 // Return true for both raw Clang AST files and object files which may
787 // contain a __clangast section.
788 if (Magic == llvm::file_magic::clang_ast)
789 return true;
790 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
791 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
792 return !Obj.takeError();
793}
794
795static bool gchProbe(const Driver &D, StringRef Path) {
796 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
797 if (!Status)
798 return false;
799
800 if (Status->isDirectory()) {
801 std::error_code EC;
802 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
803 !EC && DI != DE; DI = DI.increment(EC)) {
804 if (maybeHasClangPchSignature(D, Path: DI->path()))
805 return true;
806 }
807 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
808 return false;
809 }
810
811 if (maybeHasClangPchSignature(D, Path))
812 return true;
813 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
814 return false;
815}
816
817void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
818 const Driver &D, const ArgList &Args,
819 ArgStringList &CmdArgs,
820 const InputInfo &Output,
821 const InputInfoList &Inputs) const {
822 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
823
824 CheckPreprocessingOptions(D, Args);
825
826 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
827 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
828
829 // Handle dependency file generation.
830 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
831 if (!ArgM)
832 ArgM = Args.getLastArg(Ids: options::OPT_M);
833 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
834 if (!ArgMD)
835 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
836
837 // -M and -MM imply -w.
838 if (ArgM)
839 CmdArgs.push_back(Elt: "-w");
840 else
841 ArgM = ArgMD;
842
843 if (ArgM) {
844 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
845 // Determine the output location.
846 const char *DepFile;
847 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
848 DepFile = MF->getValue();
849 C.addFailureResultFile(Name: DepFile, JA: &JA);
850 } else if (Output.getType() == types::TY_Dependencies) {
851 DepFile = Output.getFilename();
852 } else if (!ArgMD) {
853 DepFile = "-";
854 } else {
855 DepFile = getDependencyFileName(Args, Inputs);
856 C.addFailureResultFile(Name: DepFile, JA: &JA);
857 }
858 CmdArgs.push_back(Elt: "-dependency-file");
859 CmdArgs.push_back(Elt: DepFile);
860 }
861 // Cmake generates dependency files using all compilation options specified
862 // by users. Claim those not used for dependency files.
863 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
864 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
865 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
866 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
867 }
868
869 bool HasTarget = false;
870 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
871 HasTarget = true;
872 A->claim();
873 if (A->getOption().matches(ID: options::OPT_MT)) {
874 A->render(Args, Output&: CmdArgs);
875 } else {
876 CmdArgs.push_back(Elt: "-MT");
877 SmallString<128> Quoted;
878 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
879 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
880 }
881 }
882
883 // Add a default target if one wasn't specified.
884 if (!HasTarget) {
885 const char *DepTarget;
886
887 // If user provided -o, that is the dependency target, except
888 // when we are only generating a dependency file.
889 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
890 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
891 DepTarget = OutputOpt->getValue();
892 } else {
893 // Otherwise derive from the base input.
894 //
895 // FIXME: This should use the computed output file location.
896 SmallString<128> P(Inputs[0].getBaseInput());
897 llvm::sys::path::replace_extension(path&: P, extension: "o");
898 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
899 }
900
901 CmdArgs.push_back(Elt: "-MT");
902 SmallString<128> Quoted;
903 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
904 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
905 }
906
907 if (ArgM->getOption().matches(ID: options::OPT_M) ||
908 ArgM->getOption().matches(ID: options::OPT_MD))
909 CmdArgs.push_back(Elt: "-sys-header-deps");
910
911 // Determine module file deps mode.
912 StringRef ModuleFileDepsVal;
913 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_file_deps_EQ,
914 Ids: options::OPT_fmodule_file_deps,
915 Ids: options::OPT_fno_module_file_deps)) {
916 if (A->getOption().matches(ID: options::OPT_fmodule_file_deps_EQ))
917 ModuleFileDepsVal = A->getValue();
918 else if (A->getOption().matches(ID: options::OPT_fmodule_file_deps))
919 ModuleFileDepsVal = "all";
920 else
921 ModuleFileDepsVal = "none";
922 } else if (isa<PrecompileJobAction>(Val: JA)) {
923 ModuleFileDepsVal = "all";
924 }
925 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
926 CmdArgs.push_back(
927 Elt: Args.MakeArgString(Str: "-module-file-deps=" + ModuleFileDepsVal));
928 }
929
930 if (Args.hasArg(Ids: options::OPT_MG)) {
931 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
932 ArgM->getOption().matches(ID: options::OPT_MMD))
933 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
934 CmdArgs.push_back(Elt: "-MG");
935 }
936
937 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
938 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
939
940 bool UsesLLVMOffloading = Args.hasFlag(
941 Pos: options::OPT_foffload_via_llvm, Neg: options::OPT_fno_offload_via_llvm, Default: false);
942 bool UsesOffloadInclude =
943 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc, Default: true);
944 bool NoBuiltinInc = Args.hasArg(Ids: options::OPT_nobuiltininc);
945
946 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
947 // want to pull in our wrappers instead of the vendor headers.
948 if (UsesLLVMOffloading) {
949 if (UsesOffloadInclude && !NoBuiltinInc) {
950 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
951 StringRef RuntimeHeader) {
952 SmallString<128> OffloadInclude(D.Dir);
953 llvm::sys::path::append(path&: OffloadInclude, a: "..", b: "include", c: "offload");
954 if (!IncludeSubdir.empty())
955 llvm::sys::path::append(path&: OffloadInclude, a: IncludeSubdir);
956 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: OffloadInclude),
957 "-include", Args.MakeArgString(Str: RuntimeHeader)});
958 };
959 auto AddForcedInclude = [&](StringRef Header) {
960 CmdArgs.push_back(Elt: "-include");
961 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Header));
962 };
963 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
964 AddForcedInclude("__clang_gpu_builtin_vars.h");
965 AddForcedInclude("__clang_gpu_device_functions.h");
966 AddForcedInclude("__clang_gpu_intrinsics.h");
967 if (JA.isOffloading(OKind: Action::OFK_Cuda))
968 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
969 if (JA.isOffloading(OKind: Action::OFK_HIP) &&
970 !Args.hasArg(Ids: options::OPT_nohipwrapperinc)) {
971 // HIP code commonly includes this as "hip/hip_runtime.h".
972 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
973 }
974 }
975 } else {
976 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
977 // happen before we -I or -include anything else, because we must pick up
978 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
979 // installation, rather than from e.g. /usr/local/include.
980 if (JA.isOffloading(OKind: Action::OFK_Cuda))
981 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
982 if (JA.isOffloading(OKind: Action::OFK_HIP))
983 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
984 if (JA.isOffloading(OKind: Action::OFK_SYCL))
985 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
986
987 // If we are offloading to a target via OpenMP we need to include the
988 // openmp_wrappers folder which contains alternative system headers.
989 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
990 !Args.hasArg(Ids: options::OPT_nostdinc) && UsesOffloadInclude &&
991 getToolChain().getTriple().isGPU()) {
992 if (!NoBuiltinInc) {
993 // Add openmp_wrappers/* to our system include path. This lets us
994 // wrap standard library headers.
995 SmallString<128> P(D.ResourceDir);
996 llvm::sys::path::append(path&: P, a: "include");
997 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
998 CmdArgs.push_back(Elt: "-internal-isystem");
999 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1000 }
1001
1002 CmdArgs.push_back(Elt: "-include");
1003 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
1004 }
1005 }
1006
1007 // Add -i* options, and automatically translate to
1008 // -include-pch/-include-pth for transparent PCH support. It's
1009 // wonky, but we include looking for .gch so we can support seamless
1010 // replacement into a build system already set up to be generating
1011 // .gch files.
1012
1013 if (getToolChain().getDriver().IsCLMode()) {
1014 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
1015 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
1016 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1017 JA.getKind() <= Action::AssembleJobClass) {
1018 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
1019 // -fpch-instantiate-templates is the default when creating
1020 // precomp using /Yc
1021 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
1022 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
1023 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
1024 }
1025 if (YcArg || YuArg) {
1026 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1027 if (!isa<PrecompileJobAction>(Val: JA)) {
1028 CmdArgs.push_back(Elt: "-include-pch");
1029 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
1030 C, BaseName: !ThroughHeader.empty()
1031 ? ThroughHeader
1032 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1033 }
1034
1035 if (ThroughHeader.empty()) {
1036 CmdArgs.push_back(Elt: Args.MakeArgString(
1037 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1038 } else {
1039 CmdArgs.push_back(
1040 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1041 }
1042 }
1043 }
1044
1045 bool RenderedImplicitInclude = false;
1046 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1047 if (A->getOption().matches(ID: options::OPT_include) &&
1048 D.getProbePrecompiled()) {
1049 // Handling of gcc-style gch precompiled headers.
1050 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1051 RenderedImplicitInclude = true;
1052
1053 bool FoundPCH = false;
1054 SmallString<128> P(A->getValue());
1055 // We want the files to have a name like foo.h.pch. Add a dummy extension
1056 // so that replace_extension does the right thing.
1057 P += ".dummy";
1058 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1059 if (D.getVFS().exists(Path: P))
1060 FoundPCH = true;
1061
1062 if (!FoundPCH) {
1063 // For GCC compat, probe for a file or directory ending in .gch instead.
1064 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1065 FoundPCH = gchProbe(D, Path: P.str());
1066 }
1067
1068 if (FoundPCH) {
1069 if (IsFirstImplicitInclude) {
1070 A->claim();
1071 CmdArgs.push_back(Elt: "-include-pch");
1072 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1073 continue;
1074 } else {
1075 // Ignore the PCH if not first on command line and emit warning.
1076 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1077 << A->getAsString(Args);
1078 }
1079 }
1080 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1081 // Handling of paths which must come late. These entries are handled by
1082 // the toolchain itself after the resource dir is inserted in the right
1083 // search order.
1084 // Do not claim the argument so that the use of the argument does not
1085 // silently go unnoticed on toolchains which do not honour the option.
1086 continue;
1087 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1088 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1089 continue;
1090 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1091 // This is used only by the driver. No need to pass to cc1.
1092 continue;
1093 }
1094
1095 // Not translated, render as usual.
1096 A->claim();
1097 A->render(Args, Output&: CmdArgs);
1098 }
1099
1100 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1101 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1102 // Collect all enabled NVPTX architectures.
1103 std::set<unsigned> ArchIDs;
1104 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1105 const ToolChain *TC = I.second;
1106 for (BoundArch Arch :
1107 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1108 if (Arch.Arch.isNVPTX())
1109 ArchIDs.insert(x: CudaArchToID(Arch: Arch.Arch));
1110 }
1111 }
1112
1113 if (!ArchIDs.empty()) {
1114 SmallString<128> List;
1115 llvm::raw_svector_ostream OS(List);
1116 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1117 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1118 }
1119 }
1120
1121 Args.addAllArgs(Output&: CmdArgs,
1122 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1123 options::OPT_F, options::OPT_embed_dir_EQ});
1124
1125 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1126
1127 // FIXME: There is a very unfortunate problem here, some troubled
1128 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1129 // really support that we would have to parse and then translate
1130 // those options. :(
1131 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1132 Id1: options::OPT_Xpreprocessor);
1133
1134 // -I- is a deprecated GCC feature, reject it.
1135 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1136 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1137
1138 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1139 // -isysroot to the CC1 invocation.
1140 StringRef sysroot = C.getSysRoot();
1141 if (sysroot != "") {
1142 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1143 CmdArgs.push_back(Elt: "-isysroot");
1144 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1145 }
1146 }
1147
1148 // Parse additional include paths from environment variables.
1149 // FIXME: We should probably sink the logic for handling these from the
1150 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1151 // CPATH - included following the user specified includes (but prior to
1152 // builtin and standard includes).
1153 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1154 // C_INCLUDE_PATH - system includes enabled when compiling C.
1155 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1156 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1157 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1158 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1159 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1160 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1161 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1162
1163 // While adding the include arguments, we also attempt to retrieve the
1164 // arguments of related offloading toolchains or arguments that are specific
1165 // of an offloading programming model.
1166
1167 // Add C++ include arguments, if needed.
1168 if (types::isCXX(Id: Inputs[0].getType())) {
1169 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1170 forAllAssociatedToolChains(
1171 C, JA, RegularToolChain: getToolChain(),
1172 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1173 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1174 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1175 });
1176 }
1177
1178 // If we are compiling for a GPU target with the LLVM environment we want to
1179 // override the system headers with ones created by the 'libc' project if
1180 // present.
1181 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1182 // OffloadKind as an argument.
1183 bool OffloadUsesLLVMLibc =
1184 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1185 (C.getActiveOffloadKinds() != Action::OFK_None &&
1186 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
1187 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1188 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1189 Default: true) &&
1190 !Args.hasArg(Ids: options::OPT_nobuiltininc) && OffloadUsesLLVMLibc) {
1191 SmallString<128> P(D.ResourceDir);
1192 llvm::sys::path::append(path&: P, a: "include");
1193 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1194 CmdArgs.push_back(Elt: "-internal-isystem");
1195 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1196 }
1197
1198 // Add system include arguments for all targets but IAMCU.
1199 if (!IsIAMCU)
1200 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1201 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1202 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1203 });
1204 else {
1205 // For IAMCU add special include arguments.
1206 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1207 }
1208
1209 addMacroPrefixMapArg(D, Args, CmdArgs);
1210 addCoveragePrefixMapArg(D, Args, CmdArgs);
1211
1212 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1213 Ids: options::OPT_fno_file_reproducible);
1214
1215 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1216 CmdArgs.push_back(Elt: "-source-date-epoch");
1217 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1218 }
1219
1220 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1221 Neg: options::OPT_fno_define_target_os_macros);
1222}
1223
1224// FIXME: Move to target hook.
1225static bool isSignedCharDefault(const llvm::Triple &Triple) {
1226 switch (Triple.getArch()) {
1227 default:
1228 return true;
1229
1230 case llvm::Triple::aarch64:
1231 case llvm::Triple::aarch64_32:
1232 case llvm::Triple::aarch64_be:
1233 case llvm::Triple::arm:
1234 case llvm::Triple::armeb:
1235 case llvm::Triple::thumb:
1236 case llvm::Triple::thumbeb:
1237 if (Triple.isOSDarwin() || Triple.isOSWindowsOrUEFI())
1238 return true;
1239 return false;
1240
1241 case llvm::Triple::ppc:
1242 case llvm::Triple::ppc64:
1243 if (Triple.isOSDarwin())
1244 return true;
1245 return false;
1246
1247 case llvm::Triple::csky:
1248 case llvm::Triple::hexagon:
1249 case llvm::Triple::msp430:
1250 case llvm::Triple::ppcle:
1251 case llvm::Triple::ppc64le:
1252 case llvm::Triple::riscv32:
1253 case llvm::Triple::riscv64:
1254 case llvm::Triple::riscv32be:
1255 case llvm::Triple::riscv64be:
1256 case llvm::Triple::systemz:
1257 case llvm::Triple::xcore:
1258 case llvm::Triple::xtensa:
1259 return false;
1260 }
1261}
1262
1263static bool hasMultipleInvocations(const llvm::Triple &Triple,
1264 const ArgList &Args) {
1265 // Supported only on Darwin where we invoke the compiler multiple times
1266 // followed by an invocation to lipo.
1267 if (!Triple.isOSDarwin())
1268 return false;
1269 // If more than one "-arch <arch>" is specified, we're targeting multiple
1270 // architectures resulting in a fat binary.
1271 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1272}
1273
1274static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1275 const llvm::Triple &Triple) {
1276 // When enabling remarks, we need to error if:
1277 // * The remark file is specified but we're targeting multiple architectures,
1278 // which means more than one remark file is being generated.
1279 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1280 bool hasExplicitOutputFile =
1281 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1282 if (hasMultipleInvocations && hasExplicitOutputFile) {
1283 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1284 << "-foptimization-record-file";
1285 return false;
1286 }
1287 return true;
1288}
1289
1290static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1291 const llvm::Triple &Triple,
1292 const InputInfo &Input,
1293 const InputInfo &Output, const JobAction &JA) {
1294 StringRef Format = "yaml";
1295 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1296 Format = A->getValue();
1297
1298 CmdArgs.push_back(Elt: "-opt-record-file");
1299
1300 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1301 if (A) {
1302 CmdArgs.push_back(Elt: A->getValue());
1303 } else {
1304 bool hasMultipleArchs =
1305 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1306 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1307
1308 SmallString<128> F;
1309
1310 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1311 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1312 F = FinalOutput->getValue();
1313 } else {
1314 if (Format != "yaml" && // For YAML, keep the original behavior.
1315 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1316 Output.isFilename())
1317 F = Output.getFilename();
1318 }
1319
1320 if (F.empty()) {
1321 // Use the input filename.
1322 F = llvm::sys::path::stem(path: Input.getBaseInput());
1323
1324 // If we're compiling for an offload architecture (i.e. a CUDA device),
1325 // we need to make the file name for the device compilation different
1326 // from the host compilation.
1327 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1328 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1329 llvm::sys::path::replace_extension(path&: F, extension: "");
1330 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1331 NormalizedTriple: Triple.str());
1332 F += "-";
1333 F += JA.getOffloadingArch().ArchName;
1334 }
1335 }
1336
1337 // If we're having more than one "-arch", we should name the files
1338 // differently so that every cc1 invocation writes to a different file.
1339 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1340 // name from the triple.
1341 if (hasMultipleArchs) {
1342 // First, remember the extension.
1343 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1344 // then, remove it.
1345 llvm::sys::path::replace_extension(path&: F, extension: "");
1346 // attach -<arch> to it.
1347 F += "-";
1348 F += Triple.getArchName();
1349 // put back the extension.
1350 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1351 }
1352
1353 SmallString<32> Extension;
1354 Extension += "opt.";
1355 Extension += Format;
1356
1357 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1358 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1359 }
1360
1361 if (const Arg *A =
1362 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1363 CmdArgs.push_back(Elt: "-opt-record-passes");
1364 CmdArgs.push_back(Elt: A->getValue());
1365 }
1366
1367 if (!Format.empty()) {
1368 CmdArgs.push_back(Elt: "-opt-record-format");
1369 CmdArgs.push_back(Elt: Format.data());
1370 }
1371}
1372
1373void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1374 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1375 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1376 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1377
1378 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1379 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1380}
1381
1382namespace {
1383void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1384 const ArgList &Args, ArgStringList &CmdArgs) {
1385 // Select the ABI to use.
1386 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1387 const char *ABIName = nullptr;
1388 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1389 ABIName = A->getValue();
1390 else
1391 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1392
1393 CmdArgs.push_back(Elt: "-target-abi");
1394 CmdArgs.push_back(Elt: ABIName);
1395}
1396
1397void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1398 auto StrictAlignIter =
1399 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1400 return Arg == "+strict-align" || Arg == "-strict-align";
1401 });
1402 if (StrictAlignIter != CmdArgs.rend() &&
1403 StringRef(*StrictAlignIter) == "+strict-align")
1404 CmdArgs.push_back(Elt: "-Wunaligned-access");
1405}
1406}
1407
1408static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1409 ArgStringList &CmdArgs, bool isAArch64) {
1410 const llvm::Triple &Triple = TC.getEffectiveTriple();
1411 const Arg *A = isAArch64
1412 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1413 Ids: options::OPT_mbranch_protection_EQ)
1414 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1415 const Arg *HardenPACRetArg = Args.getLastArg(Ids: options::OPT_mharden_pac_ret_EQ);
1416 const Driver &D = TC.getDriver();
1417
1418 if (HardenPACRetArg) {
1419 if (!isAArch64) {
1420 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1421 << HardenPACRetArg->getSpelling() << TC.getTriple().str();
1422 return;
1423 }
1424 StringRef ArgValue = HardenPACRetArg->getValue();
1425 if (ArgValue != "none" && ArgValue != "load-return-address") {
1426 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1427 << HardenPACRetArg->getSpelling() << ArgValue;
1428 return;
1429 }
1430 if (ArgValue != "none" &&
1431 Args.hasFlagNoClaim(Pos: options::OPT_mexecute_only,
1432 Neg: options::OPT_mno_execute_only, Default: false)) {
1433 D.Diag(DiagID: diag::err_drv_incompatible_options)
1434 << HardenPACRetArg->getAsString(Args) << "-mexecute-only";
1435 return;
1436 }
1437 }
1438
1439 // Check CmdArgs because some toolchains bypass the driver args and add to
1440 // the frontend args directly.
1441 bool HasPtrauthReturns =
1442 llvm::is_contained(Range&: CmdArgs, Element: StringRef("-fptrauth-returns")) ||
1443 Args.hasFlagNoClaim(Pos: options::OPT_fptrauth_returns,
1444 Neg: options::OPT_fno_ptrauth_returns, Default: false);
1445
1446 auto RenderHardenPACRet = [&](StringRef Scope) {
1447 if (!HardenPACRetArg)
1448 return;
1449 if (Scope == "none" && !HasPtrauthReturns)
1450 D.Diag(DiagID: diag::warn_harden_pac_ret_requires_pac_ret);
1451 else
1452 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mharden-pac-ret=") +
1453 HardenPACRetArg->getValue()));
1454 };
1455
1456 if (!A) {
1457 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1458 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1459 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1460 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1461 RenderHardenPACRet("non-leaf");
1462 } else {
1463 RenderHardenPACRet("none");
1464 }
1465 return;
1466 }
1467
1468 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1469 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1470 << Triple.getArchName();
1471
1472 StringRef Scope, Key;
1473 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1474
1475 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1476 Scope = A->getValue();
1477 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1478 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1479 << A->getSpelling() << Scope;
1480 // This spelling cannot express a key, and AArch64 Windows and UEFI only
1481 // support B-key, so default to it there as parseBranchProtection() does.
1482 Key = isAArch64 && Triple.isOSWindowsOrUEFI() ? "b_key" : "a_key";
1483 IndirectBranches =
1484 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1485 BranchProtectionPAuthLR = false;
1486 GuardedControlStack = false;
1487 } else {
1488 StringRef DiagMsg;
1489 llvm::ARM::ParsedBranchProtection PBP;
1490 bool EnablePAuthLR = false;
1491
1492 // To know if we need to enable PAuth-LR As part of the standard branch
1493 // protection option, it needs to be determined if the feature has been
1494 // activated in the `march` argument. This information is stored within the
1495 // CmdArgs variable and can be found using a search.
1496 if (isAArch64) {
1497 auto isPAuthLR = [](const char *member) {
1498 llvm::AArch64::ExtensionInfo pauthlr_extension =
1499 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1500 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1501 member;
1502 };
1503
1504 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1505 EnablePAuthLR = true;
1506 }
1507 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg, Triple,
1508 EnablePAuthLR))
1509 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1510 << A->getSpelling() << DiagMsg;
1511 if (!isAArch64 && PBP.Key == "b_key")
1512 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1513 << "b-key" << A->getAsString(Args);
1514 Scope = PBP.Scope;
1515 Key = PBP.Key;
1516 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1517 IndirectBranches = PBP.BranchTargetEnforcement;
1518 GuardedControlStack = PBP.GuardedControlStack;
1519 }
1520
1521 // GCS is currently untested with ptrauth-returns, but enabling this could be
1522 // allowed in future after testing with a suitable system.
1523 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1524 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1525 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1526 << A->getAsString(Args) << Triple.getTriple();
1527 else if (HasPtrauthReturns)
1528 D.Diag(DiagID: diag::err_drv_incompatible_options)
1529 << A->getAsString(Args) << "-fptrauth-returns";
1530 }
1531
1532 CmdArgs.push_back(
1533 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1534 if (Scope != "none")
1535 CmdArgs.push_back(
1536 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1537 if (BranchProtectionPAuthLR)
1538 CmdArgs.push_back(
1539 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1540 if (IndirectBranches)
1541 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1542
1543 if (GuardedControlStack)
1544 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1545
1546 RenderHardenPACRet(Scope);
1547}
1548
1549void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1550 ArgStringList &CmdArgs, bool KernelOrKext) const {
1551 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1552
1553 // Determine floating point ABI from the options & target defaults.
1554 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1555 if (ABI == arm::FloatABI::Soft) {
1556 // Floating point operations and argument passing are soft.
1557 // FIXME: This changes CPP defines, we need -target-soft-float.
1558 CmdArgs.push_back(Elt: "-msoft-float");
1559 CmdArgs.push_back(Elt: "-mfloat-abi");
1560 CmdArgs.push_back(Elt: "soft");
1561 } else if (ABI == arm::FloatABI::SoftFP) {
1562 // Floating point operations are hard, but argument passing is soft.
1563 CmdArgs.push_back(Elt: "-mfloat-abi");
1564 CmdArgs.push_back(Elt: "soft");
1565 } else {
1566 // Floating point operations and argument passing are hard.
1567 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1568 CmdArgs.push_back(Elt: "-mfloat-abi");
1569 CmdArgs.push_back(Elt: "hard");
1570 }
1571
1572 // Forward the -mglobal-merge option for explicit control over the pass.
1573 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1574 Ids: options::OPT_mno_global_merge)) {
1575 CmdArgs.push_back(Elt: "-mllvm");
1576 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1577 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1578 else
1579 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1580 }
1581
1582 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1583 Neg: options::OPT_mno_implicit_float, Default: true))
1584 CmdArgs.push_back(Elt: "-no-implicit-float");
1585
1586 if (Args.getLastArg(Ids: options::OPT_mcmse))
1587 CmdArgs.push_back(Elt: "-mcmse");
1588
1589 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1590
1591 // Enable/disable return address signing and indirect branch targets.
1592 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1593
1594 AddUnalignedAccessWarning(CmdArgs);
1595}
1596
1597void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1598 ArgStringList &CmdArgs) const {
1599 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1600 if (Arg *A = Args.getLastArg(Ids: options::OPT_mxnack, Ids: options::OPT_mno_xnack))
1601 A->render(Args, Output&: CmdArgs);
1602 if (Arg *A = Args.getLastArg(Ids: options::OPT_msramecc, Ids: options::OPT_mno_sramecc))
1603 A->render(Args, Output&: CmdArgs);
1604}
1605
1606void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1607 const ArgList &Args, bool KernelOrKext,
1608 ArgStringList &CmdArgs) const {
1609 const ToolChain &TC = getToolChain();
1610
1611 // Add the target features
1612 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1613
1614 // Add target specific flags.
1615 switch (TC.getArch()) {
1616 default:
1617 break;
1618
1619 case llvm::Triple::arm:
1620 case llvm::Triple::armeb:
1621 case llvm::Triple::thumb:
1622 case llvm::Triple::thumbeb:
1623 // Use the effective triple, which takes into account the deployment target.
1624 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1625 break;
1626
1627 case llvm::Triple::aarch64:
1628 case llvm::Triple::aarch64_32:
1629 case llvm::Triple::aarch64_be:
1630 AddAArch64TargetArgs(Args, CmdArgs);
1631 break;
1632
1633 case llvm::Triple::amdgpu:
1634 AddAMDGPUTargetArgs(Args, CmdArgs);
1635 break;
1636
1637 case llvm::Triple::loongarch32:
1638 case llvm::Triple::loongarch64:
1639 AddLoongArchTargetArgs(Args, CmdArgs);
1640 break;
1641
1642 case llvm::Triple::mips:
1643 case llvm::Triple::mipsel:
1644 case llvm::Triple::mips64:
1645 case llvm::Triple::mips64el:
1646 AddMIPSTargetArgs(Args, CmdArgs);
1647 break;
1648
1649 case llvm::Triple::ppc:
1650 case llvm::Triple::ppcle:
1651 case llvm::Triple::ppc64:
1652 case llvm::Triple::ppc64le:
1653 AddPPCTargetArgs(Args, CmdArgs);
1654 break;
1655
1656 case llvm::Triple::riscv32:
1657 case llvm::Triple::riscv64:
1658 case llvm::Triple::riscv32be:
1659 case llvm::Triple::riscv64be:
1660 AddRISCVTargetArgs(Args, CmdArgs);
1661 break;
1662
1663 case llvm::Triple::sparc:
1664 case llvm::Triple::sparcel:
1665 case llvm::Triple::sparcv9:
1666 AddSparcTargetArgs(Args, CmdArgs);
1667 break;
1668
1669 case llvm::Triple::systemz:
1670 AddSystemZTargetArgs(Args, CmdArgs);
1671 break;
1672
1673 case llvm::Triple::x86:
1674 case llvm::Triple::x86_64:
1675 AddX86TargetArgs(Args, CmdArgs);
1676 break;
1677
1678 case llvm::Triple::lanai:
1679 AddLanaiTargetArgs(Args, CmdArgs);
1680 break;
1681
1682 case llvm::Triple::hexagon:
1683 AddHexagonTargetArgs(Args, CmdArgs);
1684 break;
1685
1686 case llvm::Triple::wasm32:
1687 case llvm::Triple::wasm64:
1688 AddWebAssemblyTargetArgs(Args, CmdArgs);
1689 break;
1690
1691 case llvm::Triple::ve:
1692 AddVETargetArgs(Args, CmdArgs);
1693 break;
1694 }
1695}
1696
1697namespace {
1698void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1699 ArgStringList &CmdArgs) {
1700 const char *ABIName = nullptr;
1701 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1702 ABIName = A->getValue();
1703 else if (Triple.isOSDarwin())
1704 ABIName = "darwinpcs";
1705 // TODO: we probably want to have some target hook here.
1706 else if (Triple.isOSLinux() &&
1707 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1708 ABIName = "pauthtest";
1709 else
1710 ABIName = "aapcs";
1711
1712 CmdArgs.push_back(Elt: "-target-abi");
1713 CmdArgs.push_back(Elt: ABIName);
1714}
1715}
1716
1717void Clang::AddAArch64TargetArgs(const ArgList &Args,
1718 ArgStringList &CmdArgs) const {
1719 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1720
1721 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1722 Args.hasArg(Ids: options::OPT_mkernel) ||
1723 Args.hasArg(Ids: options::OPT_fapple_kext))
1724 CmdArgs.push_back(Elt: "-disable-red-zone");
1725
1726 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1727 Neg: options::OPT_mno_implicit_float, Default: true))
1728 CmdArgs.push_back(Elt: "-no-implicit-float");
1729
1730 RenderAArch64ABI(Triple, Args, CmdArgs);
1731
1732 // Forward the -mglobal-merge option for explicit control over the pass.
1733 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1734 Ids: options::OPT_mno_global_merge)) {
1735 CmdArgs.push_back(Elt: "-mllvm");
1736 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1737 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1738 else
1739 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1740 }
1741
1742 // Handle -msve_vector_bits=<bits>
1743 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1744 StringRef VScaleMax) {
1745 StringRef Val = A->getValue();
1746 const Driver &D = getToolChain().getDriver();
1747 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1748 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1749 Val == "1024+" || Val == "2048+") {
1750 unsigned Bits = 0;
1751 if (!Val.consume_back(Suffix: "+")) {
1752 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1753 (void)Invalid;
1754 assert(!Invalid && "Failed to parse value");
1755 CmdArgs.push_back(
1756 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1757 }
1758
1759 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1760 (void)Invalid;
1761 assert(!Invalid && "Failed to parse value");
1762
1763 CmdArgs.push_back(
1764 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1765 } else if (Val == "scalable") {
1766 // Silently drop requests for vector-length agnostic code as it's implied.
1767 } else {
1768 // Handle the unsupported values passed to msve-vector-bits.
1769 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1770 << A->getSpelling() << Val;
1771 }
1772 };
1773 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1774 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1775 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1776 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1777
1778 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1779
1780 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1781 CmdArgs.push_back(Elt: "-tune-cpu");
1782 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
1783 }
1784
1785 AddUnalignedAccessWarning(CmdArgs);
1786
1787 if (Triple.isOSDarwin() ||
1788 (Triple.isOSLinux() &&
1789 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1790 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1791 Neg: options::OPT_fno_ptrauth_intrinsics);
1792 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1793 Neg: options::OPT_fno_ptrauth_calls);
1794 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1795 Neg: options::OPT_fno_ptrauth_returns);
1796 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1797 Neg: options::OPT_fno_ptrauth_auth_traps);
1798 Args.addOptInFlag(
1799 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1800 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1801 Args.addOptInFlag(
1802 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1803 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1804 Args.addOptInFlag(
1805 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1806 Neg: options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1807 Args.addOptInFlag(
1808 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1809 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1810 Args.addOptInFlag(
1811 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1812 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1813 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1814 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1815 }
1816 if (Triple.isOSLinux() &&
1817 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1818 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1819 Neg: options::OPT_fno_ptrauth_init_fini);
1820 Args.addOptInFlag(
1821 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1822 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1823 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1824 Neg: options::OPT_fno_ptrauth_elf_got);
1825 }
1826 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1827 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1828
1829 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1830 Neg: options::OPT_fno_ptrauth_objc_isa);
1831 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1832 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1833 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1834 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1835
1836 // Enable/disable return address signing and indirect branch targets.
1837 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1838}
1839
1840void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1841 ArgStringList &CmdArgs) const {
1842 const llvm::Triple &Triple = getToolChain().getTriple();
1843
1844 CmdArgs.push_back(Elt: "-target-abi");
1845 CmdArgs.push_back(
1846 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1847 .data());
1848
1849 // Handle -mtune.
1850 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1851 std::string TuneCPU = A->getValue();
1852 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1853 CmdArgs.push_back(Elt: "-tune-cpu");
1854 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1855 }
1856
1857 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1858 Ids: options::OPT_mno_annotate_tablejump)) {
1859 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1860 CmdArgs.push_back(Elt: "-mllvm");
1861 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1862 }
1863 }
1864}
1865
1866void Clang::AddMIPSTargetArgs(const ArgList &Args,
1867 ArgStringList &CmdArgs) const {
1868 const Driver &D = getToolChain().getDriver();
1869 StringRef CPUName;
1870 StringRef ABIName;
1871 const llvm::Triple &Triple = getToolChain().getTriple();
1872 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1873
1874 CmdArgs.push_back(Elt: "-target-abi");
1875 CmdArgs.push_back(Elt: ABIName.data());
1876
1877 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1878 if (ABI == mips::FloatABI::Soft) {
1879 // Floating point operations and argument passing are soft.
1880 CmdArgs.push_back(Elt: "-msoft-float");
1881 CmdArgs.push_back(Elt: "-mfloat-abi");
1882 CmdArgs.push_back(Elt: "soft");
1883 } else {
1884 // Floating point operations and argument passing are hard.
1885 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1886 CmdArgs.push_back(Elt: "-mfloat-abi");
1887 CmdArgs.push_back(Elt: "hard");
1888 }
1889
1890 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1891 Ids: options::OPT_mno_ldc1_sdc1)) {
1892 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1893 CmdArgs.push_back(Elt: "-mllvm");
1894 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1895 }
1896 }
1897
1898 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1899 Ids: options::OPT_mno_check_zero_division)) {
1900 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1901 CmdArgs.push_back(Elt: "-mllvm");
1902 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1903 }
1904 }
1905
1906 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1907 CmdArgs.push_back(Elt: "-mllvm");
1908 CmdArgs.push_back(Elt: "-mfix4300");
1909 }
1910
1911 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1912 StringRef v = A->getValue();
1913 CmdArgs.push_back(Elt: "-mllvm");
1914 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1915 A->claim();
1916 }
1917
1918 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1919 Arg *ABICalls =
1920 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1921
1922 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1923 // -mgpopt is the default for static, -fno-pic environments but these two
1924 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1925 // the only case where -mllvm -mgpopt is passed.
1926 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1927 // passed explicitly when compiling something with -mabicalls
1928 // (implictly) in affect. Currently the warning is in the backend.
1929 //
1930 // When the ABI in use is N64, we also need to determine the PIC mode that
1931 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1932 bool NoABICalls =
1933 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1934
1935 llvm::Reloc::Model RelocationModel;
1936 unsigned PICLevel;
1937 bool IsPIE;
1938 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1939 ParsePICArgs(ToolChain: getToolChain(), Args);
1940
1941 NoABICalls = NoABICalls ||
1942 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1943
1944 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1945 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1946 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1947 CmdArgs.push_back(Elt: "-mllvm");
1948 CmdArgs.push_back(Elt: "-mgpopt");
1949
1950 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1951 Ids: options::OPT_mno_local_sdata);
1952 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1953 Ids: options::OPT_mno_extern_sdata);
1954 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1955 Ids: options::OPT_mno_embedded_data);
1956 if (LocalSData) {
1957 CmdArgs.push_back(Elt: "-mllvm");
1958 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1959 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1960 } else {
1961 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1962 }
1963 LocalSData->claim();
1964 }
1965
1966 if (ExternSData) {
1967 CmdArgs.push_back(Elt: "-mllvm");
1968 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1969 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1970 } else {
1971 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1972 }
1973 ExternSData->claim();
1974 }
1975
1976 if (EmbeddedData) {
1977 CmdArgs.push_back(Elt: "-mllvm");
1978 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1979 CmdArgs.push_back(Elt: "-membedded-data=1");
1980 } else {
1981 CmdArgs.push_back(Elt: "-membedded-data=0");
1982 }
1983 EmbeddedData->claim();
1984 }
1985
1986 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1987 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1988
1989 if (GPOpt)
1990 GPOpt->claim();
1991
1992 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1993 StringRef Val = StringRef(A->getValue());
1994 if (mips::hasCompactBranches(CPU&: CPUName)) {
1995 if (Val == "never" || Val == "always" || Val == "optimal") {
1996 CmdArgs.push_back(Elt: "-mllvm");
1997 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1998 } else
1999 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2000 << A->getSpelling() << Val;
2001 } else
2002 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
2003 }
2004
2005 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
2006 Ids: options::OPT_mno_relax_pic_calls)) {
2007 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
2008 CmdArgs.push_back(Elt: "-mllvm");
2009 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
2010 }
2011 }
2012}
2013
2014void Clang::AddPPCTargetArgs(const ArgList &Args,
2015 ArgStringList &CmdArgs) const {
2016 const Driver &D = getToolChain().getDriver();
2017 const llvm::Triple &T = getToolChain().getTriple();
2018 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2019 CmdArgs.push_back(Elt: "-tune-cpu");
2020 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
2021 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
2022 }
2023
2024 // Select the ABI to use.
2025 const char *ABIName = nullptr;
2026 if (T.isOSBinFormatELF()) {
2027 switch (getToolChain().getArch()) {
2028 case llvm::Triple::ppc64: {
2029 if (T.isPPC64ELFv2ABI())
2030 ABIName = "elfv2";
2031 else
2032 ABIName = "elfv1";
2033 break;
2034 }
2035 case llvm::Triple::ppc64le:
2036 ABIName = "elfv2";
2037 break;
2038 default:
2039 break;
2040 }
2041 }
2042
2043 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2044 bool VecExtabi = false;
2045 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
2046 StringRef V = A->getValue();
2047 if (V == "ieeelongdouble") {
2048 IEEELongDouble = true;
2049 A->claim();
2050 } else if (V == "ibmlongdouble") {
2051 IEEELongDouble = false;
2052 A->claim();
2053 } else if (V == "vec-default") {
2054 VecExtabi = false;
2055 A->claim();
2056 } else if (V == "vec-extabi") {
2057 VecExtabi = true;
2058 A->claim();
2059 } else if (V == "elfv1") {
2060 ABIName = "elfv1";
2061 A->claim();
2062 } else if (V == "elfv2") {
2063 ABIName = "elfv2";
2064 A->claim();
2065 } else if (V != "altivec")
2066 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2067 // the option if given as we don't have backend support for any targets
2068 // that don't use the altivec abi.
2069 ABIName = A->getValue();
2070 }
2071 if (IEEELongDouble)
2072 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
2073 if (VecExtabi) {
2074 if (!T.isOSAIX())
2075 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2076 << "-mabi=vec-extabi" << T.str();
2077 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
2078 }
2079
2080 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
2081 CmdArgs.push_back(Elt: "-disable-red-zone");
2082
2083 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2084 if (FloatABI == ppc::FloatABI::Soft) {
2085 // Floating point operations and argument passing are soft.
2086 CmdArgs.push_back(Elt: "-msoft-float");
2087 CmdArgs.push_back(Elt: "-mfloat-abi");
2088 CmdArgs.push_back(Elt: "soft");
2089 } else {
2090 // Floating point operations and argument passing are hard.
2091 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2092 CmdArgs.push_back(Elt: "-mfloat-abi");
2093 CmdArgs.push_back(Elt: "hard");
2094 }
2095
2096 if (ABIName) {
2097 CmdArgs.push_back(Elt: "-target-abi");
2098 CmdArgs.push_back(Elt: ABIName);
2099 }
2100}
2101
2102void Clang::AddRISCVTargetArgs(const ArgList &Args,
2103 ArgStringList &CmdArgs) const {
2104 const llvm::Triple &Triple = getToolChain().getTriple();
2105 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2106
2107 CmdArgs.push_back(Elt: "-target-abi");
2108 CmdArgs.push_back(Elt: ABIName.data());
2109
2110 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2111 CmdArgs.push_back(Elt: "-msmall-data-limit");
2112 CmdArgs.push_back(Elt: A->getValue());
2113 }
2114
2115 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2116 Neg: options::OPT_mno_implicit_float, Default: true))
2117 CmdArgs.push_back(Elt: "-no-implicit-float");
2118
2119 auto TuneCPU = riscv::getRISCVTuneCPU(D: getToolChain().getDriver(), Args);
2120 if (!TuneCPU)
2121 return;
2122 if (!TuneCPU->empty()) {
2123 CmdArgs.push_back(Elt: "-tune-cpu");
2124 // TuneCPU might or might not be the original -mtune string, so we
2125 // have to create a new copy here.
2126 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
2127 }
2128
2129 // Handle -mrvv-vector-bits=<bits>
2130 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2131 StringRef Val = A->getValue();
2132 const Driver &D = getToolChain().getDriver();
2133
2134 // Get minimum VLen from march.
2135 unsigned MinVLen = 0;
2136 std::string Arch = riscv::getRISCVArch(Args, Triple);
2137 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2138 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2139 // Ignore parsing error.
2140 if (!errorToBool(Err: ISAInfo.takeError()))
2141 MinVLen = (*ISAInfo)->getMinVLen();
2142
2143 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2144 // as integer as long as we have a MinVLen.
2145 unsigned Bits = 0;
2146 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2147 Bits = MinVLen;
2148 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2149 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2150 // at least MinVLen.
2151 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2152 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2153 Bits = 0;
2154 }
2155
2156 // If we got a valid value try to use it.
2157 if (Bits != 0) {
2158 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2159 CmdArgs.push_back(
2160 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2161 CmdArgs.push_back(
2162 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2163 } else if (Val != "scalable") {
2164 // Handle the unsupported values passed to mrvv-vector-bits.
2165 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2166 << A->getSpelling() << Val;
2167 }
2168 }
2169}
2170
2171void Clang::AddSparcTargetArgs(const ArgList &Args,
2172 ArgStringList &CmdArgs) const {
2173 sparc::FloatABI FloatABI =
2174 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2175
2176 if (FloatABI == sparc::FloatABI::Soft) {
2177 // Floating point operations and argument passing are soft.
2178 CmdArgs.push_back(Elt: "-msoft-float");
2179 CmdArgs.push_back(Elt: "-mfloat-abi");
2180 CmdArgs.push_back(Elt: "soft");
2181 } else {
2182 // Floating point operations and argument passing are hard.
2183 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2184 CmdArgs.push_back(Elt: "-mfloat-abi");
2185 CmdArgs.push_back(Elt: "hard");
2186 }
2187
2188 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2189 StringRef Name = A->getValue();
2190 std::string TuneCPU;
2191 if (Name == "native")
2192 TuneCPU = std::string(llvm::sys::getHostCPUName());
2193 else
2194 TuneCPU = std::string(Name);
2195
2196 CmdArgs.push_back(Elt: "-tune-cpu");
2197 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2198 }
2199}
2200
2201void Clang::AddSystemZTargetArgs(const ArgList &Args,
2202 ArgStringList &CmdArgs) const {
2203 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2204 CmdArgs.push_back(Elt: "-tune-cpu");
2205 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2206 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2207 else
2208 CmdArgs.push_back(Elt: A->getValue());
2209 }
2210
2211 bool HasBackchain =
2212 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2213 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2214 Neg: options::OPT_mno_packed_stack, Default: false);
2215 systemz::FloatABI FloatABI =
2216 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2217 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2218
2219 // Only hard float ABI (-mhard-float) is supported on z/OS.
2220 const Driver &D = getToolChain().getDriver();
2221 const llvm::Triple &Triple = getToolChain().getTriple();
2222 if (HasSoftFloat && Triple.isOSzOS()) {
2223 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2224 << "-msoft-float" << Triple.str();
2225 }
2226 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2227 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2228 << "-mpacked-stack -mbackchain -mhard-float";
2229 }
2230 if (HasBackchain)
2231 CmdArgs.push_back(Elt: "-mbackchain");
2232 if (HasPackedStack)
2233 CmdArgs.push_back(Elt: "-mpacked-stack");
2234 if (HasSoftFloat) {
2235 // Floating point operations and argument passing are soft.
2236 CmdArgs.push_back(Elt: "-msoft-float");
2237 CmdArgs.push_back(Elt: "-mfloat-abi");
2238 CmdArgs.push_back(Elt: "soft");
2239 }
2240
2241 if (Triple.isOSzOS())
2242 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mzos_ppa1_name,
2243 Ids: options::OPT_mno_zos_ppa1_name);
2244}
2245
2246void Clang::AddX86TargetArgs(const ArgList &Args,
2247 ArgStringList &CmdArgs) const {
2248 const Driver &D = getToolChain().getDriver();
2249 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2250
2251 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2252 Args.hasArg(Ids: options::OPT_mkernel) ||
2253 Args.hasArg(Ids: options::OPT_fapple_kext))
2254 CmdArgs.push_back(Elt: "-disable-red-zone");
2255
2256 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2257 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2258 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2259
2260 // Default to avoid implicit floating-point for kernel/kext code, but allow
2261 // that to be overridden with -mno-soft-float.
2262 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2263 Args.hasArg(Ids: options::OPT_fapple_kext));
2264 if (Arg *A = Args.getLastArg(
2265 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2266 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2267 const Option &O = A->getOption();
2268 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2269 O.matches(ID: options::OPT_msoft_float));
2270 }
2271 if (NoImplicitFloat)
2272 CmdArgs.push_back(Elt: "-no-implicit-float");
2273
2274 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2275 StringRef Value = A->getValue();
2276 if (Value == "intel" || Value == "att") {
2277 CmdArgs.push_back(Elt: "-mllvm");
2278 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2279 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2280 } else {
2281 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2282 << A->getSpelling() << Value;
2283 }
2284 } else if (D.IsCLMode()) {
2285 CmdArgs.push_back(Elt: "-mllvm");
2286 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2287 }
2288
2289 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2290 Ids: options::OPT_mno_skip_rax_setup))
2291 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2292 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2293
2294 // Set flags to support MCU ABI.
2295 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2296 CmdArgs.push_back(Elt: "-mfloat-abi");
2297 CmdArgs.push_back(Elt: "soft");
2298 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2299 }
2300
2301 // Handle -mtune.
2302
2303 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2304 std::string TuneCPU;
2305 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2306 TuneCPU = "generic";
2307
2308 // Override based on -mtune.
2309 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2310 StringRef Name = A->getValue();
2311
2312 if (Name == "native") {
2313 Name = llvm::sys::getHostCPUName();
2314 if (!Name.empty())
2315 TuneCPU = std::string(Name);
2316 } else
2317 TuneCPU = std::string(Name);
2318 }
2319
2320 if (!TuneCPU.empty()) {
2321 CmdArgs.push_back(Elt: "-tune-cpu");
2322 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2323 }
2324}
2325
2326static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2327 size_t Index = Option.find(C: Delimiter);
2328 if (Index != StringRef::npos)
2329 Option = Option.substr(Start: 0, N: Index);
2330 return Option;
2331}
2332
2333static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2334 Opt = getOptionName(Option: Opt);
2335 if (CmdArgs.size() < 2)
2336 return;
2337
2338 for (auto It = std::next(x: CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2339 StringRef Option = *It;
2340 if (!Option.starts_with(Prefix: Opt))
2341 continue;
2342 Option = getOptionName(Option);
2343 if (Option != Opt)
2344 continue;
2345 if (StringRef(*(It - 1)) != "-mllvm")
2346 continue;
2347
2348 It = CmdArgs.erase(CI: It);
2349 CmdArgs.erase(CI: It - 1);
2350 return;
2351 }
2352}
2353
2354static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2355 checkAndRemoveLLVMArg(CmdArgs, Opt: A);
2356 CmdArgs.push_back(Elt: "-mllvm");
2357 CmdArgs.push_back(Elt: A);
2358}
2359
2360static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2361 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2362 StringRef Option = *It;
2363 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2364 It = CmdArgs.erase(CI: It);
2365 Ie = CmdArgs.end();
2366 } else {
2367 ++It;
2368 }
2369 }
2370
2371 CmdArgs.push_back(Elt: "-menable-no-infs");
2372 CmdArgs.push_back(Elt: "-menable-no-nans");
2373 CmdArgs.push_back(Elt: "-fapprox-func");
2374 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
2375 CmdArgs.push_back(Elt: "-fno-signed-zeros");
2376 CmdArgs.push_back(Elt: "-mreassociate");
2377 CmdArgs.push_back(Elt: "-freciprocal-math");
2378 CmdArgs.push_back(Elt: "-ffp-contract=fast");
2379 CmdArgs.push_back(Elt: "-ffast-math");
2380 CmdArgs.push_back(Elt: "-ffinite-math-only");
2381 CmdArgs.push_back(Elt: "-D__FAST_MATH__");
2382 pushBackLLVMArg(CmdArgs, A: "-fast-math=true");
2383}
2384
2385static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2386 ArgStringList &CmdArgs) {
2387 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2388 bool HasHVX = HvxVerOpt.has_value();
2389 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2390 if (!Args.hasArg(Ids: options::OPT_mhexagon_hvx, Ids: options::OPT_mhexagon_hvx_EQ,
2391 Ids: options::OPT_mhexagon_hvx_ieee_fp) ||
2392 !HasHVX)
2393 return;
2394 unsigned HvxVerNum = 0;
2395 if (StringRef(HvxVer).drop_front(N: 1).getAsInteger(Radix: 10, Result&: HvxVerNum))
2396 HvxVerNum = 0;
2397
2398 if (Arg *A = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2399 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2400 Ids: options::OPT_mhexagon_hvx_ieee_fp)) {
2401 if (HvxVerNum >= 79) {
2402 if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2403 const char *Mode =
2404 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2405 .Case(S: "strict-ieee", Value: "-hexagon-qfloat-mode=strict-ieee")
2406 .Case(S: "ieee", Value: "-hexagon-qfloat-mode=ieee")
2407 .Case(S: "lossy", Value: "-hexagon-qfloat-mode=lossy")
2408 .Case(S: "legacy", Value: "-hexagon-qfloat-mode=legacy")
2409 .Default(Value: nullptr);
2410 if (!Mode) {
2411 D.Diag(DiagID: diag::err_drv_invalid_value)
2412 << A->getAsString(Args) << A->getValue();
2413 return;
2414 }
2415 pushBackLLVMArg(CmdArgs, A: Mode);
2416 if (strcmp(s1: Mode, s2: "-hexagon-qfloat-mode=lossy") == 0)
2417 addQFloatLossyFastMathArgs(CmdArgs);
2418 } else if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat)) {
2419 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=lossy");
2420 addQFloatLossyFastMathArgs(CmdArgs);
2421 } else {
2422 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=ieee");
2423 }
2424 } else {
2425 if (Arg *QFloatArg = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2426 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2427 Ids: options::OPT_mno_hexagon_hvx_qfloat);
2428 QFloatArg &&
2429 QFloatArg->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2430 D.Diag(DiagID: diag::warn_drv_unsupported_option_part_for_target)
2431 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2432 << (std::string("HVX ") + HvxVer +
2433 "; falling back to legacy qfloat mode");
2434 }
2435 }
2436 }
2437}
2438
2439void Clang::AddHexagonTargetArgs(const ArgList &Args,
2440 ArgStringList &CmdArgs) const {
2441 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2442 CmdArgs.push_back(Elt: "-Wreturn-type");
2443
2444 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2445 CmdArgs.push_back(Elt: "-mllvm");
2446 CmdArgs.push_back(
2447 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2448 }
2449
2450 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2451 CmdArgs.push_back(Elt: "-fshort-enums");
2452 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2453 CmdArgs.push_back(Elt: "-mllvm");
2454 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2455 }
2456 CmdArgs.push_back(Elt: "-mllvm");
2457 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2458
2459 // Let debuggers find the caller's HLX vector stack pointer.
2460 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group);
2461 A && !A->getOption().matches(ID: options::OPT_g0) &&
2462 !A->getOption().matches(ID: options::OPT_ggdb0)) {
2463 CmdArgs.push_back(Elt: "-mllvm");
2464 CmdArgs.push_back(Elt: "-hexagon-save-parent-vsp");
2465 }
2466
2467 addQFloatBackendArg(D: getToolChain().getDriver(), Args, CmdArgs);
2468}
2469
2470void Clang::AddLanaiTargetArgs(const ArgList &Args,
2471 ArgStringList &CmdArgs) const {
2472 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2473 StringRef CPUName = A->getValue();
2474
2475 CmdArgs.push_back(Elt: "-target-cpu");
2476 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2477 }
2478 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2479 StringRef Value = A->getValue();
2480 // Only support mregparm=4 to support old usage. Report error for all other
2481 // cases.
2482 int Mregparm;
2483 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2484 if (Mregparm != 4) {
2485 getToolChain().getDriver().Diag(
2486 DiagID: diag::err_drv_unsupported_option_argument)
2487 << A->getSpelling() << Value;
2488 }
2489 }
2490 }
2491}
2492
2493void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2494 ArgStringList &CmdArgs) const {
2495 // Default to "hidden" visibility.
2496 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2497 Ids: options::OPT_fvisibility_ms_compat))
2498 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2499}
2500
2501void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2502 // Floating point operations and argument passing are hard.
2503 CmdArgs.push_back(Elt: "-mfloat-abi");
2504 CmdArgs.push_back(Elt: "hard");
2505}
2506
2507void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2508 StringRef Target, const InputInfo &Output,
2509 const InputInfo &Input, const ArgList &Args) const {
2510 // If this is a dry run, do not create the compilation database file.
2511 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2512 return;
2513
2514 using llvm::yaml::escape;
2515 const Driver &D = getToolChain().getDriver();
2516
2517 if (!CompilationDatabase) {
2518 std::error_code EC;
2519 auto File = std::make_unique<llvm::raw_fd_ostream>(
2520 args&: Filename, args&: EC,
2521 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2522 if (EC) {
2523 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2524 << EC.message();
2525 return;
2526 }
2527 CompilationDatabase = std::move(File);
2528 }
2529 auto &CDB = *CompilationDatabase;
2530 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2531 if (!CWD)
2532 CWD = ".";
2533 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2534 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2535 if (Output.isFilename())
2536 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2537 CDB << ", \"arguments\": [\"" << escape(Input: D.DriverExecutable) << "\"";
2538 SmallString<128> Buf;
2539 Buf = "-x";
2540 Buf += types::getTypeName(Id: Input.getType());
2541 CDB << ", \"" << escape(Input: Buf) << "\"";
2542 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2543 Buf = "--sysroot=";
2544 Buf += D.SysRoot;
2545 CDB << ", \"" << escape(Input: Buf) << "\"";
2546 }
2547 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2548 if (Output.isFilename())
2549 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2550 for (auto &A: Args) {
2551 auto &O = A->getOption();
2552 // Skip language selection, which is positional.
2553 if (O.getID() == options::OPT_x)
2554 continue;
2555 // Skip writing dependency output and the compilation database itself.
2556 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2557 continue;
2558 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2559 continue;
2560 // Skip inputs.
2561 if (O.getKind() == Option::InputClass)
2562 continue;
2563 // Skip output.
2564 if (O.getID() == options::OPT_o)
2565 continue;
2566 // All other arguments are quoted and appended.
2567 ArgStringList ASL;
2568 A->render(Args, Output&: ASL);
2569 for (auto &it: ASL)
2570 CDB << ", \"" << escape(Input: it) << "\"";
2571 }
2572 Buf = "--target=";
2573 Buf += Target;
2574 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2575}
2576
2577void Clang::DumpCompilationDatabaseFragmentToDir(
2578 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2579 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2580 // If this is a dry run, do not create the compilation database file.
2581 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2582 return;
2583
2584 if (CompilationDatabase)
2585 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2586
2587 SmallString<256> Path = Dir;
2588 const auto &Driver = C.getDriver();
2589 Driver.getVFS().makeAbsolute(Path);
2590 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2591 if (Err) {
2592 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2593 return;
2594 }
2595
2596 llvm::sys::path::append(
2597 path&: Path,
2598 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2599 int FD;
2600 SmallString<256> TempPath;
2601 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2602 Flags: llvm::sys::fs::OF_Text);
2603 if (Err) {
2604 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2605 return;
2606 }
2607 CompilationDatabase =
2608 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2609 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2610}
2611
2612static bool CheckARMImplicitITArg(StringRef Value) {
2613 return Value == "always" || Value == "never" || Value == "arm" ||
2614 Value == "thumb";
2615}
2616
2617static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2618 StringRef Value) {
2619 CmdArgs.push_back(Elt: "-mllvm");
2620 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2621}
2622
2623static void CollectArgsForIntegratedAssembler(Compilation &C,
2624 const ArgList &Args,
2625 ArgStringList &CmdArgs,
2626 const Driver &D) {
2627 // Default to -mno-relax-all.
2628 //
2629 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2630 // cannot be done by assembler branch relaxation as it needs a free temporary
2631 // register. Because of this, branch relaxation is handled by a MachineIR pass
2632 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2633 // MachineIR branch relaxation inaccurate and it will miss cases where an
2634 // indirect branch is necessary.
2635 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2636 Neg: options::OPT_mno_relax_all);
2637
2638 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mincremental_linker_compatible,
2639 Ids: options::OPT_mno_incremental_linker_compatible);
2640
2641 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2642
2643 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2644 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2645
2646 // If you add more args here, also add them to the block below that
2647 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2648
2649 // When passing -I arguments to the assembler we sometimes need to
2650 // unconditionally take the next argument. For example, when parsing
2651 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2652 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2653 // arg after parsing the '-I' arg.
2654 bool TakeNextArg = false;
2655
2656 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2657 bool IsELF = Triple.isOSBinFormatELF();
2658 bool Crel = false, ExperimentalCrel = false;
2659 StringRef RelocSectionSym;
2660 bool SFrame = false, ExperimentalSFrame = false;
2661 bool ImplicitMapSyms = false;
2662 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2663 bool UseNoExecStack = false;
2664 bool Msa = false;
2665 const char *MipsTargetFeature = nullptr;
2666 llvm::SmallVector<const char *> SparcTargetFeatures;
2667 StringRef ImplicitIt;
2668 for (const Arg *A :
2669 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2670 Ids: options::OPT_mimplicit_it_EQ)) {
2671 A->claim();
2672
2673 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2674 switch (C.getDefaultToolChain().getArch()) {
2675 case llvm::Triple::arm:
2676 case llvm::Triple::armeb:
2677 case llvm::Triple::thumb:
2678 case llvm::Triple::thumbeb:
2679 // Only store the value; the last value set takes effect.
2680 ImplicitIt = A->getValue();
2681 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2682 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2683 << A->getSpelling() << ImplicitIt;
2684 continue;
2685 default:
2686 break;
2687 }
2688 }
2689
2690 for (StringRef Value : A->getValues()) {
2691 if (TakeNextArg) {
2692 CmdArgs.push_back(Elt: Value.data());
2693 TakeNextArg = false;
2694 continue;
2695 }
2696
2697 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2698 Value == "-mbig-obj")
2699 continue; // LLVM handles bigobj automatically
2700
2701 auto Equal = Value.split(Separator: '=');
2702 auto checkArg = [&](bool ValidTarget,
2703 std::initializer_list<const char *> Set) {
2704 if (!ValidTarget) {
2705 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2706 << (Twine("-Wa,") + Equal.first + "=").str()
2707 << Triple.getTriple();
2708 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2709 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2710 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2711 }
2712 };
2713 switch (C.getDefaultToolChain().getArch()) {
2714 default:
2715 break;
2716 case llvm::Triple::x86:
2717 case llvm::Triple::x86_64:
2718 if (Equal.first == "-mrelax-relocations" ||
2719 Equal.first == "--mrelax-relocations") {
2720 UseRelaxRelocations = Equal.second == "yes";
2721 checkArg(IsELF, {"yes", "no"});
2722 continue;
2723 }
2724 if (Value == "-msse2avx") {
2725 CmdArgs.push_back(Elt: "-msse2avx");
2726 continue;
2727 }
2728 break;
2729 case llvm::Triple::wasm32:
2730 case llvm::Triple::wasm64:
2731 if (Value == "--no-type-check") {
2732 CmdArgs.push_back(Elt: "-mno-type-check");
2733 continue;
2734 }
2735 break;
2736 case llvm::Triple::thumb:
2737 case llvm::Triple::thumbeb:
2738 case llvm::Triple::arm:
2739 case llvm::Triple::armeb:
2740 if (Equal.first == "-mimplicit-it") {
2741 // Only store the value; the last value set takes effect.
2742 ImplicitIt = Equal.second;
2743 checkArg(true, {"always", "never", "arm", "thumb"});
2744 continue;
2745 }
2746 if (Value == "-mthumb")
2747 // -mthumb has already been processed in ComputeLLVMTriple()
2748 // recognize but skip over here.
2749 continue;
2750 break;
2751 case llvm::Triple::aarch64:
2752 case llvm::Triple::aarch64_be:
2753 case llvm::Triple::aarch64_32:
2754 if (Equal.first == "-mmapsyms") {
2755 ImplicitMapSyms = Equal.second == "implicit";
2756 checkArg(IsELF, {"default", "implicit"});
2757 continue;
2758 }
2759 break;
2760 case llvm::Triple::mips:
2761 case llvm::Triple::mipsel:
2762 case llvm::Triple::mips64:
2763 case llvm::Triple::mips64el:
2764 if (Value == "--trap") {
2765 CmdArgs.push_back(Elt: "-target-feature");
2766 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2767 continue;
2768 }
2769 if (Value == "--break") {
2770 CmdArgs.push_back(Elt: "-target-feature");
2771 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2772 continue;
2773 }
2774 if (Value.starts_with(Prefix: "-msoft-float")) {
2775 CmdArgs.push_back(Elt: "-target-feature");
2776 CmdArgs.push_back(Elt: "+soft-float");
2777 continue;
2778 }
2779 if (Value.starts_with(Prefix: "-mhard-float")) {
2780 CmdArgs.push_back(Elt: "-target-feature");
2781 CmdArgs.push_back(Elt: "-soft-float");
2782 continue;
2783 }
2784 if (Value == "-mmsa") {
2785 Msa = true;
2786 continue;
2787 }
2788 if (Value == "-mno-msa") {
2789 Msa = false;
2790 continue;
2791 }
2792 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2793 .Case(S: "-mips1", Value: "+mips1")
2794 .Case(S: "-mips2", Value: "+mips2")
2795 .Case(S: "-mips3", Value: "+mips3")
2796 .Case(S: "-mips4", Value: "+mips4")
2797 .Case(S: "-mips5", Value: "+mips5")
2798 .Case(S: "-mips32", Value: "+mips32")
2799 .Case(S: "-mips32r2", Value: "+mips32r2")
2800 .Case(S: "-mips32r3", Value: "+mips32r3")
2801 .Case(S: "-mips32r5", Value: "+mips32r5")
2802 .Case(S: "-mips32r6", Value: "+mips32r6")
2803 .Case(S: "-mips64", Value: "+mips64")
2804 .Case(S: "-mips64r2", Value: "+mips64r2")
2805 .Case(S: "-mips64r3", Value: "+mips64r3")
2806 .Case(S: "-mips64r5", Value: "+mips64r5")
2807 .Case(S: "-mips64r6", Value: "+mips64r6")
2808 .Default(Value: nullptr);
2809 if (MipsTargetFeature)
2810 continue;
2811 break;
2812
2813 case llvm::Triple::sparc:
2814 case llvm::Triple::sparcel:
2815 case llvm::Triple::sparcv9:
2816 if (Value == "--undeclared-regs") {
2817 // LLVM already allows undeclared use of G registers, so this option
2818 // becomes a no-op. This solely exists for GNU compatibility.
2819 // TODO implement --no-undeclared-regs
2820 continue;
2821 }
2822 SparcTargetFeatures =
2823 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2824 .Case(S: "-Av8", Value: {"-v8plus"})
2825 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2826 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2827 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2828 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3",
2829 "+ua2005", "+ua2007"})
2830 .Case(S: "-Av9", Value: {"+v9"})
2831 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2832 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2833 .Case(S: "-Av9d",
2834 Value: {"+v9", "+vis", "+vis2", "+vis3", "+ua2005", "+ua2007"})
2835 .Default(Value: {});
2836 if (!SparcTargetFeatures.empty())
2837 continue;
2838 break;
2839 }
2840
2841 if (Value == "-force_cpusubtype_ALL") {
2842 // Do nothing, this is the default and we don't support anything else.
2843 } else if (Value == "-L") {
2844 CmdArgs.push_back(Elt: "-msave-temp-labels");
2845 } else if (Value == "--fatal-warnings") {
2846 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2847 } else if (Value == "--no-warn" || Value == "-W") {
2848 CmdArgs.push_back(Elt: "-massembler-no-warn");
2849 } else if (Value == "--noexecstack") {
2850 UseNoExecStack = true;
2851 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2852 Value.starts_with(Prefix: "--compress-debug-sections") ||
2853 Value == "-nocompress-debug-sections" ||
2854 Value == "--nocompress-debug-sections") {
2855 CmdArgs.push_back(Elt: Value.data());
2856 } else if (Value == "--crel") {
2857 Crel = true;
2858 } else if (Value == "--no-crel") {
2859 Crel = false;
2860 } else if (Value == "--allow-experimental-crel") {
2861 ExperimentalCrel = true;
2862 } else if (Value.starts_with(Prefix: "--reloc-section-sym=")) {
2863 RelocSectionSym = Value.substr(Start: strlen(s: "--reloc-section-sym="));
2864 } else if (Value.starts_with(Prefix: "-I")) {
2865 CmdArgs.push_back(Elt: Value.data());
2866 // We need to consume the next argument if the current arg is a plain
2867 // -I. The next arg will be the include directory.
2868 if (Value == "-I")
2869 TakeNextArg = true;
2870 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2871 // "-gdwarf-N" options are not cc1as options.
2872 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2873 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2874 CmdArgs.push_back(Elt: Value.data());
2875 } else {
2876 RenderDebugEnablingArgs(Args, CmdArgs,
2877 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2878 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2879 }
2880 } else if (Value == "--gsframe") {
2881 SFrame = true;
2882 } else if (Value == "--allow-experimental-sframe") {
2883 ExperimentalSFrame = true;
2884 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2885 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2886 // Do nothing, we'll validate it later.
2887 } else if (Value == "-defsym" || Value == "--defsym") {
2888 if (A->getNumValues() != 2) {
2889 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2890 break;
2891 }
2892 const char *S = A->getValue(N: 1);
2893 auto Pair = StringRef(S).split(Separator: '=');
2894 auto Sym = Pair.first;
2895 auto SVal = Pair.second;
2896
2897 if (Sym.empty() || SVal.empty()) {
2898 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2899 break;
2900 }
2901 int64_t IVal;
2902 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2903 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2904 break;
2905 }
2906 CmdArgs.push_back(Elt: "--defsym");
2907 TakeNextArg = true;
2908 } else if (Value == "-fdebug-compilation-dir") {
2909 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2910 TakeNextArg = true;
2911 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2912 // The flag is a -Wa / -Xassembler argument and Options doesn't
2913 // parse the argument, so this isn't automatically aliased to
2914 // -fdebug-compilation-dir (without '=') here.
2915 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2916 CmdArgs.push_back(Elt: Value.data());
2917 } else if (Value == "--version") {
2918 D.PrintVersion(C, OS&: llvm::outs());
2919 } else {
2920 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2921 << A->getSpelling() << Value;
2922 }
2923 }
2924 }
2925 if (ImplicitIt.size())
2926 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2927 if (Crel) {
2928 if (!ExperimentalCrel)
2929 D.Diag(DiagID: diag::err_drv_experimental_crel);
2930 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2931 CmdArgs.push_back(Elt: "--crel");
2932 } else {
2933 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2934 << "-Wa,--crel" << D.getTargetTriple();
2935 }
2936 }
2937 if (!RelocSectionSym.empty()) {
2938 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2939 RelocSectionSym != "none")
2940 D.Diag(DiagID: diag::err_drv_invalid_value)
2941 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2942 << RelocSectionSym;
2943 else if (Triple.isOSBinFormatELF())
2944 CmdArgs.push_back(
2945 Elt: Args.MakeArgString(Str: "--reloc-section-sym=" + RelocSectionSym));
2946 else
2947 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2948 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2949 }
2950 if (SFrame) {
2951 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2952 if (!ExperimentalSFrame)
2953 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2954 else
2955 CmdArgs.push_back(Elt: "--gsframe");
2956 } else {
2957 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2958 << "-Wa,--gsframe" << D.getTargetTriple();
2959 }
2960 }
2961 if (ImplicitMapSyms)
2962 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2963 if (Msa)
2964 CmdArgs.push_back(Elt: "-mmsa");
2965 if (!UseRelaxRelocations)
2966 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2967 if (UseNoExecStack)
2968 CmdArgs.push_back(Elt: "-mnoexecstack");
2969 if (MipsTargetFeature != nullptr) {
2970 CmdArgs.push_back(Elt: "-target-feature");
2971 CmdArgs.push_back(Elt: MipsTargetFeature);
2972 }
2973
2974 for (const char *Feature : SparcTargetFeatures) {
2975 CmdArgs.push_back(Elt: "-target-feature");
2976 CmdArgs.push_back(Elt: Feature);
2977 }
2978
2979 // forward -fembed-bitcode to assmebler
2980 if (C.getDriver().embedBitcodeEnabled() ||
2981 C.getDriver().embedBitcodeMarkerOnly())
2982 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2983
2984 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2985 CmdArgs.push_back(Elt: "-as-secure-log-file");
2986 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2987 }
2988}
2989
2990static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2991 bool OFastEnabled, const ArgList &Args,
2992 ArgStringList &CmdArgs,
2993 const JobAction &JA) {
2994 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2995 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2996 llvm::StringLiteral("SLEEF")};
2997 bool NoMathErrnoWasImpliedByVecLib = false;
2998 const Arg *VecLibArg = nullptr;
2999 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
3000 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
3001
3002 // Handle various floating point optimization flags, mapping them to the
3003 // appropriate LLVM code generation flags. This is complicated by several
3004 // "umbrella" flags, so we do this by stepping through the flags incrementally
3005 // adjusting what we think is enabled/disabled, then at the end setting the
3006 // LLVM flags based on the final state.
3007 bool HonorINFs = true;
3008 bool HonorNaNs = true;
3009 bool ApproxFunc = false;
3010 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3011 bool MathErrno = TC.IsMathErrnoDefault();
3012 bool AssociativeMath = false;
3013 bool ReciprocalMath = false;
3014 bool SignedZeros = true;
3015 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
3016 bool TrappingMathPresent = false; // Is trapping-math in args, and not
3017 // overriden by ffp-exception-behavior?
3018 bool RoundingFPMath = false;
3019 // -ffp-model values: strict, fast, precise
3020 StringRef FPModel = "";
3021 // -ffp-exception-behavior options: strict, maytrap, ignore
3022 StringRef FPExceptionBehavior = "";
3023 // -ffp-eval-method options: double, extended, source
3024 StringRef FPEvalMethod = "";
3025 llvm::DenormalMode DenormalFPMath =
3026 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
3027 llvm::DenormalMode DenormalFP32Math =
3028 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
3029
3030 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3031 // If one wasn't given by the user, don't pass it here.
3032 StringRef FPContract;
3033 // Explicit contraction options and unsafe math establish a fallback.
3034 // Without one, disabling unsafe math leaves precise/strict models unchanged.
3035 std::optional<StringRef> FPContractFallback;
3036 StringRef LastFpContractOverrideOption;
3037 const bool UseFrontendFPContractDefault =
3038 JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
3039 JA.isOffloading(OKind: Action::OFK_HIP);
3040 if (!UseFrontendFPContractDefault)
3041 FPContract = "on";
3042 bool StrictFPModel = false;
3043 StringRef Float16ExcessPrecision = "";
3044 StringRef BFloat16ExcessPrecision = "";
3045 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
3046 std::string ComplexRangeStr;
3047 StringRef LastComplexRangeOption;
3048
3049 auto enableUnsafeFPContract = [&]() {
3050 FPContract = "fast";
3051 if (!FPContractFallback)
3052 FPContractFallback = "on";
3053 };
3054
3055 // Lambda to set fast-math options. This is also used by -ffp-model=fast
3056 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
3057 if (Aggressive) {
3058 HonorINFs = false;
3059 HonorNaNs = false;
3060 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
3061 LastOpt&: LastComplexRangeOption, Range);
3062 } else {
3063 HonorINFs = true;
3064 HonorNaNs = true;
3065 setComplexRange(D, NewOpt: CallerOption,
3066 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
3067 LastOpt&: LastComplexRangeOption, Range);
3068 }
3069 MathErrno = false;
3070 AssociativeMath = true;
3071 ReciprocalMath = true;
3072 ApproxFunc = true;
3073 SignedZeros = false;
3074 TrappingMath = false;
3075 RoundingFPMath = false;
3076 FPExceptionBehavior = "";
3077 enableUnsafeFPContract();
3078 };
3079
3080 // Lambda to consolidate common handling for fp-contract
3081 auto restoreFPContractState = [&]() {
3082 if (!UseFrontendFPContractDefault && FPContractFallback)
3083 FPContract = *FPContractFallback;
3084 LastFpContractOverrideOption = "";
3085 };
3086
3087 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
3088 CmdArgs.push_back(Elt: "-mlimit-float-precision");
3089 CmdArgs.push_back(Elt: A->getValue());
3090 }
3091
3092 for (const Arg *A : Args) {
3093 llvm::scope_exit CheckMathErrnoForVecLib(
3094 [&, MathErrnoBeforeArg = MathErrno] {
3095 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3096 ArgThatEnabledMathErrnoAfterVecLib = A;
3097 });
3098
3099 switch (A->getOption().getID()) {
3100 // If this isn't an FP option skip the claim below
3101 default: continue;
3102
3103 case options::OPT_fcx_limited_range:
3104 setComplexRange(D, NewOpt: A->getSpelling(),
3105 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
3106 LastOpt&: LastComplexRangeOption, Range);
3107 break;
3108 case options::OPT_fno_cx_limited_range:
3109 setComplexRange(D, NewOpt: A->getSpelling(),
3110 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3111 LastOpt&: LastComplexRangeOption, Range);
3112 break;
3113 case options::OPT_fcx_fortran_rules:
3114 setComplexRange(D, NewOpt: A->getSpelling(),
3115 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
3116 LastOpt&: LastComplexRangeOption, Range);
3117 break;
3118 case options::OPT_fno_cx_fortran_rules:
3119 setComplexRange(D, NewOpt: A->getSpelling(),
3120 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3121 LastOpt&: LastComplexRangeOption, Range);
3122 break;
3123 case options::OPT_fcomplex_arithmetic_EQ: {
3124 LangOptions::ComplexRangeKind RangeVal;
3125 StringRef Val = A->getValue();
3126 if (Val == "full")
3127 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
3128 else if (Val == "improved")
3129 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
3130 else if (Val == "promoted")
3131 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
3132 else if (Val == "basic")
3133 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
3134 else {
3135 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3136 << A->getSpelling() << Val;
3137 break;
3138 }
3139 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
3140 LastOpt&: LastComplexRangeOption, Range);
3141 break;
3142 }
3143 case options::OPT_ffp_model_EQ: {
3144 // If -ffp-model= is seen, reset to fno-fast-math
3145 HonorINFs = true;
3146 HonorNaNs = true;
3147 ApproxFunc = false;
3148 // Turning *off* -ffast-math restores the toolchain default.
3149 MathErrno = TC.IsMathErrnoDefault();
3150 AssociativeMath = false;
3151 ReciprocalMath = false;
3152 SignedZeros = true;
3153
3154 StringRef Val = A->getValue();
3155 if (OFastEnabled && Val != "aggressive") {
3156 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3157 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3158 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
3159 break;
3160 }
3161 StrictFPModel = false;
3162 if (!FPModel.empty() && FPModel != Val)
3163 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3164 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
3165 << Args.MakeArgString(Str: "-ffp-model=" + Val);
3166 if (Val == "fast") {
3167 FPModel = Val;
3168 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
3169 // applyFastMath sets fp-contract="fast"
3170 LastFpContractOverrideOption = "-ffp-model=fast";
3171 } else if (Val == "aggressive") {
3172 FPModel = Val;
3173 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
3174 // applyFastMath sets fp-contract="fast"
3175 LastFpContractOverrideOption = "-ffp-model=aggressive";
3176 } else if (Val == "precise") {
3177 FPModel = Val;
3178 FPContract = "on";
3179 LastFpContractOverrideOption = "-ffp-model=precise";
3180 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3181 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3182 LastOpt&: LastComplexRangeOption, Range);
3183 } else if (Val == "strict") {
3184 StrictFPModel = true;
3185 FPExceptionBehavior = "strict";
3186 FPModel = Val;
3187 FPContract = "off";
3188 LastFpContractOverrideOption = "-ffp-model=strict";
3189 TrappingMath = true;
3190 RoundingFPMath = true;
3191 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3192 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3193 LastOpt&: LastComplexRangeOption, Range);
3194 } else
3195 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3196 << A->getSpelling() << Val;
3197 break;
3198 }
3199
3200 // Options controlling individual features
3201 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3202 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3203 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3204 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3205 case options::OPT_fapprox_func: ApproxFunc = true; break;
3206 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3207 case options::OPT_fmath_errno: MathErrno = true; break;
3208 case options::OPT_fno_math_errno: MathErrno = false; break;
3209 case options::OPT_fassociative_math: AssociativeMath = true; break;
3210 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3211 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3212 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3213 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3214 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3215 case options::OPT_ftrapping_math:
3216 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3217 FPExceptionBehavior != "strict")
3218 // Warn that previous value of option is overridden.
3219 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3220 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3221 FPExceptionBehavior)
3222 << "-ftrapping-math";
3223 TrappingMath = true;
3224 TrappingMathPresent = true;
3225 FPExceptionBehavior = "strict";
3226 break;
3227 case options::OPT_fveclib:
3228 VecLibArg = A;
3229 NoMathErrnoWasImpliedByVecLib =
3230 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
3231 if (NoMathErrnoWasImpliedByVecLib)
3232 MathErrno = false;
3233 break;
3234 case options::OPT_fno_trapping_math:
3235 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3236 FPExceptionBehavior != "ignore")
3237 // Warn that previous value of option is overridden.
3238 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3239 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3240 FPExceptionBehavior)
3241 << "-fno-trapping-math";
3242 TrappingMath = false;
3243 TrappingMathPresent = true;
3244 FPExceptionBehavior = "ignore";
3245 break;
3246
3247 case options::OPT_frounding_math:
3248 RoundingFPMath = true;
3249 break;
3250
3251 case options::OPT_fno_rounding_math:
3252 RoundingFPMath = false;
3253 break;
3254
3255 case options::OPT_fdenormal_fp_math_EQ:
3256 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3257 DenormalFP32Math = DenormalFPMath;
3258 if (!DenormalFPMath.isValid()) {
3259 D.Diag(DiagID: diag::err_drv_invalid_value)
3260 << A->getAsString(Args) << A->getValue();
3261 }
3262 break;
3263
3264 case options::OPT_fdenormal_fp_math_f32_EQ:
3265 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3266 if (!DenormalFP32Math.isValid()) {
3267 D.Diag(DiagID: diag::err_drv_invalid_value)
3268 << A->getAsString(Args) << A->getValue();
3269 }
3270 break;
3271
3272 // Validate and pass through -ffp-contract option.
3273 case options::OPT_ffp_contract: {
3274 StringRef Val = A->getValue();
3275 if (Val == "fast" || Val == "on" || Val == "off" ||
3276 Val == "fast-honor-pragmas") {
3277 if (Val != FPContract && LastFpContractOverrideOption != "") {
3278 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3279 << LastFpContractOverrideOption
3280 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3281 }
3282
3283 FPContract = Val;
3284 FPContractFallback = Val;
3285 LastFpContractOverrideOption = "";
3286 } else
3287 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3288 << A->getSpelling() << Val;
3289 break;
3290 }
3291
3292 // Validate and pass through -ffp-exception-behavior option.
3293 case options::OPT_ffp_exception_behavior_EQ: {
3294 StringRef Val = A->getValue();
3295 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3296 FPExceptionBehavior != Val)
3297 // Warn that previous value of option is overridden.
3298 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3299 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3300 FPExceptionBehavior)
3301 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3302 TrappingMath = TrappingMathPresent = false;
3303 if (Val == "ignore" || Val == "maytrap")
3304 FPExceptionBehavior = Val;
3305 else if (Val == "strict") {
3306 FPExceptionBehavior = Val;
3307 TrappingMath = TrappingMathPresent = true;
3308 } else
3309 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3310 << A->getSpelling() << Val;
3311 break;
3312 }
3313
3314 // Validate and pass through -ffp-eval-method option.
3315 case options::OPT_ffp_eval_method_EQ: {
3316 StringRef Val = A->getValue();
3317 if (Val == "double" || Val == "extended" || Val == "source")
3318 FPEvalMethod = Val;
3319 else
3320 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3321 << A->getSpelling() << Val;
3322 break;
3323 }
3324
3325 case options::OPT_fexcess_precision_EQ: {
3326 StringRef Val = A->getValue();
3327 const llvm::Triple::ArchType Arch = TC.getArch();
3328 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3329 if (Val == "standard" || Val == "fast")
3330 Float16ExcessPrecision = Val;
3331 // To make it GCC compatible, allow the value of "16" which
3332 // means disable excess precision, the same meaning than clang's
3333 // equivalent value "none".
3334 else if (Val == "16")
3335 Float16ExcessPrecision = "none";
3336 else
3337 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3338 << A->getSpelling() << Val;
3339 } else {
3340 if (!(Val == "standard" || Val == "fast"))
3341 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3342 << A->getSpelling() << Val;
3343 }
3344 BFloat16ExcessPrecision = Float16ExcessPrecision;
3345 break;
3346 }
3347 case options::OPT_ffinite_math_only:
3348 HonorINFs = false;
3349 HonorNaNs = false;
3350 break;
3351 case options::OPT_fno_finite_math_only:
3352 HonorINFs = true;
3353 HonorNaNs = true;
3354 break;
3355
3356 case options::OPT_funsafe_math_optimizations:
3357 AssociativeMath = true;
3358 ReciprocalMath = true;
3359 SignedZeros = false;
3360 ApproxFunc = true;
3361 TrappingMath = false;
3362 FPExceptionBehavior = "";
3363 enableUnsafeFPContract();
3364 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3365 break;
3366 case options::OPT_fno_unsafe_math_optimizations:
3367 AssociativeMath = false;
3368 ReciprocalMath = false;
3369 SignedZeros = true;
3370 ApproxFunc = false;
3371 restoreFPContractState();
3372 break;
3373
3374 case options::OPT_cl_fast_relaxed_math:
3375 applyFastMath(true, A->getSpelling());
3376 break;
3377
3378 case options::OPT_Ofast:
3379 // If -Ofast is the optimization level, then -ffast-math should be enabled
3380 if (!OFastEnabled)
3381 continue;
3382 [[fallthrough]];
3383 case options::OPT_ffast_math:
3384 applyFastMath(true, A->getSpelling());
3385 if (A->getOption().getID() == options::OPT_Ofast)
3386 LastFpContractOverrideOption = "-Ofast";
3387 else
3388 LastFpContractOverrideOption = "-ffast-math";
3389 break;
3390 case options::OPT_fno_fast_math:
3391 HonorINFs = true;
3392 HonorNaNs = true;
3393 // Turning on -ffast-math (with either flag) removes the need for
3394 // MathErrno. However, turning *off* -ffast-math merely restores the
3395 // toolchain default (which may be false).
3396 MathErrno = TC.IsMathErrnoDefault();
3397 AssociativeMath = false;
3398 ReciprocalMath = false;
3399 ApproxFunc = false;
3400 SignedZeros = true;
3401 restoreFPContractState();
3402 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3403 setComplexRange(D, NewOpt: A->getSpelling(),
3404 NewRange: LangOptions::ComplexRangeKind::CX_None,
3405 LastOpt&: LastComplexRangeOption, Range);
3406 else
3407 Range = LangOptions::ComplexRangeKind::CX_None;
3408 LastComplexRangeOption = "";
3409 break;
3410 } // End switch (A->getOption().getID())
3411
3412 // The StrictFPModel local variable is needed to report warnings
3413 // in the way we intend. If -ffp-model=strict has been used, we
3414 // want to report a warning for the next option encountered that
3415 // takes us out of the settings described by fp-model=strict, but
3416 // we don't want to continue issuing warnings for other conflicting
3417 // options after that.
3418 if (StrictFPModel) {
3419 // If -ffp-model=strict has been specified on command line but
3420 // subsequent options conflict then emit warning diagnostic.
3421 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3422 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3423 FPContract == "off")
3424 // OK: Current Arg doesn't conflict with -ffp-model=strict
3425 ;
3426 else {
3427 StrictFPModel = false;
3428 FPModel = "";
3429 // The warning for -ffp-contract would have been reported by the
3430 // OPT_ffp_contract_EQ handler above. A special check here is needed
3431 // to avoid duplicating the warning.
3432 auto RHS = (A->getNumValues() == 0)
3433 ? A->getSpelling()
3434 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3435 if (A->getSpelling() != "-ffp-contract=") {
3436 if (RHS != "-ffp-model=strict")
3437 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3438 << "-ffp-model=strict" << RHS;
3439 }
3440 }
3441 }
3442
3443 // If we handled this option claim it
3444 A->claim();
3445 }
3446
3447 if (!HonorINFs)
3448 CmdArgs.push_back(Elt: "-menable-no-infs");
3449
3450 if (!HonorNaNs)
3451 CmdArgs.push_back(Elt: "-menable-no-nans");
3452
3453 if (ApproxFunc)
3454 CmdArgs.push_back(Elt: "-fapprox-func");
3455
3456 if (MathErrno) {
3457 CmdArgs.push_back(Elt: "-fmath-errno");
3458 if (NoMathErrnoWasImpliedByVecLib)
3459 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3460 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3461 << VecLibArg->getAsString(Args);
3462 }
3463
3464 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3465 !TrappingMath)
3466 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3467
3468 if (!SignedZeros)
3469 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3470
3471 if (AssociativeMath && !SignedZeros && !TrappingMath)
3472 CmdArgs.push_back(Elt: "-mreassociate");
3473
3474 if (ReciprocalMath)
3475 CmdArgs.push_back(Elt: "-freciprocal-math");
3476
3477 if (TrappingMath) {
3478 // FP Exception Behavior is also set to strict
3479 assert(FPExceptionBehavior == "strict");
3480 }
3481
3482 // The default is IEEE.
3483 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3484 llvm::SmallString<64> DenormFlag;
3485 llvm::raw_svector_ostream ArgStr(DenormFlag);
3486 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3487 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3488 }
3489
3490 // Add f32 specific denormal mode flag if it's different.
3491 if (DenormalFP32Math != DenormalFPMath) {
3492 llvm::SmallString<64> DenormFlag;
3493 llvm::raw_svector_ostream ArgStr(DenormFlag);
3494 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3495 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3496 }
3497
3498 if (!FPContract.empty())
3499 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3500
3501 if (RoundingFPMath)
3502 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3503 else
3504 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3505
3506 if (!FPExceptionBehavior.empty())
3507 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3508 FPExceptionBehavior));
3509
3510 if (!FPEvalMethod.empty())
3511 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3512
3513 if (!Float16ExcessPrecision.empty())
3514 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3515 Float16ExcessPrecision));
3516 if (!BFloat16ExcessPrecision.empty())
3517 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3518 BFloat16ExcessPrecision));
3519
3520 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3521 if (!Recip.empty())
3522 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3523
3524 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3525 // individual features enabled by -ffast-math instead of the option itself as
3526 // that's consistent with gcc's behaviour.
3527 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3528 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3529 CmdArgs.push_back(Elt: "-ffast-math");
3530
3531 // Handle __FINITE_MATH_ONLY__ similarly.
3532 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3533 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3534 // -menable-no-nans are set by the user.
3535 bool shouldAddFiniteMathOnly = false;
3536 if (!HonorINFs && !HonorNaNs) {
3537 shouldAddFiniteMathOnly = true;
3538 } else {
3539 bool InfValues = true;
3540 bool NanValues = true;
3541 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3542 StringRef ArgValue = Arg->getValue();
3543 if (ArgValue == "-menable-no-nans")
3544 NanValues = false;
3545 else if (ArgValue == "-menable-no-infs")
3546 InfValues = false;
3547 }
3548 if (!NanValues && !InfValues)
3549 shouldAddFiniteMathOnly = true;
3550 }
3551 if (shouldAddFiniteMathOnly) {
3552 CmdArgs.push_back(Elt: "-ffinite-math-only");
3553 }
3554 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3555 CmdArgs.push_back(Elt: "-mfpmath");
3556 CmdArgs.push_back(Elt: A->getValue());
3557 }
3558
3559 // Disable a codegen optimization for floating-point casts.
3560 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3561 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3562 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3563
3564 if (Range != LangOptions::ComplexRangeKind::CX_None)
3565 ComplexRangeStr = renderComplexRangeOption(Range);
3566 if (!ComplexRangeStr.empty()) {
3567 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3568 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3569 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3570 complexRangeKindToStr(Range)));
3571 }
3572 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3573 CmdArgs.push_back(Elt: "-fcx-limited-range");
3574 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3575 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3576 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3577 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3578 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3579 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3580}
3581
3582static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3583 const llvm::Triple &Triple,
3584 const InputInfo &Input) {
3585 // Add default argument set.
3586 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3587 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3588 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3589
3590 if (!Triple.isWindowsMSVCEnvironment()) {
3591 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3592 } else {
3593 // Enable "unix" checkers that also work on Windows.
3594 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3595 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3596 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3597 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3598 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3599 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3600 }
3601
3602 // Disable some unix checkers for PS4/PS5.
3603 if (Triple.isPS()) {
3604 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3605 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3606 }
3607
3608 if (Triple.isOSDarwin()) {
3609 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3610 CmdArgs.push_back(
3611 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3612 }
3613 else if (Triple.isOSFuchsia())
3614 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3615
3616 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3617
3618 if (types::isCXX(Id: Input.getType()))
3619 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3620
3621 if (!Triple.isPS()) {
3622 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3623 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3624 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3625 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3626 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3627 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3628 }
3629
3630 // Default nullability checks.
3631 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3632 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3633 }
3634
3635 // Set the output format. The default is plist, for (lame) historical reasons.
3636 CmdArgs.push_back(Elt: "-analyzer-output");
3637 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3638 CmdArgs.push_back(Elt: A->getValue());
3639 else
3640 CmdArgs.push_back(Elt: "plist");
3641
3642 // Disable the presentation of standard compiler warnings when using
3643 // --analyze. We only want to show static analyzer diagnostics or frontend
3644 // errors.
3645 CmdArgs.push_back(Elt: "-w");
3646
3647 // Add -Xanalyzer arguments when running as analyzer.
3648 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3649}
3650
3651static bool isValidSymbolName(StringRef S) {
3652 if (S.empty())
3653 return false;
3654
3655 if (std::isdigit(S[0]))
3656 return false;
3657
3658 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3659}
3660
3661static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3662 const ArgList &Args, ArgStringList &CmdArgs,
3663 bool KernelOrKext) {
3664 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3665
3666 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3667 // doesn't even have a stack!
3668 if (EffectiveTriple.isNVPTX())
3669 return;
3670
3671 // -stack-protector=0 is default.
3672 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3673 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3674 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3675
3676 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3677 Ids: options::OPT_fstack_protector_all,
3678 Ids: options::OPT_fstack_protector_strong,
3679 Ids: options::OPT_fstack_protector)) {
3680 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3681 StackProtectorLevel =
3682 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3683 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3684 StackProtectorLevel = LangOptions::SSPStrong;
3685 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3686 StackProtectorLevel = LangOptions::SSPReq;
3687
3688 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3689 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3690 << A->getSpelling() << EffectiveTriple.getTriple();
3691 StackProtectorLevel = DefaultStackProtectorLevel;
3692 }
3693 } else {
3694 StackProtectorLevel = DefaultStackProtectorLevel;
3695 }
3696
3697 if (StackProtectorLevel) {
3698 CmdArgs.push_back(Elt: "-stack-protector");
3699 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3700 }
3701
3702 // --param ssp-buffer-size=
3703 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3704 StringRef Str(A->getValue());
3705 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3706 if (StackProtectorLevel) {
3707 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3708 // FIXME: Verify the argument is a valid integer.
3709 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3710 }
3711 A->claim();
3712 }
3713 }
3714
3715 const std::string &TripleStr = EffectiveTriple.getTriple();
3716 StringRef GuardValue;
3717 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3718 GuardValue = A->getValue();
3719 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3720 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3721 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3722 !EffectiveTriple.isSystemZ())
3723 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3724 << A->getAsString(Args) << TripleStr;
3725 // z/OS only supports the tls mode.
3726 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3727 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3728 << A->getOption().getName() << GuardValue << "tls";
3729 return;
3730 }
3731 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3732 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3733 GuardValue != "tls" && GuardValue != "global") {
3734 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3735 << A->getOption().getName() << GuardValue << "tls global";
3736 return;
3737 }
3738 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3739 GuardValue == "tls") {
3740 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3741 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3742 << A->getAsString(Args);
3743 return;
3744 }
3745 // Check whether the target subarch supports the hardware TLS register
3746 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3747 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3748 << EffectiveTriple.getArchName();
3749 return;
3750 }
3751 // Check whether the user asked for something other than -mtp=cp15
3752 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3753 StringRef Value = A->getValue();
3754 if (Value != "cp15") {
3755 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3756 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3757 return;
3758 }
3759 }
3760 CmdArgs.push_back(Elt: "-target-feature");
3761 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3762 }
3763 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3764 GuardValue != "global") {
3765 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3766 << A->getOption().getName() << GuardValue << "sysreg global";
3767 return;
3768 }
3769 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3770 if (GuardValue != "tls" && GuardValue != "global") {
3771 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3772 << A->getOption().getName() << GuardValue << "tls global";
3773 return;
3774 }
3775 if (GuardValue == "tls") {
3776 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3777 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3778 << A->getAsString(Args);
3779 return;
3780 }
3781 }
3782 }
3783 A->render(Args, Output&: CmdArgs);
3784 }
3785
3786 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3787 StringRef Value = A->getValue();
3788 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3789 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3790 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3791 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3792 << A->getAsString(Args) << TripleStr;
3793 int Offset;
3794 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3795 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3796 return;
3797 }
3798 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3799 (Offset < 0 || Offset > 0xfffff)) {
3800 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3801 << A->getOption().getName() << Value;
3802 return;
3803 }
3804 A->render(Args, Output&: CmdArgs);
3805 }
3806
3807 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3808 StringRef Value = A->getValue();
3809 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3810 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3811 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3812 << A->getAsString(Args) << TripleStr;
3813 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3814 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3815 << A->getOption().getName() << Value << "fs gs";
3816 return;
3817 }
3818 if (EffectiveTriple.isAArch64() &&
3819 llvm::StringSwitch<bool>(Value)
3820 .Cases(CaseStrings: {"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3821 "tpidr_el2", "far_el1", "far_el2"},
3822 Value: false)
3823 .Default(Value: true)) {
3824 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3825 << A->getOption().getName() << Value
3826 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3827 return;
3828 }
3829 if (EffectiveTriple.isRISCV() && Value != "tp") {
3830 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3831 << A->getOption().getName() << Value << "tp";
3832 return;
3833 }
3834 if (EffectiveTriple.isPPC64() && Value != "r13") {
3835 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3836 << A->getOption().getName() << Value << "r13";
3837 return;
3838 }
3839 if (EffectiveTriple.isPPC32() && Value != "r2") {
3840 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3841 << A->getOption().getName() << Value << "r2";
3842 return;
3843 }
3844 A->render(Args, Output&: CmdArgs);
3845 }
3846
3847 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3848 StringRef Value = A->getValue();
3849 if (!isValidSymbolName(S: Value)) {
3850 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3851 << A->getOption().getName() << "legal symbol name";
3852 return;
3853 }
3854 A->render(Args, Output&: CmdArgs);
3855 }
3856
3857 if (Arg *A =
3858 Args.getLastArg(Ids: options::OPT_mstack_protector_guard_value_width_EQ)) {
3859 if (!EffectiveTriple.isAArch64())
3860 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3861 << A->getAsString(Args) << TripleStr;
3862 StringRef Value = A->getValue();
3863 unsigned Width;
3864 if (Value.getAsInteger(Radix: 10, Result&: Width)) {
3865 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3866 return;
3867 }
3868 if (Width != 4 && Width != 8) {
3869 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3870 << A->getOption().getName() << Value;
3871 }
3872 }
3873 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstackprotector_guard_record)) {
3874 if (!EffectiveTriple.isSystemZ()) {
3875 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3876 << A->getAsString(Args) << TripleStr;
3877 return;
3878 }
3879 if (GuardValue != "global") {
3880 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3881 << "-mstack-protector-guard-record"
3882 << "-mstack-protector-guard=global";
3883 return;
3884 }
3885 A->render(Args, Output&: CmdArgs);
3886 }
3887}
3888
3889static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3890 ArgStringList &CmdArgs) {
3891 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3892
3893 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3894 !EffectiveTriple.isOSFuchsia())
3895 return;
3896
3897 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3898 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3899 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3900 return;
3901
3902 if (Args.hasFlag(Pos: options::OPT_fstack_clash_protection,
3903 Neg: options::OPT_fno_stack_clash_protection,
3904 Default: EffectiveTriple.isAndroid()))
3905 CmdArgs.push_back(Elt: "-fstack-clash-protection");
3906}
3907
3908static void RenderTrivialAutoVarInitOptions(const Driver &D,
3909 const ToolChain &TC,
3910 const ArgList &Args,
3911 ArgStringList &CmdArgs) {
3912 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3913 StringRef TrivialAutoVarInit = "";
3914
3915 for (const Arg *A : Args) {
3916 switch (A->getOption().getID()) {
3917 default:
3918 continue;
3919 case options::OPT_ftrivial_auto_var_init: {
3920 A->claim();
3921 StringRef Val = A->getValue();
3922 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3923 TrivialAutoVarInit = Val;
3924 else
3925 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3926 << A->getSpelling() << Val;
3927 break;
3928 }
3929 }
3930 }
3931
3932 if (TrivialAutoVarInit.empty())
3933 switch (DefaultTrivialAutoVarInit) {
3934 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3935 break;
3936 case LangOptions::TrivialAutoVarInitKind::Pattern:
3937 TrivialAutoVarInit = "pattern";
3938 break;
3939 case LangOptions::TrivialAutoVarInitKind::Zero:
3940 TrivialAutoVarInit = "zero";
3941 break;
3942 }
3943
3944 if (!TrivialAutoVarInit.empty()) {
3945 CmdArgs.push_back(
3946 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3947 }
3948
3949 if (Arg *A =
3950 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3951 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3952 StringRef(
3953 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3954 "uninitialized")
3955 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3956 A->claim();
3957 StringRef Val = A->getValue();
3958 if (std::stoi(str: Val.str()) <= 0)
3959 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3960 CmdArgs.push_back(
3961 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3962 }
3963
3964 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3965 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3966 StringRef(
3967 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3968 "uninitialized")
3969 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3970 A->claim();
3971 StringRef Val = A->getValue();
3972 if (std::stoi(str: Val.str()) <= 0)
3973 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3974 CmdArgs.push_back(
3975 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3976 }
3977}
3978
3979static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3980 types::ID InputType) {
3981 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3982 // for denormal flushing handling based on the target.
3983 const unsigned ForwardedArguments[] = {
3984 options::OPT_cl_opt_disable,
3985 options::OPT_cl_strict_aliasing,
3986 options::OPT_cl_single_precision_constant,
3987 options::OPT_cl_finite_math_only,
3988 options::OPT_cl_kernel_arg_info,
3989 options::OPT_cl_unsafe_math_optimizations,
3990 options::OPT_cl_fast_relaxed_math,
3991 options::OPT_cl_mad_enable,
3992 options::OPT_cl_no_signed_zeros,
3993 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3994 options::OPT_cl_uniform_work_group_size
3995 };
3996
3997 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3998 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3999 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
4000 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
4001 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
4002 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
4003 }
4004
4005 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
4006 CmdArgs.push_back(Elt: "-menable-no-infs");
4007 CmdArgs.push_back(Elt: "-menable-no-nans");
4008 }
4009
4010 for (const auto &Arg : ForwardedArguments)
4011 if (const auto *A = Args.getLastArg(Ids: Arg))
4012 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
4013
4014 // Only add the default headers if we are compiling OpenCL sources.
4015 if ((types::isOpenCL(Id: InputType) ||
4016 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
4017 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
4018 CmdArgs.push_back(Elt: "-finclude-default-header");
4019 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
4020 }
4021}
4022
4023static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
4024 ArgStringList &CmdArgs, types::ID InputType) {
4025 const unsigned ForwardedArguments[] = {
4026 options::OPT_hlsl_all_resources_bound,
4027 options::OPT_dxil_validator_version,
4028 options::OPT_res_may_alias,
4029 options::OPT_D,
4030 options::OPT_I,
4031 options::OPT_O,
4032 options::OPT_emit_llvm,
4033 options::OPT_emit_obj,
4034 options::OPT_disable_llvm_passes,
4035 options::OPT_fnative_half_type,
4036 options::OPT_fnative_int16_type,
4037 options::OPT_fmatrix_memory_layout_EQ,
4038 options::OPT_hlsl_entrypoint,
4039 options::OPT_fdx_rootsignature_define,
4040 options::OPT_fdx_rootsignature_version,
4041 options::OPT_fdx_semantic_signature_packing_mode_EQ,
4042 options::OPT_fhlsl_spv_use_unknown_image_format,
4043 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
4044 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
4045 options::OPT_fhlsl_spv_preserve_interface,
4046 options::OPT_fhlsl_spv_support_nonzero_base_instance};
4047 if (!types::isHLSL(Id: InputType))
4048 return;
4049 for (const auto &Arg : ForwardedArguments)
4050 if (const auto *A = Args.getLastArg(Ids: Arg))
4051 A->renderAsInput(Args, Output&: CmdArgs);
4052 // Add the default headers if dxc_no_stdinc is not set.
4053 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
4054 !Args.hasArg(Ids: options::OPT_nostdinc))
4055 CmdArgs.push_back(Elt: "-finclude-default-header");
4056
4057 if (Args.hasArg(Ids: options::OPT_dxc_Zss)) {
4058 if (Args.hasArg(Ids: options::OPT_dxc_Zsb))
4059 D.Diag(DiagID: diag::err_drv_dxc_invalid_shader_hash);
4060 CmdArgs.push_back(Elt: "-mllvm");
4061 CmdArgs.push_back(Elt: "-dx-Zss");
4062 }
4063 if (Arg *A = Args.getLastArg(Ids: options::OPT_dxc_Zsb))
4064 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
4065 if (Args.hasArg(Ids: options::OPT_dxc_source_in_debug_module)) {
4066 CmdArgs.push_back(Elt: "-mllvm");
4067 CmdArgs.push_back(Elt: "--dx-source-in-debug-module");
4068 }
4069 if (Args.hasArg(Ids: options::OPT_dxc_Qstrip_debug)) {
4070 CmdArgs.push_back(Elt: "-mllvm");
4071 CmdArgs.push_back(Elt: "--dx-strip-debug");
4072 }
4073 if (Args.hasArg(Ids: options::OPT_dxc_Qpdb_in_private)) {
4074 CmdArgs.push_back(Elt: "-mllvm");
4075 CmdArgs.push_back(Elt: "--dx-pdb-in-private");
4076 }
4077 CmdArgs.push_back(Elt: "-load-bool-from-mem=nonzero");
4078}
4079
4080static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4081 ArgStringList &CmdArgs, types::ID InputType) {
4082 if (!Args.hasArg(Ids: options::OPT_fopenacc))
4083 return;
4084
4085 CmdArgs.push_back(Elt: "-fopenacc");
4086}
4087
4088static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4089 const ArgList &Args, ArgStringList &CmdArgs) {
4090 // -fbuiltin is default unless -mkernel is used.
4091 bool UseBuiltins =
4092 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
4093 Default: !Args.hasArg(Ids: options::OPT_mkernel));
4094 if (!UseBuiltins)
4095 CmdArgs.push_back(Elt: "-fno-builtin");
4096
4097 // -ffreestanding implies -fno-builtin.
4098 if (Args.hasArg(Ids: options::OPT_ffreestanding))
4099 UseBuiltins = false;
4100
4101 // Process the -fno-builtin-* options.
4102 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
4103 A->claim();
4104
4105 // If -fno-builtin is specified, then there's no need to pass the option to
4106 // the frontend.
4107 if (UseBuiltins)
4108 A->render(Args, Output&: CmdArgs);
4109 }
4110}
4111
4112bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
4113 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
4114 Twine Path{Str};
4115 Path.toVector(Out&: Result);
4116 return Path.getSingleStringRef() != "";
4117 }
4118 if (llvm::sys::path::cache_directory(result&: Result)) {
4119 llvm::sys::path::append(path&: Result, a: "clang");
4120 llvm::sys::path::append(path&: Result, a: "ModuleCache");
4121 return true;
4122 }
4123 return false;
4124}
4125
4126llvm::SmallString<256>
4127clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
4128 const char *BaseInput) {
4129 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
4130 return StringRef(ModuleOutputEQ->getValue());
4131
4132 SmallString<256> OutputPath;
4133 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
4134 FinalOutput && Args.hasArg(Ids: options::OPT_c))
4135 OutputPath = FinalOutput->getValue();
4136 else {
4137 llvm::sys::fs::current_path(result&: OutputPath);
4138 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
4139 }
4140
4141 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
4142 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
4143 return OutputPath;
4144}
4145
4146static bool RenderModulesOptions(Compilation &C, const Driver &D,
4147 const ArgList &Args, const InputInfo &Input,
4148 const InputInfo &Output, bool HaveStd20,
4149 ArgStringList &CmdArgs) {
4150 const bool IsCXX = types::isCXX(Id: Input.getType());
4151 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4152 bool HaveModules = HaveStdCXXModules;
4153
4154 // -fmodules enables the use of precompiled modules (off by default).
4155 // Users can pass -fno-cxx-modules to turn off modules support for
4156 // C++/Objective-C++ programs.
4157 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
4158 Neg: options::OPT_fno_cxx_modules, Default: true);
4159 bool HaveClangModules = false;
4160 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
4161 if (AllowedInCXX || !IsCXX) {
4162 CmdArgs.push_back(Elt: "-fmodules");
4163 HaveClangModules = true;
4164 }
4165 }
4166
4167 HaveModules |= HaveClangModules;
4168
4169 if (HaveModules && !AllowedInCXX)
4170 CmdArgs.push_back(Elt: "-fno-cxx-modules");
4171
4172 // -fmodule-maps enables implicit reading of module map files. By default,
4173 // this is enabled if we are using Clang's flavor of precompiled modules.
4174 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
4175 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
4176 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
4177
4178 // -fmodules-decluse checks that modules used are declared so (off by default)
4179 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
4180 Neg: options::OPT_fno_modules_decluse);
4181
4182 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4183 // all #included headers are part of modules.
4184 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
4185 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
4186 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
4187
4188 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
4189 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
4190
4191 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4192 bool ImplicitModules = false;
4193 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
4194 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
4195 if (HaveModules)
4196 CmdArgs.push_back(Elt: "-fno-implicit-modules");
4197 } else if (HaveModules) {
4198 ImplicitModules = true;
4199 // -fmodule-cache-path specifies where our implicitly-built module files
4200 // should be written.
4201 SmallString<128> Path;
4202 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
4203 Path = A->getValue();
4204
4205 bool HasPath = true;
4206 if (C.isForDiagnostics()) {
4207 // When generating crash reports, we want to emit the modules along with
4208 // the reproduction sources, so we ignore any provided module path.
4209 Path = Output.getFilename();
4210 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
4211 llvm::sys::path::append(path&: Path, a: "modules");
4212 } else if (Path.empty()) {
4213 // No module path was provided: use the default.
4214 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
4215 }
4216
4217 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4218 // That being said, that failure is unlikely and not caching is harmless.
4219 if (HasPath) {
4220 const char Arg[] = "-fmodules-cache-path=";
4221 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
4222 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
4223 }
4224
4225 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fimplicit_modules_lock_timeout_EQ);
4226 }
4227
4228 if (HaveModules) {
4229 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
4230 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
4231 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
4232 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
4233 Neg: options::OPT_fno_modules_validate_input_files_content,
4234 Default: false))
4235 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
4236 }
4237
4238 // -fmodule-name specifies the module that is currently being built (or
4239 // used for header checking by -fmodule-maps).
4240 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
4241
4242 // -fmodule-map-file can be used to specify files containing module
4243 // definitions.
4244 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
4245
4246 // -fbuiltin-module-map can be used to load the clang
4247 // builtin headers modulemap file.
4248 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
4249 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4250 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
4251 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
4252 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
4253 CmdArgs.push_back(
4254 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
4255 }
4256
4257 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4258 // names to precompiled module files (the module is loaded only if used).
4259 // The -fmodule-file=<file> form can be used to unconditionally load
4260 // precompiled module files (whether used or not).
4261 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4262 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
4263
4264 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4265 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
4266 CmdArgs.push_back(Elt: Args.MakeArgString(
4267 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
4268 A->claim();
4269 }
4270 } else
4271 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
4272
4273 // When building modules and generating crashdumps, we need to dump a module
4274 // dependency VFS alongside the output.
4275 if (HaveClangModules && C.isForDiagnostics()) {
4276 SmallString<128> VFSDir(Output.getFilename());
4277 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
4278 // Add the cache directory as a temp so the crash diagnostics pick it up.
4279 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
4280
4281 llvm::sys::path::append(path&: VFSDir, a: "vfs");
4282 CmdArgs.push_back(Elt: "-module-dependency-dir");
4283 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
4284 }
4285
4286 if (HaveClangModules)
4287 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
4288
4289 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
4290 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_search_path);
4291 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
4292 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
4293
4294 if (HaveClangModules) {
4295 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
4296
4297 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
4298 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
4299 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
4300 << A->getAsString(Args) << "-fbuild-session-timestamp";
4301
4302 llvm::sys::fs::file_status Status;
4303 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
4304 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
4305 CmdArgs.push_back(Elt: Args.MakeArgString(
4306 Str: "-fbuild-session-timestamp=" +
4307 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4308 d: Status.getLastModificationTime().time_since_epoch())
4309 .count())));
4310 }
4311
4312 if (Args.getLastArg(
4313 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4314 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4315 Ids: options::OPT_fbuild_session_file))
4316 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4317
4318 Args.AddLastArg(Output&: CmdArgs,
4319 Ids: options::OPT_fmodules_validate_once_per_build_session);
4320 }
4321
4322 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4323 Neg: options::OPT_fno_modules_validate_system_headers,
4324 Default: ImplicitModules))
4325 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4326
4327 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_directory_dependencies,
4328 Neg: options::OPT_fno_modules_validate_directory_dependencies,
4329 Default: false))
4330 CmdArgs.push_back(Elt: "-fmodules-validate-directory-dependencies");
4331
4332 Args.AddLastArg(Output&: CmdArgs,
4333 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4334 } else {
4335 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4336 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4337 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4338 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4339 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4340 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_directory_dependencies);
4341 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_directory_dependencies);
4342 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4343 }
4344
4345 // FIXME: We provisionally don't check ODR violations for decls in the global
4346 // module fragment.
4347 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4348
4349 if (Input.getType() == driver::types::TY_CXXModule ||
4350 Input.getType() == driver::types::TY_PP_CXXModule) {
4351 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4352 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4353
4354 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4355 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4356 else if (!(Args.hasArg(Ids: options::OPT__precompile) ||
4357 Args.hasArg(Ids: options::OPT__precompile_reduced_bmi)) ||
4358 Args.hasArg(Ids: options::OPT_fmodule_output))
4359 // If --precompile is specified, we will always generate a module file if
4360 // we're compiling an importable module unit. This is fine even if the
4361 // compilation process won't reach the point of generating the module file
4362 // (e.g., in the preprocessing mode), since the attached flag
4363 // '-fmodule-output' is useless.
4364 //
4365 // But if '--precompile' is specified, it might be annoying to always
4366 // generate the module file as '--precompile' will generate the module
4367 // file anyway.
4368 CmdArgs.push_back(Elt: Args.MakeArgString(
4369 Str: "-fmodule-output=" +
4370 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4371 }
4372
4373 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4374 Args.hasArg(Ids: options::OPT__precompile) &&
4375 (!Args.hasArg(Ids: options::OPT_o) ||
4376 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4377 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4378 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4379 }
4380
4381 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4382 // other translation units than module units. This is more user friendly to
4383 // allow end uers to enable this feature without asking for help from build
4384 // systems.
4385 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4386 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4387
4388 // We need to include the case the input file is a module file here.
4389 // Since the default compilation model for C++ module interface unit will
4390 // create temporary module file and compile the temporary module file
4391 // to get the object file. Then the `-fmodule-output` flag will be
4392 // brought to the second compilation process. So we have to claim it for
4393 // the case too.
4394 if (Input.getType() == driver::types::TY_CXXModule ||
4395 Input.getType() == driver::types::TY_PP_CXXModule ||
4396 Input.getType() == driver::types::TY_ModuleFile) {
4397 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4398 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4399 }
4400
4401 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4402 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4403
4404 return HaveModules;
4405}
4406
4407static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4408 ArgStringList &CmdArgs) {
4409 // -fsigned-char is default.
4410 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4411 Ids: options::OPT_fno_signed_char,
4412 Ids: options::OPT_funsigned_char,
4413 Ids: options::OPT_fno_unsigned_char)) {
4414 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4415 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4416 CmdArgs.push_back(Elt: "-fno-signed-char");
4417 }
4418 } else if (!isSignedCharDefault(Triple: T)) {
4419 CmdArgs.push_back(Elt: "-fno-signed-char");
4420 }
4421
4422 // The default depends on the language standard.
4423 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4424
4425 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4426 Ids: options::OPT_fno_short_wchar)) {
4427 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4428 CmdArgs.push_back(Elt: "-fwchar-type=short");
4429 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4430 } else {
4431 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4432 CmdArgs.push_back(Elt: "-fwchar-type=int");
4433 if (T.isOSzOS() ||
4434 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4435 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4436 else
4437 CmdArgs.push_back(Elt: "-fsigned-wchar");
4438 }
4439 } else if (T.isOSzOS())
4440 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4441}
4442
4443static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4444 const llvm::Triple &T, const ArgList &Args,
4445 ObjCRuntime &Runtime, bool InferCovariantReturns,
4446 const InputInfo &Input, ArgStringList &CmdArgs) {
4447 const llvm::Triple::ArchType Arch = TC.getArch();
4448
4449 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4450 // is the default. Except for deployment target of 10.5, next runtime is
4451 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4452 if (Runtime.isNonFragile()) {
4453 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4454 Neg: options::OPT_fno_objc_legacy_dispatch,
4455 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4456 if (TC.UseObjCMixedDispatch())
4457 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4458 else
4459 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4460 }
4461 }
4462
4463 // Forward -fobjc-direct-precondition-thunk to cc1
4464 // Defaults to false and needs explict turn on for now
4465 // TODO: switch to default true and needs explict turn off in the future.
4466 // TODO: add support for other runtimes
4467 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4468 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4469 if (Runtime.isNeXTFamily()) {
4470 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4471 } else {
4472 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4473 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4474 }
4475 }
4476
4477 if (types::isObjC(Id: Input.getType())) {
4478 // Pass down -fobjc-msgsend-selector-stubs if present.
4479 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_selector_stubs,
4480 Neg: options::OPT_fno_objc_msgsend_selector_stubs, Default: false))
4481 CmdArgs.push_back(Elt: "-fobjc-msgsend-selector-stubs");
4482
4483 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4484 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_class_selector_stubs,
4485 Neg: options::OPT_fno_objc_msgsend_class_selector_stubs, Default: false))
4486 CmdArgs.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
4487 }
4488
4489 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4490 // to do Array/Dictionary subscripting by default.
4491 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4492 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4493 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4494
4495 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4496 // NOTE: This logic is duplicated in ToolChains.cpp.
4497 if (isObjCAutoRefCount(Args)) {
4498 TC.CheckObjCARC();
4499
4500 CmdArgs.push_back(Elt: "-fobjc-arc");
4501
4502 // FIXME: It seems like this entire block, and several around it should be
4503 // wrapped in isObjC, but for now we just use it here as this is where it
4504 // was being used previously.
4505 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4506 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4507 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4508 else
4509 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4510 }
4511
4512 // Allow the user to enable full exceptions code emission.
4513 // We default off for Objective-C, on for Objective-C++.
4514 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4515 Neg: options::OPT_fno_objc_arc_exceptions,
4516 /*Default=*/types::isCXX(Id: Input.getType())))
4517 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4518 }
4519
4520 // Silence warning for full exception code emission options when explicitly
4521 // set to use no ARC.
4522 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4523 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4524 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4525 }
4526
4527 // Allow the user to control whether messages can be converted to runtime
4528 // functions.
4529 if (types::isObjC(Id: Input.getType())) {
4530 auto *Arg = Args.getLastArg(
4531 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4532 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4533 if (Arg &&
4534 Arg->getOption().matches(
4535 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4536 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4537 }
4538
4539 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4540 // rewriter.
4541 if (InferCovariantReturns)
4542 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4543
4544 // Pass down -fobjc-weak or -fno-objc-weak if present.
4545 if (types::isObjC(Id: Input.getType())) {
4546 auto WeakArg =
4547 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4548 if (!WeakArg) {
4549 // nothing to do
4550 } else if (!Runtime.allowsWeak()) {
4551 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4552 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4553 } else {
4554 WeakArg->render(Args, Output&: CmdArgs);
4555 }
4556 }
4557
4558 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4559 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4560
4561 // Forward constant literal flags to cc1.
4562 if (types::isObjC(Id: Input.getType())) {
4563 bool EnableConstantLiterals =
4564 Args.hasFlag(Pos: options::OPT_fobjc_constant_literals,
4565 Neg: options::OPT_fno_objc_constant_literals,
4566 /*default=*/Default: true) &&
4567 Runtime.hasConstantLiteralClasses();
4568 if (EnableConstantLiterals)
4569 CmdArgs.push_back(Elt: "-fobjc-constant-literals");
4570 if (Args.hasFlag(Pos: options::OPT_fconstant_nsnumber_literals,
4571 Neg: options::OPT_fno_constant_nsnumber_literals,
4572 /*default=*/Default: true) &&
4573 EnableConstantLiterals)
4574 CmdArgs.push_back(Elt: "-fconstant-nsnumber-literals");
4575 if (Args.hasFlag(Pos: options::OPT_fconstant_nsarray_literals,
4576 Neg: options::OPT_fno_constant_nsarray_literals,
4577 /*default=*/Default: true) &&
4578 EnableConstantLiterals)
4579 CmdArgs.push_back(Elt: "-fconstant-nsarray-literals");
4580 if (Args.hasFlag(Pos: options::OPT_fconstant_nsdictionary_literals,
4581 Neg: options::OPT_fno_constant_nsdictionary_literals,
4582 /*default=*/Default: true) &&
4583 EnableConstantLiterals)
4584 CmdArgs.push_back(Elt: "-fconstant-nsdictionary-literals");
4585 }
4586}
4587
4588static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4589 ArgStringList &CmdArgs) {
4590 bool CaretDefault = true;
4591 bool ColumnDefault = true;
4592
4593 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4594 Ids: options::OPT__SLASH_diagnostics_column,
4595 Ids: options::OPT__SLASH_diagnostics_caret)) {
4596 switch (A->getOption().getID()) {
4597 case options::OPT__SLASH_diagnostics_caret:
4598 CaretDefault = true;
4599 ColumnDefault = true;
4600 break;
4601 case options::OPT__SLASH_diagnostics_column:
4602 CaretDefault = false;
4603 ColumnDefault = true;
4604 break;
4605 case options::OPT__SLASH_diagnostics_classic:
4606 CaretDefault = false;
4607 ColumnDefault = false;
4608 break;
4609 }
4610 }
4611
4612 // -fcaret-diagnostics is default.
4613 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4614 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4615 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4616
4617 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4618 Neg: options::OPT_fno_diagnostics_fixit_info);
4619 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4620 Neg: options::OPT_fno_diagnostics_show_option);
4621
4622 if (const Arg *A =
4623 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4624 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4625 CmdArgs.push_back(Elt: A->getValue());
4626 }
4627
4628 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4629 Neg: options::OPT_fno_diagnostics_show_hotness);
4630
4631 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_safety_c,
4632 Neg: options::OPT_fno_lifetime_safety_c);
4633
4634 if (const Arg *A =
4635 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4636 std::string Opt =
4637 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4638 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4639 }
4640
4641 if (const Arg *A =
4642 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4643 std::string Opt =
4644 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4645 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4646 }
4647
4648 if (const Arg *A =
4649 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_inlining_chain,
4650 Ids: options::OPT_fno_diagnostics_show_inlining_chain)) {
4651 if (A->getOption().matches(ID: options::OPT_fdiagnostics_show_inlining_chain))
4652 CmdArgs.push_back(Elt: "-fdiagnostics-show-inlining-chain");
4653 else
4654 CmdArgs.push_back(Elt: "-fno-diagnostics-show-inlining-chain");
4655 }
4656
4657 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4658 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4659 CmdArgs.push_back(Elt: A->getValue());
4660 if (StringRef(A->getValue()) == "sarif" ||
4661 StringRef(A->getValue()) == "SARIF")
4662 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4663 }
4664
4665 if (const Arg *A = Args.getLastArg(
4666 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4667 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4668 const Option &O = A->getOption();
4669 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4670 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4671 else
4672 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4673 }
4674
4675 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4676
4677 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4678 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4679
4680 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4681 Neg: options::OPT_fno_show_source_location);
4682
4683 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4684 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4685
4686 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4687 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4688
4689 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4690 Default: ColumnDefault))
4691 CmdArgs.push_back(Elt: "-fno-show-column");
4692
4693 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4694 Neg: options::OPT_fno_spell_checking);
4695
4696 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4697}
4698
4699static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4700 const ArgList &Args, ArgStringList &CmdArgs,
4701 unsigned DwarfVersion) {
4702 auto *DwarfFormatArg =
4703 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4704 if (!DwarfFormatArg)
4705 return;
4706
4707 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4708 if (DwarfVersion < 3)
4709 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4710 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4711 else if (!T.isArch64Bit())
4712 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4713 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4714 else if (!T.isOSBinFormatELF())
4715 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4716 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4717 }
4718
4719 DwarfFormatArg->render(Args, Output&: CmdArgs);
4720}
4721
4722static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4723 const ArgList &Args) {
4724 bool NeedsSimpleTemplateNames =
4725 Args.hasFlag(Pos: options::OPT_gsimple_template_names,
4726 Neg: options::OPT_gno_simple_template_names,
4727 Default: TC.getDefaultDebugSimpleTemplateNames());
4728 if (!NeedsSimpleTemplateNames)
4729 return false;
4730
4731 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsimple_template_names))
4732 if (!checkDebugInfoOption(A, Args, D, TC))
4733 return false;
4734
4735 return true;
4736}
4737
4738static void
4739renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4740 const ArgList &Args, types::ID InputType,
4741 ArgStringList &CmdArgs, const InputInfo &Output,
4742 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4743 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4744 bool IRInput = isLLVMIR(Id: InputType);
4745 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4746 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4747 !isOpenCL(Id: InputType);
4748
4749 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4750
4751 if (!Args.hasFlag(Pos: options::OPT_fdebug_record_sysroot,
4752 Neg: options::OPT_fno_debug_record_sysroot, Default: true))
4753 CmdArgs.push_back(Elt: "-fno-debug-record-sysroot");
4754
4755 // The 'g' groups options involve a somewhat intricate sequence of decisions
4756 // about what to pass from the driver to the frontend, but by the time they
4757 // reach cc1 they've been factored into three well-defined orthogonal choices:
4758 // * what level of debug info to generate
4759 // * what dwarf version to write
4760 // * what debugger tuning to use
4761 // This avoids having to monkey around further in cc1 other than to disable
4762 // codeview if not running in a Windows environment. Perhaps even that
4763 // decision should be made in the driver as well though.
4764 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4765
4766 bool SplitDWARFInlining =
4767 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4768 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4769
4770 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4771 // object file generation and no IR generation, -gN should not be needed. So
4772 // allow -gsplit-dwarf with either -gN or IR input.
4773 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4774 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4775 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4776 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4777 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4778 << TC.getTripleString();
4779 return;
4780 }
4781 Arg *SplitDWARFArg;
4782 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4783 if (DwarfFission != DwarfFissionKind::None &&
4784 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4785 DwarfFission = DwarfFissionKind::None;
4786 SplitDWARFInlining = false;
4787 }
4788 }
4789 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4790 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4791
4792 // If the last option explicitly specified a debug-info level, use it.
4793 if (checkDebugInfoOption(A, Args, D, TC) &&
4794 A->getOption().matches(ID: options::OPT_gN_Group)) {
4795 DebugInfoKind = debugLevelToInfoKind(A: *A);
4796 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4797 // complicated if you've disabled inline info in the skeleton CUs
4798 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4799 // line-tables-only, so let those compose naturally in that case.
4800 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4801 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4802 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4803 SplitDWARFInlining))
4804 DwarfFission = DwarfFissionKind::None;
4805 }
4806 }
4807
4808 // If a debugger tuning argument appeared, remember it.
4809 bool HasDebuggerTuning = false;
4810 if (const Arg *A =
4811 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4812 HasDebuggerTuning = true;
4813 if (checkDebugInfoOption(A, Args, D, TC)) {
4814 if (A->getOption().matches(ID: options::OPT_glldb))
4815 DebuggerTuning = llvm::DebuggerKind::LLDB;
4816 else if (A->getOption().matches(ID: options::OPT_gsce))
4817 DebuggerTuning = llvm::DebuggerKind::SCE;
4818 else if (A->getOption().matches(ID: options::OPT_gdbx))
4819 DebuggerTuning = llvm::DebuggerKind::DBX;
4820 else
4821 DebuggerTuning = llvm::DebuggerKind::GDB;
4822 }
4823 }
4824
4825 // If a -gdwarf argument appeared, remember it.
4826 bool EmitDwarf = false;
4827 if (const Arg *A = getDwarfNArg(Args))
4828 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4829
4830 bool EmitCodeView = false;
4831 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4832 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4833
4834 // If the user asked for debug info but did not explicitly specify -gcodeview
4835 // or -gdwarf, ask the toolchain for the default format.
4836 if (!EmitCodeView && !EmitDwarf &&
4837 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4838 switch (TC.getDefaultDebugFormat()) {
4839 case llvm::codegenoptions::DIF_CodeView:
4840 EmitCodeView = true;
4841 break;
4842 case llvm::codegenoptions::DIF_DWARF:
4843 EmitDwarf = true;
4844 break;
4845 }
4846 }
4847
4848 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4849 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4850 // be lower than what the user wanted.
4851 if (EmitDwarf) {
4852 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4853 // Clamp effective DWARF version to the max supported by the toolchain.
4854 EffectiveDWARFVersion =
4855 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4856 } else {
4857 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4858 }
4859
4860 // -gline-directives-only supported only for the DWARF debug info.
4861 if (RequestedDWARFVersion == 0 &&
4862 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4863 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4864
4865 // strict DWARF is set to false by default. But for DBX, we need it to be set
4866 // as true by default.
4867 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4868 (void)checkDebugInfoOption(A, Args, D, TC);
4869 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4870 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4871 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4872
4873 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4874 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4875
4876 // Column info is included by default for everything except SCE and
4877 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4878 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4879 // practice, however, the Microsoft debuggers don't handle missing end columns
4880 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4881 // it's better not to include any column info.
4882 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4883 (void)checkDebugInfoOption(A, Args, D, TC);
4884 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4885 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4886 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4887 DebuggerTuning != llvm::DebuggerKind::DBX)))
4888 CmdArgs.push_back(Elt: "-gno-column-info");
4889
4890 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4891 Neg: options::OPT_gno_call_site_info, Default: true))
4892 CmdArgs.push_back(Elt: "-gno-call-site-info");
4893
4894 // FIXME: Move backend command line options to the module.
4895 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4896 // If -gline-tables-only or -gline-directives-only is the last option it
4897 // wins.
4898 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4899 TC)) {
4900 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4901 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4902 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4903 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4904 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4905 }
4906 }
4907 }
4908
4909 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4910 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4911
4912 // After we've dealt with all combinations of things that could
4913 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4914 // figure out if we need to "upgrade" it to standalone debug info.
4915 // We parse these two '-f' options whether or not they will be used,
4916 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4917 bool NeedFullDebug = Args.hasFlag(
4918 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4919 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4920 TC.GetDefaultStandaloneDebug());
4921 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4922 (void)checkDebugInfoOption(A, Args, D, TC);
4923
4924 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4925 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4926 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4927 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4928 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4929 else if (NeedFullDebug)
4930 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4931 }
4932
4933 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4934 Default: false)) {
4935 // Source embedding is a vendor extension to DWARF v5. By now we have
4936 // checked if a DWARF version was stated explicitly, and have otherwise
4937 // fallen back to the target default, so if this is still not at least 5
4938 // we emit an error.
4939 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4940 if (RequestedDWARFVersion < 5)
4941 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4942 << A->getAsString(Args) << "-gdwarf-5";
4943 else if (EffectiveDWARFVersion < 5)
4944 // The toolchain has reduced allowed dwarf version, so we can't enable
4945 // -gembed-source.
4946 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4947 << A->getAsString(Args) << TC.getTripleString() << 5
4948 << EffectiveDWARFVersion;
4949 else if (checkDebugInfoOption(A, Args, D, TC))
4950 CmdArgs.push_back(Elt: "-gembed-source");
4951 }
4952
4953 // Enable Key Instructions by default if we're emitting DWARF, the language is
4954 // plain C or C++, and optimisations are enabled.
4955 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4956 bool KeyInstructionsOnByDefault =
4957 EmitDwarf && PlainCOrCXX && OptLevel &&
4958 !OptLevel->getOption().matches(ID: options::OPT_O0);
4959 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4960 Neg: options::OPT_gno_key_instructions,
4961 Default: KeyInstructionsOnByDefault))
4962 CmdArgs.push_back(Elt: "-gkey-instructions");
4963
4964 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4965 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4966 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4967
4968 if (Args.hasFlag(Pos: options::OPT_fdynamic_debugging,
4969 Neg: options::OPT_fno_dynamic_debugging, Default: false)) {
4970 // As this is an experimental feature we can afford to be strict about
4971 // supported configurations.
4972 // NOTE on adding target support, consider adding "tail-pad-to-size"
4973 // support in `llvm::prepareForDynamicDebugging`.
4974 if (!TC.getTriple().isX86())
4975 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4976 << Args.getLastArg(Ids: options::OPT_fdynamic_debugging)->getAsString(Args)
4977 << T.getTriple();
4978 if (IsUsingLTO)
4979 D.Diag(DiagID: diag::err_drv_dyndbg_lto);
4980 if (DwarfFission != DwarfFissionKind::None)
4981 D.Diag(DiagID: diag::err_drv_dyndbg_incompatible)
4982 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getAsString(Args);
4983 // There's no fundamental reason why IR input should be incompatible, but
4984 // it would add some complexity, and reducing the test matrix is valuable.
4985 if (IRInput)
4986 D.Diag(DiagID: diag::err_drv_dyndbg_ir);
4987
4988 // Disable composition with sanitizers for now.
4989 if (auto *San = Args.getLastArg(Ids: options::OPT_fsanitize_EQ))
4990 D.Diag(DiagID: diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4991
4992 if (!EmitDwarf)
4993 D.Diag(DiagID: diag::warn_drv_dyndbg_req_debug);
4994 else
4995 CmdArgs.push_back(Elt: "-fdynamic-debugging");
4996 }
4997
4998 if (EmitCodeView) {
4999 CmdArgs.push_back(Elt: "-gcodeview");
5000
5001 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
5002 Neg: options::OPT_gno_codeview_ghash);
5003
5004 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
5005 Neg: options::OPT_gno_codeview_command_line);
5006 }
5007
5008 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
5009 Neg: options::OPT_gno_inline_line_tables);
5010
5011 // When emitting remarks, we need at least debug lines in the output.
5012 if (willEmitRemarks(Args) &&
5013 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
5014 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
5015
5016 // Adjust the debug info kind for the given toolchain.
5017 TC.adjustDebugInfoKind(DebugInfoKind, Args);
5018
5019 // On AIX, the debugger tuning option can be omitted if it is not explicitly
5020 // set.
5021 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
5022 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
5023 ? llvm::DebuggerKind::Default
5024 : DebuggerTuning);
5025
5026 // -fdebug-macro turns on macro debug info generation.
5027 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
5028 Default: false))
5029 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
5030 D, TC))
5031 CmdArgs.push_back(Elt: "-debug-info-macro");
5032
5033 // -ggnu-pubnames turns on gnu style pubnames in the backend.
5034 const auto *PubnamesArg =
5035 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
5036 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
5037 if (DwarfFission != DwarfFissionKind::None ||
5038 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
5039 const bool OptionSet =
5040 (PubnamesArg &&
5041 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
5042 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
5043 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
5044 (!PubnamesArg ||
5045 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
5046 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
5047 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
5048 ID: options::OPT_gpubnames)
5049 ? "-gpubnames"
5050 : "-ggnu-pubnames");
5051 }
5052
5053 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
5054 if (getDebugSimpleTemplateNames(TC, D, Args)) {
5055 ForwardTemplateParams = true;
5056 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
5057 }
5058
5059 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
5060 bool UseDebugTemplateAlias =
5061 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
5062 if (const auto *DebugTemplateAlias = Args.getLastArg(
5063 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
5064 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
5065 // asks for it we should let them have it (if the target supports it).
5066 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
5067 const auto &Opt = DebugTemplateAlias->getOption();
5068 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
5069 }
5070 }
5071 if (UseDebugTemplateAlias)
5072 CmdArgs.push_back(Elt: "-gtemplate-alias");
5073
5074 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
5075 StringRef v = A->getValue();
5076 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
5077 }
5078
5079 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
5080 Neg: options::OPT_fno_debug_ranges_base_address);
5081
5082 // -gdwarf-aranges turns on the emission of the aranges section in the
5083 // backend.
5084 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
5085 A && checkDebugInfoOption(A, Args, D, TC)) {
5086 CmdArgs.push_back(Elt: "-mllvm");
5087 CmdArgs.push_back(Elt: "-generate-arange-section");
5088 }
5089
5090 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
5091 Neg: options::OPT_fno_force_dwarf_frame);
5092
5093 bool EnableTypeUnits = false;
5094 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
5095 Neg: options::OPT_fno_debug_types_section, Default: false)) {
5096 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5097 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5098 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
5099 ->getAsString(Args)
5100 << T.getTriple();
5101 } else if (checkDebugInfoOption(
5102 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
5103 TC)) {
5104 EnableTypeUnits = true;
5105 CmdArgs.push_back(Elt: "-mllvm");
5106 CmdArgs.push_back(Elt: "-generate-type-units");
5107 }
5108 }
5109
5110 if (const Arg *A =
5111 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
5112 Ids: options::OPT_gno_omit_unreferenced_methods))
5113 (void)checkDebugInfoOption(A, Args, D, TC);
5114 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
5115 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
5116 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5117 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5118 !EnableTypeUnits) {
5119 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
5120 }
5121
5122 // To avoid join/split of directory+filename, the integrated assembler prefers
5123 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5124 // form before DWARF v5.
5125 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
5126 Neg: options::OPT_fno_dwarf_directory_asm,
5127 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5128 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
5129
5130 // Decide how to render forward declarations of template instantiations.
5131 // SCE wants full descriptions, others just get them in the name.
5132 if (ForwardTemplateParams)
5133 CmdArgs.push_back(Elt: "-debug-forward-template-params");
5134
5135 // Do we need to explicitly import anonymous namespaces into the parent
5136 // scope?
5137 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5138 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
5139
5140 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
5141 if (useMachORelocatableDwarf(T, DwarfVersion: EffectiveDWARFVersion))
5142 CmdArgs.push_back(Elt: "-grelocatable-dwarf");
5143 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5144
5145 // This controls whether or not we perform JustMyCode instrumentation.
5146 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
5147 if (TC.getTriple().isOSBinFormatELF() ||
5148 TC.getTriple().isWindowsMSVCEnvironment()) {
5149 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5150 CmdArgs.push_back(Elt: "-fjmc");
5151 else if (D.IsCLMode())
5152 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5153 << "'/Zi', '/Z7'";
5154 else
5155 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5156 << "-g";
5157 } else {
5158 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
5159 }
5160 }
5161
5162 // Add in -fdebug-compilation-dir if necessary.
5163 const char *DebugCompilationDir =
5164 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
5165
5166 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5167
5168 // Add the output path to the object file for CodeView debug infos.
5169 if (EmitCodeView && Output.isFilename())
5170 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5171 OutputFileName: Output.getFilename());
5172}
5173
5174static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5175 ArgStringList &CmdArgs) {
5176 unsigned RTOptionID = options::OPT__SLASH_MT;
5177
5178 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5179 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5180 // but defining _DEBUG is sticky.
5181 RTOptionID = options::OPT__SLASH_MTd;
5182
5183 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
5184 RTOptionID = A->getOption().getID();
5185
5186 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5187 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5188 .Case(S: "static", Value: options::OPT__SLASH_MT)
5189 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
5190 .Case(S: "dll", Value: options::OPT__SLASH_MD)
5191 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
5192 .Default(Value: options::OPT__SLASH_MT);
5193 }
5194
5195 StringRef FlagForCRT;
5196 switch (RTOptionID) {
5197 case options::OPT__SLASH_MD:
5198 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5199 CmdArgs.push_back(Elt: "-D_DEBUG");
5200 CmdArgs.push_back(Elt: "-D_MT");
5201 CmdArgs.push_back(Elt: "-D_DLL");
5202 FlagForCRT = "--dependent-lib=msvcrt";
5203 break;
5204 case options::OPT__SLASH_MDd:
5205 CmdArgs.push_back(Elt: "-D_DEBUG");
5206 CmdArgs.push_back(Elt: "-D_MT");
5207 CmdArgs.push_back(Elt: "-D_DLL");
5208 FlagForCRT = "--dependent-lib=msvcrtd";
5209 break;
5210 case options::OPT__SLASH_MT:
5211 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5212 CmdArgs.push_back(Elt: "-D_DEBUG");
5213 CmdArgs.push_back(Elt: "-D_MT");
5214 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5215 FlagForCRT = "--dependent-lib=libcmt";
5216 break;
5217 case options::OPT__SLASH_MTd:
5218 CmdArgs.push_back(Elt: "-D_DEBUG");
5219 CmdArgs.push_back(Elt: "-D_MT");
5220 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5221 FlagForCRT = "--dependent-lib=libcmtd";
5222 break;
5223 default:
5224 llvm_unreachable("Unexpected option ID.");
5225 }
5226
5227 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5228 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
5229 } else {
5230 CmdArgs.push_back(Elt: FlagForCRT.data());
5231
5232 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5233 // users want. The /Za flag to cl.exe turns this off, but it's not
5234 // implemented in clang.
5235 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
5236 }
5237
5238 // SYCL: Add SYCL runtime library dependency
5239 // SYCL runtime is a required dependency similar to CRT, so we use
5240 // --dependent-lib to embed it in the object file metadata
5241 if (Args.hasFlag(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false) &&
5242 !Args.hasArg(Ids: options::OPT_nolibsycl) &&
5243 !Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5244
5245 // Determine debug vs release based on CRT flags
5246 bool IsDebugBuild = false;
5247
5248 // Check -fms-runtime-lib=dll_dbg
5249 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5250 StringRef RuntimeVal = A->getValue();
5251 if (RuntimeVal == "dll_dbg")
5252 IsDebugBuild = true;
5253 }
5254
5255 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5256 // overriding options (e.g., /MDd /MD -> /MD wins)
5257 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group)) {
5258 if (A->getOption().matches(ID: options::OPT__SLASH_MDd))
5259 IsDebugBuild = true;
5260 }
5261
5262 // Add appropriate SYCL runtime library dependency
5263 CmdArgs.push_back(Elt: IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5264 : "--dependent-lib=LLVMSYCL");
5265 }
5266
5267 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5268 // even if the file doesn't actually refer to any of the routines because
5269 // the CRT itself has incomplete dependency markings.
5270 if (TC.getTriple().isWindowsArm64EC())
5271 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
5272}
5273
5274void Clang::ConstructJob(Compilation &C, const JobAction &JA,
5275 const InputInfo &Output, const InputInfoList &Inputs,
5276 const ArgList &Args, const char *LinkingOutput) const {
5277 const auto &TC = getToolChain();
5278 const llvm::Triple &RawTriple = TC.getTriple();
5279 const llvm::Triple &Triple = TC.getEffectiveTriple();
5280 const std::string &TripleStr = Triple.getTriple();
5281
5282 bool KernelOrKext =
5283 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
5284 const Driver &D = TC.getDriver();
5285 ArgStringList CmdArgs;
5286
5287 assert(Inputs.size() >= 1 && "Must have at least one input.");
5288 // CUDA/HIP compilation may have multiple inputs (source file + results of
5289 // device-side compilations). OpenMP device jobs also take the host IR as a
5290 // second input. Module precompilation accepts a list of header files to
5291 // include as part of the module. API extraction accepts a list of header
5292 // files whose API information is emitted in the output. All other jobs are
5293 // expected to have exactly one input. SYCL compilation only expects a
5294 // single input.
5295 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
5296 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
5297 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
5298 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
5299 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
5300 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
5301 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
5302 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
5303 bool UsesLLVMOffloading = Args.hasFlag(
5304 Pos: options::OPT_foffload_via_llvm, Neg: options::OPT_fno_offload_via_llvm, Default: false);
5305 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
5306 JA.isDeviceOffloading(OKind: Action::OFK_Host));
5307 bool IsHostOffloadingAction =
5308 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
5309 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
5310 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()));
5311
5312 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5313 bool IsRDCMode = Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc,
5314 /*Default=*/IsSYCL);
5315
5316 auto LTOMode = TC.getLTOMode(Args, Kind: JA.getOffloadingDeviceKind());
5317 bool IsUsingLTO = LTOMode != LTOK_None;
5318
5319 // Extract API doesn't have a main input file, so invent a fake one as a
5320 // placeholder.
5321 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5322 "extract-api");
5323
5324 const InputInfo &Input =
5325 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5326
5327 InputInfoList ExtractAPIInputs;
5328 InputInfoList HostOffloadingInputs;
5329 const InputInfo *OpenMPDeviceInput = nullptr;
5330 for (const InputInfo &I : Inputs) {
5331 if (&I == &Input || I.getType() == types::TY_Nothing) {
5332 // This is the primary input or contains nothing.
5333 } else if (IsExtractAPI) {
5334 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5335 if (I.getType() != ExpectedInputType) {
5336 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
5337 << I.getFilename() << types::getTypeName(Id: I.getType())
5338 << types::getTypeName(Id: ExpectedInputType);
5339 }
5340 ExtractAPIInputs.push_back(Elt: I);
5341 } else if (IsHostOffloadingAction) {
5342 HostOffloadingInputs.push_back(Elt: I);
5343 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5344 OpenMPDeviceInput = &I;
5345 } else {
5346 llvm_unreachable("unexpectedly given multiple inputs");
5347 }
5348 }
5349
5350 bool IsUEFI = RawTriple.isUEFI();
5351 bool IsIAMCU = RawTriple.isOSIAMCU();
5352
5353 // C++ is not supported for IAMCU.
5354 if (IsIAMCU && types::isCXX(Id: Input.getType()))
5355 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5356
5357 // Invoke ourselves in -cc1 mode.
5358 //
5359 // FIXME: Implement custom jobs for internal actions.
5360 CmdArgs.push_back(Elt: "-cc1");
5361
5362 // Add the "effective" target triple.
5363 CmdArgs.push_back(Elt: "-triple");
5364 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: TripleStr));
5365
5366 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5367
5368 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5369 if (AuxTriple) {
5370 CmdArgs.push_back(Elt: "-aux-triple");
5371 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: AuxTriple->str()));
5372
5373 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5374 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5375 // Windows), we need to pass Windows-specific flags to cc1.
5376 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5377 } else if (JA.getOffloadingHostActiveKinds() != Action::OFK_None) {
5378 // Figure out the device side triple for the host-side compilation.
5379 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5380 ++I) {
5381 Compilation::const_offload_toolchains_range OffloadToolChains =
5382 C.getOffloadToolChains(Kind: static_cast<Action::OffloadKind>(I));
5383 if (OffloadToolChains.first == OffloadToolChains.second)
5384 continue;
5385
5386 const llvm::Triple &DeviceAuxTriple =
5387 OffloadToolChains.first->second->getTriple();
5388 CmdArgs.push_back(Elt: "-aux-triple");
5389 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: DeviceAuxTriple.str()));
5390 break;
5391 }
5392 }
5393
5394 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
5395 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
5396 Args.ClaimAllArgs(Id0: options::OPT_MJ);
5397 } else if (const Arg *GenCDBFragment =
5398 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
5399 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
5400 Target: TripleStr, Output, Input, Args);
5401 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
5402 }
5403
5404 if ((getToolChain().getTriple().isAMDGPU() ||
5405 (getToolChain().getTriple().isSPIRV() &&
5406 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5407 // Device side compilation printf
5408 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
5409 CmdArgs.push_back(Elt: Args.MakeArgString(
5410 Str: "-mprintf-kind=" +
5411 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
5412 // Force compiler error on invalid conversion specifiers
5413 CmdArgs.push_back(
5414 Elt: Args.MakeArgStringRef(Str: "-Werror=format-invalid-specifier"));
5415 }
5416 }
5417
5418 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5419 // We need to figure out which CUDA version we're compiling for, as that
5420 // determines how we load and launch GPU kernels.
5421 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5422 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5423 assert(CTC && "Expected valid CUDA Toolchain.");
5424 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5425 CmdArgs.push_back(Elt: Args.MakeArgString(
5426 Str: Twine("-target-sdk-version=") +
5427 CudaVersionToString(V: CTC->CudaInstallation.version())));
5428 }
5429
5430 // Optimization level for CodeGen.
5431 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5432 if (A->getOption().matches(ID: options::OPT_O4)) {
5433 CmdArgs.push_back(Elt: "-O3");
5434 D.Diag(DiagID: diag::warn_O4_is_O3);
5435 } else {
5436 A->render(Args, Output&: CmdArgs);
5437 }
5438 }
5439
5440 // Unconditionally claim the printf option now to avoid unused diagnostic.
5441 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5442 PF->claim();
5443
5444 if (IsSYCL) {
5445 if (IsSYCLDevice) {
5446 // We want to compile sycl kernels.
5447 CmdArgs.push_back(Elt: "-fsycl-is-device");
5448
5449 // Set O2 optimization level by default
5450 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5451 CmdArgs.push_back(Elt: "-O2");
5452 } else {
5453 // Add any options that are needed specific to SYCL offload while
5454 // performing the host side compilation.
5455
5456 // Let the front-end host compilation flow know about SYCL offload
5457 // compilation.
5458 CmdArgs.push_back(Elt: "-fsycl-is-host");
5459 }
5460
5461 // Set options for both host and device.
5462 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5463 if (SYCLStdArg) {
5464 SYCLStdArg->render(Args, Output&: CmdArgs);
5465 } else {
5466 // Ensure the default version in SYCL mode is 2020.
5467 CmdArgs.push_back(Elt: "-sycl-std=2020");
5468 }
5469 }
5470
5471 if (Args.hasFlag(Pos: options::OPT_fclangir, Neg: options::OPT_fno_clangir, Default: false))
5472 CmdArgs.push_back(Elt: "-fclangir");
5473
5474 if (IsOpenMPDevice) {
5475 // We have to pass the triple of the host if compiling for an OpenMP device.
5476 const llvm::Triple &HostTriple =
5477 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5478 CmdArgs.push_back(Elt: "-aux-triple");
5479 CmdArgs.push_back(Elt: HostTriple.str().c_str());
5480 }
5481
5482 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5483 Triple.getArch() == llvm::Triple::thumb)) {
5484 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5485 unsigned Version = 0;
5486 bool Failure =
5487 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5488 if (Failure || Version < 7)
5489 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5490 << TripleStr;
5491 }
5492
5493 // Push all default warning arguments that are specific to
5494 // the given target. These come before user provided warning options
5495 // are provided.
5496 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5497
5498 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5499 if (Triple.isSPIR() || Triple.isSPIRV())
5500 CmdArgs.push_back(Elt: "-Wspir-compat");
5501
5502 // Select the appropriate action.
5503 RewriteKind rewriteKind = RK_None;
5504
5505 bool UnifiedLTO = false;
5506 if (IsUsingLTO) {
5507 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5508 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5509 if (UnifiedLTO)
5510 CmdArgs.push_back(Elt: "-funified-lto");
5511 }
5512
5513 if (Args.hasArg(Ids: options::OPT_fdefined_pointer_subtraction))
5514 CmdArgs.push_back(Elt: "-fdefined-pointer-subtraction");
5515
5516 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5517 // it claims when not running an assembler. Otherwise, clang would emit
5518 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5519 // flags while debugging something. That'd be somewhat inconvenient, and it's
5520 // also inconsistent with most other flags -- we don't warn on
5521 // -ffunction-sections not being used in -E mode either for example, even
5522 // though it's not really used either.
5523 if (!isa<AssembleJobAction>(Val: JA)) {
5524 // The args claimed here should match the args used in
5525 // CollectArgsForIntegratedAssembler().
5526 if (TC.useIntegratedAs()) {
5527 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5528 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5529 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5530 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5531 switch (C.getDefaultToolChain().getArch()) {
5532 case llvm::Triple::arm:
5533 case llvm::Triple::armeb:
5534 case llvm::Triple::thumb:
5535 case llvm::Triple::thumbeb:
5536 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5537 break;
5538 default:
5539 break;
5540 }
5541 }
5542 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5543 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5544 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5545 }
5546
5547 bool IsAMDSPIRVForHIPDevice =
5548 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5549 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5550
5551 if (isa<AnalyzeJobAction>(Val: JA)) {
5552 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5553 CmdArgs.push_back(Elt: "-analyze");
5554 } else if (isa<PreprocessJobAction>(Val: JA)) {
5555 if (Output.getType() == types::TY_Dependencies)
5556 CmdArgs.push_back(Elt: "-Eonly");
5557 else {
5558 CmdArgs.push_back(Elt: "-E");
5559 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5560 !Args.hasArg(Ids: options::OPT_g_Group))
5561 CmdArgs.push_back(Elt: "-P");
5562 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5563 CmdArgs.push_back(Elt: "-fdirectives-only");
5564 }
5565 } else if (isa<AssembleJobAction>(Val: JA)) {
5566 CmdArgs.push_back(Elt: "-emit-obj");
5567
5568 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5569
5570 // Also ignore explicit -force_cpusubtype_ALL option.
5571 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5572 } else if (isa<PrecompileJobAction>(Val: JA)) {
5573 if (JA.getType() == types::TY_Nothing)
5574 CmdArgs.push_back(Elt: "-fsyntax-only");
5575 else if (JA.getType() == types::TY_ModuleFile) {
5576 if (Args.hasArg(Ids: options::OPT__precompile_reduced_bmi) ||
5577 ((Input.getType() == types::TY_CXXStdModule ||
5578 Input.getType() == types::TY_PP_CXXStdModule) &&
5579 !Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi)))
5580 CmdArgs.push_back(Elt: "-emit-reduced-module-interface");
5581 else
5582 CmdArgs.push_back(Elt: "-emit-module-interface");
5583 } else if (JA.getType() == types::TY_HeaderUnit)
5584 CmdArgs.push_back(Elt: "-emit-header-unit");
5585 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5586 CmdArgs.push_back(Elt: "-emit-pch");
5587 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5588 CmdArgs.push_back(Elt: "-verify-pch");
5589 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5590 assert(JA.getType() == types::TY_API_INFO &&
5591 "Extract API actions must generate a API information.");
5592 CmdArgs.push_back(Elt: "-extract-api");
5593
5594 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5595 PrettySGFArg->render(Args, Output&: CmdArgs);
5596
5597 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5598
5599 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5600 ProductNameArg->render(Args, Output&: CmdArgs);
5601 if (Arg *ExtractAPIIgnoresFileArg =
5602 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5603 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5604 if (Arg *EmitExtensionSymbolGraphs =
5605 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5606 if (!SymbolGraphDirArg)
5607 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5608
5609 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5610 }
5611 if (SymbolGraphDirArg)
5612 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5613 } else {
5614 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5615 "Invalid action for clang tool.");
5616 if (JA.getType() == types::TY_Nothing) {
5617 CmdArgs.push_back(Elt: "-fsyntax-only");
5618 } else if (JA.getType() == types::TY_LLVM_IR ||
5619 JA.getType() == types::TY_LTO_IR) {
5620 CmdArgs.push_back(Elt: "-emit-llvm");
5621 } else if (JA.getType() == types::TY_LLVM_BC ||
5622 JA.getType() == types::TY_LTO_BC) {
5623 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5624 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5625 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5626 CmdArgs.push_back(Elt: "-emit-llvm");
5627 } else {
5628 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5629 }
5630 } else if (JA.getType() == types::TY_IFS ||
5631 JA.getType() == types::TY_IFS_CPP) {
5632 StringRef ArgStr =
5633 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5634 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5635 : "ifs-v1";
5636 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5637 CmdArgs.push_back(
5638 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr));
5639 } else if (JA.getType() == types::TY_PP_Asm) {
5640 CmdArgs.push_back(Elt: "-S");
5641 } else if (JA.getType() == types::TY_AST) {
5642 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5643 CmdArgs.push_back(Elt: "-emit-pch");
5644 } else if (JA.getType() == types::TY_ModuleFile) {
5645 CmdArgs.push_back(Elt: "-module-file-info");
5646 } else if (JA.getType() == types::TY_RewrittenObjC) {
5647 CmdArgs.push_back(Elt: "-rewrite-objc");
5648 rewriteKind = RK_NonFragile;
5649 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5650 CmdArgs.push_back(Elt: "-rewrite-objc");
5651 rewriteKind = RK_Fragile;
5652 } else if (JA.getType() == types::TY_CIR) {
5653 CmdArgs.push_back(Elt: "-emit-cir");
5654 } else if (JA.getType() == types::TY_CIRBC) {
5655 CmdArgs.push_back(Elt: "-emit-cir-bc");
5656 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5657 CmdArgs.push_back(Elt: "-emit-obj");
5658 } else {
5659 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5660 }
5661
5662 // Preserve use-list order by default when emitting bitcode, so that
5663 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5664 // same result as running passes here. For LTO, we don't need to preserve
5665 // the use-list order, since serialization to bitcode is part of the flow.
5666 if (JA.getType() == types::TY_LLVM_BC)
5667 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5668
5669 if (IsUsingLTO) {
5670 const Arg *LTOArg = Args.getLastArg(Ids: options::OPT_foffload_lto,
5671 Ids: options::OPT_foffload_lto_EQ);
5672 if (Triple.isNVPTX() && !IsRDCMode &&
5673 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5674 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5675 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5676 << "-fno-gpu-rdc";
5677 } else {
5678 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5679 CmdArgs.push_back(Elt: Args.MakeArgString(
5680 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5681 // PS4 uses the legacy LTO API, which does not support some of the
5682 // features enabled by -flto-unit.
5683 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5684 CmdArgs.push_back(Elt: "-flto-unit");
5685 }
5686 }
5687 }
5688
5689 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5690
5691 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5692 if (!types::isLLVMIR(Id: Input.getType()))
5693 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5694 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5695 }
5696
5697 if (Triple.isPPC())
5698 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5699 Neg: options::OPT_mno_regnames);
5700
5701 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5702 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5703
5704 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5705 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5706
5707 if (Args.getLastArg(Ids: options::OPT_save_dynamic_debugging_temps))
5708 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_dynamic_debugging_temps);
5709
5710 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5711 Ids: options::OPT_fmemory_profile_EQ,
5712 Ids: options::OPT_fno_memory_profile);
5713 if (MemProfArg &&
5714 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5715 MemProfArg->render(Args, Output&: CmdArgs);
5716
5717 if (auto *MemProfUseArg =
5718 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5719 if (MemProfArg)
5720 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5721 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5722 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5723 Ids: options::OPT_fprofile_generate_EQ))
5724 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5725 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5726 MemProfUseArg->render(Args, Output&: CmdArgs);
5727 }
5728
5729 auto *CopyProfArg =
5730 Args.getLastArg(Ids: options::OPT_fcopyprof, Ids: options::OPT_fno_copyprof);
5731 if (CopyProfArg &&
5732 !CopyProfArg->getOption().matches(ID: options::OPT_fno_copyprof)) {
5733 CopyProfArg->render(Args, Output&: CmdArgs);
5734 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcopyprof_static_size_threshold_EQ);
5735 }
5736
5737 // Embed-bitcode option.
5738 // Only white-listed flags below are allowed to be embedded.
5739 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5740 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5741 // Add flags implied by -fembed-bitcode.
5742 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5743 // Disable all llvm IR level optimizations.
5744 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5745
5746 // Render target options.
5747 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
5748 DeviceOffloadKind: JA.getOffloadingDeviceKind());
5749
5750 // reject options that shouldn't be supported in bitcode
5751 // also reject kernel/kext
5752 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5753 options::OPT_mkernel,
5754 options::OPT_fapple_kext,
5755 options::OPT_ffunction_sections,
5756 options::OPT_fno_function_sections,
5757 options::OPT_fdata_sections,
5758 options::OPT_fno_data_sections,
5759 options::OPT_fbasic_block_sections_EQ,
5760 options::OPT_funique_internal_linkage_names,
5761 options::OPT_fno_unique_internal_linkage_names,
5762 options::OPT_funique_section_names,
5763 options::OPT_fno_unique_section_names,
5764 options::OPT_funique_basic_block_section_names,
5765 options::OPT_fno_unique_basic_block_section_names,
5766 options::OPT_mrestrict_it,
5767 options::OPT_mno_restrict_it,
5768 options::OPT_mstackrealign,
5769 options::OPT_mno_stackrealign,
5770 options::OPT_mstack_alignment,
5771 options::OPT_mcmodel_EQ,
5772 options::OPT_mlong_calls,
5773 options::OPT_mno_long_calls,
5774 options::OPT_ggnu_pubnames,
5775 options::OPT_gdwarf_aranges,
5776 options::OPT_fdebug_types_section,
5777 options::OPT_fno_debug_types_section,
5778 options::OPT_fdwarf_directory_asm,
5779 options::OPT_fno_dwarf_directory_asm,
5780 options::OPT_mrelax_all,
5781 options::OPT_mno_relax_all,
5782 options::OPT_ftrap_function_EQ,
5783 options::OPT_ffixed_r9,
5784 options::OPT_mfix_cortex_a53_835769,
5785 options::OPT_mno_fix_cortex_a53_835769,
5786 options::OPT_ffixed_x18,
5787 options::OPT_mglobal_merge,
5788 options::OPT_mno_global_merge,
5789 options::OPT_mred_zone,
5790 options::OPT_mno_red_zone,
5791 options::OPT_Wa_COMMA,
5792 options::OPT_Xassembler,
5793 options::OPT_mllvm,
5794 options::OPT_mmlir,
5795 };
5796 for (const auto &A : Args)
5797 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5798 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5799
5800 // Render the CodeGen options that need to be passed.
5801 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5802 Neg: options::OPT_fno_optimize_sibling_calls);
5803
5804 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5805 CmdArgs, JA);
5806
5807 // Render ABI arguments
5808 switch (TC.getArch()) {
5809 default: break;
5810 case llvm::Triple::arm:
5811 case llvm::Triple::armeb:
5812 case llvm::Triple::thumbeb:
5813 RenderARMABI(D, Triple, Args, CmdArgs);
5814 break;
5815 case llvm::Triple::aarch64:
5816 case llvm::Triple::aarch64_32:
5817 case llvm::Triple::aarch64_be:
5818 RenderAArch64ABI(Triple, Args, CmdArgs);
5819 break;
5820 }
5821
5822 // Input/Output file.
5823 if (Output.getType() == types::TY_Dependencies) {
5824 // Handled with other dependency code.
5825 } else if (Output.isFilename()) {
5826 CmdArgs.push_back(Elt: "-o");
5827 CmdArgs.push_back(Elt: Output.getFilename());
5828 } else {
5829 assert(Output.isNothing() && "Input output.");
5830 }
5831
5832 for (const auto &II : Inputs) {
5833 addDashXForInput(Args, Input: II, CmdArgs);
5834 if (II.isFilename())
5835 CmdArgs.push_back(Elt: II.getFilename());
5836 else
5837 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5838 }
5839
5840 C.addCommand(Cmd: std::make_unique<Command>(
5841 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getDriverProgramPath(),
5842 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5843 return;
5844 }
5845
5846 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5847 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5848
5849 // We normally speed up the clang process a bit by skipping destructors at
5850 // exit, but when we're generating diagnostics we can rely on some of the
5851 // cleanup.
5852 if (!C.isForDiagnostics())
5853 CmdArgs.push_back(Elt: "-disable-free");
5854 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5855
5856#ifdef NDEBUG
5857 const bool IsAssertBuild = false;
5858#else
5859 const bool IsAssertBuild = true;
5860#endif
5861
5862 // Disable the verification pass in no-asserts builds unless otherwise
5863 // specified.
5864 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5865 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5866 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5867 }
5868
5869 // Discard value names in no-asserts builds unless otherwise specified.
5870 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5871 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild))
5872 CmdArgs.push_back(Elt: "-discard-value-names");
5873
5874 // Set the main file name, so that debug info works even with
5875 // -save-temps.
5876 CmdArgs.push_back(Elt: "-main-file-name");
5877 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5878
5879 // Some flags which affect the language (via preprocessor
5880 // defines).
5881 if (Args.hasArg(Ids: options::OPT_static))
5882 CmdArgs.push_back(Elt: "-static-define");
5883
5884 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5885
5886 if (Args.hasArg(Ids: options::OPT_municode))
5887 CmdArgs.push_back(Elt: "-DUNICODE");
5888
5889 if (isa<AnalyzeJobAction>(Val: JA))
5890 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5891
5892 if (isa<AnalyzeJobAction>(Val: JA) ||
5893 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5894 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5895
5896 // Enable compatilibily mode to avoid analyzer-config related errors.
5897 // Since we can't access frontend flags through hasArg, let's manually iterate
5898 // through them.
5899 bool FoundAnalyzerConfig = false;
5900 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5901 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5902 FoundAnalyzerConfig = true;
5903 break;
5904 }
5905 if (!FoundAnalyzerConfig)
5906 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5907 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5908 FoundAnalyzerConfig = true;
5909 break;
5910 }
5911 if (FoundAnalyzerConfig)
5912 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5913
5914 CheckCodeGenerationOptions(D, Args);
5915
5916 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5917 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5918 if (FunctionAlignment) {
5919 CmdArgs.push_back(Elt: "-function-alignment");
5920 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(FunctionAlignment)));
5921 }
5922
5923 if (const Arg *A =
5924 Args.getLastArg(Ids: options::OPT_fpreferred_function_alignment_EQ)) {
5925 unsigned Value = 0;
5926 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5927 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5928 << A->getAsString(Args) << A->getValue();
5929 else if (!llvm::isPowerOf2_32(Value))
5930 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5931 << A->getAsString(Args) << A->getValue();
5932
5933 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpreferred-function-alignment=" +
5934 Twine(std::min(a: Value, b: 65536u))));
5935 }
5936
5937 // We support -falign-loops=N where N is a power of 2. GCC supports more
5938 // forms.
5939 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5940 unsigned Value = 0;
5941 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5942 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5943 << A->getAsString(Args) << A->getValue();
5944 else if (Value & (Value - 1))
5945 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5946 << A->getAsString(Args) << A->getValue();
5947 // Treat =0 as unspecified (use the target preference).
5948 if (Value)
5949 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5950 Twine(std::min(a: Value, b: 65536u))));
5951 }
5952
5953 if (Triple.isOSzOS()) {
5954 // On z/OS some of the system header feature macros need to
5955 // be defined to enable most cross platform projects to build
5956 // successfully. Ths include the libc++ library. A
5957 // complicating factor is that users can define these
5958 // macros to the same or different values. We need to add
5959 // the definition for these macros to the compilation command
5960 // if the user hasn't already defined them.
5961
5962 auto findMacroDefinition = [&](const std::string &Macro) {
5963 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5964 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5965 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5966 });
5967 };
5968
5969 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5970 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5971 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5972 // _OPEN_DEFAULT is required for XL compat
5973 if (!findMacroDefinition("_OPEN_DEFAULT"))
5974 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5975 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5976 // _XOPEN_SOURCE=600 is required for libcxx.
5977 if (!findMacroDefinition("_XOPEN_SOURCE"))
5978 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5979 }
5980 }
5981
5982 llvm::Reloc::Model RelocationModel;
5983 unsigned PICLevel;
5984 bool IsPIE;
5985 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5986 Arg *LastPICDataRelArg =
5987 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5988 Ids: options::OPT_mpic_data_is_text_relative);
5989 bool NoPICDataIsTextRelative = false;
5990 if (LastPICDataRelArg) {
5991 if (LastPICDataRelArg->getOption().matches(
5992 ID: options::OPT_mno_pic_data_is_text_relative)) {
5993 NoPICDataIsTextRelative = true;
5994 if (!PICLevel)
5995 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5996 << "-mno-pic-data-is-text-relative"
5997 << "-fpic/-fpie";
5998 }
5999 if (!Triple.isSystemZ())
6000 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6001 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
6002 : "-mpic-data-is-text-relative")
6003 << RawTriple.str();
6004 }
6005
6006 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
6007 RelocationModel == llvm::Reloc::ROPI_RWPI;
6008 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
6009 RelocationModel == llvm::Reloc::ROPI_RWPI;
6010
6011 if (Args.hasArg(Ids: options::OPT_mcmse) &&
6012 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6013 if (IsROPI)
6014 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
6015 if (IsRWPI)
6016 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
6017 }
6018
6019 if (IsROPI && types::isCXX(Id: Input.getType()) &&
6020 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
6021 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
6022
6023 const char *RMName = RelocationModelName(Model: RelocationModel);
6024 if (RMName) {
6025 CmdArgs.push_back(Elt: "-mrelocation-model");
6026 CmdArgs.push_back(Elt: RMName);
6027 }
6028 if (PICLevel > 0) {
6029 CmdArgs.push_back(Elt: "-pic-level");
6030 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
6031 if (IsPIE)
6032 CmdArgs.push_back(Elt: "-pic-is-pie");
6033 if (NoPICDataIsTextRelative)
6034 CmdArgs.push_back(Elt: "-mcmodel=medium");
6035 }
6036
6037 if (RelocationModel == llvm::Reloc::ROPI ||
6038 RelocationModel == llvm::Reloc::ROPI_RWPI)
6039 CmdArgs.push_back(Elt: "-fropi");
6040 if (RelocationModel == llvm::Reloc::RWPI ||
6041 RelocationModel == llvm::Reloc::ROPI_RWPI)
6042 CmdArgs.push_back(Elt: "-frwpi");
6043
6044 // -meabi=gnu/5 are encoded in the cc1 -triple environment; forward only other
6045 // values (e.g. 4, which has no triple representation, and invalid values).
6046 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
6047 StringRef Value = A->getValue();
6048 if (Value != "gnu" && Value != "5") {
6049 CmdArgs.push_back(Elt: "-meabi");
6050 CmdArgs.push_back(Elt: A->getValue());
6051 }
6052 }
6053
6054 // -fsemantic-interposition is forwarded to CC1: set the
6055 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
6056 // make default visibility external linkage definitions dso_preemptable.
6057 //
6058 // -fno-semantic-interposition: if the target supports .Lfoo$local local
6059 // aliases (make default visibility external linkage definitions dso_local).
6060 // This is the CC1 default for ELF to match COFF/Mach-O.
6061 //
6062 // Otherwise use Clang's traditional behavior: like
6063 // -fno-semantic-interposition but local aliases are not used. So references
6064 // can be interposed if not optimized out.
6065 if (Triple.isOSBinFormatELF()) {
6066 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
6067 Ids: options::OPT_fno_semantic_interposition);
6068 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
6069 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
6070 bool SupportsLocalAlias =
6071 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
6072 if (!A)
6073 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
6074 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
6075 A->render(Args, Output&: CmdArgs);
6076 else if (!SupportsLocalAlias)
6077 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
6078 }
6079 }
6080
6081 {
6082 std::string Model;
6083 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
6084 if (!TC.isThreadModelSupported(Model: A->getValue()))
6085 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
6086 << A->getValue() << A->getAsString(Args);
6087 Model = A->getValue();
6088 } else
6089 Model = TC.getThreadModel();
6090 if (Model != "posix") {
6091 CmdArgs.push_back(Elt: "-mthread-model");
6092 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
6093 }
6094 }
6095
6096 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
6097 StringRef Name = A->getValue();
6098 if (Name == "SVML") {
6099 if (Triple.getArch() != llvm::Triple::x86 &&
6100 Triple.getArch() != llvm::Triple::x86_64)
6101 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6102 << Name << Triple.getArchName();
6103 } else if (Name == "AMDLIBM") {
6104 if (Triple.getArch() != llvm::Triple::x86 &&
6105 Triple.getArch() != llvm::Triple::x86_64)
6106 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6107 << Name << Triple.getArchName();
6108 } else if (Name == "libmvec") {
6109 if (Triple.getArch() != llvm::Triple::x86 &&
6110 Triple.getArch() != llvm::Triple::x86_64 &&
6111 Triple.getArch() != llvm::Triple::aarch64 &&
6112 Triple.getArch() != llvm::Triple::aarch64_be)
6113 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6114 << Name << Triple.getArchName();
6115 } else if (Name == "SLEEF" || Name == "ArmPL") {
6116 if (Triple.getArch() != llvm::Triple::aarch64 &&
6117 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6118 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6119 << Name << Triple.getArchName();
6120 }
6121 A->render(Args, Output&: CmdArgs);
6122 }
6123
6124 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
6125 Neg: options::OPT_fno_merge_all_constants, Default: false))
6126 CmdArgs.push_back(Elt: "-fmerge-all-constants");
6127
6128 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
6129 Neg: options::OPT_fno_delete_null_pointer_checks);
6130
6131 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_dse,
6132 Neg: options::OPT_fno_lifetime_dse);
6133
6134 // LLVM Code Generator Options.
6135
6136 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
6137 if (!Triple.isOSAIX() || Triple.isPPC32())
6138 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6139 << A->getSpelling() << RawTriple.str();
6140 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
6141 }
6142
6143 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
6144 // Emit the unsupported option error until the Clang's library integration
6145 // support for 128-bit long double is available for AIX.
6146 if (Triple.isOSAIX())
6147 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6148 << A->getSpelling() << RawTriple.str();
6149 }
6150
6151 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
6152 StringRef V = A->getValue(), V1 = V;
6153 unsigned Size;
6154 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
6155 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6156 << V << A->getOption().getName();
6157 else
6158 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
6159 }
6160
6161 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
6162 Neg: options::OPT_fno_jump_tables);
6163 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
6164 Neg: options::OPT_fno_profile_sample_accurate);
6165 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
6166 Neg: options::OPT_fno_preserve_as_comments);
6167
6168 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
6169 CmdArgs.push_back(Elt: "-mregparm");
6170 CmdArgs.push_back(Elt: A->getValue());
6171 }
6172
6173 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
6174 Ids: options::OPT_msvr4_struct_return)) {
6175 if (!TC.getTriple().isPPC32()) {
6176 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6177 << A->getSpelling() << RawTriple.str();
6178 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
6179 CmdArgs.push_back(Elt: "-maix-struct-return");
6180 } else {
6181 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6182 CmdArgs.push_back(Elt: "-msvr4-struct-return");
6183 }
6184 }
6185
6186 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
6187 Ids: options::OPT_freg_struct_return)) {
6188 if (TC.getArch() != llvm::Triple::x86) {
6189 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6190 << A->getSpelling() << RawTriple.str();
6191 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
6192 CmdArgs.push_back(Elt: "-fpcc-struct-return");
6193 } else {
6194 assert(A->getOption().matches(options::OPT_freg_struct_return));
6195 CmdArgs.push_back(Elt: "-freg-struct-return");
6196 }
6197 }
6198
6199 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
6200 if (Triple.getArch() == llvm::Triple::m68k)
6201 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
6202 else
6203 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
6204 }
6205
6206 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
6207 // enable-matrix is needed by both the LangOpts and by LLVM.
6208 CmdArgs.push_back(Elt: "-fenable-matrix");
6209 CmdArgs.push_back(Elt: "-mllvm");
6210 CmdArgs.push_back(Elt: "-enable-matrix");
6211 // Only handle default layout if matrix is enabled
6212 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
6213 StringRef Val = A->getValue();
6214 if (Val == "row-major" || Val == "column-major") {
6215 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
6216 CmdArgs.push_back(Elt: "-mllvm");
6217 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
6218
6219 } else {
6220 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6221 }
6222 }
6223 }
6224
6225 CodeGenOptions::FramePointerKind FPKeepKind =
6226 getFramePointerKind(Args, Triple: RawTriple);
6227 const char *FPKeepKindStr = nullptr;
6228 switch (FPKeepKind) {
6229 case CodeGenOptions::FramePointerKind::None:
6230 FPKeepKindStr = "-mframe-pointer=none";
6231 break;
6232 case CodeGenOptions::FramePointerKind::Reserved:
6233 FPKeepKindStr = "-mframe-pointer=reserved";
6234 break;
6235 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
6236 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6237 break;
6238 case CodeGenOptions::FramePointerKind::NonLeaf:
6239 FPKeepKindStr = "-mframe-pointer=non-leaf";
6240 break;
6241 case CodeGenOptions::FramePointerKind::All:
6242 FPKeepKindStr = "-mframe-pointer=all";
6243 break;
6244 }
6245 assert(FPKeepKindStr && "unknown FramePointerKind");
6246 CmdArgs.push_back(Elt: FPKeepKindStr);
6247
6248 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
6249 Neg: options::OPT_fno_zero_initialized_in_bss);
6250
6251 bool OFastEnabled = isOptimizationLevelFast(Args);
6252 if (Args.hasArg(Ids: options::OPT_Ofast))
6253 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
6254 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6255 // enabled. This alias option is being used to simplify the hasFlag logic.
6256 OptSpecifier StrictAliasingAliasOption =
6257 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6258 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6259 // doesn't do any TBAA.
6260 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
6261 Neg: options::OPT_fno_strict_aliasing,
6262 Default: !IsWindowsMSVC && !IsUEFI))
6263 CmdArgs.push_back(Elt: "-relaxed-aliasing");
6264 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
6265 Default: false))
6266 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
6267 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
6268 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
6269 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
6270
6271 if (Arg *A = Args.getLastArg(Ids: options::OPT_fstrict_bool,
6272 Ids: options::OPT_fno_strict_bool,
6273 Ids: options::OPT_fno_strict_bool_EQ)) {
6274 StringRef BFM = "";
6275 if (A->getOption().matches(ID: options::OPT_fstrict_bool))
6276 BFM = "strict";
6277 else if (A->getOption().matches(ID: options::OPT_fno_strict_bool))
6278 BFM = "nonstrict";
6279 else if (A->getValue() == StringRef("truncate"))
6280 BFM = "truncate";
6281 else if (A->getValue() == StringRef("nonzero"))
6282 BFM = "nonzero";
6283 else
6284 D.Diag(DiagID: diag::err_drv_invalid_value)
6285 << A->getAsString(Args) << A->getValue();
6286 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-load-bool-from-mem=" + BFM));
6287 } else if (KernelOrKext) {
6288 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6289 CmdArgs.push_back(Elt: "-load-bool-from-mem=truncate");
6290 }
6291
6292 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
6293 Neg: options::OPT_fno_strict_enums);
6294 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
6295 Neg: options::OPT_fno_strict_return);
6296 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
6297 Neg: options::OPT_fno_allow_editor_placeholders);
6298 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
6299 Neg: options::OPT_fno_strict_vtable_pointers);
6300 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
6301 Neg: options::OPT_fno_force_emit_vtables);
6302 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
6303 Neg: options::OPT_fno_optimize_sibling_calls);
6304 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
6305 Neg: options::OPT_fno_escaping_block_tail_calls);
6306
6307 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
6308 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
6309
6310 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6311 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6312
6313 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6314 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6315
6316 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
6317 Ids: options::OPT_fno_disable_block_signature_string);
6318
6319 // Handle segmented stacks.
6320 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
6321 Neg: options::OPT_fno_split_stack);
6322
6323 // -fprotect-parens=0 is default.
6324 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
6325 Neg: options::OPT_fno_protect_parens, Default: false))
6326 CmdArgs.push_back(Elt: "-fprotect-parens");
6327
6328 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6329
6330 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
6331 Neg: options::OPT_fno_atomic_remote_memory);
6332 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
6333 Neg: options::OPT_fno_atomic_fine_grained_memory);
6334 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
6335 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
6336
6337 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
6338 const llvm::Triple::ArchType Arch = TC.getArch();
6339 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6340 StringRef V = A->getValue();
6341 if (V == "64")
6342 CmdArgs.push_back(Elt: "-fextend-arguments=64");
6343 else if (V != "32")
6344 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6345 << A->getValue() << A->getOption().getName();
6346 } else
6347 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6348 << A->getOption().getName() << TripleStr;
6349 }
6350
6351 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
6352 if (TC.getArch() == llvm::Triple::avr)
6353 A->render(Args, Output&: CmdArgs);
6354 else
6355 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6356 << A->getAsString(Args) << TripleStr;
6357 }
6358
6359 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
6360 if (TC.getTriple().isX86())
6361 A->render(Args, Output&: CmdArgs);
6362 else if (TC.getTriple().isPPC() &&
6363 (A->getOption().getID() != options::OPT_mlong_double_80))
6364 A->render(Args, Output&: CmdArgs);
6365 else
6366 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6367 << A->getAsString(Args) << TripleStr;
6368 }
6369
6370 // Decide whether to use verbose asm. Verbose assembly is the default on
6371 // toolchains which have the integrated assembler on by default.
6372 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6373 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
6374 Default: IsIntegratedAssemblerDefault))
6375 CmdArgs.push_back(Elt: "-fno-verbose-asm");
6376
6377 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6378 // use that to indicate the MC default in the backend.
6379 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
6380 StringRef V = A->getValue();
6381 unsigned Num;
6382 if (V == "none")
6383 A->render(Args, Output&: CmdArgs);
6384 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
6385 (V.empty() || (V.consume_front(Prefix: ".") &&
6386 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
6387 A->render(Args, Output&: CmdArgs);
6388 else
6389 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6390 << A->getValue() << A->getOption().getName();
6391 }
6392
6393 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6394 // option to disable integrated-as explicitly.
6395 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
6396 CmdArgs.push_back(Elt: "-no-integrated-as");
6397
6398 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
6399 CmdArgs.push_back(Elt: "-mdebug-pass");
6400 CmdArgs.push_back(Elt: "Structure");
6401 }
6402 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
6403 CmdArgs.push_back(Elt: "-mdebug-pass");
6404 CmdArgs.push_back(Elt: "Arguments");
6405 }
6406
6407 // Enable -mconstructor-aliases except on darwin, where we have to work around
6408 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6409 // code, where aliases aren't supported.
6410 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6411 CmdArgs.push_back(Elt: "-mconstructor-aliases");
6412
6413 // Darwin's kernel doesn't support guard variables; just die if we
6414 // try to use them.
6415 if (KernelOrKext && RawTriple.isOSDarwin())
6416 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
6417
6418 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
6419 Ids: options::OPT_mno_ms_bitfields)) {
6420 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
6421 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
6422 else
6423 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
6424 }
6425
6426 if (Triple.isOSCygMing()) {
6427 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
6428 Neg: options::OPT_fno_auto_import);
6429 }
6430
6431 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
6432 Default: Triple.isX86() && IsWindowsMSVC))
6433 CmdArgs.push_back(Elt: "-fms-volatile");
6434
6435 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6436 // defaults to -fno-direct-access-external-data. Pass the option if different
6437 // from the default.
6438 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
6439 Ids: options::OPT_fno_direct_access_external_data)) {
6440 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
6441 (PICLevel == 0))
6442 A->render(Args, Output&: CmdArgs);
6443 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6444 // Some targets default to -fno-direct-access-external-data even for
6445 // -fno-pic.
6446 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
6447 }
6448
6449 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6450 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
6451
6452 // -fhosted is default.
6453 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6454 // use Freestanding.
6455 bool Freestanding =
6456 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
6457 KernelOrKext;
6458 if (Freestanding)
6459 CmdArgs.push_back(Elt: "-ffreestanding");
6460
6461 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
6462
6463 BoundArch OffloadArch = JA.getOffloadingArch();
6464 auto SanitizeArgs =
6465 TC.getSanitizerArgs(JobArgs: Args, BA: OffloadArch, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6466 Args.AddLastArg(Output&: CmdArgs,
6467 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6468
6469 // This is a coarse approximation of what llvm-gcc actually does, both
6470 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6471 // complicated ways.
6472 bool IsAsyncUnwindTablesDefault =
6473 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6474 bool IsSyncUnwindTablesDefault =
6475 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6476
6477 bool AsyncUnwindTables = Args.hasFlag(
6478 Pos: options::OPT_fasynchronous_unwind_tables,
6479 Neg: options::OPT_fno_asynchronous_unwind_tables,
6480 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6481 !Freestanding);
6482 bool UnwindTables =
6483 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6484 Default: IsSyncUnwindTablesDefault && !Freestanding);
6485 if (AsyncUnwindTables)
6486 CmdArgs.push_back(Elt: "-funwind-tables=2");
6487 else if (UnwindTables)
6488 CmdArgs.push_back(Elt: "-funwind-tables=1");
6489
6490 // Sframe unwind tables are independent of the other types. Although also
6491 // defined for aarch64, only x86_64 support is implemented at the moment.
6492 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6493 if (Triple.isOSBinFormatELF() && Triple.isX86())
6494 CmdArgs.push_back(Elt: "--gsframe");
6495 else
6496 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6497 << A->getOption().getName() << TripleStr;
6498 }
6499
6500 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6501 // `--gpu-use-aux-triple-only` is specified.
6502 if (AuxTriple && !Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only)) {
6503 const ArgList &HostArgs =
6504 C.getArgsForToolChain(TC: nullptr, BA: BoundArch(), DeviceOffloadKind: Action::OFK_None);
6505 std::string HostCPU = getCPUName(D, Args: HostArgs, T: *AuxTriple, /*FromAs*/ false);
6506 if (!HostCPU.empty()) {
6507 CmdArgs.push_back(Elt: "-aux-target-cpu");
6508 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6509 }
6510 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6511 /*ForAS*/ false, /*IsAux*/ true);
6512 }
6513
6514 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
6515 DeviceOffloadKind: JA.getOffloadingDeviceKind());
6516
6517 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6518
6519 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6520 StringRef Value = A->getValue();
6521 unsigned TLSSize = 0;
6522 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6523 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6524 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6525 << A->getOption().getName() << TripleStr;
6526 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6527 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6528 << A->getOption().getName() << Value;
6529 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6530 }
6531
6532 if (isTLSDESCEnabled(TC, Args))
6533 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6534
6535 // Add the target cpu
6536 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6537 if (!CPU.empty()) {
6538 CmdArgs.push_back(Elt: "-target-cpu");
6539 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6540 }
6541
6542 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6543
6544 // Add clang-cl arguments.
6545 types::ID InputType = Input.getType();
6546 if (D.IsCLMode())
6547 AddClangCLArgs(Args, InputType, CmdArgs);
6548
6549 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6550 llvm::codegenoptions::NoDebugInfo;
6551 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6552 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6553 DebugInfoKind, DwarfFission, IsUsingLTO);
6554
6555 // Add the split debug info name to the command lines here so we
6556 // can propagate it to the backend.
6557 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6558 (TC.getTriple().isOSBinFormatELF() ||
6559 TC.getTriple().isOSBinFormatWasm() ||
6560 TC.getTriple().isOSBinFormatCOFF()) &&
6561 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6562 isa<BackendJobAction>(Val: JA));
6563 if (SplitDWARF) {
6564 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6565 CmdArgs.push_back(Elt: "-split-dwarf-file");
6566 CmdArgs.push_back(Elt: SplitDWARFOut);
6567 if (DwarfFission == DwarfFissionKind::Split) {
6568 CmdArgs.push_back(Elt: "-split-dwarf-output");
6569 CmdArgs.push_back(Elt: SplitDWARFOut);
6570 }
6571 }
6572
6573 // Pass the linker version in use.
6574 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6575 CmdArgs.push_back(Elt: "-target-linker-version");
6576 CmdArgs.push_back(Elt: A->getValue());
6577 }
6578
6579 // Explicitly error on some things we know we don't support and can't just
6580 // ignore.
6581 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6582 Arg *Unsupported;
6583 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6584 TC.getArch() == llvm::Triple::x86) {
6585 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6586 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6587 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6588 << Unsupported->getOption().getName();
6589 }
6590 // The faltivec option has been superseded by the maltivec option.
6591 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6592 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6593 << Unsupported->getOption().getName()
6594 << "please use -maltivec and include altivec.h explicitly";
6595 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6596 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6597 << Unsupported->getOption().getName() << "please use -mno-altivec";
6598 }
6599
6600 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6601
6602 if (Args.getLastArg(Ids: options::OPT_H)) {
6603 CmdArgs.push_back(Elt: "-H");
6604 CmdArgs.push_back(Elt: "-sys-header-deps");
6605 }
6606 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6607
6608 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6609 CmdArgs.push_back(Elt: "-header-include-file");
6610 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6611 ? D.CCPrintHeadersFilename.c_str()
6612 : "-");
6613 CmdArgs.push_back(Elt: "-sys-header-deps");
6614 CmdArgs.push_back(Elt: Args.MakeArgString(
6615 Str: "-header-include-format=" +
6616 Twine(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6617 CmdArgs.push_back(Elt: Args.MakeArgString(
6618 Str: "-header-include-filtering=" +
6619 Twine(headerIncludeFilteringKindToString(K: D.CCPrintHeadersFiltering))));
6620 }
6621 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6622 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6623
6624 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6625 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6626 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6627 ? D.CCLogDiagnosticsFilename.c_str()
6628 : "-");
6629 }
6630
6631 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6632 // crashes.
6633 if (D.CCGenDiagnostics)
6634 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6635
6636 // Allow backend to put its diagnostic files in the same place as frontend
6637 // crash diagnostics files.
6638 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6639 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6640 CmdArgs.push_back(Elt: "-mllvm");
6641 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6642 }
6643
6644 addSeparateSectionFlags(Triple, Args, CmdArgs);
6645
6646 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6647 Ids: options::OPT_fno_basic_block_address_map)) {
6648 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6649 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6650 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
6651 A->render(Args, Output&: CmdArgs);
6652 } else {
6653 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6654 << A->getAsString(Args) << TripleStr;
6655 }
6656 }
6657
6658 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6659 StringRef Val = A->getValue();
6660 if (Val == "labels") {
6661 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6662 << A->getAsString(Args) << /*hasReplacement=*/true
6663 << "-fbasic-block-address-map";
6664 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6665 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6666 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6667 D.Diag(DiagID: diag::err_drv_invalid_value)
6668 << A->getAsString(Args) << A->getValue();
6669 else
6670 A->render(Args, Output&: CmdArgs);
6671 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6672 // "all" is not supported on AArch64 since branch relaxation creates new
6673 // basic blocks for some cross-section branches.
6674 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6675 D.Diag(DiagID: diag::err_drv_invalid_value)
6676 << A->getAsString(Args) << A->getValue();
6677 else
6678 A->render(Args, Output&: CmdArgs);
6679 } else if (Triple.isNVPTX()) {
6680 // Do not pass the option to the GPU compilation. We still want it enabled
6681 // for the host-side compilation, so seeing it here is not an error.
6682 } else if (Val != "none") {
6683 // =none is allowed everywhere. It's useful for overriding the option
6684 // and is the same as not specifying the option.
6685 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6686 << A->getAsString(Args) << TripleStr;
6687 }
6688 }
6689
6690 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6691 Neg: options::OPT_fno_unique_section_names);
6692 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6693 Neg: options::OPT_fno_separate_named_sections);
6694 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6695 Neg: options::OPT_fno_unique_internal_linkage_names);
6696 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6697 Neg: options::OPT_fno_unique_basic_block_section_names);
6698
6699 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6700
6701 if (Arg *A =
6702 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6703 Ids: options::OPT_fno_partition_static_data_sections)) {
6704 if (!A->getOption().matches(
6705 ID: options::OPT_fno_partition_static_data_sections)) {
6706 // This codegen pass is only available on x86 and AArch64 ELF targets.
6707 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6708 A->render(Args, Output&: CmdArgs);
6709 CmdArgs.push_back(Elt: "-mllvm");
6710 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6711 } else
6712 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6713 << A->getAsString(Args) << TripleStr;
6714 }
6715 }
6716
6717 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6718 Ids: options::OPT_finstrument_functions_after_inlining,
6719 Ids: options::OPT_finstrument_function_entry_bare);
6720 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6721 Ids: options::OPT_fno_convergent_functions);
6722
6723 // NVPTX doesn't support PGO or coverage
6724 if (!Triple.isNVPTX())
6725 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6726
6727 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6728
6729 if (getLastProfileSampleUseArg(Args) &&
6730 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6731 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6732 CmdArgs.push_back(Elt: "-mllvm");
6733 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6734 }
6735
6736 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6737 if (RawTriple.isPS() &&
6738 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6739 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6740 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6741 }
6742
6743 // Pass options for controlling the default header search paths.
6744 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6745 CmdArgs.push_back(Elt: "-nostdsysteminc");
6746 CmdArgs.push_back(Elt: "-nobuiltininc");
6747 } else {
6748 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6749 CmdArgs.push_back(Elt: "-nostdsysteminc");
6750 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6751 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6752 }
6753
6754 // Pass the path to compiler resource files.
6755 CmdArgs.push_back(Elt: "-resource-dir");
6756 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6757
6758 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6759
6760 // Add preprocessing options like -I, -D, etc. if we are using the
6761 // preprocessor.
6762 //
6763 // FIXME: Support -fpreprocessed
6764 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6765 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6766
6767 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6768 // that "The compiler can only warn and ignore the option if not recognized".
6769 // When building with ccache, it will pass -D options to clang even on
6770 // preprocessed inputs and configure concludes that -fPIC is not supported.
6771 Args.ClaimAllArgs(Id0: options::OPT_D);
6772
6773 // Warn about ignored options to clang.
6774 for (const Arg *A :
6775 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6776 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6777 A->claim();
6778 }
6779
6780 for (const Arg *A :
6781 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6782 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6783 A->claim();
6784 }
6785
6786 claimNoWarnArgs(Args);
6787
6788 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6789
6790 for (const Arg *A :
6791 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6792 A->claim();
6793 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6794 unsigned WarningNumber;
6795 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6796 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6797 << A->getAsString(Args) << A->getValue();
6798 continue;
6799 }
6800
6801 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6802 CmdArgs.push_back(Elt: Args.MakeArgString(
6803 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6804 }
6805 continue;
6806 }
6807 A->render(Args, Output&: CmdArgs);
6808 }
6809
6810 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6811
6812 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6813 CmdArgs.push_back(Elt: "-pedantic");
6814 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6815 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6816
6817 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6818 Neg: options::OPT_fno_fixed_point);
6819
6820 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_overflow_behavior_types,
6821 Neg: options::OPT_fno_experimental_overflow_behavior_types);
6822
6823 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6824 A->render(Args, Output&: CmdArgs);
6825
6826 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6827 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6828
6829 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6830 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6831
6832 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6833 A->render(Args, Output&: CmdArgs);
6834
6835 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6836 // (-ansi is equivalent to -std=c89 or -std=c++98).
6837 //
6838 // If a std is supplied, only add -trigraphs if it follows the
6839 // option.
6840 bool ImplyVCPPCVer = false;
6841 bool ImplyVCPPCXXVer = false;
6842 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6843 if (Std) {
6844 if (Std->getOption().matches(ID: options::OPT_ansi))
6845 if (types::isCXX(Id: InputType))
6846 CmdArgs.push_back(Elt: "-std=c++98");
6847 else
6848 CmdArgs.push_back(Elt: "-std=c89");
6849 else {
6850 if (IsSYCL) {
6851 const LangStandard *LangStd =
6852 LangStandard::getLangStandardForName(Name: Std->getValue());
6853 if (LangStd) {
6854 // Use of -std= with 'C' is not supported for SYCL.
6855 if (LangStd->getLanguage() == Language::C)
6856 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
6857 << Std->getAsString(Args) << "-fsycl";
6858 // SYCL requires C++17 or later.
6859 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6860 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6861 }
6862 }
6863 Std->render(Args, Output&: CmdArgs);
6864 }
6865
6866 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6867 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6868 Ids: options::OPT_ftrigraphs,
6869 Ids: options::OPT_fno_trigraphs))
6870 if (A != Std)
6871 A->render(Args, Output&: CmdArgs);
6872 } else {
6873 // Honor -std-default.
6874 //
6875 // FIXME: Clang doesn't correctly handle -std= when the input language
6876 // doesn't match. For the time being just ignore this for C++ inputs;
6877 // eventually we want to do all the standard defaulting here instead of
6878 // splitting it between the driver and clang -cc1.
6879 if (!types::isCXX(Id: InputType)) {
6880 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6881 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6882 /*Joined=*/true);
6883 } else
6884 ImplyVCPPCVer = true;
6885 }
6886 else if (IsWindowsMSVC)
6887 ImplyVCPPCXXVer = true;
6888
6889 if (IsSYCL && types::isCXX(Id: InputType) &&
6890 !Args.hasArg(Ids: options::OPT__SLASH_std) && !IsWindowsMSVC)
6891 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6892 // on the command line will override. On Windows MSVC, this is handled
6893 // by the ImplyVCPPCXXVer path below.
6894 CmdArgs.push_back(Elt: "-std=c++17");
6895
6896 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6897 Ids: options::OPT_fno_trigraphs);
6898 }
6899
6900 // GCC's behavior for -Wwrite-strings is a bit strange:
6901 // * In C, this "warning flag" changes the types of string literals from
6902 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6903 // for the discarded qualifier.
6904 // * In C++, this is just a normal warning flag.
6905 //
6906 // Implementing this warning correctly in C is hard, so we follow GCC's
6907 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6908 // a non-const char* in C, rather than using this crude hack.
6909 if (!types::isCXX(Id: InputType)) {
6910 // FIXME: This should behave just like a warning flag, and thus should also
6911 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6912 Arg *WriteStrings =
6913 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6914 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6915 if (WriteStrings &&
6916 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6917 CmdArgs.push_back(Elt: "-fconst-strings");
6918 }
6919
6920 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6921 // during C++ compilation, which it is by default. GCC keeps this define even
6922 // in the presence of '-w', match this behavior bug-for-bug.
6923 if (types::isCXX(Id: InputType) &&
6924 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6925 Default: true)) {
6926 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6927 }
6928
6929 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6930 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6931 if (Asm->getOption().matches(ID: options::OPT_fasm))
6932 CmdArgs.push_back(Elt: "-fgnu-keywords");
6933 else
6934 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6935 }
6936
6937 if (!ShouldEnableAutolink(Args, TC, JA))
6938 CmdArgs.push_back(Elt: "-fno-autolink");
6939
6940 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6941 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6942 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6943 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6944
6945 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6946
6947 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6948 Args.ClaimAllArgs(Id0: options::OPT_fexperimental_new_constant_interpreter);
6949 Args.AddLastArg(Output&: CmdArgs,
6950 Ids: options::OPT_fno_experimental_new_constant_interpreter);
6951 } else {
6952 Args.ClaimAllArgs(Id0: options::OPT_fno_experimental_new_constant_interpreter);
6953 Args.AddLastArg(Output&: CmdArgs,
6954 Ids: options::OPT_fexperimental_new_constant_interpreter);
6955 }
6956
6957 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6958 CmdArgs.push_back(Elt: "-fbracket-depth");
6959 CmdArgs.push_back(Elt: A->getValue());
6960 }
6961
6962 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6963 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6964 if (A->getNumValues()) {
6965 StringRef bytes = A->getValue();
6966 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6967 } else
6968 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6969 }
6970
6971 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6972 CmdArgs.push_back(Elt: "-relocatable-pch");
6973 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fpch_base_dir_is_cwd);
6974
6975 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6976 static const char *kCFABIs[] = {
6977 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6978 };
6979
6980 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6981 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6982 else
6983 A->render(Args, Output&: CmdArgs);
6984 }
6985
6986 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6987 CmdArgs.push_back(Elt: "-fconstant-string-class");
6988 CmdArgs.push_back(Elt: A->getValue());
6989 }
6990
6991 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_array_class_EQ)) {
6992 CmdArgs.push_back(Elt: "-fconstant-array-class");
6993 CmdArgs.push_back(Elt: A->getValue());
6994 }
6995 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_dictionary_class_EQ)) {
6996 CmdArgs.push_back(Elt: "-fconstant-dictionary-class");
6997 CmdArgs.push_back(Elt: A->getValue());
6998 }
6999 if (Arg *A =
7000 Args.getLastArg(Ids: options::OPT_fconstant_integer_number_class_EQ)) {
7001 CmdArgs.push_back(Elt: "-fconstant-integer-number-class");
7002 CmdArgs.push_back(Elt: A->getValue());
7003 }
7004 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_float_number_class_EQ)) {
7005 CmdArgs.push_back(Elt: "-fconstant-float-number-class");
7006 CmdArgs.push_back(Elt: A->getValue());
7007 }
7008 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_double_number_class_EQ)) {
7009 CmdArgs.push_back(Elt: "-fconstant-double-number-class");
7010 CmdArgs.push_back(Elt: A->getValue());
7011 }
7012
7013 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
7014 CmdArgs.push_back(Elt: "-ftabstop");
7015 CmdArgs.push_back(Elt: A->getValue());
7016 }
7017
7018 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
7019 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
7020 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
7021
7022 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
7023 Neg: options::OPT_fno_stack_size_section);
7024
7025 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
7026 CmdArgs.push_back(Elt: "-stack-usage-file");
7027
7028 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
7029 SmallString<128> OutputFilename(OutputOpt->getValue());
7030 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
7031 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
7032 } else
7033 CmdArgs.push_back(
7034 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
7035 }
7036
7037 CmdArgs.push_back(Elt: "-ferror-limit");
7038 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
7039 CmdArgs.push_back(Elt: A->getValue());
7040 else
7041 CmdArgs.push_back(Elt: "19");
7042
7043 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
7044 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
7045 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
7046 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
7047 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
7048
7049 // Pass -fmessage-length=.
7050 unsigned MessageLength = 0;
7051 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
7052 StringRef V(A->getValue());
7053 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
7054 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7055 << V << A->getOption().getName();
7056 } else {
7057 // If -fmessage-length=N was not specified, determine whether this is a
7058 // terminal and, if so, implicitly define -fmessage-length appropriately.
7059 MessageLength = llvm::sys::Process::StandardErrColumns();
7060 }
7061 if (MessageLength != 0)
7062 CmdArgs.push_back(
7063 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
7064
7065 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
7066 CmdArgs.push_back(
7067 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
7068
7069 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
7070 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
7071 Twine(A->getValue(N: 0))));
7072
7073 // -fvisibility= and -fvisibility-ms-compat are of a piece.
7074 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
7075 Ids: options::OPT_fvisibility_ms_compat)) {
7076 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
7077 A->render(Args, Output&: CmdArgs);
7078 } else {
7079 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
7080 CmdArgs.push_back(Elt: "-fvisibility=hidden");
7081 CmdArgs.push_back(Elt: "-ftype-visibility=default");
7082 }
7083 } else if (IsOpenMPDevice) {
7084 // When compiling for the OpenMP device we want protected visibility by
7085 // default. This prevents the device from accidentally preempting code on
7086 // the host, makes the system more robust, and improves performance.
7087 CmdArgs.push_back(Elt: "-fvisibility=protected");
7088 }
7089
7090 // PS4/PS5 process these options in addClangTargetOptions.
7091 if (!RawTriple.isPS()) {
7092 if (const Arg *A =
7093 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
7094 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
7095 if (A->getOption().matches(
7096 ID: options::OPT_fvisibility_from_dllstorageclass)) {
7097 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
7098 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
7099 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
7100 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
7101 Args.AddLastArg(Output&: CmdArgs,
7102 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7103 }
7104 }
7105 }
7106
7107 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
7108 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
7109 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
7110
7111 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
7112 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
7113
7114 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7115 // -fvisibility-global-new-delete=force-hidden.
7116 if (const Arg *A =
7117 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7118 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
7119 << A->getAsString(Args) << /*hasReplacement=*/true
7120 << "-fvisibility-global-new-delete=force-hidden";
7121 }
7122
7123 if (const Arg *A =
7124 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
7125 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7126 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
7127 A->render(Args, Output&: CmdArgs);
7128 } else {
7129 assert(A->getOption().matches(
7130 options::OPT_fvisibility_global_new_delete_hidden));
7131 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
7132 }
7133 }
7134
7135 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
7136
7137 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
7138 Neg: options::OPT_fno_new_infallible, Default: false))
7139 CmdArgs.push_back(Elt: "-fnew-infallible");
7140
7141 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
7142 Neg: options::OPT_foperator_names, Default: false))
7143 CmdArgs.push_back(Elt: "-fno-operator-names");
7144
7145 // Forward -f (flag) options which we can pass directly.
7146 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
7147 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
7148 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
7149 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
7150 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
7151 Ids: options::OPT_fno_raw_string_literals);
7152
7153 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
7154 Default: Triple.hasDefaultEmulatedTLS()))
7155 CmdArgs.push_back(Elt: "-femulated-tls");
7156
7157 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
7158 Neg: options::OPT_fno_check_new);
7159
7160 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
7161 // FIXME: There's no reason for this to be restricted to some backend.
7162 // The backend code needs to be changed to include the appropriate function
7163 // calls automatically.
7164 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7165 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7166 << A->getAsString(Args) << TripleStr;
7167 }
7168
7169 // AltiVec-like language extensions aren't relevant for assembling.
7170 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
7171 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
7172
7173 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
7174 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
7175
7176 // Forward flags for OpenMP. We don't do this if the current action is an
7177 // device offloading action other than OpenMP.
7178 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
7179 Neg: options::OPT_fno_openmp, Default: false) &&
7180 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7181 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
7182 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
7183 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
7184
7185 // Determine if target-fast optimizations should be enabled
7186 bool TargetFastUsed =
7187 Args.hasFlag(Pos: options::OPT_fopenmp_target_fast,
7188 Neg: options::OPT_fno_openmp_target_fast, Default: OFastEnabled);
7189 switch (D.getOpenMPRuntime(Args)) {
7190 case Driver::OMPRT_OMP:
7191 case Driver::OMPRT_IOMP5:
7192 // Clang can generate useful OpenMP code for these two runtime libraries.
7193 CmdArgs.push_back(Elt: "-fopenmp");
7194
7195 // If no option regarding the use of TLS in OpenMP codegeneration is
7196 // given, decide a default based on the target. Otherwise rely on the
7197 // options and pass the right information to the frontend.
7198 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
7199 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7200 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
7201 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7202 Ids: options::OPT_fno_openmp_simd);
7203 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
7204 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7205 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
7206 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
7207 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
7208 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
7209 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7210 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7211 // effect: the teams reduction buffer is sized at kernel launch by the
7212 // offload plugin to match the actual number of teams. Honoring a
7213 // smaller user-supplied value would silently truncate the buffer for
7214 // larger launches.
7215 if (Arg *A = Args.getLastArg(
7216 Ids: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7217 D.Diag(DiagID: diag::warn_drv_deprecated_custom)
7218 << A->getAsString(Args)
7219 << "the value is ignored; the teams reduction buffer is sized "
7220 "automatically at kernel launch";
7221 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
7222 Neg: options::OPT_fno_openmp_optimistic_collapse,
7223 /*Default=*/false))
7224 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
7225
7226 // When in OpenMP offloading mode with NVPTX target, forward
7227 // cuda-mode flag
7228 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
7229 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7230 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
7231
7232 // When in OpenMP offloading mode, enable debugging on the device.
7233 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
7234 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
7235 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
7236 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
7237
7238 // When in OpenMP offloading mode, forward assumptions information about
7239 // thread and team counts in the device.
7240 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
7241 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
7242 /*Default=*/TargetFastUsed))
7243 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
7244 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
7245 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
7246 /*Default=*/TargetFastUsed))
7247 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
7248
7249 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7250 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_thread_state,
7251 Neg: options::OPT_fno_openmp_assume_no_thread_state,
7252 /*Default=*/TargetFastUsed))
7253 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
7254
7255 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7256 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_nested_parallelism,
7257 Neg: options::OPT_fno_openmp_assume_no_nested_parallelism,
7258 /*Default=*/TargetFastUsed))
7259 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
7260
7261 // Handle -fopenmp-target-atomic-reduction.
7262 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_atomic_reduction,
7263 Neg: options::OPT_fno_openmp_target_atomic_reduction,
7264 /*Default=*/false))
7265 CmdArgs.push_back(Elt: "-fopenmp-target-atomic-reduction");
7266
7267 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
7268 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
7269 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
7270 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
7271 break;
7272 default:
7273 // By default, if Clang doesn't know how to generate useful OpenMP code
7274 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7275 // down to the actual compilation.
7276 // FIXME: It would be better to have a mode which *only* omits IR
7277 // generation based on the OpenMP support so that we get consistent
7278 // semantic analysis, etc.
7279 break;
7280 }
7281 } else {
7282 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7283 Ids: options::OPT_fno_openmp_simd);
7284 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7285 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
7286 Neg: options::OPT_fno_openmp_extensions);
7287 }
7288 // Forward '-foffload-via-llvm' to code generation to target the LLVM/Offload
7289 // runtime.
7290 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7291 Neg: options::OPT_fno_offload_via_llvm, Default: false))
7292 CmdArgs.push_back(Elt: "-foffload-via-llvm");
7293
7294 const XRayArgs &XRay = TC.getXRayArgs(Args);
7295 XRay.addArgs(TC, Args, CmdArgs, InputType);
7296
7297 for (const auto &Filename :
7298 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
7299 if (D.getVFS().exists(Path: Filename))
7300 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
7301 else
7302 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
7303 }
7304
7305 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
7306 StringRef S0 = A->getValue(), S = S0;
7307 unsigned Size, Offset = 0;
7308 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7309 !Triple.isX86() && !Triple.isSystemZ() &&
7310 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7311 Triple.getArch() == llvm::Triple::ppc64 ||
7312 Triple.getArch() == llvm::Triple::ppc64le)))
7313 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7314 << A->getAsString(Args) << TripleStr;
7315 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
7316 (!S.empty() &&
7317 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
7318 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
7319 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7320 << S0 << A->getOption().getName();
7321 else if (Size < Offset)
7322 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
7323 else {
7324 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
7325 CmdArgs.push_back(Elt: Args.MakeArgString(
7326 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
7327 if (!S.empty())
7328 CmdArgs.push_back(
7329 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
7330 }
7331 }
7332
7333 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
7334
7335 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
7336 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
7337
7338 for (const auto &A :
7339 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
7340 CmdArgs.push_back(
7341 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
7342
7343 if (TC.SupportsProfiling()) {
7344 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
7345
7346 llvm::Triple::ArchType Arch = TC.getArch();
7347 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
7348 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7349 A->render(Args, Output&: CmdArgs);
7350 else
7351 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7352 << A->getAsString(Args) << TripleStr;
7353 }
7354 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
7355 if (Arch == llvm::Triple::systemz ||
7356 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7357 A->render(Args, Output&: CmdArgs);
7358 else
7359 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7360 << A->getAsString(Args) << TripleStr;
7361 }
7362 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
7363 if (Arch == llvm::Triple::systemz ||
7364 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7365 A->render(Args, Output&: CmdArgs);
7366 else
7367 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7368 << A->getAsString(Args) << TripleStr;
7369 }
7370 }
7371
7372 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
7373 if (TC.getTriple().isOSzOS()) {
7374 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7375 << A->getAsString(Args) << TripleStr;
7376 }
7377 }
7378 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
7379 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7380 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7381 << A->getAsString(Args) << TripleStr;
7382 }
7383 }
7384 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
7385 if (A->getOption().matches(ID: options::OPT_p)) {
7386 A->claim();
7387 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
7388 CmdArgs.push_back(Elt: "-pg");
7389 }
7390 }
7391
7392 // Reject AIX-specific link options on other targets.
7393 if (!TC.getTriple().isOSAIX()) {
7394 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
7395 Ids: options::OPT_mxcoff_build_id_EQ)) {
7396 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7397 << A->getSpelling() << TripleStr;
7398 }
7399 }
7400
7401 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
7402 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
7403 CmdArgs.push_back(Elt: "-fapple-kext");
7404
7405 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
7406 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
7407 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
7408 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
7409 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
7410 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
7411 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
7412 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
7413 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
7414 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
7415 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
7416
7417 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
7418 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
7419 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
7420 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
7421 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_compress_EQ);
7422 }
7423
7424 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
7425 CmdArgs.push_back(Elt: "-ftrapv-handler");
7426 CmdArgs.push_back(Elt: A->getValue());
7427 }
7428
7429 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
7430
7431 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
7432 Ids: options::OPT_fno_finite_loops);
7433
7434 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
7435 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
7436 Ids: options::OPT_fno_unroll_loops);
7437 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
7438 Ids: options::OPT_fno_loop_interchange);
7439 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
7440 Neg: options::OPT_fno_experimental_loop_fusion);
7441
7442 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
7443
7444 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
7445
7446 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
7447 Neg: options::OPT_mno_speculative_load_hardening);
7448
7449 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7450 RenderSCPOptions(TC, Args, CmdArgs);
7451 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7452
7453 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
7454
7455 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
7456 Neg: options::OPT_mno_stackrealign);
7457
7458 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
7459 StringRef Value = A->getValue();
7460 int64_t Alignment = 0;
7461 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
7462 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7463 << Value << A->getOption().getName();
7464 else if (Alignment & (Alignment - 1))
7465 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
7466 << A->getAsString(Args) << Value;
7467 else
7468 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
7469 }
7470
7471 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
7472 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
7473
7474 if (!Size.empty())
7475 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
7476 else
7477 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
7478 }
7479
7480 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
7481 Neg: options::OPT_mno_stack_arg_probe);
7482
7483 if (Arg *A = Args.getLastArg(Ids: options::OPT_msmall_int_abi_compat_EQ))
7484 A->render(Args, Output&: CmdArgs);
7485
7486 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
7487 Ids: options::OPT_mno_restrict_it)) {
7488 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
7489 CmdArgs.push_back(Elt: "-mllvm");
7490 CmdArgs.push_back(Elt: "-arm-restrict-it");
7491 } else {
7492 CmdArgs.push_back(Elt: "-mllvm");
7493 CmdArgs.push_back(Elt: "-arm-default-it");
7494 }
7495 }
7496
7497 // Forward -cl options to -cc1
7498 RenderOpenCLOptions(Args, CmdArgs, InputType);
7499
7500 // Forward hlsl options to -cc1
7501 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7502
7503 // Forward OpenACC options to -cc1
7504 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7505
7506 if (IsHIP) {
7507 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
7508 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
7509 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
7510 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
7511 Neg: options::OPT_fno_gpu_allow_device_init);
7512 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
7513 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
7514 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
7515 Neg: options::OPT_fno_hip_kernel_arg_name);
7516 if (TC.getTriple().isSPIRV() &&
7517 TC.getTriple().getVendor() == llvm::Triple::VendorType::AMD)
7518 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fenable_spirv_size_optimization);
7519 }
7520
7521 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7522 CmdArgs.push_back(Elt: "-fgpu-rdc");
7523
7524 if (IsCuda || IsHIP) {
7525 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
7526 Neg: options::OPT_fno_gpu_defer_diag);
7527 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
7528 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
7529 Default: false)) {
7530 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
7531 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
7532 }
7533 }
7534
7535 // Forward --no-offloadlib to -cc1.
7536 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7537 CmdArgs.push_back(Elt: "--no-offloadlib");
7538
7539 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7540 CmdArgs.push_back(
7541 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7542
7543 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7544 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7545 SA->getValue()));
7546 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7547 // Emit IBT endbr64 instructions by default
7548 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7549 // jump-table can generate indirect jumps, which are not permitted
7550 CmdArgs.push_back(Elt: "-fno-jump-tables");
7551 }
7552
7553 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7554 CmdArgs.push_back(
7555 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7556
7557 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7558
7559 // Forward -f options with positive and negative forms; we translate these by
7560 // hand. Do not propagate PGO options to the GPU-side compilations as the
7561 // profile info is for the host-side compilation only.
7562 if (!(IsCudaDevice || IsHIPDevice)) {
7563 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7564 auto *PGOArg = Args.getLastArg(
7565 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7566 Ids: options::OPT_fcs_profile_generate,
7567 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7568 Ids: options::OPT_fprofile_use_EQ);
7569 if (PGOArg)
7570 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7571 << "SampleUse with PGO options";
7572
7573 StringRef fname = A->getValue();
7574 if (!llvm::sys::fs::exists(Path: fname))
7575 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7576 else
7577 A->render(Args, Output&: CmdArgs);
7578 }
7579 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7580
7581 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7582 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7583 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7584 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7585 // off.
7586 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7587 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7588 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7589 }
7590 }
7591 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7592
7593 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7594 Neg: options::OPT_fno_assume_sane_operator_new);
7595
7596 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7597 CmdArgs.push_back(Elt: "-fapinotes");
7598 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7599 Neg: options::OPT_fno_apinotes_modules, Default: false))
7600 CmdArgs.push_back(Elt: "-fapinotes-modules");
7601 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7602
7603 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7604 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7605 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7606
7607 // -fblocks=0 is default.
7608 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7609 Default: TC.IsBlocksDefault()) ||
7610 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7611 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7612 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7613 CmdArgs.push_back(Elt: "-fblocks");
7614
7615 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7616 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7617 }
7618
7619 // -fencode-extended-block-signature=1 is default.
7620 if (TC.IsEncodeExtendedBlockSignatureDefault())
7621 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7622
7623 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7624 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7625 types::isCXX(Id: InputType))
7626 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7627
7628 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7629 /*Default=*/false))
7630 CmdArgs.push_back(Elt: "-fdefer-ts");
7631
7632 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7633 Ids: options::OPT_fno_double_square_bracket_attributes);
7634
7635 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7636 Neg: options::OPT_fno_access_control);
7637 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7638 Neg: options::OPT_fno_elide_constructors);
7639
7640 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7641
7642 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7643 (RTTIMode == ToolChain::RM_Disabled)))
7644 CmdArgs.push_back(Elt: "-fno-rtti");
7645
7646 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7647 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7648 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7649 CmdArgs.push_back(Elt: "-fshort-enums");
7650
7651 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7652
7653 // -fuse-cxa-atexit is default.
7654 if (!Args.hasFlag(
7655 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7656 Default: !RawTriple.isOSAIX() &&
7657 (!RawTriple.isOSWindows() ||
7658 RawTriple.isWindowsCygwinEnvironment()) &&
7659 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7660 RawTriple.hasEnvironment())) ||
7661 KernelOrKext)
7662 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7663
7664 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7665 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7666 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7667 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7668
7669 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7670 Neg: options::OPT_fno_use_line_directives);
7671
7672 // -fno-minimize-whitespace is default.
7673 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7674 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7675 types::ID InputType = Inputs[0].getType();
7676 if (!isDerivedFromC(Id: InputType))
7677 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7678 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7679 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7680 }
7681
7682 // -fno-keep-system-includes is default.
7683 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7684 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7685 types::ID InputType = Inputs[0].getType();
7686 if (!isDerivedFromC(Id: InputType))
7687 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7688 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7689 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7690 }
7691
7692 // -fms-extensions=0 is default.
7693 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7694 Default: IsWindowsMSVC || IsUEFI))
7695 CmdArgs.push_back(Elt: "-fms-extensions");
7696
7697 // -fms-compatibility=0 is default.
7698 bool IsMSVCCompat = Args.hasFlag(
7699 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7700 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7701 Neg: options::OPT_fno_ms_extensions, Default: true)));
7702 if (IsMSVCCompat) {
7703 CmdArgs.push_back(Elt: "-fms-compatibility");
7704 if (!types::isCXX(Id: Input.getType()) &&
7705 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7706 CmdArgs.push_back(Elt: "-fms-define-stdc");
7707 }
7708
7709 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7710 // clang and flang.
7711 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7712
7713 // -fms-anonymous-structs is disabled by default.
7714 // Determine whether to enable Microsoft named anonymous struct/union support.
7715 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7716 // where the feature can be:
7717 // - Explicitly enabled via -fms-anonymous-structs.
7718 // - Explicitly disabled via fno-ms-anonymous-structs
7719 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7720 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7721 //
7722 // When multiple relevent options are present, the last option on the command
7723 // line takes precedence. This allows users to selectively override implicit
7724 // enablement. Examples:
7725 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7726 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7727 auto MSAnonymousStructsOptionToUseOrNull =
7728 [](const ArgList &Args) -> const char * {
7729 const char *Option = nullptr;
7730 constexpr const char *Enable = "-fms-anonymous-structs";
7731 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7732
7733 // Iterate through all arguments in order to implement "last flag wins".
7734 for (const Arg *A : Args) {
7735 switch (A->getOption().getID()) {
7736 case options::OPT_fms_anonymous_structs:
7737 A->claim();
7738 Option = Enable;
7739 break;
7740 case options::OPT_fno_ms_anonymous_structs:
7741 A->claim();
7742 Option = Disable;
7743 break;
7744 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7745 // feature.
7746 case options::OPT_fms_extensions:
7747 case options::OPT_fms_compatibility:
7748 Option = Enable;
7749 break;
7750 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7751 // disables the feature.
7752 case options::OPT_fno_ms_extensions:
7753 case options::OPT_fno_ms_compatibility:
7754 Option = Disable;
7755 break;
7756 default:
7757 break;
7758 }
7759 }
7760 return Option;
7761 };
7762
7763 // Only pass a flag to CC1 if a relevant option was seen
7764 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7765 CmdArgs.push_back(Elt: MSAnonOpt);
7766
7767 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7768 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7769 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7770
7771 // Handle -fgcc-version, if present.
7772 VersionTuple GNUCVer;
7773 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7774 // Check that the version has 1 to 3 components and the minor and patch
7775 // versions fit in two decimal digits.
7776 StringRef Val = A->getValue();
7777 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7778 bool Invalid = GNUCVer.tryParse(string: Val);
7779 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7780 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7781 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7782 D.Diag(DiagID: diag::err_drv_invalid_value)
7783 << A->getAsString(Args) << A->getValue();
7784 }
7785 } else if (!IsMSVCCompat) {
7786 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7787 GNUCVer = VersionTuple(4, 2, 1);
7788 }
7789 if (!GNUCVer.empty()) {
7790 CmdArgs.push_back(
7791 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7792 }
7793
7794 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7795 if (!MSVT.empty())
7796 CmdArgs.push_back(
7797 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7798
7799 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7800 if (ImplyVCPPCVer) {
7801 StringRef LanguageStandard;
7802 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7803 Std = StdArg;
7804 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7805 .Case(S: "c11", Value: "-std=c11")
7806 .Case(S: "c17", Value: "-std=c17")
7807 // If you add cases below for spellings that are
7808 // not in LangStandards.def, update
7809 // TransferableCommand::tryParseStdArg() in
7810 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7811 // to match.
7812 // TODO: add c23 when MSVC supports it.
7813 .Case(S: "clatest", Value: "-std=c23")
7814 .Default(Value: "");
7815 if (LanguageStandard.empty())
7816 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7817 << StdArg->getAsString(Args);
7818 }
7819 CmdArgs.push_back(Elt: LanguageStandard.data());
7820 }
7821 if (ImplyVCPPCXXVer) {
7822 StringRef LanguageStandard;
7823 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7824 Std = StdArg;
7825 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7826 .Case(S: "c++14", Value: "-std=c++14")
7827 .Case(S: "c++17", Value: "-std=c++17")
7828 .Case(S: "c++20", Value: "-std=c++20")
7829 .Case(S: "c++23", Value: "-std=c++23")
7830 // If you add cases below for spellings that are
7831 // not in LangStandards.def, update
7832 // TransferableCommand::tryParseStdArg() in
7833 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7834 // to match.
7835 // TODO add c++26, c++29 when MSVC supports
7836 // it.
7837 .Case(S: "c++23preview", Value: "-std=c++23")
7838 .Case(S: "c++26preview", Value: "-std=c++26")
7839 .Case(S: "c++latest", Value: "-std=c++2d")
7840 .Default(Value: "");
7841 if (IsSYCL) {
7842 const LangStandard *LangStd =
7843 LangStandard::getLangStandardForName(Name: StdArg->getValue());
7844 if (LangStd) {
7845 // Use of /std: with 'C' is not supported for SYCL.
7846 if (LangStd->getLanguage() == Language::C)
7847 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7848 << StdArg->getAsString(Args) << "-fsycl";
7849 // SYCL requires C++17 or later.
7850 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7851 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17)
7852 << StdArg->getAsString(Args);
7853 }
7854 }
7855 if (LanguageStandard.empty())
7856 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7857 << StdArg->getAsString(Args);
7858 }
7859
7860 if (LanguageStandard.empty()) {
7861 if (IsSYCL)
7862 // For SYCL, C++17 is the default.
7863 LanguageStandard = "-std=c++17";
7864 else if (IsMSVC2015Compatible)
7865 LanguageStandard = "-std=c++14";
7866 else
7867 LanguageStandard = "-std=c++11";
7868 }
7869
7870 CmdArgs.push_back(Elt: LanguageStandard.data());
7871 }
7872
7873 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7874 Neg: options::OPT_fno_borland_extensions);
7875
7876 // -fno-declspec is default, except for PS4/PS5.
7877 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7878 Default: RawTriple.isPS()))
7879 CmdArgs.push_back(Elt: "-fdeclspec");
7880 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7881 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7882
7883 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7884 // than 19.
7885 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7886 Neg: options::OPT_fno_threadsafe_statics,
7887 Default: !types::isOpenCL(Id: InputType) &&
7888 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7889 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7890
7891 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7892 Default: true))
7893 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7894
7895 // Add -fno-assumptions, if it was specified.
7896 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7897 Default: true))
7898 CmdArgs.push_back(Elt: "-fno-assumptions");
7899
7900 // -fgnu-keywords default varies depending on language; only pass if
7901 // specified.
7902 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7903 Ids: options::OPT_fno_gnu_keywords);
7904
7905 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7906 Neg: options::OPT_fno_gnu89_inline);
7907
7908 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7909 Ids: options::OPT_finline_hint_functions,
7910 Ids: options::OPT_fno_inline_functions);
7911 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7912 if (A->getOption().matches(ID: options::OPT_fno_inline))
7913 A->render(Args, Output&: CmdArgs);
7914 } else if (InlineArg) {
7915 InlineArg->render(Args, Output&: CmdArgs);
7916 }
7917
7918 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7919
7920 // FIXME: Find a better way to determine whether we are in C++20.
7921 bool HaveCxx20 =
7922 Std &&
7923 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7924 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7925 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7926 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7927 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7928 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7929 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++26preview") ||
7930 Std->containsValue(Value: "c++2d") || Std->containsValue(Value: "gnu++2d") ||
7931 Std->containsValue(Value: "c++latest") || Std->containsValue(Value: "gnu++latest"));
7932 bool HaveModules =
7933 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7934
7935 // -fdelayed-template-parsing is default when targeting MSVC.
7936 // Many old Windows SDK versions require this to parse.
7937 //
7938 // According to
7939 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7940 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7941 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7942 // not enable -fdelayed-template-parsing by default after C++20.
7943 //
7944 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7945 // able to disable this by default at some point.
7946 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7947 Neg: options::OPT_fno_delayed_template_parsing,
7948 Default: IsWindowsMSVC && !HaveCxx20)) {
7949 if (HaveCxx20)
7950 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7951
7952 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7953 }
7954
7955 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7956 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7957 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7958 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7959 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7960 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7961 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7962 Default: false))
7963 CmdArgs.push_back(Elt: "-fmodules-codegen");
7964 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7965 Default: false))
7966 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7967
7968 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7969 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7970 Input, CmdArgs);
7971
7972 if (types::isObjC(Id: Input.getType()) &&
7973 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7974 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7975 Default: !Runtime.isNeXTFamily()))
7976 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7977
7978 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7979 Neg: options::OPT_fno_application_extension, Default: false))
7980 CmdArgs.push_back(Elt: "-fapplication-extension");
7981
7982 // Handle GCC-style exception args.
7983 bool EH = false;
7984 if (!C.getDriver().IsCLMode())
7985 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7986 IsDeviceOffloadAction, objcRuntime: Runtime, CmdArgs);
7987
7988 // Handle exception personalities
7989 Arg *A = Args.getLastArg(
7990 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7991 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions,
7992 Ids: options::OPT_femscripten_exceptions);
7993 if (A) {
7994 const Option &Opt = A->getOption();
7995 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7996 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7997 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7998 CmdArgs.push_back(Elt: "-exception-model=seh");
7999 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
8000 CmdArgs.push_back(Elt: "-exception-model=dwarf");
8001 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
8002 CmdArgs.push_back(Elt: "-exception-model=wasm");
8003 if (Opt.matches(ID: options::OPT_femscripten_exceptions))
8004 CmdArgs.push_back(Elt: "-exception-model=emscripten");
8005 } else {
8006 switch (TC.GetExceptionModel(Args)) {
8007 default:
8008 break;
8009 case llvm::ExceptionHandling::DwarfCFI:
8010 CmdArgs.push_back(Elt: "-exception-model=dwarf");
8011 break;
8012 case llvm::ExceptionHandling::SjLj:
8013 CmdArgs.push_back(Elt: "-exception-model=sjlj");
8014 break;
8015 case llvm::ExceptionHandling::WinEH:
8016 CmdArgs.push_back(Elt: "-exception-model=seh");
8017 break;
8018 }
8019 }
8020
8021 // Unwind information version for x64 Windows.
8022 // Forward the new unified flag if present, otherwise translate legacy flags.
8023 if (const Arg *A = Args.getLastArg(Ids: options::OPT_winx64_eh_unwind_EQ)) {
8024 A->claim();
8025 CmdArgs.push_back(
8026 Elt: Args.MakeArgString(Str: Twine("-fwinx64-eh-unwind=") + A->getValue()));
8027 } else if (const Arg *A =
8028 Args.getLastArg(Ids: options::OPT_winx64_eh_unwindv2_EQ)) {
8029 A->claim();
8030 StringRef Val = A->getValue();
8031 if (Val == "best-effort")
8032 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
8033 else if (Val == "required")
8034 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
8035 // "disabled" maps to v1 default, nothing to forward.
8036 else if (Val != "disabled")
8037 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
8038 }
8039
8040 // Control Flow Guard mechanism for Windows.
8041 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_win_cfg_mechanism);
8042
8043 // C++ "sane" operator new.
8044 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
8045 Neg: options::OPT_fno_assume_sane_operator_new);
8046
8047 // -fassume-unique-vtables is on by default.
8048 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
8049 Neg: options::OPT_fno_assume_unique_vtables);
8050
8051 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
8052 // by default.
8053 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
8054 Ids: options::OPT_fno_sized_deallocation);
8055
8056 // -faligned-allocation is on by default in C++17 onwards and otherwise off
8057 // by default.
8058 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
8059 Ids: options::OPT_fno_aligned_allocation,
8060 Ids: options::OPT_faligned_new_EQ)) {
8061 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
8062 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
8063 else
8064 CmdArgs.push_back(Elt: "-faligned-allocation");
8065 }
8066
8067 // The default new alignment can be specified using a dedicated option or via
8068 // a GCC-compatible option that also turns on aligned allocation.
8069 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
8070 Ids: options::OPT_faligned_new_EQ))
8071 CmdArgs.push_back(
8072 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
8073
8074 // -fconstant-cfstrings is default, and may be subject to argument translation
8075 // on Darwin.
8076 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
8077 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
8078 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
8079 Neg: options::OPT_mno_constant_cfstrings, Default: true))
8080 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
8081
8082 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
8083 Neg: options::OPT_fno_pascal_strings);
8084
8085 // Honor -fpack-struct= and -fpack-struct, if given. Note that
8086 // -fno-pack-struct doesn't apply to -fpack-struct=.
8087 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
8088 CmdArgs.push_back(
8089 Elt: Args.MakeArgString(Str: "-fpack-struct=" + Twine(A->getValue())));
8090 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
8091 Neg: options::OPT_fno_pack_struct, Default: false)) {
8092 CmdArgs.push_back(Elt: "-fpack-struct=1");
8093 }
8094
8095 // Handle -fmax-type-align=N and -fno-type-align
8096 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
8097 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
8098 if (!SkipMaxTypeAlign) {
8099 std::string MaxTypeAlignStr = "-fmax-type-align=";
8100 MaxTypeAlignStr += A->getValue();
8101 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
8102 }
8103 } else if (RawTriple.isOSDarwin()) {
8104 if (!SkipMaxTypeAlign) {
8105 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8106 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
8107 }
8108 }
8109
8110 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
8111 CmdArgs.push_back(Elt: "-Qn");
8112
8113 // -fno-common is the default, set -fcommon only when that flag is set.
8114 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
8115
8116 // -fsigned-bitfields is default, and clang doesn't yet support
8117 // -funsigned-bitfields.
8118 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
8119 Neg: options::OPT_funsigned_bitfields, Default: true))
8120 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
8121 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
8122
8123 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8124 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
8125 D.Diag(DiagID: diag::err_drv_clang_unsupported)
8126 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
8127
8128 // -finput_charset=UTF-8 is default. Reject others
8129 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
8130 StringRef value = inputCharset->getValue();
8131 if (!value.equals_insensitive(RHS: "utf-8"))
8132 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8133 << value;
8134 }
8135
8136 // -fexec_charset=UTF-8 is default. Reject others
8137 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
8138 StringRef value = execCharset->getValue();
8139 if (!value.equals_insensitive(RHS: "utf-8"))
8140 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8141 << value;
8142 }
8143
8144 RenderDiagnosticsOptions(D, Args, CmdArgs);
8145
8146 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
8147 Neg: options::OPT_fno_asm_blocks);
8148
8149 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
8150 Neg: options::OPT_fno_gnu_inline_asm);
8151
8152 handleVectorizeLoopsArgs(Args, CmdArgs);
8153 handleVectorizeSLPArgs(Args, CmdArgs);
8154
8155 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
8156 if (!VecWidth.empty())
8157 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
8158
8159 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
8160 Args.AddLastArg(Output&: CmdArgs,
8161 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
8162
8163 // -fdollars-in-identifiers default varies depending on platform and
8164 // language; only pass if specified.
8165 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
8166 Ids: options::OPT_fno_dollars_in_identifiers)) {
8167 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
8168 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
8169 else
8170 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
8171 }
8172
8173 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
8174 Neg: options::OPT_fno_apple_pragma_pack);
8175
8176 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8177 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8178 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8179
8180 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
8181 Neg: options::OPT_fno_rewrite_imports, Default: false);
8182 if (RewriteImports)
8183 CmdArgs.push_back(Elt: "-frewrite-imports");
8184
8185 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
8186 Neg: options::OPT_fno_directives_only);
8187
8188 // Enable rewrite includes if the user's asked for it or if we're generating
8189 // diagnostics.
8190 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8191 // nice to enable this when doing a crashdump for modules as well.
8192 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
8193 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
8194 (C.isForDiagnostics() && !HaveModules))
8195 CmdArgs.push_back(Elt: "-frewrite-includes");
8196
8197 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
8198 Neg: options::OPT_fno_zos_extensions, Default: false))
8199 CmdArgs.push_back(Elt: "-fzos-extensions");
8200 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
8201 CmdArgs.push_back(Elt: "-fno-zos-extensions");
8202
8203 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8204 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
8205 Ids: options::OPT_traditional_cpp)) {
8206 if (isa<PreprocessJobAction>(Val: JA))
8207 CmdArgs.push_back(Elt: "-traditional-cpp");
8208 else
8209 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
8210 }
8211
8212 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
8213 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
8214 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
8215
8216 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
8217
8218 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_extract_summaries);
8219 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_tu_summary_file);
8220 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_compilation_unit_id);
8221 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_include_local_entities);
8222 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_no_extract_from_system_headers);
8223 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_source_transformation);
8224 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_global_scope_analysis_result);
8225 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_link_unit_id);
8226 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_src_edit_file);
8227 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_transformation_report_file);
8228
8229 // Handle serialized diagnostics.
8230 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
8231 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
8232 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
8233 }
8234
8235 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
8236 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
8237
8238 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
8239 A->render(Args, Output&: CmdArgs);
8240 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
8241 A && A->containsValue(Value: "g")) {
8242 // Set -fextend-variable-liveness=all by default at -Og.
8243 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
8244 }
8245
8246 // Forward -fcomment-block-commands to -cc1.
8247 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
8248 // Forward -fparse-all-comments to -cc1.
8249 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
8250 // Forward -fretain-comments to -cc1.
8251 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fretain_comments);
8252
8253 // Turn -fplugin=name.so into -load name.so
8254 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
8255 CmdArgs.push_back(Elt: "-load");
8256 CmdArgs.push_back(Elt: A->getValue());
8257 A->claim();
8258 }
8259
8260 // Turn -fplugin-arg-pluginname-key=value into
8261 // -plugin-arg-pluginname key=value
8262 // GCC has an actual plugin_argument struct with key/value pairs that it
8263 // passes to its plugins, but we don't, so just pass it on as-is.
8264 //
8265 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8266 // argument key are allowed to contain dashes. GCC therefore only
8267 // allows dashes in the key. We do the same.
8268 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
8269 auto ArgValue = StringRef(A->getValue());
8270 auto FirstDashIndex = ArgValue.find(C: '-');
8271 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
8272 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
8273
8274 A->claim();
8275 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8276 if (PluginName.empty()) {
8277 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8278 } else {
8279 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
8280 << PluginName << A->getAsString(Args);
8281 }
8282 continue;
8283 }
8284
8285 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
8286 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
8287 }
8288
8289 // Forward -fpass-plugin=name.so to -cc1.
8290 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
8291 CmdArgs.push_back(
8292 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
8293 A->claim();
8294 }
8295
8296 // Forward --vfsoverlay to -cc1.
8297 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
8298 CmdArgs.push_back(Elt: "--vfsoverlay");
8299 CmdArgs.push_back(Elt: A->getValue());
8300 A->claim();
8301 }
8302
8303 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
8304 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
8305
8306 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
8307 Neg: options::OPT_fno_experimental_late_parse_attributes);
8308
8309 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
8310 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
8311 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
8312 A->render(Args, Output&: CmdArgs);
8313 else
8314 CmdArgs.push_back(Elt: Args.MakeArgString(
8315 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8316 }
8317
8318 if (Args.hasFlag(
8319 Pos: options::OPT_fexperimental_allow_pointer_field_protection_attr,
8320 Neg: options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8321 Default: false) ||
8322 Args.hasFlag(Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8323 Neg: options::OPT_fno_experimental_pointer_field_protection_abi,
8324 Default: false))
8325 CmdArgs.push_back(Elt: "-fexperimental-allow-pointer-field-protection-attr");
8326
8327 if (!IsCudaDevice) {
8328 Args.addOptInFlag(
8329 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8330 Neg: options::OPT_fno_experimental_pointer_field_protection_abi);
8331 Args.addOptInFlag(
8332 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_tagged,
8333 Neg: options::OPT_fno_experimental_pointer_field_protection_tagged);
8334 }
8335
8336 // Setup statistics file output.
8337 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8338 if (!StatsFile.empty()) {
8339 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
8340 if (D.CCPrintInternalStats)
8341 CmdArgs.push_back(Elt: "-stats-file-append");
8342 }
8343
8344 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8345 // parser.
8346 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
8347 Arg->claim();
8348 // -finclude-default-header flag is for preprocessor,
8349 // do not pass it to other cc1 commands when save-temps is enabled
8350 if (C.getDriver().isSaveTempsEnabled() &&
8351 !isa<PreprocessJobAction>(Val: JA)) {
8352 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8353 continue;
8354 }
8355 CmdArgs.push_back(Elt: Arg->getValue());
8356 }
8357 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
8358 A->claim();
8359
8360 // We translate this by hand to the -cc1 argument, since nightly test uses
8361 // it and developers have been trained to spell it with -mllvm. Both
8362 // spellings are now deprecated and should be removed.
8363 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
8364 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
8365 } else {
8366 A->render(Args, Output&: CmdArgs);
8367 }
8368 }
8369
8370 // This needs to run after -Xclang argument forwarding to pick up the target
8371 // features enabled through -Xclang -target-feature flags.
8372 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8373
8374 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
8375
8376#if CLANG_ENABLE_CIR
8377 // Forward -mmlir arguments to to the MLIR option parser.
8378 for (const Arg *A : Args.filtered(Ids: options::OPT_mmlir)) {
8379 A->claim();
8380 A->render(Args, Output&: CmdArgs);
8381 }
8382#endif // CLANG_ENABLE_CIR
8383
8384 // With -save-temps, we want to save the unoptimized bitcode output from the
8385 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8386 // by the frontend.
8387 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8388 // has slightly different breakdown between stages.
8389 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8390 // pristine IR generated by the frontend. Ideally, a new compile action should
8391 // be added so both IR can be captured.
8392 if ((C.getDriver().isSaveTempsEnabled() ||
8393 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
8394 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8395 isa<CompileJobAction>(Val: JA))
8396 CmdArgs.push_back(Elt: "-disable-llvm-passes");
8397
8398 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
8399
8400 const char *Exec = D.getDriverProgramPath();
8401
8402 // Optionally embed the -cc1 level arguments into the debug info or a
8403 // section, for build analysis.
8404 // Also record command line arguments into the debug info if
8405 // -grecord-gcc-switches options is set on.
8406 // By default, -gno-record-gcc-switches is set on and no recording.
8407 auto GRecordSwitches = false;
8408 auto FRecordSwitches = false;
8409 bool DXRecordSwitches = false;
8410 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches,
8411 DXRecordCommandLine&: DXRecordSwitches)) {
8412 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8413 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8414 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8415 CmdArgs.push_back(Elt: FlagsArgString);
8416 }
8417 if (FRecordSwitches) {
8418 CmdArgs.push_back(Elt: "-record-command-line");
8419 CmdArgs.push_back(Elt: FlagsArgString);
8420 }
8421 if (DXRecordSwitches) {
8422 CmdArgs.push_back(Elt: "-fdx-record-command-line");
8423 CmdArgs.push_back(Elt: FlagsArgString);
8424 }
8425 }
8426
8427 // Host-side offloading compilation receives all device-side outputs. Include
8428 // them in the host compilation depending on the target.
8429 if (!HostOffloadingInputs.empty()) {
8430 bool UseOffloadIncludeBinary =
8431 (IsCuda || IsHIP) &&
8432 (!IsRDCMode || Args.hasArg(Ids: options::OPT_cuda_emit_nvcc_abi)) &&
8433 !UsesLLVMOffloading;
8434 UseOffloadIncludeBinary |= IsSYCL && !IsRDCMode;
8435 if (UseOffloadIncludeBinary) {
8436 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8437 CmdArgs.push_back(Elt: "-foffload-include-binary");
8438 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
8439 } else {
8440 for (const InputInfo Input : HostOffloadingInputs)
8441 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
8442 TC.getInputFilename(Input)));
8443 }
8444 }
8445
8446 if (IsCuda) {
8447 if (Args.hasArg(Ids: options::OPT_cuda_emit_nvcc_abi))
8448 CmdArgs.push_back(Elt: "--cuda-emit-nvcc-abi");
8449 }
8450
8451 if (IsCuda || IsHIP) {
8452 // Determine the original source input.
8453 const Action *SourceAction = &JA;
8454 while (SourceAction->getKind() != Action::InputClass) {
8455 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8456 SourceAction = SourceAction->getInputs()[0];
8457 }
8458 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
8459 if (!CUID.empty())
8460 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
8461
8462 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8463 // be overriden by -fno-gpu-approx-transcendentals.
8464 bool UseApproxTranscendentals = Args.hasFlag(
8465 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
8466 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
8467 Neg: options::OPT_fno_gpu_approx_transcendentals,
8468 Default: UseApproxTranscendentals))
8469 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
8470 } else {
8471 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
8472 Ids: options::OPT_fno_gpu_approx_transcendentals);
8473 }
8474
8475 if (IsHIP) {
8476 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
8477 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
8478 }
8479
8480 Args.AddAllArgs(Output&: CmdArgs,
8481 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8482
8483 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
8484 Ids: options::OPT_fno_offload_uniform_block);
8485
8486 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
8487 Ids: options::OPT_fno_offload_implicit_host_device_templates);
8488
8489 if (IsCudaDevice || IsHIPDevice) {
8490 StringRef InlineThresh =
8491 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
8492 if (!InlineThresh.empty()) {
8493 std::string ArgStr =
8494 std::string("-inline-threshold=") + InlineThresh.str();
8495 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
8496 }
8497 }
8498
8499 if (IsHIPDevice)
8500 Args.addOptOutFlag(Output&: CmdArgs,
8501 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8502 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8503
8504 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8505 // to specify the result of the compile phase on the host, so the meaningful
8506 // device declarations can be identified. Also, -fopenmp-is-target-device is
8507 // passed along to tell the frontend that it is generating code for a device,
8508 // so that only the relevant declarations are emitted.
8509 if (IsOpenMPDevice) {
8510 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
8511 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8512 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
8513 CmdArgs.push_back(Elt: "-fcuda-is-device");
8514
8515 if (OpenMPDeviceInput) {
8516 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
8517 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
8518 }
8519 }
8520
8521 if (Triple.isAMDGPU() ||
8522 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8523 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8524
8525 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
8526 Neg: options::OPT_mno_unsafe_fp_atomics);
8527 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
8528 Neg: options::OPT_mno_amdgpu_ieee);
8529 }
8530
8531 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8532
8533 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
8534 Neg: options::OPT_fno_devirtualize_speculatively,
8535 /*Default value*/ Default: false))
8536 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
8537
8538 bool VirtualFunctionElimination =
8539 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
8540 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
8541 if (VirtualFunctionElimination) {
8542 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8543 // in the future).
8544 if (LTOMode != LTOK_Full)
8545 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8546 << "-fvirtual-function-elimination"
8547 << "-flto=full";
8548
8549 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
8550 }
8551
8552 // VFE requires whole-program-vtables, and enables it by default.
8553 bool WholeProgramVTables = Args.hasFlag(
8554 Pos: options::OPT_fwhole_program_vtables,
8555 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
8556 if (VirtualFunctionElimination && !WholeProgramVTables) {
8557 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8558 << "-fno-whole-program-vtables"
8559 << "-fvirtual-function-elimination";
8560 }
8561
8562 if (WholeProgramVTables) {
8563 // PS4 uses the legacy LTO API, which does not support this feature in
8564 // ThinLTO mode.
8565 bool IsPS4 = getToolChain().getTriple().isPS4();
8566
8567 // Check if we passed LTO options but they were suppressed because this is a
8568 // device offloading action, or we passed device offload LTO options which
8569 // were suppressed because this is not the device offload action.
8570 // Check if we are using PS4 in regular LTO mode.
8571 // Otherwise, issue an error.
8572
8573 auto OtherLTOMode = TC.getLTOMode(
8574 Args, Kind: IsDeviceOffloadAction ? Action::OFK_None
8575 : static_cast<Action::OffloadKind>(
8576 C.getActiveOffloadKinds()));
8577 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8578
8579 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8580 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8581 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8582 << "-fwhole-program-vtables"
8583 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8584
8585 // Propagate -fwhole-program-vtables if this is an LTO compile.
8586 if (IsUsingLTO)
8587 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
8588 }
8589
8590 bool DefaultsSplitLTOUnit =
8591 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8592 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8593 (!Triple.isPS4() && UnifiedLTO);
8594 bool SplitLTOUnit =
8595 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
8596 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
8597 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8598 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8599 << "-fsanitize=cfi";
8600 if (SplitLTOUnit)
8601 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
8602
8603 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
8604 Ids: options::OPT_fno_fat_lto_objects)) {
8605 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
8606 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8607 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8608 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8609 << A->getAsString(Args) << TC.getTripleString();
8610 }
8611 CmdArgs.push_back(Elt: Args.MakeArgString(
8612 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8613 CmdArgs.push_back(Elt: "-flto-unit");
8614 CmdArgs.push_back(Elt: "-ffat-lto-objects");
8615 A->render(Args, Output&: CmdArgs);
8616 }
8617 }
8618
8619 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8620
8621 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8622 Ids: options::OPT_fno_force_enable_int128)) {
8623 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8624 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8625 }
8626
8627 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8628 Neg: options::OPT_fno_keep_static_consts);
8629 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8630 Neg: options::OPT_fno_keep_persistent_storage_variables);
8631 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_inline_functions,
8632 Neg: options::OPT_fno_keep_inline_functions);
8633 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodule_local_hints,
8634 Neg: options::OPT_fno_module_local_hints);
8635 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8636 Neg: options::OPT_fno_complete_member_pointers);
8637 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8638 A->render(Args, Output&: CmdArgs);
8639
8640 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8641
8642 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8643
8644 if (Triple.isAArch64() &&
8645 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8646 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8647 // Disable Function Multiversioning on AArch64 target.
8648 CmdArgs.push_back(Elt: "-target-feature");
8649 CmdArgs.push_back(Elt: "-fmv");
8650 }
8651
8652 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8653 Default: (TC.getTriple().isOSBinFormatELF() ||
8654 TC.getTriple().isOSBinFormatCOFF()) &&
8655 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8656 !TC.getTriple().isOSNetBSD() &&
8657 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8658 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8659 CmdArgs.push_back(Elt: "-faddrsig");
8660
8661 const bool HasDefaultDwarf2CFIASM =
8662 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8663 (EH || UnwindTables || AsyncUnwindTables ||
8664 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8665 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8666 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8667 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8668
8669 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8670 std::string Str = A->getAsString(Args);
8671 if (!TC.getTriple().isOSBinFormatELF())
8672 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8673 << Str << TC.getTripleString();
8674 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8675 }
8676
8677 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8678 // the -cc1 command easier to edit when reproducing compiler crashes.
8679 if (Output.getType() == types::TY_Dependencies) {
8680 // Handled with other dependency code.
8681 } else if (Output.isFilename()) {
8682 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8683 Output.getType() == clang::driver::types::TY_IFS) {
8684 SmallString<128> OutputFilename(Output.getFilename());
8685 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8686 CmdArgs.push_back(Elt: "-o");
8687 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8688 } else {
8689 CmdArgs.push_back(Elt: "-o");
8690 CmdArgs.push_back(Elt: Output.getFilename());
8691 }
8692 } else {
8693 assert(Output.isNothing() && "Invalid output.");
8694 }
8695
8696 addDashXForInput(Args, Input, CmdArgs);
8697
8698 ArrayRef<InputInfo> FrontendInputs = Input;
8699 if (IsExtractAPI)
8700 FrontendInputs = ExtractAPIInputs;
8701 else if (Input.isNothing())
8702 FrontendInputs = {};
8703
8704 for (const InputInfo &Input : FrontendInputs) {
8705 if (Input.isFilename())
8706 CmdArgs.push_back(Elt: Input.getFilename());
8707 else
8708 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8709 }
8710
8711 if (D.CC1Main && !D.CCGenDiagnostics) {
8712 // Invoke the CC1 directly in this process
8713 C.addCommand(Cmd: std::make_unique<CC1Command>(
8714 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8715 args: Output, args: D.getPrependArg()));
8716 } else {
8717 C.addCommand(Cmd: std::make_unique<Command>(
8718 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8719 args: Output, args: D.getPrependArg()));
8720 }
8721
8722 // Make the compile command echo its inputs for /showFilenames.
8723 if (Output.getType() == types::TY_Object &&
8724 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8725 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8726 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8727 }
8728
8729 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8730 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8731 !Args.hasArg(Ids: options::OPT_mfentry))
8732 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8733 << A->getAsString(Args);
8734
8735 // Claim some arguments which clang supports automatically.
8736
8737 // -fpch-preprocess is used with gcc to add a special marker in the output to
8738 // include the PCH file.
8739 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8740
8741 // Claim some arguments which clang doesn't support, but we don't
8742 // care to warn the user about.
8743 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8744 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8745
8746 // Disable warnings for clang -E -emit-llvm foo.c
8747 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8748}
8749
8750Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8751 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8752 // as it is for other tools. Some operations on a Tool actually test
8753 // whether that tool is Clang based on the Tool's Name as a string.
8754 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8755
8756Clang::~Clang() {}
8757
8758/// Add options related to the Objective-C runtime/ABI.
8759///
8760/// Returns true if the runtime is non-fragile.
8761ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8762 const InputInfoList &inputs,
8763 ArgStringList &cmdArgs,
8764 RewriteKind rewriteKind) const {
8765 // Look for the controlling runtime option.
8766 Arg *runtimeArg =
8767 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8768 Ids: options::OPT_fobjc_runtime_EQ);
8769
8770 // Just forward -fobjc-runtime= to the frontend. This supercedes
8771 // options about fragility.
8772 if (runtimeArg &&
8773 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8774 ObjCRuntime runtime;
8775 StringRef value = runtimeArg->getValue();
8776 if (runtime.tryParse(input: value)) {
8777 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8778 << value;
8779 }
8780 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8781 (runtime.getVersion() >= VersionTuple(2, 0)))
8782 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8783 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8784 !getToolChain().getTriple().isOSBinFormatWasm()) {
8785 getToolChain().getDriver().Diag(
8786 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8787 << runtime.getVersion().getMajor();
8788 }
8789
8790 runtimeArg->render(Args: args, Output&: cmdArgs);
8791 return runtime;
8792 }
8793
8794 // Otherwise, we'll need the ABI "version". Version numbers are
8795 // slightly confusing for historical reasons:
8796 // 1 - Traditional "fragile" ABI
8797 // 2 - Non-fragile ABI, version 1
8798 // 3 - Non-fragile ABI, version 2
8799 unsigned objcABIVersion = 1;
8800 // If -fobjc-abi-version= is present, use that to set the version.
8801 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8802 StringRef value = abiArg->getValue();
8803 if (value == "1")
8804 objcABIVersion = 1;
8805 else if (value == "2")
8806 objcABIVersion = 2;
8807 else if (value == "3")
8808 objcABIVersion = 3;
8809 else
8810 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8811 } else {
8812 // Otherwise, determine if we are using the non-fragile ABI.
8813 bool nonFragileABIIsDefault =
8814 (rewriteKind == RK_NonFragile ||
8815 (rewriteKind == RK_None &&
8816 getToolChain().IsObjCNonFragileABIDefault()));
8817 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8818 Neg: options::OPT_fno_objc_nonfragile_abi,
8819 Default: nonFragileABIIsDefault)) {
8820// Determine the non-fragile ABI version to use.
8821#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8822 unsigned nonFragileABIVersion = 1;
8823#else
8824 unsigned nonFragileABIVersion = 2;
8825#endif
8826
8827 if (Arg *abiArg =
8828 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8829 StringRef value = abiArg->getValue();
8830 if (value == "1")
8831 nonFragileABIVersion = 1;
8832 else if (value == "2")
8833 nonFragileABIVersion = 2;
8834 else
8835 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8836 << value;
8837 }
8838
8839 objcABIVersion = 1 + nonFragileABIVersion;
8840 } else {
8841 objcABIVersion = 1;
8842 }
8843 }
8844
8845 // We don't actually care about the ABI version other than whether
8846 // it's non-fragile.
8847 bool isNonFragile = objcABIVersion != 1;
8848
8849 // If we have no runtime argument, ask the toolchain for its default runtime.
8850 // However, the rewriter only really supports the Mac runtime, so assume that.
8851 ObjCRuntime runtime;
8852 if (!runtimeArg) {
8853 switch (rewriteKind) {
8854 case RK_None:
8855 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8856 break;
8857 case RK_Fragile:
8858 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8859 break;
8860 case RK_NonFragile:
8861 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8862 break;
8863 }
8864
8865 // -fnext-runtime
8866 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8867 // On Darwin, make this use the default behavior for the toolchain.
8868 if (getToolChain().getTriple().isOSDarwin()) {
8869 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8870
8871 // Otherwise, build for a generic macosx port.
8872 } else {
8873 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8874 }
8875
8876 // -fgnu-runtime
8877 } else {
8878 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8879 // Legacy behaviour is to target the gnustep runtime if we are in
8880 // non-fragile mode or the GCC runtime in fragile mode.
8881 if (isNonFragile)
8882 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8883 else
8884 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8885 }
8886
8887 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8888 return types::isObjC(Id: input.getType());
8889 }))
8890 cmdArgs.push_back(
8891 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8892 return runtime;
8893}
8894
8895static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8896 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8897 I += HaveDash;
8898 return !HaveDash;
8899}
8900
8901namespace {
8902struct EHFlags {
8903 bool Synch = false;
8904 bool Asynch = false;
8905 bool NoUnwindC = false;
8906};
8907} // end anonymous namespace
8908
8909/// /EH controls whether to run destructor cleanups when exceptions are
8910/// thrown. There are three modifiers:
8911/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8912/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8913/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8914/// - c: Assume that extern "C" functions are implicitly nounwind.
8915/// The default is /EHs-c-, meaning cleanups are disabled.
8916static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8917 bool isWindowsMSVC) {
8918 EHFlags EH;
8919
8920 std::vector<std::string> EHArgs =
8921 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8922 for (const auto &EHVal : EHArgs) {
8923 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8924 switch (EHVal[I]) {
8925 case 'a':
8926 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8927 if (EH.Asynch) {
8928 // Async exceptions are Windows MSVC only.
8929 if (!isWindowsMSVC) {
8930 EH.Asynch = false;
8931 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8932 continue;
8933 }
8934 EH.Synch = false;
8935 }
8936 continue;
8937 case 'c':
8938 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8939 continue;
8940 case 's':
8941 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8942 if (EH.Synch)
8943 EH.Asynch = false;
8944 continue;
8945 default:
8946 break;
8947 }
8948 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8949 break;
8950 }
8951 }
8952 // The /GX, /GX- flags are only processed if there are not /EH flags.
8953 // The default is that /GX is not specified.
8954 if (EHArgs.empty() &&
8955 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8956 /*Default=*/false)) {
8957 EH.Synch = true;
8958 EH.NoUnwindC = true;
8959 }
8960
8961 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8962 EH.Synch = false;
8963 EH.NoUnwindC = false;
8964 EH.Asynch = false;
8965 }
8966
8967 return EH;
8968}
8969
8970void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8971 ArgStringList &CmdArgs) const {
8972 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8973
8974 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8975
8976 if (Arg *ShowIncludes =
8977 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8978 Ids: options::OPT__SLASH_showIncludes_user)) {
8979 CmdArgs.push_back(Elt: "--show-includes");
8980 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8981 CmdArgs.push_back(Elt: "-sys-header-deps");
8982 }
8983
8984 // This controls whether or not we emit RTTI data for polymorphic types.
8985 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8986 /*Default=*/false))
8987 CmdArgs.push_back(Elt: "-fno-rtti-data");
8988
8989 // This controls whether or not we emit stack-protector instrumentation.
8990 // In MSVC, Buffer Security Check (/GS) is on by default.
8991 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8992 /*Default=*/true)) {
8993 CmdArgs.push_back(Elt: "-stack-protector");
8994 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8995 }
8996
8997 const Driver &D = getToolChain().getDriver();
8998
8999 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
9000 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
9001 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
9002 if (types::isCXX(Id: InputType))
9003 CmdArgs.push_back(Elt: "-fcxx-exceptions");
9004 CmdArgs.push_back(Elt: "-fexceptions");
9005 if (EH.Asynch)
9006 CmdArgs.push_back(Elt: "-fasync-exceptions");
9007 }
9008 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
9009 CmdArgs.push_back(Elt: "-fexternc-nounwind");
9010
9011 // /EP should expand to -E -P.
9012 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
9013 CmdArgs.push_back(Elt: "-E");
9014 CmdArgs.push_back(Elt: "-P");
9015 }
9016
9017 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
9018 Neg: options::OPT__SLASH_Zc_dllexportInlines,
9019 Default: false)) {
9020 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
9021 }
9022
9023 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
9024 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
9025 CmdArgs.push_back(Elt: "-fno-wchar");
9026 }
9027
9028 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
9029 llvm::Triple::ArchType Arch = getToolChain().getArch();
9030 std::vector<std::string> Values =
9031 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
9032 if (!Values.empty()) {
9033 llvm::SmallSet<std::string, 4> SupportedArches;
9034 if (Arch == llvm::Triple::x86)
9035 SupportedArches.insert(V: "IA32");
9036
9037 for (auto &V : Values)
9038 if (!SupportedArches.contains(V))
9039 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
9040 << std::string("/arch:").append(str: V) << "/kernel";
9041 }
9042
9043 CmdArgs.push_back(Elt: "-fno-rtti");
9044 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
9045 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
9046 << "/kernel";
9047 }
9048
9049 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
9050 Ids: options::OPT__SLASH_vlen_EQ_256,
9051 Ids: options::OPT__SLASH_vlen_EQ_512)) {
9052 llvm::Triple::ArchType AT = getToolChain().getArch();
9053 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
9054 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
9055 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
9056 "AVX10.2"};
9057
9058 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
9059 if (Arch512.contains(V: Arch))
9060 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
9061 else
9062 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
9063 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
9064 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
9065 if (Arch512.contains(V: Arch))
9066 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
9067 else if (Arch != "AVX" && Arch != "AVX2")
9068 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
9069 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
9070 } else {
9071 if (Arch == "AVX10.1" || Arch == "AVX10.2")
9072 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
9073 }
9074 } else {
9075 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
9076 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
9077 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
9078 CmdArgs.push_back(Elt: "-target-feature");
9079 CmdArgs.push_back(Elt: "-amx-tile");
9080 }
9081 if (Arch == "AVX10.2") {
9082 CmdArgs.push_back(Elt: "-target-feature");
9083 CmdArgs.push_back(Elt: "+avx10.2");
9084 }
9085 }
9086
9087 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
9088 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
9089 if (MostGeneralArg && BestCaseArg)
9090 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
9091 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
9092
9093 if (MostGeneralArg) {
9094 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
9095 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
9096 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
9097
9098 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9099 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9100 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9101 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
9102 << FirstConflict->getAsString(Args)
9103 << SecondConflict->getAsString(Args);
9104
9105 if (SingleArg)
9106 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
9107 else if (MultipleArg)
9108 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
9109 else
9110 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
9111 }
9112
9113 if (Args.hasArg(Ids: options::OPT_regcall4))
9114 CmdArgs.push_back(Elt: "-regcall4");
9115
9116 // Parse the default calling convention options.
9117 if (Arg *CCArg =
9118 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
9119 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
9120 Ids: options::OPT__SLASH_Gregcall)) {
9121 unsigned DCCOptId = CCArg->getOption().getID();
9122 const char *DCCFlag = nullptr;
9123 bool ArchSupported = !isNVPTX;
9124 llvm::Triple::ArchType Arch = getToolChain().getArch();
9125 switch (DCCOptId) {
9126 case options::OPT__SLASH_Gd:
9127 DCCFlag = "-fdefault-calling-conv=cdecl";
9128 break;
9129 case options::OPT__SLASH_Gr:
9130 ArchSupported = Arch == llvm::Triple::x86;
9131 DCCFlag = "-fdefault-calling-conv=fastcall";
9132 break;
9133 case options::OPT__SLASH_Gz:
9134 ArchSupported = Arch == llvm::Triple::x86;
9135 DCCFlag = "-fdefault-calling-conv=stdcall";
9136 break;
9137 case options::OPT__SLASH_Gv:
9138 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9139 DCCFlag = "-fdefault-calling-conv=vectorcall";
9140 break;
9141 case options::OPT__SLASH_Gregcall:
9142 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9143 DCCFlag = "-fdefault-calling-conv=regcall";
9144 break;
9145 }
9146
9147 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9148 if (ArchSupported && DCCFlag)
9149 CmdArgs.push_back(Elt: DCCFlag);
9150 }
9151
9152 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
9153 CmdArgs.push_back(Elt: "-regcall4");
9154
9155 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
9156
9157 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
9158 CmdArgs.push_back(Elt: "-fdiagnostics-format");
9159 CmdArgs.push_back(Elt: "msvc");
9160 }
9161
9162 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
9163 CmdArgs.push_back(Elt: "-fms-kernel");
9164
9165 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9166 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9167 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
9168 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
9169 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
9170 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
9171
9172 // Handle the various /guard options. We don't immediately push back clang
9173 // args since there are /d2 args that can modify the behavior of /guard:cf.
9174 bool HasCFGuard = false;
9175 bool HasCFGuardNoChecks = false;
9176 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
9177 StringRef GuardArgs = A->getValue();
9178 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9179 // "ehcont-".
9180 if (GuardArgs.equals_insensitive(RHS: "cf")) {
9181 // Emit CFG instrumentation and the table of address-taken functions.
9182 HasCFGuard = true;
9183 HasCFGuardNoChecks = false;
9184 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
9185 // Emit only the table of address-taken functions.
9186 HasCFGuard = false;
9187 HasCFGuardNoChecks = true;
9188 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
9189 // Emit EH continuation table.
9190 CmdArgs.push_back(Elt: "-ehcontguard");
9191 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
9192 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
9193 // Do nothing, but we might want to emit a security warning in future.
9194 } else {
9195 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9196 }
9197 A->claim();
9198 }
9199
9200 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9201 // If CFG is not enabled, it is a no-op.
9202 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardnochecks)) {
9203 if (HasCFGuard) {
9204 HasCFGuard = false;
9205 HasCFGuardNoChecks = true;
9206 }
9207 }
9208
9209 if (HasCFGuard)
9210 CmdArgs.push_back(Elt: "-cfguard");
9211 else if (HasCFGuardNoChecks)
9212 CmdArgs.push_back(Elt: "-cfguard-no-checks");
9213
9214 // Control Flow Guard mechanism for Windows.
9215 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch_))
9216 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=check");
9217 else if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch))
9218 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=dispatch");
9219
9220 for (const auto &FuncOverride :
9221 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
9222 CmdArgs.push_back(Elt: Args.MakeArgString(
9223 Str: Twine("-loader-replaceable-function=") + FuncOverride));
9224 }
9225
9226 if (Args.hasArg(Ids: options::OPT__SLASH_experimental_deterministic)) {
9227 CmdArgs.push_back(Elt: "-Wdate-time");
9228
9229 if (Args.hasArg(Ids: options::OPT_mincremental_linker_compatible)) {
9230 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
9231 << "/experimental:deterministic"
9232 << "/Brepro-";
9233 }
9234 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9235 // deterministic result, but we force this timestamp to 0, which also
9236 // produces deterministic result.
9237 CmdArgs.push_back(Elt: "-mno-incremental-linker-compatible");
9238 }
9239
9240 bool HasNoDateTime = Args.hasFlag(Pos: options::OPT__SLASH_d1nodatetime,
9241 Neg: options::OPT__SLASH_d1nodatetime_, Default: false);
9242
9243 if (HasNoDateTime)
9244 CmdArgs.push_back(Elt: "-init-datetime-macros=undefined");
9245
9246 // /Brepro is an alias for -mincremental-linker-compatible option.
9247 if (!Args.hasFlag(Pos: options::OPT_mincremental_linker_compatible,
9248 Neg: options::OPT_mno_incremental_linker_compatible,
9249 Default: getToolChain()
9250 .getTriple()
9251 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9252 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9253 // This option does not allow the user redefinitions for these macros.
9254 if (!HasNoDateTime)
9255 CmdArgs.push_back(Elt: "-init-datetime-macros=literalone");
9256 // Omit tool, current workdir and command line in COFF CV debug section.
9257 CmdArgs.push_back(Elt: "-gno-codeview-command-line");
9258 CmdArgs.push_back(Elt: "-gno-codeview-cwd");
9259 }
9260}
9261
9262const char *Clang::getBaseInputName(const ArgList &Args,
9263 const InputInfo &Input) {
9264 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
9265}
9266
9267const char *Clang::getBaseInputStem(const ArgList &Args,
9268 const InputInfoList &Inputs) {
9269 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
9270
9271 if (const char *End = strrchr(s: Str, c: '.'))
9272 return Args.MakeArgString(Str: std::string(Str, End));
9273
9274 return Str;
9275}
9276
9277const char *Clang::getDependencyFileName(const ArgList &Args,
9278 const InputInfoList &Inputs) {
9279 // FIXME: Think about this more.
9280
9281 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
9282 SmallString<128> OutputFilename(OutputOpt->getValue());
9283 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
9284 return Args.MakeArgString(Str: OutputFilename);
9285 }
9286
9287 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
9288}
9289
9290// Begin ClangAs
9291
9292void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9293 ArgStringList &CmdArgs) const {
9294 StringRef CPUName;
9295 StringRef ABIName;
9296 const llvm::Triple &Triple = getToolChain().getTriple();
9297 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9298
9299 CmdArgs.push_back(Elt: "-target-abi");
9300 CmdArgs.push_back(Elt: ABIName.data());
9301}
9302
9303void ClangAs::AddX86TargetArgs(const ArgList &Args,
9304 ArgStringList &CmdArgs) const {
9305 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
9306 /*IsLTO=*/false);
9307
9308 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
9309 StringRef Value = A->getValue();
9310 if (Value == "intel" || Value == "att") {
9311 CmdArgs.push_back(Elt: "-mllvm");
9312 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
9313 } else {
9314 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
9315 << A->getSpelling() << Value;
9316 }
9317 }
9318}
9319
9320void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9321 ArgStringList &CmdArgs) const {
9322 CmdArgs.push_back(Elt: "-target-abi");
9323 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
9324 Triple: getToolChain().getTriple())
9325 .data());
9326}
9327
9328void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9329 ArgStringList &CmdArgs) const {
9330 const llvm::Triple &Triple = getToolChain().getTriple();
9331 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9332
9333 CmdArgs.push_back(Elt: "-target-abi");
9334 CmdArgs.push_back(Elt: ABIName.data());
9335
9336 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9337 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9338 CmdArgs.push_back(Elt: "-mllvm");
9339 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
9340 }
9341}
9342
9343void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
9344 const InputInfo &Output, const InputInfoList &Inputs,
9345 const ArgList &Args,
9346 const char *LinkingOutput) const {
9347 ArgStringList CmdArgs;
9348
9349 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9350 const InputInfo &Input = Inputs[0];
9351
9352 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9353 const std::string &TripleStr = Triple.getTriple();
9354 const auto &D = getToolChain().getDriver();
9355
9356 // Don't warn about "clang -w -c foo.s"
9357 Args.ClaimAllArgs(Id0: options::OPT_w);
9358 // and "clang -emit-llvm -c foo.s"
9359 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
9360
9361 claimNoWarnArgs(Args);
9362
9363 // Invoke ourselves in -cc1as mode.
9364 //
9365 // FIXME: Implement custom jobs for internal actions.
9366 CmdArgs.push_back(Elt: "-cc1as");
9367
9368 // Add the "effective" target triple.
9369 CmdArgs.push_back(Elt: "-triple");
9370 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
9371
9372 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
9373
9374 // Set the output mode, we currently only expect to be used as a real
9375 // assembler.
9376 CmdArgs.push_back(Elt: "-filetype");
9377 CmdArgs.push_back(Elt: "obj");
9378
9379 // Set the main file name, so that debug info works even with
9380 // -save-temps or preprocessed assembly.
9381 CmdArgs.push_back(Elt: "-main-file-name");
9382 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
9383
9384 // Add the target cpu
9385 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
9386 if (!CPU.empty()) {
9387 CmdArgs.push_back(Elt: "-target-cpu");
9388 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
9389 }
9390
9391 // Add the target features
9392 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
9393
9394 // Ignore explicit -force_cpusubtype_ALL option.
9395 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
9396
9397 // Pass along any -I options so we get proper .include search paths.
9398 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
9399
9400 // Pass along any --embed-dir or similar options so we get proper embed paths.
9401 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
9402
9403 // Determine the original source input.
9404 auto FindSource = [](const Action *S) -> const Action * {
9405 while (S->getKind() != Action::InputClass) {
9406 assert(!S->getInputs().empty() && "unexpected root action!");
9407 S = S->getInputs()[0];
9408 }
9409 return S;
9410 };
9411 const Action *SourceAction = FindSource(&JA);
9412
9413 // Forward -g and handle debug info related flags, assuming we are dealing
9414 // with an actual assembly file.
9415 bool WantDebug = false;
9416 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
9417 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
9418 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
9419 !A->getOption().matches(ID: options::OPT_ggdb0);
9420
9421 // If a -gdwarf argument appeared, remember it.
9422 bool EmitDwarf = false;
9423 if (const Arg *A = getDwarfNArg(Args))
9424 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9425
9426 bool EmitCodeView = false;
9427 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
9428 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9429
9430 // If the user asked for debug info but did not explicitly specify -gcodeview
9431 // or -gdwarf, ask the toolchain for the default format.
9432 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9433 switch (getToolChain().getDefaultDebugFormat()) {
9434 case llvm::codegenoptions::DIF_CodeView:
9435 EmitCodeView = true;
9436 break;
9437 case llvm::codegenoptions::DIF_DWARF:
9438 EmitDwarf = true;
9439 break;
9440 }
9441 }
9442
9443 // If the arguments don't imply DWARF, don't emit any debug info here.
9444 if (!EmitDwarf)
9445 WantDebug = false;
9446
9447 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9448 llvm::codegenoptions::NoDebugInfo;
9449
9450 // Add the -fdebug-compilation-dir flag if needed.
9451 const char *DebugCompilationDir =
9452 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
9453
9454 if (SourceAction->getType() == types::TY_Asm ||
9455 SourceAction->getType() == types::TY_PP_Asm) {
9456 // You might think that it would be ok to set DebugInfoKind outside of
9457 // the guard for source type, however there is a test which asserts
9458 // that some assembler invocation receives no -debug-info-kind,
9459 // and it's not clear whether that test is just overly restrictive.
9460 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9461 : llvm::codegenoptions::NoDebugInfo);
9462
9463 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
9464 CmdArgs);
9465
9466 // Set the AT_producer to the clang version when using the integrated
9467 // assembler on assembly source files.
9468 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
9469 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
9470
9471 // And pass along -I options
9472 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
9473 }
9474 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
9475 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9476 DebuggerTuning: llvm::DebuggerKind::Default);
9477 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
9478 if (useMachORelocatableDwarf(T: Triple, DwarfVersion))
9479 CmdArgs.push_back(Elt: "-grelocatable-dwarf");
9480 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
9481
9482 // Handle -fPIC et al -- the relocation-model affects the assembler
9483 // for some targets.
9484 llvm::Reloc::Model RelocationModel;
9485 unsigned PICLevel;
9486 bool IsPIE;
9487 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
9488 ParsePICArgs(ToolChain: getToolChain(), Args);
9489
9490 const char *RMName = RelocationModelName(Model: RelocationModel);
9491 if (RMName) {
9492 CmdArgs.push_back(Elt: "-mrelocation-model");
9493 CmdArgs.push_back(Elt: RMName);
9494 }
9495
9496 // Optionally embed the -cc1as level arguments into the debug info, for build
9497 // analysis.
9498 if (getToolChain().UseDwarfDebugFlags()) {
9499 ArgStringList OriginalArgs;
9500 for (const auto &Arg : Args)
9501 Arg->render(Args, Output&: OriginalArgs);
9502
9503 SmallString<256> Flags;
9504 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9505 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
9506 for (const char *OriginalArg : OriginalArgs) {
9507 SmallString<128> EscapedArg;
9508 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
9509 Flags += " ";
9510 Flags += EscapedArg;
9511 }
9512 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
9513 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
9514 }
9515
9516 // FIXME: Add -static support, once we have it.
9517
9518 // Add target specific flags.
9519 switch (getToolChain().getArch()) {
9520 default:
9521 break;
9522
9523 case llvm::Triple::mips:
9524 case llvm::Triple::mipsel:
9525 case llvm::Triple::mips64:
9526 case llvm::Triple::mips64el:
9527 AddMIPSTargetArgs(Args, CmdArgs);
9528 break;
9529
9530 case llvm::Triple::x86:
9531 case llvm::Triple::x86_64:
9532 AddX86TargetArgs(Args, CmdArgs);
9533 break;
9534
9535 case llvm::Triple::arm:
9536 case llvm::Triple::armeb:
9537 case llvm::Triple::thumb:
9538 case llvm::Triple::thumbeb:
9539 // This isn't in AddARMTargetArgs because we want to do this for assembly
9540 // only, not C/C++.
9541 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9542 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9543 CmdArgs.push_back(Elt: "-mllvm");
9544 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
9545 }
9546 break;
9547
9548 case llvm::Triple::aarch64:
9549 case llvm::Triple::aarch64_32:
9550 case llvm::Triple::aarch64_be:
9551 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
9552 CmdArgs.push_back(Elt: "-mllvm");
9553 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
9554 }
9555 break;
9556
9557 case llvm::Triple::loongarch32:
9558 case llvm::Triple::loongarch64:
9559 AddLoongArchTargetArgs(Args, CmdArgs);
9560 break;
9561
9562 case llvm::Triple::riscv32:
9563 case llvm::Triple::riscv64:
9564 case llvm::Triple::riscv32be:
9565 case llvm::Triple::riscv64be:
9566 AddRISCVTargetArgs(Args, CmdArgs);
9567 break;
9568
9569 case llvm::Triple::hexagon:
9570 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9571 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9572 CmdArgs.push_back(Elt: "-mllvm");
9573 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
9574 }
9575 break;
9576 }
9577
9578 // Consume all the warning flags. Usually this would be handled more
9579 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9580 // doesn't handle that so rather than warning about unused flags that are
9581 // actually used, we'll lie by omission instead.
9582 // FIXME: Stop lying and consume only the appropriate driver flags
9583 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
9584
9585 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9586 D: getToolChain().getDriver());
9587
9588 // Forward -Xclangas arguments to -cc1as
9589 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
9590 Arg->claim();
9591 CmdArgs.push_back(Elt: Arg->getValue());
9592 }
9593
9594 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
9595
9596 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9597 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9598 OutputFileName: Output.getFilename());
9599
9600 // Fixup any previous commands that use -object-file-name because when we
9601 // generated them, the final .obj name wasn't yet known.
9602 for (Command &J : C.getJobs()) {
9603 if (SourceAction != FindSource(&J.getSource()))
9604 continue;
9605 auto &JArgs = J.getArguments();
9606 for (unsigned I = 0; I < JArgs.size(); ++I) {
9607 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
9608 Output.isFilename()) {
9609 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9610 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
9611 OutputFileName: Output.getFilename());
9612 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
9613 J.replaceArguments(List: NewArgs);
9614 break;
9615 }
9616 }
9617 }
9618
9619 assert(Output.isFilename() && "Unexpected lipo output.");
9620 CmdArgs.push_back(Elt: "-o");
9621 CmdArgs.push_back(Elt: Output.getFilename());
9622
9623 const llvm::Triple &T = getToolChain().getTriple();
9624 Arg *A;
9625 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
9626 T.isOSBinFormatELF()) {
9627 CmdArgs.push_back(Elt: "-split-dwarf-output");
9628 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
9629 }
9630
9631 if (Triple.isAMDGPU())
9632 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9633
9634 assert(Input.isFilename() && "Invalid input.");
9635 CmdArgs.push_back(Elt: Input.getFilename());
9636
9637 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9638 if (D.CC1Main && !D.CCGenDiagnostics) {
9639 // Invoke cc1as directly in this process.
9640 C.addCommand(Cmd: std::make_unique<CC1Command>(
9641 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9642 args: Output, args: D.getPrependArg()));
9643 } else {
9644 C.addCommand(Cmd: std::make_unique<Command>(
9645 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9646 args: Output, args: D.getPrependArg()));
9647 }
9648}
9649
9650// Begin OffloadBundler
9651void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
9652 const InputInfo &Output,
9653 const InputInfoList &Inputs,
9654 const llvm::opt::ArgList &TCArgs,
9655 const char *LinkingOutput) const {
9656 // The version with only one output is expected to refer to a bundling job.
9657 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9658
9659 // The bundling command looks like this:
9660 // clang-offload-bundler -type=bc
9661 // -targets=host-triple,openmp-triple1,openmp-triple2
9662 // -output=output_file
9663 // -input=unbundle_file_host
9664 // -input=unbundle_file_tgt1
9665 // -input=unbundle_file_tgt2
9666
9667 ArgStringList CmdArgs;
9668
9669 // Get the type.
9670 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9671 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
9672
9673 assert(JA.getInputs().size() == Inputs.size() &&
9674 "Not have inputs for all dependence actions??");
9675
9676 // Get the targets.
9677 SmallString<128> Triples;
9678 Triples += "-targets=";
9679 for (unsigned I = 0; I < Inputs.size(); ++I) {
9680 if (I)
9681 Triples += ',';
9682
9683 // Find ToolChain for this input.
9684 Action::OffloadKind CurKind = Action::OFK_Host;
9685 const ToolChain *CurTC = &getToolChain();
9686 const Action *CurDep = JA.getInputs()[I];
9687
9688 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
9689 CurTC = nullptr;
9690 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, BoundArch BA) {
9691 assert(CurTC == nullptr && "Expected one dependence!");
9692 CurKind = A->getOffloadingDeviceKind();
9693 CurTC = TC;
9694 });
9695 }
9696 Triples += Action::GetOffloadKindName(Kind: CurKind);
9697 Triples += '-';
9698 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9699 Args: TCArgs, BA: CurDep->getOffloadingArch()))
9700 .normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9701
9702 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9703 Triples += '-';
9704 Triples += CurDep->getOffloadingArch().ArchName;
9705 }
9706 }
9707 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9708
9709 // Get bundled file command.
9710 CmdArgs.push_back(
9711 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9712
9713 // Get unbundled files command.
9714 for (unsigned I = 0; I < Inputs.size(); ++I) {
9715 SmallString<128> UB;
9716 UB += "-input=";
9717
9718 // Find ToolChain for this input.
9719 const ToolChain *CurTC = &getToolChain();
9720 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9721 CurTC = nullptr;
9722 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, BoundArch) {
9723 assert(CurTC == nullptr && "Expected one dependence!");
9724 CurTC = TC;
9725 });
9726 UB += C.addTempFile(
9727 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9728 } else {
9729 UB += CurTC->getInputFilename(Input: Inputs[I]);
9730 }
9731 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9732 }
9733 addOffloadCompressArgs(TCArgs, CmdArgs);
9734 if (TCArgs.hasArg(Ids: options::OPT_v))
9735 CmdArgs.push_back(Elt: "--verbose");
9736 // All the inputs are encoded as commands.
9737 C.addCommand(Cmd: std::make_unique<Command>(
9738 args: JA, args: *this, args: ResponseFileSupport::None(),
9739 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9740 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9741}
9742
9743void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9744 const InputInfo &Output,
9745 const InputInfoList &Inputs,
9746 const llvm::opt::ArgList &Args,
9747 const char *LinkingOutput) const {
9748 ArgStringList CmdArgs;
9749
9750 // Add the output file name.
9751 assert(Output.isFilename() && "Invalid output.");
9752 CmdArgs.push_back(Elt: "-o");
9753 CmdArgs.push_back(Elt: Output.getFilename());
9754
9755 // Create the inputs to bundle the needed metadata.
9756 for (const InputInfo &Input : Inputs) {
9757 const Action *OffloadAction = Input.getAction();
9758 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9759 const ArgList &TCArgs =
9760 C.getArgsForToolChain(TC, BA: OffloadAction->getOffloadingArch(),
9761 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9762 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9763 BoundArch Arch = OffloadAction->getOffloadingArch();
9764 if (Arch.empty())
9765 Arch = BoundArch(TCArgs.getLastArgValue(Id: options::OPT_march_EQ));
9766
9767 StringRef Kind =
9768 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9769
9770 ArgStringList Features;
9771 SmallVector<StringRef> FeatureArgs;
9772 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9773 ForAS: false);
9774 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9775 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9776
9777 // TODO: We need to pass in the full target-id and handle it properly in the
9778 // linker wrapper.
9779 SmallVector<std::string> Parts{
9780 "file=" + File.str(),
9781 "triple=" + TC->ComputeEffectiveClangTriple(Args: TCArgs, BA: Arch),
9782 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9783 "kind=" + Kind.str(),
9784 };
9785
9786 if (TC->isUsingLTO(Args: TCArgs, Kind: OffloadAction->getOffloadingDeviceKind()))
9787 for (StringRef Feature : FeatureArgs)
9788 Parts.emplace_back(Args: "feature=" + Feature.str());
9789
9790 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9791 }
9792
9793 // FIXME: --offload-compress is HIP only until the OpenMP runtime accepts it.
9794 if (JA.isDeviceOffloading(OKind: Action::OFK_HIP) &&
9795 Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false))
9796 addOffloadCompressArgs(TCArgs: Args, CmdArgs, /*EmitCompressionFormat=*/true);
9797
9798 C.addCommand(Cmd: std::make_unique<Command>(
9799 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(),
9800 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9801 args&: CmdArgs, args: Inputs, args: Output));
9802}
9803
9804// Options that need the profile compiler-rt library on the target toolchain.
9805// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9806// too.
9807static bool requiresProfileRT(unsigned ID) {
9808 switch (ID) {
9809 case options::OPT_fprofile_generate:
9810 case options::OPT_fprofile_generate_EQ:
9811 case options::OPT_fprofile_instr_generate:
9812 case options::OPT_fprofile_instr_generate_EQ:
9813 case options::OPT_fcoverage_mapping:
9814 case options::OPT_fno_coverage_mapping:
9815 case options::OPT_fcoverage_compilation_dir_EQ:
9816 case options::OPT_ffile_compilation_dir_EQ:
9817 case options::OPT_fcoverage_prefix_map_EQ:
9818 return true;
9819 default:
9820 return false;
9821 }
9822}
9823
9824// Options that need the ubsan compiler-rt library on the target toolchain.
9825static bool requiresUBSanRT(unsigned ID) {
9826 switch (ID) {
9827 case options::OPT_fsanitize_EQ:
9828 case options::OPT_fno_sanitize_EQ:
9829 case options::OPT_fsanitize_minimal_runtime:
9830 case options::OPT_fno_sanitize_minimal_runtime:
9831 return true;
9832 default:
9833 return false;
9834 }
9835}
9836
9837void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9838 const InputInfo &Output,
9839 const InputInfoList &Inputs,
9840 const ArgList &Args,
9841 const char *LinkingOutput) const {
9842 using namespace options;
9843
9844 // A list of permitted options that will be forwarded to the embedded device
9845 // compilation job.
9846 const llvm::DenseSet<unsigned> CompilerOptions{
9847 OPT_v,
9848 OPT_hip_path_EQ,
9849 OPT_O_Group,
9850 OPT_g_Group,
9851 OPT_g_flags_Group,
9852 OPT_R_value_Group,
9853 OPT_R_Group,
9854 OPT_Xcuda_ptxas,
9855 OPT_ptxas_path_EQ,
9856 OPT_ftime_report,
9857 OPT_ftime_trace,
9858 OPT_ftime_trace_EQ,
9859 OPT_ftime_trace_granularity_EQ,
9860 OPT_ftime_trace_verbose,
9861 OPT_ftime_trace_compress_EQ,
9862 OPT_opt_record_file,
9863 OPT_opt_record_format,
9864 OPT_opt_record_passes,
9865 OPT_fsave_optimization_record,
9866 OPT_fsave_optimization_record_EQ,
9867 OPT_fno_save_optimization_record,
9868 OPT_foptimization_record_file_EQ,
9869 OPT_foptimization_record_passes_EQ,
9870 OPT_save_temps,
9871 OPT_save_temps_EQ,
9872 OPT_mcode_object_version_EQ,
9873 OPT_load,
9874 OPT_no_canonical_prefixes,
9875 OPT_fno_lto,
9876 OPT_flto,
9877 OPT_flto_partitions_EQ,
9878 OPT_flto_EQ,
9879 OPT_hipspv_pass_plugin_EQ,
9880 OPT_use_spirv_backend,
9881 OPT_no_use_spirv_backend,
9882 OPT_fmultilib_flag,
9883 OPT_fprofile_generate,
9884 OPT_fprofile_generate_EQ,
9885 OPT_fprofile_instr_generate,
9886 OPT_fprofile_instr_generate_EQ,
9887 OPT_fcoverage_mapping,
9888 OPT_fno_coverage_mapping,
9889 OPT_fcoverage_compilation_dir_EQ,
9890 OPT_ffile_compilation_dir_EQ,
9891 OPT_fcoverage_prefix_map_EQ,
9892 OPT_fsanitize_EQ,
9893 OPT_fno_sanitize_EQ,
9894 OPT_fsanitize_minimal_runtime,
9895 OPT_fno_sanitize_minimal_runtime,
9896 OPT_fsanitize_trap_EQ,
9897 OPT_fno_sanitize_trap_EQ,
9898 OPT_fvectorize,
9899 OPT_fno_vectorize,
9900 OPT_fslp_vectorize,
9901 OPT_fno_slp_vectorize,
9902 OPT_hipstdpar,
9903 OPT_fenable_spirv_size_optimization};
9904 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9905 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9906 // CMake implicit linker argument parsing.
9907 bool SuppressHIPNoRDCVerbose =
9908 JA.getType() == types::TY_HIP_FATBIN &&
9909 !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
9910 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9911 return TC.getVFS().exists(
9912 Path: TC.getCompilerRT(Args, Component: Name, Type: ToolChain::FT_Static));
9913 };
9914 auto ToolChainHasSanitizerRT = [&](const ToolChain &TC, const ArgList &TCArgs,
9915 Action::OffloadKind Kind) {
9916 if (TC.getSanitizerArgs(JobArgs: TCArgs, /*BA=*/{}, DeviceOffloadKind: Kind).needsCsanRt())
9917 return ToolChainHasRT(TC, "csan");
9918 return ToolChainHasRT(TC, "ubsan_minimal") ||
9919 ToolChainHasRT(TC, "ubsan_standalone");
9920 };
9921 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC,
9922 bool HasSanitizerRT) {
9923 unsigned ID = A->getOption().getID();
9924 // Don't forward profiling arguments if the toolchain doesn't support it.
9925 // Without this check using it on the host would result in linker errors.
9926 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9927 // together to avoid a device cc1 diagnostic.
9928 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9929 return false;
9930 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9931 // Without this check using it on the host would result in linker errors.
9932 if (requiresUBSanRT(ID) && !HasSanitizerRT)
9933 return false;
9934 // Don't forward -mllvm to toolchains that don't support LLVM.
9935 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9936 };
9937 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9938 const ToolChain &TC, bool HasSanitizerRT) {
9939 if (A->getOption().matches(ID: OPT_v) && SuppressHIPNoRDCVerbose)
9940 return false;
9941 return (Set.contains(V: A->getOption().getID()) ||
9942 (A->getOption().getGroup().isValid() &&
9943 Set.contains(V: A->getOption().getGroup().getID()))) &&
9944 ShouldForwardForToolChain(A, TC, HasSanitizerRT);
9945 };
9946
9947 ArgStringList CmdArgs;
9948 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9949 Action::OFK_HIP, Action::OFK_SYCL}) {
9950 auto TCRange = C.getOffloadToolChains(Kind);
9951 for (auto &I : llvm::make_range(p: TCRange)) {
9952 const ToolChain *TC = I.second;
9953
9954 // We do not use a bound architecture here so options passed only to a
9955 // specific architecture via -Xarch_<cpu> will not be forwarded.
9956 ArgStringList CompilerArgs;
9957 ArgStringList LinkerArgs;
9958 const DerivedArgList &ToolChainArgs =
9959 C.getArgsForToolChain(TC, /*BA=*/{}, DeviceOffloadKind: Kind);
9960 const bool HasSanitizerRT =
9961 ToolChainHasSanitizerRT(*TC, ToolChainArgs, Kind);
9962 for (Arg *A : ToolChainArgs) {
9963 if (A->getOption().matches(ID: OPT_Zlinker_input))
9964 LinkerArgs.emplace_back(Args: A->getValue());
9965 else if (ShouldForward(CompilerOptions, A, *TC, HasSanitizerRT)) {
9966 A->claim();
9967 A->render(Args, Output&: CompilerArgs);
9968 } else if (ShouldForward(LinkerOptions, A, *TC, HasSanitizerRT)) {
9969 A->claim();
9970 A->render(Args, Output&: LinkerArgs);
9971 }
9972 }
9973
9974 // If the user explicitly requested it via `--offload-arch` we should
9975 // extract it from any static libraries if present. Device images are
9976 // labeled with the canonical target ID, so request that.
9977 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ)) {
9978 std::optional<std::string> TargetID =
9979 getCanonicalTargetID(T: TC->getTriple(), TargetID: Arg);
9980 CmdArgs.emplace_back(Args: Args.MakeArgString(
9981 Str: "--should-extract=" + (TargetID ? StringRef(*TargetID) : Arg)));
9982 }
9983
9984 // If this is OpenMP the device linker will need `-lompdevice`.
9985 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9986 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9987 LinkerArgs.emplace_back(Args: "-lompdevice");
9988
9989 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9990 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9991 // flags to normal compilation.
9992 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9993 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9994 if (TC->getTriple().isSPIRV() &&
9995 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9996 Kind != Action::OFK_SYCL && !TC->isUsingLTO(Args: ToolChainArgs, Kind)) {
9997 // For SPIR-V some functions will be defined by the runtime so allow
9998 // unresolved symbols in `spirv-link`.
9999 LinkerArgs.emplace_back(Args: "--allow-partial-linkage");
10000 // Don't optimize out exported symbols.
10001 LinkerArgs.emplace_back(Args: "--create-library");
10002 }
10003
10004 // Forward the SYCL device image split option to clang-sycl-linker.
10005 // The driver and clang-sycl-linker share the same value vocabulary, so
10006 // the value is passed through verbatim after validation.
10007 if (Kind == Action::OFK_SYCL) {
10008 if (Arg *A =
10009 ToolChainArgs.getLastArg(Ids: OPT_fsycl_device_image_split_EQ)) {
10010 StringRef Mode = A->getValue();
10011 if (Mode != "kernel" && Mode != "translation_unit" &&
10012 Mode != "link_unit")
10013 C.getDriver().Diag(DiagID: clang::diag::err_drv_invalid_value)
10014 << A->getSpelling() << Mode;
10015 else
10016 LinkerArgs.emplace_back(
10017 Args: Args.MakeArgString(Str: "--module-split-mode=" + Mode));
10018 }
10019 }
10020
10021 // Forward all of these to the appropriate toolchain.
10022 for (StringRef Arg : CompilerArgs)
10023 CmdArgs.push_back(Elt: Args.MakeArgString(
10024 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
10025 for (StringRef Arg : LinkerArgs)
10026 CmdArgs.push_back(Elt: Args.MakeArgString(
10027 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
10028
10029 // Forward the LTO mode for this toolchain.
10030 auto DeviceLTOMode = TC->getLTOMode(Args: ToolChainArgs, Kind);
10031 if (DeviceLTOMode == LTOK_Full)
10032 CmdArgs.push_back(Elt: Args.MakeArgString(
10033 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
10034 else if (DeviceLTOMode == LTOK_Thin) {
10035 CmdArgs.push_back(Elt: Args.MakeArgString(
10036 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
10037 if (TC->getTriple().isAMDGPU()) {
10038 CmdArgs.push_back(
10039 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
10040 "=-plugin-opt=-force-import-all"));
10041 CmdArgs.push_back(
10042 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
10043 "=-plugin-opt=-avail-extern-to-local"));
10044 CmdArgs.push_back(Elt: Args.MakeArgString(
10045 Str: "--device-linker=" + TC->getTripleString() +
10046 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
10047 if (Kind == Action::OFK_OpenMP) {
10048 CmdArgs.push_back(
10049 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
10050 "=-plugin-opt=-amdgpu-internalize-symbols"));
10051 }
10052 }
10053 }
10054 }
10055 }
10056
10057 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
10058 CmdArgs.push_back(
10059 Elt: Args.MakeArgString(Str: "--host-triple=" + AuxTriple->getTriple()));
10060 else
10061 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--host-triple=" +
10062 getToolChain().getTripleString()));
10063
10064 if (Args.hasArg(Ids: options::OPT_v) && !SuppressHIPNoRDCVerbose)
10065 CmdArgs.push_back(Elt: "--wrapper-verbose");
10066 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ)) {
10067 CmdArgs.push_back(
10068 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
10069 CmdArgs.push_back(Elt: Args.MakeArgString(
10070 Str: Twine("--device-compiler=--cuda-path=") + A->getValue()));
10071 }
10072 if (Arg *A = Args.getLastArg(Ids: options::OPT_rocm_path_EQ)) {
10073 CmdArgs.push_back(Elt: Args.MakeArgString(
10074 Str: Twine("--device-compiler=--rocm-path=") + A->getValue()));
10075 }
10076
10077 // Construct the link job so we can wrap around it.
10078 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
10079 const auto &LinkCommand = C.getJobs().getJobs().back();
10080
10081 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
10082 // wrapper.
10083 for (Arg *A :
10084 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
10085 StringRef Val = A->getValue(N: 0);
10086 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
10087 auto WrapperOption =
10088 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
10089 if (Val.empty())
10090 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
10091 else
10092 CmdArgs.push_back(Elt: Args.MakeArgString(
10093 Str: WrapperOption +
10094 ToolChain::normalizeOffloadTriple(OrigTT: Val.drop_front()).str() + "=" +
10095 A->getValue(N: 1)));
10096 }
10097 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
10098 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
10099
10100 // Embed bitcode instead of an object in JIT mode.
10101 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
10102 Neg: options::OPT_fno_openmp_target_jit, Default: false))
10103 CmdArgs.push_back(Elt: "--embed-bitcode");
10104
10105 // Save temporary files created by the linker wrapper.
10106 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
10107 Args.hasArg(Ids: options::OPT_save_temps))
10108 CmdArgs.push_back(Elt: "--save-temps");
10109
10110 // Pass in the C library for GPUs if present and not disabled.
10111 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
10112 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
10113 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
10114 Ids: options::OPT_nogpulibc)) {
10115 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
10116 // The device C library is only available for NVPTX and AMDGPU targets
10117 // and we only link it by default for OpenMP currently.
10118 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10119 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
10120 return;
10121 bool HasLibC = TC.getStdlibIncludePath().has_value();
10122 if (HasLibC) {
10123 CmdArgs.push_back(Elt: Args.MakeArgString(
10124 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10125 CmdArgs.push_back(Elt: Args.MakeArgString(
10126 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10127 }
10128 auto HasCompilerRT = getToolChain().getVFS().exists(
10129 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static,
10130 /*IsFortran=*/false));
10131 if (HasCompilerRT)
10132 CmdArgs.push_back(
10133 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10134 "-lclang_rt.builtins"));
10135
10136 bool HasFlangRT = getToolChain().getVFS().exists(
10137 Path: TC.getCompilerRT(Args, Component: "runtime", Type: ToolChain::FT_Static,
10138 /*IsFortran=*/true));
10139 if (HasFlangRT && C.getDriver().IsFlangMode())
10140 CmdArgs.push_back(
10141 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10142 "-lflang_rt.runtime"));
10143 });
10144 }
10145
10146 // Add the linker arguments to be forwarded by the wrapper.
10147 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
10148 LinkCommand->getExecutable()));
10149
10150 // We use action type to differentiate two use cases of the linker wrapper.
10151 // TY_Image for normal linker wrapper work.
10152 // TY_HIP_FATBIN and TY_SYCL_FATBIN for device-only links emitting a fat
10153 // binary directly.
10154 assert(JA.getType() == types::TY_HIP_FATBIN ||
10155 JA.getType() == types::TY_SYCL_FATBIN ||
10156 JA.getType() == types::TY_Image);
10157 if (JA.getType() != types::TY_Image) {
10158 CmdArgs.push_back(Elt: "--emit-fatbin-only");
10159 CmdArgs.append(IL: {"-o", Output.getFilename()});
10160 for (auto Input : Inputs)
10161 CmdArgs.push_back(Elt: Input.getFilename());
10162 } else {
10163 for (const char *LinkArg : LinkCommand->getArguments())
10164 CmdArgs.push_back(Elt: LinkArg);
10165 }
10166
10167 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
10168
10169 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10170 if (OffloadJobs.A) {
10171 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10172 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
10173 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10174 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=" +
10175 Twine(OffloadJobs.NumThreads)));
10176 } else if (!OffloadJobs.A->isClaimed()) {
10177 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
10178 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10179 }
10180 }
10181
10182 // Propagate -no-canonical-prefixes.
10183 if (Args.hasArg(Ids: options::OPT_no_canonical_prefixes))
10184 CmdArgs.push_back(Elt: "--no-canonical-prefixes");
10185
10186 const char *Exec =
10187 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
10188
10189 // Replace the executable and arguments of the link job with the
10190 // wrapper.
10191 LinkCommand->replaceExecutable(Exe: Exec);
10192 LinkCommand->replaceArguments(List: CmdArgs);
10193}
10194