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/Version.h"
28#include "clang/Config/config.h"
29#include "clang/Driver/Action.h"
30#include "clang/Driver/CommonArgs.h"
31#include "clang/Driver/Distro.h"
32#include "clang/Driver/InputInfo.h"
33#include "clang/Driver/SanitizerArgs.h"
34#include "clang/Driver/Types.h"
35#include "clang/Driver/XRayArgs.h"
36#include "clang/Options/OptionUtils.h"
37#include "clang/Options/Options.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/BinaryFormat/Magic.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/Frontend/Debug/Options.h"
44#include "llvm/Object/ObjectFile.h"
45#include "llvm/Option/ArgList.h"
46#include "llvm/ProfileData/InstrProfReader.h"
47#include "llvm/Support/CodeGen.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/Error.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/Process.h"
54#include "llvm/Support/YAMLParser.h"
55#include "llvm/TargetParser/AArch64TargetParser.h"
56#include "llvm/TargetParser/ARMTargetParserCommon.h"
57#include "llvm/TargetParser/Host.h"
58#include "llvm/TargetParser/LoongArchTargetParser.h"
59#include "llvm/TargetParser/PPCTargetParser.h"
60#include "llvm/TargetParser/RISCVISAInfo.h"
61#include "llvm/TargetParser/RISCVTargetParser.h"
62#include <cctype>
63#include <iterator>
64
65using namespace clang::driver;
66using namespace clang::driver::tools;
67using namespace clang;
68using namespace llvm::opt;
69
70static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
71 if (Arg *A = Args.getLastArg(Ids: options::OPT_C, Ids: options::OPT_CC,
72 Ids: options::OPT_fminimize_whitespace,
73 Ids: options::OPT_fno_minimize_whitespace,
74 Ids: options::OPT_fkeep_system_includes,
75 Ids: options::OPT_fno_keep_system_includes)) {
76 if (!Args.hasArg(Ids: options::OPT_E) && !Args.hasArg(Ids: options::OPT__SLASH_P) &&
77 !Args.hasArg(Ids: options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
78 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
79 << A->getBaseArg().getAsString(Args)
80 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
81 }
82 }
83}
84
85static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
86 // In gcc, only ARM checks this, but it seems reasonable to check universally.
87 if (Args.hasArg(Ids: options::OPT_static))
88 if (const Arg *A =
89 Args.getLastArg(Ids: options::OPT_dynamic, Ids: options::OPT_mdynamic_no_pic))
90 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
91 << "-static";
92}
93
94/// Apply \a Work on the current tool chain \a RegularToolChain and any other
95/// offloading tool chain that is associated with the current action \a JA.
96static void
97forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
98 const ToolChain &RegularToolChain,
99 llvm::function_ref<void(const ToolChain &)> Work) {
100 // Apply Work on the current/regular tool chain.
101 Work(RegularToolChain);
102
103 // Apply Work on all the offloading tool chains associated with the current
104 // action.
105 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
106 Action::OFK_HIP, Action::OFK_SYCL}) {
107 if (JA.isHostOffloading(OKind: Kind)) {
108 auto TCs = C.getOffloadToolChains(Kind);
109 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
110 Work(*II->second);
111 } else if (JA.isDeviceOffloading(OKind: Kind))
112 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
113 }
114}
115
116static bool
117shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
118 const llvm::Triple &Triple) {
119 // We use the zero-cost exception tables for Objective-C if the non-fragile
120 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
121 // later.
122 if (runtime.isNonFragile())
123 return true;
124
125 if (!Triple.isMacOSX())
126 return false;
127
128 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
129 (Triple.getArch() == llvm::Triple::x86_64 ||
130 Triple.getArch() == llvm::Triple::arm));
131}
132
133/// Adds exception related arguments to the driver command arguments. There's a
134/// main flag, -fexceptions and also language specific flags to enable/disable
135/// C++ and Objective-C exceptions. This makes it possible to for example
136/// disable C++ exceptions but enable Objective-C exceptions.
137static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
138 const ToolChain &TC, bool KernelOrKext,
139 bool IsDeviceOffloadAction,
140 const ObjCRuntime &objcRuntime,
141 ArgStringList &CmdArgs) {
142 const llvm::Triple &Triple = TC.getTriple();
143
144 if (KernelOrKext) {
145 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
146 // arguments now to avoid warnings about unused arguments.
147 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
148 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
149 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
152 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
153 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
154 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
155 return false;
156 }
157
158 // See if the user explicitly enabled exceptions.
159 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
160 Default: false);
161
162 // Async exceptions are Windows MSVC only.
163 if (Triple.isWindowsMSVCEnvironment()) {
164 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
165 Neg: options::OPT_fno_async_exceptions, Default: false);
166 if (EHa) {
167 CmdArgs.push_back(Elt: "-fasync-exceptions");
168 EH = true;
169 }
170 }
171
172 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
173 // is not necessarily sensible, but follows GCC.
174 if (types::isObjC(Id: InputType) &&
175 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
176 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
177 CmdArgs.push_back(Elt: "-fobjc-exceptions");
178
179 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
180 }
181
182 if (types::isCXX(Id: InputType)) {
183 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
184 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
185 !Triple.isPS() && !Triple.isDriverKit() &&
186 !(Triple.isGPU() && !IsDeviceOffloadAction);
187 Arg *ExceptionArg = Args.getLastArg(
188 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
189 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
190 if (ExceptionArg)
191 CXXExceptionsEnabled =
192 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
193 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
194
195 if (CXXExceptionsEnabled) {
196 CmdArgs.push_back(Elt: "-fcxx-exceptions");
197
198 EH = true;
199 }
200 }
201
202 // OPT_fignore_exceptions means exception could still be thrown,
203 // but no clean up or catch would happen in current module.
204 // So we do not set EH to false.
205 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
206
207 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
208 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
209
210 if (EH)
211 CmdArgs.push_back(Elt: "-fexceptions");
212 return EH;
213}
214
215static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
216 const JobAction &JA) {
217 bool Default = true;
218 if (TC.getTriple().isOSDarwin()) {
219 // The native darwin assembler doesn't support the linker_option directives,
220 // so we disable them if we think the .s file will be passed to it.
221 Default = TC.useIntegratedAs();
222 }
223 // The linker_option directives are intended for host compilation.
224 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
225 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
226 Default = false;
227 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
228 Default);
229}
230
231/// Add a CC1 option to specify the debug compilation directory.
232static const char *addDebugCompDirArg(const ArgList &Args,
233 ArgStringList &CmdArgs,
234 const llvm::vfs::FileSystem &VFS) {
235 std::string DebugCompDir;
236 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
237 Ids: options::OPT_fdebug_compilation_dir_EQ))
238 DebugCompDir = A->getValue();
239
240 if (DebugCompDir.empty()) {
241 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
242 DebugCompDir = std::move(*CWD);
243 else
244 return nullptr;
245 }
246 CmdArgs.push_back(
247 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
248 StringRef Path(CmdArgs.back());
249 return Path.substr(Start: Path.find(C: '=') + 1).data();
250}
251
252static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
253 const char *DebugCompilationDir,
254 const char *OutputFileName) {
255 // No need to generate a value for -object-file-name if it was provided.
256 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
257 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
258 return;
259
260 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
261 return;
262
263 SmallString<128> ObjFileNameForDebug(OutputFileName);
264 if (ObjFileNameForDebug != "-" &&
265 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
266 (!DebugCompilationDir ||
267 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
268 // Make the path absolute in the debug infos like MSVC does.
269 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
270 }
271 // If the object file name is a relative path, then always use Windows
272 // backslash style as -object-file-name is used for embedding object file path
273 // in codeview and it can only be generated when targeting on Windows.
274 // Otherwise, just use native absolute path.
275 llvm::sys::path::Style Style =
276 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
277 ? llvm::sys::path::Style::native
278 : llvm::sys::path::Style::windows_backslash;
279 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
280 style: Style);
281 CmdArgs.push_back(
282 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
283}
284
285/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
286static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
287 const ArgList &Args, ArgStringList &CmdArgs) {
288 auto AddOneArg = [&](StringRef Map, StringRef Name) {
289 if (!Map.contains(C: '='))
290 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
291 else
292 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
293 };
294
295 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
296 Ids: options::OPT_fdebug_prefix_map_EQ)) {
297 AddOneArg(A->getValue(), A->getOption().getName());
298 A->claim();
299 }
300 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
301 if (GlobalRemapEntry.empty())
302 return;
303 AddOneArg(GlobalRemapEntry, "environment");
304}
305
306/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
307static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
308 ArgStringList &CmdArgs) {
309 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
310 Ids: options::OPT_fmacro_prefix_map_EQ)) {
311 StringRef Map = A->getValue();
312 if (!Map.contains(C: '='))
313 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
314 << Map << A->getOption().getName();
315 else
316 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
317 A->claim();
318 }
319}
320
321/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
322static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
323 ArgStringList &CmdArgs) {
324 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
325 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
326 StringRef Map = A->getValue();
327 if (!Map.contains(C: '='))
328 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
329 << Map << A->getOption().getName();
330 else
331 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
332 A->claim();
333 }
334}
335
336/// Add -x lang to \p CmdArgs for \p Input.
337static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
338 ArgStringList &CmdArgs) {
339 // When using -verify-pch, we don't want to provide the type
340 // 'precompiled-header' if it was inferred from the file extension
341 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
342 return;
343
344 CmdArgs.push_back(Elt: "-x");
345 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
346 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
347 else {
348 // Map the driver type to the frontend type. This is mostly an identity
349 // mapping, except that the distinction between module interface units
350 // and other source files does not exist at the frontend layer.
351 const char *ClangType;
352 switch (Input.getType()) {
353 case types::TY_CXXModule:
354 case types::TY_CXXStdModule:
355 ClangType = "c++";
356 break;
357 case types::TY_PP_CXXModule:
358 ClangType = "c++-cpp-output";
359 break;
360 default:
361 ClangType = types::getTypeName(Id: Input.getType());
362 break;
363 }
364 CmdArgs.push_back(Elt: ClangType);
365 }
366}
367
368static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
369 const JobAction &JA, const InputInfo &Output,
370 const ArgList &Args, SanitizerArgs &SanArgs,
371 ArgStringList &CmdArgs) {
372 const Driver &D = TC.getDriver();
373 const llvm::Triple &T = TC.getTriple();
374 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
375 Ids: options::OPT_fprofile_generate_EQ,
376 Ids: options::OPT_fno_profile_generate);
377 if (PGOGenerateArg &&
378 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
379 PGOGenerateArg = nullptr;
380
381 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
382
383 auto *ProfileGenerateArg = Args.getLastArg(
384 Ids: options::OPT_fprofile_instr_generate,
385 Ids: options::OPT_fprofile_instr_generate_EQ,
386 Ids: options::OPT_fno_profile_instr_generate);
387 if (ProfileGenerateArg &&
388 ProfileGenerateArg->getOption().matches(
389 ID: options::OPT_fno_profile_instr_generate))
390 ProfileGenerateArg = nullptr;
391
392 if (PGOGenerateArg && ProfileGenerateArg)
393 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
394 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
395
396 auto *ProfileUseArg = getLastProfileUseArg(Args);
397
398 if (PGOGenerateArg && ProfileUseArg)
399 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
400 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
401
402 if (ProfileGenerateArg && ProfileUseArg)
403 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
404 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
405
406 if (CSPGOGenerateArg && PGOGenerateArg) {
407 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
408 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
409 PGOGenerateArg = nullptr;
410 }
411
412 if (TC.getTriple().isOSAIX()) {
413 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
414 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
415 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
416 }
417
418 if (ProfileGenerateArg) {
419 if (ProfileGenerateArg->getOption().matches(
420 ID: options::OPT_fprofile_instr_generate_EQ))
421 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
422 ProfileGenerateArg->getValue()));
423 // The default is to use Clang Instrumentation.
424 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
425 if (TC.getTriple().isWindowsMSVCEnvironment() &&
426 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
427 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
428 // Add dependent lib for clang_rt.profile
429 CmdArgs.push_back(Elt: Args.MakeArgString(
430 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
431 }
432 }
433
434 if (auto *ColdFuncCoverageArg = Args.getLastArg(
435 Ids: options::OPT_fprofile_generate_cold_function_coverage,
436 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
437 SmallString<128> Path(
438 ColdFuncCoverageArg->getOption().matches(
439 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
440 ? ColdFuncCoverageArg->getValue()
441 : "");
442 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
443 // FIXME: Idealy the file path should be passed through
444 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
445 // shared with other profile use path(see PGOOptions), we need to refactor
446 // PGOOptions to make it work.
447 CmdArgs.push_back(Elt: "-mllvm");
448 CmdArgs.push_back(Elt: Args.MakeArgString(
449 Str: Twine("--instrument-cold-function-only-path=") + Path));
450 CmdArgs.push_back(Elt: "-mllvm");
451 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
452 CmdArgs.push_back(Elt: "-mllvm");
453 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
454 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
455 }
456
457 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
458 if (!PGOGenerateArg && !CSPGOGenerateArg)
459 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
460 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
461 CmdArgs.push_back(Elt: "-mllvm");
462 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
463 }
464
465 Arg *PGOGenArg = nullptr;
466 if (PGOGenerateArg) {
467 assert(!CSPGOGenerateArg);
468 PGOGenArg = PGOGenerateArg;
469 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
470 }
471 if (CSPGOGenerateArg) {
472 assert(!PGOGenerateArg);
473 PGOGenArg = CSPGOGenerateArg;
474 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
475 }
476 if (PGOGenArg) {
477 if (TC.getTriple().isWindowsMSVCEnvironment() &&
478 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
479 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
480 // Add dependent lib for clang_rt.profile
481 CmdArgs.push_back(Elt: Args.MakeArgString(
482 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
483 }
484 if (PGOGenArg->getOption().matches(
485 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
486 : options::OPT_fcs_profile_generate_EQ)) {
487 SmallString<128> Path(PGOGenArg->getValue());
488 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
489 CmdArgs.push_back(
490 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
491 }
492 }
493
494 if (ProfileUseArg) {
495 SmallString<128> UsePathBuf;
496 StringRef UsePath;
497 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
498 UsePath = ProfileUseArg->getValue();
499 else if ((ProfileUseArg->getOption().matches(
500 ID: options::OPT_fprofile_use_EQ) ||
501 ProfileUseArg->getOption().matches(
502 ID: options::OPT_fprofile_instr_use))) {
503 UsePathBuf =
504 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
505 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
506 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
507 UsePath = UsePathBuf;
508 }
509 auto ReaderOrErr =
510 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
511 if (auto E = ReaderOrErr.takeError()) {
512 auto DiagID = D.getDiags().getCustomDiagID(
513 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
514 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
515 D.Diag(DiagID) << UsePath.str() << EI.message();
516 });
517 } else {
518 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
519 std::move(ReaderOrErr.get());
520 StringRef UseKind;
521 // Currently memprof profiles are only added at the IR level. Mark the
522 // profile type as IR in that case as well and the subsequent matching
523 // needs to detect which is available (might be one or both).
524 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
525 if (PGOReader->hasCSIRLevelProfile())
526 UseKind = "csllvm";
527 else
528 UseKind = "llvm";
529 } else
530 UseKind = "clang";
531
532 CmdArgs.push_back(
533 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
534 CmdArgs.push_back(
535 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
536 }
537 }
538
539 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
540 Neg: options::OPT_fno_test_coverage, Default: false) ||
541 Args.hasArg(Ids: options::OPT_coverage);
542 bool EmitCovData = TC.needsGCovInstrumentation(Args);
543
544 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
545 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
546 if (!ProfileGenerateArg)
547 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
548 << "-fcoverage-mapping"
549 << "-fprofile-instr-generate";
550
551 CmdArgs.push_back(Elt: "-fcoverage-mapping");
552 }
553
554 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
555 Default: false)) {
556 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
557 Neg: options::OPT_fno_coverage_mapping, Default: false))
558 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
559 << "-fcoverage-mcdc"
560 << "-fcoverage-mapping";
561
562 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
563 }
564
565 StringRef CoverageCompDir;
566 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
567 Ids: options::OPT_fcoverage_compilation_dir_EQ))
568 CoverageCompDir = A->getValue();
569 if (CoverageCompDir.empty()) {
570 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
571 CmdArgs.push_back(
572 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
573 } else
574 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
575 CoverageCompDir));
576
577 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
578 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
579 if (!Args.hasArg(Ids: options::OPT_coverage))
580 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
581 << "-fprofile-exclude-files="
582 << "--coverage";
583
584 StringRef v = Arg->getValue();
585 CmdArgs.push_back(
586 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
587 }
588
589 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
590 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
591 if (!Args.hasArg(Ids: options::OPT_coverage))
592 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
593 << "-fprofile-filter-files="
594 << "--coverage";
595
596 StringRef v = Arg->getValue();
597 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
598 }
599
600 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
601 StringRef Val = A->getValue();
602 if (Val == "atomic" || Val == "prefer-atomic")
603 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
604 else if (Val != "single")
605 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
606 << A->getSpelling() << Val;
607 }
608 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
609 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
610 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
611 << A->getSpelling()
612 << "-fprofile-generate, -fprofile-instr-generate, or "
613 "-fcs-profile-generate";
614 else {
615 CmdArgs.push_back(Elt: "-fprofile-continuous");
616 // Platforms that require a bias variable:
617 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
618 CmdArgs.push_back(Elt: "-mllvm");
619 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
620 }
621 // -fprofile-instr-generate does not decide the profile file name in the
622 // FE, and so it does not define the filename symbol
623 // (__llvm_profile_filename). Instead, the runtime uses the name
624 // "default.profraw" for the profile file. When continuous mode is ON, we
625 // will create the filename symbol so that we can insert the "%c"
626 // modifier.
627 if (ProfileGenerateArg &&
628 (ProfileGenerateArg->getOption().matches(
629 ID: options::OPT_fprofile_instr_generate) ||
630 (ProfileGenerateArg->getOption().matches(
631 ID: options::OPT_fprofile_instr_generate_EQ) &&
632 strlen(s: ProfileGenerateArg->getValue()) == 0)))
633 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
634 }
635 }
636
637 int FunctionGroups = 1;
638 int SelectedFunctionGroup = 0;
639 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
640 StringRef Val = A->getValue();
641 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
642 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
643 }
644 if (const auto *A =
645 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
646 StringRef Val = A->getValue();
647 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
648 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
649 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
650 }
651 if (FunctionGroups != 1)
652 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
653 Twine(FunctionGroups)));
654 if (SelectedFunctionGroup != 0)
655 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
656 Twine(SelectedFunctionGroup)));
657
658 // Leave -fprofile-dir= an unused argument unless .gcda emission is
659 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
660 // the flag used. There is no -fno-profile-dir, so the user has no
661 // targeted way to suppress the warning.
662 Arg *FProfileDir = nullptr;
663 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
664 Args.hasArg(Ids: options::OPT_coverage))
665 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
666
667 // Put the .gcno and .gcda files (if needed) next to the primary output file,
668 // or fall back to a file in the current directory for `clang -c --coverage
669 // d/a.c` in the absence of -o.
670 if (EmitCovNotes || EmitCovData) {
671 SmallString<128> CoverageFilename;
672 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
673 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
674 // path separator.
675 CoverageFilename = DumpDir->getValue();
676 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
677 } else if (Arg *FinalOutput =
678 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
679 CoverageFilename = FinalOutput->getValue();
680 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
681 CoverageFilename = FinalOutput->getValue();
682 } else {
683 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
684 }
685 if (llvm::sys::path::is_relative(path: CoverageFilename))
686 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
687 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
688 if (EmitCovNotes) {
689 CmdArgs.push_back(
690 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
691 }
692
693 if (EmitCovData) {
694 if (FProfileDir) {
695 SmallString<128> Gcno = std::move(CoverageFilename);
696 CoverageFilename = FProfileDir->getValue();
697 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
698 }
699 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
700 CmdArgs.push_back(
701 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
702 }
703 }
704}
705
706static void
707RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
708 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
709 unsigned DwarfVersion,
710 llvm::DebuggerKind DebuggerTuning) {
711 addDebugInfoKind(CmdArgs, DebugInfoKind);
712 if (DwarfVersion > 0)
713 CmdArgs.push_back(
714 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
715 switch (DebuggerTuning) {
716 case llvm::DebuggerKind::GDB:
717 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
718 break;
719 case llvm::DebuggerKind::LLDB:
720 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
721 break;
722 case llvm::DebuggerKind::SCE:
723 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
724 break;
725 case llvm::DebuggerKind::DBX:
726 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
727 break;
728 default:
729 break;
730 }
731}
732
733static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
734 const ArgList &Args,
735 ArgStringList &CmdArgs,
736 bool IsCC1As = false) {
737 // If no version was requested by the user, use the default value from the
738 // back end. This is consistent with the value returned from
739 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
740 // requiring the corresponding llvm to have the AMDGPU target enabled,
741 // provided the user (e.g. front end tests) can use the default.
742 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
743 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
744 CmdArgs.insert(I: CmdArgs.begin() + 1,
745 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
746 Twine(CodeObjVer)));
747 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
748 // -cc1as does not accept -mcode-object-version option.
749 if (!IsCC1As)
750 CmdArgs.insert(I: CmdArgs.begin() + 1,
751 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
752 Twine(CodeObjVer)));
753 }
754}
755
756static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
757 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
758 D.getVFS().getBufferForFile(Name: Path);
759 if (!MemBuf)
760 return false;
761 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
762 if (Magic == llvm::file_magic::unknown)
763 return false;
764 // Return true for both raw Clang AST files and object files which may
765 // contain a __clangast section.
766 if (Magic == llvm::file_magic::clang_ast)
767 return true;
768 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
769 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
770 return !Obj.takeError();
771}
772
773static bool gchProbe(const Driver &D, StringRef Path) {
774 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
775 if (!Status)
776 return false;
777
778 if (Status->isDirectory()) {
779 std::error_code EC;
780 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
781 !EC && DI != DE; DI = DI.increment(EC)) {
782 if (maybeHasClangPchSignature(D, Path: DI->path()))
783 return true;
784 }
785 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
786 return false;
787 }
788
789 if (maybeHasClangPchSignature(D, Path))
790 return true;
791 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
792 return false;
793}
794
795void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
796 const Driver &D, const ArgList &Args,
797 ArgStringList &CmdArgs,
798 const InputInfo &Output,
799 const InputInfoList &Inputs) const {
800 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
801
802 CheckPreprocessingOptions(D, Args);
803
804 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
805 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
806
807 // Handle dependency file generation.
808 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
809 if (!ArgM)
810 ArgM = Args.getLastArg(Ids: options::OPT_M);
811 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
812 if (!ArgMD)
813 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
814
815 // -M and -MM imply -w.
816 if (ArgM)
817 CmdArgs.push_back(Elt: "-w");
818 else
819 ArgM = ArgMD;
820
821 if (ArgM) {
822 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
823 // Determine the output location.
824 const char *DepFile;
825 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
826 DepFile = MF->getValue();
827 C.addFailureResultFile(Name: DepFile, JA: &JA);
828 } else if (Output.getType() == types::TY_Dependencies) {
829 DepFile = Output.getFilename();
830 } else if (!ArgMD) {
831 DepFile = "-";
832 } else {
833 DepFile = getDependencyFileName(Args, Inputs);
834 C.addFailureResultFile(Name: DepFile, JA: &JA);
835 }
836 CmdArgs.push_back(Elt: "-dependency-file");
837 CmdArgs.push_back(Elt: DepFile);
838 }
839 // Cmake generates dependency files using all compilation options specified
840 // by users. Claim those not used for dependency files.
841 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
842 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
843 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
844 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
845 }
846
847 bool HasTarget = false;
848 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
849 HasTarget = true;
850 A->claim();
851 if (A->getOption().matches(ID: options::OPT_MT)) {
852 A->render(Args, Output&: CmdArgs);
853 } else {
854 CmdArgs.push_back(Elt: "-MT");
855 SmallString<128> Quoted;
856 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
857 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
858 }
859 }
860
861 // Add a default target if one wasn't specified.
862 if (!HasTarget) {
863 const char *DepTarget;
864
865 // If user provided -o, that is the dependency target, except
866 // when we are only generating a dependency file.
867 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
868 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
869 DepTarget = OutputOpt->getValue();
870 } else {
871 // Otherwise derive from the base input.
872 //
873 // FIXME: This should use the computed output file location.
874 SmallString<128> P(Inputs[0].getBaseInput());
875 llvm::sys::path::replace_extension(path&: P, extension: "o");
876 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
877 }
878
879 CmdArgs.push_back(Elt: "-MT");
880 SmallString<128> Quoted;
881 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
882 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
883 }
884
885 if (ArgM->getOption().matches(ID: options::OPT_M) ||
886 ArgM->getOption().matches(ID: options::OPT_MD))
887 CmdArgs.push_back(Elt: "-sys-header-deps");
888
889 // Determine module file deps mode.
890 StringRef ModuleFileDepsVal;
891 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_file_deps_EQ,
892 Ids: options::OPT_fmodule_file_deps,
893 Ids: options::OPT_fno_module_file_deps)) {
894 if (A->getOption().matches(ID: options::OPT_fmodule_file_deps_EQ))
895 ModuleFileDepsVal = A->getValue();
896 else if (A->getOption().matches(ID: options::OPT_fmodule_file_deps))
897 ModuleFileDepsVal = "all";
898 else
899 ModuleFileDepsVal = "none";
900 } else if (isa<PrecompileJobAction>(Val: JA)) {
901 ModuleFileDepsVal = "all";
902 }
903 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
904 CmdArgs.push_back(
905 Elt: Args.MakeArgString(Str: "-module-file-deps=" + ModuleFileDepsVal));
906 }
907
908 if (Args.hasArg(Ids: options::OPT_MG)) {
909 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
910 ArgM->getOption().matches(ID: options::OPT_MMD))
911 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
912 CmdArgs.push_back(Elt: "-MG");
913 }
914
915 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
916 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
917
918 bool UsesLLVMOffloading = Args.hasFlag(
919 Pos: options::OPT_foffload_via_llvm, Neg: options::OPT_fno_offload_via_llvm, Default: false);
920 bool UsesOffloadInclude =
921 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc, Default: true);
922 bool NoBuiltinInc = Args.hasArg(Ids: options::OPT_nobuiltininc);
923
924 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
925 // want to pull in our wrappers instead of the vendor headers.
926 if (UsesLLVMOffloading) {
927 if (UsesOffloadInclude && !NoBuiltinInc) {
928 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
929 StringRef RuntimeHeader) {
930 SmallString<128> OffloadInclude(D.Dir);
931 llvm::sys::path::append(path&: OffloadInclude, a: "..", b: "include", c: "offload");
932 if (!IncludeSubdir.empty())
933 llvm::sys::path::append(path&: OffloadInclude, a: IncludeSubdir);
934 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: OffloadInclude),
935 "-include", Args.MakeArgString(Str: RuntimeHeader)});
936 };
937 auto AddForcedInclude = [&](StringRef Header) {
938 CmdArgs.push_back(Elt: "-include");
939 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Header));
940 };
941 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
942 AddForcedInclude("__clang_gpu_builtin_vars.h");
943 AddForcedInclude("__clang_gpu_device_functions.h");
944 AddForcedInclude("__clang_gpu_intrinsics.h");
945 if (JA.isOffloading(OKind: Action::OFK_Cuda))
946 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
947 if (JA.isOffloading(OKind: Action::OFK_HIP) &&
948 !Args.hasArg(Ids: options::OPT_nohipwrapperinc)) {
949 // HIP code commonly includes this as "hip/hip_runtime.h".
950 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
951 }
952 }
953 } else {
954 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
955 // happen before we -I or -include anything else, because we must pick up
956 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
957 // installation, rather than from e.g. /usr/local/include.
958 if (JA.isOffloading(OKind: Action::OFK_Cuda))
959 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
960 if (JA.isOffloading(OKind: Action::OFK_HIP))
961 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
962 if (JA.isOffloading(OKind: Action::OFK_SYCL))
963 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
964
965 // If we are offloading to a target via OpenMP we need to include the
966 // openmp_wrappers folder which contains alternative system headers.
967 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
968 !Args.hasArg(Ids: options::OPT_nostdinc) && UsesOffloadInclude &&
969 getToolChain().getTriple().isGPU()) {
970 if (!NoBuiltinInc) {
971 // Add openmp_wrappers/* to our system include path. This lets us
972 // wrap standard library headers.
973 SmallString<128> P(D.ResourceDir);
974 llvm::sys::path::append(path&: P, a: "include");
975 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
976 CmdArgs.push_back(Elt: "-internal-isystem");
977 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
978 }
979
980 CmdArgs.push_back(Elt: "-include");
981 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
982 }
983 }
984
985 // Add -i* options, and automatically translate to
986 // -include-pch/-include-pth for transparent PCH support. It's
987 // wonky, but we include looking for .gch so we can support seamless
988 // replacement into a build system already set up to be generating
989 // .gch files.
990
991 if (getToolChain().getDriver().IsCLMode()) {
992 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
993 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
994 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
995 JA.getKind() <= Action::AssembleJobClass) {
996 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
997 // -fpch-instantiate-templates is the default when creating
998 // precomp using /Yc
999 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
1000 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
1001 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
1002 }
1003 if (YcArg || YuArg) {
1004 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1005 if (!isa<PrecompileJobAction>(Val: JA)) {
1006 CmdArgs.push_back(Elt: "-include-pch");
1007 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
1008 C, BaseName: !ThroughHeader.empty()
1009 ? ThroughHeader
1010 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1011 }
1012
1013 if (ThroughHeader.empty()) {
1014 CmdArgs.push_back(Elt: Args.MakeArgString(
1015 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1016 } else {
1017 CmdArgs.push_back(
1018 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1019 }
1020 }
1021 }
1022
1023 bool RenderedImplicitInclude = false;
1024 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1025 if (A->getOption().matches(ID: options::OPT_include) &&
1026 D.getProbePrecompiled()) {
1027 // Handling of gcc-style gch precompiled headers.
1028 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1029 RenderedImplicitInclude = true;
1030
1031 bool FoundPCH = false;
1032 SmallString<128> P(A->getValue());
1033 // We want the files to have a name like foo.h.pch. Add a dummy extension
1034 // so that replace_extension does the right thing.
1035 P += ".dummy";
1036 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1037 if (D.getVFS().exists(Path: P))
1038 FoundPCH = true;
1039
1040 if (!FoundPCH) {
1041 // For GCC compat, probe for a file or directory ending in .gch instead.
1042 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1043 FoundPCH = gchProbe(D, Path: P.str());
1044 }
1045
1046 if (FoundPCH) {
1047 if (IsFirstImplicitInclude) {
1048 A->claim();
1049 CmdArgs.push_back(Elt: "-include-pch");
1050 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1051 continue;
1052 } else {
1053 // Ignore the PCH if not first on command line and emit warning.
1054 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1055 << A->getAsString(Args);
1056 }
1057 }
1058 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1059 // Handling of paths which must come late. These entries are handled by
1060 // the toolchain itself after the resource dir is inserted in the right
1061 // search order.
1062 // Do not claim the argument so that the use of the argument does not
1063 // silently go unnoticed on toolchains which do not honour the option.
1064 continue;
1065 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1066 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1067 continue;
1068 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1069 // This is used only by the driver. No need to pass to cc1.
1070 continue;
1071 }
1072
1073 // Not translated, render as usual.
1074 A->claim();
1075 A->render(Args, Output&: CmdArgs);
1076 }
1077
1078 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1079 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1080 // Collect all enabled NVPTX architectures.
1081 std::set<unsigned> ArchIDs;
1082 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1083 const ToolChain *TC = I.second;
1084 for (BoundArch Arch :
1085 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1086 if (Arch.Arch.isNVPTX())
1087 ArchIDs.insert(x: CudaArchToID(Arch: Arch.Arch));
1088 }
1089 }
1090
1091 if (!ArchIDs.empty()) {
1092 SmallString<128> List;
1093 llvm::raw_svector_ostream OS(List);
1094 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1095 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1096 }
1097 }
1098
1099 Args.addAllArgs(Output&: CmdArgs,
1100 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1101 options::OPT_F, options::OPT_embed_dir_EQ});
1102
1103 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1104
1105 // FIXME: There is a very unfortunate problem here, some troubled
1106 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1107 // really support that we would have to parse and then translate
1108 // those options. :(
1109 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1110 Id1: options::OPT_Xpreprocessor);
1111
1112 // -I- is a deprecated GCC feature, reject it.
1113 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1114 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1115
1116 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1117 // -isysroot to the CC1 invocation.
1118 StringRef sysroot = C.getSysRoot();
1119 if (sysroot != "") {
1120 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1121 CmdArgs.push_back(Elt: "-isysroot");
1122 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1123 }
1124 }
1125
1126 // Parse additional include paths from environment variables.
1127 // FIXME: We should probably sink the logic for handling these from the
1128 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1129 // CPATH - included following the user specified includes (but prior to
1130 // builtin and standard includes).
1131 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1132 // C_INCLUDE_PATH - system includes enabled when compiling C.
1133 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1134 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1135 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1136 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1137 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1138 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1139 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1140
1141 // While adding the include arguments, we also attempt to retrieve the
1142 // arguments of related offloading toolchains or arguments that are specific
1143 // of an offloading programming model.
1144
1145 // Add C++ include arguments, if needed.
1146 if (types::isCXX(Id: Inputs[0].getType())) {
1147 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1148 forAllAssociatedToolChains(
1149 C, JA, RegularToolChain: getToolChain(),
1150 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1151 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1152 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1153 });
1154 }
1155
1156 // If we are compiling for a GPU target with the LLVM environment we want to
1157 // override the system headers with ones created by the 'libc' project if
1158 // present.
1159 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1160 // OffloadKind as an argument.
1161 bool OffloadUsesLLVMLibc =
1162 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1163 (C.getActiveOffloadKinds() != Action::OFK_None &&
1164 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
1165 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1166 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1167 Default: true) &&
1168 !Args.hasArg(Ids: options::OPT_nobuiltininc) && OffloadUsesLLVMLibc) {
1169 SmallString<128> P(D.ResourceDir);
1170 llvm::sys::path::append(path&: P, a: "include");
1171 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1172 CmdArgs.push_back(Elt: "-internal-isystem");
1173 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1174 }
1175
1176 // Add system include arguments for all targets but IAMCU.
1177 if (!IsIAMCU)
1178 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1179 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1180 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1181 });
1182 else {
1183 // For IAMCU add special include arguments.
1184 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1185 }
1186
1187 addMacroPrefixMapArg(D, Args, CmdArgs);
1188 addCoveragePrefixMapArg(D, Args, CmdArgs);
1189
1190 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1191 Ids: options::OPT_fno_file_reproducible);
1192
1193 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1194 CmdArgs.push_back(Elt: "-source-date-epoch");
1195 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1196 }
1197
1198 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1199 Neg: options::OPT_fno_define_target_os_macros);
1200}
1201
1202// FIXME: Move to target hook.
1203static bool isSignedCharDefault(const llvm::Triple &Triple) {
1204 switch (Triple.getArch()) {
1205 default:
1206 return true;
1207
1208 case llvm::Triple::aarch64:
1209 case llvm::Triple::aarch64_32:
1210 case llvm::Triple::aarch64_be:
1211 case llvm::Triple::arm:
1212 case llvm::Triple::armeb:
1213 case llvm::Triple::thumb:
1214 case llvm::Triple::thumbeb:
1215 if (Triple.isOSDarwin() || Triple.isOSWindows())
1216 return true;
1217 return false;
1218
1219 case llvm::Triple::ppc:
1220 case llvm::Triple::ppc64:
1221 if (Triple.isOSDarwin())
1222 return true;
1223 return false;
1224
1225 case llvm::Triple::csky:
1226 case llvm::Triple::hexagon:
1227 case llvm::Triple::msp430:
1228 case llvm::Triple::ppcle:
1229 case llvm::Triple::ppc64le:
1230 case llvm::Triple::riscv32:
1231 case llvm::Triple::riscv64:
1232 case llvm::Triple::riscv32be:
1233 case llvm::Triple::riscv64be:
1234 case llvm::Triple::systemz:
1235 case llvm::Triple::xcore:
1236 case llvm::Triple::xtensa:
1237 return false;
1238 }
1239}
1240
1241static bool hasMultipleInvocations(const llvm::Triple &Triple,
1242 const ArgList &Args) {
1243 // Supported only on Darwin where we invoke the compiler multiple times
1244 // followed by an invocation to lipo.
1245 if (!Triple.isOSDarwin())
1246 return false;
1247 // If more than one "-arch <arch>" is specified, we're targeting multiple
1248 // architectures resulting in a fat binary.
1249 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1250}
1251
1252static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1253 const llvm::Triple &Triple) {
1254 // When enabling remarks, we need to error if:
1255 // * The remark file is specified but we're targeting multiple architectures,
1256 // which means more than one remark file is being generated.
1257 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1258 bool hasExplicitOutputFile =
1259 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1260 if (hasMultipleInvocations && hasExplicitOutputFile) {
1261 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1262 << "-foptimization-record-file";
1263 return false;
1264 }
1265 return true;
1266}
1267
1268static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1269 const llvm::Triple &Triple,
1270 const InputInfo &Input,
1271 const InputInfo &Output, const JobAction &JA) {
1272 StringRef Format = "yaml";
1273 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1274 Format = A->getValue();
1275
1276 CmdArgs.push_back(Elt: "-opt-record-file");
1277
1278 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1279 if (A) {
1280 CmdArgs.push_back(Elt: A->getValue());
1281 } else {
1282 bool hasMultipleArchs =
1283 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1284 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1285
1286 SmallString<128> F;
1287
1288 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1289 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1290 F = FinalOutput->getValue();
1291 } else {
1292 if (Format != "yaml" && // For YAML, keep the original behavior.
1293 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1294 Output.isFilename())
1295 F = Output.getFilename();
1296 }
1297
1298 if (F.empty()) {
1299 // Use the input filename.
1300 F = llvm::sys::path::stem(path: Input.getBaseInput());
1301
1302 // If we're compiling for an offload architecture (i.e. a CUDA device),
1303 // we need to make the file name for the device compilation different
1304 // from the host compilation.
1305 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1306 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1307 llvm::sys::path::replace_extension(path&: F, extension: "");
1308 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1309 NormalizedTriple: Triple.str());
1310 F += "-";
1311 F += JA.getOffloadingArch().ArchName;
1312 }
1313 }
1314
1315 // If we're having more than one "-arch", we should name the files
1316 // differently so that every cc1 invocation writes to a different file.
1317 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1318 // name from the triple.
1319 if (hasMultipleArchs) {
1320 // First, remember the extension.
1321 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1322 // then, remove it.
1323 llvm::sys::path::replace_extension(path&: F, extension: "");
1324 // attach -<arch> to it.
1325 F += "-";
1326 F += Triple.getArchName();
1327 // put back the extension.
1328 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1329 }
1330
1331 SmallString<32> Extension;
1332 Extension += "opt.";
1333 Extension += Format;
1334
1335 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1336 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1337 }
1338
1339 if (const Arg *A =
1340 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1341 CmdArgs.push_back(Elt: "-opt-record-passes");
1342 CmdArgs.push_back(Elt: A->getValue());
1343 }
1344
1345 if (!Format.empty()) {
1346 CmdArgs.push_back(Elt: "-opt-record-format");
1347 CmdArgs.push_back(Elt: Format.data());
1348 }
1349}
1350
1351void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1352 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1353 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1354 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1355
1356 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1357 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1358}
1359
1360namespace {
1361void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1362 const ArgList &Args, ArgStringList &CmdArgs) {
1363 // Select the ABI to use.
1364 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1365 const char *ABIName = nullptr;
1366 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1367 ABIName = A->getValue();
1368 else
1369 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1370
1371 CmdArgs.push_back(Elt: "-target-abi");
1372 CmdArgs.push_back(Elt: ABIName);
1373}
1374
1375void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1376 auto StrictAlignIter =
1377 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1378 return Arg == "+strict-align" || Arg == "-strict-align";
1379 });
1380 if (StrictAlignIter != CmdArgs.rend() &&
1381 StringRef(*StrictAlignIter) == "+strict-align")
1382 CmdArgs.push_back(Elt: "-Wunaligned-access");
1383}
1384}
1385
1386static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1387 ArgStringList &CmdArgs, bool isAArch64) {
1388 const llvm::Triple &Triple = TC.getEffectiveTriple();
1389 const Arg *A = isAArch64
1390 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1391 Ids: options::OPT_mbranch_protection_EQ)
1392 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1393 if (!A) {
1394 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1395 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1396 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1397 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1398 }
1399 return;
1400 }
1401
1402 const Driver &D = TC.getDriver();
1403 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1404 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1405 << Triple.getArchName();
1406
1407 StringRef Scope, Key;
1408 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1409
1410 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1411 Scope = A->getValue();
1412 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1413 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1414 << A->getSpelling() << Scope;
1415 // This spelling cannot express a key, and AArch64 Windows only supports
1416 // B-key, so default to it there as parseBranchProtection() does.
1417 Key = isAArch64 && Triple.isOSWindows() ? "b_key" : "a_key";
1418 IndirectBranches =
1419 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1420 BranchProtectionPAuthLR = false;
1421 GuardedControlStack = false;
1422 } else {
1423 StringRef DiagMsg;
1424 llvm::ARM::ParsedBranchProtection PBP;
1425 bool EnablePAuthLR = false;
1426
1427 // To know if we need to enable PAuth-LR As part of the standard branch
1428 // protection option, it needs to be determined if the feature has been
1429 // activated in the `march` argument. This information is stored within the
1430 // CmdArgs variable and can be found using a search.
1431 if (isAArch64) {
1432 auto isPAuthLR = [](const char *member) {
1433 llvm::AArch64::ExtensionInfo pauthlr_extension =
1434 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1435 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1436 member;
1437 };
1438
1439 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1440 EnablePAuthLR = true;
1441 }
1442 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg, Triple,
1443 EnablePAuthLR))
1444 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1445 << A->getSpelling() << DiagMsg;
1446 if (!isAArch64 && PBP.Key == "b_key")
1447 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1448 << "b-key" << A->getAsString(Args);
1449 Scope = PBP.Scope;
1450 Key = PBP.Key;
1451 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1452 IndirectBranches = PBP.BranchTargetEnforcement;
1453 GuardedControlStack = PBP.GuardedControlStack;
1454 }
1455
1456 Arg *PtrauthReturnsArg = Args.getLastArg(Ids: options::OPT_fptrauth_returns,
1457 Ids: options::OPT_fno_ptrauth_returns);
1458 bool HasPtrauthReturns =
1459 PtrauthReturnsArg &&
1460 PtrauthReturnsArg->getOption().matches(ID: options::OPT_fptrauth_returns);
1461 // GCS is currently untested with ptrauth-returns, but enabling this could be
1462 // allowed in future after testing with a suitable system.
1463 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1464 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1465 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1466 << A->getAsString(Args) << Triple.getTriple();
1467 else if (HasPtrauthReturns)
1468 D.Diag(DiagID: diag::err_drv_incompatible_options)
1469 << A->getAsString(Args) << "-fptrauth-returns";
1470 }
1471
1472 CmdArgs.push_back(
1473 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1474 if (Scope != "none")
1475 CmdArgs.push_back(
1476 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1477 if (BranchProtectionPAuthLR)
1478 CmdArgs.push_back(
1479 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1480 if (IndirectBranches)
1481 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1482
1483 if (GuardedControlStack)
1484 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1485}
1486
1487void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1488 ArgStringList &CmdArgs, bool KernelOrKext) const {
1489 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1490
1491 // Determine floating point ABI from the options & target defaults.
1492 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1493 if (ABI == arm::FloatABI::Soft) {
1494 // Floating point operations and argument passing are soft.
1495 // FIXME: This changes CPP defines, we need -target-soft-float.
1496 CmdArgs.push_back(Elt: "-msoft-float");
1497 CmdArgs.push_back(Elt: "-mfloat-abi");
1498 CmdArgs.push_back(Elt: "soft");
1499 } else if (ABI == arm::FloatABI::SoftFP) {
1500 // Floating point operations are hard, but argument passing is soft.
1501 CmdArgs.push_back(Elt: "-mfloat-abi");
1502 CmdArgs.push_back(Elt: "soft");
1503 } else {
1504 // Floating point operations and argument passing are hard.
1505 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1506 CmdArgs.push_back(Elt: "-mfloat-abi");
1507 CmdArgs.push_back(Elt: "hard");
1508 }
1509
1510 // Forward the -mglobal-merge option for explicit control over the pass.
1511 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1512 Ids: options::OPT_mno_global_merge)) {
1513 CmdArgs.push_back(Elt: "-mllvm");
1514 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1515 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1516 else
1517 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1518 }
1519
1520 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1521 Neg: options::OPT_mno_implicit_float, Default: true))
1522 CmdArgs.push_back(Elt: "-no-implicit-float");
1523
1524 if (Args.getLastArg(Ids: options::OPT_mcmse))
1525 CmdArgs.push_back(Elt: "-mcmse");
1526
1527 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1528
1529 // Enable/disable return address signing and indirect branch targets.
1530 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1531
1532 AddUnalignedAccessWarning(CmdArgs);
1533}
1534
1535void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1536 ArgStringList &CmdArgs) const {
1537 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1538 if (Arg *A = Args.getLastArg(Ids: options::OPT_mxnack, Ids: options::OPT_mno_xnack))
1539 A->render(Args, Output&: CmdArgs);
1540 if (Arg *A = Args.getLastArg(Ids: options::OPT_msramecc, Ids: options::OPT_mno_sramecc))
1541 A->render(Args, Output&: CmdArgs);
1542}
1543
1544void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1545 const ArgList &Args, bool KernelOrKext,
1546 ArgStringList &CmdArgs) const {
1547 const ToolChain &TC = getToolChain();
1548
1549 // Add the target features
1550 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1551
1552 // Add target specific flags.
1553 switch (TC.getArch()) {
1554 default:
1555 break;
1556
1557 case llvm::Triple::arm:
1558 case llvm::Triple::armeb:
1559 case llvm::Triple::thumb:
1560 case llvm::Triple::thumbeb:
1561 // Use the effective triple, which takes into account the deployment target.
1562 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1563 break;
1564
1565 case llvm::Triple::aarch64:
1566 case llvm::Triple::aarch64_32:
1567 case llvm::Triple::aarch64_be:
1568 AddAArch64TargetArgs(Args, CmdArgs);
1569 break;
1570
1571 case llvm::Triple::amdgpu:
1572 AddAMDGPUTargetArgs(Args, CmdArgs);
1573 break;
1574
1575 case llvm::Triple::loongarch32:
1576 case llvm::Triple::loongarch64:
1577 AddLoongArchTargetArgs(Args, CmdArgs);
1578 break;
1579
1580 case llvm::Triple::mips:
1581 case llvm::Triple::mipsel:
1582 case llvm::Triple::mips64:
1583 case llvm::Triple::mips64el:
1584 AddMIPSTargetArgs(Args, CmdArgs);
1585 break;
1586
1587 case llvm::Triple::ppc:
1588 case llvm::Triple::ppcle:
1589 case llvm::Triple::ppc64:
1590 case llvm::Triple::ppc64le:
1591 AddPPCTargetArgs(Args, CmdArgs);
1592 break;
1593
1594 case llvm::Triple::riscv32:
1595 case llvm::Triple::riscv64:
1596 case llvm::Triple::riscv32be:
1597 case llvm::Triple::riscv64be:
1598 AddRISCVTargetArgs(Args, CmdArgs);
1599 break;
1600
1601 case llvm::Triple::sparc:
1602 case llvm::Triple::sparcel:
1603 case llvm::Triple::sparcv9:
1604 AddSparcTargetArgs(Args, CmdArgs);
1605 break;
1606
1607 case llvm::Triple::systemz:
1608 AddSystemZTargetArgs(Args, CmdArgs);
1609 break;
1610
1611 case llvm::Triple::x86:
1612 case llvm::Triple::x86_64:
1613 AddX86TargetArgs(Args, CmdArgs);
1614 break;
1615
1616 case llvm::Triple::lanai:
1617 AddLanaiTargetArgs(Args, CmdArgs);
1618 break;
1619
1620 case llvm::Triple::hexagon:
1621 AddHexagonTargetArgs(Args, CmdArgs);
1622 break;
1623
1624 case llvm::Triple::wasm32:
1625 case llvm::Triple::wasm64:
1626 AddWebAssemblyTargetArgs(Args, CmdArgs);
1627 break;
1628
1629 case llvm::Triple::ve:
1630 AddVETargetArgs(Args, CmdArgs);
1631 break;
1632 }
1633}
1634
1635namespace {
1636void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1637 ArgStringList &CmdArgs) {
1638 const char *ABIName = nullptr;
1639 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1640 ABIName = A->getValue();
1641 else if (Triple.isOSDarwin())
1642 ABIName = "darwinpcs";
1643 // TODO: we probably want to have some target hook here.
1644 else if (Triple.isOSLinux() &&
1645 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1646 ABIName = "pauthtest";
1647 else
1648 ABIName = "aapcs";
1649
1650 CmdArgs.push_back(Elt: "-target-abi");
1651 CmdArgs.push_back(Elt: ABIName);
1652}
1653}
1654
1655void Clang::AddAArch64TargetArgs(const ArgList &Args,
1656 ArgStringList &CmdArgs) const {
1657 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1658
1659 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1660 Args.hasArg(Ids: options::OPT_mkernel) ||
1661 Args.hasArg(Ids: options::OPT_fapple_kext))
1662 CmdArgs.push_back(Elt: "-disable-red-zone");
1663
1664 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1665 Neg: options::OPT_mno_implicit_float, Default: true))
1666 CmdArgs.push_back(Elt: "-no-implicit-float");
1667
1668 RenderAArch64ABI(Triple, Args, CmdArgs);
1669
1670 // Forward the -mglobal-merge option for explicit control over the pass.
1671 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1672 Ids: options::OPT_mno_global_merge)) {
1673 CmdArgs.push_back(Elt: "-mllvm");
1674 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1675 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1676 else
1677 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1678 }
1679
1680 // Handle -msve_vector_bits=<bits>
1681 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1682 StringRef VScaleMax) {
1683 StringRef Val = A->getValue();
1684 const Driver &D = getToolChain().getDriver();
1685 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1686 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1687 Val == "1024+" || Val == "2048+") {
1688 unsigned Bits = 0;
1689 if (!Val.consume_back(Suffix: "+")) {
1690 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1691 (void)Invalid;
1692 assert(!Invalid && "Failed to parse value");
1693 CmdArgs.push_back(
1694 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1695 }
1696
1697 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1698 (void)Invalid;
1699 assert(!Invalid && "Failed to parse value");
1700
1701 CmdArgs.push_back(
1702 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1703 } else if (Val == "scalable") {
1704 // Silently drop requests for vector-length agnostic code as it's implied.
1705 } else {
1706 // Handle the unsupported values passed to msve-vector-bits.
1707 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1708 << A->getSpelling() << Val;
1709 }
1710 };
1711 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1712 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1713 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1714 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1715
1716 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1717
1718 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1719 CmdArgs.push_back(Elt: "-tune-cpu");
1720 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
1721 }
1722
1723 AddUnalignedAccessWarning(CmdArgs);
1724
1725 if (Triple.isOSDarwin() ||
1726 (Triple.isOSLinux() &&
1727 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1728 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1729 Neg: options::OPT_fno_ptrauth_intrinsics);
1730 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1731 Neg: options::OPT_fno_ptrauth_calls);
1732 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1733 Neg: options::OPT_fno_ptrauth_returns);
1734 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1735 Neg: options::OPT_fno_ptrauth_auth_traps);
1736 Args.addOptInFlag(
1737 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1738 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1739 Args.addOptInFlag(
1740 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1741 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1742 Args.addOptInFlag(
1743 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1744 Neg: options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1745 Args.addOptInFlag(
1746 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1747 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1748 Args.addOptInFlag(
1749 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1750 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1751 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1752 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1753 }
1754 if (Triple.isOSLinux() &&
1755 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1756 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1757 Neg: options::OPT_fno_ptrauth_init_fini);
1758 Args.addOptInFlag(
1759 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1760 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1761 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1762 Neg: options::OPT_fno_ptrauth_elf_got);
1763 }
1764 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1765 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1766
1767 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1768 Neg: options::OPT_fno_ptrauth_objc_isa);
1769 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1770 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1771 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1772 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1773
1774 // Enable/disable return address signing and indirect branch targets.
1775 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1776}
1777
1778void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1779 ArgStringList &CmdArgs) const {
1780 const llvm::Triple &Triple = getToolChain().getTriple();
1781
1782 CmdArgs.push_back(Elt: "-target-abi");
1783 CmdArgs.push_back(
1784 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1785 .data());
1786
1787 // Handle -mtune.
1788 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1789 std::string TuneCPU = A->getValue();
1790 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1791 CmdArgs.push_back(Elt: "-tune-cpu");
1792 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1793 }
1794
1795 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1796 Ids: options::OPT_mno_annotate_tablejump)) {
1797 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1798 CmdArgs.push_back(Elt: "-mllvm");
1799 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1800 }
1801 }
1802}
1803
1804void Clang::AddMIPSTargetArgs(const ArgList &Args,
1805 ArgStringList &CmdArgs) const {
1806 const Driver &D = getToolChain().getDriver();
1807 StringRef CPUName;
1808 StringRef ABIName;
1809 const llvm::Triple &Triple = getToolChain().getTriple();
1810 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1811
1812 CmdArgs.push_back(Elt: "-target-abi");
1813 CmdArgs.push_back(Elt: ABIName.data());
1814
1815 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1816 if (ABI == mips::FloatABI::Soft) {
1817 // Floating point operations and argument passing are soft.
1818 CmdArgs.push_back(Elt: "-msoft-float");
1819 CmdArgs.push_back(Elt: "-mfloat-abi");
1820 CmdArgs.push_back(Elt: "soft");
1821 } else {
1822 // Floating point operations and argument passing are hard.
1823 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1824 CmdArgs.push_back(Elt: "-mfloat-abi");
1825 CmdArgs.push_back(Elt: "hard");
1826 }
1827
1828 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1829 Ids: options::OPT_mno_ldc1_sdc1)) {
1830 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1831 CmdArgs.push_back(Elt: "-mllvm");
1832 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1833 }
1834 }
1835
1836 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1837 Ids: options::OPT_mno_check_zero_division)) {
1838 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1839 CmdArgs.push_back(Elt: "-mllvm");
1840 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1841 }
1842 }
1843
1844 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1845 CmdArgs.push_back(Elt: "-mllvm");
1846 CmdArgs.push_back(Elt: "-mfix4300");
1847 }
1848
1849 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1850 StringRef v = A->getValue();
1851 CmdArgs.push_back(Elt: "-mllvm");
1852 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1853 A->claim();
1854 }
1855
1856 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1857 Arg *ABICalls =
1858 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1859
1860 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1861 // -mgpopt is the default for static, -fno-pic environments but these two
1862 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1863 // the only case where -mllvm -mgpopt is passed.
1864 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1865 // passed explicitly when compiling something with -mabicalls
1866 // (implictly) in affect. Currently the warning is in the backend.
1867 //
1868 // When the ABI in use is N64, we also need to determine the PIC mode that
1869 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1870 bool NoABICalls =
1871 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1872
1873 llvm::Reloc::Model RelocationModel;
1874 unsigned PICLevel;
1875 bool IsPIE;
1876 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1877 ParsePICArgs(ToolChain: getToolChain(), Args);
1878
1879 NoABICalls = NoABICalls ||
1880 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1881
1882 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1883 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1884 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1885 CmdArgs.push_back(Elt: "-mllvm");
1886 CmdArgs.push_back(Elt: "-mgpopt");
1887
1888 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1889 Ids: options::OPT_mno_local_sdata);
1890 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1891 Ids: options::OPT_mno_extern_sdata);
1892 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1893 Ids: options::OPT_mno_embedded_data);
1894 if (LocalSData) {
1895 CmdArgs.push_back(Elt: "-mllvm");
1896 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1897 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1898 } else {
1899 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1900 }
1901 LocalSData->claim();
1902 }
1903
1904 if (ExternSData) {
1905 CmdArgs.push_back(Elt: "-mllvm");
1906 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1907 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1908 } else {
1909 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1910 }
1911 ExternSData->claim();
1912 }
1913
1914 if (EmbeddedData) {
1915 CmdArgs.push_back(Elt: "-mllvm");
1916 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1917 CmdArgs.push_back(Elt: "-membedded-data=1");
1918 } else {
1919 CmdArgs.push_back(Elt: "-membedded-data=0");
1920 }
1921 EmbeddedData->claim();
1922 }
1923
1924 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1925 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1926
1927 if (GPOpt)
1928 GPOpt->claim();
1929
1930 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1931 StringRef Val = StringRef(A->getValue());
1932 if (mips::hasCompactBranches(CPU&: CPUName)) {
1933 if (Val == "never" || Val == "always" || Val == "optimal") {
1934 CmdArgs.push_back(Elt: "-mllvm");
1935 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1936 } else
1937 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1938 << A->getSpelling() << Val;
1939 } else
1940 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
1941 }
1942
1943 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
1944 Ids: options::OPT_mno_relax_pic_calls)) {
1945 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
1946 CmdArgs.push_back(Elt: "-mllvm");
1947 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1948 }
1949 }
1950}
1951
1952void Clang::AddPPCTargetArgs(const ArgList &Args,
1953 ArgStringList &CmdArgs) const {
1954 const Driver &D = getToolChain().getDriver();
1955 const llvm::Triple &T = getToolChain().getTriple();
1956 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1957 CmdArgs.push_back(Elt: "-tune-cpu");
1958 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
1959 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
1960 }
1961
1962 // Select the ABI to use.
1963 const char *ABIName = nullptr;
1964 if (T.isOSBinFormatELF()) {
1965 switch (getToolChain().getArch()) {
1966 case llvm::Triple::ppc64: {
1967 if (T.isPPC64ELFv2ABI())
1968 ABIName = "elfv2";
1969 else
1970 ABIName = "elfv1";
1971 break;
1972 }
1973 case llvm::Triple::ppc64le:
1974 ABIName = "elfv2";
1975 break;
1976 default:
1977 break;
1978 }
1979 }
1980
1981 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1982 bool VecExtabi = false;
1983 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
1984 StringRef V = A->getValue();
1985 if (V == "ieeelongdouble") {
1986 IEEELongDouble = true;
1987 A->claim();
1988 } else if (V == "ibmlongdouble") {
1989 IEEELongDouble = false;
1990 A->claim();
1991 } else if (V == "vec-default") {
1992 VecExtabi = false;
1993 A->claim();
1994 } else if (V == "vec-extabi") {
1995 VecExtabi = true;
1996 A->claim();
1997 } else if (V == "elfv1") {
1998 ABIName = "elfv1";
1999 A->claim();
2000 } else if (V == "elfv2") {
2001 ABIName = "elfv2";
2002 A->claim();
2003 } else if (V != "altivec")
2004 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2005 // the option if given as we don't have backend support for any targets
2006 // that don't use the altivec abi.
2007 ABIName = A->getValue();
2008 }
2009 if (IEEELongDouble)
2010 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
2011 if (VecExtabi) {
2012 if (!T.isOSAIX())
2013 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2014 << "-mabi=vec-extabi" << T.str();
2015 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
2016 }
2017
2018 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
2019 CmdArgs.push_back(Elt: "-disable-red-zone");
2020
2021 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2022 if (FloatABI == ppc::FloatABI::Soft) {
2023 // Floating point operations and argument passing are soft.
2024 CmdArgs.push_back(Elt: "-msoft-float");
2025 CmdArgs.push_back(Elt: "-mfloat-abi");
2026 CmdArgs.push_back(Elt: "soft");
2027 } else {
2028 // Floating point operations and argument passing are hard.
2029 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2030 CmdArgs.push_back(Elt: "-mfloat-abi");
2031 CmdArgs.push_back(Elt: "hard");
2032 }
2033
2034 if (ABIName) {
2035 CmdArgs.push_back(Elt: "-target-abi");
2036 CmdArgs.push_back(Elt: ABIName);
2037 }
2038}
2039
2040void Clang::AddRISCVTargetArgs(const ArgList &Args,
2041 ArgStringList &CmdArgs) const {
2042 const llvm::Triple &Triple = getToolChain().getTriple();
2043 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2044
2045 CmdArgs.push_back(Elt: "-target-abi");
2046 CmdArgs.push_back(Elt: ABIName.data());
2047
2048 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2049 CmdArgs.push_back(Elt: "-msmall-data-limit");
2050 CmdArgs.push_back(Elt: A->getValue());
2051 }
2052
2053 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2054 Neg: options::OPT_mno_implicit_float, Default: true))
2055 CmdArgs.push_back(Elt: "-no-implicit-float");
2056
2057 auto TuneCPU = riscv::getRISCVTuneCPU(D: getToolChain().getDriver(), Args);
2058 if (!TuneCPU)
2059 return;
2060 if (!TuneCPU->empty()) {
2061 CmdArgs.push_back(Elt: "-tune-cpu");
2062 // TuneCPU might or might not be the original -mtune string, so we
2063 // have to create a new copy here.
2064 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
2065 }
2066
2067 // Handle -mrvv-vector-bits=<bits>
2068 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2069 StringRef Val = A->getValue();
2070 const Driver &D = getToolChain().getDriver();
2071
2072 // Get minimum VLen from march.
2073 unsigned MinVLen = 0;
2074 std::string Arch = riscv::getRISCVArch(Args, Triple);
2075 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2076 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2077 // Ignore parsing error.
2078 if (!errorToBool(Err: ISAInfo.takeError()))
2079 MinVLen = (*ISAInfo)->getMinVLen();
2080
2081 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2082 // as integer as long as we have a MinVLen.
2083 unsigned Bits = 0;
2084 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2085 Bits = MinVLen;
2086 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2087 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2088 // at least MinVLen.
2089 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2090 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2091 Bits = 0;
2092 }
2093
2094 // If we got a valid value try to use it.
2095 if (Bits != 0) {
2096 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2097 CmdArgs.push_back(
2098 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2099 CmdArgs.push_back(
2100 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2101 } else if (Val != "scalable") {
2102 // Handle the unsupported values passed to mrvv-vector-bits.
2103 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2104 << A->getSpelling() << Val;
2105 }
2106 }
2107}
2108
2109void Clang::AddSparcTargetArgs(const ArgList &Args,
2110 ArgStringList &CmdArgs) const {
2111 sparc::FloatABI FloatABI =
2112 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2113
2114 if (FloatABI == sparc::FloatABI::Soft) {
2115 // Floating point operations and argument passing are soft.
2116 CmdArgs.push_back(Elt: "-msoft-float");
2117 CmdArgs.push_back(Elt: "-mfloat-abi");
2118 CmdArgs.push_back(Elt: "soft");
2119 } else {
2120 // Floating point operations and argument passing are hard.
2121 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2122 CmdArgs.push_back(Elt: "-mfloat-abi");
2123 CmdArgs.push_back(Elt: "hard");
2124 }
2125
2126 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2127 StringRef Name = A->getValue();
2128 std::string TuneCPU;
2129 if (Name == "native")
2130 TuneCPU = std::string(llvm::sys::getHostCPUName());
2131 else
2132 TuneCPU = std::string(Name);
2133
2134 CmdArgs.push_back(Elt: "-tune-cpu");
2135 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2136 }
2137}
2138
2139void Clang::AddSystemZTargetArgs(const ArgList &Args,
2140 ArgStringList &CmdArgs) const {
2141 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2142 CmdArgs.push_back(Elt: "-tune-cpu");
2143 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2144 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2145 else
2146 CmdArgs.push_back(Elt: A->getValue());
2147 }
2148
2149 bool HasBackchain =
2150 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2151 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2152 Neg: options::OPT_mno_packed_stack, Default: false);
2153 systemz::FloatABI FloatABI =
2154 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2155 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2156
2157 // Only hard float ABI (-mhard-float) is supported on z/OS.
2158 const Driver &D = getToolChain().getDriver();
2159 const llvm::Triple &Triple = getToolChain().getTriple();
2160 if (HasSoftFloat && Triple.isOSzOS()) {
2161 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2162 << "-msoft-float" << Triple.str();
2163 }
2164 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2165 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2166 << "-mpacked-stack -mbackchain -mhard-float";
2167 }
2168 if (HasBackchain)
2169 CmdArgs.push_back(Elt: "-mbackchain");
2170 if (HasPackedStack)
2171 CmdArgs.push_back(Elt: "-mpacked-stack");
2172 if (HasSoftFloat) {
2173 // Floating point operations and argument passing are soft.
2174 CmdArgs.push_back(Elt: "-msoft-float");
2175 CmdArgs.push_back(Elt: "-mfloat-abi");
2176 CmdArgs.push_back(Elt: "soft");
2177 }
2178
2179 if (Triple.isOSzOS())
2180 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mzos_ppa1_name,
2181 Ids: options::OPT_mno_zos_ppa1_name);
2182}
2183
2184void Clang::AddX86TargetArgs(const ArgList &Args,
2185 ArgStringList &CmdArgs) const {
2186 const Driver &D = getToolChain().getDriver();
2187 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2188
2189 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2190 Args.hasArg(Ids: options::OPT_mkernel) ||
2191 Args.hasArg(Ids: options::OPT_fapple_kext))
2192 CmdArgs.push_back(Elt: "-disable-red-zone");
2193
2194 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2195 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2196 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2197
2198 // Default to avoid implicit floating-point for kernel/kext code, but allow
2199 // that to be overridden with -mno-soft-float.
2200 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2201 Args.hasArg(Ids: options::OPT_fapple_kext));
2202 if (Arg *A = Args.getLastArg(
2203 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2204 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2205 const Option &O = A->getOption();
2206 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2207 O.matches(ID: options::OPT_msoft_float));
2208 }
2209 if (NoImplicitFloat)
2210 CmdArgs.push_back(Elt: "-no-implicit-float");
2211
2212 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2213 StringRef Value = A->getValue();
2214 if (Value == "intel" || Value == "att") {
2215 CmdArgs.push_back(Elt: "-mllvm");
2216 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2217 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2218 } else {
2219 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2220 << A->getSpelling() << Value;
2221 }
2222 } else if (D.IsCLMode()) {
2223 CmdArgs.push_back(Elt: "-mllvm");
2224 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2225 }
2226
2227 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2228 Ids: options::OPT_mno_skip_rax_setup))
2229 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2230 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2231
2232 // Set flags to support MCU ABI.
2233 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2234 CmdArgs.push_back(Elt: "-mfloat-abi");
2235 CmdArgs.push_back(Elt: "soft");
2236 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2237 }
2238
2239 // Handle -mtune.
2240
2241 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2242 std::string TuneCPU;
2243 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2244 TuneCPU = "generic";
2245
2246 // Override based on -mtune.
2247 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2248 StringRef Name = A->getValue();
2249
2250 if (Name == "native") {
2251 Name = llvm::sys::getHostCPUName();
2252 if (!Name.empty())
2253 TuneCPU = std::string(Name);
2254 } else
2255 TuneCPU = std::string(Name);
2256 }
2257
2258 if (!TuneCPU.empty()) {
2259 CmdArgs.push_back(Elt: "-tune-cpu");
2260 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2261 }
2262}
2263
2264static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2265 size_t Index = Option.find(C: Delimiter);
2266 if (Index != StringRef::npos)
2267 Option = Option.substr(Start: 0, N: Index);
2268 return Option;
2269}
2270
2271static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2272 Opt = getOptionName(Option: Opt);
2273 if (CmdArgs.size() < 2)
2274 return;
2275
2276 for (auto It = std::next(x: CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2277 StringRef Option = *It;
2278 if (!Option.starts_with(Prefix: Opt))
2279 continue;
2280 Option = getOptionName(Option);
2281 if (Option != Opt)
2282 continue;
2283 if (StringRef(*(It - 1)) != "-mllvm")
2284 continue;
2285
2286 It = CmdArgs.erase(CI: It);
2287 CmdArgs.erase(CI: It - 1);
2288 return;
2289 }
2290}
2291
2292static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2293 checkAndRemoveLLVMArg(CmdArgs, Opt: A);
2294 CmdArgs.push_back(Elt: "-mllvm");
2295 CmdArgs.push_back(Elt: A);
2296}
2297
2298static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2299 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2300 StringRef Option = *It;
2301 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2302 It = CmdArgs.erase(CI: It);
2303 Ie = CmdArgs.end();
2304 } else {
2305 ++It;
2306 }
2307 }
2308
2309 CmdArgs.push_back(Elt: "-menable-no-infs");
2310 CmdArgs.push_back(Elt: "-menable-no-nans");
2311 CmdArgs.push_back(Elt: "-fapprox-func");
2312 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
2313 CmdArgs.push_back(Elt: "-fno-signed-zeros");
2314 CmdArgs.push_back(Elt: "-mreassociate");
2315 CmdArgs.push_back(Elt: "-freciprocal-math");
2316 CmdArgs.push_back(Elt: "-ffp-contract=fast");
2317 CmdArgs.push_back(Elt: "-ffast-math");
2318 CmdArgs.push_back(Elt: "-ffinite-math-only");
2319 CmdArgs.push_back(Elt: "-D__FAST_MATH__");
2320 pushBackLLVMArg(CmdArgs, A: "-fast-math=true");
2321}
2322
2323static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2324 ArgStringList &CmdArgs) {
2325 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2326 bool HasHVX = HvxVerOpt.has_value();
2327 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2328 if (!Args.hasArg(Ids: options::OPT_mhexagon_hvx, Ids: options::OPT_mhexagon_hvx_EQ,
2329 Ids: options::OPT_mhexagon_hvx_ieee_fp) ||
2330 !HasHVX)
2331 return;
2332 unsigned HvxVerNum = 0;
2333 if (StringRef(HvxVer).drop_front(N: 1).getAsInteger(Radix: 10, Result&: HvxVerNum))
2334 HvxVerNum = 0;
2335
2336 if (Arg *A = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2337 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2338 Ids: options::OPT_mhexagon_hvx_ieee_fp)) {
2339 if (HvxVerNum >= 79) {
2340 if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2341 const char *Mode =
2342 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2343 .Case(S: "strict-ieee", Value: "-hexagon-qfloat-mode=strict-ieee")
2344 .Case(S: "ieee", Value: "-hexagon-qfloat-mode=ieee")
2345 .Case(S: "lossy", Value: "-hexagon-qfloat-mode=lossy")
2346 .Case(S: "legacy", Value: "-hexagon-qfloat-mode=legacy")
2347 .Default(Value: nullptr);
2348 if (!Mode) {
2349 D.Diag(DiagID: diag::err_drv_invalid_value)
2350 << A->getAsString(Args) << A->getValue();
2351 return;
2352 }
2353 pushBackLLVMArg(CmdArgs, A: Mode);
2354 if (strcmp(s1: Mode, s2: "-hexagon-qfloat-mode=lossy") == 0)
2355 addQFloatLossyFastMathArgs(CmdArgs);
2356 } else if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat)) {
2357 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=lossy");
2358 addQFloatLossyFastMathArgs(CmdArgs);
2359 } else {
2360 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=ieee");
2361 }
2362 } else {
2363 if (Arg *QFloatArg = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2364 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2365 Ids: options::OPT_mno_hexagon_hvx_qfloat);
2366 QFloatArg &&
2367 QFloatArg->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2368 D.Diag(DiagID: diag::warn_drv_unsupported_option_part_for_target)
2369 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2370 << (std::string("HVX ") + HvxVer +
2371 "; falling back to legacy qfloat mode");
2372 }
2373 }
2374 }
2375}
2376
2377void Clang::AddHexagonTargetArgs(const ArgList &Args,
2378 ArgStringList &CmdArgs) const {
2379 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2380 CmdArgs.push_back(Elt: "-Wreturn-type");
2381
2382 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2383 CmdArgs.push_back(Elt: "-mllvm");
2384 CmdArgs.push_back(
2385 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2386 }
2387
2388 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2389 CmdArgs.push_back(Elt: "-fshort-enums");
2390 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2391 CmdArgs.push_back(Elt: "-mllvm");
2392 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2393 }
2394 CmdArgs.push_back(Elt: "-mllvm");
2395 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2396
2397 addQFloatBackendArg(D: getToolChain().getDriver(), Args, CmdArgs);
2398}
2399
2400void Clang::AddLanaiTargetArgs(const ArgList &Args,
2401 ArgStringList &CmdArgs) const {
2402 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2403 StringRef CPUName = A->getValue();
2404
2405 CmdArgs.push_back(Elt: "-target-cpu");
2406 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2407 }
2408 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2409 StringRef Value = A->getValue();
2410 // Only support mregparm=4 to support old usage. Report error for all other
2411 // cases.
2412 int Mregparm;
2413 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2414 if (Mregparm != 4) {
2415 getToolChain().getDriver().Diag(
2416 DiagID: diag::err_drv_unsupported_option_argument)
2417 << A->getSpelling() << Value;
2418 }
2419 }
2420 }
2421}
2422
2423void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2424 ArgStringList &CmdArgs) const {
2425 // Default to "hidden" visibility.
2426 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2427 Ids: options::OPT_fvisibility_ms_compat))
2428 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2429}
2430
2431void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2432 // Floating point operations and argument passing are hard.
2433 CmdArgs.push_back(Elt: "-mfloat-abi");
2434 CmdArgs.push_back(Elt: "hard");
2435}
2436
2437void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2438 StringRef Target, const InputInfo &Output,
2439 const InputInfo &Input, const ArgList &Args) const {
2440 // If this is a dry run, do not create the compilation database file.
2441 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2442 return;
2443
2444 using llvm::yaml::escape;
2445 const Driver &D = getToolChain().getDriver();
2446
2447 if (!CompilationDatabase) {
2448 std::error_code EC;
2449 auto File = std::make_unique<llvm::raw_fd_ostream>(
2450 args&: Filename, args&: EC,
2451 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2452 if (EC) {
2453 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2454 << EC.message();
2455 return;
2456 }
2457 CompilationDatabase = std::move(File);
2458 }
2459 auto &CDB = *CompilationDatabase;
2460 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2461 if (!CWD)
2462 CWD = ".";
2463 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2464 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2465 if (Output.isFilename())
2466 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2467 CDB << ", \"arguments\": [\"" << escape(Input: D.DriverExecutable) << "\"";
2468 SmallString<128> Buf;
2469 Buf = "-x";
2470 Buf += types::getTypeName(Id: Input.getType());
2471 CDB << ", \"" << escape(Input: Buf) << "\"";
2472 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2473 Buf = "--sysroot=";
2474 Buf += D.SysRoot;
2475 CDB << ", \"" << escape(Input: Buf) << "\"";
2476 }
2477 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2478 if (Output.isFilename())
2479 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2480 for (auto &A: Args) {
2481 auto &O = A->getOption();
2482 // Skip language selection, which is positional.
2483 if (O.getID() == options::OPT_x)
2484 continue;
2485 // Skip writing dependency output and the compilation database itself.
2486 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2487 continue;
2488 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2489 continue;
2490 // Skip inputs.
2491 if (O.getKind() == Option::InputClass)
2492 continue;
2493 // Skip output.
2494 if (O.getID() == options::OPT_o)
2495 continue;
2496 // All other arguments are quoted and appended.
2497 ArgStringList ASL;
2498 A->render(Args, Output&: ASL);
2499 for (auto &it: ASL)
2500 CDB << ", \"" << escape(Input: it) << "\"";
2501 }
2502 Buf = "--target=";
2503 Buf += Target;
2504 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2505}
2506
2507void Clang::DumpCompilationDatabaseFragmentToDir(
2508 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2509 const InputInfo &Input, const llvm::opt::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 if (CompilationDatabase)
2515 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2516
2517 SmallString<256> Path = Dir;
2518 const auto &Driver = C.getDriver();
2519 Driver.getVFS().makeAbsolute(Path);
2520 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2521 if (Err) {
2522 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2523 return;
2524 }
2525
2526 llvm::sys::path::append(
2527 path&: Path,
2528 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2529 int FD;
2530 SmallString<256> TempPath;
2531 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2532 Flags: llvm::sys::fs::OF_Text);
2533 if (Err) {
2534 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2535 return;
2536 }
2537 CompilationDatabase =
2538 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2539 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2540}
2541
2542static bool CheckARMImplicitITArg(StringRef Value) {
2543 return Value == "always" || Value == "never" || Value == "arm" ||
2544 Value == "thumb";
2545}
2546
2547static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2548 StringRef Value) {
2549 CmdArgs.push_back(Elt: "-mllvm");
2550 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2551}
2552
2553static void CollectArgsForIntegratedAssembler(Compilation &C,
2554 const ArgList &Args,
2555 ArgStringList &CmdArgs,
2556 const Driver &D) {
2557 // Default to -mno-relax-all.
2558 //
2559 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2560 // cannot be done by assembler branch relaxation as it needs a free temporary
2561 // register. Because of this, branch relaxation is handled by a MachineIR pass
2562 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2563 // MachineIR branch relaxation inaccurate and it will miss cases where an
2564 // indirect branch is necessary.
2565 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2566 Neg: options::OPT_mno_relax_all);
2567
2568 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mincremental_linker_compatible,
2569 Ids: options::OPT_mno_incremental_linker_compatible);
2570
2571 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2572
2573 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2574 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2575
2576 // If you add more args here, also add them to the block below that
2577 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2578
2579 // When passing -I arguments to the assembler we sometimes need to
2580 // unconditionally take the next argument. For example, when parsing
2581 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2582 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2583 // arg after parsing the '-I' arg.
2584 bool TakeNextArg = false;
2585
2586 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2587 bool IsELF = Triple.isOSBinFormatELF();
2588 bool Crel = false, ExperimentalCrel = false;
2589 StringRef RelocSectionSym;
2590 bool SFrame = false, ExperimentalSFrame = false;
2591 bool ImplicitMapSyms = false;
2592 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2593 bool UseNoExecStack = false;
2594 bool Msa = false;
2595 const char *MipsTargetFeature = nullptr;
2596 llvm::SmallVector<const char *> SparcTargetFeatures;
2597 StringRef ImplicitIt;
2598 for (const Arg *A :
2599 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2600 Ids: options::OPT_mimplicit_it_EQ)) {
2601 A->claim();
2602
2603 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2604 switch (C.getDefaultToolChain().getArch()) {
2605 case llvm::Triple::arm:
2606 case llvm::Triple::armeb:
2607 case llvm::Triple::thumb:
2608 case llvm::Triple::thumbeb:
2609 // Only store the value; the last value set takes effect.
2610 ImplicitIt = A->getValue();
2611 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2612 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2613 << A->getSpelling() << ImplicitIt;
2614 continue;
2615 default:
2616 break;
2617 }
2618 }
2619
2620 for (StringRef Value : A->getValues()) {
2621 if (TakeNextArg) {
2622 CmdArgs.push_back(Elt: Value.data());
2623 TakeNextArg = false;
2624 continue;
2625 }
2626
2627 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2628 Value == "-mbig-obj")
2629 continue; // LLVM handles bigobj automatically
2630
2631 auto Equal = Value.split(Separator: '=');
2632 auto checkArg = [&](bool ValidTarget,
2633 std::initializer_list<const char *> Set) {
2634 if (!ValidTarget) {
2635 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2636 << (Twine("-Wa,") + Equal.first + "=").str()
2637 << Triple.getTriple();
2638 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2639 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2640 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2641 }
2642 };
2643 switch (C.getDefaultToolChain().getArch()) {
2644 default:
2645 break;
2646 case llvm::Triple::x86:
2647 case llvm::Triple::x86_64:
2648 if (Equal.first == "-mrelax-relocations" ||
2649 Equal.first == "--mrelax-relocations") {
2650 UseRelaxRelocations = Equal.second == "yes";
2651 checkArg(IsELF, {"yes", "no"});
2652 continue;
2653 }
2654 if (Value == "-msse2avx") {
2655 CmdArgs.push_back(Elt: "-msse2avx");
2656 continue;
2657 }
2658 break;
2659 case llvm::Triple::wasm32:
2660 case llvm::Triple::wasm64:
2661 if (Value == "--no-type-check") {
2662 CmdArgs.push_back(Elt: "-mno-type-check");
2663 continue;
2664 }
2665 break;
2666 case llvm::Triple::thumb:
2667 case llvm::Triple::thumbeb:
2668 case llvm::Triple::arm:
2669 case llvm::Triple::armeb:
2670 if (Equal.first == "-mimplicit-it") {
2671 // Only store the value; the last value set takes effect.
2672 ImplicitIt = Equal.second;
2673 checkArg(true, {"always", "never", "arm", "thumb"});
2674 continue;
2675 }
2676 if (Value == "-mthumb")
2677 // -mthumb has already been processed in ComputeLLVMTriple()
2678 // recognize but skip over here.
2679 continue;
2680 break;
2681 case llvm::Triple::aarch64:
2682 case llvm::Triple::aarch64_be:
2683 case llvm::Triple::aarch64_32:
2684 if (Equal.first == "-mmapsyms") {
2685 ImplicitMapSyms = Equal.second == "implicit";
2686 checkArg(IsELF, {"default", "implicit"});
2687 continue;
2688 }
2689 break;
2690 case llvm::Triple::mips:
2691 case llvm::Triple::mipsel:
2692 case llvm::Triple::mips64:
2693 case llvm::Triple::mips64el:
2694 if (Value == "--trap") {
2695 CmdArgs.push_back(Elt: "-target-feature");
2696 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2697 continue;
2698 }
2699 if (Value == "--break") {
2700 CmdArgs.push_back(Elt: "-target-feature");
2701 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2702 continue;
2703 }
2704 if (Value.starts_with(Prefix: "-msoft-float")) {
2705 CmdArgs.push_back(Elt: "-target-feature");
2706 CmdArgs.push_back(Elt: "+soft-float");
2707 continue;
2708 }
2709 if (Value.starts_with(Prefix: "-mhard-float")) {
2710 CmdArgs.push_back(Elt: "-target-feature");
2711 CmdArgs.push_back(Elt: "-soft-float");
2712 continue;
2713 }
2714 if (Value == "-mmsa") {
2715 Msa = true;
2716 continue;
2717 }
2718 if (Value == "-mno-msa") {
2719 Msa = false;
2720 continue;
2721 }
2722 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2723 .Case(S: "-mips1", Value: "+mips1")
2724 .Case(S: "-mips2", Value: "+mips2")
2725 .Case(S: "-mips3", Value: "+mips3")
2726 .Case(S: "-mips4", Value: "+mips4")
2727 .Case(S: "-mips5", Value: "+mips5")
2728 .Case(S: "-mips32", Value: "+mips32")
2729 .Case(S: "-mips32r2", Value: "+mips32r2")
2730 .Case(S: "-mips32r3", Value: "+mips32r3")
2731 .Case(S: "-mips32r5", Value: "+mips32r5")
2732 .Case(S: "-mips32r6", Value: "+mips32r6")
2733 .Case(S: "-mips64", Value: "+mips64")
2734 .Case(S: "-mips64r2", Value: "+mips64r2")
2735 .Case(S: "-mips64r3", Value: "+mips64r3")
2736 .Case(S: "-mips64r5", Value: "+mips64r5")
2737 .Case(S: "-mips64r6", Value: "+mips64r6")
2738 .Default(Value: nullptr);
2739 if (MipsTargetFeature)
2740 continue;
2741 break;
2742
2743 case llvm::Triple::sparc:
2744 case llvm::Triple::sparcel:
2745 case llvm::Triple::sparcv9:
2746 if (Value == "--undeclared-regs") {
2747 // LLVM already allows undeclared use of G registers, so this option
2748 // becomes a no-op. This solely exists for GNU compatibility.
2749 // TODO implement --no-undeclared-regs
2750 continue;
2751 }
2752 SparcTargetFeatures =
2753 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2754 .Case(S: "-Av8", Value: {"-v8plus"})
2755 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2756 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2757 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2758 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2759 .Case(S: "-Av9", Value: {"+v9"})
2760 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2761 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2762 .Case(S: "-Av9d", Value: {"+v9", "+vis", "+vis2", "+vis3"})
2763 .Default(Value: {});
2764 if (!SparcTargetFeatures.empty())
2765 continue;
2766 break;
2767 }
2768
2769 if (Value == "-force_cpusubtype_ALL") {
2770 // Do nothing, this is the default and we don't support anything else.
2771 } else if (Value == "-L") {
2772 CmdArgs.push_back(Elt: "-msave-temp-labels");
2773 } else if (Value == "--fatal-warnings") {
2774 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2775 } else if (Value == "--no-warn" || Value == "-W") {
2776 CmdArgs.push_back(Elt: "-massembler-no-warn");
2777 } else if (Value == "--noexecstack") {
2778 UseNoExecStack = true;
2779 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2780 Value.starts_with(Prefix: "--compress-debug-sections") ||
2781 Value == "-nocompress-debug-sections" ||
2782 Value == "--nocompress-debug-sections") {
2783 CmdArgs.push_back(Elt: Value.data());
2784 } else if (Value == "--crel") {
2785 Crel = true;
2786 } else if (Value == "--no-crel") {
2787 Crel = false;
2788 } else if (Value == "--allow-experimental-crel") {
2789 ExperimentalCrel = true;
2790 } else if (Value.starts_with(Prefix: "--reloc-section-sym=")) {
2791 RelocSectionSym = Value.substr(Start: strlen(s: "--reloc-section-sym="));
2792 } else if (Value.starts_with(Prefix: "-I")) {
2793 CmdArgs.push_back(Elt: Value.data());
2794 // We need to consume the next argument if the current arg is a plain
2795 // -I. The next arg will be the include directory.
2796 if (Value == "-I")
2797 TakeNextArg = true;
2798 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2799 // "-gdwarf-N" options are not cc1as options.
2800 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2801 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2802 CmdArgs.push_back(Elt: Value.data());
2803 } else {
2804 RenderDebugEnablingArgs(Args, CmdArgs,
2805 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2806 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2807 }
2808 } else if (Value == "--gsframe") {
2809 SFrame = true;
2810 } else if (Value == "--allow-experimental-sframe") {
2811 ExperimentalSFrame = true;
2812 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2813 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2814 // Do nothing, we'll validate it later.
2815 } else if (Value == "-defsym" || Value == "--defsym") {
2816 if (A->getNumValues() != 2) {
2817 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2818 break;
2819 }
2820 const char *S = A->getValue(N: 1);
2821 auto Pair = StringRef(S).split(Separator: '=');
2822 auto Sym = Pair.first;
2823 auto SVal = Pair.second;
2824
2825 if (Sym.empty() || SVal.empty()) {
2826 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2827 break;
2828 }
2829 int64_t IVal;
2830 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2831 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2832 break;
2833 }
2834 CmdArgs.push_back(Elt: "--defsym");
2835 TakeNextArg = true;
2836 } else if (Value == "-fdebug-compilation-dir") {
2837 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2838 TakeNextArg = true;
2839 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2840 // The flag is a -Wa / -Xassembler argument and Options doesn't
2841 // parse the argument, so this isn't automatically aliased to
2842 // -fdebug-compilation-dir (without '=') here.
2843 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2844 CmdArgs.push_back(Elt: Value.data());
2845 } else if (Value == "--version") {
2846 D.PrintVersion(C, OS&: llvm::outs());
2847 } else {
2848 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2849 << A->getSpelling() << Value;
2850 }
2851 }
2852 }
2853 if (ImplicitIt.size())
2854 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2855 if (Crel) {
2856 if (!ExperimentalCrel)
2857 D.Diag(DiagID: diag::err_drv_experimental_crel);
2858 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2859 CmdArgs.push_back(Elt: "--crel");
2860 } else {
2861 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2862 << "-Wa,--crel" << D.getTargetTriple();
2863 }
2864 }
2865 if (!RelocSectionSym.empty()) {
2866 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2867 RelocSectionSym != "none")
2868 D.Diag(DiagID: diag::err_drv_invalid_value)
2869 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2870 << RelocSectionSym;
2871 else if (Triple.isOSBinFormatELF())
2872 CmdArgs.push_back(
2873 Elt: Args.MakeArgString(Str: "--reloc-section-sym=" + RelocSectionSym));
2874 else
2875 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2876 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2877 }
2878 if (SFrame) {
2879 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2880 if (!ExperimentalSFrame)
2881 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2882 else
2883 CmdArgs.push_back(Elt: "--gsframe");
2884 } else {
2885 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2886 << "-Wa,--gsframe" << D.getTargetTriple();
2887 }
2888 }
2889 if (ImplicitMapSyms)
2890 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2891 if (Msa)
2892 CmdArgs.push_back(Elt: "-mmsa");
2893 if (!UseRelaxRelocations)
2894 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2895 if (UseNoExecStack)
2896 CmdArgs.push_back(Elt: "-mnoexecstack");
2897 if (MipsTargetFeature != nullptr) {
2898 CmdArgs.push_back(Elt: "-target-feature");
2899 CmdArgs.push_back(Elt: MipsTargetFeature);
2900 }
2901
2902 for (const char *Feature : SparcTargetFeatures) {
2903 CmdArgs.push_back(Elt: "-target-feature");
2904 CmdArgs.push_back(Elt: Feature);
2905 }
2906
2907 // forward -fembed-bitcode to assmebler
2908 if (C.getDriver().embedBitcodeEnabled() ||
2909 C.getDriver().embedBitcodeMarkerOnly())
2910 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2911
2912 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2913 CmdArgs.push_back(Elt: "-as-secure-log-file");
2914 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2915 }
2916}
2917
2918static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2919 bool OFastEnabled, const ArgList &Args,
2920 ArgStringList &CmdArgs,
2921 const JobAction &JA) {
2922 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2923 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2924 llvm::StringLiteral("SLEEF")};
2925 bool NoMathErrnoWasImpliedByVecLib = false;
2926 const Arg *VecLibArg = nullptr;
2927 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2928 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2929
2930 // Handle various floating point optimization flags, mapping them to the
2931 // appropriate LLVM code generation flags. This is complicated by several
2932 // "umbrella" flags, so we do this by stepping through the flags incrementally
2933 // adjusting what we think is enabled/disabled, then at the end setting the
2934 // LLVM flags based on the final state.
2935 bool HonorINFs = true;
2936 bool HonorNaNs = true;
2937 bool ApproxFunc = false;
2938 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2939 bool MathErrno = TC.IsMathErrnoDefault();
2940 bool AssociativeMath = false;
2941 bool ReciprocalMath = false;
2942 bool SignedZeros = true;
2943 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2944 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2945 // overriden by ffp-exception-behavior?
2946 bool RoundingFPMath = false;
2947 // -ffp-model values: strict, fast, precise
2948 StringRef FPModel = "";
2949 // -ffp-exception-behavior options: strict, maytrap, ignore
2950 StringRef FPExceptionBehavior = "";
2951 // -ffp-eval-method options: double, extended, source
2952 StringRef FPEvalMethod = "";
2953 llvm::DenormalMode DenormalFPMath =
2954 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2955 llvm::DenormalMode DenormalFP32Math =
2956 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
2957
2958 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2959 // If one wasn't given by the user, don't pass it here.
2960 StringRef FPContract;
2961 StringRef LastSeenFfpContractOption;
2962 StringRef LastFpContractOverrideOption;
2963 bool SeenUnsafeMathModeOption = false;
2964 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2965 !JA.isOffloading(OKind: Action::OFK_HIP))
2966 FPContract = "on";
2967 bool StrictFPModel = false;
2968 StringRef Float16ExcessPrecision = "";
2969 StringRef BFloat16ExcessPrecision = "";
2970 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2971 std::string ComplexRangeStr;
2972 StringRef LastComplexRangeOption;
2973
2974 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2975 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2976 if (Aggressive) {
2977 HonorINFs = false;
2978 HonorNaNs = false;
2979 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2980 LastOpt&: LastComplexRangeOption, Range);
2981 } else {
2982 HonorINFs = true;
2983 HonorNaNs = true;
2984 setComplexRange(D, NewOpt: CallerOption,
2985 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
2986 LastOpt&: LastComplexRangeOption, Range);
2987 }
2988 MathErrno = false;
2989 AssociativeMath = true;
2990 ReciprocalMath = true;
2991 ApproxFunc = true;
2992 SignedZeros = false;
2993 TrappingMath = false;
2994 RoundingFPMath = false;
2995 FPExceptionBehavior = "";
2996 FPContract = "fast";
2997 SeenUnsafeMathModeOption = true;
2998 };
2999
3000 // Lambda to consolidate common handling for fp-contract
3001 auto restoreFPContractState = [&]() {
3002 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3003 // For other targets, if the state has been changed by one of the
3004 // unsafe-math umbrella options a subsequent -fno-fast-math or
3005 // -fno-unsafe-math-optimizations option reverts to the last value seen for
3006 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3007 // option. If we have not seen an unsafe-math option or -ffp-contract,
3008 // we leave the FPContract state unchanged.
3009 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
3010 !JA.isOffloading(OKind: Action::OFK_HIP)) {
3011 if (LastSeenFfpContractOption != "")
3012 FPContract = LastSeenFfpContractOption;
3013 else if (SeenUnsafeMathModeOption)
3014 FPContract = "on";
3015 }
3016 // In this case, we're reverting to the last explicit fp-contract option
3017 // or the platform default
3018 LastFpContractOverrideOption = "";
3019 };
3020
3021 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
3022 CmdArgs.push_back(Elt: "-mlimit-float-precision");
3023 CmdArgs.push_back(Elt: A->getValue());
3024 }
3025
3026 for (const Arg *A : Args) {
3027 llvm::scope_exit CheckMathErrnoForVecLib(
3028 [&, MathErrnoBeforeArg = MathErrno] {
3029 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3030 ArgThatEnabledMathErrnoAfterVecLib = A;
3031 });
3032
3033 switch (A->getOption().getID()) {
3034 // If this isn't an FP option skip the claim below
3035 default: continue;
3036
3037 case options::OPT_fcx_limited_range:
3038 setComplexRange(D, NewOpt: A->getSpelling(),
3039 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
3040 LastOpt&: LastComplexRangeOption, Range);
3041 break;
3042 case options::OPT_fno_cx_limited_range:
3043 setComplexRange(D, NewOpt: A->getSpelling(),
3044 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3045 LastOpt&: LastComplexRangeOption, Range);
3046 break;
3047 case options::OPT_fcx_fortran_rules:
3048 setComplexRange(D, NewOpt: A->getSpelling(),
3049 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
3050 LastOpt&: LastComplexRangeOption, Range);
3051 break;
3052 case options::OPT_fno_cx_fortran_rules:
3053 setComplexRange(D, NewOpt: A->getSpelling(),
3054 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3055 LastOpt&: LastComplexRangeOption, Range);
3056 break;
3057 case options::OPT_fcomplex_arithmetic_EQ: {
3058 LangOptions::ComplexRangeKind RangeVal;
3059 StringRef Val = A->getValue();
3060 if (Val == "full")
3061 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
3062 else if (Val == "improved")
3063 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
3064 else if (Val == "promoted")
3065 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
3066 else if (Val == "basic")
3067 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
3068 else {
3069 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3070 << A->getSpelling() << Val;
3071 break;
3072 }
3073 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
3074 LastOpt&: LastComplexRangeOption, Range);
3075 break;
3076 }
3077 case options::OPT_ffp_model_EQ: {
3078 // If -ffp-model= is seen, reset to fno-fast-math
3079 HonorINFs = true;
3080 HonorNaNs = true;
3081 ApproxFunc = false;
3082 // Turning *off* -ffast-math restores the toolchain default.
3083 MathErrno = TC.IsMathErrnoDefault();
3084 AssociativeMath = false;
3085 ReciprocalMath = false;
3086 SignedZeros = true;
3087
3088 StringRef Val = A->getValue();
3089 if (OFastEnabled && Val != "aggressive") {
3090 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3091 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3092 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
3093 break;
3094 }
3095 StrictFPModel = false;
3096 if (!FPModel.empty() && FPModel != Val)
3097 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3098 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
3099 << Args.MakeArgString(Str: "-ffp-model=" + Val);
3100 if (Val == "fast") {
3101 FPModel = Val;
3102 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
3103 // applyFastMath sets fp-contract="fast"
3104 LastFpContractOverrideOption = "-ffp-model=fast";
3105 } else if (Val == "aggressive") {
3106 FPModel = Val;
3107 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
3108 // applyFastMath sets fp-contract="fast"
3109 LastFpContractOverrideOption = "-ffp-model=aggressive";
3110 } else if (Val == "precise") {
3111 FPModel = Val;
3112 FPContract = "on";
3113 LastFpContractOverrideOption = "-ffp-model=precise";
3114 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3115 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3116 LastOpt&: LastComplexRangeOption, Range);
3117 } else if (Val == "strict") {
3118 StrictFPModel = true;
3119 FPExceptionBehavior = "strict";
3120 FPModel = Val;
3121 FPContract = "off";
3122 LastFpContractOverrideOption = "-ffp-model=strict";
3123 TrappingMath = true;
3124 RoundingFPMath = true;
3125 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3126 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3127 LastOpt&: LastComplexRangeOption, Range);
3128 } else
3129 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3130 << A->getSpelling() << Val;
3131 break;
3132 }
3133
3134 // Options controlling individual features
3135 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3136 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3137 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3138 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3139 case options::OPT_fapprox_func: ApproxFunc = true; break;
3140 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3141 case options::OPT_fmath_errno: MathErrno = true; break;
3142 case options::OPT_fno_math_errno: MathErrno = false; break;
3143 case options::OPT_fassociative_math: AssociativeMath = true; break;
3144 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3145 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3146 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3147 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3148 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3149 case options::OPT_ftrapping_math:
3150 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3151 FPExceptionBehavior != "strict")
3152 // Warn that previous value of option is overridden.
3153 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3154 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3155 FPExceptionBehavior)
3156 << "-ftrapping-math";
3157 TrappingMath = true;
3158 TrappingMathPresent = true;
3159 FPExceptionBehavior = "strict";
3160 break;
3161 case options::OPT_fveclib:
3162 VecLibArg = A;
3163 NoMathErrnoWasImpliedByVecLib =
3164 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
3165 if (NoMathErrnoWasImpliedByVecLib)
3166 MathErrno = false;
3167 break;
3168 case options::OPT_fno_trapping_math:
3169 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3170 FPExceptionBehavior != "ignore")
3171 // Warn that previous value of option is overridden.
3172 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3173 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3174 FPExceptionBehavior)
3175 << "-fno-trapping-math";
3176 TrappingMath = false;
3177 TrappingMathPresent = true;
3178 FPExceptionBehavior = "ignore";
3179 break;
3180
3181 case options::OPT_frounding_math:
3182 RoundingFPMath = true;
3183 break;
3184
3185 case options::OPT_fno_rounding_math:
3186 RoundingFPMath = false;
3187 break;
3188
3189 case options::OPT_fdenormal_fp_math_EQ:
3190 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3191 DenormalFP32Math = DenormalFPMath;
3192 if (!DenormalFPMath.isValid()) {
3193 D.Diag(DiagID: diag::err_drv_invalid_value)
3194 << A->getAsString(Args) << A->getValue();
3195 }
3196 break;
3197
3198 case options::OPT_fdenormal_fp_math_f32_EQ:
3199 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3200 if (!DenormalFP32Math.isValid()) {
3201 D.Diag(DiagID: diag::err_drv_invalid_value)
3202 << A->getAsString(Args) << A->getValue();
3203 }
3204 break;
3205
3206 // Validate and pass through -ffp-contract option.
3207 case options::OPT_ffp_contract: {
3208 StringRef Val = A->getValue();
3209 if (Val == "fast" || Val == "on" || Val == "off" ||
3210 Val == "fast-honor-pragmas") {
3211 if (Val != FPContract && LastFpContractOverrideOption != "") {
3212 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3213 << LastFpContractOverrideOption
3214 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3215 }
3216
3217 FPContract = Val;
3218 LastSeenFfpContractOption = Val;
3219 LastFpContractOverrideOption = "";
3220 } else
3221 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3222 << A->getSpelling() << Val;
3223 break;
3224 }
3225
3226 // Validate and pass through -ffp-exception-behavior option.
3227 case options::OPT_ffp_exception_behavior_EQ: {
3228 StringRef Val = A->getValue();
3229 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3230 FPExceptionBehavior != Val)
3231 // Warn that previous value of option is overridden.
3232 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3233 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3234 FPExceptionBehavior)
3235 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3236 TrappingMath = TrappingMathPresent = false;
3237 if (Val == "ignore" || Val == "maytrap")
3238 FPExceptionBehavior = Val;
3239 else if (Val == "strict") {
3240 FPExceptionBehavior = Val;
3241 TrappingMath = TrappingMathPresent = true;
3242 } else
3243 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3244 << A->getSpelling() << Val;
3245 break;
3246 }
3247
3248 // Validate and pass through -ffp-eval-method option.
3249 case options::OPT_ffp_eval_method_EQ: {
3250 StringRef Val = A->getValue();
3251 if (Val == "double" || Val == "extended" || Val == "source")
3252 FPEvalMethod = Val;
3253 else
3254 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3255 << A->getSpelling() << Val;
3256 break;
3257 }
3258
3259 case options::OPT_fexcess_precision_EQ: {
3260 StringRef Val = A->getValue();
3261 const llvm::Triple::ArchType Arch = TC.getArch();
3262 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3263 if (Val == "standard" || Val == "fast")
3264 Float16ExcessPrecision = Val;
3265 // To make it GCC compatible, allow the value of "16" which
3266 // means disable excess precision, the same meaning than clang's
3267 // equivalent value "none".
3268 else if (Val == "16")
3269 Float16ExcessPrecision = "none";
3270 else
3271 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3272 << A->getSpelling() << Val;
3273 } else {
3274 if (!(Val == "standard" || Val == "fast"))
3275 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3276 << A->getSpelling() << Val;
3277 }
3278 BFloat16ExcessPrecision = Float16ExcessPrecision;
3279 break;
3280 }
3281 case options::OPT_ffinite_math_only:
3282 HonorINFs = false;
3283 HonorNaNs = false;
3284 break;
3285 case options::OPT_fno_finite_math_only:
3286 HonorINFs = true;
3287 HonorNaNs = true;
3288 break;
3289
3290 case options::OPT_funsafe_math_optimizations:
3291 AssociativeMath = true;
3292 ReciprocalMath = true;
3293 SignedZeros = false;
3294 ApproxFunc = true;
3295 TrappingMath = false;
3296 FPExceptionBehavior = "";
3297 FPContract = "fast";
3298 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3299 SeenUnsafeMathModeOption = true;
3300 break;
3301 case options::OPT_fno_unsafe_math_optimizations:
3302 AssociativeMath = false;
3303 ReciprocalMath = false;
3304 SignedZeros = true;
3305 ApproxFunc = false;
3306 restoreFPContractState();
3307 break;
3308
3309 case options::OPT_cl_fast_relaxed_math:
3310 applyFastMath(true, A->getSpelling());
3311 break;
3312
3313 case options::OPT_Ofast:
3314 // If -Ofast is the optimization level, then -ffast-math should be enabled
3315 if (!OFastEnabled)
3316 continue;
3317 [[fallthrough]];
3318 case options::OPT_ffast_math:
3319 applyFastMath(true, A->getSpelling());
3320 if (A->getOption().getID() == options::OPT_Ofast)
3321 LastFpContractOverrideOption = "-Ofast";
3322 else
3323 LastFpContractOverrideOption = "-ffast-math";
3324 break;
3325 case options::OPT_fno_fast_math:
3326 HonorINFs = true;
3327 HonorNaNs = true;
3328 // Turning on -ffast-math (with either flag) removes the need for
3329 // MathErrno. However, turning *off* -ffast-math merely restores the
3330 // toolchain default (which may be false).
3331 MathErrno = TC.IsMathErrnoDefault();
3332 AssociativeMath = false;
3333 ReciprocalMath = false;
3334 ApproxFunc = false;
3335 SignedZeros = true;
3336 restoreFPContractState();
3337 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3338 setComplexRange(D, NewOpt: A->getSpelling(),
3339 NewRange: LangOptions::ComplexRangeKind::CX_None,
3340 LastOpt&: LastComplexRangeOption, Range);
3341 else
3342 Range = LangOptions::ComplexRangeKind::CX_None;
3343 LastComplexRangeOption = "";
3344 LastFpContractOverrideOption = "";
3345 break;
3346 } // End switch (A->getOption().getID())
3347
3348 // The StrictFPModel local variable is needed to report warnings
3349 // in the way we intend. If -ffp-model=strict has been used, we
3350 // want to report a warning for the next option encountered that
3351 // takes us out of the settings described by fp-model=strict, but
3352 // we don't want to continue issuing warnings for other conflicting
3353 // options after that.
3354 if (StrictFPModel) {
3355 // If -ffp-model=strict has been specified on command line but
3356 // subsequent options conflict then emit warning diagnostic.
3357 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3358 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3359 FPContract == "off")
3360 // OK: Current Arg doesn't conflict with -ffp-model=strict
3361 ;
3362 else {
3363 StrictFPModel = false;
3364 FPModel = "";
3365 // The warning for -ffp-contract would have been reported by the
3366 // OPT_ffp_contract_EQ handler above. A special check here is needed
3367 // to avoid duplicating the warning.
3368 auto RHS = (A->getNumValues() == 0)
3369 ? A->getSpelling()
3370 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3371 if (A->getSpelling() != "-ffp-contract=") {
3372 if (RHS != "-ffp-model=strict")
3373 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3374 << "-ffp-model=strict" << RHS;
3375 }
3376 }
3377 }
3378
3379 // If we handled this option claim it
3380 A->claim();
3381 }
3382
3383 if (!HonorINFs)
3384 CmdArgs.push_back(Elt: "-menable-no-infs");
3385
3386 if (!HonorNaNs)
3387 CmdArgs.push_back(Elt: "-menable-no-nans");
3388
3389 if (ApproxFunc)
3390 CmdArgs.push_back(Elt: "-fapprox-func");
3391
3392 if (MathErrno) {
3393 CmdArgs.push_back(Elt: "-fmath-errno");
3394 if (NoMathErrnoWasImpliedByVecLib)
3395 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3396 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3397 << VecLibArg->getAsString(Args);
3398 }
3399
3400 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3401 !TrappingMath)
3402 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3403
3404 if (!SignedZeros)
3405 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3406
3407 if (AssociativeMath && !SignedZeros && !TrappingMath)
3408 CmdArgs.push_back(Elt: "-mreassociate");
3409
3410 if (ReciprocalMath)
3411 CmdArgs.push_back(Elt: "-freciprocal-math");
3412
3413 if (TrappingMath) {
3414 // FP Exception Behavior is also set to strict
3415 assert(FPExceptionBehavior == "strict");
3416 }
3417
3418 // The default is IEEE.
3419 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3420 llvm::SmallString<64> DenormFlag;
3421 llvm::raw_svector_ostream ArgStr(DenormFlag);
3422 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3423 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3424 }
3425
3426 // Add f32 specific denormal mode flag if it's different.
3427 if (DenormalFP32Math != DenormalFPMath) {
3428 llvm::SmallString<64> DenormFlag;
3429 llvm::raw_svector_ostream ArgStr(DenormFlag);
3430 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3431 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3432 }
3433
3434 if (!FPContract.empty())
3435 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3436
3437 if (RoundingFPMath)
3438 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3439 else
3440 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3441
3442 if (!FPExceptionBehavior.empty())
3443 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3444 FPExceptionBehavior));
3445
3446 if (!FPEvalMethod.empty())
3447 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3448
3449 if (!Float16ExcessPrecision.empty())
3450 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3451 Float16ExcessPrecision));
3452 if (!BFloat16ExcessPrecision.empty())
3453 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3454 BFloat16ExcessPrecision));
3455
3456 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3457 if (!Recip.empty())
3458 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3459
3460 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3461 // individual features enabled by -ffast-math instead of the option itself as
3462 // that's consistent with gcc's behaviour.
3463 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3464 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3465 CmdArgs.push_back(Elt: "-ffast-math");
3466
3467 // Handle __FINITE_MATH_ONLY__ similarly.
3468 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3469 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3470 // -menable-no-nans are set by the user.
3471 bool shouldAddFiniteMathOnly = false;
3472 if (!HonorINFs && !HonorNaNs) {
3473 shouldAddFiniteMathOnly = true;
3474 } else {
3475 bool InfValues = true;
3476 bool NanValues = true;
3477 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3478 StringRef ArgValue = Arg->getValue();
3479 if (ArgValue == "-menable-no-nans")
3480 NanValues = false;
3481 else if (ArgValue == "-menable-no-infs")
3482 InfValues = false;
3483 }
3484 if (!NanValues && !InfValues)
3485 shouldAddFiniteMathOnly = true;
3486 }
3487 if (shouldAddFiniteMathOnly) {
3488 CmdArgs.push_back(Elt: "-ffinite-math-only");
3489 }
3490 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3491 CmdArgs.push_back(Elt: "-mfpmath");
3492 CmdArgs.push_back(Elt: A->getValue());
3493 }
3494
3495 // Disable a codegen optimization for floating-point casts.
3496 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3497 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3498 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3499
3500 if (Range != LangOptions::ComplexRangeKind::CX_None)
3501 ComplexRangeStr = renderComplexRangeOption(Range);
3502 if (!ComplexRangeStr.empty()) {
3503 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3504 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3505 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3506 complexRangeKindToStr(Range)));
3507 }
3508 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3509 CmdArgs.push_back(Elt: "-fcx-limited-range");
3510 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3511 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3512 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3513 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3514 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3515 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3516}
3517
3518static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3519 const llvm::Triple &Triple,
3520 const InputInfo &Input) {
3521 // Add default argument set.
3522 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3523 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3524 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3525
3526 if (!Triple.isWindowsMSVCEnvironment()) {
3527 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3528 } else {
3529 // Enable "unix" checkers that also work on Windows.
3530 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3531 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3532 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3533 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3534 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3535 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3536 }
3537
3538 // Disable some unix checkers for PS4/PS5.
3539 if (Triple.isPS()) {
3540 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3541 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3542 }
3543
3544 if (Triple.isOSDarwin()) {
3545 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3546 CmdArgs.push_back(
3547 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3548 }
3549 else if (Triple.isOSFuchsia())
3550 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3551
3552 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3553
3554 if (types::isCXX(Id: Input.getType()))
3555 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3556
3557 if (!Triple.isPS()) {
3558 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3559 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3560 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3561 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3562 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3563 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3564 }
3565
3566 // Default nullability checks.
3567 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3568 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3569 }
3570
3571 // Set the output format. The default is plist, for (lame) historical reasons.
3572 CmdArgs.push_back(Elt: "-analyzer-output");
3573 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3574 CmdArgs.push_back(Elt: A->getValue());
3575 else
3576 CmdArgs.push_back(Elt: "plist");
3577
3578 // Disable the presentation of standard compiler warnings when using
3579 // --analyze. We only want to show static analyzer diagnostics or frontend
3580 // errors.
3581 CmdArgs.push_back(Elt: "-w");
3582
3583 // Add -Xanalyzer arguments when running as analyzer.
3584 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3585}
3586
3587static bool isValidSymbolName(StringRef S) {
3588 if (S.empty())
3589 return false;
3590
3591 if (std::isdigit(S[0]))
3592 return false;
3593
3594 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3595}
3596
3597static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3598 const ArgList &Args, ArgStringList &CmdArgs,
3599 bool KernelOrKext) {
3600 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3601
3602 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3603 // doesn't even have a stack!
3604 if (EffectiveTriple.isNVPTX())
3605 return;
3606
3607 // -stack-protector=0 is default.
3608 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3609 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3610 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3611
3612 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3613 Ids: options::OPT_fstack_protector_all,
3614 Ids: options::OPT_fstack_protector_strong,
3615 Ids: options::OPT_fstack_protector)) {
3616 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3617 StackProtectorLevel =
3618 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3619 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3620 StackProtectorLevel = LangOptions::SSPStrong;
3621 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3622 StackProtectorLevel = LangOptions::SSPReq;
3623
3624 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3625 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3626 << A->getSpelling() << EffectiveTriple.getTriple();
3627 StackProtectorLevel = DefaultStackProtectorLevel;
3628 }
3629 } else {
3630 StackProtectorLevel = DefaultStackProtectorLevel;
3631 }
3632
3633 if (StackProtectorLevel) {
3634 CmdArgs.push_back(Elt: "-stack-protector");
3635 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3636 }
3637
3638 // --param ssp-buffer-size=
3639 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3640 StringRef Str(A->getValue());
3641 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3642 if (StackProtectorLevel) {
3643 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3644 // FIXME: Verify the argument is a valid integer.
3645 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3646 }
3647 A->claim();
3648 }
3649 }
3650
3651 const std::string &TripleStr = EffectiveTriple.getTriple();
3652 StringRef GuardValue;
3653 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3654 GuardValue = A->getValue();
3655 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3656 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3657 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3658 !EffectiveTriple.isSystemZ())
3659 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3660 << A->getAsString(Args) << TripleStr;
3661 // z/OS only supports the tls mode.
3662 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3663 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3664 << A->getOption().getName() << GuardValue << "tls";
3665 return;
3666 }
3667 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3668 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3669 GuardValue != "tls" && GuardValue != "global") {
3670 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3671 << A->getOption().getName() << GuardValue << "tls global";
3672 return;
3673 }
3674 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3675 GuardValue == "tls") {
3676 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3677 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3678 << A->getAsString(Args);
3679 return;
3680 }
3681 // Check whether the target subarch supports the hardware TLS register
3682 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3683 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3684 << EffectiveTriple.getArchName();
3685 return;
3686 }
3687 // Check whether the user asked for something other than -mtp=cp15
3688 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3689 StringRef Value = A->getValue();
3690 if (Value != "cp15") {
3691 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3692 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3693 return;
3694 }
3695 }
3696 CmdArgs.push_back(Elt: "-target-feature");
3697 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3698 }
3699 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3700 GuardValue != "global") {
3701 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3702 << A->getOption().getName() << GuardValue << "sysreg global";
3703 return;
3704 }
3705 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3706 if (GuardValue != "tls" && GuardValue != "global") {
3707 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3708 << A->getOption().getName() << GuardValue << "tls global";
3709 return;
3710 }
3711 if (GuardValue == "tls") {
3712 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3713 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3714 << A->getAsString(Args);
3715 return;
3716 }
3717 }
3718 }
3719 A->render(Args, Output&: CmdArgs);
3720 }
3721
3722 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3723 StringRef Value = A->getValue();
3724 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3725 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3726 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3727 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3728 << A->getAsString(Args) << TripleStr;
3729 int Offset;
3730 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3731 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3732 return;
3733 }
3734 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3735 (Offset < 0 || Offset > 0xfffff)) {
3736 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3737 << A->getOption().getName() << Value;
3738 return;
3739 }
3740 A->render(Args, Output&: CmdArgs);
3741 }
3742
3743 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3744 StringRef Value = A->getValue();
3745 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3746 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3747 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3748 << A->getAsString(Args) << TripleStr;
3749 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3750 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3751 << A->getOption().getName() << Value << "fs gs";
3752 return;
3753 }
3754 if (EffectiveTriple.isAArch64() &&
3755 llvm::StringSwitch<bool>(Value)
3756 .Cases(CaseStrings: {"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3757 "tpidr_el2", "far_el1", "far_el2"},
3758 Value: false)
3759 .Default(Value: true)) {
3760 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3761 << A->getOption().getName() << Value
3762 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3763 return;
3764 }
3765 if (EffectiveTriple.isRISCV() && Value != "tp") {
3766 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3767 << A->getOption().getName() << Value << "tp";
3768 return;
3769 }
3770 if (EffectiveTriple.isPPC64() && Value != "r13") {
3771 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3772 << A->getOption().getName() << Value << "r13";
3773 return;
3774 }
3775 if (EffectiveTriple.isPPC32() && Value != "r2") {
3776 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3777 << A->getOption().getName() << Value << "r2";
3778 return;
3779 }
3780 A->render(Args, Output&: CmdArgs);
3781 }
3782
3783 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3784 StringRef Value = A->getValue();
3785 if (!isValidSymbolName(S: Value)) {
3786 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3787 << A->getOption().getName() << "legal symbol name";
3788 return;
3789 }
3790 A->render(Args, Output&: CmdArgs);
3791 }
3792
3793 if (Arg *A =
3794 Args.getLastArg(Ids: options::OPT_mstack_protector_guard_value_width_EQ)) {
3795 if (!EffectiveTriple.isAArch64())
3796 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3797 << A->getAsString(Args) << TripleStr;
3798 StringRef Value = A->getValue();
3799 unsigned Width;
3800 if (Value.getAsInteger(Radix: 10, Result&: Width)) {
3801 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3802 return;
3803 }
3804 if (Width != 4 && Width != 8) {
3805 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3806 << A->getOption().getName() << Value;
3807 }
3808 }
3809 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstackprotector_guard_record)) {
3810 if (!EffectiveTriple.isSystemZ()) {
3811 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3812 << A->getAsString(Args) << TripleStr;
3813 return;
3814 }
3815 if (GuardValue != "global") {
3816 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3817 << "-mstack-protector-guard-record"
3818 << "-mstack-protector-guard=global";
3819 return;
3820 }
3821 A->render(Args, Output&: CmdArgs);
3822 }
3823}
3824
3825static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3826 ArgStringList &CmdArgs) {
3827 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3828
3829 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3830 !EffectiveTriple.isOSFuchsia())
3831 return;
3832
3833 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3834 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3835 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3836 return;
3837
3838 if (Args.hasFlag(Pos: options::OPT_fstack_clash_protection,
3839 Neg: options::OPT_fno_stack_clash_protection,
3840 Default: EffectiveTriple.isAndroid()))
3841 CmdArgs.push_back(Elt: "-fstack-clash-protection");
3842}
3843
3844static void RenderTrivialAutoVarInitOptions(const Driver &D,
3845 const ToolChain &TC,
3846 const ArgList &Args,
3847 ArgStringList &CmdArgs) {
3848 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3849 StringRef TrivialAutoVarInit = "";
3850
3851 for (const Arg *A : Args) {
3852 switch (A->getOption().getID()) {
3853 default:
3854 continue;
3855 case options::OPT_ftrivial_auto_var_init: {
3856 A->claim();
3857 StringRef Val = A->getValue();
3858 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3859 TrivialAutoVarInit = Val;
3860 else
3861 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3862 << A->getSpelling() << Val;
3863 break;
3864 }
3865 }
3866 }
3867
3868 if (TrivialAutoVarInit.empty())
3869 switch (DefaultTrivialAutoVarInit) {
3870 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3871 break;
3872 case LangOptions::TrivialAutoVarInitKind::Pattern:
3873 TrivialAutoVarInit = "pattern";
3874 break;
3875 case LangOptions::TrivialAutoVarInitKind::Zero:
3876 TrivialAutoVarInit = "zero";
3877 break;
3878 }
3879
3880 if (!TrivialAutoVarInit.empty()) {
3881 CmdArgs.push_back(
3882 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3883 }
3884
3885 if (Arg *A =
3886 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3887 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3888 StringRef(
3889 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3890 "uninitialized")
3891 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3892 A->claim();
3893 StringRef Val = A->getValue();
3894 if (std::stoi(str: Val.str()) <= 0)
3895 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3896 CmdArgs.push_back(
3897 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3898 }
3899
3900 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3901 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3902 StringRef(
3903 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3904 "uninitialized")
3905 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3906 A->claim();
3907 StringRef Val = A->getValue();
3908 if (std::stoi(str: Val.str()) <= 0)
3909 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3910 CmdArgs.push_back(
3911 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3912 }
3913}
3914
3915static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3916 types::ID InputType) {
3917 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3918 // for denormal flushing handling based on the target.
3919 const unsigned ForwardedArguments[] = {
3920 options::OPT_cl_opt_disable,
3921 options::OPT_cl_strict_aliasing,
3922 options::OPT_cl_single_precision_constant,
3923 options::OPT_cl_finite_math_only,
3924 options::OPT_cl_kernel_arg_info,
3925 options::OPT_cl_unsafe_math_optimizations,
3926 options::OPT_cl_fast_relaxed_math,
3927 options::OPT_cl_mad_enable,
3928 options::OPT_cl_no_signed_zeros,
3929 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3930 options::OPT_cl_uniform_work_group_size
3931 };
3932
3933 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3934 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3935 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3936 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
3937 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3938 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3939 }
3940
3941 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
3942 CmdArgs.push_back(Elt: "-menable-no-infs");
3943 CmdArgs.push_back(Elt: "-menable-no-nans");
3944 }
3945
3946 for (const auto &Arg : ForwardedArguments)
3947 if (const auto *A = Args.getLastArg(Ids: Arg))
3948 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
3949
3950 // Only add the default headers if we are compiling OpenCL sources.
3951 if ((types::isOpenCL(Id: InputType) ||
3952 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
3953 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
3954 CmdArgs.push_back(Elt: "-finclude-default-header");
3955 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3956 }
3957}
3958
3959static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
3960 ArgStringList &CmdArgs, types::ID InputType) {
3961 const unsigned ForwardedArguments[] = {
3962 options::OPT_hlsl_all_resources_bound,
3963 options::OPT_dxil_validator_version,
3964 options::OPT_res_may_alias,
3965 options::OPT_D,
3966 options::OPT_I,
3967 options::OPT_O,
3968 options::OPT_emit_llvm,
3969 options::OPT_emit_obj,
3970 options::OPT_disable_llvm_passes,
3971 options::OPT_fnative_half_type,
3972 options::OPT_fnative_int16_type,
3973 options::OPT_fmatrix_memory_layout_EQ,
3974 options::OPT_hlsl_entrypoint,
3975 options::OPT_fdx_rootsignature_define,
3976 options::OPT_fdx_rootsignature_version,
3977 options::OPT_fhlsl_spv_use_unknown_image_format,
3978 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
3979 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
3980 options::OPT_fhlsl_spv_preserve_interface};
3981 if (!types::isHLSL(Id: InputType))
3982 return;
3983 for (const auto &Arg : ForwardedArguments)
3984 if (const auto *A = Args.getLastArg(Ids: Arg))
3985 A->renderAsInput(Args, Output&: CmdArgs);
3986 // Add the default headers if dxc_no_stdinc is not set.
3987 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
3988 !Args.hasArg(Ids: options::OPT_nostdinc))
3989 CmdArgs.push_back(Elt: "-finclude-default-header");
3990
3991 if (Args.hasArg(Ids: options::OPT_dxc_Zss)) {
3992 if (Args.hasArg(Ids: options::OPT_dxc_Zsb))
3993 D.Diag(DiagID: diag::err_drv_dxc_invalid_shader_hash);
3994 CmdArgs.push_back(Elt: "-mllvm");
3995 CmdArgs.push_back(Elt: "-dx-Zss");
3996 }
3997 if (Arg *A = Args.getLastArg(Ids: options::OPT_dxc_Zsb))
3998 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
3999 if (Args.hasArg(Ids: options::OPT_dxc_source_in_debug_module)) {
4000 CmdArgs.push_back(Elt: "-mllvm");
4001 CmdArgs.push_back(Elt: "--dx-source-in-debug-module");
4002 }
4003 if (Args.hasArg(Ids: options::OPT_dxc_Qstrip_debug)) {
4004 CmdArgs.push_back(Elt: "-mllvm");
4005 CmdArgs.push_back(Elt: "--dx-strip-debug");
4006 }
4007 if (Args.hasArg(Ids: options::OPT_dxc_Qpdb_in_private)) {
4008 CmdArgs.push_back(Elt: "-mllvm");
4009 CmdArgs.push_back(Elt: "--dx-pdb-in-private");
4010 }
4011}
4012
4013static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4014 ArgStringList &CmdArgs, types::ID InputType) {
4015 if (!Args.hasArg(Ids: options::OPT_fopenacc))
4016 return;
4017
4018 CmdArgs.push_back(Elt: "-fopenacc");
4019}
4020
4021static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4022 const ArgList &Args, ArgStringList &CmdArgs) {
4023 // -fbuiltin is default unless -mkernel is used.
4024 bool UseBuiltins =
4025 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
4026 Default: !Args.hasArg(Ids: options::OPT_mkernel));
4027 if (!UseBuiltins)
4028 CmdArgs.push_back(Elt: "-fno-builtin");
4029
4030 // -ffreestanding implies -fno-builtin.
4031 if (Args.hasArg(Ids: options::OPT_ffreestanding))
4032 UseBuiltins = false;
4033
4034 // Process the -fno-builtin-* options.
4035 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
4036 A->claim();
4037
4038 // If -fno-builtin is specified, then there's no need to pass the option to
4039 // the frontend.
4040 if (UseBuiltins)
4041 A->render(Args, Output&: CmdArgs);
4042 }
4043}
4044
4045bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
4046 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
4047 Twine Path{Str};
4048 Path.toVector(Out&: Result);
4049 return Path.getSingleStringRef() != "";
4050 }
4051 if (llvm::sys::path::cache_directory(result&: Result)) {
4052 llvm::sys::path::append(path&: Result, a: "clang");
4053 llvm::sys::path::append(path&: Result, a: "ModuleCache");
4054 return true;
4055 }
4056 return false;
4057}
4058
4059llvm::SmallString<256>
4060clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
4061 const char *BaseInput) {
4062 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
4063 return StringRef(ModuleOutputEQ->getValue());
4064
4065 SmallString<256> OutputPath;
4066 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
4067 FinalOutput && Args.hasArg(Ids: options::OPT_c))
4068 OutputPath = FinalOutput->getValue();
4069 else {
4070 llvm::sys::fs::current_path(result&: OutputPath);
4071 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
4072 }
4073
4074 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
4075 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
4076 return OutputPath;
4077}
4078
4079static bool RenderModulesOptions(Compilation &C, const Driver &D,
4080 const ArgList &Args, const InputInfo &Input,
4081 const InputInfo &Output, bool HaveStd20,
4082 ArgStringList &CmdArgs) {
4083 const bool IsCXX = types::isCXX(Id: Input.getType());
4084 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4085 bool HaveModules = HaveStdCXXModules;
4086
4087 // -fmodules enables the use of precompiled modules (off by default).
4088 // Users can pass -fno-cxx-modules to turn off modules support for
4089 // C++/Objective-C++ programs.
4090 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
4091 Neg: options::OPT_fno_cxx_modules, Default: true);
4092 bool HaveClangModules = false;
4093 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
4094 if (AllowedInCXX || !IsCXX) {
4095 CmdArgs.push_back(Elt: "-fmodules");
4096 HaveClangModules = true;
4097 }
4098 }
4099
4100 HaveModules |= HaveClangModules;
4101
4102 if (HaveModules && !AllowedInCXX)
4103 CmdArgs.push_back(Elt: "-fno-cxx-modules");
4104
4105 // -fmodule-maps enables implicit reading of module map files. By default,
4106 // this is enabled if we are using Clang's flavor of precompiled modules.
4107 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
4108 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
4109 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
4110
4111 // -fmodules-decluse checks that modules used are declared so (off by default)
4112 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
4113 Neg: options::OPT_fno_modules_decluse);
4114
4115 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4116 // all #included headers are part of modules.
4117 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
4118 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
4119 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
4120
4121 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
4122 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
4123
4124 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4125 bool ImplicitModules = false;
4126 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
4127 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
4128 if (HaveModules)
4129 CmdArgs.push_back(Elt: "-fno-implicit-modules");
4130 } else if (HaveModules) {
4131 ImplicitModules = true;
4132 // -fmodule-cache-path specifies where our implicitly-built module files
4133 // should be written.
4134 SmallString<128> Path;
4135 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
4136 Path = A->getValue();
4137
4138 bool HasPath = true;
4139 if (C.isForDiagnostics()) {
4140 // When generating crash reports, we want to emit the modules along with
4141 // the reproduction sources, so we ignore any provided module path.
4142 Path = Output.getFilename();
4143 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
4144 llvm::sys::path::append(path&: Path, a: "modules");
4145 } else if (Path.empty()) {
4146 // No module path was provided: use the default.
4147 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
4148 }
4149
4150 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4151 // That being said, that failure is unlikely and not caching is harmless.
4152 if (HasPath) {
4153 const char Arg[] = "-fmodules-cache-path=";
4154 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
4155 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
4156 }
4157
4158 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fimplicit_modules_lock_timeout_EQ);
4159 }
4160
4161 if (HaveModules) {
4162 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
4163 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
4164 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
4165 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
4166 Neg: options::OPT_fno_modules_validate_input_files_content,
4167 Default: false))
4168 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
4169 }
4170
4171 // -fmodule-name specifies the module that is currently being built (or
4172 // used for header checking by -fmodule-maps).
4173 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
4174
4175 // -fmodule-map-file can be used to specify files containing module
4176 // definitions.
4177 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
4178
4179 // -fbuiltin-module-map can be used to load the clang
4180 // builtin headers modulemap file.
4181 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
4182 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4183 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
4184 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
4185 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
4186 CmdArgs.push_back(
4187 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
4188 }
4189
4190 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4191 // names to precompiled module files (the module is loaded only if used).
4192 // The -fmodule-file=<file> form can be used to unconditionally load
4193 // precompiled module files (whether used or not).
4194 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4195 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
4196
4197 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4198 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
4199 CmdArgs.push_back(Elt: Args.MakeArgString(
4200 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
4201 A->claim();
4202 }
4203 } else
4204 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
4205
4206 // When building modules and generating crashdumps, we need to dump a module
4207 // dependency VFS alongside the output.
4208 if (HaveClangModules && C.isForDiagnostics()) {
4209 SmallString<128> VFSDir(Output.getFilename());
4210 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
4211 // Add the cache directory as a temp so the crash diagnostics pick it up.
4212 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
4213
4214 llvm::sys::path::append(path&: VFSDir, a: "vfs");
4215 CmdArgs.push_back(Elt: "-module-dependency-dir");
4216 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
4217 }
4218
4219 if (HaveClangModules)
4220 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
4221
4222 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
4223 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_search_path);
4224 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
4225 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
4226
4227 if (HaveClangModules) {
4228 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
4229
4230 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
4231 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
4232 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
4233 << A->getAsString(Args) << "-fbuild-session-timestamp";
4234
4235 llvm::sys::fs::file_status Status;
4236 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
4237 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
4238 CmdArgs.push_back(Elt: Args.MakeArgString(
4239 Str: "-fbuild-session-timestamp=" +
4240 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4241 d: Status.getLastModificationTime().time_since_epoch())
4242 .count())));
4243 }
4244
4245 if (Args.getLastArg(
4246 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4247 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4248 Ids: options::OPT_fbuild_session_file))
4249 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4250
4251 Args.AddLastArg(Output&: CmdArgs,
4252 Ids: options::OPT_fmodules_validate_once_per_build_session);
4253 }
4254
4255 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4256 Neg: options::OPT_fno_modules_validate_system_headers,
4257 Default: ImplicitModules))
4258 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4259
4260 Args.AddLastArg(Output&: CmdArgs,
4261 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4262 } else {
4263 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4264 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4265 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4266 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4267 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4268 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4269 }
4270
4271 // FIXME: We provisionally don't check ODR violations for decls in the global
4272 // module fragment.
4273 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4274
4275 if (Input.getType() == driver::types::TY_CXXModule ||
4276 Input.getType() == driver::types::TY_PP_CXXModule) {
4277 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4278 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4279
4280 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4281 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4282 else if (!(Args.hasArg(Ids: options::OPT__precompile) ||
4283 Args.hasArg(Ids: options::OPT__precompile_reduced_bmi)) ||
4284 Args.hasArg(Ids: options::OPT_fmodule_output))
4285 // If --precompile is specified, we will always generate a module file if
4286 // we're compiling an importable module unit. This is fine even if the
4287 // compilation process won't reach the point of generating the module file
4288 // (e.g., in the preprocessing mode), since the attached flag
4289 // '-fmodule-output' is useless.
4290 //
4291 // But if '--precompile' is specified, it might be annoying to always
4292 // generate the module file as '--precompile' will generate the module
4293 // file anyway.
4294 CmdArgs.push_back(Elt: Args.MakeArgString(
4295 Str: "-fmodule-output=" +
4296 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4297 }
4298
4299 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4300 Args.hasArg(Ids: options::OPT__precompile) &&
4301 (!Args.hasArg(Ids: options::OPT_o) ||
4302 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4303 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4304 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4305 }
4306
4307 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4308 // other translation units than module units. This is more user friendly to
4309 // allow end uers to enable this feature without asking for help from build
4310 // systems.
4311 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4312 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4313
4314 // We need to include the case the input file is a module file here.
4315 // Since the default compilation model for C++ module interface unit will
4316 // create temporary module file and compile the temporary module file
4317 // to get the object file. Then the `-fmodule-output` flag will be
4318 // brought to the second compilation process. So we have to claim it for
4319 // the case too.
4320 if (Input.getType() == driver::types::TY_CXXModule ||
4321 Input.getType() == driver::types::TY_PP_CXXModule ||
4322 Input.getType() == driver::types::TY_ModuleFile) {
4323 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4324 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4325 }
4326
4327 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4328 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4329
4330 return HaveModules;
4331}
4332
4333static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4334 ArgStringList &CmdArgs) {
4335 // -fsigned-char is default.
4336 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4337 Ids: options::OPT_fno_signed_char,
4338 Ids: options::OPT_funsigned_char,
4339 Ids: options::OPT_fno_unsigned_char)) {
4340 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4341 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4342 CmdArgs.push_back(Elt: "-fno-signed-char");
4343 }
4344 } else if (!isSignedCharDefault(Triple: T)) {
4345 CmdArgs.push_back(Elt: "-fno-signed-char");
4346 }
4347
4348 // The default depends on the language standard.
4349 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4350
4351 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4352 Ids: options::OPT_fno_short_wchar)) {
4353 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4354 CmdArgs.push_back(Elt: "-fwchar-type=short");
4355 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4356 } else {
4357 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4358 CmdArgs.push_back(Elt: "-fwchar-type=int");
4359 if (T.isOSzOS() ||
4360 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4361 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4362 else
4363 CmdArgs.push_back(Elt: "-fsigned-wchar");
4364 }
4365 } else if (T.isOSzOS())
4366 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4367}
4368
4369static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4370 const llvm::Triple &T, const ArgList &Args,
4371 ObjCRuntime &Runtime, bool InferCovariantReturns,
4372 const InputInfo &Input, ArgStringList &CmdArgs) {
4373 const llvm::Triple::ArchType Arch = TC.getArch();
4374
4375 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4376 // is the default. Except for deployment target of 10.5, next runtime is
4377 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4378 if (Runtime.isNonFragile()) {
4379 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4380 Neg: options::OPT_fno_objc_legacy_dispatch,
4381 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4382 if (TC.UseObjCMixedDispatch())
4383 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4384 else
4385 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4386 }
4387 }
4388
4389 // Forward -fobjc-direct-precondition-thunk to cc1
4390 // Defaults to false and needs explict turn on for now
4391 // TODO: switch to default true and needs explict turn off in the future.
4392 // TODO: add support for other runtimes
4393 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4394 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4395 if (Runtime.isNeXTFamily()) {
4396 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4397 } else {
4398 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4399 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4400 }
4401 }
4402
4403 if (types::isObjC(Id: Input.getType())) {
4404 // Pass down -fobjc-msgsend-selector-stubs if present.
4405 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_selector_stubs,
4406 Neg: options::OPT_fno_objc_msgsend_selector_stubs, Default: false))
4407 CmdArgs.push_back(Elt: "-fobjc-msgsend-selector-stubs");
4408
4409 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4410 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_class_selector_stubs,
4411 Neg: options::OPT_fno_objc_msgsend_class_selector_stubs, Default: false))
4412 CmdArgs.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
4413 }
4414
4415 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4416 // to do Array/Dictionary subscripting by default.
4417 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4418 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4419 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4420
4421 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4422 // NOTE: This logic is duplicated in ToolChains.cpp.
4423 if (isObjCAutoRefCount(Args)) {
4424 TC.CheckObjCARC();
4425
4426 CmdArgs.push_back(Elt: "-fobjc-arc");
4427
4428 // FIXME: It seems like this entire block, and several around it should be
4429 // wrapped in isObjC, but for now we just use it here as this is where it
4430 // was being used previously.
4431 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4432 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4433 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4434 else
4435 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4436 }
4437
4438 // Allow the user to enable full exceptions code emission.
4439 // We default off for Objective-C, on for Objective-C++.
4440 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4441 Neg: options::OPT_fno_objc_arc_exceptions,
4442 /*Default=*/types::isCXX(Id: Input.getType())))
4443 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4444 }
4445
4446 // Silence warning for full exception code emission options when explicitly
4447 // set to use no ARC.
4448 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4449 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4450 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4451 }
4452
4453 // Allow the user to control whether messages can be converted to runtime
4454 // functions.
4455 if (types::isObjC(Id: Input.getType())) {
4456 auto *Arg = Args.getLastArg(
4457 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4458 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4459 if (Arg &&
4460 Arg->getOption().matches(
4461 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4462 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4463 }
4464
4465 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4466 // rewriter.
4467 if (InferCovariantReturns)
4468 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4469
4470 // Pass down -fobjc-weak or -fno-objc-weak if present.
4471 if (types::isObjC(Id: Input.getType())) {
4472 auto WeakArg =
4473 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4474 if (!WeakArg) {
4475 // nothing to do
4476 } else if (!Runtime.allowsWeak()) {
4477 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4478 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4479 } else {
4480 WeakArg->render(Args, Output&: CmdArgs);
4481 }
4482 }
4483
4484 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4485 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4486
4487 // Forward constant literal flags to cc1.
4488 if (types::isObjC(Id: Input.getType())) {
4489 bool EnableConstantLiterals =
4490 Args.hasFlag(Pos: options::OPT_fobjc_constant_literals,
4491 Neg: options::OPT_fno_objc_constant_literals,
4492 /*default=*/Default: true) &&
4493 Runtime.hasConstantLiteralClasses();
4494 if (EnableConstantLiterals)
4495 CmdArgs.push_back(Elt: "-fobjc-constant-literals");
4496 if (Args.hasFlag(Pos: options::OPT_fconstant_nsnumber_literals,
4497 Neg: options::OPT_fno_constant_nsnumber_literals,
4498 /*default=*/Default: true) &&
4499 EnableConstantLiterals)
4500 CmdArgs.push_back(Elt: "-fconstant-nsnumber-literals");
4501 if (Args.hasFlag(Pos: options::OPT_fconstant_nsarray_literals,
4502 Neg: options::OPT_fno_constant_nsarray_literals,
4503 /*default=*/Default: true) &&
4504 EnableConstantLiterals)
4505 CmdArgs.push_back(Elt: "-fconstant-nsarray-literals");
4506 if (Args.hasFlag(Pos: options::OPT_fconstant_nsdictionary_literals,
4507 Neg: options::OPT_fno_constant_nsdictionary_literals,
4508 /*default=*/Default: true) &&
4509 EnableConstantLiterals)
4510 CmdArgs.push_back(Elt: "-fconstant-nsdictionary-literals");
4511 }
4512}
4513
4514static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4515 ArgStringList &CmdArgs) {
4516 bool CaretDefault = true;
4517 bool ColumnDefault = true;
4518
4519 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4520 Ids: options::OPT__SLASH_diagnostics_column,
4521 Ids: options::OPT__SLASH_diagnostics_caret)) {
4522 switch (A->getOption().getID()) {
4523 case options::OPT__SLASH_diagnostics_caret:
4524 CaretDefault = true;
4525 ColumnDefault = true;
4526 break;
4527 case options::OPT__SLASH_diagnostics_column:
4528 CaretDefault = false;
4529 ColumnDefault = true;
4530 break;
4531 case options::OPT__SLASH_diagnostics_classic:
4532 CaretDefault = false;
4533 ColumnDefault = false;
4534 break;
4535 }
4536 }
4537
4538 // -fcaret-diagnostics is default.
4539 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4540 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4541 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4542
4543 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4544 Neg: options::OPT_fno_diagnostics_fixit_info);
4545 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4546 Neg: options::OPT_fno_diagnostics_show_option);
4547
4548 if (const Arg *A =
4549 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4550 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4551 CmdArgs.push_back(Elt: A->getValue());
4552 }
4553
4554 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4555 Neg: options::OPT_fno_diagnostics_show_hotness);
4556
4557 if (const Arg *A =
4558 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4559 std::string Opt =
4560 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4561 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4562 }
4563
4564 if (const Arg *A =
4565 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4566 std::string Opt =
4567 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4568 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4569 }
4570
4571 if (const Arg *A =
4572 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_inlining_chain,
4573 Ids: options::OPT_fno_diagnostics_show_inlining_chain)) {
4574 if (A->getOption().matches(ID: options::OPT_fdiagnostics_show_inlining_chain))
4575 CmdArgs.push_back(Elt: "-fdiagnostics-show-inlining-chain");
4576 else
4577 CmdArgs.push_back(Elt: "-fno-diagnostics-show-inlining-chain");
4578 }
4579
4580 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4581 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4582 CmdArgs.push_back(Elt: A->getValue());
4583 if (StringRef(A->getValue()) == "sarif" ||
4584 StringRef(A->getValue()) == "SARIF")
4585 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4586 }
4587
4588 if (const Arg *A = Args.getLastArg(
4589 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4590 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4591 const Option &O = A->getOption();
4592 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4593 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4594 else
4595 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4596 }
4597
4598 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4599
4600 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4601 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4602
4603 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4604 Neg: options::OPT_fno_show_source_location);
4605
4606 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4607 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4608
4609 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4610 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4611
4612 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4613 Default: ColumnDefault))
4614 CmdArgs.push_back(Elt: "-fno-show-column");
4615
4616 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4617 Neg: options::OPT_fno_spell_checking);
4618
4619 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4620}
4621
4622static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4623 const ArgList &Args, ArgStringList &CmdArgs,
4624 unsigned DwarfVersion) {
4625 auto *DwarfFormatArg =
4626 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4627 if (!DwarfFormatArg)
4628 return;
4629
4630 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4631 if (DwarfVersion < 3)
4632 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4633 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4634 else if (!T.isArch64Bit())
4635 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4636 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4637 else if (!T.isOSBinFormatELF())
4638 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4639 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4640 }
4641
4642 DwarfFormatArg->render(Args, Output&: CmdArgs);
4643}
4644
4645static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4646 const ArgList &Args) {
4647 bool NeedsSimpleTemplateNames =
4648 Args.hasFlag(Pos: options::OPT_gsimple_template_names,
4649 Neg: options::OPT_gno_simple_template_names,
4650 Default: TC.getDefaultDebugSimpleTemplateNames());
4651 if (!NeedsSimpleTemplateNames)
4652 return false;
4653
4654 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsimple_template_names))
4655 if (!checkDebugInfoOption(A, Args, D, TC))
4656 return false;
4657
4658 return true;
4659}
4660
4661static void
4662renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4663 const ArgList &Args, types::ID InputType,
4664 ArgStringList &CmdArgs, const InputInfo &Output,
4665 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4666 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4667 bool IRInput = isLLVMIR(Id: InputType);
4668 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4669 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4670 !isOpenCL(Id: InputType);
4671
4672 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4673
4674 if (!Args.hasFlag(Pos: options::OPT_fdebug_record_sysroot,
4675 Neg: options::OPT_fno_debug_record_sysroot, Default: true))
4676 CmdArgs.push_back(Elt: "-fno-debug-record-sysroot");
4677
4678 // The 'g' groups options involve a somewhat intricate sequence of decisions
4679 // about what to pass from the driver to the frontend, but by the time they
4680 // reach cc1 they've been factored into three well-defined orthogonal choices:
4681 // * what level of debug info to generate
4682 // * what dwarf version to write
4683 // * what debugger tuning to use
4684 // This avoids having to monkey around further in cc1 other than to disable
4685 // codeview if not running in a Windows environment. Perhaps even that
4686 // decision should be made in the driver as well though.
4687 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4688
4689 bool SplitDWARFInlining =
4690 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4691 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4692
4693 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4694 // object file generation and no IR generation, -gN should not be needed. So
4695 // allow -gsplit-dwarf with either -gN or IR input.
4696 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4697 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4698 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4699 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4700 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4701 << TC.getTripleString();
4702 return;
4703 }
4704 Arg *SplitDWARFArg;
4705 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4706 if (DwarfFission != DwarfFissionKind::None &&
4707 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4708 DwarfFission = DwarfFissionKind::None;
4709 SplitDWARFInlining = false;
4710 }
4711 }
4712 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4713 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4714
4715 // If the last option explicitly specified a debug-info level, use it.
4716 if (checkDebugInfoOption(A, Args, D, TC) &&
4717 A->getOption().matches(ID: options::OPT_gN_Group)) {
4718 DebugInfoKind = debugLevelToInfoKind(A: *A);
4719 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4720 // complicated if you've disabled inline info in the skeleton CUs
4721 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4722 // line-tables-only, so let those compose naturally in that case.
4723 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4724 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4725 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4726 SplitDWARFInlining))
4727 DwarfFission = DwarfFissionKind::None;
4728 }
4729 }
4730
4731 // If a debugger tuning argument appeared, remember it.
4732 bool HasDebuggerTuning = false;
4733 if (const Arg *A =
4734 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4735 HasDebuggerTuning = true;
4736 if (checkDebugInfoOption(A, Args, D, TC)) {
4737 if (A->getOption().matches(ID: options::OPT_glldb))
4738 DebuggerTuning = llvm::DebuggerKind::LLDB;
4739 else if (A->getOption().matches(ID: options::OPT_gsce))
4740 DebuggerTuning = llvm::DebuggerKind::SCE;
4741 else if (A->getOption().matches(ID: options::OPT_gdbx))
4742 DebuggerTuning = llvm::DebuggerKind::DBX;
4743 else
4744 DebuggerTuning = llvm::DebuggerKind::GDB;
4745 }
4746 }
4747
4748 // If a -gdwarf argument appeared, remember it.
4749 bool EmitDwarf = false;
4750 if (const Arg *A = getDwarfNArg(Args))
4751 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4752
4753 bool EmitCodeView = false;
4754 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4755 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4756
4757 // If the user asked for debug info but did not explicitly specify -gcodeview
4758 // or -gdwarf, ask the toolchain for the default format.
4759 if (!EmitCodeView && !EmitDwarf &&
4760 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4761 switch (TC.getDefaultDebugFormat()) {
4762 case llvm::codegenoptions::DIF_CodeView:
4763 EmitCodeView = true;
4764 break;
4765 case llvm::codegenoptions::DIF_DWARF:
4766 EmitDwarf = true;
4767 break;
4768 }
4769 }
4770
4771 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4772 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4773 // be lower than what the user wanted.
4774 if (EmitDwarf) {
4775 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4776 // Clamp effective DWARF version to the max supported by the toolchain.
4777 EffectiveDWARFVersion =
4778 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4779 } else {
4780 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4781 }
4782
4783 // -gline-directives-only supported only for the DWARF debug info.
4784 if (RequestedDWARFVersion == 0 &&
4785 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4786 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4787
4788 // strict DWARF is set to false by default. But for DBX, we need it to be set
4789 // as true by default.
4790 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4791 (void)checkDebugInfoOption(A, Args, D, TC);
4792 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4793 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4794 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4795
4796 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4797 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4798
4799 // Column info is included by default for everything except SCE and
4800 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4801 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4802 // practice, however, the Microsoft debuggers don't handle missing end columns
4803 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4804 // it's better not to include any column info.
4805 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4806 (void)checkDebugInfoOption(A, Args, D, TC);
4807 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4808 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4809 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4810 DebuggerTuning != llvm::DebuggerKind::DBX)))
4811 CmdArgs.push_back(Elt: "-gno-column-info");
4812
4813 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4814 Neg: options::OPT_gno_call_site_info, Default: true))
4815 CmdArgs.push_back(Elt: "-gno-call-site-info");
4816
4817 // FIXME: Move backend command line options to the module.
4818 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4819 // If -gline-tables-only or -gline-directives-only is the last option it
4820 // wins.
4821 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4822 TC)) {
4823 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4824 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4825 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4826 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4827 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4828 }
4829 }
4830 }
4831
4832 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4833 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4834
4835 // After we've dealt with all combinations of things that could
4836 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4837 // figure out if we need to "upgrade" it to standalone debug info.
4838 // We parse these two '-f' options whether or not they will be used,
4839 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4840 bool NeedFullDebug = Args.hasFlag(
4841 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4842 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4843 TC.GetDefaultStandaloneDebug());
4844 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4845 (void)checkDebugInfoOption(A, Args, D, TC);
4846
4847 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4848 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4849 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4850 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4851 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4852 else if (NeedFullDebug)
4853 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4854 }
4855
4856 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4857 Default: false)) {
4858 // Source embedding is a vendor extension to DWARF v5. By now we have
4859 // checked if a DWARF version was stated explicitly, and have otherwise
4860 // fallen back to the target default, so if this is still not at least 5
4861 // we emit an error.
4862 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4863 if (RequestedDWARFVersion < 5)
4864 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4865 << A->getAsString(Args) << "-gdwarf-5";
4866 else if (EffectiveDWARFVersion < 5)
4867 // The toolchain has reduced allowed dwarf version, so we can't enable
4868 // -gembed-source.
4869 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4870 << A->getAsString(Args) << TC.getTripleString() << 5
4871 << EffectiveDWARFVersion;
4872 else if (checkDebugInfoOption(A, Args, D, TC))
4873 CmdArgs.push_back(Elt: "-gembed-source");
4874 }
4875
4876 // Enable Key Instructions by default if we're emitting DWARF, the language is
4877 // plain C or C++, and optimisations are enabled.
4878 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4879 bool KeyInstructionsOnByDefault =
4880 EmitDwarf && PlainCOrCXX && OptLevel &&
4881 !OptLevel->getOption().matches(ID: options::OPT_O0);
4882 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4883 Neg: options::OPT_gno_key_instructions,
4884 Default: KeyInstructionsOnByDefault))
4885 CmdArgs.push_back(Elt: "-gkey-instructions");
4886
4887 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4888 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4889 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4890
4891 if (Args.hasFlag(Pos: options::OPT_fdynamic_debugging,
4892 Neg: options::OPT_fno_dynamic_debugging, Default: false)) {
4893 // As this is an experimental feature we can afford to be strict about
4894 // supported configurations.
4895 // NOTE on adding target support, consider adding "tail-pad-to-size"
4896 // support in `llvm::prepareForDynamicDebugging`.
4897 if (!TC.getTriple().isX86())
4898 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4899 << Args.getLastArg(Ids: options::OPT_fdynamic_debugging)->getAsString(Args)
4900 << T.getTriple();
4901 if (IsUsingLTO)
4902 D.Diag(DiagID: diag::err_drv_dyndbg_lto);
4903 if (DwarfFission != DwarfFissionKind::None)
4904 D.Diag(DiagID: diag::err_drv_dyndbg_incompatible)
4905 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getAsString(Args);
4906 // There's no fundamental reason why IR input should be incompatible, but
4907 // it would add some complexity, and reducing the test matrix is valuable.
4908 if (IRInput)
4909 D.Diag(DiagID: diag::err_drv_dyndbg_ir);
4910
4911 // Disable composition with sanitizers for now.
4912 if (auto *San = Args.getLastArg(Ids: options::OPT_fsanitize_EQ))
4913 D.Diag(DiagID: diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4914
4915 if (!EmitDwarf)
4916 D.Diag(DiagID: diag::warn_drv_dyndbg_req_debug);
4917 else
4918 CmdArgs.push_back(Elt: "-fdynamic-debugging");
4919 }
4920
4921 if (EmitCodeView) {
4922 CmdArgs.push_back(Elt: "-gcodeview");
4923
4924 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
4925 Neg: options::OPT_gno_codeview_ghash);
4926
4927 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
4928 Neg: options::OPT_gno_codeview_command_line);
4929 }
4930
4931 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
4932 Neg: options::OPT_gno_inline_line_tables);
4933
4934 // When emitting remarks, we need at least debug lines in the output.
4935 if (willEmitRemarks(Args) &&
4936 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4937 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4938
4939 // Adjust the debug info kind for the given toolchain.
4940 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4941
4942 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4943 // set.
4944 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4945 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
4946 ? llvm::DebuggerKind::Default
4947 : DebuggerTuning);
4948
4949 // -fdebug-macro turns on macro debug info generation.
4950 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
4951 Default: false))
4952 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
4953 D, TC))
4954 CmdArgs.push_back(Elt: "-debug-info-macro");
4955
4956 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4957 const auto *PubnamesArg =
4958 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
4959 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
4960 if (DwarfFission != DwarfFissionKind::None ||
4961 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
4962 const bool OptionSet =
4963 (PubnamesArg &&
4964 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
4965 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
4966 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4967 (!PubnamesArg ||
4968 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
4969 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
4970 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
4971 ID: options::OPT_gpubnames)
4972 ? "-gpubnames"
4973 : "-ggnu-pubnames");
4974 }
4975
4976 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4977 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4978 ForwardTemplateParams = true;
4979 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
4980 }
4981
4982 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4983 bool UseDebugTemplateAlias =
4984 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4985 if (const auto *DebugTemplateAlias = Args.getLastArg(
4986 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
4987 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4988 // asks for it we should let them have it (if the target supports it).
4989 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
4990 const auto &Opt = DebugTemplateAlias->getOption();
4991 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
4992 }
4993 }
4994 if (UseDebugTemplateAlias)
4995 CmdArgs.push_back(Elt: "-gtemplate-alias");
4996
4997 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
4998 StringRef v = A->getValue();
4999 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
5000 }
5001
5002 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
5003 Neg: options::OPT_fno_debug_ranges_base_address);
5004
5005 // -gdwarf-aranges turns on the emission of the aranges section in the
5006 // backend.
5007 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
5008 A && checkDebugInfoOption(A, Args, D, TC)) {
5009 CmdArgs.push_back(Elt: "-mllvm");
5010 CmdArgs.push_back(Elt: "-generate-arange-section");
5011 }
5012
5013 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
5014 Neg: options::OPT_fno_force_dwarf_frame);
5015
5016 bool EnableTypeUnits = false;
5017 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
5018 Neg: options::OPT_fno_debug_types_section, Default: false)) {
5019 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5020 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5021 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
5022 ->getAsString(Args)
5023 << T.getTriple();
5024 } else if (checkDebugInfoOption(
5025 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
5026 TC)) {
5027 EnableTypeUnits = true;
5028 CmdArgs.push_back(Elt: "-mllvm");
5029 CmdArgs.push_back(Elt: "-generate-type-units");
5030 }
5031 }
5032
5033 if (const Arg *A =
5034 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
5035 Ids: options::OPT_gno_omit_unreferenced_methods))
5036 (void)checkDebugInfoOption(A, Args, D, TC);
5037 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
5038 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
5039 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5040 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5041 !EnableTypeUnits) {
5042 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
5043 }
5044
5045 // To avoid join/split of directory+filename, the integrated assembler prefers
5046 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5047 // form before DWARF v5.
5048 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
5049 Neg: options::OPT_fno_dwarf_directory_asm,
5050 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5051 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
5052
5053 // Decide how to render forward declarations of template instantiations.
5054 // SCE wants full descriptions, others just get them in the name.
5055 if (ForwardTemplateParams)
5056 CmdArgs.push_back(Elt: "-debug-forward-template-params");
5057
5058 // Do we need to explicitly import anonymous namespaces into the parent
5059 // scope?
5060 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5061 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
5062
5063 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
5064 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5065
5066 // This controls whether or not we perform JustMyCode instrumentation.
5067 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
5068 if (TC.getTriple().isOSBinFormatELF() ||
5069 TC.getTriple().isWindowsMSVCEnvironment()) {
5070 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5071 CmdArgs.push_back(Elt: "-fjmc");
5072 else if (D.IsCLMode())
5073 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5074 << "'/Zi', '/Z7'";
5075 else
5076 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5077 << "-g";
5078 } else {
5079 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
5080 }
5081 }
5082
5083 // Add in -fdebug-compilation-dir if necessary.
5084 const char *DebugCompilationDir =
5085 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
5086
5087 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5088
5089 // Add the output path to the object file for CodeView debug infos.
5090 if (EmitCodeView && Output.isFilename())
5091 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5092 OutputFileName: Output.getFilename());
5093}
5094
5095static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5096 ArgStringList &CmdArgs) {
5097 unsigned RTOptionID = options::OPT__SLASH_MT;
5098
5099 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5100 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5101 // but defining _DEBUG is sticky.
5102 RTOptionID = options::OPT__SLASH_MTd;
5103
5104 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
5105 RTOptionID = A->getOption().getID();
5106
5107 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5108 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5109 .Case(S: "static", Value: options::OPT__SLASH_MT)
5110 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
5111 .Case(S: "dll", Value: options::OPT__SLASH_MD)
5112 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
5113 .Default(Value: options::OPT__SLASH_MT);
5114 }
5115
5116 StringRef FlagForCRT;
5117 switch (RTOptionID) {
5118 case options::OPT__SLASH_MD:
5119 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5120 CmdArgs.push_back(Elt: "-D_DEBUG");
5121 CmdArgs.push_back(Elt: "-D_MT");
5122 CmdArgs.push_back(Elt: "-D_DLL");
5123 FlagForCRT = "--dependent-lib=msvcrt";
5124 break;
5125 case options::OPT__SLASH_MDd:
5126 CmdArgs.push_back(Elt: "-D_DEBUG");
5127 CmdArgs.push_back(Elt: "-D_MT");
5128 CmdArgs.push_back(Elt: "-D_DLL");
5129 FlagForCRT = "--dependent-lib=msvcrtd";
5130 break;
5131 case options::OPT__SLASH_MT:
5132 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5133 CmdArgs.push_back(Elt: "-D_DEBUG");
5134 CmdArgs.push_back(Elt: "-D_MT");
5135 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5136 FlagForCRT = "--dependent-lib=libcmt";
5137 break;
5138 case options::OPT__SLASH_MTd:
5139 CmdArgs.push_back(Elt: "-D_DEBUG");
5140 CmdArgs.push_back(Elt: "-D_MT");
5141 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5142 FlagForCRT = "--dependent-lib=libcmtd";
5143 break;
5144 default:
5145 llvm_unreachable("Unexpected option ID.");
5146 }
5147
5148 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5149 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
5150 } else {
5151 CmdArgs.push_back(Elt: FlagForCRT.data());
5152
5153 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5154 // users want. The /Za flag to cl.exe turns this off, but it's not
5155 // implemented in clang.
5156 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
5157 }
5158
5159 // SYCL: Add SYCL runtime library dependency
5160 // SYCL runtime is a required dependency similar to CRT, so we use
5161 // --dependent-lib to embed it in the object file metadata
5162 if (Args.hasFlag(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false) &&
5163 !Args.hasArg(Ids: options::OPT_nolibsycl) &&
5164 !Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5165
5166 // Determine debug vs release based on CRT flags
5167 bool IsDebugBuild = false;
5168
5169 // Check -fms-runtime-lib=dll_dbg
5170 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5171 StringRef RuntimeVal = A->getValue();
5172 if (RuntimeVal == "dll_dbg")
5173 IsDebugBuild = true;
5174 }
5175
5176 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5177 // overriding options (e.g., /MDd /MD -> /MD wins)
5178 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group)) {
5179 if (A->getOption().matches(ID: options::OPT__SLASH_MDd))
5180 IsDebugBuild = true;
5181 }
5182
5183 // Add appropriate SYCL runtime library dependency
5184 CmdArgs.push_back(Elt: IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5185 : "--dependent-lib=LLVMSYCL");
5186 }
5187
5188 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5189 // even if the file doesn't actually refer to any of the routines because
5190 // the CRT itself has incomplete dependency markings.
5191 if (TC.getTriple().isWindowsArm64EC())
5192 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
5193}
5194
5195void Clang::ConstructJob(Compilation &C, const JobAction &JA,
5196 const InputInfo &Output, const InputInfoList &Inputs,
5197 const ArgList &Args, const char *LinkingOutput) const {
5198 const auto &TC = getToolChain();
5199 const llvm::Triple &RawTriple = TC.getTriple();
5200 const llvm::Triple &Triple = TC.getEffectiveTriple();
5201 const std::string &TripleStr = Triple.getTriple();
5202
5203 bool KernelOrKext =
5204 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
5205 const Driver &D = TC.getDriver();
5206 ArgStringList CmdArgs;
5207
5208 assert(Inputs.size() >= 1 && "Must have at least one input.");
5209 // CUDA/HIP compilation may have multiple inputs (source file + results of
5210 // device-side compilations). OpenMP device jobs also take the host IR as a
5211 // second input. Module precompilation accepts a list of header files to
5212 // include as part of the module. API extraction accepts a list of header
5213 // files whose API information is emitted in the output. All other jobs are
5214 // expected to have exactly one input. SYCL compilation only expects a
5215 // single input.
5216 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
5217 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
5218 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
5219 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
5220 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
5221 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
5222 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
5223 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
5224 bool UsesLLVMOffloading = Args.hasFlag(
5225 Pos: options::OPT_foffload_via_llvm, Neg: options::OPT_fno_offload_via_llvm, Default: false);
5226 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
5227 JA.isDeviceOffloading(OKind: Action::OFK_Host));
5228 bool IsHostOffloadingAction =
5229 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
5230 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
5231 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()));
5232
5233 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5234 bool IsRDCMode = Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc,
5235 /*Default=*/IsSYCL);
5236
5237 auto LTOMode = TC.getLTOMode(Args, Kind: JA.getOffloadingDeviceKind());
5238 bool IsUsingLTO = LTOMode != LTOK_None;
5239
5240 // Extract API doesn't have a main input file, so invent a fake one as a
5241 // placeholder.
5242 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5243 "extract-api");
5244
5245 const InputInfo &Input =
5246 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5247
5248 InputInfoList ExtractAPIInputs;
5249 InputInfoList HostOffloadingInputs;
5250 const InputInfo *OpenMPDeviceInput = nullptr;
5251 for (const InputInfo &I : Inputs) {
5252 if (&I == &Input || I.getType() == types::TY_Nothing) {
5253 // This is the primary input or contains nothing.
5254 } else if (IsExtractAPI) {
5255 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5256 if (I.getType() != ExpectedInputType) {
5257 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
5258 << I.getFilename() << types::getTypeName(Id: I.getType())
5259 << types::getTypeName(Id: ExpectedInputType);
5260 }
5261 ExtractAPIInputs.push_back(Elt: I);
5262 } else if (IsHostOffloadingAction) {
5263 HostOffloadingInputs.push_back(Elt: I);
5264 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5265 OpenMPDeviceInput = &I;
5266 } else {
5267 llvm_unreachable("unexpectedly given multiple inputs");
5268 }
5269 }
5270
5271 bool IsUEFI = RawTriple.isUEFI();
5272 bool IsIAMCU = RawTriple.isOSIAMCU();
5273
5274 // C++ is not supported for IAMCU.
5275 if (IsIAMCU && types::isCXX(Id: Input.getType()))
5276 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5277
5278 // Invoke ourselves in -cc1 mode.
5279 //
5280 // FIXME: Implement custom jobs for internal actions.
5281 CmdArgs.push_back(Elt: "-cc1");
5282
5283 // Add the "effective" target triple.
5284 CmdArgs.push_back(Elt: "-triple");
5285 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: TripleStr));
5286
5287 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5288
5289 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5290 if (AuxTriple) {
5291 CmdArgs.push_back(Elt: "-aux-triple");
5292 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: AuxTriple->str()));
5293
5294 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5295 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5296 // Windows), we need to pass Windows-specific flags to cc1.
5297 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5298 } else if (JA.getOffloadingHostActiveKinds() != Action::OFK_None) {
5299 // Figure out the device side triple for the host-side compilation.
5300 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5301 ++I) {
5302 Compilation::const_offload_toolchains_range OffloadToolChains =
5303 C.getOffloadToolChains(Kind: static_cast<Action::OffloadKind>(I));
5304 if (OffloadToolChains.first == OffloadToolChains.second)
5305 continue;
5306
5307 const llvm::Triple &DeviceAuxTriple =
5308 OffloadToolChains.first->second->getTriple();
5309 CmdArgs.push_back(Elt: "-aux-triple");
5310 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: DeviceAuxTriple.str()));
5311 break;
5312 }
5313 }
5314
5315 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
5316 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
5317 Args.ClaimAllArgs(Id0: options::OPT_MJ);
5318 } else if (const Arg *GenCDBFragment =
5319 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
5320 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
5321 Target: TripleStr, Output, Input, Args);
5322 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
5323 }
5324
5325 if ((getToolChain().getTriple().isAMDGPU() ||
5326 (getToolChain().getTriple().isSPIRV() &&
5327 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5328 // Device side compilation printf
5329 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
5330 CmdArgs.push_back(Elt: Args.MakeArgString(
5331 Str: "-mprintf-kind=" +
5332 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
5333 // Force compiler error on invalid conversion specifiers
5334 CmdArgs.push_back(
5335 Elt: Args.MakeArgStringRef(Str: "-Werror=format-invalid-specifier"));
5336 }
5337 }
5338
5339 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5340 // We need to figure out which CUDA version we're compiling for, as that
5341 // determines how we load and launch GPU kernels.
5342 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5343 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5344 assert(CTC && "Expected valid CUDA Toolchain.");
5345 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5346 CmdArgs.push_back(Elt: Args.MakeArgString(
5347 Str: Twine("-target-sdk-version=") +
5348 CudaVersionToString(V: CTC->CudaInstallation.version())));
5349 }
5350
5351 // Optimization level for CodeGen.
5352 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5353 if (A->getOption().matches(ID: options::OPT_O4)) {
5354 CmdArgs.push_back(Elt: "-O3");
5355 D.Diag(DiagID: diag::warn_O4_is_O3);
5356 } else {
5357 A->render(Args, Output&: CmdArgs);
5358 }
5359 }
5360
5361 // Unconditionally claim the printf option now to avoid unused diagnostic.
5362 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5363 PF->claim();
5364
5365 if (IsSYCL) {
5366 if (IsSYCLDevice) {
5367 // We want to compile sycl kernels.
5368 CmdArgs.push_back(Elt: "-fsycl-is-device");
5369
5370 // Set O2 optimization level by default
5371 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5372 CmdArgs.push_back(Elt: "-O2");
5373 } else {
5374 // Add any options that are needed specific to SYCL offload while
5375 // performing the host side compilation.
5376
5377 // Let the front-end host compilation flow know about SYCL offload
5378 // compilation.
5379 CmdArgs.push_back(Elt: "-fsycl-is-host");
5380 }
5381
5382 // Set options for both host and device.
5383 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5384 if (SYCLStdArg) {
5385 SYCLStdArg->render(Args, Output&: CmdArgs);
5386 } else {
5387 // Ensure the default version in SYCL mode is 2020.
5388 CmdArgs.push_back(Elt: "-sycl-std=2020");
5389 }
5390 }
5391
5392 if (Args.hasFlag(Pos: options::OPT_fclangir, Neg: options::OPT_fno_clangir, Default: false))
5393 CmdArgs.push_back(Elt: "-fclangir");
5394
5395 if (IsOpenMPDevice) {
5396 // We have to pass the triple of the host if compiling for an OpenMP device.
5397 const llvm::Triple &HostTriple =
5398 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5399 CmdArgs.push_back(Elt: "-aux-triple");
5400 CmdArgs.push_back(Elt: HostTriple.str().c_str());
5401 }
5402
5403 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5404 Triple.getArch() == llvm::Triple::thumb)) {
5405 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5406 unsigned Version = 0;
5407 bool Failure =
5408 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5409 if (Failure || Version < 7)
5410 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5411 << TripleStr;
5412 }
5413
5414 // Push all default warning arguments that are specific to
5415 // the given target. These come before user provided warning options
5416 // are provided.
5417 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5418
5419 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5420 if (Triple.isSPIR() || Triple.isSPIRV())
5421 CmdArgs.push_back(Elt: "-Wspir-compat");
5422
5423 // Select the appropriate action.
5424 RewriteKind rewriteKind = RK_None;
5425
5426 bool UnifiedLTO = false;
5427 if (IsUsingLTO) {
5428 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5429 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5430 if (UnifiedLTO)
5431 CmdArgs.push_back(Elt: "-funified-lto");
5432 }
5433
5434 if (Args.hasArg(Ids: options::OPT_fdefined_pointer_subtraction))
5435 CmdArgs.push_back(Elt: "-fdefined-pointer-subtraction");
5436
5437 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5438 // it claims when not running an assembler. Otherwise, clang would emit
5439 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5440 // flags while debugging something. That'd be somewhat inconvenient, and it's
5441 // also inconsistent with most other flags -- we don't warn on
5442 // -ffunction-sections not being used in -E mode either for example, even
5443 // though it's not really used either.
5444 if (!isa<AssembleJobAction>(Val: JA)) {
5445 // The args claimed here should match the args used in
5446 // CollectArgsForIntegratedAssembler().
5447 if (TC.useIntegratedAs()) {
5448 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5449 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5450 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5451 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5452 switch (C.getDefaultToolChain().getArch()) {
5453 case llvm::Triple::arm:
5454 case llvm::Triple::armeb:
5455 case llvm::Triple::thumb:
5456 case llvm::Triple::thumbeb:
5457 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5458 break;
5459 default:
5460 break;
5461 }
5462 }
5463 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5464 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5465 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5466 }
5467
5468 bool IsAMDSPIRVForHIPDevice =
5469 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5470 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5471
5472 if (isa<AnalyzeJobAction>(Val: JA)) {
5473 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5474 CmdArgs.push_back(Elt: "-analyze");
5475 } else if (isa<PreprocessJobAction>(Val: JA)) {
5476 if (Output.getType() == types::TY_Dependencies)
5477 CmdArgs.push_back(Elt: "-Eonly");
5478 else {
5479 CmdArgs.push_back(Elt: "-E");
5480 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5481 !Args.hasArg(Ids: options::OPT_g_Group))
5482 CmdArgs.push_back(Elt: "-P");
5483 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5484 CmdArgs.push_back(Elt: "-fdirectives-only");
5485 }
5486 } else if (isa<AssembleJobAction>(Val: JA)) {
5487 CmdArgs.push_back(Elt: "-emit-obj");
5488
5489 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5490
5491 // Also ignore explicit -force_cpusubtype_ALL option.
5492 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5493 } else if (isa<PrecompileJobAction>(Val: JA)) {
5494 if (JA.getType() == types::TY_Nothing)
5495 CmdArgs.push_back(Elt: "-fsyntax-only");
5496 else if (JA.getType() == types::TY_ModuleFile) {
5497 if (Args.hasArg(Ids: options::OPT__precompile_reduced_bmi) ||
5498 ((Input.getType() == types::TY_CXXStdModule ||
5499 Input.getType() == types::TY_PP_CXXStdModule) &&
5500 !Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi)))
5501 CmdArgs.push_back(Elt: "-emit-reduced-module-interface");
5502 else
5503 CmdArgs.push_back(Elt: "-emit-module-interface");
5504 } else if (JA.getType() == types::TY_HeaderUnit)
5505 CmdArgs.push_back(Elt: "-emit-header-unit");
5506 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5507 CmdArgs.push_back(Elt: "-emit-pch");
5508 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5509 CmdArgs.push_back(Elt: "-verify-pch");
5510 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5511 assert(JA.getType() == types::TY_API_INFO &&
5512 "Extract API actions must generate a API information.");
5513 CmdArgs.push_back(Elt: "-extract-api");
5514
5515 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5516 PrettySGFArg->render(Args, Output&: CmdArgs);
5517
5518 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5519
5520 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5521 ProductNameArg->render(Args, Output&: CmdArgs);
5522 if (Arg *ExtractAPIIgnoresFileArg =
5523 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5524 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5525 if (Arg *EmitExtensionSymbolGraphs =
5526 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5527 if (!SymbolGraphDirArg)
5528 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5529
5530 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5531 }
5532 if (SymbolGraphDirArg)
5533 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5534 } else {
5535 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5536 "Invalid action for clang tool.");
5537 if (JA.getType() == types::TY_Nothing) {
5538 CmdArgs.push_back(Elt: "-fsyntax-only");
5539 } else if (JA.getType() == types::TY_LLVM_IR ||
5540 JA.getType() == types::TY_LTO_IR) {
5541 CmdArgs.push_back(Elt: "-emit-llvm");
5542 } else if (JA.getType() == types::TY_LLVM_BC ||
5543 JA.getType() == types::TY_LTO_BC) {
5544 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5545 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5546 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5547 CmdArgs.push_back(Elt: "-emit-llvm");
5548 } else {
5549 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5550 }
5551 } else if (JA.getType() == types::TY_IFS ||
5552 JA.getType() == types::TY_IFS_CPP) {
5553 StringRef ArgStr =
5554 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5555 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5556 : "ifs-v1";
5557 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5558 CmdArgs.push_back(
5559 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr));
5560 } else if (JA.getType() == types::TY_PP_Asm) {
5561 CmdArgs.push_back(Elt: "-S");
5562 } else if (JA.getType() == types::TY_AST) {
5563 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5564 CmdArgs.push_back(Elt: "-emit-pch");
5565 } else if (JA.getType() == types::TY_ModuleFile) {
5566 CmdArgs.push_back(Elt: "-module-file-info");
5567 } else if (JA.getType() == types::TY_RewrittenObjC) {
5568 CmdArgs.push_back(Elt: "-rewrite-objc");
5569 rewriteKind = RK_NonFragile;
5570 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5571 CmdArgs.push_back(Elt: "-rewrite-objc");
5572 rewriteKind = RK_Fragile;
5573 } else if (JA.getType() == types::TY_CIR) {
5574 CmdArgs.push_back(Elt: "-emit-cir");
5575 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5576 CmdArgs.push_back(Elt: "-emit-obj");
5577 } else {
5578 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5579 }
5580
5581 // Preserve use-list order by default when emitting bitcode, so that
5582 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5583 // same result as running passes here. For LTO, we don't need to preserve
5584 // the use-list order, since serialization to bitcode is part of the flow.
5585 if (JA.getType() == types::TY_LLVM_BC)
5586 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5587
5588 if (IsUsingLTO) {
5589 const Arg *LTOArg = Args.getLastArg(Ids: options::OPT_foffload_lto,
5590 Ids: options::OPT_foffload_lto_EQ);
5591 if (Triple.isNVPTX() && !IsRDCMode &&
5592 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5593 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5594 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5595 << "-fno-gpu-rdc";
5596 } else {
5597 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5598 CmdArgs.push_back(Elt: Args.MakeArgString(
5599 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5600 // PS4 uses the legacy LTO API, which does not support some of the
5601 // features enabled by -flto-unit.
5602 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5603 CmdArgs.push_back(Elt: "-flto-unit");
5604 }
5605 }
5606 }
5607
5608 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5609
5610 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5611 if (!types::isLLVMIR(Id: Input.getType()))
5612 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5613 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5614 }
5615
5616 if (Triple.isPPC())
5617 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5618 Neg: options::OPT_mno_regnames);
5619
5620 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5621 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5622
5623 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5624 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5625
5626 if (Args.getLastArg(Ids: options::OPT_save_dynamic_debugging_temps))
5627 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_dynamic_debugging_temps);
5628
5629 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5630 Ids: options::OPT_fmemory_profile_EQ,
5631 Ids: options::OPT_fno_memory_profile);
5632 if (MemProfArg &&
5633 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5634 MemProfArg->render(Args, Output&: CmdArgs);
5635
5636 if (auto *MemProfUseArg =
5637 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5638 if (MemProfArg)
5639 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5640 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5641 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5642 Ids: options::OPT_fprofile_generate_EQ))
5643 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5644 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5645 MemProfUseArg->render(Args, Output&: CmdArgs);
5646 }
5647
5648 // Embed-bitcode option.
5649 // Only white-listed flags below are allowed to be embedded.
5650 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5651 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5652 // Add flags implied by -fembed-bitcode.
5653 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5654 // Disable all llvm IR level optimizations.
5655 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5656
5657 // Render target options.
5658 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
5659 DeviceOffloadKind: JA.getOffloadingDeviceKind());
5660
5661 // reject options that shouldn't be supported in bitcode
5662 // also reject kernel/kext
5663 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5664 options::OPT_mkernel,
5665 options::OPT_fapple_kext,
5666 options::OPT_ffunction_sections,
5667 options::OPT_fno_function_sections,
5668 options::OPT_fdata_sections,
5669 options::OPT_fno_data_sections,
5670 options::OPT_fbasic_block_sections_EQ,
5671 options::OPT_funique_internal_linkage_names,
5672 options::OPT_fno_unique_internal_linkage_names,
5673 options::OPT_funique_section_names,
5674 options::OPT_fno_unique_section_names,
5675 options::OPT_funique_basic_block_section_names,
5676 options::OPT_fno_unique_basic_block_section_names,
5677 options::OPT_mrestrict_it,
5678 options::OPT_mno_restrict_it,
5679 options::OPT_mstackrealign,
5680 options::OPT_mno_stackrealign,
5681 options::OPT_mstack_alignment,
5682 options::OPT_mcmodel_EQ,
5683 options::OPT_mlong_calls,
5684 options::OPT_mno_long_calls,
5685 options::OPT_ggnu_pubnames,
5686 options::OPT_gdwarf_aranges,
5687 options::OPT_fdebug_types_section,
5688 options::OPT_fno_debug_types_section,
5689 options::OPT_fdwarf_directory_asm,
5690 options::OPT_fno_dwarf_directory_asm,
5691 options::OPT_mrelax_all,
5692 options::OPT_mno_relax_all,
5693 options::OPT_ftrap_function_EQ,
5694 options::OPT_ffixed_r9,
5695 options::OPT_mfix_cortex_a53_835769,
5696 options::OPT_mno_fix_cortex_a53_835769,
5697 options::OPT_ffixed_x18,
5698 options::OPT_mglobal_merge,
5699 options::OPT_mno_global_merge,
5700 options::OPT_mred_zone,
5701 options::OPT_mno_red_zone,
5702 options::OPT_Wa_COMMA,
5703 options::OPT_Xassembler,
5704 options::OPT_mllvm,
5705 options::OPT_mmlir,
5706 };
5707 for (const auto &A : Args)
5708 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5709 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5710
5711 // Render the CodeGen options that need to be passed.
5712 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5713 Neg: options::OPT_fno_optimize_sibling_calls);
5714
5715 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5716 CmdArgs, JA);
5717
5718 // Render ABI arguments
5719 switch (TC.getArch()) {
5720 default: break;
5721 case llvm::Triple::arm:
5722 case llvm::Triple::armeb:
5723 case llvm::Triple::thumbeb:
5724 RenderARMABI(D, Triple, Args, CmdArgs);
5725 break;
5726 case llvm::Triple::aarch64:
5727 case llvm::Triple::aarch64_32:
5728 case llvm::Triple::aarch64_be:
5729 RenderAArch64ABI(Triple, Args, CmdArgs);
5730 break;
5731 }
5732
5733 // Input/Output file.
5734 if (Output.getType() == types::TY_Dependencies) {
5735 // Handled with other dependency code.
5736 } else if (Output.isFilename()) {
5737 CmdArgs.push_back(Elt: "-o");
5738 CmdArgs.push_back(Elt: Output.getFilename());
5739 } else {
5740 assert(Output.isNothing() && "Input output.");
5741 }
5742
5743 for (const auto &II : Inputs) {
5744 addDashXForInput(Args, Input: II, CmdArgs);
5745 if (II.isFilename())
5746 CmdArgs.push_back(Elt: II.getFilename());
5747 else
5748 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5749 }
5750
5751 C.addCommand(Cmd: std::make_unique<Command>(
5752 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getDriverProgramPath(),
5753 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5754 return;
5755 }
5756
5757 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5758 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5759
5760 // We normally speed up the clang process a bit by skipping destructors at
5761 // exit, but when we're generating diagnostics we can rely on some of the
5762 // cleanup.
5763 if (!C.isForDiagnostics())
5764 CmdArgs.push_back(Elt: "-disable-free");
5765 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5766
5767#ifdef NDEBUG
5768 const bool IsAssertBuild = false;
5769#else
5770 const bool IsAssertBuild = true;
5771#endif
5772
5773 // Disable the verification pass in no-asserts builds unless otherwise
5774 // specified.
5775 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5776 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5777 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5778 }
5779
5780 // Discard value names in no-asserts builds unless otherwise specified.
5781 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5782 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild)) {
5783 if (Args.hasArg(Ids: options::OPT_fdiscard_value_names) &&
5784 llvm::any_of(Range: Inputs, P: [](const clang::driver::InputInfo &II) {
5785 return types::isLLVMIR(Id: II.getType());
5786 })) {
5787 D.Diag(DiagID: diag::warn_ignoring_fdiscard_for_bitcode);
5788 }
5789 CmdArgs.push_back(Elt: "-discard-value-names");
5790 }
5791
5792 // Set the main file name, so that debug info works even with
5793 // -save-temps.
5794 CmdArgs.push_back(Elt: "-main-file-name");
5795 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5796
5797 // Some flags which affect the language (via preprocessor
5798 // defines).
5799 if (Args.hasArg(Ids: options::OPT_static))
5800 CmdArgs.push_back(Elt: "-static-define");
5801
5802 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5803
5804 if (Args.hasArg(Ids: options::OPT_municode))
5805 CmdArgs.push_back(Elt: "-DUNICODE");
5806
5807 if (isa<AnalyzeJobAction>(Val: JA))
5808 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5809
5810 if (isa<AnalyzeJobAction>(Val: JA) ||
5811 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5812 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5813
5814 // Enable compatilibily mode to avoid analyzer-config related errors.
5815 // Since we can't access frontend flags through hasArg, let's manually iterate
5816 // through them.
5817 bool FoundAnalyzerConfig = false;
5818 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5819 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5820 FoundAnalyzerConfig = true;
5821 break;
5822 }
5823 if (!FoundAnalyzerConfig)
5824 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5825 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5826 FoundAnalyzerConfig = true;
5827 break;
5828 }
5829 if (FoundAnalyzerConfig)
5830 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5831
5832 CheckCodeGenerationOptions(D, Args);
5833
5834 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5835 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5836 if (FunctionAlignment) {
5837 CmdArgs.push_back(Elt: "-function-alignment");
5838 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(FunctionAlignment)));
5839 }
5840
5841 if (const Arg *A =
5842 Args.getLastArg(Ids: options::OPT_fpreferred_function_alignment_EQ)) {
5843 unsigned Value = 0;
5844 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5845 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5846 << A->getAsString(Args) << A->getValue();
5847 else if (!llvm::isPowerOf2_32(Value))
5848 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5849 << A->getAsString(Args) << A->getValue();
5850
5851 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpreferred-function-alignment=" +
5852 Twine(std::min(a: Value, b: 65536u))));
5853 }
5854
5855 // We support -falign-loops=N where N is a power of 2. GCC supports more
5856 // forms.
5857 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5858 unsigned Value = 0;
5859 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5860 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5861 << A->getAsString(Args) << A->getValue();
5862 else if (Value & (Value - 1))
5863 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5864 << A->getAsString(Args) << A->getValue();
5865 // Treat =0 as unspecified (use the target preference).
5866 if (Value)
5867 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5868 Twine(std::min(a: Value, b: 65536u))));
5869 }
5870
5871 if (Triple.isOSzOS()) {
5872 // On z/OS some of the system header feature macros need to
5873 // be defined to enable most cross platform projects to build
5874 // successfully. Ths include the libc++ library. A
5875 // complicating factor is that users can define these
5876 // macros to the same or different values. We need to add
5877 // the definition for these macros to the compilation command
5878 // if the user hasn't already defined them.
5879
5880 auto findMacroDefinition = [&](const std::string &Macro) {
5881 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5882 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5883 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5884 });
5885 };
5886
5887 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5888 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5889 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5890 // _OPEN_DEFAULT is required for XL compat
5891 if (!findMacroDefinition("_OPEN_DEFAULT"))
5892 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5893 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5894 // _XOPEN_SOURCE=600 is required for libcxx.
5895 if (!findMacroDefinition("_XOPEN_SOURCE"))
5896 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5897 }
5898 }
5899
5900 llvm::Reloc::Model RelocationModel;
5901 unsigned PICLevel;
5902 bool IsPIE;
5903 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5904 Arg *LastPICDataRelArg =
5905 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5906 Ids: options::OPT_mpic_data_is_text_relative);
5907 bool NoPICDataIsTextRelative = false;
5908 if (LastPICDataRelArg) {
5909 if (LastPICDataRelArg->getOption().matches(
5910 ID: options::OPT_mno_pic_data_is_text_relative)) {
5911 NoPICDataIsTextRelative = true;
5912 if (!PICLevel)
5913 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5914 << "-mno-pic-data-is-text-relative"
5915 << "-fpic/-fpie";
5916 }
5917 if (!Triple.isSystemZ())
5918 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5919 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5920 : "-mpic-data-is-text-relative")
5921 << RawTriple.str();
5922 }
5923
5924 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5925 RelocationModel == llvm::Reloc::ROPI_RWPI;
5926 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5927 RelocationModel == llvm::Reloc::ROPI_RWPI;
5928
5929 if (Args.hasArg(Ids: options::OPT_mcmse) &&
5930 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
5931 if (IsROPI)
5932 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
5933 if (IsRWPI)
5934 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5935 }
5936
5937 if (IsROPI && types::isCXX(Id: Input.getType()) &&
5938 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
5939 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
5940
5941 const char *RMName = RelocationModelName(Model: RelocationModel);
5942 if (RMName) {
5943 CmdArgs.push_back(Elt: "-mrelocation-model");
5944 CmdArgs.push_back(Elt: RMName);
5945 }
5946 if (PICLevel > 0) {
5947 CmdArgs.push_back(Elt: "-pic-level");
5948 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
5949 if (IsPIE)
5950 CmdArgs.push_back(Elt: "-pic-is-pie");
5951 if (NoPICDataIsTextRelative)
5952 CmdArgs.push_back(Elt: "-mcmodel=medium");
5953 }
5954
5955 if (RelocationModel == llvm::Reloc::ROPI ||
5956 RelocationModel == llvm::Reloc::ROPI_RWPI)
5957 CmdArgs.push_back(Elt: "-fropi");
5958 if (RelocationModel == llvm::Reloc::RWPI ||
5959 RelocationModel == llvm::Reloc::ROPI_RWPI)
5960 CmdArgs.push_back(Elt: "-frwpi");
5961
5962 // -meabi=gnu/5 are encoded in the cc1 -triple environment; forward only other
5963 // values (e.g. 4, which has no triple representation, and invalid values).
5964 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
5965 StringRef Value = A->getValue();
5966 if (Value != "gnu" && Value != "5") {
5967 CmdArgs.push_back(Elt: "-meabi");
5968 CmdArgs.push_back(Elt: A->getValue());
5969 }
5970 }
5971
5972 // -fsemantic-interposition is forwarded to CC1: set the
5973 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5974 // make default visibility external linkage definitions dso_preemptable.
5975 //
5976 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5977 // aliases (make default visibility external linkage definitions dso_local).
5978 // This is the CC1 default for ELF to match COFF/Mach-O.
5979 //
5980 // Otherwise use Clang's traditional behavior: like
5981 // -fno-semantic-interposition but local aliases are not used. So references
5982 // can be interposed if not optimized out.
5983 if (Triple.isOSBinFormatELF()) {
5984 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
5985 Ids: options::OPT_fno_semantic_interposition);
5986 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5987 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5988 bool SupportsLocalAlias =
5989 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5990 if (!A)
5991 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5992 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
5993 A->render(Args, Output&: CmdArgs);
5994 else if (!SupportsLocalAlias)
5995 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5996 }
5997 }
5998
5999 {
6000 std::string Model;
6001 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
6002 if (!TC.isThreadModelSupported(Model: A->getValue()))
6003 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
6004 << A->getValue() << A->getAsString(Args);
6005 Model = A->getValue();
6006 } else
6007 Model = TC.getThreadModel();
6008 if (Model != "posix") {
6009 CmdArgs.push_back(Elt: "-mthread-model");
6010 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
6011 }
6012 }
6013
6014 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
6015 StringRef Name = A->getValue();
6016 if (Name == "SVML") {
6017 if (Triple.getArch() != llvm::Triple::x86 &&
6018 Triple.getArch() != llvm::Triple::x86_64)
6019 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6020 << Name << Triple.getArchName();
6021 } else if (Name == "AMDLIBM") {
6022 if (Triple.getArch() != llvm::Triple::x86 &&
6023 Triple.getArch() != llvm::Triple::x86_64)
6024 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6025 << Name << Triple.getArchName();
6026 } else if (Name == "libmvec") {
6027 if (Triple.getArch() != llvm::Triple::x86 &&
6028 Triple.getArch() != llvm::Triple::x86_64 &&
6029 Triple.getArch() != llvm::Triple::aarch64 &&
6030 Triple.getArch() != llvm::Triple::aarch64_be)
6031 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6032 << Name << Triple.getArchName();
6033 } else if (Name == "SLEEF" || Name == "ArmPL") {
6034 if (Triple.getArch() != llvm::Triple::aarch64 &&
6035 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6036 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6037 << Name << Triple.getArchName();
6038 }
6039 A->render(Args, Output&: CmdArgs);
6040 }
6041
6042 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
6043 Neg: options::OPT_fno_merge_all_constants, Default: false))
6044 CmdArgs.push_back(Elt: "-fmerge-all-constants");
6045
6046 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
6047 Neg: options::OPT_fno_delete_null_pointer_checks);
6048
6049 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_dse,
6050 Neg: options::OPT_fno_lifetime_dse);
6051
6052 // LLVM Code Generator Options.
6053
6054 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
6055 if (!Triple.isOSAIX() || Triple.isPPC32())
6056 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6057 << A->getSpelling() << RawTriple.str();
6058 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
6059 }
6060
6061 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
6062 // Emit the unsupported option error until the Clang's library integration
6063 // support for 128-bit long double is available for AIX.
6064 if (Triple.isOSAIX())
6065 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6066 << A->getSpelling() << RawTriple.str();
6067 }
6068
6069 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
6070 StringRef V = A->getValue(), V1 = V;
6071 unsigned Size;
6072 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
6073 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6074 << V << A->getOption().getName();
6075 else
6076 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
6077 }
6078
6079 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
6080 Neg: options::OPT_fno_jump_tables);
6081 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
6082 Neg: options::OPT_fno_profile_sample_accurate);
6083 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
6084 Neg: options::OPT_fno_preserve_as_comments);
6085
6086 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
6087 CmdArgs.push_back(Elt: "-mregparm");
6088 CmdArgs.push_back(Elt: A->getValue());
6089 }
6090
6091 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
6092 Ids: options::OPT_msvr4_struct_return)) {
6093 if (!TC.getTriple().isPPC32()) {
6094 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6095 << A->getSpelling() << RawTriple.str();
6096 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
6097 CmdArgs.push_back(Elt: "-maix-struct-return");
6098 } else {
6099 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6100 CmdArgs.push_back(Elt: "-msvr4-struct-return");
6101 }
6102 }
6103
6104 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
6105 Ids: options::OPT_freg_struct_return)) {
6106 if (TC.getArch() != llvm::Triple::x86) {
6107 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6108 << A->getSpelling() << RawTriple.str();
6109 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
6110 CmdArgs.push_back(Elt: "-fpcc-struct-return");
6111 } else {
6112 assert(A->getOption().matches(options::OPT_freg_struct_return));
6113 CmdArgs.push_back(Elt: "-freg-struct-return");
6114 }
6115 }
6116
6117 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
6118 if (Triple.getArch() == llvm::Triple::m68k)
6119 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
6120 else
6121 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
6122 }
6123
6124 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
6125 // enable-matrix is needed by both the LangOpts and by LLVM.
6126 CmdArgs.push_back(Elt: "-fenable-matrix");
6127 CmdArgs.push_back(Elt: "-mllvm");
6128 CmdArgs.push_back(Elt: "-enable-matrix");
6129 // Only handle default layout if matrix is enabled
6130 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
6131 StringRef Val = A->getValue();
6132 if (Val == "row-major" || Val == "column-major") {
6133 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
6134 CmdArgs.push_back(Elt: "-mllvm");
6135 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
6136
6137 } else {
6138 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6139 }
6140 }
6141 }
6142
6143 CodeGenOptions::FramePointerKind FPKeepKind =
6144 getFramePointerKind(Args, Triple: RawTriple);
6145 const char *FPKeepKindStr = nullptr;
6146 switch (FPKeepKind) {
6147 case CodeGenOptions::FramePointerKind::None:
6148 FPKeepKindStr = "-mframe-pointer=none";
6149 break;
6150 case CodeGenOptions::FramePointerKind::Reserved:
6151 FPKeepKindStr = "-mframe-pointer=reserved";
6152 break;
6153 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
6154 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6155 break;
6156 case CodeGenOptions::FramePointerKind::NonLeaf:
6157 FPKeepKindStr = "-mframe-pointer=non-leaf";
6158 break;
6159 case CodeGenOptions::FramePointerKind::All:
6160 FPKeepKindStr = "-mframe-pointer=all";
6161 break;
6162 }
6163 assert(FPKeepKindStr && "unknown FramePointerKind");
6164 CmdArgs.push_back(Elt: FPKeepKindStr);
6165
6166 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
6167 Neg: options::OPT_fno_zero_initialized_in_bss);
6168
6169 bool OFastEnabled = isOptimizationLevelFast(Args);
6170 if (Args.hasArg(Ids: options::OPT_Ofast))
6171 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
6172 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6173 // enabled. This alias option is being used to simplify the hasFlag logic.
6174 OptSpecifier StrictAliasingAliasOption =
6175 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6176 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6177 // doesn't do any TBAA.
6178 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
6179 Neg: options::OPT_fno_strict_aliasing,
6180 Default: !IsWindowsMSVC && !IsUEFI))
6181 CmdArgs.push_back(Elt: "-relaxed-aliasing");
6182 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
6183 Default: false))
6184 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
6185 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
6186 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
6187 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
6188
6189 if (Arg *A = Args.getLastArg(Ids: options::OPT_fstrict_bool,
6190 Ids: options::OPT_fno_strict_bool,
6191 Ids: options::OPT_fno_strict_bool_EQ)) {
6192 StringRef BFM = "";
6193 if (A->getOption().matches(ID: options::OPT_fstrict_bool))
6194 BFM = "strict";
6195 else if (A->getOption().matches(ID: options::OPT_fno_strict_bool))
6196 BFM = "nonstrict";
6197 else if (A->getValue() == StringRef("truncate"))
6198 BFM = "truncate";
6199 else if (A->getValue() == StringRef("nonzero"))
6200 BFM = "nonzero";
6201 else
6202 D.Diag(DiagID: diag::err_drv_invalid_value)
6203 << A->getAsString(Args) << A->getValue();
6204 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-load-bool-from-mem=" + BFM));
6205 } else if (KernelOrKext) {
6206 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6207 CmdArgs.push_back(Elt: "-load-bool-from-mem=truncate");
6208 }
6209
6210 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
6211 Neg: options::OPT_fno_strict_enums);
6212 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
6213 Neg: options::OPT_fno_strict_return);
6214 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
6215 Neg: options::OPT_fno_allow_editor_placeholders);
6216 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
6217 Neg: options::OPT_fno_strict_vtable_pointers);
6218 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
6219 Neg: options::OPT_fno_force_emit_vtables);
6220 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
6221 Neg: options::OPT_fno_optimize_sibling_calls);
6222 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
6223 Neg: options::OPT_fno_escaping_block_tail_calls);
6224
6225 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
6226 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
6227
6228 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6229 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6230
6231 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6232 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6233
6234 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
6235 Ids: options::OPT_fno_disable_block_signature_string);
6236
6237 // Handle segmented stacks.
6238 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
6239 Neg: options::OPT_fno_split_stack);
6240
6241 // -fprotect-parens=0 is default.
6242 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
6243 Neg: options::OPT_fno_protect_parens, Default: false))
6244 CmdArgs.push_back(Elt: "-fprotect-parens");
6245
6246 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6247
6248 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
6249 Neg: options::OPT_fno_atomic_remote_memory);
6250 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
6251 Neg: options::OPT_fno_atomic_fine_grained_memory);
6252 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
6253 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
6254
6255 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
6256 const llvm::Triple::ArchType Arch = TC.getArch();
6257 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6258 StringRef V = A->getValue();
6259 if (V == "64")
6260 CmdArgs.push_back(Elt: "-fextend-arguments=64");
6261 else if (V != "32")
6262 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6263 << A->getValue() << A->getOption().getName();
6264 } else
6265 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6266 << A->getOption().getName() << TripleStr;
6267 }
6268
6269 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
6270 if (TC.getArch() == llvm::Triple::avr)
6271 A->render(Args, Output&: CmdArgs);
6272 else
6273 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6274 << A->getAsString(Args) << TripleStr;
6275 }
6276
6277 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
6278 if (TC.getTriple().isX86())
6279 A->render(Args, Output&: CmdArgs);
6280 else if (TC.getTriple().isPPC() &&
6281 (A->getOption().getID() != options::OPT_mlong_double_80))
6282 A->render(Args, Output&: CmdArgs);
6283 else
6284 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6285 << A->getAsString(Args) << TripleStr;
6286 }
6287
6288 // Decide whether to use verbose asm. Verbose assembly is the default on
6289 // toolchains which have the integrated assembler on by default.
6290 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6291 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
6292 Default: IsIntegratedAssemblerDefault))
6293 CmdArgs.push_back(Elt: "-fno-verbose-asm");
6294
6295 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6296 // use that to indicate the MC default in the backend.
6297 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
6298 StringRef V = A->getValue();
6299 unsigned Num;
6300 if (V == "none")
6301 A->render(Args, Output&: CmdArgs);
6302 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
6303 (V.empty() || (V.consume_front(Prefix: ".") &&
6304 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
6305 A->render(Args, Output&: CmdArgs);
6306 else
6307 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6308 << A->getValue() << A->getOption().getName();
6309 }
6310
6311 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6312 // option to disable integrated-as explicitly.
6313 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
6314 CmdArgs.push_back(Elt: "-no-integrated-as");
6315
6316 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
6317 CmdArgs.push_back(Elt: "-mdebug-pass");
6318 CmdArgs.push_back(Elt: "Structure");
6319 }
6320 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
6321 CmdArgs.push_back(Elt: "-mdebug-pass");
6322 CmdArgs.push_back(Elt: "Arguments");
6323 }
6324
6325 // Enable -mconstructor-aliases except on darwin, where we have to work around
6326 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6327 // code, where aliases aren't supported.
6328 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6329 CmdArgs.push_back(Elt: "-mconstructor-aliases");
6330
6331 // Darwin's kernel doesn't support guard variables; just die if we
6332 // try to use them.
6333 if (KernelOrKext && RawTriple.isOSDarwin())
6334 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
6335
6336 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
6337 Ids: options::OPT_mno_ms_bitfields)) {
6338 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
6339 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
6340 else
6341 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
6342 }
6343
6344 if (Triple.isOSCygMing()) {
6345 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
6346 Neg: options::OPT_fno_auto_import);
6347 }
6348
6349 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
6350 Default: Triple.isX86() && IsWindowsMSVC))
6351 CmdArgs.push_back(Elt: "-fms-volatile");
6352
6353 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6354 // defaults to -fno-direct-access-external-data. Pass the option if different
6355 // from the default.
6356 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
6357 Ids: options::OPT_fno_direct_access_external_data)) {
6358 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
6359 (PICLevel == 0))
6360 A->render(Args, Output&: CmdArgs);
6361 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6362 // Some targets default to -fno-direct-access-external-data even for
6363 // -fno-pic.
6364 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
6365 }
6366
6367 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6368 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
6369
6370 // -fhosted is default.
6371 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6372 // use Freestanding.
6373 bool Freestanding =
6374 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
6375 KernelOrKext;
6376 if (Freestanding)
6377 CmdArgs.push_back(Elt: "-ffreestanding");
6378
6379 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
6380
6381 BoundArch OffloadArch = JA.getOffloadingArch();
6382 auto SanitizeArgs =
6383 TC.getSanitizerArgs(JobArgs: Args, BA: OffloadArch, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6384 Args.AddLastArg(Output&: CmdArgs,
6385 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6386
6387 // This is a coarse approximation of what llvm-gcc actually does, both
6388 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6389 // complicated ways.
6390 bool IsAsyncUnwindTablesDefault =
6391 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6392 bool IsSyncUnwindTablesDefault =
6393 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6394
6395 bool AsyncUnwindTables = Args.hasFlag(
6396 Pos: options::OPT_fasynchronous_unwind_tables,
6397 Neg: options::OPT_fno_asynchronous_unwind_tables,
6398 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6399 !Freestanding);
6400 bool UnwindTables =
6401 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6402 Default: IsSyncUnwindTablesDefault && !Freestanding);
6403 if (AsyncUnwindTables)
6404 CmdArgs.push_back(Elt: "-funwind-tables=2");
6405 else if (UnwindTables)
6406 CmdArgs.push_back(Elt: "-funwind-tables=1");
6407
6408 // Sframe unwind tables are independent of the other types. Although also
6409 // defined for aarch64, only x86_64 support is implemented at the moment.
6410 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6411 if (Triple.isOSBinFormatELF() && Triple.isX86())
6412 CmdArgs.push_back(Elt: "--gsframe");
6413 else
6414 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6415 << A->getOption().getName() << TripleStr;
6416 }
6417
6418 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6419 // `--gpu-use-aux-triple-only` is specified.
6420 if (AuxTriple && !Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only)) {
6421 const ArgList &HostArgs =
6422 C.getArgsForToolChain(TC: nullptr, BA: BoundArch(), DeviceOffloadKind: Action::OFK_None);
6423 std::string HostCPU = getCPUName(D, Args: HostArgs, T: *AuxTriple, /*FromAs*/ false);
6424 if (!HostCPU.empty()) {
6425 CmdArgs.push_back(Elt: "-aux-target-cpu");
6426 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6427 }
6428 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6429 /*ForAS*/ false, /*IsAux*/ true);
6430 }
6431
6432 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
6433 DeviceOffloadKind: JA.getOffloadingDeviceKind());
6434
6435 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6436
6437 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6438 StringRef Value = A->getValue();
6439 unsigned TLSSize = 0;
6440 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6441 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6442 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6443 << A->getOption().getName() << TripleStr;
6444 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6445 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6446 << A->getOption().getName() << Value;
6447 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6448 }
6449
6450 if (isTLSDESCEnabled(TC, Args))
6451 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6452
6453 // Add the target cpu
6454 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6455 if (!CPU.empty()) {
6456 CmdArgs.push_back(Elt: "-target-cpu");
6457 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6458 }
6459
6460 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6461
6462 // Add clang-cl arguments.
6463 types::ID InputType = Input.getType();
6464 if (D.IsCLMode())
6465 AddClangCLArgs(Args, InputType, CmdArgs);
6466
6467 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6468 llvm::codegenoptions::NoDebugInfo;
6469 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6470 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6471 DebugInfoKind, DwarfFission, IsUsingLTO);
6472
6473 // Add the split debug info name to the command lines here so we
6474 // can propagate it to the backend.
6475 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6476 (TC.getTriple().isOSBinFormatELF() ||
6477 TC.getTriple().isOSBinFormatWasm() ||
6478 TC.getTriple().isOSBinFormatCOFF()) &&
6479 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6480 isa<BackendJobAction>(Val: JA));
6481 if (SplitDWARF) {
6482 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6483 CmdArgs.push_back(Elt: "-split-dwarf-file");
6484 CmdArgs.push_back(Elt: SplitDWARFOut);
6485 if (DwarfFission == DwarfFissionKind::Split) {
6486 CmdArgs.push_back(Elt: "-split-dwarf-output");
6487 CmdArgs.push_back(Elt: SplitDWARFOut);
6488 }
6489 }
6490
6491 // Pass the linker version in use.
6492 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6493 CmdArgs.push_back(Elt: "-target-linker-version");
6494 CmdArgs.push_back(Elt: A->getValue());
6495 }
6496
6497 // Explicitly error on some things we know we don't support and can't just
6498 // ignore.
6499 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6500 Arg *Unsupported;
6501 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6502 TC.getArch() == llvm::Triple::x86) {
6503 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6504 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6505 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6506 << Unsupported->getOption().getName();
6507 }
6508 // The faltivec option has been superseded by the maltivec option.
6509 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6510 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6511 << Unsupported->getOption().getName()
6512 << "please use -maltivec and include altivec.h explicitly";
6513 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6514 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6515 << Unsupported->getOption().getName() << "please use -mno-altivec";
6516 }
6517
6518 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6519
6520 if (Args.getLastArg(Ids: options::OPT_H)) {
6521 CmdArgs.push_back(Elt: "-H");
6522 CmdArgs.push_back(Elt: "-sys-header-deps");
6523 }
6524 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6525
6526 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6527 CmdArgs.push_back(Elt: "-header-include-file");
6528 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6529 ? D.CCPrintHeadersFilename.c_str()
6530 : "-");
6531 CmdArgs.push_back(Elt: "-sys-header-deps");
6532 CmdArgs.push_back(Elt: Args.MakeArgString(
6533 Str: "-header-include-format=" +
6534 Twine(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6535 CmdArgs.push_back(Elt: Args.MakeArgString(
6536 Str: "-header-include-filtering=" +
6537 Twine(headerIncludeFilteringKindToString(K: D.CCPrintHeadersFiltering))));
6538 }
6539 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6540 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6541
6542 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6543 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6544 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6545 ? D.CCLogDiagnosticsFilename.c_str()
6546 : "-");
6547 }
6548
6549 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6550 // crashes.
6551 if (D.CCGenDiagnostics)
6552 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6553
6554 // Allow backend to put its diagnostic files in the same place as frontend
6555 // crash diagnostics files.
6556 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6557 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6558 CmdArgs.push_back(Elt: "-mllvm");
6559 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6560 }
6561
6562 addSeparateSectionFlags(Triple, Args, CmdArgs);
6563
6564 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6565 Ids: options::OPT_fno_basic_block_address_map)) {
6566 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6567 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6568 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
6569 A->render(Args, Output&: CmdArgs);
6570 } else {
6571 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6572 << A->getAsString(Args) << TripleStr;
6573 }
6574 }
6575
6576 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6577 StringRef Val = A->getValue();
6578 if (Val == "labels") {
6579 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6580 << A->getAsString(Args) << /*hasReplacement=*/true
6581 << "-fbasic-block-address-map";
6582 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6583 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6584 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6585 D.Diag(DiagID: diag::err_drv_invalid_value)
6586 << A->getAsString(Args) << A->getValue();
6587 else
6588 A->render(Args, Output&: CmdArgs);
6589 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6590 // "all" is not supported on AArch64 since branch relaxation creates new
6591 // basic blocks for some cross-section branches.
6592 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6593 D.Diag(DiagID: diag::err_drv_invalid_value)
6594 << A->getAsString(Args) << A->getValue();
6595 else
6596 A->render(Args, Output&: CmdArgs);
6597 } else if (Triple.isNVPTX()) {
6598 // Do not pass the option to the GPU compilation. We still want it enabled
6599 // for the host-side compilation, so seeing it here is not an error.
6600 } else if (Val != "none") {
6601 // =none is allowed everywhere. It's useful for overriding the option
6602 // and is the same as not specifying the option.
6603 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6604 << A->getAsString(Args) << TripleStr;
6605 }
6606 }
6607
6608 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6609 Neg: options::OPT_fno_unique_section_names);
6610 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6611 Neg: options::OPT_fno_separate_named_sections);
6612 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6613 Neg: options::OPT_fno_unique_internal_linkage_names);
6614 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6615 Neg: options::OPT_fno_unique_basic_block_section_names);
6616
6617 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6618
6619 if (Arg *A =
6620 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6621 Ids: options::OPT_fno_partition_static_data_sections)) {
6622 if (!A->getOption().matches(
6623 ID: options::OPT_fno_partition_static_data_sections)) {
6624 // This codegen pass is only available on x86 and AArch64 ELF targets.
6625 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6626 A->render(Args, Output&: CmdArgs);
6627 CmdArgs.push_back(Elt: "-mllvm");
6628 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6629 } else
6630 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6631 << A->getAsString(Args) << TripleStr;
6632 }
6633 }
6634
6635 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6636 Ids: options::OPT_finstrument_functions_after_inlining,
6637 Ids: options::OPT_finstrument_function_entry_bare);
6638 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6639 Ids: options::OPT_fno_convergent_functions);
6640
6641 // NVPTX doesn't support PGO or coverage
6642 if (!Triple.isNVPTX())
6643 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6644
6645 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6646
6647 if (getLastProfileSampleUseArg(Args) &&
6648 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6649 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6650 CmdArgs.push_back(Elt: "-mllvm");
6651 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6652 }
6653
6654 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6655 if (RawTriple.isPS() &&
6656 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6657 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6658 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6659 }
6660
6661 // Pass options for controlling the default header search paths.
6662 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6663 CmdArgs.push_back(Elt: "-nostdsysteminc");
6664 CmdArgs.push_back(Elt: "-nobuiltininc");
6665 } else {
6666 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6667 CmdArgs.push_back(Elt: "-nostdsysteminc");
6668 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6669 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6670 }
6671
6672 // Pass the path to compiler resource files.
6673 CmdArgs.push_back(Elt: "-resource-dir");
6674 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6675
6676 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6677
6678 // Add preprocessing options like -I, -D, etc. if we are using the
6679 // preprocessor.
6680 //
6681 // FIXME: Support -fpreprocessed
6682 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6683 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6684
6685 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6686 // that "The compiler can only warn and ignore the option if not recognized".
6687 // When building with ccache, it will pass -D options to clang even on
6688 // preprocessed inputs and configure concludes that -fPIC is not supported.
6689 Args.ClaimAllArgs(Id0: options::OPT_D);
6690
6691 // Warn about ignored options to clang.
6692 for (const Arg *A :
6693 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6694 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6695 A->claim();
6696 }
6697
6698 for (const Arg *A :
6699 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6700 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6701 A->claim();
6702 }
6703
6704 claimNoWarnArgs(Args);
6705
6706 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6707
6708 for (const Arg *A :
6709 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6710 A->claim();
6711 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6712 unsigned WarningNumber;
6713 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6714 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6715 << A->getAsString(Args) << A->getValue();
6716 continue;
6717 }
6718
6719 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6720 CmdArgs.push_back(Elt: Args.MakeArgString(
6721 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6722 }
6723 continue;
6724 }
6725 A->render(Args, Output&: CmdArgs);
6726 }
6727
6728 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6729
6730 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6731 CmdArgs.push_back(Elt: "-pedantic");
6732 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6733 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6734
6735 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6736 Neg: options::OPT_fno_fixed_point);
6737
6738 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_overflow_behavior_types,
6739 Neg: options::OPT_fno_experimental_overflow_behavior_types);
6740
6741 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6742 A->render(Args, Output&: CmdArgs);
6743
6744 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6745 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6746
6747 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6748 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6749
6750 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6751 A->render(Args, Output&: CmdArgs);
6752
6753 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6754 // (-ansi is equivalent to -std=c89 or -std=c++98).
6755 //
6756 // If a std is supplied, only add -trigraphs if it follows the
6757 // option.
6758 bool ImplyVCPPCVer = false;
6759 bool ImplyVCPPCXXVer = false;
6760 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6761 if (Std) {
6762 if (Std->getOption().matches(ID: options::OPT_ansi))
6763 if (types::isCXX(Id: InputType))
6764 CmdArgs.push_back(Elt: "-std=c++98");
6765 else
6766 CmdArgs.push_back(Elt: "-std=c89");
6767 else {
6768 if (IsSYCL) {
6769 const LangStandard *LangStd =
6770 LangStandard::getLangStandardForName(Name: Std->getValue());
6771 if (LangStd) {
6772 // Use of -std= with 'C' is not supported for SYCL.
6773 if (LangStd->getLanguage() == Language::C)
6774 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
6775 << Std->getAsString(Args) << "-fsycl";
6776 // SYCL requires C++17 or later.
6777 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6778 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6779 }
6780 }
6781 Std->render(Args, Output&: CmdArgs);
6782 }
6783
6784 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6785 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6786 Ids: options::OPT_ftrigraphs,
6787 Ids: options::OPT_fno_trigraphs))
6788 if (A != Std)
6789 A->render(Args, Output&: CmdArgs);
6790 } else {
6791 // Honor -std-default.
6792 //
6793 // FIXME: Clang doesn't correctly handle -std= when the input language
6794 // doesn't match. For the time being just ignore this for C++ inputs;
6795 // eventually we want to do all the standard defaulting here instead of
6796 // splitting it between the driver and clang -cc1.
6797 if (!types::isCXX(Id: InputType)) {
6798 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6799 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6800 /*Joined=*/true);
6801 } else
6802 ImplyVCPPCVer = true;
6803 }
6804 else if (IsWindowsMSVC)
6805 ImplyVCPPCXXVer = true;
6806
6807 if (IsSYCL && types::isCXX(Id: InputType) &&
6808 !Args.hasArg(Ids: options::OPT__SLASH_std) && !IsWindowsMSVC)
6809 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6810 // on the command line will override. On Windows MSVC, this is handled
6811 // by the ImplyVCPPCXXVer path below.
6812 CmdArgs.push_back(Elt: "-std=c++17");
6813
6814 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6815 Ids: options::OPT_fno_trigraphs);
6816 }
6817
6818 // GCC's behavior for -Wwrite-strings is a bit strange:
6819 // * In C, this "warning flag" changes the types of string literals from
6820 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6821 // for the discarded qualifier.
6822 // * In C++, this is just a normal warning flag.
6823 //
6824 // Implementing this warning correctly in C is hard, so we follow GCC's
6825 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6826 // a non-const char* in C, rather than using this crude hack.
6827 if (!types::isCXX(Id: InputType)) {
6828 // FIXME: This should behave just like a warning flag, and thus should also
6829 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6830 Arg *WriteStrings =
6831 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6832 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6833 if (WriteStrings &&
6834 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6835 CmdArgs.push_back(Elt: "-fconst-strings");
6836 }
6837
6838 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6839 // during C++ compilation, which it is by default. GCC keeps this define even
6840 // in the presence of '-w', match this behavior bug-for-bug.
6841 if (types::isCXX(Id: InputType) &&
6842 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6843 Default: true)) {
6844 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6845 }
6846
6847 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6848 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6849 if (Asm->getOption().matches(ID: options::OPT_fasm))
6850 CmdArgs.push_back(Elt: "-fgnu-keywords");
6851 else
6852 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6853 }
6854
6855 if (!ShouldEnableAutolink(Args, TC, JA))
6856 CmdArgs.push_back(Elt: "-fno-autolink");
6857
6858 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6859 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6860 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6861 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6862
6863 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6864
6865 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6866 Args.ClaimAllArgs(Id0: options::OPT_fexperimental_new_constant_interpreter);
6867 Args.AddLastArg(Output&: CmdArgs,
6868 Ids: options::OPT_fno_experimental_new_constant_interpreter);
6869 } else {
6870 Args.ClaimAllArgs(Id0: options::OPT_fno_experimental_new_constant_interpreter);
6871 Args.AddLastArg(Output&: CmdArgs,
6872 Ids: options::OPT_fexperimental_new_constant_interpreter);
6873 }
6874
6875 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6876 CmdArgs.push_back(Elt: "-fbracket-depth");
6877 CmdArgs.push_back(Elt: A->getValue());
6878 }
6879
6880 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6881 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6882 if (A->getNumValues()) {
6883 StringRef bytes = A->getValue();
6884 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6885 } else
6886 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6887 }
6888
6889 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6890 CmdArgs.push_back(Elt: "-relocatable-pch");
6891
6892 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6893 static const char *kCFABIs[] = {
6894 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6895 };
6896
6897 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6898 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6899 else
6900 A->render(Args, Output&: CmdArgs);
6901 }
6902
6903 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6904 CmdArgs.push_back(Elt: "-fconstant-string-class");
6905 CmdArgs.push_back(Elt: A->getValue());
6906 }
6907
6908 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_array_class_EQ)) {
6909 CmdArgs.push_back(Elt: "-fconstant-array-class");
6910 CmdArgs.push_back(Elt: A->getValue());
6911 }
6912 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_dictionary_class_EQ)) {
6913 CmdArgs.push_back(Elt: "-fconstant-dictionary-class");
6914 CmdArgs.push_back(Elt: A->getValue());
6915 }
6916 if (Arg *A =
6917 Args.getLastArg(Ids: options::OPT_fconstant_integer_number_class_EQ)) {
6918 CmdArgs.push_back(Elt: "-fconstant-integer-number-class");
6919 CmdArgs.push_back(Elt: A->getValue());
6920 }
6921 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_float_number_class_EQ)) {
6922 CmdArgs.push_back(Elt: "-fconstant-float-number-class");
6923 CmdArgs.push_back(Elt: A->getValue());
6924 }
6925 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_double_number_class_EQ)) {
6926 CmdArgs.push_back(Elt: "-fconstant-double-number-class");
6927 CmdArgs.push_back(Elt: A->getValue());
6928 }
6929
6930 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
6931 CmdArgs.push_back(Elt: "-ftabstop");
6932 CmdArgs.push_back(Elt: A->getValue());
6933 }
6934
6935 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
6936 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
6937 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
6938
6939 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
6940 Neg: options::OPT_fno_stack_size_section);
6941
6942 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
6943 CmdArgs.push_back(Elt: "-stack-usage-file");
6944
6945 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
6946 SmallString<128> OutputFilename(OutputOpt->getValue());
6947 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
6948 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
6949 } else
6950 CmdArgs.push_back(
6951 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6952 }
6953
6954 CmdArgs.push_back(Elt: "-ferror-limit");
6955 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
6956 CmdArgs.push_back(Elt: A->getValue());
6957 else
6958 CmdArgs.push_back(Elt: "19");
6959
6960 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
6961 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
6962 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
6963 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
6964 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
6965
6966 // Pass -fmessage-length=.
6967 unsigned MessageLength = 0;
6968 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
6969 StringRef V(A->getValue());
6970 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
6971 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6972 << V << A->getOption().getName();
6973 } else {
6974 // If -fmessage-length=N was not specified, determine whether this is a
6975 // terminal and, if so, implicitly define -fmessage-length appropriately.
6976 MessageLength = llvm::sys::Process::StandardErrColumns();
6977 }
6978 if (MessageLength != 0)
6979 CmdArgs.push_back(
6980 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
6981
6982 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
6983 CmdArgs.push_back(
6984 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
6985
6986 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
6987 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
6988 Twine(A->getValue(N: 0))));
6989
6990 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6991 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
6992 Ids: options::OPT_fvisibility_ms_compat)) {
6993 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
6994 A->render(Args, Output&: CmdArgs);
6995 } else {
6996 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6997 CmdArgs.push_back(Elt: "-fvisibility=hidden");
6998 CmdArgs.push_back(Elt: "-ftype-visibility=default");
6999 }
7000 } else if (IsOpenMPDevice) {
7001 // When compiling for the OpenMP device we want protected visibility by
7002 // default. This prevents the device from accidentally preempting code on
7003 // the host, makes the system more robust, and improves performance.
7004 CmdArgs.push_back(Elt: "-fvisibility=protected");
7005 }
7006
7007 // PS4/PS5 process these options in addClangTargetOptions.
7008 if (!RawTriple.isPS()) {
7009 if (const Arg *A =
7010 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
7011 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
7012 if (A->getOption().matches(
7013 ID: options::OPT_fvisibility_from_dllstorageclass)) {
7014 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
7015 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
7016 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
7017 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
7018 Args.AddLastArg(Output&: CmdArgs,
7019 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7020 }
7021 }
7022 }
7023
7024 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
7025 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
7026 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
7027
7028 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
7029 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
7030
7031 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7032 // -fvisibility-global-new-delete=force-hidden.
7033 if (const Arg *A =
7034 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7035 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
7036 << A->getAsString(Args) << /*hasReplacement=*/true
7037 << "-fvisibility-global-new-delete=force-hidden";
7038 }
7039
7040 if (const Arg *A =
7041 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
7042 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7043 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
7044 A->render(Args, Output&: CmdArgs);
7045 } else {
7046 assert(A->getOption().matches(
7047 options::OPT_fvisibility_global_new_delete_hidden));
7048 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
7049 }
7050 }
7051
7052 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
7053
7054 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
7055 Neg: options::OPT_fno_new_infallible, Default: false))
7056 CmdArgs.push_back(Elt: "-fnew-infallible");
7057
7058 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
7059 Neg: options::OPT_foperator_names, Default: false))
7060 CmdArgs.push_back(Elt: "-fno-operator-names");
7061
7062 // Forward -f (flag) options which we can pass directly.
7063 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
7064 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
7065 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
7066 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
7067 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
7068 Ids: options::OPT_fno_raw_string_literals);
7069
7070 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
7071 Default: Triple.hasDefaultEmulatedTLS()))
7072 CmdArgs.push_back(Elt: "-femulated-tls");
7073
7074 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
7075 Neg: options::OPT_fno_check_new);
7076
7077 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
7078 // FIXME: There's no reason for this to be restricted to some backend.
7079 // The backend code needs to be changed to include the appropriate function
7080 // calls automatically.
7081 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7082 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7083 << A->getAsString(Args) << TripleStr;
7084 }
7085
7086 // AltiVec-like language extensions aren't relevant for assembling.
7087 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
7088 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
7089
7090 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
7091 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
7092
7093 // Forward flags for OpenMP. We don't do this if the current action is an
7094 // device offloading action other than OpenMP.
7095 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
7096 Neg: options::OPT_fno_openmp, Default: false) &&
7097 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7098 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
7099 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
7100 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
7101
7102 // Determine if target-fast optimizations should be enabled
7103 bool TargetFastUsed =
7104 Args.hasFlag(Pos: options::OPT_fopenmp_target_fast,
7105 Neg: options::OPT_fno_openmp_target_fast, Default: OFastEnabled);
7106 switch (D.getOpenMPRuntime(Args)) {
7107 case Driver::OMPRT_OMP:
7108 case Driver::OMPRT_IOMP5:
7109 // Clang can generate useful OpenMP code for these two runtime libraries.
7110 CmdArgs.push_back(Elt: "-fopenmp");
7111
7112 // If no option regarding the use of TLS in OpenMP codegeneration is
7113 // given, decide a default based on the target. Otherwise rely on the
7114 // options and pass the right information to the frontend.
7115 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
7116 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7117 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
7118 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7119 Ids: options::OPT_fno_openmp_simd);
7120 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
7121 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7122 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
7123 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
7124 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
7125 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
7126 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7127 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7128 // effect: the teams reduction buffer is sized at kernel launch by the
7129 // offload plugin to match the actual number of teams. Honoring a
7130 // smaller user-supplied value would silently truncate the buffer for
7131 // larger launches.
7132 if (Arg *A = Args.getLastArg(
7133 Ids: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7134 D.Diag(DiagID: diag::warn_drv_deprecated_custom)
7135 << A->getAsString(Args)
7136 << "the value is ignored; the teams reduction buffer is sized "
7137 "automatically at kernel launch";
7138 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
7139 Neg: options::OPT_fno_openmp_optimistic_collapse,
7140 /*Default=*/false))
7141 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
7142
7143 // When in OpenMP offloading mode with NVPTX target, forward
7144 // cuda-mode flag
7145 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
7146 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7147 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
7148
7149 // When in OpenMP offloading mode, enable debugging on the device.
7150 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
7151 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
7152 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
7153 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
7154
7155 // When in OpenMP offloading mode, forward assumptions information about
7156 // thread and team counts in the device.
7157 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
7158 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
7159 /*Default=*/TargetFastUsed))
7160 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
7161 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
7162 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
7163 /*Default=*/TargetFastUsed))
7164 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
7165
7166 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7167 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_thread_state,
7168 Neg: options::OPT_fno_openmp_assume_no_thread_state,
7169 /*Default=*/TargetFastUsed))
7170 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
7171
7172 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7173 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_nested_parallelism,
7174 Neg: options::OPT_fno_openmp_assume_no_nested_parallelism,
7175 /*Default=*/TargetFastUsed))
7176 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
7177
7178 // Handle -fopenmp-target-atomic-reduction.
7179 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_atomic_reduction,
7180 Neg: options::OPT_fno_openmp_target_atomic_reduction,
7181 /*Default=*/false))
7182 CmdArgs.push_back(Elt: "-fopenmp-target-atomic-reduction");
7183
7184 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
7185 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
7186 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
7187 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
7188 break;
7189 default:
7190 // By default, if Clang doesn't know how to generate useful OpenMP code
7191 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7192 // down to the actual compilation.
7193 // FIXME: It would be better to have a mode which *only* omits IR
7194 // generation based on the OpenMP support so that we get consistent
7195 // semantic analysis, etc.
7196 break;
7197 }
7198 } else {
7199 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7200 Ids: options::OPT_fno_openmp_simd);
7201 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7202 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
7203 Neg: options::OPT_fno_openmp_extensions);
7204 }
7205 // Forward '-foffload-via-llvm' to code generation to target the LLVM/Offload
7206 // runtime.
7207 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7208 Neg: options::OPT_fno_offload_via_llvm, Default: false))
7209 CmdArgs.push_back(Elt: "-foffload-via-llvm");
7210
7211 const XRayArgs &XRay = TC.getXRayArgs(Args);
7212 XRay.addArgs(TC, Args, CmdArgs, InputType);
7213
7214 for (const auto &Filename :
7215 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
7216 if (D.getVFS().exists(Path: Filename))
7217 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
7218 else
7219 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
7220 }
7221
7222 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
7223 StringRef S0 = A->getValue(), S = S0;
7224 unsigned Size, Offset = 0;
7225 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7226 !Triple.isX86() && !Triple.isSystemZ() &&
7227 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7228 Triple.getArch() == llvm::Triple::ppc64 ||
7229 Triple.getArch() == llvm::Triple::ppc64le)))
7230 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7231 << A->getAsString(Args) << TripleStr;
7232 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
7233 (!S.empty() &&
7234 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
7235 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
7236 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7237 << S0 << A->getOption().getName();
7238 else if (Size < Offset)
7239 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
7240 else {
7241 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
7242 CmdArgs.push_back(Elt: Args.MakeArgString(
7243 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
7244 if (!S.empty())
7245 CmdArgs.push_back(
7246 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
7247 }
7248 }
7249
7250 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
7251
7252 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
7253 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
7254
7255 for (const auto &A :
7256 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
7257 CmdArgs.push_back(
7258 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
7259
7260 if (TC.SupportsProfiling()) {
7261 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
7262
7263 llvm::Triple::ArchType Arch = TC.getArch();
7264 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
7265 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7266 A->render(Args, Output&: CmdArgs);
7267 else
7268 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7269 << A->getAsString(Args) << TripleStr;
7270 }
7271 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
7272 if (Arch == llvm::Triple::systemz)
7273 A->render(Args, Output&: CmdArgs);
7274 else
7275 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7276 << A->getAsString(Args) << TripleStr;
7277 }
7278 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
7279 if (Arch == llvm::Triple::systemz)
7280 A->render(Args, Output&: CmdArgs);
7281 else
7282 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7283 << A->getAsString(Args) << TripleStr;
7284 }
7285 }
7286
7287 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
7288 if (TC.getTriple().isOSzOS()) {
7289 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7290 << A->getAsString(Args) << TripleStr;
7291 }
7292 }
7293 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
7294 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7295 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7296 << A->getAsString(Args) << TripleStr;
7297 }
7298 }
7299 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
7300 if (A->getOption().matches(ID: options::OPT_p)) {
7301 A->claim();
7302 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
7303 CmdArgs.push_back(Elt: "-pg");
7304 }
7305 }
7306
7307 // Reject AIX-specific link options on other targets.
7308 if (!TC.getTriple().isOSAIX()) {
7309 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
7310 Ids: options::OPT_mxcoff_build_id_EQ)) {
7311 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7312 << A->getSpelling() << TripleStr;
7313 }
7314 }
7315
7316 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
7317 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
7318 CmdArgs.push_back(Elt: "-fapple-kext");
7319
7320 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
7321 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
7322 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
7323 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
7324 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
7325 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
7326 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
7327 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
7328 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
7329 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
7330 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
7331
7332 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
7333 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
7334 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
7335 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
7336 }
7337
7338 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
7339 CmdArgs.push_back(Elt: "-ftrapv-handler");
7340 CmdArgs.push_back(Elt: A->getValue());
7341 }
7342
7343 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
7344
7345 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
7346 Ids: options::OPT_fno_finite_loops);
7347
7348 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
7349 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
7350 Ids: options::OPT_fno_unroll_loops);
7351 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
7352 Ids: options::OPT_fno_loop_interchange);
7353 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
7354 Neg: options::OPT_fno_experimental_loop_fusion);
7355
7356 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
7357
7358 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
7359
7360 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
7361 Neg: options::OPT_mno_speculative_load_hardening);
7362
7363 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7364 RenderSCPOptions(TC, Args, CmdArgs);
7365 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7366
7367 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
7368
7369 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
7370 Neg: options::OPT_mno_stackrealign);
7371
7372 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
7373 StringRef Value = A->getValue();
7374 int64_t Alignment = 0;
7375 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
7376 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7377 << Value << A->getOption().getName();
7378 else if (Alignment & (Alignment - 1))
7379 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
7380 << A->getAsString(Args) << Value;
7381 else
7382 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
7383 }
7384
7385 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
7386 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
7387
7388 if (!Size.empty())
7389 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
7390 else
7391 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
7392 }
7393
7394 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
7395 Neg: options::OPT_mno_stack_arg_probe);
7396
7397 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
7398 Ids: options::OPT_mno_restrict_it)) {
7399 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
7400 CmdArgs.push_back(Elt: "-mllvm");
7401 CmdArgs.push_back(Elt: "-arm-restrict-it");
7402 } else {
7403 CmdArgs.push_back(Elt: "-mllvm");
7404 CmdArgs.push_back(Elt: "-arm-default-it");
7405 }
7406 }
7407
7408 // Forward -cl options to -cc1
7409 RenderOpenCLOptions(Args, CmdArgs, InputType);
7410
7411 // Forward hlsl options to -cc1
7412 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7413
7414 // Forward OpenACC options to -cc1
7415 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7416
7417 if (IsHIP) {
7418 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
7419 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
7420 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
7421 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
7422 Neg: options::OPT_fno_gpu_allow_device_init);
7423 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
7424 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
7425 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
7426 Neg: options::OPT_fno_hip_kernel_arg_name);
7427 }
7428
7429 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7430 CmdArgs.push_back(Elt: "-fgpu-rdc");
7431
7432 if (IsCuda || IsHIP) {
7433 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
7434 Neg: options::OPT_fno_gpu_defer_diag);
7435 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
7436 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
7437 Default: false)) {
7438 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
7439 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
7440 }
7441 }
7442
7443 // Forward --no-offloadlib to -cc1.
7444 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7445 CmdArgs.push_back(Elt: "--no-offloadlib");
7446
7447 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7448 CmdArgs.push_back(
7449 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7450
7451 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7452 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7453 SA->getValue()));
7454 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7455 // Emit IBT endbr64 instructions by default
7456 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7457 // jump-table can generate indirect jumps, which are not permitted
7458 CmdArgs.push_back(Elt: "-fno-jump-tables");
7459 }
7460
7461 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7462 CmdArgs.push_back(
7463 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7464
7465 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7466
7467 // Forward -f options with positive and negative forms; we translate these by
7468 // hand. Do not propagate PGO options to the GPU-side compilations as the
7469 // profile info is for the host-side compilation only.
7470 if (!(IsCudaDevice || IsHIPDevice)) {
7471 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7472 auto *PGOArg = Args.getLastArg(
7473 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7474 Ids: options::OPT_fcs_profile_generate,
7475 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7476 Ids: options::OPT_fprofile_use_EQ);
7477 if (PGOArg)
7478 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7479 << "SampleUse with PGO options";
7480
7481 StringRef fname = A->getValue();
7482 if (!llvm::sys::fs::exists(Path: fname))
7483 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7484 else
7485 A->render(Args, Output&: CmdArgs);
7486 }
7487 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7488
7489 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7490 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7491 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7492 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7493 // off.
7494 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7495 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7496 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7497 }
7498 }
7499 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7500
7501 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7502 Neg: options::OPT_fno_assume_sane_operator_new);
7503
7504 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7505 CmdArgs.push_back(Elt: "-fapinotes");
7506 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7507 Neg: options::OPT_fno_apinotes_modules, Default: false))
7508 CmdArgs.push_back(Elt: "-fapinotes-modules");
7509 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7510
7511 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7512 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7513 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7514
7515 // -fblocks=0 is default.
7516 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7517 Default: TC.IsBlocksDefault()) ||
7518 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7519 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7520 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7521 CmdArgs.push_back(Elt: "-fblocks");
7522
7523 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7524 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7525 }
7526
7527 // -fencode-extended-block-signature=1 is default.
7528 if (TC.IsEncodeExtendedBlockSignatureDefault())
7529 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7530
7531 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7532 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7533 types::isCXX(Id: InputType))
7534 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7535
7536 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7537 /*Default=*/false))
7538 CmdArgs.push_back(Elt: "-fdefer-ts");
7539
7540 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7541 Ids: options::OPT_fno_double_square_bracket_attributes);
7542
7543 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7544 Neg: options::OPT_fno_access_control);
7545 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7546 Neg: options::OPT_fno_elide_constructors);
7547
7548 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7549
7550 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7551 (RTTIMode == ToolChain::RM_Disabled)))
7552 CmdArgs.push_back(Elt: "-fno-rtti");
7553
7554 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7555 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7556 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7557 CmdArgs.push_back(Elt: "-fshort-enums");
7558
7559 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7560
7561 // -fuse-cxa-atexit is default.
7562 if (!Args.hasFlag(
7563 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7564 Default: !RawTriple.isOSAIX() &&
7565 (!RawTriple.isOSWindows() ||
7566 RawTriple.isWindowsCygwinEnvironment()) &&
7567 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7568 RawTriple.hasEnvironment())) ||
7569 KernelOrKext)
7570 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7571
7572 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7573 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7574 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7575 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7576
7577 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7578 Neg: options::OPT_fno_use_line_directives);
7579
7580 // -fno-minimize-whitespace is default.
7581 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7582 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7583 types::ID InputType = Inputs[0].getType();
7584 if (!isDerivedFromC(Id: InputType))
7585 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7586 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7587 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7588 }
7589
7590 // -fno-keep-system-includes is default.
7591 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7592 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7593 types::ID InputType = Inputs[0].getType();
7594 if (!isDerivedFromC(Id: InputType))
7595 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7596 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7597 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7598 }
7599
7600 // -fms-extensions=0 is default.
7601 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7602 Default: IsWindowsMSVC || IsUEFI))
7603 CmdArgs.push_back(Elt: "-fms-extensions");
7604
7605 // -fms-compatibility=0 is default.
7606 bool IsMSVCCompat = Args.hasFlag(
7607 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7608 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7609 Neg: options::OPT_fno_ms_extensions, Default: true)));
7610 if (IsMSVCCompat) {
7611 CmdArgs.push_back(Elt: "-fms-compatibility");
7612 if (!types::isCXX(Id: Input.getType()) &&
7613 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7614 CmdArgs.push_back(Elt: "-fms-define-stdc");
7615 }
7616
7617 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7618 // clang and flang.
7619 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7620
7621 // -fms-anonymous-structs is disabled by default.
7622 // Determine whether to enable Microsoft named anonymous struct/union support.
7623 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7624 // where the feature can be:
7625 // - Explicitly enabled via -fms-anonymous-structs.
7626 // - Explicitly disabled via fno-ms-anonymous-structs
7627 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7628 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7629 //
7630 // When multiple relevent options are present, the last option on the command
7631 // line takes precedence. This allows users to selectively override implicit
7632 // enablement. Examples:
7633 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7634 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7635 auto MSAnonymousStructsOptionToUseOrNull =
7636 [](const ArgList &Args) -> const char * {
7637 const char *Option = nullptr;
7638 constexpr const char *Enable = "-fms-anonymous-structs";
7639 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7640
7641 // Iterate through all arguments in order to implement "last flag wins".
7642 for (const Arg *A : Args) {
7643 switch (A->getOption().getID()) {
7644 case options::OPT_fms_anonymous_structs:
7645 A->claim();
7646 Option = Enable;
7647 break;
7648 case options::OPT_fno_ms_anonymous_structs:
7649 A->claim();
7650 Option = Disable;
7651 break;
7652 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7653 // feature.
7654 case options::OPT_fms_extensions:
7655 case options::OPT_fms_compatibility:
7656 Option = Enable;
7657 break;
7658 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7659 // disables the feature.
7660 case options::OPT_fno_ms_extensions:
7661 case options::OPT_fno_ms_compatibility:
7662 Option = Disable;
7663 break;
7664 default:
7665 break;
7666 }
7667 }
7668 return Option;
7669 };
7670
7671 // Only pass a flag to CC1 if a relevant option was seen
7672 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7673 CmdArgs.push_back(Elt: MSAnonOpt);
7674
7675 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7676 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7677 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7678
7679 // Handle -fgcc-version, if present.
7680 VersionTuple GNUCVer;
7681 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7682 // Check that the version has 1 to 3 components and the minor and patch
7683 // versions fit in two decimal digits.
7684 StringRef Val = A->getValue();
7685 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7686 bool Invalid = GNUCVer.tryParse(string: Val);
7687 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7688 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7689 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7690 D.Diag(DiagID: diag::err_drv_invalid_value)
7691 << A->getAsString(Args) << A->getValue();
7692 }
7693 } else if (!IsMSVCCompat) {
7694 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7695 GNUCVer = VersionTuple(4, 2, 1);
7696 }
7697 if (!GNUCVer.empty()) {
7698 CmdArgs.push_back(
7699 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7700 }
7701
7702 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7703 if (!MSVT.empty())
7704 CmdArgs.push_back(
7705 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7706
7707 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7708 if (ImplyVCPPCVer) {
7709 StringRef LanguageStandard;
7710 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7711 Std = StdArg;
7712 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7713 .Case(S: "c11", Value: "-std=c11")
7714 .Case(S: "c17", Value: "-std=c17")
7715 // If you add cases below for spellings that are
7716 // not in LangStandards.def, update
7717 // TransferableCommand::tryParseStdArg() in
7718 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7719 // to match.
7720 // TODO: add c23 when MSVC supports it.
7721 .Case(S: "clatest", Value: "-std=c23")
7722 .Default(Value: "");
7723 if (LanguageStandard.empty())
7724 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7725 << StdArg->getAsString(Args);
7726 }
7727 CmdArgs.push_back(Elt: LanguageStandard.data());
7728 }
7729 if (ImplyVCPPCXXVer) {
7730 StringRef LanguageStandard;
7731 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7732 Std = StdArg;
7733 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7734 .Case(S: "c++14", Value: "-std=c++14")
7735 .Case(S: "c++17", Value: "-std=c++17")
7736 .Case(S: "c++20", Value: "-std=c++20")
7737 // If you add cases below for spellings that are
7738 // not in LangStandards.def, update
7739 // TransferableCommand::tryParseStdArg() in
7740 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7741 // to match.
7742 // TODO add c++23, c++26, c++29 when MSVC supports
7743 // it.
7744 .Case(S: "c++23preview", Value: "-std=c++23")
7745 .Case(S: "c++26preview", Value: "-std=c++26")
7746 .Case(S: "c++latest", Value: "-std=c++2d")
7747 .Default(Value: "");
7748 if (IsSYCL) {
7749 const LangStandard *LangStd =
7750 LangStandard::getLangStandardForName(Name: StdArg->getValue());
7751 if (LangStd) {
7752 // Use of /std: with 'C' is not supported for SYCL.
7753 if (LangStd->getLanguage() == Language::C)
7754 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7755 << StdArg->getAsString(Args) << "-fsycl";
7756 // SYCL requires C++17 or later.
7757 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7758 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17)
7759 << StdArg->getAsString(Args);
7760 }
7761 }
7762 if (LanguageStandard.empty())
7763 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7764 << StdArg->getAsString(Args);
7765 }
7766
7767 if (LanguageStandard.empty()) {
7768 if (IsSYCL)
7769 // For SYCL, C++17 is the default.
7770 LanguageStandard = "-std=c++17";
7771 else if (IsMSVC2015Compatible)
7772 LanguageStandard = "-std=c++14";
7773 else
7774 LanguageStandard = "-std=c++11";
7775 }
7776
7777 CmdArgs.push_back(Elt: LanguageStandard.data());
7778 }
7779
7780 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7781 Neg: options::OPT_fno_borland_extensions);
7782
7783 // -fno-declspec is default, except for PS4/PS5.
7784 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7785 Default: RawTriple.isPS()))
7786 CmdArgs.push_back(Elt: "-fdeclspec");
7787 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7788 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7789
7790 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7791 // than 19.
7792 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7793 Neg: options::OPT_fno_threadsafe_statics,
7794 Default: !types::isOpenCL(Id: InputType) &&
7795 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7796 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7797
7798 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7799 Default: true))
7800 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7801
7802 // Add -fno-assumptions, if it was specified.
7803 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7804 Default: true))
7805 CmdArgs.push_back(Elt: "-fno-assumptions");
7806
7807 // -fgnu-keywords default varies depending on language; only pass if
7808 // specified.
7809 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7810 Ids: options::OPT_fno_gnu_keywords);
7811
7812 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7813 Neg: options::OPT_fno_gnu89_inline);
7814
7815 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7816 Ids: options::OPT_finline_hint_functions,
7817 Ids: options::OPT_fno_inline_functions);
7818 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7819 if (A->getOption().matches(ID: options::OPT_fno_inline))
7820 A->render(Args, Output&: CmdArgs);
7821 } else if (InlineArg) {
7822 InlineArg->render(Args, Output&: CmdArgs);
7823 }
7824
7825 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7826
7827 // FIXME: Find a better way to determine whether we are in C++20.
7828 bool HaveCxx20 =
7829 Std &&
7830 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7831 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7832 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7833 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7834 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7835 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7836 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++26preview") ||
7837 Std->containsValue(Value: "c++2d") || Std->containsValue(Value: "gnu++2d") ||
7838 Std->containsValue(Value: "c++latest") || Std->containsValue(Value: "gnu++latest"));
7839 bool HaveModules =
7840 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7841
7842 // -fdelayed-template-parsing is default when targeting MSVC.
7843 // Many old Windows SDK versions require this to parse.
7844 //
7845 // According to
7846 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7847 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7848 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7849 // not enable -fdelayed-template-parsing by default after C++20.
7850 //
7851 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7852 // able to disable this by default at some point.
7853 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7854 Neg: options::OPT_fno_delayed_template_parsing,
7855 Default: IsWindowsMSVC && !HaveCxx20)) {
7856 if (HaveCxx20)
7857 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7858
7859 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7860 }
7861
7862 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7863 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7864 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7865 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7866 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7867 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7868 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7869 Default: false))
7870 CmdArgs.push_back(Elt: "-fmodules-codegen");
7871 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7872 Default: false))
7873 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7874
7875 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7876 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7877 Input, CmdArgs);
7878
7879 if (types::isObjC(Id: Input.getType()) &&
7880 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7881 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7882 Default: !Runtime.isNeXTFamily()))
7883 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7884
7885 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7886 Neg: options::OPT_fno_application_extension, Default: false))
7887 CmdArgs.push_back(Elt: "-fapplication-extension");
7888
7889 // Handle GCC-style exception args.
7890 bool EH = false;
7891 if (!C.getDriver().IsCLMode())
7892 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7893 IsDeviceOffloadAction, objcRuntime: Runtime, CmdArgs);
7894
7895 // Handle exception personalities
7896 Arg *A = Args.getLastArg(
7897 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7898 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions,
7899 Ids: options::OPT_femscripten_exceptions);
7900 if (A) {
7901 const Option &Opt = A->getOption();
7902 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7903 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7904 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7905 CmdArgs.push_back(Elt: "-exception-model=seh");
7906 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
7907 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7908 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
7909 CmdArgs.push_back(Elt: "-exception-model=wasm");
7910 if (Opt.matches(ID: options::OPT_femscripten_exceptions))
7911 CmdArgs.push_back(Elt: "-exception-model=emscripten");
7912 } else {
7913 switch (TC.GetExceptionModel(Args)) {
7914 default:
7915 break;
7916 case llvm::ExceptionHandling::DwarfCFI:
7917 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7918 break;
7919 case llvm::ExceptionHandling::SjLj:
7920 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7921 break;
7922 case llvm::ExceptionHandling::WinEH:
7923 CmdArgs.push_back(Elt: "-exception-model=seh");
7924 break;
7925 }
7926 }
7927
7928 // Unwind information version for x64 Windows.
7929 // Forward the new unified flag if present, otherwise translate legacy flags.
7930 if (const Arg *A = Args.getLastArg(Ids: options::OPT_winx64_eh_unwind_EQ)) {
7931 A->claim();
7932 CmdArgs.push_back(
7933 Elt: Args.MakeArgString(Str: Twine("-fwinx64-eh-unwind=") + A->getValue()));
7934 } else if (const Arg *A =
7935 Args.getLastArg(Ids: options::OPT_winx64_eh_unwindv2_EQ)) {
7936 A->claim();
7937 StringRef Val = A->getValue();
7938 if (Val == "best-effort")
7939 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
7940 else if (Val == "required")
7941 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
7942 // "disabled" maps to v1 default, nothing to forward.
7943 else if (Val != "disabled")
7944 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
7945 }
7946
7947 // Control Flow Guard mechanism for Windows.
7948 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_win_cfg_mechanism);
7949
7950 // C++ "sane" operator new.
7951 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7952 Neg: options::OPT_fno_assume_sane_operator_new);
7953
7954 // -fassume-unique-vtables is on by default.
7955 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
7956 Neg: options::OPT_fno_assume_unique_vtables);
7957
7958 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7959 // by default.
7960 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
7961 Ids: options::OPT_fno_sized_deallocation);
7962
7963 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7964 // by default.
7965 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
7966 Ids: options::OPT_fno_aligned_allocation,
7967 Ids: options::OPT_faligned_new_EQ)) {
7968 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
7969 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
7970 else
7971 CmdArgs.push_back(Elt: "-faligned-allocation");
7972 }
7973
7974 // The default new alignment can be specified using a dedicated option or via
7975 // a GCC-compatible option that also turns on aligned allocation.
7976 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
7977 Ids: options::OPT_faligned_new_EQ))
7978 CmdArgs.push_back(
7979 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
7980
7981 // -fconstant-cfstrings is default, and may be subject to argument translation
7982 // on Darwin.
7983 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
7984 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
7985 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
7986 Neg: options::OPT_mno_constant_cfstrings, Default: true))
7987 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
7988
7989 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
7990 Neg: options::OPT_fno_pascal_strings);
7991
7992 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7993 // -fno-pack-struct doesn't apply to -fpack-struct=.
7994 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
7995 CmdArgs.push_back(
7996 Elt: Args.MakeArgString(Str: "-fpack-struct=" + Twine(A->getValue())));
7997 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
7998 Neg: options::OPT_fno_pack_struct, Default: false)) {
7999 CmdArgs.push_back(Elt: "-fpack-struct=1");
8000 }
8001
8002 // Handle -fmax-type-align=N and -fno-type-align
8003 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
8004 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
8005 if (!SkipMaxTypeAlign) {
8006 std::string MaxTypeAlignStr = "-fmax-type-align=";
8007 MaxTypeAlignStr += A->getValue();
8008 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
8009 }
8010 } else if (RawTriple.isOSDarwin()) {
8011 if (!SkipMaxTypeAlign) {
8012 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8013 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
8014 }
8015 }
8016
8017 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
8018 CmdArgs.push_back(Elt: "-Qn");
8019
8020 // -fno-common is the default, set -fcommon only when that flag is set.
8021 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
8022
8023 // -fsigned-bitfields is default, and clang doesn't yet support
8024 // -funsigned-bitfields.
8025 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
8026 Neg: options::OPT_funsigned_bitfields, Default: true))
8027 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
8028 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
8029
8030 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8031 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
8032 D.Diag(DiagID: diag::err_drv_clang_unsupported)
8033 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
8034
8035 // -finput_charset=UTF-8 is default. Reject others
8036 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
8037 StringRef value = inputCharset->getValue();
8038 if (!value.equals_insensitive(RHS: "utf-8"))
8039 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8040 << value;
8041 }
8042
8043 // -fexec_charset=UTF-8 is default. Reject others
8044 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
8045 StringRef value = execCharset->getValue();
8046 if (!value.equals_insensitive(RHS: "utf-8"))
8047 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8048 << value;
8049 }
8050
8051 RenderDiagnosticsOptions(D, Args, CmdArgs);
8052
8053 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
8054 Neg: options::OPT_fno_asm_blocks);
8055
8056 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
8057 Neg: options::OPT_fno_gnu_inline_asm);
8058
8059 handleVectorizeLoopsArgs(Args, CmdArgs);
8060 handleVectorizeSLPArgs(Args, CmdArgs);
8061
8062 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
8063 if (!VecWidth.empty())
8064 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
8065
8066 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
8067 Args.AddLastArg(Output&: CmdArgs,
8068 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
8069
8070 // -fdollars-in-identifiers default varies depending on platform and
8071 // language; only pass if specified.
8072 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
8073 Ids: options::OPT_fno_dollars_in_identifiers)) {
8074 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
8075 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
8076 else
8077 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
8078 }
8079
8080 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
8081 Neg: options::OPT_fno_apple_pragma_pack);
8082
8083 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8084 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8085 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8086
8087 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
8088 Neg: options::OPT_fno_rewrite_imports, Default: false);
8089 if (RewriteImports)
8090 CmdArgs.push_back(Elt: "-frewrite-imports");
8091
8092 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
8093 Neg: options::OPT_fno_directives_only);
8094
8095 // Enable rewrite includes if the user's asked for it or if we're generating
8096 // diagnostics.
8097 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8098 // nice to enable this when doing a crashdump for modules as well.
8099 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
8100 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
8101 (C.isForDiagnostics() && !HaveModules))
8102 CmdArgs.push_back(Elt: "-frewrite-includes");
8103
8104 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
8105 Neg: options::OPT_fno_zos_extensions, Default: false))
8106 CmdArgs.push_back(Elt: "-fzos-extensions");
8107 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
8108 CmdArgs.push_back(Elt: "-fno-zos-extensions");
8109
8110 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8111 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
8112 Ids: options::OPT_traditional_cpp)) {
8113 if (isa<PreprocessJobAction>(Val: JA))
8114 CmdArgs.push_back(Elt: "-traditional-cpp");
8115 else
8116 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
8117 }
8118
8119 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
8120 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
8121 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
8122
8123 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
8124
8125 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_extract_summaries);
8126 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_tu_summary_file);
8127 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_compilation_unit_id);
8128 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_include_local_entities);
8129 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_no_extract_from_system_headers);
8130 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_source_transformation);
8131 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_global_scope_analysis_result);
8132 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_link_unit_id);
8133 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_src_edit_file);
8134 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_transformation_report_file);
8135
8136 // Handle serialized diagnostics.
8137 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
8138 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
8139 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
8140 }
8141
8142 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
8143 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
8144
8145 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
8146 A->render(Args, Output&: CmdArgs);
8147 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
8148 A && A->containsValue(Value: "g")) {
8149 // Set -fextend-variable-liveness=all by default at -Og.
8150 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
8151 }
8152
8153 // Forward -fcomment-block-commands to -cc1.
8154 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
8155 // Forward -fparse-all-comments to -cc1.
8156 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
8157
8158 // Turn -fplugin=name.so into -load name.so
8159 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
8160 CmdArgs.push_back(Elt: "-load");
8161 CmdArgs.push_back(Elt: A->getValue());
8162 A->claim();
8163 }
8164
8165 // Turn -fplugin-arg-pluginname-key=value into
8166 // -plugin-arg-pluginname key=value
8167 // GCC has an actual plugin_argument struct with key/value pairs that it
8168 // passes to its plugins, but we don't, so just pass it on as-is.
8169 //
8170 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8171 // argument key are allowed to contain dashes. GCC therefore only
8172 // allows dashes in the key. We do the same.
8173 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
8174 auto ArgValue = StringRef(A->getValue());
8175 auto FirstDashIndex = ArgValue.find(C: '-');
8176 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
8177 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
8178
8179 A->claim();
8180 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8181 if (PluginName.empty()) {
8182 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8183 } else {
8184 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
8185 << PluginName << A->getAsString(Args);
8186 }
8187 continue;
8188 }
8189
8190 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
8191 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
8192 }
8193
8194 // Forward -fpass-plugin=name.so to -cc1.
8195 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
8196 CmdArgs.push_back(
8197 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
8198 A->claim();
8199 }
8200
8201 // Forward --vfsoverlay to -cc1.
8202 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
8203 CmdArgs.push_back(Elt: "--vfsoverlay");
8204 CmdArgs.push_back(Elt: A->getValue());
8205 A->claim();
8206 }
8207
8208 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
8209 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
8210
8211 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
8212 Neg: options::OPT_fno_experimental_late_parse_attributes);
8213
8214 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
8215 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
8216 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
8217 A->render(Args, Output&: CmdArgs);
8218 else
8219 CmdArgs.push_back(Elt: Args.MakeArgString(
8220 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8221 }
8222
8223 if (Args.hasFlag(
8224 Pos: options::OPT_fexperimental_allow_pointer_field_protection_attr,
8225 Neg: options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8226 Default: false) ||
8227 Args.hasFlag(Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8228 Neg: options::OPT_fno_experimental_pointer_field_protection_abi,
8229 Default: false))
8230 CmdArgs.push_back(Elt: "-fexperimental-allow-pointer-field-protection-attr");
8231
8232 if (!IsCudaDevice) {
8233 Args.addOptInFlag(
8234 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8235 Neg: options::OPT_fno_experimental_pointer_field_protection_abi);
8236 Args.addOptInFlag(
8237 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_tagged,
8238 Neg: options::OPT_fno_experimental_pointer_field_protection_tagged);
8239 }
8240
8241 // Setup statistics file output.
8242 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8243 if (!StatsFile.empty()) {
8244 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
8245 if (D.CCPrintInternalStats)
8246 CmdArgs.push_back(Elt: "-stats-file-append");
8247 }
8248
8249 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8250 // parser.
8251 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
8252 Arg->claim();
8253 // -finclude-default-header flag is for preprocessor,
8254 // do not pass it to other cc1 commands when save-temps is enabled
8255 if (C.getDriver().isSaveTempsEnabled() &&
8256 !isa<PreprocessJobAction>(Val: JA)) {
8257 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8258 continue;
8259 }
8260 CmdArgs.push_back(Elt: Arg->getValue());
8261 }
8262 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
8263 A->claim();
8264
8265 // We translate this by hand to the -cc1 argument, since nightly test uses
8266 // it and developers have been trained to spell it with -mllvm. Both
8267 // spellings are now deprecated and should be removed.
8268 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
8269 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
8270 } else {
8271 A->render(Args, Output&: CmdArgs);
8272 }
8273 }
8274
8275 // This needs to run after -Xclang argument forwarding to pick up the target
8276 // features enabled through -Xclang -target-feature flags.
8277 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8278
8279 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
8280
8281#if CLANG_ENABLE_CIR
8282 // Forward -mmlir arguments to to the MLIR option parser.
8283 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8284 A->claim();
8285 A->render(Args, CmdArgs);
8286 }
8287#endif // CLANG_ENABLE_CIR
8288
8289 // With -save-temps, we want to save the unoptimized bitcode output from the
8290 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8291 // by the frontend.
8292 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8293 // has slightly different breakdown between stages.
8294 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8295 // pristine IR generated by the frontend. Ideally, a new compile action should
8296 // be added so both IR can be captured.
8297 if ((C.getDriver().isSaveTempsEnabled() ||
8298 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
8299 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8300 isa<CompileJobAction>(Val: JA))
8301 CmdArgs.push_back(Elt: "-disable-llvm-passes");
8302
8303 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
8304
8305 const char *Exec = D.getDriverProgramPath();
8306
8307 // Optionally embed the -cc1 level arguments into the debug info or a
8308 // section, for build analysis.
8309 // Also record command line arguments into the debug info if
8310 // -grecord-gcc-switches options is set on.
8311 // By default, -gno-record-gcc-switches is set on and no recording.
8312 auto GRecordSwitches = false;
8313 auto FRecordSwitches = false;
8314 bool DXRecordSwitches = false;
8315 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches,
8316 DXRecordCommandLine&: DXRecordSwitches)) {
8317 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8318 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8319 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8320 CmdArgs.push_back(Elt: FlagsArgString);
8321 }
8322 if (FRecordSwitches) {
8323 CmdArgs.push_back(Elt: "-record-command-line");
8324 CmdArgs.push_back(Elt: FlagsArgString);
8325 }
8326 if (DXRecordSwitches) {
8327 CmdArgs.push_back(Elt: "-fdx-record-command-line");
8328 CmdArgs.push_back(Elt: FlagsArgString);
8329 }
8330 }
8331
8332 // Host-side offloading compilation receives all device-side outputs. Include
8333 // them in the host compilation depending on the target.
8334 if (!HostOffloadingInputs.empty()) {
8335 bool UseOffloadIncludeBinary =
8336 (IsCuda || IsHIP) &&
8337 (!IsRDCMode || Args.hasArg(Ids: options::OPT_cuda_emit_nvcc_abi)) &&
8338 !UsesLLVMOffloading;
8339 UseOffloadIncludeBinary |= IsSYCL && !IsRDCMode;
8340 if (UseOffloadIncludeBinary) {
8341 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8342 CmdArgs.push_back(Elt: "-foffload-include-binary");
8343 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
8344 } else {
8345 for (const InputInfo Input : HostOffloadingInputs)
8346 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
8347 TC.getInputFilename(Input)));
8348 }
8349 }
8350
8351 if (IsCuda) {
8352 if (Args.hasArg(Ids: options::OPT_cuda_emit_nvcc_abi))
8353 CmdArgs.push_back(Elt: "--cuda-emit-nvcc-abi");
8354 }
8355
8356 if (IsCuda || IsHIP) {
8357 // Determine the original source input.
8358 const Action *SourceAction = &JA;
8359 while (SourceAction->getKind() != Action::InputClass) {
8360 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8361 SourceAction = SourceAction->getInputs()[0];
8362 }
8363 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
8364 if (!CUID.empty())
8365 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
8366
8367 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8368 // be overriden by -fno-gpu-approx-transcendentals.
8369 bool UseApproxTranscendentals = Args.hasFlag(
8370 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
8371 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
8372 Neg: options::OPT_fno_gpu_approx_transcendentals,
8373 Default: UseApproxTranscendentals))
8374 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
8375 } else {
8376 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
8377 Ids: options::OPT_fno_gpu_approx_transcendentals);
8378 }
8379
8380 if (IsHIP) {
8381 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
8382 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
8383 }
8384
8385 Args.AddAllArgs(Output&: CmdArgs,
8386 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8387
8388 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
8389 Ids: options::OPT_fno_offload_uniform_block);
8390
8391 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
8392 Ids: options::OPT_fno_offload_implicit_host_device_templates);
8393
8394 if (IsCudaDevice || IsHIPDevice) {
8395 StringRef InlineThresh =
8396 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
8397 if (!InlineThresh.empty()) {
8398 std::string ArgStr =
8399 std::string("-inline-threshold=") + InlineThresh.str();
8400 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
8401 }
8402 }
8403
8404 if (IsHIPDevice)
8405 Args.addOptOutFlag(Output&: CmdArgs,
8406 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8407 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8408
8409 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8410 // to specify the result of the compile phase on the host, so the meaningful
8411 // device declarations can be identified. Also, -fopenmp-is-target-device is
8412 // passed along to tell the frontend that it is generating code for a device,
8413 // so that only the relevant declarations are emitted.
8414 if (IsOpenMPDevice) {
8415 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
8416 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8417 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
8418 CmdArgs.push_back(Elt: "-fcuda-is-device");
8419
8420 if (OpenMPDeviceInput) {
8421 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
8422 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
8423 }
8424 }
8425
8426 if (Triple.isAMDGPU() ||
8427 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8428 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8429
8430 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
8431 Neg: options::OPT_mno_unsafe_fp_atomics);
8432 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
8433 Neg: options::OPT_mno_amdgpu_ieee);
8434 }
8435
8436 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8437
8438 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
8439 Neg: options::OPT_fno_devirtualize_speculatively,
8440 /*Default value*/ Default: false))
8441 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
8442
8443 bool VirtualFunctionElimination =
8444 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
8445 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
8446 if (VirtualFunctionElimination) {
8447 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8448 // in the future).
8449 if (LTOMode != LTOK_Full)
8450 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8451 << "-fvirtual-function-elimination"
8452 << "-flto=full";
8453
8454 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
8455 }
8456
8457 // VFE requires whole-program-vtables, and enables it by default.
8458 bool WholeProgramVTables = Args.hasFlag(
8459 Pos: options::OPT_fwhole_program_vtables,
8460 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
8461 if (VirtualFunctionElimination && !WholeProgramVTables) {
8462 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8463 << "-fno-whole-program-vtables"
8464 << "-fvirtual-function-elimination";
8465 }
8466
8467 if (WholeProgramVTables) {
8468 // PS4 uses the legacy LTO API, which does not support this feature in
8469 // ThinLTO mode.
8470 bool IsPS4 = getToolChain().getTriple().isPS4();
8471
8472 // Check if we passed LTO options but they were suppressed because this is a
8473 // device offloading action, or we passed device offload LTO options which
8474 // were suppressed because this is not the device offload action.
8475 // Check if we are using PS4 in regular LTO mode.
8476 // Otherwise, issue an error.
8477
8478 auto OtherLTOMode = TC.getLTOMode(
8479 Args, Kind: IsDeviceOffloadAction ? Action::OFK_None
8480 : static_cast<Action::OffloadKind>(
8481 C.getActiveOffloadKinds()));
8482 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8483
8484 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8485 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8486 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8487 << "-fwhole-program-vtables"
8488 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8489
8490 // Propagate -fwhole-program-vtables if this is an LTO compile.
8491 if (IsUsingLTO)
8492 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
8493 }
8494
8495 bool DefaultsSplitLTOUnit =
8496 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8497 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8498 (!Triple.isPS4() && UnifiedLTO);
8499 bool SplitLTOUnit =
8500 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
8501 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
8502 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8503 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8504 << "-fsanitize=cfi";
8505 if (SplitLTOUnit)
8506 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
8507
8508 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
8509 Ids: options::OPT_fno_fat_lto_objects)) {
8510 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
8511 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8512 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8513 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8514 << A->getAsString(Args) << TC.getTripleString();
8515 }
8516 CmdArgs.push_back(Elt: Args.MakeArgString(
8517 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8518 CmdArgs.push_back(Elt: "-flto-unit");
8519 CmdArgs.push_back(Elt: "-ffat-lto-objects");
8520 A->render(Args, Output&: CmdArgs);
8521 }
8522 }
8523
8524 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8525
8526 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8527 Ids: options::OPT_fno_force_enable_int128)) {
8528 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8529 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8530 }
8531
8532 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8533 Neg: options::OPT_fno_keep_static_consts);
8534 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8535 Neg: options::OPT_fno_keep_persistent_storage_variables);
8536 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_inline_functions,
8537 Neg: options::OPT_fno_keep_inline_functions);
8538 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8539 Neg: options::OPT_fno_complete_member_pointers);
8540 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8541 A->render(Args, Output&: CmdArgs);
8542
8543 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8544
8545 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8546
8547 if (Triple.isAArch64() &&
8548 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8549 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8550 // Disable Function Multiversioning on AArch64 target.
8551 CmdArgs.push_back(Elt: "-target-feature");
8552 CmdArgs.push_back(Elt: "-fmv");
8553 }
8554
8555 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8556 Default: (TC.getTriple().isOSBinFormatELF() ||
8557 TC.getTriple().isOSBinFormatCOFF()) &&
8558 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8559 !TC.getTriple().isOSNetBSD() &&
8560 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8561 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8562 CmdArgs.push_back(Elt: "-faddrsig");
8563
8564 const bool HasDefaultDwarf2CFIASM =
8565 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8566 (EH || UnwindTables || AsyncUnwindTables ||
8567 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8568 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8569 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8570 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8571
8572 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8573 std::string Str = A->getAsString(Args);
8574 if (!TC.getTriple().isOSBinFormatELF())
8575 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8576 << Str << TC.getTripleString();
8577 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8578 }
8579
8580 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8581 // the -cc1 command easier to edit when reproducing compiler crashes.
8582 if (Output.getType() == types::TY_Dependencies) {
8583 // Handled with other dependency code.
8584 } else if (Output.isFilename()) {
8585 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8586 Output.getType() == clang::driver::types::TY_IFS) {
8587 SmallString<128> OutputFilename(Output.getFilename());
8588 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8589 CmdArgs.push_back(Elt: "-o");
8590 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8591 } else {
8592 CmdArgs.push_back(Elt: "-o");
8593 CmdArgs.push_back(Elt: Output.getFilename());
8594 }
8595 } else {
8596 assert(Output.isNothing() && "Invalid output.");
8597 }
8598
8599 addDashXForInput(Args, Input, CmdArgs);
8600
8601 ArrayRef<InputInfo> FrontendInputs = Input;
8602 if (IsExtractAPI)
8603 FrontendInputs = ExtractAPIInputs;
8604 else if (Input.isNothing())
8605 FrontendInputs = {};
8606
8607 for (const InputInfo &Input : FrontendInputs) {
8608 if (Input.isFilename())
8609 CmdArgs.push_back(Elt: Input.getFilename());
8610 else
8611 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8612 }
8613
8614 if (D.CC1Main && !D.CCGenDiagnostics) {
8615 // Invoke the CC1 directly in this process
8616 C.addCommand(Cmd: std::make_unique<CC1Command>(
8617 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8618 args: Output, args: D.getPrependArg()));
8619 } else {
8620 C.addCommand(Cmd: std::make_unique<Command>(
8621 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8622 args: Output, args: D.getPrependArg()));
8623 }
8624
8625 // Make the compile command echo its inputs for /showFilenames.
8626 if (Output.getType() == types::TY_Object &&
8627 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8628 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8629 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8630 }
8631
8632 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8633 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8634 !Args.hasArg(Ids: options::OPT_mfentry))
8635 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8636 << A->getAsString(Args);
8637
8638 // Claim some arguments which clang supports automatically.
8639
8640 // -fpch-preprocess is used with gcc to add a special marker in the output to
8641 // include the PCH file.
8642 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8643
8644 // Claim some arguments which clang doesn't support, but we don't
8645 // care to warn the user about.
8646 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8647 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8648
8649 // Disable warnings for clang -E -emit-llvm foo.c
8650 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8651}
8652
8653Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8654 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8655 // as it is for other tools. Some operations on a Tool actually test
8656 // whether that tool is Clang based on the Tool's Name as a string.
8657 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8658
8659Clang::~Clang() {}
8660
8661/// Add options related to the Objective-C runtime/ABI.
8662///
8663/// Returns true if the runtime is non-fragile.
8664ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8665 const InputInfoList &inputs,
8666 ArgStringList &cmdArgs,
8667 RewriteKind rewriteKind) const {
8668 // Look for the controlling runtime option.
8669 Arg *runtimeArg =
8670 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8671 Ids: options::OPT_fobjc_runtime_EQ);
8672
8673 // Just forward -fobjc-runtime= to the frontend. This supercedes
8674 // options about fragility.
8675 if (runtimeArg &&
8676 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8677 ObjCRuntime runtime;
8678 StringRef value = runtimeArg->getValue();
8679 if (runtime.tryParse(input: value)) {
8680 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8681 << value;
8682 }
8683 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8684 (runtime.getVersion() >= VersionTuple(2, 0)))
8685 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8686 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8687 !getToolChain().getTriple().isOSBinFormatWasm()) {
8688 getToolChain().getDriver().Diag(
8689 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8690 << runtime.getVersion().getMajor();
8691 }
8692
8693 runtimeArg->render(Args: args, Output&: cmdArgs);
8694 return runtime;
8695 }
8696
8697 // Otherwise, we'll need the ABI "version". Version numbers are
8698 // slightly confusing for historical reasons:
8699 // 1 - Traditional "fragile" ABI
8700 // 2 - Non-fragile ABI, version 1
8701 // 3 - Non-fragile ABI, version 2
8702 unsigned objcABIVersion = 1;
8703 // If -fobjc-abi-version= is present, use that to set the version.
8704 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8705 StringRef value = abiArg->getValue();
8706 if (value == "1")
8707 objcABIVersion = 1;
8708 else if (value == "2")
8709 objcABIVersion = 2;
8710 else if (value == "3")
8711 objcABIVersion = 3;
8712 else
8713 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8714 } else {
8715 // Otherwise, determine if we are using the non-fragile ABI.
8716 bool nonFragileABIIsDefault =
8717 (rewriteKind == RK_NonFragile ||
8718 (rewriteKind == RK_None &&
8719 getToolChain().IsObjCNonFragileABIDefault()));
8720 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8721 Neg: options::OPT_fno_objc_nonfragile_abi,
8722 Default: nonFragileABIIsDefault)) {
8723// Determine the non-fragile ABI version to use.
8724#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8725 unsigned nonFragileABIVersion = 1;
8726#else
8727 unsigned nonFragileABIVersion = 2;
8728#endif
8729
8730 if (Arg *abiArg =
8731 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8732 StringRef value = abiArg->getValue();
8733 if (value == "1")
8734 nonFragileABIVersion = 1;
8735 else if (value == "2")
8736 nonFragileABIVersion = 2;
8737 else
8738 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8739 << value;
8740 }
8741
8742 objcABIVersion = 1 + nonFragileABIVersion;
8743 } else {
8744 objcABIVersion = 1;
8745 }
8746 }
8747
8748 // We don't actually care about the ABI version other than whether
8749 // it's non-fragile.
8750 bool isNonFragile = objcABIVersion != 1;
8751
8752 // If we have no runtime argument, ask the toolchain for its default runtime.
8753 // However, the rewriter only really supports the Mac runtime, so assume that.
8754 ObjCRuntime runtime;
8755 if (!runtimeArg) {
8756 switch (rewriteKind) {
8757 case RK_None:
8758 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8759 break;
8760 case RK_Fragile:
8761 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8762 break;
8763 case RK_NonFragile:
8764 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8765 break;
8766 }
8767
8768 // -fnext-runtime
8769 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8770 // On Darwin, make this use the default behavior for the toolchain.
8771 if (getToolChain().getTriple().isOSDarwin()) {
8772 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8773
8774 // Otherwise, build for a generic macosx port.
8775 } else {
8776 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8777 }
8778
8779 // -fgnu-runtime
8780 } else {
8781 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8782 // Legacy behaviour is to target the gnustep runtime if we are in
8783 // non-fragile mode or the GCC runtime in fragile mode.
8784 if (isNonFragile)
8785 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8786 else
8787 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8788 }
8789
8790 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8791 return types::isObjC(Id: input.getType());
8792 }))
8793 cmdArgs.push_back(
8794 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8795 return runtime;
8796}
8797
8798static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8799 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8800 I += HaveDash;
8801 return !HaveDash;
8802}
8803
8804namespace {
8805struct EHFlags {
8806 bool Synch = false;
8807 bool Asynch = false;
8808 bool NoUnwindC = false;
8809};
8810} // end anonymous namespace
8811
8812/// /EH controls whether to run destructor cleanups when exceptions are
8813/// thrown. There are three modifiers:
8814/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8815/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8816/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8817/// - c: Assume that extern "C" functions are implicitly nounwind.
8818/// The default is /EHs-c-, meaning cleanups are disabled.
8819static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8820 bool isWindowsMSVC) {
8821 EHFlags EH;
8822
8823 std::vector<std::string> EHArgs =
8824 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8825 for (const auto &EHVal : EHArgs) {
8826 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8827 switch (EHVal[I]) {
8828 case 'a':
8829 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8830 if (EH.Asynch) {
8831 // Async exceptions are Windows MSVC only.
8832 if (!isWindowsMSVC) {
8833 EH.Asynch = false;
8834 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8835 continue;
8836 }
8837 EH.Synch = false;
8838 }
8839 continue;
8840 case 'c':
8841 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8842 continue;
8843 case 's':
8844 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8845 if (EH.Synch)
8846 EH.Asynch = false;
8847 continue;
8848 default:
8849 break;
8850 }
8851 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8852 break;
8853 }
8854 }
8855 // The /GX, /GX- flags are only processed if there are not /EH flags.
8856 // The default is that /GX is not specified.
8857 if (EHArgs.empty() &&
8858 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8859 /*Default=*/false)) {
8860 EH.Synch = true;
8861 EH.NoUnwindC = true;
8862 }
8863
8864 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8865 EH.Synch = false;
8866 EH.NoUnwindC = false;
8867 EH.Asynch = false;
8868 }
8869
8870 return EH;
8871}
8872
8873void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8874 ArgStringList &CmdArgs) const {
8875 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8876
8877 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8878
8879 if (Arg *ShowIncludes =
8880 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8881 Ids: options::OPT__SLASH_showIncludes_user)) {
8882 CmdArgs.push_back(Elt: "--show-includes");
8883 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8884 CmdArgs.push_back(Elt: "-sys-header-deps");
8885 }
8886
8887 // This controls whether or not we emit RTTI data for polymorphic types.
8888 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8889 /*Default=*/false))
8890 CmdArgs.push_back(Elt: "-fno-rtti-data");
8891
8892 // This controls whether or not we emit stack-protector instrumentation.
8893 // In MSVC, Buffer Security Check (/GS) is on by default.
8894 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8895 /*Default=*/true)) {
8896 CmdArgs.push_back(Elt: "-stack-protector");
8897 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8898 }
8899
8900 const Driver &D = getToolChain().getDriver();
8901
8902 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8903 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8904 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8905 if (types::isCXX(Id: InputType))
8906 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8907 CmdArgs.push_back(Elt: "-fexceptions");
8908 if (EH.Asynch)
8909 CmdArgs.push_back(Elt: "-fasync-exceptions");
8910 }
8911 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8912 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8913
8914 // /EP should expand to -E -P.
8915 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
8916 CmdArgs.push_back(Elt: "-E");
8917 CmdArgs.push_back(Elt: "-P");
8918 }
8919
8920 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
8921 Neg: options::OPT__SLASH_Zc_dllexportInlines,
8922 Default: false)) {
8923 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8924 }
8925
8926 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
8927 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
8928 CmdArgs.push_back(Elt: "-fno-wchar");
8929 }
8930
8931 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8932 llvm::Triple::ArchType Arch = getToolChain().getArch();
8933 std::vector<std::string> Values =
8934 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
8935 if (!Values.empty()) {
8936 llvm::SmallSet<std::string, 4> SupportedArches;
8937 if (Arch == llvm::Triple::x86)
8938 SupportedArches.insert(V: "IA32");
8939
8940 for (auto &V : Values)
8941 if (!SupportedArches.contains(V))
8942 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8943 << std::string("/arch:").append(str: V) << "/kernel";
8944 }
8945
8946 CmdArgs.push_back(Elt: "-fno-rtti");
8947 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
8948 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
8949 << "/kernel";
8950 }
8951
8952 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
8953 Ids: options::OPT__SLASH_vlen_EQ_256,
8954 Ids: options::OPT__SLASH_vlen_EQ_512)) {
8955 llvm::Triple::ArchType AT = getToolChain().getArch();
8956 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8957 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
8958 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8959 "AVX10.2"};
8960
8961 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
8962 if (Arch512.contains(V: Arch))
8963 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
8964 else
8965 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8966 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
8967 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
8968 if (Arch512.contains(V: Arch))
8969 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8970 else if (Arch != "AVX" && Arch != "AVX2")
8971 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8972 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
8973 } else {
8974 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8975 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8976 }
8977 } else {
8978 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
8979 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8980 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8981 CmdArgs.push_back(Elt: "-target-feature");
8982 CmdArgs.push_back(Elt: "-amx-tile");
8983 }
8984 if (Arch == "AVX10.2") {
8985 CmdArgs.push_back(Elt: "-target-feature");
8986 CmdArgs.push_back(Elt: "+avx10.2");
8987 }
8988 }
8989
8990 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
8991 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
8992 if (MostGeneralArg && BestCaseArg)
8993 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8994 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8995
8996 if (MostGeneralArg) {
8997 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
8998 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
8999 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
9000
9001 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9002 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9003 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9004 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
9005 << FirstConflict->getAsString(Args)
9006 << SecondConflict->getAsString(Args);
9007
9008 if (SingleArg)
9009 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
9010 else if (MultipleArg)
9011 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
9012 else
9013 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
9014 }
9015
9016 if (Args.hasArg(Ids: options::OPT_regcall4))
9017 CmdArgs.push_back(Elt: "-regcall4");
9018
9019 // Parse the default calling convention options.
9020 if (Arg *CCArg =
9021 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
9022 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
9023 Ids: options::OPT__SLASH_Gregcall)) {
9024 unsigned DCCOptId = CCArg->getOption().getID();
9025 const char *DCCFlag = nullptr;
9026 bool ArchSupported = !isNVPTX;
9027 llvm::Triple::ArchType Arch = getToolChain().getArch();
9028 switch (DCCOptId) {
9029 case options::OPT__SLASH_Gd:
9030 DCCFlag = "-fdefault-calling-conv=cdecl";
9031 break;
9032 case options::OPT__SLASH_Gr:
9033 ArchSupported = Arch == llvm::Triple::x86;
9034 DCCFlag = "-fdefault-calling-conv=fastcall";
9035 break;
9036 case options::OPT__SLASH_Gz:
9037 ArchSupported = Arch == llvm::Triple::x86;
9038 DCCFlag = "-fdefault-calling-conv=stdcall";
9039 break;
9040 case options::OPT__SLASH_Gv:
9041 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9042 DCCFlag = "-fdefault-calling-conv=vectorcall";
9043 break;
9044 case options::OPT__SLASH_Gregcall:
9045 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9046 DCCFlag = "-fdefault-calling-conv=regcall";
9047 break;
9048 }
9049
9050 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9051 if (ArchSupported && DCCFlag)
9052 CmdArgs.push_back(Elt: DCCFlag);
9053 }
9054
9055 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
9056 CmdArgs.push_back(Elt: "-regcall4");
9057
9058 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
9059
9060 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
9061 CmdArgs.push_back(Elt: "-fdiagnostics-format");
9062 CmdArgs.push_back(Elt: "msvc");
9063 }
9064
9065 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
9066 CmdArgs.push_back(Elt: "-fms-kernel");
9067
9068 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9069 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9070 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
9071 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
9072 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
9073 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
9074
9075 // Handle the various /guard options. We don't immediately push back clang
9076 // args since there are /d2 args that can modify the behavior of /guard:cf.
9077 bool HasCFGuard = false;
9078 bool HasCFGuardNoChecks = false;
9079 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
9080 StringRef GuardArgs = A->getValue();
9081 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9082 // "ehcont-".
9083 if (GuardArgs.equals_insensitive(RHS: "cf")) {
9084 // Emit CFG instrumentation and the table of address-taken functions.
9085 HasCFGuard = true;
9086 HasCFGuardNoChecks = false;
9087 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
9088 // Emit only the table of address-taken functions.
9089 HasCFGuard = false;
9090 HasCFGuardNoChecks = true;
9091 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
9092 // Emit EH continuation table.
9093 CmdArgs.push_back(Elt: "-ehcontguard");
9094 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
9095 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
9096 // Do nothing, but we might want to emit a security warning in future.
9097 } else {
9098 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9099 }
9100 A->claim();
9101 }
9102
9103 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9104 // If CFG is not enabled, it is a no-op.
9105 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardnochecks)) {
9106 if (HasCFGuard) {
9107 HasCFGuard = false;
9108 HasCFGuardNoChecks = true;
9109 }
9110 }
9111
9112 if (HasCFGuard)
9113 CmdArgs.push_back(Elt: "-cfguard");
9114 else if (HasCFGuardNoChecks)
9115 CmdArgs.push_back(Elt: "-cfguard-no-checks");
9116
9117 // Control Flow Guard mechanism for Windows.
9118 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch_))
9119 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=check");
9120 else if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch))
9121 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=dispatch");
9122
9123 for (const auto &FuncOverride :
9124 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
9125 CmdArgs.push_back(Elt: Args.MakeArgString(
9126 Str: Twine("-loader-replaceable-function=") + FuncOverride));
9127 }
9128
9129 if (Args.hasArg(Ids: options::OPT__SLASH_experimental_deterministic)) {
9130 CmdArgs.push_back(Elt: "-Wdate-time");
9131
9132 if (Args.hasArg(Ids: options::OPT_mincremental_linker_compatible)) {
9133 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
9134 << "/experimental:deterministic"
9135 << "/Brepro-";
9136 }
9137 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9138 // deterministic result, but we force this timestamp to 0, which also
9139 // produces deterministic result.
9140 CmdArgs.push_back(Elt: "-mno-incremental-linker-compatible");
9141 }
9142
9143 bool HasNoDateTime = Args.hasFlag(Pos: options::OPT__SLASH_d1nodatetime,
9144 Neg: options::OPT__SLASH_d1nodatetime_, Default: false);
9145
9146 if (HasNoDateTime)
9147 CmdArgs.push_back(Elt: "-init-datetime-macros=undefined");
9148
9149 // /Brepro is an alias for -mincremental-linker-compatible option.
9150 if (!Args.hasFlag(Pos: options::OPT_mincremental_linker_compatible,
9151 Neg: options::OPT_mno_incremental_linker_compatible,
9152 Default: getToolChain()
9153 .getTriple()
9154 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9155 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9156 // This option does not allow the user redefinitions for these macros.
9157 if (!HasNoDateTime)
9158 CmdArgs.push_back(Elt: "-init-datetime-macros=literalone");
9159 }
9160}
9161
9162const char *Clang::getBaseInputName(const ArgList &Args,
9163 const InputInfo &Input) {
9164 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
9165}
9166
9167const char *Clang::getBaseInputStem(const ArgList &Args,
9168 const InputInfoList &Inputs) {
9169 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
9170
9171 if (const char *End = strrchr(s: Str, c: '.'))
9172 return Args.MakeArgString(Str: std::string(Str, End));
9173
9174 return Str;
9175}
9176
9177const char *Clang::getDependencyFileName(const ArgList &Args,
9178 const InputInfoList &Inputs) {
9179 // FIXME: Think about this more.
9180
9181 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
9182 SmallString<128> OutputFilename(OutputOpt->getValue());
9183 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
9184 return Args.MakeArgString(Str: OutputFilename);
9185 }
9186
9187 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
9188}
9189
9190// Begin ClangAs
9191
9192void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9193 ArgStringList &CmdArgs) const {
9194 StringRef CPUName;
9195 StringRef ABIName;
9196 const llvm::Triple &Triple = getToolChain().getTriple();
9197 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9198
9199 CmdArgs.push_back(Elt: "-target-abi");
9200 CmdArgs.push_back(Elt: ABIName.data());
9201}
9202
9203void ClangAs::AddX86TargetArgs(const ArgList &Args,
9204 ArgStringList &CmdArgs) const {
9205 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
9206 /*IsLTO=*/false);
9207
9208 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
9209 StringRef Value = A->getValue();
9210 if (Value == "intel" || Value == "att") {
9211 CmdArgs.push_back(Elt: "-mllvm");
9212 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
9213 } else {
9214 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
9215 << A->getSpelling() << Value;
9216 }
9217 }
9218}
9219
9220void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9221 ArgStringList &CmdArgs) const {
9222 CmdArgs.push_back(Elt: "-target-abi");
9223 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
9224 Triple: getToolChain().getTriple())
9225 .data());
9226}
9227
9228void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9229 ArgStringList &CmdArgs) const {
9230 const llvm::Triple &Triple = getToolChain().getTriple();
9231 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9232
9233 CmdArgs.push_back(Elt: "-target-abi");
9234 CmdArgs.push_back(Elt: ABIName.data());
9235
9236 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9237 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9238 CmdArgs.push_back(Elt: "-mllvm");
9239 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
9240 }
9241}
9242
9243void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
9244 const InputInfo &Output, const InputInfoList &Inputs,
9245 const ArgList &Args,
9246 const char *LinkingOutput) const {
9247 ArgStringList CmdArgs;
9248
9249 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9250 const InputInfo &Input = Inputs[0];
9251
9252 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9253 const std::string &TripleStr = Triple.getTriple();
9254 const auto &D = getToolChain().getDriver();
9255
9256 // Don't warn about "clang -w -c foo.s"
9257 Args.ClaimAllArgs(Id0: options::OPT_w);
9258 // and "clang -emit-llvm -c foo.s"
9259 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
9260
9261 claimNoWarnArgs(Args);
9262
9263 // Invoke ourselves in -cc1as mode.
9264 //
9265 // FIXME: Implement custom jobs for internal actions.
9266 CmdArgs.push_back(Elt: "-cc1as");
9267
9268 // Add the "effective" target triple.
9269 CmdArgs.push_back(Elt: "-triple");
9270 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
9271
9272 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
9273
9274 // Set the output mode, we currently only expect to be used as a real
9275 // assembler.
9276 CmdArgs.push_back(Elt: "-filetype");
9277 CmdArgs.push_back(Elt: "obj");
9278
9279 // Set the main file name, so that debug info works even with
9280 // -save-temps or preprocessed assembly.
9281 CmdArgs.push_back(Elt: "-main-file-name");
9282 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
9283
9284 // Add the target cpu
9285 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
9286 if (!CPU.empty()) {
9287 CmdArgs.push_back(Elt: "-target-cpu");
9288 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
9289 }
9290
9291 // Add the target features
9292 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
9293
9294 // Ignore explicit -force_cpusubtype_ALL option.
9295 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
9296
9297 // Pass along any -I options so we get proper .include search paths.
9298 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
9299
9300 // Pass along any --embed-dir or similar options so we get proper embed paths.
9301 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
9302
9303 // Determine the original source input.
9304 auto FindSource = [](const Action *S) -> const Action * {
9305 while (S->getKind() != Action::InputClass) {
9306 assert(!S->getInputs().empty() && "unexpected root action!");
9307 S = S->getInputs()[0];
9308 }
9309 return S;
9310 };
9311 const Action *SourceAction = FindSource(&JA);
9312
9313 // Forward -g and handle debug info related flags, assuming we are dealing
9314 // with an actual assembly file.
9315 bool WantDebug = false;
9316 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
9317 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
9318 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
9319 !A->getOption().matches(ID: options::OPT_ggdb0);
9320
9321 // If a -gdwarf argument appeared, remember it.
9322 bool EmitDwarf = false;
9323 if (const Arg *A = getDwarfNArg(Args))
9324 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9325
9326 bool EmitCodeView = false;
9327 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
9328 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9329
9330 // If the user asked for debug info but did not explicitly specify -gcodeview
9331 // or -gdwarf, ask the toolchain for the default format.
9332 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9333 switch (getToolChain().getDefaultDebugFormat()) {
9334 case llvm::codegenoptions::DIF_CodeView:
9335 EmitCodeView = true;
9336 break;
9337 case llvm::codegenoptions::DIF_DWARF:
9338 EmitDwarf = true;
9339 break;
9340 }
9341 }
9342
9343 // If the arguments don't imply DWARF, don't emit any debug info here.
9344 if (!EmitDwarf)
9345 WantDebug = false;
9346
9347 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9348 llvm::codegenoptions::NoDebugInfo;
9349
9350 // Add the -fdebug-compilation-dir flag if needed.
9351 const char *DebugCompilationDir =
9352 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
9353
9354 if (SourceAction->getType() == types::TY_Asm ||
9355 SourceAction->getType() == types::TY_PP_Asm) {
9356 // You might think that it would be ok to set DebugInfoKind outside of
9357 // the guard for source type, however there is a test which asserts
9358 // that some assembler invocation receives no -debug-info-kind,
9359 // and it's not clear whether that test is just overly restrictive.
9360 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9361 : llvm::codegenoptions::NoDebugInfo);
9362
9363 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
9364 CmdArgs);
9365
9366 // Set the AT_producer to the clang version when using the integrated
9367 // assembler on assembly source files.
9368 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
9369 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
9370
9371 // And pass along -I options
9372 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
9373 }
9374 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
9375 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9376 DebuggerTuning: llvm::DebuggerKind::Default);
9377 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
9378 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
9379
9380 // Handle -fPIC et al -- the relocation-model affects the assembler
9381 // for some targets.
9382 llvm::Reloc::Model RelocationModel;
9383 unsigned PICLevel;
9384 bool IsPIE;
9385 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
9386 ParsePICArgs(ToolChain: getToolChain(), Args);
9387
9388 const char *RMName = RelocationModelName(Model: RelocationModel);
9389 if (RMName) {
9390 CmdArgs.push_back(Elt: "-mrelocation-model");
9391 CmdArgs.push_back(Elt: RMName);
9392 }
9393
9394 // Optionally embed the -cc1as level arguments into the debug info, for build
9395 // analysis.
9396 if (getToolChain().UseDwarfDebugFlags()) {
9397 ArgStringList OriginalArgs;
9398 for (const auto &Arg : Args)
9399 Arg->render(Args, Output&: OriginalArgs);
9400
9401 SmallString<256> Flags;
9402 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9403 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
9404 for (const char *OriginalArg : OriginalArgs) {
9405 SmallString<128> EscapedArg;
9406 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
9407 Flags += " ";
9408 Flags += EscapedArg;
9409 }
9410 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
9411 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
9412 }
9413
9414 // FIXME: Add -static support, once we have it.
9415
9416 // Add target specific flags.
9417 switch (getToolChain().getArch()) {
9418 default:
9419 break;
9420
9421 case llvm::Triple::mips:
9422 case llvm::Triple::mipsel:
9423 case llvm::Triple::mips64:
9424 case llvm::Triple::mips64el:
9425 AddMIPSTargetArgs(Args, CmdArgs);
9426 break;
9427
9428 case llvm::Triple::x86:
9429 case llvm::Triple::x86_64:
9430 AddX86TargetArgs(Args, CmdArgs);
9431 break;
9432
9433 case llvm::Triple::arm:
9434 case llvm::Triple::armeb:
9435 case llvm::Triple::thumb:
9436 case llvm::Triple::thumbeb:
9437 // This isn't in AddARMTargetArgs because we want to do this for assembly
9438 // only, not C/C++.
9439 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9440 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9441 CmdArgs.push_back(Elt: "-mllvm");
9442 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
9443 }
9444 break;
9445
9446 case llvm::Triple::aarch64:
9447 case llvm::Triple::aarch64_32:
9448 case llvm::Triple::aarch64_be:
9449 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
9450 CmdArgs.push_back(Elt: "-mllvm");
9451 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
9452 }
9453 break;
9454
9455 case llvm::Triple::loongarch32:
9456 case llvm::Triple::loongarch64:
9457 AddLoongArchTargetArgs(Args, CmdArgs);
9458 break;
9459
9460 case llvm::Triple::riscv32:
9461 case llvm::Triple::riscv64:
9462 case llvm::Triple::riscv32be:
9463 case llvm::Triple::riscv64be:
9464 AddRISCVTargetArgs(Args, CmdArgs);
9465 break;
9466
9467 case llvm::Triple::hexagon:
9468 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9469 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9470 CmdArgs.push_back(Elt: "-mllvm");
9471 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
9472 }
9473 break;
9474 }
9475
9476 // Consume all the warning flags. Usually this would be handled more
9477 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9478 // doesn't handle that so rather than warning about unused flags that are
9479 // actually used, we'll lie by omission instead.
9480 // FIXME: Stop lying and consume only the appropriate driver flags
9481 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
9482
9483 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9484 D: getToolChain().getDriver());
9485
9486 // Forward -Xclangas arguments to -cc1as
9487 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
9488 Arg->claim();
9489 CmdArgs.push_back(Elt: Arg->getValue());
9490 }
9491
9492 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
9493
9494 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9495 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9496 OutputFileName: Output.getFilename());
9497
9498 // Fixup any previous commands that use -object-file-name because when we
9499 // generated them, the final .obj name wasn't yet known.
9500 for (Command &J : C.getJobs()) {
9501 if (SourceAction != FindSource(&J.getSource()))
9502 continue;
9503 auto &JArgs = J.getArguments();
9504 for (unsigned I = 0; I < JArgs.size(); ++I) {
9505 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
9506 Output.isFilename()) {
9507 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9508 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
9509 OutputFileName: Output.getFilename());
9510 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
9511 J.replaceArguments(List: NewArgs);
9512 break;
9513 }
9514 }
9515 }
9516
9517 assert(Output.isFilename() && "Unexpected lipo output.");
9518 CmdArgs.push_back(Elt: "-o");
9519 CmdArgs.push_back(Elt: Output.getFilename());
9520
9521 const llvm::Triple &T = getToolChain().getTriple();
9522 Arg *A;
9523 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
9524 T.isOSBinFormatELF()) {
9525 CmdArgs.push_back(Elt: "-split-dwarf-output");
9526 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
9527 }
9528
9529 if (Triple.isAMDGPU())
9530 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9531
9532 assert(Input.isFilename() && "Invalid input.");
9533 CmdArgs.push_back(Elt: Input.getFilename());
9534
9535 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9536 if (D.CC1Main && !D.CCGenDiagnostics) {
9537 // Invoke cc1as directly in this process.
9538 C.addCommand(Cmd: std::make_unique<CC1Command>(
9539 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9540 args: Output, args: D.getPrependArg()));
9541 } else {
9542 C.addCommand(Cmd: std::make_unique<Command>(
9543 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9544 args: Output, args: D.getPrependArg()));
9545 }
9546}
9547
9548// Begin OffloadBundler
9549void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
9550 const InputInfo &Output,
9551 const InputInfoList &Inputs,
9552 const llvm::opt::ArgList &TCArgs,
9553 const char *LinkingOutput) const {
9554 // The version with only one output is expected to refer to a bundling job.
9555 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9556
9557 // The bundling command looks like this:
9558 // clang-offload-bundler -type=bc
9559 // -targets=host-triple,openmp-triple1,openmp-triple2
9560 // -output=output_file
9561 // -input=unbundle_file_host
9562 // -input=unbundle_file_tgt1
9563 // -input=unbundle_file_tgt2
9564
9565 ArgStringList CmdArgs;
9566
9567 // Get the type.
9568 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9569 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
9570
9571 assert(JA.getInputs().size() == Inputs.size() &&
9572 "Not have inputs for all dependence actions??");
9573
9574 // Get the targets.
9575 SmallString<128> Triples;
9576 Triples += "-targets=";
9577 for (unsigned I = 0; I < Inputs.size(); ++I) {
9578 if (I)
9579 Triples += ',';
9580
9581 // Find ToolChain for this input.
9582 Action::OffloadKind CurKind = Action::OFK_Host;
9583 const ToolChain *CurTC = &getToolChain();
9584 const Action *CurDep = JA.getInputs()[I];
9585
9586 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
9587 CurTC = nullptr;
9588 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, BoundArch BA) {
9589 assert(CurTC == nullptr && "Expected one dependence!");
9590 CurKind = A->getOffloadingDeviceKind();
9591 CurTC = TC;
9592 });
9593 }
9594 Triples += Action::GetOffloadKindName(Kind: CurKind);
9595 Triples += '-';
9596 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9597 Args: TCArgs, BA: CurDep->getOffloadingArch()))
9598 .normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9599
9600 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9601 Triples += '-';
9602 Triples += CurDep->getOffloadingArch().ArchName;
9603 }
9604 }
9605 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9606
9607 // Get bundled file command.
9608 CmdArgs.push_back(
9609 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9610
9611 // Get unbundled files command.
9612 for (unsigned I = 0; I < Inputs.size(); ++I) {
9613 SmallString<128> UB;
9614 UB += "-input=";
9615
9616 // Find ToolChain for this input.
9617 const ToolChain *CurTC = &getToolChain();
9618 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9619 CurTC = nullptr;
9620 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, BoundArch) {
9621 assert(CurTC == nullptr && "Expected one dependence!");
9622 CurTC = TC;
9623 });
9624 UB += C.addTempFile(
9625 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9626 } else {
9627 UB += CurTC->getInputFilename(Input: Inputs[I]);
9628 }
9629 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9630 }
9631 addOffloadCompressArgs(TCArgs, CmdArgs);
9632 // All the inputs are encoded as commands.
9633 C.addCommand(Cmd: std::make_unique<Command>(
9634 args: JA, args: *this, args: ResponseFileSupport::None(),
9635 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9636 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9637}
9638
9639void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9640 const InputInfo &Output,
9641 const InputInfoList &Inputs,
9642 const llvm::opt::ArgList &Args,
9643 const char *LinkingOutput) const {
9644 ArgStringList CmdArgs;
9645
9646 // Add the output file name.
9647 assert(Output.isFilename() && "Invalid output.");
9648 CmdArgs.push_back(Elt: "-o");
9649 CmdArgs.push_back(Elt: Output.getFilename());
9650
9651 // Create the inputs to bundle the needed metadata.
9652 for (const InputInfo &Input : Inputs) {
9653 const Action *OffloadAction = Input.getAction();
9654 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9655 const ArgList &TCArgs =
9656 C.getArgsForToolChain(TC, BA: OffloadAction->getOffloadingArch(),
9657 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9658 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9659 BoundArch Arch = OffloadAction->getOffloadingArch();
9660 if (Arch.empty())
9661 Arch = BoundArch(TCArgs.getLastArgValue(Id: options::OPT_march_EQ));
9662
9663 StringRef Kind =
9664 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9665
9666 ArgStringList Features;
9667 SmallVector<StringRef> FeatureArgs;
9668 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9669 ForAS: false);
9670 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9671 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9672
9673 // TODO: We need to pass in the full target-id and handle it properly in the
9674 // linker wrapper.
9675 SmallVector<std::string> Parts{
9676 "file=" + File.str(),
9677 "triple=" + TC->ComputeEffectiveClangTriple(Args: TCArgs, BA: Arch),
9678 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9679 "kind=" + Kind.str(),
9680 };
9681
9682 if (TC->isUsingLTO(Args: TCArgs, Kind: OffloadAction->getOffloadingDeviceKind()))
9683 for (StringRef Feature : FeatureArgs)
9684 Parts.emplace_back(Args: "feature=" + Feature.str());
9685
9686 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9687 }
9688
9689 C.addCommand(Cmd: std::make_unique<Command>(
9690 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(),
9691 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9692 args&: CmdArgs, args: Inputs, args: Output));
9693}
9694
9695// Options that need the profile compiler-rt library on the target toolchain.
9696// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9697// too.
9698static bool requiresProfileRT(unsigned ID) {
9699 switch (ID) {
9700 case options::OPT_fprofile_generate:
9701 case options::OPT_fprofile_generate_EQ:
9702 case options::OPT_fprofile_instr_generate:
9703 case options::OPT_fprofile_instr_generate_EQ:
9704 case options::OPT_fcoverage_mapping:
9705 case options::OPT_fno_coverage_mapping:
9706 case options::OPT_fcoverage_compilation_dir_EQ:
9707 case options::OPT_ffile_compilation_dir_EQ:
9708 case options::OPT_fcoverage_prefix_map_EQ:
9709 return true;
9710 default:
9711 return false;
9712 }
9713}
9714
9715// Options that need the ubsan compiler-rt library on the target toolchain.
9716static bool requiresUBSanRT(unsigned ID) {
9717 switch (ID) {
9718 case options::OPT_fsanitize_EQ:
9719 case options::OPT_fno_sanitize_EQ:
9720 case options::OPT_fsanitize_minimal_runtime:
9721 case options::OPT_fno_sanitize_minimal_runtime:
9722 return true;
9723 default:
9724 return false;
9725 }
9726}
9727
9728void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9729 const InputInfo &Output,
9730 const InputInfoList &Inputs,
9731 const ArgList &Args,
9732 const char *LinkingOutput) const {
9733 using namespace options;
9734
9735 // A list of permitted options that will be forwarded to the embedded device
9736 // compilation job.
9737 const llvm::DenseSet<unsigned> CompilerOptions{
9738 OPT_v,
9739 OPT_hip_path_EQ,
9740 OPT_O_Group,
9741 OPT_g_Group,
9742 OPT_g_flags_Group,
9743 OPT_R_value_Group,
9744 OPT_R_Group,
9745 OPT_Xcuda_ptxas,
9746 OPT_ptxas_path_EQ,
9747 OPT_ftime_report,
9748 OPT_ftime_trace,
9749 OPT_ftime_trace_EQ,
9750 OPT_ftime_trace_granularity_EQ,
9751 OPT_ftime_trace_verbose,
9752 OPT_opt_record_file,
9753 OPT_opt_record_format,
9754 OPT_opt_record_passes,
9755 OPT_fsave_optimization_record,
9756 OPT_fsave_optimization_record_EQ,
9757 OPT_fno_save_optimization_record,
9758 OPT_foptimization_record_file_EQ,
9759 OPT_foptimization_record_passes_EQ,
9760 OPT_save_temps,
9761 OPT_save_temps_EQ,
9762 OPT_mcode_object_version_EQ,
9763 OPT_load,
9764 OPT_no_canonical_prefixes,
9765 OPT_fno_lto,
9766 OPT_flto,
9767 OPT_flto_partitions_EQ,
9768 OPT_flto_EQ,
9769 OPT_hipspv_pass_plugin_EQ,
9770 OPT_use_spirv_backend,
9771 OPT_no_use_spirv_backend,
9772 OPT_fmultilib_flag,
9773 OPT_fprofile_generate,
9774 OPT_fprofile_generate_EQ,
9775 OPT_fprofile_instr_generate,
9776 OPT_fprofile_instr_generate_EQ,
9777 OPT_fcoverage_mapping,
9778 OPT_fno_coverage_mapping,
9779 OPT_fcoverage_compilation_dir_EQ,
9780 OPT_ffile_compilation_dir_EQ,
9781 OPT_fcoverage_prefix_map_EQ,
9782 OPT_fsanitize_EQ,
9783 OPT_fno_sanitize_EQ,
9784 OPT_fsanitize_minimal_runtime,
9785 OPT_fno_sanitize_minimal_runtime,
9786 OPT_fsanitize_trap_EQ,
9787 OPT_fno_sanitize_trap_EQ,
9788 OPT_fslp_vectorize,
9789 OPT_fno_slp_vectorize,
9790 OPT_hipstdpar};
9791 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9792 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9793 // CMake implicit linker argument parsing.
9794 bool SuppressHIPNoRDCVerbose =
9795 JA.getType() == types::TY_HIP_FATBIN &&
9796 !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
9797 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9798 return TC.getVFS().exists(
9799 Path: TC.getCompilerRT(Args, Component: Name, Type: ToolChain::FT_Static));
9800 };
9801 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9802 unsigned ID = A->getOption().getID();
9803 // Don't forward profiling arguments if the toolchain doesn't support it.
9804 // Without this check using it on the host would result in linker errors.
9805 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9806 // together to avoid a device cc1 diagnostic.
9807 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9808 return false;
9809 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9810 // Without this check using it on the host would result in linker errors.
9811 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal") &&
9812 !ToolChainHasRT(TC, "ubsan_standalone"))
9813 return false;
9814 // Don't forward -mllvm to toolchains that don't support LLVM.
9815 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9816 };
9817 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9818 const ToolChain &TC) {
9819 if (A->getOption().matches(ID: OPT_v) && SuppressHIPNoRDCVerbose)
9820 return false;
9821 return (Set.contains(V: A->getOption().getID()) ||
9822 (A->getOption().getGroup().isValid() &&
9823 Set.contains(V: A->getOption().getGroup().getID()))) &&
9824 ShouldForwardForToolChain(A, TC);
9825 };
9826
9827 ArgStringList CmdArgs;
9828 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9829 Action::OFK_HIP, Action::OFK_SYCL}) {
9830 auto TCRange = C.getOffloadToolChains(Kind);
9831 for (auto &I : llvm::make_range(p: TCRange)) {
9832 const ToolChain *TC = I.second;
9833
9834 // We do not use a bound architecture here so options passed only to a
9835 // specific architecture via -Xarch_<cpu> will not be forwarded.
9836 ArgStringList CompilerArgs;
9837 ArgStringList LinkerArgs;
9838 const DerivedArgList &ToolChainArgs =
9839 C.getArgsForToolChain(TC, /*BA=*/{}, DeviceOffloadKind: Kind);
9840 for (Arg *A : ToolChainArgs) {
9841 if (A->getOption().matches(ID: OPT_Zlinker_input))
9842 LinkerArgs.emplace_back(Args: A->getValue());
9843 else if (ShouldForward(CompilerOptions, A, *TC)) {
9844 A->claim();
9845 A->render(Args, Output&: CompilerArgs);
9846 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9847 A->claim();
9848 A->render(Args, Output&: LinkerArgs);
9849 }
9850 }
9851
9852 // If the user explicitly requested it via `--offload-arch` we should
9853 // extract it from any static libraries if present.
9854 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ))
9855 CmdArgs.emplace_back(Args: Args.MakeArgString(Str: "--should-extract=" + Arg));
9856
9857 // If this is OpenMP the device linker will need `-lompdevice`.
9858 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9859 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9860 LinkerArgs.emplace_back(Args: "-lompdevice");
9861
9862 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9863 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9864 // flags to normal compilation.
9865 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9866 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9867 if (TC->getTriple().isSPIRV() &&
9868 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9869 Kind != Action::OFK_SYCL && !TC->isUsingLTO(Args: ToolChainArgs, Kind)) {
9870 // For SPIR-V some functions will be defined by the runtime so allow
9871 // unresolved symbols in `spirv-link`.
9872 LinkerArgs.emplace_back(Args: "--allow-partial-linkage");
9873 // Don't optimize out exported symbols.
9874 LinkerArgs.emplace_back(Args: "--create-library");
9875 }
9876
9877 // Forward the SYCL device image split option to clang-sycl-linker.
9878 // The driver and clang-sycl-linker share the same value vocabulary, so
9879 // the value is passed through verbatim after validation.
9880 if (Kind == Action::OFK_SYCL) {
9881 if (Arg *A =
9882 ToolChainArgs.getLastArg(Ids: OPT_fsycl_device_image_split_EQ)) {
9883 StringRef Mode = A->getValue();
9884 if (Mode != "kernel" && Mode != "translation_unit" &&
9885 Mode != "link_unit")
9886 C.getDriver().Diag(DiagID: clang::diag::err_drv_invalid_value)
9887 << A->getSpelling() << Mode;
9888 else
9889 LinkerArgs.emplace_back(
9890 Args: Args.MakeArgString(Str: "--module-split-mode=" + Mode));
9891 }
9892 }
9893
9894 // Forward all of these to the appropriate toolchain.
9895 for (StringRef Arg : CompilerArgs)
9896 CmdArgs.push_back(Elt: Args.MakeArgString(
9897 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9898 for (StringRef Arg : LinkerArgs)
9899 CmdArgs.push_back(Elt: Args.MakeArgString(
9900 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9901
9902 // Forward the LTO mode for this toolchain.
9903 auto DeviceLTOMode = TC->getLTOMode(Args: ToolChainArgs, Kind);
9904 if (DeviceLTOMode == LTOK_Full)
9905 CmdArgs.push_back(Elt: Args.MakeArgString(
9906 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9907 else if (DeviceLTOMode == LTOK_Thin) {
9908 CmdArgs.push_back(Elt: Args.MakeArgString(
9909 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9910 if (TC->getTriple().isAMDGPU()) {
9911 CmdArgs.push_back(
9912 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9913 "=-plugin-opt=-force-import-all"));
9914 CmdArgs.push_back(
9915 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9916 "=-plugin-opt=-avail-extern-to-local"));
9917 CmdArgs.push_back(Elt: Args.MakeArgString(
9918 Str: "--device-linker=" + TC->getTripleString() +
9919 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9920 if (Kind == Action::OFK_OpenMP) {
9921 CmdArgs.push_back(
9922 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9923 "=-plugin-opt=-amdgpu-internalize-symbols"));
9924 }
9925 }
9926 }
9927 }
9928 }
9929
9930 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9931 CmdArgs.push_back(
9932 Elt: Args.MakeArgString(Str: "--host-triple=" + AuxTriple->getTriple()));
9933 else
9934 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--host-triple=" +
9935 getToolChain().getTripleString()));
9936
9937 if (Args.hasArg(Ids: options::OPT_v) && !SuppressHIPNoRDCVerbose)
9938 CmdArgs.push_back(Elt: "--wrapper-verbose");
9939 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ)) {
9940 CmdArgs.push_back(
9941 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
9942 CmdArgs.push_back(Elt: Args.MakeArgString(
9943 Str: Twine("--device-compiler=--cuda-path=") + A->getValue()));
9944 }
9945 if (Arg *A = Args.getLastArg(Ids: options::OPT_rocm_path_EQ)) {
9946 CmdArgs.push_back(Elt: Args.MakeArgString(
9947 Str: Twine("--device-compiler=--rocm-path=") + A->getValue()));
9948 }
9949
9950 // Construct the link job so we can wrap around it.
9951 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
9952 const auto &LinkCommand = C.getJobs().getJobs().back();
9953
9954 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9955 // wrapper.
9956 for (Arg *A :
9957 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
9958 StringRef Val = A->getValue(N: 0);
9959 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9960 auto WrapperOption =
9961 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9962 if (Val.empty())
9963 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
9964 else
9965 CmdArgs.push_back(Elt: Args.MakeArgString(
9966 Str: WrapperOption +
9967 ToolChain::normalizeOffloadTriple(OrigTT: Val.drop_front()).str() + "=" +
9968 A->getValue(N: 1)));
9969 }
9970 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
9971 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
9972
9973 // Embed bitcode instead of an object in JIT mode.
9974 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
9975 Neg: options::OPT_fno_openmp_target_jit, Default: false))
9976 CmdArgs.push_back(Elt: "--embed-bitcode");
9977
9978 // Save temporary files created by the linker wrapper.
9979 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
9980 Args.hasArg(Ids: options::OPT_save_temps))
9981 CmdArgs.push_back(Elt: "--save-temps");
9982
9983 // Pass in the C library for GPUs if present and not disabled.
9984 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
9985 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
9986 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
9987 Ids: options::OPT_nogpulibc)) {
9988 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
9989 // The device C library is only available for NVPTX and AMDGPU targets
9990 // and we only link it by default for OpenMP currently.
9991 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
9992 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
9993 return;
9994 bool HasLibC = TC.getStdlibIncludePath().has_value();
9995 if (HasLibC) {
9996 CmdArgs.push_back(Elt: Args.MakeArgString(
9997 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9998 CmdArgs.push_back(Elt: Args.MakeArgString(
9999 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10000 }
10001 auto HasCompilerRT = getToolChain().getVFS().exists(
10002 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static,
10003 /*IsFortran=*/false));
10004 if (HasCompilerRT)
10005 CmdArgs.push_back(
10006 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10007 "-lclang_rt.builtins"));
10008
10009 bool HasFlangRT = getToolChain().getVFS().exists(
10010 Path: TC.getCompilerRT(Args, Component: "runtime", Type: ToolChain::FT_Static,
10011 /*IsFortran=*/true));
10012 if (HasFlangRT && C.getDriver().IsFlangMode())
10013 CmdArgs.push_back(
10014 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10015 "-lflang_rt.runtime"));
10016 });
10017 }
10018
10019 // Add the linker arguments to be forwarded by the wrapper.
10020 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
10021 LinkCommand->getExecutable()));
10022
10023 // We use action type to differentiate two use cases of the linker wrapper.
10024 // TY_Image for normal linker wrapper work.
10025 // TY_HIP_FATBIN and TY_SYCL_FATBIN for device-only links emitting a fat
10026 // binary directly.
10027 assert(JA.getType() == types::TY_HIP_FATBIN ||
10028 JA.getType() == types::TY_SYCL_FATBIN ||
10029 JA.getType() == types::TY_Image);
10030 if (JA.getType() != types::TY_Image) {
10031 CmdArgs.push_back(Elt: "--emit-fatbin-only");
10032 CmdArgs.append(IL: {"-o", Output.getFilename()});
10033 for (auto Input : Inputs)
10034 CmdArgs.push_back(Elt: Input.getFilename());
10035 } else {
10036 for (const char *LinkArg : LinkCommand->getArguments())
10037 CmdArgs.push_back(Elt: LinkArg);
10038 }
10039
10040 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
10041
10042 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10043 if (OffloadJobs.A) {
10044 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10045 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
10046 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10047 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=" +
10048 Twine(OffloadJobs.NumThreads)));
10049 } else if (!OffloadJobs.A->isClaimed()) {
10050 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
10051 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10052 }
10053 }
10054
10055 // Propagate -no-canonical-prefixes.
10056 if (Args.hasArg(Ids: options::OPT_no_canonical_prefixes))
10057 CmdArgs.push_back(Elt: "--no-canonical-prefixes");
10058
10059 const char *Exec =
10060 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
10061
10062 // Replace the executable and arguments of the link job with the
10063 // wrapper.
10064 LinkCommand->replaceExecutable(Exe: Exec);
10065 LinkCommand->replaceArguments(List: CmdArgs);
10066}
10067