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/Compression.h"
50#include "llvm/Support/Error.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/Process.h"
55#include "llvm/Support/YAMLParser.h"
56#include "llvm/TargetParser/AArch64TargetParser.h"
57#include "llvm/TargetParser/ARMTargetParserCommon.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/LoongArchTargetParser.h"
60#include "llvm/TargetParser/PPCTargetParser.h"
61#include "llvm/TargetParser/RISCVISAInfo.h"
62#include "llvm/TargetParser/RISCVTargetParser.h"
63#include <cctype>
64
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 const ObjCRuntime &objcRuntime,
140 ArgStringList &CmdArgs) {
141 const llvm::Triple &Triple = TC.getTriple();
142
143 if (KernelOrKext) {
144 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
145 // arguments now to avoid warnings about unused arguments.
146 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
147 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
148 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
149 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
152 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
153 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
154 return false;
155 }
156
157 // See if the user explicitly enabled exceptions.
158 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
159 Default: false);
160
161 // Async exceptions are Windows MSVC only.
162 if (Triple.isWindowsMSVCEnvironment()) {
163 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
164 Neg: options::OPT_fno_async_exceptions, Default: false);
165 if (EHa) {
166 CmdArgs.push_back(Elt: "-fasync-exceptions");
167 EH = true;
168 }
169 }
170
171 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
172 // is not necessarily sensible, but follows GCC.
173 if (types::isObjC(Id: InputType) &&
174 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
175 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
176 CmdArgs.push_back(Elt: "-fobjc-exceptions");
177
178 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
179 }
180
181 if (types::isCXX(Id: InputType)) {
182 // Disable C++ EH by default on XCore and PS4/PS5.
183 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
184 !Triple.isPS() && !Triple.isDriverKit();
185 Arg *ExceptionArg = Args.getLastArg(
186 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
187 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
188 if (ExceptionArg)
189 CXXExceptionsEnabled =
190 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
191 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
192
193 if (CXXExceptionsEnabled) {
194 CmdArgs.push_back(Elt: "-fcxx-exceptions");
195
196 EH = true;
197 }
198 }
199
200 // OPT_fignore_exceptions means exception could still be thrown,
201 // but no clean up or catch would happen in current module.
202 // So we do not set EH to false.
203 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
204
205 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
206 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
207
208 if (EH)
209 CmdArgs.push_back(Elt: "-fexceptions");
210 return EH;
211}
212
213static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
214 const JobAction &JA) {
215 bool Default = true;
216 if (TC.getTriple().isOSDarwin()) {
217 // The native darwin assembler doesn't support the linker_option directives,
218 // so we disable them if we think the .s file will be passed to it.
219 Default = TC.useIntegratedAs();
220 }
221 // The linker_option directives are intended for host compilation.
222 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
223 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
224 Default = false;
225 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
226 Default);
227}
228
229/// Add a CC1 option to specify the debug compilation directory.
230static const char *addDebugCompDirArg(const ArgList &Args,
231 ArgStringList &CmdArgs,
232 const llvm::vfs::FileSystem &VFS) {
233 std::string DebugCompDir;
234 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
235 Ids: options::OPT_fdebug_compilation_dir_EQ))
236 DebugCompDir = A->getValue();
237
238 if (DebugCompDir.empty()) {
239 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
240 DebugCompDir = std::move(*CWD);
241 else
242 return nullptr;
243 }
244 CmdArgs.push_back(
245 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
246 StringRef Path(CmdArgs.back());
247 return Path.substr(Start: Path.find(C: '=') + 1).data();
248}
249
250static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
251 const char *DebugCompilationDir,
252 const char *OutputFileName) {
253 // No need to generate a value for -object-file-name if it was provided.
254 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
255 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
256 return;
257
258 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
259 return;
260
261 SmallString<128> ObjFileNameForDebug(OutputFileName);
262 if (ObjFileNameForDebug != "-" &&
263 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
264 (!DebugCompilationDir ||
265 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
266 // Make the path absolute in the debug infos like MSVC does.
267 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
268 }
269 // If the object file name is a relative path, then always use Windows
270 // backslash style as -object-file-name is used for embedding object file path
271 // in codeview and it can only be generated when targeting on Windows.
272 // Otherwise, just use native absolute path.
273 llvm::sys::path::Style Style =
274 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
275 ? llvm::sys::path::Style::native
276 : llvm::sys::path::Style::windows_backslash;
277 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
278 style: Style);
279 CmdArgs.push_back(
280 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
281}
282
283/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
284static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
285 const ArgList &Args, ArgStringList &CmdArgs) {
286 auto AddOneArg = [&](StringRef Map, StringRef Name) {
287 if (!Map.contains(C: '='))
288 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
289 else
290 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
291 };
292
293 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
294 Ids: options::OPT_fdebug_prefix_map_EQ)) {
295 AddOneArg(A->getValue(), A->getOption().getName());
296 A->claim();
297 }
298 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
299 if (GlobalRemapEntry.empty())
300 return;
301 AddOneArg(GlobalRemapEntry, "environment");
302}
303
304/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
305static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
306 ArgStringList &CmdArgs) {
307 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
308 Ids: options::OPT_fmacro_prefix_map_EQ)) {
309 StringRef Map = A->getValue();
310 if (!Map.contains(C: '='))
311 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
312 << Map << A->getOption().getName();
313 else
314 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
315 A->claim();
316 }
317}
318
319/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
320static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
321 ArgStringList &CmdArgs) {
322 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
323 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
324 StringRef Map = A->getValue();
325 if (!Map.contains(C: '='))
326 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
327 << Map << A->getOption().getName();
328 else
329 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
330 A->claim();
331 }
332}
333
334/// Add -x lang to \p CmdArgs for \p Input.
335static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
336 ArgStringList &CmdArgs) {
337 // When using -verify-pch, we don't want to provide the type
338 // 'precompiled-header' if it was inferred from the file extension
339 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
340 return;
341
342 CmdArgs.push_back(Elt: "-x");
343 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
344 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
345 else {
346 // Map the driver type to the frontend type. This is mostly an identity
347 // mapping, except that the distinction between module interface units
348 // and other source files does not exist at the frontend layer.
349 const char *ClangType;
350 switch (Input.getType()) {
351 case types::TY_CXXModule:
352 ClangType = "c++";
353 break;
354 case types::TY_PP_CXXModule:
355 ClangType = "c++-cpp-output";
356 break;
357 default:
358 ClangType = types::getTypeName(Id: Input.getType());
359 break;
360 }
361 CmdArgs.push_back(Elt: ClangType);
362 }
363}
364
365static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
366 const JobAction &JA, const InputInfo &Output,
367 const ArgList &Args, SanitizerArgs &SanArgs,
368 ArgStringList &CmdArgs) {
369 const Driver &D = TC.getDriver();
370 const llvm::Triple &T = TC.getTriple();
371 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
372 Ids: options::OPT_fprofile_generate_EQ,
373 Ids: options::OPT_fno_profile_generate);
374 if (PGOGenerateArg &&
375 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
376 PGOGenerateArg = nullptr;
377
378 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
379
380 auto *ProfileGenerateArg = Args.getLastArg(
381 Ids: options::OPT_fprofile_instr_generate,
382 Ids: options::OPT_fprofile_instr_generate_EQ,
383 Ids: options::OPT_fno_profile_instr_generate);
384 if (ProfileGenerateArg &&
385 ProfileGenerateArg->getOption().matches(
386 ID: options::OPT_fno_profile_instr_generate))
387 ProfileGenerateArg = nullptr;
388
389 if (PGOGenerateArg && ProfileGenerateArg)
390 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
391 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
392
393 auto *ProfileUseArg = getLastProfileUseArg(Args);
394
395 if (PGOGenerateArg && ProfileUseArg)
396 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
397 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
398
399 if (ProfileGenerateArg && ProfileUseArg)
400 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
401 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
402
403 if (CSPGOGenerateArg && PGOGenerateArg) {
404 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
405 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
406 PGOGenerateArg = nullptr;
407 }
408
409 if (TC.getTriple().isOSAIX()) {
410 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
411 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
412 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
413 }
414
415 if (ProfileGenerateArg) {
416 if (ProfileGenerateArg->getOption().matches(
417 ID: options::OPT_fprofile_instr_generate_EQ))
418 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
419 ProfileGenerateArg->getValue()));
420 // The default is to use Clang Instrumentation.
421 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
422 if (TC.getTriple().isWindowsMSVCEnvironment() &&
423 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
424 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
425 // Add dependent lib for clang_rt.profile
426 CmdArgs.push_back(Elt: Args.MakeArgString(
427 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
428 }
429 }
430
431 if (auto *ColdFuncCoverageArg = Args.getLastArg(
432 Ids: options::OPT_fprofile_generate_cold_function_coverage,
433 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
434 SmallString<128> Path(
435 ColdFuncCoverageArg->getOption().matches(
436 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
437 ? ColdFuncCoverageArg->getValue()
438 : "");
439 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
440 // FIXME: Idealy the file path should be passed through
441 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
442 // shared with other profile use path(see PGOOptions), we need to refactor
443 // PGOOptions to make it work.
444 CmdArgs.push_back(Elt: "-mllvm");
445 CmdArgs.push_back(Elt: Args.MakeArgString(
446 Str: Twine("--instrument-cold-function-only-path=") + Path));
447 CmdArgs.push_back(Elt: "-mllvm");
448 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
449 CmdArgs.push_back(Elt: "-mllvm");
450 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
451 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
452 }
453
454 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
455 if (!PGOGenerateArg && !CSPGOGenerateArg)
456 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
457 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
458 CmdArgs.push_back(Elt: "-mllvm");
459 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
460 }
461
462 Arg *PGOGenArg = nullptr;
463 if (PGOGenerateArg) {
464 assert(!CSPGOGenerateArg);
465 PGOGenArg = PGOGenerateArg;
466 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
467 }
468 if (CSPGOGenerateArg) {
469 assert(!PGOGenerateArg);
470 PGOGenArg = CSPGOGenerateArg;
471 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
472 }
473 if (PGOGenArg) {
474 if (TC.getTriple().isWindowsMSVCEnvironment() &&
475 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
476 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
477 // Add dependent lib for clang_rt.profile
478 CmdArgs.push_back(Elt: Args.MakeArgString(
479 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
480 }
481 if (PGOGenArg->getOption().matches(
482 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
483 : options::OPT_fcs_profile_generate_EQ)) {
484 SmallString<128> Path(PGOGenArg->getValue());
485 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
486 CmdArgs.push_back(
487 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
488 }
489 }
490
491 if (ProfileUseArg) {
492 SmallString<128> UsePathBuf;
493 StringRef UsePath;
494 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
495 UsePath = ProfileUseArg->getValue();
496 else if ((ProfileUseArg->getOption().matches(
497 ID: options::OPT_fprofile_use_EQ) ||
498 ProfileUseArg->getOption().matches(
499 ID: options::OPT_fprofile_instr_use))) {
500 UsePathBuf =
501 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
502 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
503 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
504 UsePath = UsePathBuf;
505 }
506 auto ReaderOrErr =
507 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
508 if (auto E = ReaderOrErr.takeError()) {
509 auto DiagID = D.getDiags().getCustomDiagID(
510 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
511 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
512 D.Diag(DiagID) << UsePath.str() << EI.message();
513 });
514 } else {
515 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
516 std::move(ReaderOrErr.get());
517 StringRef UseKind;
518 // Currently memprof profiles are only added at the IR level. Mark the
519 // profile type as IR in that case as well and the subsequent matching
520 // needs to detect which is available (might be one or both).
521 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
522 if (PGOReader->hasCSIRLevelProfile())
523 UseKind = "csllvm";
524 else
525 UseKind = "llvm";
526 } else
527 UseKind = "clang";
528
529 CmdArgs.push_back(
530 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
531 CmdArgs.push_back(
532 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
533 }
534 }
535
536 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
537 Neg: options::OPT_fno_test_coverage, Default: false) ||
538 Args.hasArg(Ids: options::OPT_coverage);
539 bool EmitCovData = TC.needsGCovInstrumentation(Args);
540
541 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
542 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
543 if (!ProfileGenerateArg)
544 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
545 << "-fcoverage-mapping"
546 << "-fprofile-instr-generate";
547
548 CmdArgs.push_back(Elt: "-fcoverage-mapping");
549 }
550
551 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
552 Default: false)) {
553 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
554 Neg: options::OPT_fno_coverage_mapping, Default: false))
555 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
556 << "-fcoverage-mcdc"
557 << "-fcoverage-mapping";
558
559 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
560 }
561
562 StringRef CoverageCompDir;
563 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
564 Ids: options::OPT_fcoverage_compilation_dir_EQ))
565 CoverageCompDir = A->getValue();
566 if (CoverageCompDir.empty()) {
567 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
568 CmdArgs.push_back(
569 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
570 } else
571 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
572 CoverageCompDir));
573
574 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
575 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
576 if (!Args.hasArg(Ids: options::OPT_coverage))
577 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
578 << "-fprofile-exclude-files="
579 << "--coverage";
580
581 StringRef v = Arg->getValue();
582 CmdArgs.push_back(
583 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
584 }
585
586 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
587 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
588 if (!Args.hasArg(Ids: options::OPT_coverage))
589 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
590 << "-fprofile-filter-files="
591 << "--coverage";
592
593 StringRef v = Arg->getValue();
594 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
595 }
596
597 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
598 StringRef Val = A->getValue();
599 if (Val == "atomic" || Val == "prefer-atomic")
600 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
601 else if (Val != "single")
602 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
603 << A->getSpelling() << Val;
604 }
605 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
606 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
607 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
608 << A->getSpelling()
609 << "-fprofile-generate, -fprofile-instr-generate, or "
610 "-fcs-profile-generate";
611 else {
612 CmdArgs.push_back(Elt: "-fprofile-continuous");
613 // Platforms that require a bias variable:
614 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
615 CmdArgs.push_back(Elt: "-mllvm");
616 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
617 }
618 // -fprofile-instr-generate does not decide the profile file name in the
619 // FE, and so it does not define the filename symbol
620 // (__llvm_profile_filename). Instead, the runtime uses the name
621 // "default.profraw" for the profile file. When continuous mode is ON, we
622 // will create the filename symbol so that we can insert the "%c"
623 // modifier.
624 if (ProfileGenerateArg &&
625 (ProfileGenerateArg->getOption().matches(
626 ID: options::OPT_fprofile_instr_generate) ||
627 (ProfileGenerateArg->getOption().matches(
628 ID: options::OPT_fprofile_instr_generate_EQ) &&
629 strlen(s: ProfileGenerateArg->getValue()) == 0)))
630 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
631 }
632 }
633
634 int FunctionGroups = 1;
635 int SelectedFunctionGroup = 0;
636 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
637 StringRef Val = A->getValue();
638 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
639 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
640 }
641 if (const auto *A =
642 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
643 StringRef Val = A->getValue();
644 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
645 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
646 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
647 }
648 if (FunctionGroups != 1)
649 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
650 Twine(FunctionGroups)));
651 if (SelectedFunctionGroup != 0)
652 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
653 Twine(SelectedFunctionGroup)));
654
655 // Leave -fprofile-dir= an unused argument unless .gcda emission is
656 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
657 // the flag used. There is no -fno-profile-dir, so the user has no
658 // targeted way to suppress the warning.
659 Arg *FProfileDir = nullptr;
660 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
661 Args.hasArg(Ids: options::OPT_coverage))
662 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
663
664 // Put the .gcno and .gcda files (if needed) next to the primary output file,
665 // or fall back to a file in the current directory for `clang -c --coverage
666 // d/a.c` in the absence of -o.
667 if (EmitCovNotes || EmitCovData) {
668 SmallString<128> CoverageFilename;
669 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
670 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
671 // path separator.
672 CoverageFilename = DumpDir->getValue();
673 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
674 } else if (Arg *FinalOutput =
675 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
676 CoverageFilename = FinalOutput->getValue();
677 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
678 CoverageFilename = FinalOutput->getValue();
679 } else {
680 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
681 }
682 if (llvm::sys::path::is_relative(path: CoverageFilename))
683 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
684 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
685 if (EmitCovNotes) {
686 CmdArgs.push_back(
687 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
688 }
689
690 if (EmitCovData) {
691 if (FProfileDir) {
692 SmallString<128> Gcno = std::move(CoverageFilename);
693 CoverageFilename = FProfileDir->getValue();
694 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
695 }
696 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
697 CmdArgs.push_back(
698 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
699 }
700 }
701}
702
703static void
704RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
705 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
706 unsigned DwarfVersion,
707 llvm::DebuggerKind DebuggerTuning) {
708 addDebugInfoKind(CmdArgs, DebugInfoKind);
709 if (DwarfVersion > 0)
710 CmdArgs.push_back(
711 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
712 switch (DebuggerTuning) {
713 case llvm::DebuggerKind::GDB:
714 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
715 break;
716 case llvm::DebuggerKind::LLDB:
717 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
718 break;
719 case llvm::DebuggerKind::SCE:
720 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
721 break;
722 case llvm::DebuggerKind::DBX:
723 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
724 break;
725 default:
726 break;
727 }
728}
729
730static void RenderDebugInfoCompressionArgs(const ArgList &Args,
731 ArgStringList &CmdArgs,
732 const Driver &D,
733 const ToolChain &TC) {
734 const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ);
735 if (!A)
736 return;
737 if (checkDebugInfoOption(A, Args, D, TC)) {
738 StringRef Value = A->getValue();
739 if (Value == "none") {
740 CmdArgs.push_back(Elt: "--compress-debug-sections=none");
741 } else if (Value == "zlib") {
742 if (llvm::compression::zlib::isAvailable()) {
743 CmdArgs.push_back(
744 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
745 } else {
746 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zlib";
747 }
748 } else if (Value == "zstd") {
749 if (llvm::compression::zstd::isAvailable()) {
750 CmdArgs.push_back(
751 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
752 } else {
753 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zstd";
754 }
755 } else {
756 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
757 << A->getSpelling() << Value;
758 }
759 }
760}
761
762static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
763 const ArgList &Args,
764 ArgStringList &CmdArgs,
765 bool IsCC1As = false) {
766 // If no version was requested by the user, use the default value from the
767 // back end. This is consistent with the value returned from
768 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
769 // requiring the corresponding llvm to have the AMDGPU target enabled,
770 // provided the user (e.g. front end tests) can use the default.
771 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
772 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
773 CmdArgs.insert(I: CmdArgs.begin() + 1,
774 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
775 Twine(CodeObjVer)));
776 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
777 // -cc1as does not accept -mcode-object-version option.
778 if (!IsCC1As)
779 CmdArgs.insert(I: CmdArgs.begin() + 1,
780 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
781 Twine(CodeObjVer)));
782 }
783}
784
785static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
786 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
787 D.getVFS().getBufferForFile(Name: Path);
788 if (!MemBuf)
789 return false;
790 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
791 if (Magic == llvm::file_magic::unknown)
792 return false;
793 // Return true for both raw Clang AST files and object files which may
794 // contain a __clangast section.
795 if (Magic == llvm::file_magic::clang_ast)
796 return true;
797 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
798 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
799 return !Obj.takeError();
800}
801
802static bool gchProbe(const Driver &D, StringRef Path) {
803 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
804 if (!Status)
805 return false;
806
807 if (Status->isDirectory()) {
808 std::error_code EC;
809 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
810 !EC && DI != DE; DI = DI.increment(EC)) {
811 if (maybeHasClangPchSignature(D, Path: DI->path()))
812 return true;
813 }
814 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
815 return false;
816 }
817
818 if (maybeHasClangPchSignature(D, Path))
819 return true;
820 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
821 return false;
822}
823
824void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
825 const Driver &D, const ArgList &Args,
826 ArgStringList &CmdArgs,
827 const InputInfo &Output,
828 const InputInfoList &Inputs) const {
829 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
830
831 CheckPreprocessingOptions(D, Args);
832
833 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
834 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
835
836 // Handle dependency file generation.
837 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
838 if (!ArgM)
839 ArgM = Args.getLastArg(Ids: options::OPT_M);
840 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
841 if (!ArgMD)
842 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
843
844 // -M and -MM imply -w.
845 if (ArgM)
846 CmdArgs.push_back(Elt: "-w");
847 else
848 ArgM = ArgMD;
849
850 if (ArgM) {
851 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
852 // Determine the output location.
853 const char *DepFile;
854 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
855 DepFile = MF->getValue();
856 C.addFailureResultFile(Name: DepFile, JA: &JA);
857 } else if (Output.getType() == types::TY_Dependencies) {
858 DepFile = Output.getFilename();
859 } else if (!ArgMD) {
860 DepFile = "-";
861 } else {
862 DepFile = getDependencyFileName(Args, Inputs);
863 C.addFailureResultFile(Name: DepFile, JA: &JA);
864 }
865 CmdArgs.push_back(Elt: "-dependency-file");
866 CmdArgs.push_back(Elt: DepFile);
867 }
868 // Cmake generates dependency files using all compilation options specified
869 // by users. Claim those not used for dependency files.
870 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
871 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
872 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
873 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
874 }
875
876 bool HasTarget = false;
877 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
878 HasTarget = true;
879 A->claim();
880 if (A->getOption().matches(ID: options::OPT_MT)) {
881 A->render(Args, Output&: CmdArgs);
882 } else {
883 CmdArgs.push_back(Elt: "-MT");
884 SmallString<128> Quoted;
885 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
886 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
887 }
888 }
889
890 // Add a default target if one wasn't specified.
891 if (!HasTarget) {
892 const char *DepTarget;
893
894 // If user provided -o, that is the dependency target, except
895 // when we are only generating a dependency file.
896 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
897 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
898 DepTarget = OutputOpt->getValue();
899 } else {
900 // Otherwise derive from the base input.
901 //
902 // FIXME: This should use the computed output file location.
903 SmallString<128> P(Inputs[0].getBaseInput());
904 llvm::sys::path::replace_extension(path&: P, extension: "o");
905 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
906 }
907
908 CmdArgs.push_back(Elt: "-MT");
909 SmallString<128> Quoted;
910 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
911 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
912 }
913
914 if (ArgM->getOption().matches(ID: options::OPT_M) ||
915 ArgM->getOption().matches(ID: options::OPT_MD))
916 CmdArgs.push_back(Elt: "-sys-header-deps");
917 if ((isa<PrecompileJobAction>(Val: JA) &&
918 !Args.hasArg(Ids: options::OPT_fno_module_file_deps)) ||
919 Args.hasArg(Ids: options::OPT_fmodule_file_deps))
920 CmdArgs.push_back(Elt: "-module-file-deps");
921 }
922
923 if (Args.hasArg(Ids: options::OPT_MG)) {
924 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
925 ArgM->getOption().matches(ID: options::OPT_MMD))
926 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
927 CmdArgs.push_back(Elt: "-MG");
928 }
929
930 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
931 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
932
933 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
934 // before we -I or -include anything else, because we must pick up the
935 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
936 // rather than from e.g. /usr/local/include.
937 if (JA.isOffloading(OKind: Action::OFK_Cuda))
938 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
939 if (JA.isOffloading(OKind: Action::OFK_HIP))
940 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
941 if (JA.isOffloading(OKind: Action::OFK_SYCL))
942 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
943
944 // If we are offloading to a target via OpenMP we need to include the
945 // openmp_wrappers folder which contains alternative system headers.
946 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
947 !Args.hasArg(Ids: options::OPT_nostdinc) &&
948 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
949 Default: true) &&
950 getToolChain().getTriple().isGPU()) {
951 if (!Args.hasArg(Ids: options::OPT_nobuiltininc)) {
952 // Add openmp_wrappers/* to our system include path. This lets us wrap
953 // standard library headers.
954 SmallString<128> P(D.ResourceDir);
955 llvm::sys::path::append(path&: P, a: "include");
956 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
957 CmdArgs.push_back(Elt: "-internal-isystem");
958 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
959 }
960
961 CmdArgs.push_back(Elt: "-include");
962 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
963 }
964
965 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm)) {
966 // Add llvm_wrappers/* to our system include path. This lets us wrap
967 // standard library headers and other headers.
968 SmallString<128> P(D.ResourceDir);
969 llvm::sys::path::append(path&: P, a: "include", b: "llvm_offload_wrappers");
970 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: P), "-include"});
971 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))
972 CmdArgs.push_back(Elt: "__llvm_offload_device.h");
973 else
974 CmdArgs.push_back(Elt: "__llvm_offload_host.h");
975 }
976
977 // Add -i* options, and automatically translate to
978 // -include-pch/-include-pth for transparent PCH support. It's
979 // wonky, but we include looking for .gch so we can support seamless
980 // replacement into a build system already set up to be generating
981 // .gch files.
982
983 if (getToolChain().getDriver().IsCLMode()) {
984 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
985 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
986 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
987 JA.getKind() <= Action::AssembleJobClass) {
988 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
989 // -fpch-instantiate-templates is the default when creating
990 // precomp using /Yc
991 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
992 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
993 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
994 }
995 if (YcArg || YuArg) {
996 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
997 if (!isa<PrecompileJobAction>(Val: JA)) {
998 CmdArgs.push_back(Elt: "-include-pch");
999 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
1000 C, BaseName: !ThroughHeader.empty()
1001 ? ThroughHeader
1002 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1003 }
1004
1005 if (ThroughHeader.empty()) {
1006 CmdArgs.push_back(Elt: Args.MakeArgString(
1007 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1008 } else {
1009 CmdArgs.push_back(
1010 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1011 }
1012 }
1013 }
1014
1015 bool RenderedImplicitInclude = false;
1016 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1017 if (A->getOption().matches(ID: options::OPT_include) &&
1018 D.getProbePrecompiled()) {
1019 // Handling of gcc-style gch precompiled headers.
1020 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1021 RenderedImplicitInclude = true;
1022
1023 bool FoundPCH = false;
1024 SmallString<128> P(A->getValue());
1025 // We want the files to have a name like foo.h.pch. Add a dummy extension
1026 // so that replace_extension does the right thing.
1027 P += ".dummy";
1028 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1029 if (D.getVFS().exists(Path: P))
1030 FoundPCH = true;
1031
1032 if (!FoundPCH) {
1033 // For GCC compat, probe for a file or directory ending in .gch instead.
1034 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1035 FoundPCH = gchProbe(D, Path: P.str());
1036 }
1037
1038 if (FoundPCH) {
1039 if (IsFirstImplicitInclude) {
1040 A->claim();
1041 CmdArgs.push_back(Elt: "-include-pch");
1042 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1043 continue;
1044 } else {
1045 // Ignore the PCH if not first on command line and emit warning.
1046 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1047 << A->getAsString(Args);
1048 }
1049 }
1050 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1051 // Handling of paths which must come late. These entries are handled by
1052 // the toolchain itself after the resource dir is inserted in the right
1053 // search order.
1054 // Do not claim the argument so that the use of the argument does not
1055 // silently go unnoticed on toolchains which do not honour the option.
1056 continue;
1057 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1058 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1059 continue;
1060 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1061 // This is used only by the driver. No need to pass to cc1.
1062 continue;
1063 }
1064
1065 // Not translated, render as usual.
1066 A->claim();
1067 A->render(Args, Output&: CmdArgs);
1068 }
1069
1070 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1071 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1072 // Collect all enabled NVPTX architectures.
1073 std::set<unsigned> ArchIDs;
1074 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1075 const ToolChain *TC = I.second;
1076 for (StringRef Arch :
1077 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1078 OffloadArch OA = StringToOffloadArch(S: Arch);
1079 if (IsNVIDIAOffloadArch(A: OA))
1080 ArchIDs.insert(x: CudaArchToID(Arch: OA));
1081 }
1082 }
1083
1084 if (!ArchIDs.empty()) {
1085 SmallString<128> List;
1086 llvm::raw_svector_ostream OS(List);
1087 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1088 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1089 }
1090 }
1091
1092 Args.addAllArgs(Output&: CmdArgs,
1093 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1094 options::OPT_F, options::OPT_embed_dir_EQ});
1095
1096 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1097
1098 // FIXME: There is a very unfortunate problem here, some troubled
1099 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1100 // really support that we would have to parse and then translate
1101 // those options. :(
1102 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1103 Id1: options::OPT_Xpreprocessor);
1104
1105 // -I- is a deprecated GCC feature, reject it.
1106 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1107 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1108
1109 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1110 // -isysroot to the CC1 invocation.
1111 StringRef sysroot = C.getSysRoot();
1112 if (sysroot != "") {
1113 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1114 CmdArgs.push_back(Elt: "-isysroot");
1115 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1116 }
1117 }
1118
1119 // Parse additional include paths from environment variables.
1120 // FIXME: We should probably sink the logic for handling these from the
1121 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1122 // CPATH - included following the user specified includes (but prior to
1123 // builtin and standard includes).
1124 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1125 // C_INCLUDE_PATH - system includes enabled when compiling C.
1126 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1127 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1128 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1129 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1130 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1131 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1132 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1133
1134 // While adding the include arguments, we also attempt to retrieve the
1135 // arguments of related offloading toolchains or arguments that are specific
1136 // of an offloading programming model.
1137
1138 // Add C++ include arguments, if needed.
1139 if (types::isCXX(Id: Inputs[0].getType())) {
1140 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1141 forAllAssociatedToolChains(
1142 C, JA, RegularToolChain: getToolChain(),
1143 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1144 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1145 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1146 });
1147 }
1148
1149 // If we are compiling for a GPU target we want to override the system headers
1150 // with ones created by the 'libc' project if present.
1151 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1152 // OffloadKind as an argument.
1153 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1154 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1155 Default: true) &&
1156 !Args.hasArg(Ids: options::OPT_nobuiltininc) &&
1157 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1158 // TODO: CUDA / HIP include their own headers for some common functions
1159 // implemented here. We'll need to clean those up so they do not conflict.
1160 SmallString<128> P(D.ResourceDir);
1161 llvm::sys::path::append(path&: P, a: "include");
1162 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1163 CmdArgs.push_back(Elt: "-internal-isystem");
1164 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1165 }
1166
1167 // Add system include arguments for all targets but IAMCU.
1168 if (!IsIAMCU)
1169 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1170 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1171 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1172 });
1173 else {
1174 // For IAMCU add special include arguments.
1175 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1176 }
1177
1178 addMacroPrefixMapArg(D, Args, CmdArgs);
1179 addCoveragePrefixMapArg(D, Args, CmdArgs);
1180
1181 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1182 Ids: options::OPT_fno_file_reproducible);
1183
1184 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1185 CmdArgs.push_back(Elt: "-source-date-epoch");
1186 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1187 }
1188
1189 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1190 Neg: options::OPT_fno_define_target_os_macros);
1191}
1192
1193// FIXME: Move to target hook.
1194static bool isSignedCharDefault(const llvm::Triple &Triple) {
1195 switch (Triple.getArch()) {
1196 default:
1197 return true;
1198
1199 case llvm::Triple::aarch64:
1200 case llvm::Triple::aarch64_32:
1201 case llvm::Triple::aarch64_be:
1202 case llvm::Triple::arm:
1203 case llvm::Triple::armeb:
1204 case llvm::Triple::thumb:
1205 case llvm::Triple::thumbeb:
1206 if (Triple.isOSDarwin() || Triple.isOSWindows())
1207 return true;
1208 return false;
1209
1210 case llvm::Triple::ppc:
1211 case llvm::Triple::ppc64:
1212 if (Triple.isOSDarwin())
1213 return true;
1214 return false;
1215
1216 case llvm::Triple::csky:
1217 case llvm::Triple::hexagon:
1218 case llvm::Triple::msp430:
1219 case llvm::Triple::ppcle:
1220 case llvm::Triple::ppc64le:
1221 case llvm::Triple::riscv32:
1222 case llvm::Triple::riscv64:
1223 case llvm::Triple::riscv32be:
1224 case llvm::Triple::riscv64be:
1225 case llvm::Triple::systemz:
1226 case llvm::Triple::xcore:
1227 case llvm::Triple::xtensa:
1228 return false;
1229 }
1230}
1231
1232static bool hasMultipleInvocations(const llvm::Triple &Triple,
1233 const ArgList &Args) {
1234 // Supported only on Darwin where we invoke the compiler multiple times
1235 // followed by an invocation to lipo.
1236 if (!Triple.isOSDarwin())
1237 return false;
1238 // If more than one "-arch <arch>" is specified, we're targeting multiple
1239 // architectures resulting in a fat binary.
1240 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1241}
1242
1243static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1244 const llvm::Triple &Triple) {
1245 // When enabling remarks, we need to error if:
1246 // * The remark file is specified but we're targeting multiple architectures,
1247 // which means more than one remark file is being generated.
1248 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1249 bool hasExplicitOutputFile =
1250 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1251 if (hasMultipleInvocations && hasExplicitOutputFile) {
1252 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1253 << "-foptimization-record-file";
1254 return false;
1255 }
1256 return true;
1257}
1258
1259static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1260 const llvm::Triple &Triple,
1261 const InputInfo &Input,
1262 const InputInfo &Output, const JobAction &JA) {
1263 StringRef Format = "yaml";
1264 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1265 Format = A->getValue();
1266
1267 CmdArgs.push_back(Elt: "-opt-record-file");
1268
1269 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1270 if (A) {
1271 CmdArgs.push_back(Elt: A->getValue());
1272 } else {
1273 bool hasMultipleArchs =
1274 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1275 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1276
1277 SmallString<128> F;
1278
1279 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1280 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1281 F = FinalOutput->getValue();
1282 } else {
1283 if (Format != "yaml" && // For YAML, keep the original behavior.
1284 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1285 Output.isFilename())
1286 F = Output.getFilename();
1287 }
1288
1289 if (F.empty()) {
1290 // Use the input filename.
1291 F = llvm::sys::path::stem(path: Input.getBaseInput());
1292
1293 // If we're compiling for an offload architecture (i.e. a CUDA device),
1294 // we need to make the file name for the device compilation different
1295 // from the host compilation.
1296 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1297 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1298 llvm::sys::path::replace_extension(path&: F, extension: "");
1299 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1300 NormalizedTriple: Triple.normalize());
1301 F += "-";
1302 F += JA.getOffloadingArch();
1303 }
1304 }
1305
1306 // If we're having more than one "-arch", we should name the files
1307 // differently so that every cc1 invocation writes to a different file.
1308 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1309 // name from the triple.
1310 if (hasMultipleArchs) {
1311 // First, remember the extension.
1312 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1313 // then, remove it.
1314 llvm::sys::path::replace_extension(path&: F, extension: "");
1315 // attach -<arch> to it.
1316 F += "-";
1317 F += Triple.getArchName();
1318 // put back the extension.
1319 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1320 }
1321
1322 SmallString<32> Extension;
1323 Extension += "opt.";
1324 Extension += Format;
1325
1326 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1327 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1328 }
1329
1330 if (const Arg *A =
1331 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1332 CmdArgs.push_back(Elt: "-opt-record-passes");
1333 CmdArgs.push_back(Elt: A->getValue());
1334 }
1335
1336 if (!Format.empty()) {
1337 CmdArgs.push_back(Elt: "-opt-record-format");
1338 CmdArgs.push_back(Elt: Format.data());
1339 }
1340}
1341
1342void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1343 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1344 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1345 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1346
1347 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1348 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1349}
1350
1351namespace {
1352void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1353 const ArgList &Args, ArgStringList &CmdArgs) {
1354 // Select the ABI to use.
1355 // FIXME: Support -meabi.
1356 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1357 const char *ABIName = nullptr;
1358 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1359 ABIName = A->getValue();
1360 else
1361 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1362
1363 CmdArgs.push_back(Elt: "-target-abi");
1364 CmdArgs.push_back(Elt: ABIName);
1365}
1366
1367void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1368 auto StrictAlignIter =
1369 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1370 return Arg == "+strict-align" || Arg == "-strict-align";
1371 });
1372 if (StrictAlignIter != CmdArgs.rend() &&
1373 StringRef(*StrictAlignIter) == "+strict-align")
1374 CmdArgs.push_back(Elt: "-Wunaligned-access");
1375}
1376}
1377
1378static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1379 ArgStringList &CmdArgs, bool isAArch64) {
1380 const llvm::Triple &Triple = TC.getEffectiveTriple();
1381 const Arg *A = isAArch64
1382 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1383 Ids: options::OPT_mbranch_protection_EQ)
1384 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1385 if (!A) {
1386 if (Triple.isOSOpenBSD() && isAArch64) {
1387 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1388 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1389 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1390 }
1391 return;
1392 }
1393
1394 const Driver &D = TC.getDriver();
1395 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1396 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1397 << Triple.getArchName();
1398
1399 StringRef Scope, Key;
1400 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1401
1402 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1403 Scope = A->getValue();
1404 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1405 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1406 << A->getSpelling() << Scope;
1407 Key = "a_key";
1408 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1409 BranchProtectionPAuthLR = false;
1410 GuardedControlStack = false;
1411 } else {
1412 StringRef DiagMsg;
1413 llvm::ARM::ParsedBranchProtection PBP;
1414 bool EnablePAuthLR = false;
1415
1416 // To know if we need to enable PAuth-LR As part of the standard branch
1417 // protection option, it needs to be determined if the feature has been
1418 // activated in the `march` argument. This information is stored within the
1419 // CmdArgs variable and can be found using a search.
1420 if (isAArch64) {
1421 auto isPAuthLR = [](const char *member) {
1422 llvm::AArch64::ExtensionInfo pauthlr_extension =
1423 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1424 return pauthlr_extension.PosTargetFeature == member;
1425 };
1426
1427 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1428 EnablePAuthLR = true;
1429 }
1430 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg,
1431 EnablePAuthLR))
1432 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1433 << A->getSpelling() << DiagMsg;
1434 if (!isAArch64 && PBP.Key == "b_key")
1435 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1436 << "b-key" << A->getAsString(Args);
1437 Scope = PBP.Scope;
1438 Key = PBP.Key;
1439 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1440 IndirectBranches = PBP.BranchTargetEnforcement;
1441 GuardedControlStack = PBP.GuardedControlStack;
1442 }
1443
1444 Arg *PtrauthReturnsArg = Args.getLastArg(Ids: options::OPT_fptrauth_returns,
1445 Ids: options::OPT_fno_ptrauth_returns);
1446 bool HasPtrauthReturns =
1447 PtrauthReturnsArg &&
1448 PtrauthReturnsArg->getOption().matches(ID: options::OPT_fptrauth_returns);
1449 // GCS is currently untested with ptrauth-returns, but enabling this could be
1450 // allowed in future after testing with a suitable system.
1451 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1452 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1453 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1454 << A->getAsString(Args) << Triple.getTriple();
1455 else if (HasPtrauthReturns)
1456 D.Diag(DiagID: diag::err_drv_incompatible_options)
1457 << A->getAsString(Args) << "-fptrauth-returns";
1458 }
1459
1460 CmdArgs.push_back(
1461 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1462 if (Scope != "none")
1463 CmdArgs.push_back(
1464 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1465 if (BranchProtectionPAuthLR)
1466 CmdArgs.push_back(
1467 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1468 if (IndirectBranches)
1469 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1470
1471 if (GuardedControlStack)
1472 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1473}
1474
1475void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1476 ArgStringList &CmdArgs, bool KernelOrKext) const {
1477 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1478
1479 // Determine floating point ABI from the options & target defaults.
1480 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1481 if (ABI == arm::FloatABI::Soft) {
1482 // Floating point operations and argument passing are soft.
1483 // FIXME: This changes CPP defines, we need -target-soft-float.
1484 CmdArgs.push_back(Elt: "-msoft-float");
1485 CmdArgs.push_back(Elt: "-mfloat-abi");
1486 CmdArgs.push_back(Elt: "soft");
1487 } else if (ABI == arm::FloatABI::SoftFP) {
1488 // Floating point operations are hard, but argument passing is soft.
1489 CmdArgs.push_back(Elt: "-mfloat-abi");
1490 CmdArgs.push_back(Elt: "soft");
1491 } else {
1492 // Floating point operations and argument passing are hard.
1493 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1494 CmdArgs.push_back(Elt: "-mfloat-abi");
1495 CmdArgs.push_back(Elt: "hard");
1496 }
1497
1498 // Forward the -mglobal-merge option for explicit control over the pass.
1499 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1500 Ids: options::OPT_mno_global_merge)) {
1501 CmdArgs.push_back(Elt: "-mllvm");
1502 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1503 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1504 else
1505 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1506 }
1507
1508 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1509 Neg: options::OPT_mno_implicit_float, Default: true))
1510 CmdArgs.push_back(Elt: "-no-implicit-float");
1511
1512 if (Args.getLastArg(Ids: options::OPT_mcmse))
1513 CmdArgs.push_back(Elt: "-mcmse");
1514
1515 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1516
1517 // Enable/disable return address signing and indirect branch targets.
1518 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1519
1520 AddUnalignedAccessWarning(CmdArgs);
1521}
1522
1523void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1524 const ArgList &Args, bool KernelOrKext,
1525 ArgStringList &CmdArgs) const {
1526 const ToolChain &TC = getToolChain();
1527
1528 // Add the target features
1529 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1530
1531 // Add target specific flags.
1532 switch (TC.getArch()) {
1533 default:
1534 break;
1535
1536 case llvm::Triple::arm:
1537 case llvm::Triple::armeb:
1538 case llvm::Triple::thumb:
1539 case llvm::Triple::thumbeb:
1540 // Use the effective triple, which takes into account the deployment target.
1541 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1542 break;
1543
1544 case llvm::Triple::aarch64:
1545 case llvm::Triple::aarch64_32:
1546 case llvm::Triple::aarch64_be:
1547 AddAArch64TargetArgs(Args, CmdArgs);
1548 break;
1549
1550 case llvm::Triple::loongarch32:
1551 case llvm::Triple::loongarch64:
1552 AddLoongArchTargetArgs(Args, CmdArgs);
1553 break;
1554
1555 case llvm::Triple::mips:
1556 case llvm::Triple::mipsel:
1557 case llvm::Triple::mips64:
1558 case llvm::Triple::mips64el:
1559 AddMIPSTargetArgs(Args, CmdArgs);
1560 break;
1561
1562 case llvm::Triple::ppc:
1563 case llvm::Triple::ppcle:
1564 case llvm::Triple::ppc64:
1565 case llvm::Triple::ppc64le:
1566 AddPPCTargetArgs(Args, CmdArgs);
1567 break;
1568
1569 case llvm::Triple::riscv32:
1570 case llvm::Triple::riscv64:
1571 case llvm::Triple::riscv32be:
1572 case llvm::Triple::riscv64be:
1573 AddRISCVTargetArgs(Args, CmdArgs);
1574 break;
1575
1576 case llvm::Triple::sparc:
1577 case llvm::Triple::sparcel:
1578 case llvm::Triple::sparcv9:
1579 AddSparcTargetArgs(Args, CmdArgs);
1580 break;
1581
1582 case llvm::Triple::systemz:
1583 AddSystemZTargetArgs(Args, CmdArgs);
1584 break;
1585
1586 case llvm::Triple::x86:
1587 case llvm::Triple::x86_64:
1588 AddX86TargetArgs(Args, CmdArgs);
1589 break;
1590
1591 case llvm::Triple::lanai:
1592 AddLanaiTargetArgs(Args, CmdArgs);
1593 break;
1594
1595 case llvm::Triple::hexagon:
1596 AddHexagonTargetArgs(Args, CmdArgs);
1597 break;
1598
1599 case llvm::Triple::wasm32:
1600 case llvm::Triple::wasm64:
1601 AddWebAssemblyTargetArgs(Args, CmdArgs);
1602 break;
1603
1604 case llvm::Triple::ve:
1605 AddVETargetArgs(Args, CmdArgs);
1606 break;
1607 }
1608}
1609
1610namespace {
1611void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1612 ArgStringList &CmdArgs) {
1613 const char *ABIName = nullptr;
1614 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1615 ABIName = A->getValue();
1616 else if (Triple.isOSDarwin())
1617 ABIName = "darwinpcs";
1618 // TODO: we probably want to have some target hook here.
1619 else if (Triple.isOSLinux() &&
1620 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1621 ABIName = "pauthtest";
1622 else
1623 ABIName = "aapcs";
1624
1625 CmdArgs.push_back(Elt: "-target-abi");
1626 CmdArgs.push_back(Elt: ABIName);
1627}
1628}
1629
1630void Clang::AddAArch64TargetArgs(const ArgList &Args,
1631 ArgStringList &CmdArgs) const {
1632 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1633
1634 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1635 Args.hasArg(Ids: options::OPT_mkernel) ||
1636 Args.hasArg(Ids: options::OPT_fapple_kext))
1637 CmdArgs.push_back(Elt: "-disable-red-zone");
1638
1639 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1640 Neg: options::OPT_mno_implicit_float, Default: true))
1641 CmdArgs.push_back(Elt: "-no-implicit-float");
1642
1643 RenderAArch64ABI(Triple, Args, CmdArgs);
1644
1645 // Forward the -mglobal-merge option for explicit control over the pass.
1646 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1647 Ids: options::OPT_mno_global_merge)) {
1648 CmdArgs.push_back(Elt: "-mllvm");
1649 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1650 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1651 else
1652 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1653 }
1654
1655 // Handle -msve_vector_bits=<bits>
1656 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1657 StringRef VScaleMax) {
1658 StringRef Val = A->getValue();
1659 const Driver &D = getToolChain().getDriver();
1660 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1661 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1662 Val == "1024+" || Val == "2048+") {
1663 unsigned Bits = 0;
1664 if (!Val.consume_back(Suffix: "+")) {
1665 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1666 (void)Invalid;
1667 assert(!Invalid && "Failed to parse value");
1668 CmdArgs.push_back(
1669 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1670 }
1671
1672 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1673 (void)Invalid;
1674 assert(!Invalid && "Failed to parse value");
1675
1676 CmdArgs.push_back(
1677 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1678 } else if (Val == "scalable") {
1679 // Silently drop requests for vector-length agnostic code as it's implied.
1680 } else {
1681 // Handle the unsupported values passed to msve-vector-bits.
1682 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1683 << A->getSpelling() << Val;
1684 }
1685 };
1686 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1687 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1688 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1689 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1690
1691 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1692
1693 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1694 CmdArgs.push_back(Elt: "-tune-cpu");
1695 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
1696 }
1697
1698 AddUnalignedAccessWarning(CmdArgs);
1699
1700 if (Triple.isOSDarwin() ||
1701 (Triple.isOSLinux() &&
1702 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1703 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1704 Neg: options::OPT_fno_ptrauth_intrinsics);
1705 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1706 Neg: options::OPT_fno_ptrauth_calls);
1707 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1708 Neg: options::OPT_fno_ptrauth_returns);
1709 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1710 Neg: options::OPT_fno_ptrauth_auth_traps);
1711 Args.addOptInFlag(
1712 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1713 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1714 Args.addOptInFlag(
1715 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1716 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1717 Args.addOptInFlag(
1718 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1719 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1720 Args.addOptInFlag(
1721 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1722 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1723 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1724 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1725 }
1726 if (Triple.isOSLinux() &&
1727 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1728 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1729 Neg: options::OPT_fno_ptrauth_init_fini);
1730 Args.addOptInFlag(
1731 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1732 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1733 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1734 Neg: options::OPT_fno_ptrauth_elf_got);
1735 }
1736 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1737 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1738
1739 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1740 Neg: options::OPT_fno_ptrauth_objc_isa);
1741 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1742 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1743 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1744 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1745
1746 // Enable/disable return address signing and indirect branch targets.
1747 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1748}
1749
1750void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1751 ArgStringList &CmdArgs) const {
1752 const llvm::Triple &Triple = getToolChain().getTriple();
1753
1754 CmdArgs.push_back(Elt: "-target-abi");
1755 CmdArgs.push_back(
1756 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1757 .data());
1758
1759 // Handle -mtune.
1760 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1761 std::string TuneCPU = A->getValue();
1762 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1763 CmdArgs.push_back(Elt: "-tune-cpu");
1764 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1765 }
1766
1767 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1768 Ids: options::OPT_mno_annotate_tablejump)) {
1769 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1770 CmdArgs.push_back(Elt: "-mllvm");
1771 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1772 }
1773 }
1774}
1775
1776void Clang::AddMIPSTargetArgs(const ArgList &Args,
1777 ArgStringList &CmdArgs) const {
1778 const Driver &D = getToolChain().getDriver();
1779 StringRef CPUName;
1780 StringRef ABIName;
1781 const llvm::Triple &Triple = getToolChain().getTriple();
1782 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1783
1784 CmdArgs.push_back(Elt: "-target-abi");
1785 CmdArgs.push_back(Elt: ABIName.data());
1786
1787 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1788 if (ABI == mips::FloatABI::Soft) {
1789 // Floating point operations and argument passing are soft.
1790 CmdArgs.push_back(Elt: "-msoft-float");
1791 CmdArgs.push_back(Elt: "-mfloat-abi");
1792 CmdArgs.push_back(Elt: "soft");
1793 } else {
1794 // Floating point operations and argument passing are hard.
1795 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1796 CmdArgs.push_back(Elt: "-mfloat-abi");
1797 CmdArgs.push_back(Elt: "hard");
1798 }
1799
1800 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1801 Ids: options::OPT_mno_ldc1_sdc1)) {
1802 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1803 CmdArgs.push_back(Elt: "-mllvm");
1804 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1805 }
1806 }
1807
1808 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1809 Ids: options::OPT_mno_check_zero_division)) {
1810 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1811 CmdArgs.push_back(Elt: "-mllvm");
1812 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1813 }
1814 }
1815
1816 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1817 CmdArgs.push_back(Elt: "-mllvm");
1818 CmdArgs.push_back(Elt: "-mfix4300");
1819 }
1820
1821 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1822 StringRef v = A->getValue();
1823 CmdArgs.push_back(Elt: "-mllvm");
1824 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1825 A->claim();
1826 }
1827
1828 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1829 Arg *ABICalls =
1830 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1831
1832 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1833 // -mgpopt is the default for static, -fno-pic environments but these two
1834 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1835 // the only case where -mllvm -mgpopt is passed.
1836 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1837 // passed explicitly when compiling something with -mabicalls
1838 // (implictly) in affect. Currently the warning is in the backend.
1839 //
1840 // When the ABI in use is N64, we also need to determine the PIC mode that
1841 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1842 bool NoABICalls =
1843 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1844
1845 llvm::Reloc::Model RelocationModel;
1846 unsigned PICLevel;
1847 bool IsPIE;
1848 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1849 ParsePICArgs(ToolChain: getToolChain(), Args);
1850
1851 NoABICalls = NoABICalls ||
1852 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1853
1854 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1855 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1856 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1857 CmdArgs.push_back(Elt: "-mllvm");
1858 CmdArgs.push_back(Elt: "-mgpopt");
1859
1860 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1861 Ids: options::OPT_mno_local_sdata);
1862 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1863 Ids: options::OPT_mno_extern_sdata);
1864 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1865 Ids: options::OPT_mno_embedded_data);
1866 if (LocalSData) {
1867 CmdArgs.push_back(Elt: "-mllvm");
1868 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1869 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1870 } else {
1871 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1872 }
1873 LocalSData->claim();
1874 }
1875
1876 if (ExternSData) {
1877 CmdArgs.push_back(Elt: "-mllvm");
1878 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1879 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1880 } else {
1881 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1882 }
1883 ExternSData->claim();
1884 }
1885
1886 if (EmbeddedData) {
1887 CmdArgs.push_back(Elt: "-mllvm");
1888 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1889 CmdArgs.push_back(Elt: "-membedded-data=1");
1890 } else {
1891 CmdArgs.push_back(Elt: "-membedded-data=0");
1892 }
1893 EmbeddedData->claim();
1894 }
1895
1896 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1897 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1898
1899 if (GPOpt)
1900 GPOpt->claim();
1901
1902 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1903 StringRef Val = StringRef(A->getValue());
1904 if (mips::hasCompactBranches(CPU&: CPUName)) {
1905 if (Val == "never" || Val == "always" || Val == "optimal") {
1906 CmdArgs.push_back(Elt: "-mllvm");
1907 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1908 } else
1909 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1910 << A->getSpelling() << Val;
1911 } else
1912 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
1913 }
1914
1915 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
1916 Ids: options::OPT_mno_relax_pic_calls)) {
1917 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
1918 CmdArgs.push_back(Elt: "-mllvm");
1919 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1920 }
1921 }
1922}
1923
1924void Clang::AddPPCTargetArgs(const ArgList &Args,
1925 ArgStringList &CmdArgs) const {
1926 const Driver &D = getToolChain().getDriver();
1927 const llvm::Triple &T = getToolChain().getTriple();
1928 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1929 CmdArgs.push_back(Elt: "-tune-cpu");
1930 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
1931 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU.str()));
1932 }
1933
1934 // Select the ABI to use.
1935 const char *ABIName = nullptr;
1936 if (T.isOSBinFormatELF()) {
1937 switch (getToolChain().getArch()) {
1938 case llvm::Triple::ppc64: {
1939 if (T.isPPC64ELFv2ABI())
1940 ABIName = "elfv2";
1941 else
1942 ABIName = "elfv1";
1943 break;
1944 }
1945 case llvm::Triple::ppc64le:
1946 ABIName = "elfv2";
1947 break;
1948 default:
1949 break;
1950 }
1951 }
1952
1953 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1954 bool VecExtabi = false;
1955 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
1956 StringRef V = A->getValue();
1957 if (V == "ieeelongdouble") {
1958 IEEELongDouble = true;
1959 A->claim();
1960 } else if (V == "ibmlongdouble") {
1961 IEEELongDouble = false;
1962 A->claim();
1963 } else if (V == "vec-default") {
1964 VecExtabi = false;
1965 A->claim();
1966 } else if (V == "vec-extabi") {
1967 VecExtabi = true;
1968 A->claim();
1969 } else if (V == "elfv1") {
1970 ABIName = "elfv1";
1971 A->claim();
1972 } else if (V == "elfv2") {
1973 ABIName = "elfv2";
1974 A->claim();
1975 } else if (V != "altivec")
1976 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1977 // the option if given as we don't have backend support for any targets
1978 // that don't use the altivec abi.
1979 ABIName = A->getValue();
1980 }
1981 if (IEEELongDouble)
1982 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
1983 if (VecExtabi) {
1984 if (!T.isOSAIX())
1985 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1986 << "-mabi=vec-extabi" << T.str();
1987 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
1988 }
1989
1990 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
1991 CmdArgs.push_back(Elt: "-disable-red-zone");
1992
1993 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1994 if (FloatABI == ppc::FloatABI::Soft) {
1995 // Floating point operations and argument passing are soft.
1996 CmdArgs.push_back(Elt: "-msoft-float");
1997 CmdArgs.push_back(Elt: "-mfloat-abi");
1998 CmdArgs.push_back(Elt: "soft");
1999 } else {
2000 // Floating point operations and argument passing are hard.
2001 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2002 CmdArgs.push_back(Elt: "-mfloat-abi");
2003 CmdArgs.push_back(Elt: "hard");
2004 }
2005
2006 if (ABIName) {
2007 CmdArgs.push_back(Elt: "-target-abi");
2008 CmdArgs.push_back(Elt: ABIName);
2009 }
2010}
2011
2012void Clang::AddRISCVTargetArgs(const ArgList &Args,
2013 ArgStringList &CmdArgs) const {
2014 const llvm::Triple &Triple = getToolChain().getTriple();
2015 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2016
2017 CmdArgs.push_back(Elt: "-target-abi");
2018 CmdArgs.push_back(Elt: ABIName.data());
2019
2020 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2021 CmdArgs.push_back(Elt: "-msmall-data-limit");
2022 CmdArgs.push_back(Elt: A->getValue());
2023 }
2024
2025 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2026 Neg: options::OPT_mno_implicit_float, Default: true))
2027 CmdArgs.push_back(Elt: "-no-implicit-float");
2028
2029 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2030 CmdArgs.push_back(Elt: "-tune-cpu");
2031 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2032 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2033 else
2034 CmdArgs.push_back(Elt: A->getValue());
2035 }
2036
2037 // Handle -mrvv-vector-bits=<bits>
2038 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2039 StringRef Val = A->getValue();
2040 const Driver &D = getToolChain().getDriver();
2041
2042 // Get minimum VLen from march.
2043 unsigned MinVLen = 0;
2044 std::string Arch = riscv::getRISCVArch(Args, Triple);
2045 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2046 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2047 // Ignore parsing error.
2048 if (!errorToBool(Err: ISAInfo.takeError()))
2049 MinVLen = (*ISAInfo)->getMinVLen();
2050
2051 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2052 // as integer as long as we have a MinVLen.
2053 unsigned Bits = 0;
2054 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2055 Bits = MinVLen;
2056 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2057 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2058 // at least MinVLen.
2059 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2060 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2061 Bits = 0;
2062 }
2063
2064 // If we got a valid value try to use it.
2065 if (Bits != 0) {
2066 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2067 CmdArgs.push_back(
2068 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2069 CmdArgs.push_back(
2070 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2071 } else if (Val != "scalable") {
2072 // Handle the unsupported values passed to mrvv-vector-bits.
2073 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2074 << A->getSpelling() << Val;
2075 }
2076 }
2077}
2078
2079void Clang::AddSparcTargetArgs(const ArgList &Args,
2080 ArgStringList &CmdArgs) const {
2081 sparc::FloatABI FloatABI =
2082 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2083
2084 if (FloatABI == sparc::FloatABI::Soft) {
2085 // Floating point operations and argument passing are soft.
2086 CmdArgs.push_back(Elt: "-msoft-float");
2087 CmdArgs.push_back(Elt: "-mfloat-abi");
2088 CmdArgs.push_back(Elt: "soft");
2089 } else {
2090 // Floating point operations and argument passing are hard.
2091 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2092 CmdArgs.push_back(Elt: "-mfloat-abi");
2093 CmdArgs.push_back(Elt: "hard");
2094 }
2095
2096 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2097 StringRef Name = A->getValue();
2098 std::string TuneCPU;
2099 if (Name == "native")
2100 TuneCPU = std::string(llvm::sys::getHostCPUName());
2101 else
2102 TuneCPU = std::string(Name);
2103
2104 CmdArgs.push_back(Elt: "-tune-cpu");
2105 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2106 }
2107}
2108
2109void Clang::AddSystemZTargetArgs(const ArgList &Args,
2110 ArgStringList &CmdArgs) const {
2111 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2112 CmdArgs.push_back(Elt: "-tune-cpu");
2113 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2114 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2115 else
2116 CmdArgs.push_back(Elt: A->getValue());
2117 }
2118
2119 bool HasBackchain =
2120 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2121 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2122 Neg: options::OPT_mno_packed_stack, Default: false);
2123 systemz::FloatABI FloatABI =
2124 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2125 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2126 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2127 const Driver &D = getToolChain().getDriver();
2128 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2129 << "-mpacked-stack -mbackchain -mhard-float";
2130 }
2131 if (HasBackchain)
2132 CmdArgs.push_back(Elt: "-mbackchain");
2133 if (HasPackedStack)
2134 CmdArgs.push_back(Elt: "-mpacked-stack");
2135 if (HasSoftFloat) {
2136 // Floating point operations and argument passing are soft.
2137 CmdArgs.push_back(Elt: "-msoft-float");
2138 CmdArgs.push_back(Elt: "-mfloat-abi");
2139 CmdArgs.push_back(Elt: "soft");
2140 }
2141}
2142
2143void Clang::AddX86TargetArgs(const ArgList &Args,
2144 ArgStringList &CmdArgs) const {
2145 const Driver &D = getToolChain().getDriver();
2146 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2147
2148 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2149 Args.hasArg(Ids: options::OPT_mkernel) ||
2150 Args.hasArg(Ids: options::OPT_fapple_kext))
2151 CmdArgs.push_back(Elt: "-disable-red-zone");
2152
2153 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2154 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2155 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2156
2157 // Default to avoid implicit floating-point for kernel/kext code, but allow
2158 // that to be overridden with -mno-soft-float.
2159 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2160 Args.hasArg(Ids: options::OPT_fapple_kext));
2161 if (Arg *A = Args.getLastArg(
2162 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2163 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2164 const Option &O = A->getOption();
2165 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2166 O.matches(ID: options::OPT_msoft_float));
2167 }
2168 if (NoImplicitFloat)
2169 CmdArgs.push_back(Elt: "-no-implicit-float");
2170
2171 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2172 StringRef Value = A->getValue();
2173 if (Value == "intel" || Value == "att") {
2174 CmdArgs.push_back(Elt: "-mllvm");
2175 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2176 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2177 } else {
2178 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2179 << A->getSpelling() << Value;
2180 }
2181 } else if (D.IsCLMode()) {
2182 CmdArgs.push_back(Elt: "-mllvm");
2183 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2184 }
2185
2186 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2187 Ids: options::OPT_mno_skip_rax_setup))
2188 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2189 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2190
2191 // Set flags to support MCU ABI.
2192 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2193 CmdArgs.push_back(Elt: "-mfloat-abi");
2194 CmdArgs.push_back(Elt: "soft");
2195 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2196 }
2197
2198 // Handle -mtune.
2199
2200 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2201 std::string TuneCPU;
2202 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2203 TuneCPU = "generic";
2204
2205 // Override based on -mtune.
2206 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2207 StringRef Name = A->getValue();
2208
2209 if (Name == "native") {
2210 Name = llvm::sys::getHostCPUName();
2211 if (!Name.empty())
2212 TuneCPU = std::string(Name);
2213 } else
2214 TuneCPU = std::string(Name);
2215 }
2216
2217 if (!TuneCPU.empty()) {
2218 CmdArgs.push_back(Elt: "-tune-cpu");
2219 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2220 }
2221}
2222
2223void Clang::AddHexagonTargetArgs(const ArgList &Args,
2224 ArgStringList &CmdArgs) const {
2225 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2226 CmdArgs.push_back(Elt: "-Wreturn-type");
2227
2228 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2229 CmdArgs.push_back(Elt: "-mllvm");
2230 CmdArgs.push_back(
2231 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2232 }
2233
2234 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2235 CmdArgs.push_back(Elt: "-fshort-enums");
2236 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2237 CmdArgs.push_back(Elt: "-mllvm");
2238 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2239 }
2240 CmdArgs.push_back(Elt: "-mllvm");
2241 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2242}
2243
2244void Clang::AddLanaiTargetArgs(const ArgList &Args,
2245 ArgStringList &CmdArgs) const {
2246 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2247 StringRef CPUName = A->getValue();
2248
2249 CmdArgs.push_back(Elt: "-target-cpu");
2250 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2251 }
2252 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2253 StringRef Value = A->getValue();
2254 // Only support mregparm=4 to support old usage. Report error for all other
2255 // cases.
2256 int Mregparm;
2257 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2258 if (Mregparm != 4) {
2259 getToolChain().getDriver().Diag(
2260 DiagID: diag::err_drv_unsupported_option_argument)
2261 << A->getSpelling() << Value;
2262 }
2263 }
2264 }
2265}
2266
2267void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2268 ArgStringList &CmdArgs) const {
2269 // Default to "hidden" visibility.
2270 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2271 Ids: options::OPT_fvisibility_ms_compat))
2272 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2273}
2274
2275void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2276 // Floating point operations and argument passing are hard.
2277 CmdArgs.push_back(Elt: "-mfloat-abi");
2278 CmdArgs.push_back(Elt: "hard");
2279}
2280
2281void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2282 StringRef Target, const InputInfo &Output,
2283 const InputInfo &Input, const ArgList &Args) const {
2284 // If this is a dry run, do not create the compilation database file.
2285 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2286 return;
2287
2288 using llvm::yaml::escape;
2289 const Driver &D = getToolChain().getDriver();
2290
2291 if (!CompilationDatabase) {
2292 std::error_code EC;
2293 auto File = std::make_unique<llvm::raw_fd_ostream>(
2294 args&: Filename, args&: EC,
2295 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2296 if (EC) {
2297 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2298 << EC.message();
2299 return;
2300 }
2301 CompilationDatabase = std::move(File);
2302 }
2303 auto &CDB = *CompilationDatabase;
2304 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2305 if (!CWD)
2306 CWD = ".";
2307 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2308 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2309 if (Output.isFilename())
2310 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2311 CDB << ", \"arguments\": [\"" << escape(Input: D.ClangExecutable) << "\"";
2312 SmallString<128> Buf;
2313 Buf = "-x";
2314 Buf += types::getTypeName(Id: Input.getType());
2315 CDB << ", \"" << escape(Input: Buf) << "\"";
2316 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2317 Buf = "--sysroot=";
2318 Buf += D.SysRoot;
2319 CDB << ", \"" << escape(Input: Buf) << "\"";
2320 }
2321 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2322 if (Output.isFilename())
2323 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2324 for (auto &A: Args) {
2325 auto &O = A->getOption();
2326 // Skip language selection, which is positional.
2327 if (O.getID() == options::OPT_x)
2328 continue;
2329 // Skip writing dependency output and the compilation database itself.
2330 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2331 continue;
2332 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2333 continue;
2334 // Skip inputs.
2335 if (O.getKind() == Option::InputClass)
2336 continue;
2337 // Skip output.
2338 if (O.getID() == options::OPT_o)
2339 continue;
2340 // All other arguments are quoted and appended.
2341 ArgStringList ASL;
2342 A->render(Args, Output&: ASL);
2343 for (auto &it: ASL)
2344 CDB << ", \"" << escape(Input: it) << "\"";
2345 }
2346 Buf = "--target=";
2347 Buf += Target;
2348 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2349}
2350
2351void Clang::DumpCompilationDatabaseFragmentToDir(
2352 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2353 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2354 // If this is a dry run, do not create the compilation database file.
2355 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2356 return;
2357
2358 if (CompilationDatabase)
2359 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2360
2361 SmallString<256> Path = Dir;
2362 const auto &Driver = C.getDriver();
2363 Driver.getVFS().makeAbsolute(Path);
2364 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2365 if (Err) {
2366 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2367 return;
2368 }
2369
2370 llvm::sys::path::append(
2371 path&: Path,
2372 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2373 int FD;
2374 SmallString<256> TempPath;
2375 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2376 Flags: llvm::sys::fs::OF_Text);
2377 if (Err) {
2378 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2379 return;
2380 }
2381 CompilationDatabase =
2382 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2383 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2384}
2385
2386static bool CheckARMImplicitITArg(StringRef Value) {
2387 return Value == "always" || Value == "never" || Value == "arm" ||
2388 Value == "thumb";
2389}
2390
2391static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2392 StringRef Value) {
2393 CmdArgs.push_back(Elt: "-mllvm");
2394 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2395}
2396
2397static void CollectArgsForIntegratedAssembler(Compilation &C,
2398 const ArgList &Args,
2399 ArgStringList &CmdArgs,
2400 const Driver &D) {
2401 // Default to -mno-relax-all.
2402 //
2403 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2404 // cannot be done by assembler branch relaxation as it needs a free temporary
2405 // register. Because of this, branch relaxation is handled by a MachineIR pass
2406 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2407 // MachineIR branch relaxation inaccurate and it will miss cases where an
2408 // indirect branch is necessary.
2409 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2410 Neg: options::OPT_mno_relax_all);
2411
2412 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mincremental_linker_compatible,
2413 Ids: options::OPT_mno_incremental_linker_compatible);
2414
2415 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2416
2417 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2418 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2419
2420 // If you add more args here, also add them to the block below that
2421 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2422
2423 // When passing -I arguments to the assembler we sometimes need to
2424 // unconditionally take the next argument. For example, when parsing
2425 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2426 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2427 // arg after parsing the '-I' arg.
2428 bool TakeNextArg = false;
2429
2430 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2431 bool IsELF = Triple.isOSBinFormatELF();
2432 bool Crel = false, ExperimentalCrel = false;
2433 StringRef RelocSectionSym;
2434 bool SFrame = false, ExperimentalSFrame = false;
2435 bool ImplicitMapSyms = false;
2436 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2437 bool UseNoExecStack = false;
2438 bool Msa = false;
2439 const char *MipsTargetFeature = nullptr;
2440 llvm::SmallVector<const char *> SparcTargetFeatures;
2441 StringRef ImplicitIt;
2442 for (const Arg *A :
2443 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2444 Ids: options::OPT_mimplicit_it_EQ)) {
2445 A->claim();
2446
2447 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2448 switch (C.getDefaultToolChain().getArch()) {
2449 case llvm::Triple::arm:
2450 case llvm::Triple::armeb:
2451 case llvm::Triple::thumb:
2452 case llvm::Triple::thumbeb:
2453 // Only store the value; the last value set takes effect.
2454 ImplicitIt = A->getValue();
2455 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2456 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2457 << A->getSpelling() << ImplicitIt;
2458 continue;
2459 default:
2460 break;
2461 }
2462 }
2463
2464 for (StringRef Value : A->getValues()) {
2465 if (TakeNextArg) {
2466 CmdArgs.push_back(Elt: Value.data());
2467 TakeNextArg = false;
2468 continue;
2469 }
2470
2471 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2472 Value == "-mbig-obj")
2473 continue; // LLVM handles bigobj automatically
2474
2475 auto Equal = Value.split(Separator: '=');
2476 auto checkArg = [&](bool ValidTarget,
2477 std::initializer_list<const char *> Set) {
2478 if (!ValidTarget) {
2479 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2480 << (Twine("-Wa,") + Equal.first + "=").str()
2481 << Triple.getTriple();
2482 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2483 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2484 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2485 }
2486 };
2487 switch (C.getDefaultToolChain().getArch()) {
2488 default:
2489 break;
2490 case llvm::Triple::x86:
2491 case llvm::Triple::x86_64:
2492 if (Equal.first == "-mrelax-relocations" ||
2493 Equal.first == "--mrelax-relocations") {
2494 UseRelaxRelocations = Equal.second == "yes";
2495 checkArg(IsELF, {"yes", "no"});
2496 continue;
2497 }
2498 if (Value == "-msse2avx") {
2499 CmdArgs.push_back(Elt: "-msse2avx");
2500 continue;
2501 }
2502 break;
2503 case llvm::Triple::wasm32:
2504 case llvm::Triple::wasm64:
2505 if (Value == "--no-type-check") {
2506 CmdArgs.push_back(Elt: "-mno-type-check");
2507 continue;
2508 }
2509 break;
2510 case llvm::Triple::thumb:
2511 case llvm::Triple::thumbeb:
2512 case llvm::Triple::arm:
2513 case llvm::Triple::armeb:
2514 if (Equal.first == "-mimplicit-it") {
2515 // Only store the value; the last value set takes effect.
2516 ImplicitIt = Equal.second;
2517 checkArg(true, {"always", "never", "arm", "thumb"});
2518 continue;
2519 }
2520 if (Value == "-mthumb")
2521 // -mthumb has already been processed in ComputeLLVMTriple()
2522 // recognize but skip over here.
2523 continue;
2524 break;
2525 case llvm::Triple::aarch64:
2526 case llvm::Triple::aarch64_be:
2527 case llvm::Triple::aarch64_32:
2528 if (Equal.first == "-mmapsyms") {
2529 ImplicitMapSyms = Equal.second == "implicit";
2530 checkArg(IsELF, {"default", "implicit"});
2531 continue;
2532 }
2533 break;
2534 case llvm::Triple::mips:
2535 case llvm::Triple::mipsel:
2536 case llvm::Triple::mips64:
2537 case llvm::Triple::mips64el:
2538 if (Value == "--trap") {
2539 CmdArgs.push_back(Elt: "-target-feature");
2540 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2541 continue;
2542 }
2543 if (Value == "--break") {
2544 CmdArgs.push_back(Elt: "-target-feature");
2545 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2546 continue;
2547 }
2548 if (Value.starts_with(Prefix: "-msoft-float")) {
2549 CmdArgs.push_back(Elt: "-target-feature");
2550 CmdArgs.push_back(Elt: "+soft-float");
2551 continue;
2552 }
2553 if (Value.starts_with(Prefix: "-mhard-float")) {
2554 CmdArgs.push_back(Elt: "-target-feature");
2555 CmdArgs.push_back(Elt: "-soft-float");
2556 continue;
2557 }
2558 if (Value == "-mmsa") {
2559 Msa = true;
2560 continue;
2561 }
2562 if (Value == "-mno-msa") {
2563 Msa = false;
2564 continue;
2565 }
2566 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2567 .Case(S: "-mips1", Value: "+mips1")
2568 .Case(S: "-mips2", Value: "+mips2")
2569 .Case(S: "-mips3", Value: "+mips3")
2570 .Case(S: "-mips4", Value: "+mips4")
2571 .Case(S: "-mips5", Value: "+mips5")
2572 .Case(S: "-mips32", Value: "+mips32")
2573 .Case(S: "-mips32r2", Value: "+mips32r2")
2574 .Case(S: "-mips32r3", Value: "+mips32r3")
2575 .Case(S: "-mips32r5", Value: "+mips32r5")
2576 .Case(S: "-mips32r6", Value: "+mips32r6")
2577 .Case(S: "-mips64", Value: "+mips64")
2578 .Case(S: "-mips64r2", Value: "+mips64r2")
2579 .Case(S: "-mips64r3", Value: "+mips64r3")
2580 .Case(S: "-mips64r5", Value: "+mips64r5")
2581 .Case(S: "-mips64r6", Value: "+mips64r6")
2582 .Default(Value: nullptr);
2583 if (MipsTargetFeature)
2584 continue;
2585 break;
2586
2587 case llvm::Triple::sparc:
2588 case llvm::Triple::sparcel:
2589 case llvm::Triple::sparcv9:
2590 if (Value == "--undeclared-regs") {
2591 // LLVM already allows undeclared use of G registers, so this option
2592 // becomes a no-op. This solely exists for GNU compatibility.
2593 // TODO implement --no-undeclared-regs
2594 continue;
2595 }
2596 SparcTargetFeatures =
2597 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2598 .Case(S: "-Av8", Value: {"-v8plus"})
2599 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2600 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2601 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2602 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2603 .Case(S: "-Av9", Value: {"+v9"})
2604 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2605 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2606 .Case(S: "-Av9d", Value: {"+v9", "+vis", "+vis2", "+vis3"})
2607 .Default(Value: {});
2608 if (!SparcTargetFeatures.empty())
2609 continue;
2610 break;
2611 }
2612
2613 if (Value == "-force_cpusubtype_ALL") {
2614 // Do nothing, this is the default and we don't support anything else.
2615 } else if (Value == "-L") {
2616 CmdArgs.push_back(Elt: "-msave-temp-labels");
2617 } else if (Value == "--fatal-warnings") {
2618 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2619 } else if (Value == "--no-warn" || Value == "-W") {
2620 CmdArgs.push_back(Elt: "-massembler-no-warn");
2621 } else if (Value == "--noexecstack") {
2622 UseNoExecStack = true;
2623 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2624 Value.starts_with(Prefix: "--compress-debug-sections") ||
2625 Value == "-nocompress-debug-sections" ||
2626 Value == "--nocompress-debug-sections") {
2627 CmdArgs.push_back(Elt: Value.data());
2628 } else if (Value == "--crel") {
2629 Crel = true;
2630 } else if (Value == "--no-crel") {
2631 Crel = false;
2632 } else if (Value == "--allow-experimental-crel") {
2633 ExperimentalCrel = true;
2634 } else if (Value.starts_with(Prefix: "--reloc-section-sym=")) {
2635 RelocSectionSym = Value.substr(Start: strlen(s: "--reloc-section-sym="));
2636 } else if (Value.starts_with(Prefix: "-I")) {
2637 CmdArgs.push_back(Elt: Value.data());
2638 // We need to consume the next argument if the current arg is a plain
2639 // -I. The next arg will be the include directory.
2640 if (Value == "-I")
2641 TakeNextArg = true;
2642 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2643 // "-gdwarf-N" options are not cc1as options.
2644 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2645 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2646 CmdArgs.push_back(Elt: Value.data());
2647 } else {
2648 RenderDebugEnablingArgs(Args, CmdArgs,
2649 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2650 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2651 }
2652 } else if (Value == "--gsframe") {
2653 SFrame = true;
2654 } else if (Value == "--allow-experimental-sframe") {
2655 ExperimentalSFrame = true;
2656 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2657 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2658 // Do nothing, we'll validate it later.
2659 } else if (Value == "-defsym" || Value == "--defsym") {
2660 if (A->getNumValues() != 2) {
2661 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2662 break;
2663 }
2664 const char *S = A->getValue(N: 1);
2665 auto Pair = StringRef(S).split(Separator: '=');
2666 auto Sym = Pair.first;
2667 auto SVal = Pair.second;
2668
2669 if (Sym.empty() || SVal.empty()) {
2670 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2671 break;
2672 }
2673 int64_t IVal;
2674 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2675 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2676 break;
2677 }
2678 CmdArgs.push_back(Elt: "--defsym");
2679 TakeNextArg = true;
2680 } else if (Value == "-fdebug-compilation-dir") {
2681 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2682 TakeNextArg = true;
2683 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2684 // The flag is a -Wa / -Xassembler argument and Options doesn't
2685 // parse the argument, so this isn't automatically aliased to
2686 // -fdebug-compilation-dir (without '=') here.
2687 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2688 CmdArgs.push_back(Elt: Value.data());
2689 } else if (Value == "--version") {
2690 D.PrintVersion(C, OS&: llvm::outs());
2691 } else {
2692 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2693 << A->getSpelling() << Value;
2694 }
2695 }
2696 }
2697 if (ImplicitIt.size())
2698 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2699 if (Crel) {
2700 if (!ExperimentalCrel)
2701 D.Diag(DiagID: diag::err_drv_experimental_crel);
2702 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2703 CmdArgs.push_back(Elt: "--crel");
2704 } else {
2705 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2706 << "-Wa,--crel" << D.getTargetTriple();
2707 }
2708 }
2709 if (!RelocSectionSym.empty()) {
2710 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2711 RelocSectionSym != "none")
2712 D.Diag(DiagID: diag::err_drv_invalid_value)
2713 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2714 << RelocSectionSym;
2715 else if (Triple.isOSBinFormatELF())
2716 CmdArgs.push_back(
2717 Elt: Args.MakeArgString(Str: "--reloc-section-sym=" + RelocSectionSym));
2718 else
2719 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2720 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2721 }
2722 if (SFrame) {
2723 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2724 if (!ExperimentalSFrame)
2725 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2726 else
2727 CmdArgs.push_back(Elt: "--gsframe");
2728 } else {
2729 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2730 << "-Wa,--gsframe" << D.getTargetTriple();
2731 }
2732 }
2733 if (ImplicitMapSyms)
2734 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2735 if (Msa)
2736 CmdArgs.push_back(Elt: "-mmsa");
2737 if (!UseRelaxRelocations)
2738 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2739 if (UseNoExecStack)
2740 CmdArgs.push_back(Elt: "-mnoexecstack");
2741 if (MipsTargetFeature != nullptr) {
2742 CmdArgs.push_back(Elt: "-target-feature");
2743 CmdArgs.push_back(Elt: MipsTargetFeature);
2744 }
2745
2746 for (const char *Feature : SparcTargetFeatures) {
2747 CmdArgs.push_back(Elt: "-target-feature");
2748 CmdArgs.push_back(Elt: Feature);
2749 }
2750
2751 // forward -fembed-bitcode to assmebler
2752 if (C.getDriver().embedBitcodeEnabled() ||
2753 C.getDriver().embedBitcodeMarkerOnly())
2754 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2755
2756 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2757 CmdArgs.push_back(Elt: "-as-secure-log-file");
2758 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2759 }
2760}
2761
2762static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2763 bool OFastEnabled, const ArgList &Args,
2764 ArgStringList &CmdArgs,
2765 const JobAction &JA) {
2766 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2767 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2768 llvm::StringLiteral("SLEEF")};
2769 bool NoMathErrnoWasImpliedByVecLib = false;
2770 const Arg *VecLibArg = nullptr;
2771 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2772 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2773
2774 // Handle various floating point optimization flags, mapping them to the
2775 // appropriate LLVM code generation flags. This is complicated by several
2776 // "umbrella" flags, so we do this by stepping through the flags incrementally
2777 // adjusting what we think is enabled/disabled, then at the end setting the
2778 // LLVM flags based on the final state.
2779 bool HonorINFs = true;
2780 bool HonorNaNs = true;
2781 bool ApproxFunc = false;
2782 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2783 bool MathErrno = TC.IsMathErrnoDefault();
2784 bool AssociativeMath = false;
2785 bool ReciprocalMath = false;
2786 bool SignedZeros = true;
2787 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2788 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2789 // overriden by ffp-exception-behavior?
2790 bool RoundingFPMath = false;
2791 // -ffp-model values: strict, fast, precise
2792 StringRef FPModel = "";
2793 // -ffp-exception-behavior options: strict, maytrap, ignore
2794 StringRef FPExceptionBehavior = "";
2795 // -ffp-eval-method options: double, extended, source
2796 StringRef FPEvalMethod = "";
2797 llvm::DenormalMode DenormalFPMath =
2798 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2799 llvm::DenormalMode DenormalFP32Math =
2800 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
2801
2802 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2803 // If one wasn't given by the user, don't pass it here.
2804 StringRef FPContract;
2805 StringRef LastSeenFfpContractOption;
2806 StringRef LastFpContractOverrideOption;
2807 bool SeenUnsafeMathModeOption = false;
2808 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2809 !JA.isOffloading(OKind: Action::OFK_HIP))
2810 FPContract = "on";
2811 bool StrictFPModel = false;
2812 StringRef Float16ExcessPrecision = "";
2813 StringRef BFloat16ExcessPrecision = "";
2814 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2815 std::string ComplexRangeStr;
2816 StringRef LastComplexRangeOption;
2817
2818 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2819 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2820 if (Aggressive) {
2821 HonorINFs = false;
2822 HonorNaNs = false;
2823 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2824 LastOpt&: LastComplexRangeOption, Range);
2825 } else {
2826 HonorINFs = true;
2827 HonorNaNs = true;
2828 setComplexRange(D, NewOpt: CallerOption,
2829 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
2830 LastOpt&: LastComplexRangeOption, Range);
2831 }
2832 MathErrno = false;
2833 AssociativeMath = true;
2834 ReciprocalMath = true;
2835 ApproxFunc = true;
2836 SignedZeros = false;
2837 TrappingMath = false;
2838 RoundingFPMath = false;
2839 FPExceptionBehavior = "";
2840 FPContract = "fast";
2841 SeenUnsafeMathModeOption = true;
2842 };
2843
2844 // Lambda to consolidate common handling for fp-contract
2845 auto restoreFPContractState = [&]() {
2846 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2847 // For other targets, if the state has been changed by one of the
2848 // unsafe-math umbrella options a subsequent -fno-fast-math or
2849 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2850 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2851 // option. If we have not seen an unsafe-math option or -ffp-contract,
2852 // we leave the FPContract state unchanged.
2853 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2854 !JA.isOffloading(OKind: Action::OFK_HIP)) {
2855 if (LastSeenFfpContractOption != "")
2856 FPContract = LastSeenFfpContractOption;
2857 else if (SeenUnsafeMathModeOption)
2858 FPContract = "on";
2859 }
2860 // In this case, we're reverting to the last explicit fp-contract option
2861 // or the platform default
2862 LastFpContractOverrideOption = "";
2863 };
2864
2865 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
2866 CmdArgs.push_back(Elt: "-mlimit-float-precision");
2867 CmdArgs.push_back(Elt: A->getValue());
2868 }
2869
2870 for (const Arg *A : Args) {
2871 llvm::scope_exit CheckMathErrnoForVecLib(
2872 [&, MathErrnoBeforeArg = MathErrno] {
2873 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
2874 ArgThatEnabledMathErrnoAfterVecLib = A;
2875 });
2876
2877 switch (A->getOption().getID()) {
2878 // If this isn't an FP option skip the claim below
2879 default: continue;
2880
2881 case options::OPT_fcx_limited_range:
2882 setComplexRange(D, NewOpt: A->getSpelling(),
2883 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2884 LastOpt&: LastComplexRangeOption, Range);
2885 break;
2886 case options::OPT_fno_cx_limited_range:
2887 setComplexRange(D, NewOpt: A->getSpelling(),
2888 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2889 LastOpt&: LastComplexRangeOption, Range);
2890 break;
2891 case options::OPT_fcx_fortran_rules:
2892 setComplexRange(D, NewOpt: A->getSpelling(),
2893 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
2894 LastOpt&: LastComplexRangeOption, Range);
2895 break;
2896 case options::OPT_fno_cx_fortran_rules:
2897 setComplexRange(D, NewOpt: A->getSpelling(),
2898 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2899 LastOpt&: LastComplexRangeOption, Range);
2900 break;
2901 case options::OPT_fcomplex_arithmetic_EQ: {
2902 LangOptions::ComplexRangeKind RangeVal;
2903 StringRef Val = A->getValue();
2904 if (Val == "full")
2905 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
2906 else if (Val == "improved")
2907 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
2908 else if (Val == "promoted")
2909 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
2910 else if (Val == "basic")
2911 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
2912 else {
2913 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2914 << A->getSpelling() << Val;
2915 break;
2916 }
2917 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
2918 LastOpt&: LastComplexRangeOption, Range);
2919 break;
2920 }
2921 case options::OPT_ffp_model_EQ: {
2922 // If -ffp-model= is seen, reset to fno-fast-math
2923 HonorINFs = true;
2924 HonorNaNs = true;
2925 ApproxFunc = false;
2926 // Turning *off* -ffast-math restores the toolchain default.
2927 MathErrno = TC.IsMathErrnoDefault();
2928 AssociativeMath = false;
2929 ReciprocalMath = false;
2930 SignedZeros = true;
2931
2932 StringRef Val = A->getValue();
2933 if (OFastEnabled && Val != "aggressive") {
2934 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
2935 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2936 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
2937 break;
2938 }
2939 StrictFPModel = false;
2940 if (!FPModel.empty() && FPModel != Val)
2941 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2942 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
2943 << Args.MakeArgString(Str: "-ffp-model=" + Val);
2944 if (Val == "fast") {
2945 FPModel = Val;
2946 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
2947 // applyFastMath sets fp-contract="fast"
2948 LastFpContractOverrideOption = "-ffp-model=fast";
2949 } else if (Val == "aggressive") {
2950 FPModel = Val;
2951 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
2952 // applyFastMath sets fp-contract="fast"
2953 LastFpContractOverrideOption = "-ffp-model=aggressive";
2954 } else if (Val == "precise") {
2955 FPModel = Val;
2956 FPContract = "on";
2957 LastFpContractOverrideOption = "-ffp-model=precise";
2958 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2959 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2960 LastOpt&: LastComplexRangeOption, Range);
2961 } else if (Val == "strict") {
2962 StrictFPModel = true;
2963 FPExceptionBehavior = "strict";
2964 FPModel = Val;
2965 FPContract = "off";
2966 LastFpContractOverrideOption = "-ffp-model=strict";
2967 TrappingMath = true;
2968 RoundingFPMath = true;
2969 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2970 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2971 LastOpt&: LastComplexRangeOption, Range);
2972 } else
2973 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2974 << A->getSpelling() << Val;
2975 break;
2976 }
2977
2978 // Options controlling individual features
2979 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2980 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2981 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2982 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2983 case options::OPT_fapprox_func: ApproxFunc = true; break;
2984 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2985 case options::OPT_fmath_errno: MathErrno = true; break;
2986 case options::OPT_fno_math_errno: MathErrno = false; break;
2987 case options::OPT_fassociative_math: AssociativeMath = true; break;
2988 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2989 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2990 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2991 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2992 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2993 case options::OPT_ftrapping_math:
2994 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2995 FPExceptionBehavior != "strict")
2996 // Warn that previous value of option is overridden.
2997 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2998 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
2999 FPExceptionBehavior)
3000 << "-ftrapping-math";
3001 TrappingMath = true;
3002 TrappingMathPresent = true;
3003 FPExceptionBehavior = "strict";
3004 break;
3005 case options::OPT_fveclib:
3006 VecLibArg = A;
3007 NoMathErrnoWasImpliedByVecLib =
3008 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
3009 if (NoMathErrnoWasImpliedByVecLib)
3010 MathErrno = false;
3011 break;
3012 case options::OPT_fno_trapping_math:
3013 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3014 FPExceptionBehavior != "ignore")
3015 // Warn that previous value of option is overridden.
3016 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3017 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3018 FPExceptionBehavior)
3019 << "-fno-trapping-math";
3020 TrappingMath = false;
3021 TrappingMathPresent = true;
3022 FPExceptionBehavior = "ignore";
3023 break;
3024
3025 case options::OPT_frounding_math:
3026 RoundingFPMath = true;
3027 break;
3028
3029 case options::OPT_fno_rounding_math:
3030 RoundingFPMath = false;
3031 break;
3032
3033 case options::OPT_fdenormal_fp_math_EQ:
3034 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3035 DenormalFP32Math = DenormalFPMath;
3036 if (!DenormalFPMath.isValid()) {
3037 D.Diag(DiagID: diag::err_drv_invalid_value)
3038 << A->getAsString(Args) << A->getValue();
3039 }
3040 break;
3041
3042 case options::OPT_fdenormal_fp_math_f32_EQ:
3043 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3044 if (!DenormalFP32Math.isValid()) {
3045 D.Diag(DiagID: diag::err_drv_invalid_value)
3046 << A->getAsString(Args) << A->getValue();
3047 }
3048 break;
3049
3050 // Validate and pass through -ffp-contract option.
3051 case options::OPT_ffp_contract: {
3052 StringRef Val = A->getValue();
3053 if (Val == "fast" || Val == "on" || Val == "off" ||
3054 Val == "fast-honor-pragmas") {
3055 if (Val != FPContract && LastFpContractOverrideOption != "") {
3056 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3057 << LastFpContractOverrideOption
3058 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3059 }
3060
3061 FPContract = Val;
3062 LastSeenFfpContractOption = Val;
3063 LastFpContractOverrideOption = "";
3064 } else
3065 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3066 << A->getSpelling() << Val;
3067 break;
3068 }
3069
3070 // Validate and pass through -ffp-exception-behavior option.
3071 case options::OPT_ffp_exception_behavior_EQ: {
3072 StringRef Val = A->getValue();
3073 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3074 FPExceptionBehavior != Val)
3075 // Warn that previous value of option is overridden.
3076 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3077 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3078 FPExceptionBehavior)
3079 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3080 TrappingMath = TrappingMathPresent = false;
3081 if (Val == "ignore" || Val == "maytrap")
3082 FPExceptionBehavior = Val;
3083 else if (Val == "strict") {
3084 FPExceptionBehavior = Val;
3085 TrappingMath = TrappingMathPresent = true;
3086 } else
3087 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3088 << A->getSpelling() << Val;
3089 break;
3090 }
3091
3092 // Validate and pass through -ffp-eval-method option.
3093 case options::OPT_ffp_eval_method_EQ: {
3094 StringRef Val = A->getValue();
3095 if (Val == "double" || Val == "extended" || Val == "source")
3096 FPEvalMethod = Val;
3097 else
3098 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3099 << A->getSpelling() << Val;
3100 break;
3101 }
3102
3103 case options::OPT_fexcess_precision_EQ: {
3104 StringRef Val = A->getValue();
3105 const llvm::Triple::ArchType Arch = TC.getArch();
3106 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3107 if (Val == "standard" || Val == "fast")
3108 Float16ExcessPrecision = Val;
3109 // To make it GCC compatible, allow the value of "16" which
3110 // means disable excess precision, the same meaning than clang's
3111 // equivalent value "none".
3112 else if (Val == "16")
3113 Float16ExcessPrecision = "none";
3114 else
3115 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3116 << A->getSpelling() << Val;
3117 } else {
3118 if (!(Val == "standard" || Val == "fast"))
3119 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3120 << A->getSpelling() << Val;
3121 }
3122 BFloat16ExcessPrecision = Float16ExcessPrecision;
3123 break;
3124 }
3125 case options::OPT_ffinite_math_only:
3126 HonorINFs = false;
3127 HonorNaNs = false;
3128 break;
3129 case options::OPT_fno_finite_math_only:
3130 HonorINFs = true;
3131 HonorNaNs = true;
3132 break;
3133
3134 case options::OPT_funsafe_math_optimizations:
3135 AssociativeMath = true;
3136 ReciprocalMath = true;
3137 SignedZeros = false;
3138 ApproxFunc = true;
3139 TrappingMath = false;
3140 FPExceptionBehavior = "";
3141 FPContract = "fast";
3142 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3143 SeenUnsafeMathModeOption = true;
3144 break;
3145 case options::OPT_fno_unsafe_math_optimizations:
3146 AssociativeMath = false;
3147 ReciprocalMath = false;
3148 SignedZeros = true;
3149 ApproxFunc = false;
3150 restoreFPContractState();
3151 break;
3152
3153 case options::OPT_Ofast:
3154 // If -Ofast is the optimization level, then -ffast-math should be enabled
3155 if (!OFastEnabled)
3156 continue;
3157 [[fallthrough]];
3158 case options::OPT_ffast_math:
3159 applyFastMath(true, A->getSpelling());
3160 if (A->getOption().getID() == options::OPT_Ofast)
3161 LastFpContractOverrideOption = "-Ofast";
3162 else
3163 LastFpContractOverrideOption = "-ffast-math";
3164 break;
3165 case options::OPT_fno_fast_math:
3166 HonorINFs = true;
3167 HonorNaNs = true;
3168 // Turning on -ffast-math (with either flag) removes the need for
3169 // MathErrno. However, turning *off* -ffast-math merely restores the
3170 // toolchain default (which may be false).
3171 MathErrno = TC.IsMathErrnoDefault();
3172 AssociativeMath = false;
3173 ReciprocalMath = false;
3174 ApproxFunc = false;
3175 SignedZeros = true;
3176 restoreFPContractState();
3177 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3178 setComplexRange(D, NewOpt: A->getSpelling(),
3179 NewRange: LangOptions::ComplexRangeKind::CX_None,
3180 LastOpt&: LastComplexRangeOption, Range);
3181 else
3182 Range = LangOptions::ComplexRangeKind::CX_None;
3183 LastComplexRangeOption = "";
3184 LastFpContractOverrideOption = "";
3185 break;
3186 } // End switch (A->getOption().getID())
3187
3188 // The StrictFPModel local variable is needed to report warnings
3189 // in the way we intend. If -ffp-model=strict has been used, we
3190 // want to report a warning for the next option encountered that
3191 // takes us out of the settings described by fp-model=strict, but
3192 // we don't want to continue issuing warnings for other conflicting
3193 // options after that.
3194 if (StrictFPModel) {
3195 // If -ffp-model=strict has been specified on command line but
3196 // subsequent options conflict then emit warning diagnostic.
3197 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3198 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3199 FPContract == "off")
3200 // OK: Current Arg doesn't conflict with -ffp-model=strict
3201 ;
3202 else {
3203 StrictFPModel = false;
3204 FPModel = "";
3205 // The warning for -ffp-contract would have been reported by the
3206 // OPT_ffp_contract_EQ handler above. A special check here is needed
3207 // to avoid duplicating the warning.
3208 auto RHS = (A->getNumValues() == 0)
3209 ? A->getSpelling()
3210 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3211 if (A->getSpelling() != "-ffp-contract=") {
3212 if (RHS != "-ffp-model=strict")
3213 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3214 << "-ffp-model=strict" << RHS;
3215 }
3216 }
3217 }
3218
3219 // If we handled this option claim it
3220 A->claim();
3221 }
3222
3223 if (!HonorINFs)
3224 CmdArgs.push_back(Elt: "-menable-no-infs");
3225
3226 if (!HonorNaNs)
3227 CmdArgs.push_back(Elt: "-menable-no-nans");
3228
3229 if (ApproxFunc)
3230 CmdArgs.push_back(Elt: "-fapprox-func");
3231
3232 if (MathErrno) {
3233 CmdArgs.push_back(Elt: "-fmath-errno");
3234 if (NoMathErrnoWasImpliedByVecLib)
3235 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3236 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3237 << VecLibArg->getAsString(Args);
3238 }
3239
3240 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3241 !TrappingMath)
3242 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3243
3244 if (!SignedZeros)
3245 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3246
3247 if (AssociativeMath && !SignedZeros && !TrappingMath)
3248 CmdArgs.push_back(Elt: "-mreassociate");
3249
3250 if (ReciprocalMath)
3251 CmdArgs.push_back(Elt: "-freciprocal-math");
3252
3253 if (TrappingMath) {
3254 // FP Exception Behavior is also set to strict
3255 assert(FPExceptionBehavior == "strict");
3256 }
3257
3258 // The default is IEEE.
3259 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3260 llvm::SmallString<64> DenormFlag;
3261 llvm::raw_svector_ostream ArgStr(DenormFlag);
3262 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3263 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3264 }
3265
3266 // Add f32 specific denormal mode flag if it's different.
3267 if (DenormalFP32Math != DenormalFPMath) {
3268 llvm::SmallString<64> DenormFlag;
3269 llvm::raw_svector_ostream ArgStr(DenormFlag);
3270 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3271 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3272 }
3273
3274 if (!FPContract.empty())
3275 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3276
3277 if (RoundingFPMath)
3278 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3279 else
3280 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3281
3282 if (!FPExceptionBehavior.empty())
3283 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3284 FPExceptionBehavior));
3285
3286 if (!FPEvalMethod.empty())
3287 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3288
3289 if (!Float16ExcessPrecision.empty())
3290 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3291 Float16ExcessPrecision));
3292 if (!BFloat16ExcessPrecision.empty())
3293 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3294 BFloat16ExcessPrecision));
3295
3296 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3297 if (!Recip.empty())
3298 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3299
3300 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3301 // individual features enabled by -ffast-math instead of the option itself as
3302 // that's consistent with gcc's behaviour.
3303 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3304 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3305 CmdArgs.push_back(Elt: "-ffast-math");
3306
3307 // Handle __FINITE_MATH_ONLY__ similarly.
3308 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3309 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3310 // -menable-no-nans are set by the user.
3311 bool shouldAddFiniteMathOnly = false;
3312 if (!HonorINFs && !HonorNaNs) {
3313 shouldAddFiniteMathOnly = true;
3314 } else {
3315 bool InfValues = true;
3316 bool NanValues = true;
3317 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3318 StringRef ArgValue = Arg->getValue();
3319 if (ArgValue == "-menable-no-nans")
3320 NanValues = false;
3321 else if (ArgValue == "-menable-no-infs")
3322 InfValues = false;
3323 }
3324 if (!NanValues && !InfValues)
3325 shouldAddFiniteMathOnly = true;
3326 }
3327 if (shouldAddFiniteMathOnly) {
3328 CmdArgs.push_back(Elt: "-ffinite-math-only");
3329 }
3330 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3331 CmdArgs.push_back(Elt: "-mfpmath");
3332 CmdArgs.push_back(Elt: A->getValue());
3333 }
3334
3335 // Disable a codegen optimization for floating-point casts.
3336 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3337 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3338 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3339
3340 if (Range != LangOptions::ComplexRangeKind::CX_None)
3341 ComplexRangeStr = renderComplexRangeOption(Range);
3342 if (!ComplexRangeStr.empty()) {
3343 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3344 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3345 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3346 complexRangeKindToStr(Range)));
3347 }
3348 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3349 CmdArgs.push_back(Elt: "-fcx-limited-range");
3350 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3351 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3352 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3353 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3354 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3355 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3356}
3357
3358static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3359 const llvm::Triple &Triple,
3360 const InputInfo &Input) {
3361 // Add default argument set.
3362 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3363 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3364 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3365
3366 if (!Triple.isWindowsMSVCEnvironment()) {
3367 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3368 } else {
3369 // Enable "unix" checkers that also work on Windows.
3370 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3371 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3372 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3373 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3374 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3375 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3376 }
3377
3378 // Disable some unix checkers for PS4/PS5.
3379 if (Triple.isPS()) {
3380 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3381 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3382 }
3383
3384 if (Triple.isOSDarwin()) {
3385 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3386 CmdArgs.push_back(
3387 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3388 }
3389 else if (Triple.isOSFuchsia())
3390 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3391
3392 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3393
3394 if (types::isCXX(Id: Input.getType()))
3395 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3396
3397 if (!Triple.isPS()) {
3398 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3399 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3400 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3401 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3402 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3403 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3404 }
3405
3406 // Default nullability checks.
3407 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3408 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3409 }
3410
3411 // Set the output format. The default is plist, for (lame) historical reasons.
3412 CmdArgs.push_back(Elt: "-analyzer-output");
3413 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3414 CmdArgs.push_back(Elt: A->getValue());
3415 else
3416 CmdArgs.push_back(Elt: "plist");
3417
3418 // Disable the presentation of standard compiler warnings when using
3419 // --analyze. We only want to show static analyzer diagnostics or frontend
3420 // errors.
3421 CmdArgs.push_back(Elt: "-w");
3422
3423 // Add -Xanalyzer arguments when running as analyzer.
3424 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3425}
3426
3427static bool isValidSymbolName(StringRef S) {
3428 if (S.empty())
3429 return false;
3430
3431 if (std::isdigit(S[0]))
3432 return false;
3433
3434 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3435}
3436
3437static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3438 const ArgList &Args, ArgStringList &CmdArgs,
3439 bool KernelOrKext) {
3440 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3441
3442 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3443 // doesn't even have a stack!
3444 if (EffectiveTriple.isNVPTX())
3445 return;
3446
3447 // -stack-protector=0 is default.
3448 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3449 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3450 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3451
3452 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3453 Ids: options::OPT_fstack_protector_all,
3454 Ids: options::OPT_fstack_protector_strong,
3455 Ids: options::OPT_fstack_protector)) {
3456 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3457 StackProtectorLevel =
3458 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3459 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3460 StackProtectorLevel = LangOptions::SSPStrong;
3461 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3462 StackProtectorLevel = LangOptions::SSPReq;
3463
3464 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3465 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3466 << A->getSpelling() << EffectiveTriple.getTriple();
3467 StackProtectorLevel = DefaultStackProtectorLevel;
3468 }
3469 } else {
3470 StackProtectorLevel = DefaultStackProtectorLevel;
3471 }
3472
3473 if (StackProtectorLevel) {
3474 CmdArgs.push_back(Elt: "-stack-protector");
3475 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3476 }
3477
3478 // --param ssp-buffer-size=
3479 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3480 StringRef Str(A->getValue());
3481 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3482 if (StackProtectorLevel) {
3483 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3484 // FIXME: Verify the argument is a valid integer.
3485 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3486 }
3487 A->claim();
3488 }
3489 }
3490
3491 const std::string &TripleStr = EffectiveTriple.getTriple();
3492 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3493 StringRef Value = A->getValue();
3494 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3495 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3496 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3497 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3498 << A->getAsString(Args) << TripleStr;
3499 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3500 EffectiveTriple.isThumb()) &&
3501 Value != "tls" && Value != "global") {
3502 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3503 << A->getOption().getName() << Value << "tls global";
3504 return;
3505 }
3506 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3507 Value == "tls") {
3508 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3509 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3510 << A->getAsString(Args);
3511 return;
3512 }
3513 // Check whether the target subarch supports the hardware TLS register
3514 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3515 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3516 << EffectiveTriple.getArchName();
3517 return;
3518 }
3519 // Check whether the user asked for something other than -mtp=cp15
3520 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3521 StringRef Value = A->getValue();
3522 if (Value != "cp15") {
3523 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3524 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3525 return;
3526 }
3527 }
3528 CmdArgs.push_back(Elt: "-target-feature");
3529 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3530 }
3531 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3532 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3533 << A->getOption().getName() << Value << "sysreg global";
3534 return;
3535 }
3536 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3537 if (Value != "tls" && Value != "global") {
3538 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3539 << A->getOption().getName() << Value << "tls global";
3540 return;
3541 }
3542 if (Value == "tls") {
3543 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3544 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3545 << A->getAsString(Args);
3546 return;
3547 }
3548 }
3549 }
3550 A->render(Args, Output&: CmdArgs);
3551 }
3552
3553 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3554 StringRef Value = A->getValue();
3555 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3556 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3557 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3558 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3559 << A->getAsString(Args) << TripleStr;
3560 int Offset;
3561 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3562 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3563 return;
3564 }
3565 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3566 (Offset < 0 || Offset > 0xfffff)) {
3567 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3568 << A->getOption().getName() << Value;
3569 return;
3570 }
3571 A->render(Args, Output&: CmdArgs);
3572 }
3573
3574 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3575 StringRef Value = A->getValue();
3576 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3577 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3578 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3579 << A->getAsString(Args) << TripleStr;
3580 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3581 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3582 << A->getOption().getName() << Value << "fs gs";
3583 return;
3584 }
3585 if (EffectiveTriple.isAArch64() &&
3586 llvm::StringSwitch<bool>(Value)
3587 .Cases(CaseStrings: {"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3588 "tpidr_el2", "far_el1", "far_el2"},
3589 Value: false)
3590 .Default(Value: true)) {
3591 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3592 << A->getOption().getName() << Value
3593 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3594 return;
3595 }
3596 if (EffectiveTriple.isRISCV() && Value != "tp") {
3597 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3598 << A->getOption().getName() << Value << "tp";
3599 return;
3600 }
3601 if (EffectiveTriple.isPPC64() && Value != "r13") {
3602 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3603 << A->getOption().getName() << Value << "r13";
3604 return;
3605 }
3606 if (EffectiveTriple.isPPC32() && Value != "r2") {
3607 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3608 << A->getOption().getName() << Value << "r2";
3609 return;
3610 }
3611 A->render(Args, Output&: CmdArgs);
3612 }
3613
3614 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3615 StringRef Value = A->getValue();
3616 if (!isValidSymbolName(S: Value)) {
3617 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3618 << A->getOption().getName() << "legal symbol name";
3619 return;
3620 }
3621 A->render(Args, Output&: CmdArgs);
3622 }
3623}
3624
3625static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3626 ArgStringList &CmdArgs) {
3627 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3628
3629 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3630 !EffectiveTriple.isOSFuchsia())
3631 return;
3632
3633 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3634 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3635 !EffectiveTriple.isRISCV())
3636 return;
3637
3638 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_clash_protection,
3639 Neg: options::OPT_fno_stack_clash_protection);
3640}
3641
3642static void RenderTrivialAutoVarInitOptions(const Driver &D,
3643 const ToolChain &TC,
3644 const ArgList &Args,
3645 ArgStringList &CmdArgs) {
3646 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3647 StringRef TrivialAutoVarInit = "";
3648
3649 for (const Arg *A : Args) {
3650 switch (A->getOption().getID()) {
3651 default:
3652 continue;
3653 case options::OPT_ftrivial_auto_var_init: {
3654 A->claim();
3655 StringRef Val = A->getValue();
3656 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3657 TrivialAutoVarInit = Val;
3658 else
3659 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3660 << A->getSpelling() << Val;
3661 break;
3662 }
3663 }
3664 }
3665
3666 if (TrivialAutoVarInit.empty())
3667 switch (DefaultTrivialAutoVarInit) {
3668 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3669 break;
3670 case LangOptions::TrivialAutoVarInitKind::Pattern:
3671 TrivialAutoVarInit = "pattern";
3672 break;
3673 case LangOptions::TrivialAutoVarInitKind::Zero:
3674 TrivialAutoVarInit = "zero";
3675 break;
3676 }
3677
3678 if (!TrivialAutoVarInit.empty()) {
3679 CmdArgs.push_back(
3680 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3681 }
3682
3683 if (Arg *A =
3684 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3685 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3686 StringRef(
3687 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3688 "uninitialized")
3689 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3690 A->claim();
3691 StringRef Val = A->getValue();
3692 if (std::stoi(str: Val.str()) <= 0)
3693 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3694 CmdArgs.push_back(
3695 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3696 }
3697
3698 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3699 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3700 StringRef(
3701 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3702 "uninitialized")
3703 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3704 A->claim();
3705 StringRef Val = A->getValue();
3706 if (std::stoi(str: Val.str()) <= 0)
3707 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3708 CmdArgs.push_back(
3709 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3710 }
3711}
3712
3713static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3714 types::ID InputType) {
3715 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3716 // for denormal flushing handling based on the target.
3717 const unsigned ForwardedArguments[] = {
3718 options::OPT_cl_opt_disable,
3719 options::OPT_cl_strict_aliasing,
3720 options::OPT_cl_single_precision_constant,
3721 options::OPT_cl_finite_math_only,
3722 options::OPT_cl_kernel_arg_info,
3723 options::OPT_cl_unsafe_math_optimizations,
3724 options::OPT_cl_fast_relaxed_math,
3725 options::OPT_cl_mad_enable,
3726 options::OPT_cl_no_signed_zeros,
3727 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3728 options::OPT_cl_uniform_work_group_size
3729 };
3730
3731 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3732 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3733 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3734 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
3735 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3736 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3737 }
3738
3739 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
3740 CmdArgs.push_back(Elt: "-menable-no-infs");
3741 CmdArgs.push_back(Elt: "-menable-no-nans");
3742 }
3743
3744 for (const auto &Arg : ForwardedArguments)
3745 if (const auto *A = Args.getLastArg(Ids: Arg))
3746 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
3747
3748 // Only add the default headers if we are compiling OpenCL sources.
3749 if ((types::isOpenCL(Id: InputType) ||
3750 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
3751 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
3752 CmdArgs.push_back(Elt: "-finclude-default-header");
3753 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3754 }
3755}
3756
3757static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3758 types::ID InputType) {
3759 const unsigned ForwardedArguments[] = {
3760 options::OPT_hlsl_all_resources_bound,
3761 options::OPT_dxil_validator_version,
3762 options::OPT_res_may_alias,
3763 options::OPT_D,
3764 options::OPT_I,
3765 options::OPT_O,
3766 options::OPT_emit_llvm,
3767 options::OPT_emit_obj,
3768 options::OPT_disable_llvm_passes,
3769 options::OPT_fnative_half_type,
3770 options::OPT_fnative_int16_type,
3771 options::OPT_fmatrix_memory_layout_EQ,
3772 options::OPT_hlsl_entrypoint,
3773 options::OPT_fdx_rootsignature_define,
3774 options::OPT_fdx_rootsignature_version,
3775 options::OPT_fhlsl_spv_use_unknown_image_format,
3776 options::OPT_fhlsl_spv_enable_maximal_reconvergence};
3777 if (!types::isHLSL(Id: InputType))
3778 return;
3779 for (const auto &Arg : ForwardedArguments)
3780 if (const auto *A = Args.getLastArg(Ids: Arg))
3781 A->renderAsInput(Args, Output&: CmdArgs);
3782 // Add the default headers if dxc_no_stdinc is not set.
3783 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
3784 !Args.hasArg(Ids: options::OPT_nostdinc))
3785 CmdArgs.push_back(Elt: "-finclude-default-header");
3786}
3787
3788static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3789 ArgStringList &CmdArgs, types::ID InputType) {
3790 if (!Args.hasArg(Ids: options::OPT_fopenacc))
3791 return;
3792
3793 CmdArgs.push_back(Elt: "-fopenacc");
3794}
3795
3796static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3797 const ArgList &Args, ArgStringList &CmdArgs) {
3798 // -fbuiltin is default unless -mkernel is used.
3799 bool UseBuiltins =
3800 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
3801 Default: !Args.hasArg(Ids: options::OPT_mkernel));
3802 if (!UseBuiltins)
3803 CmdArgs.push_back(Elt: "-fno-builtin");
3804
3805 // -ffreestanding implies -fno-builtin.
3806 if (Args.hasArg(Ids: options::OPT_ffreestanding))
3807 UseBuiltins = false;
3808
3809 // Process the -fno-builtin-* options.
3810 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
3811 A->claim();
3812
3813 // If -fno-builtin is specified, then there's no need to pass the option to
3814 // the frontend.
3815 if (UseBuiltins)
3816 A->render(Args, Output&: CmdArgs);
3817 }
3818}
3819
3820bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3821 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
3822 Twine Path{Str};
3823 Path.toVector(Out&: Result);
3824 return Path.getSingleStringRef() != "";
3825 }
3826 if (llvm::sys::path::cache_directory(result&: Result)) {
3827 llvm::sys::path::append(path&: Result, a: "clang");
3828 llvm::sys::path::append(path&: Result, a: "ModuleCache");
3829 return true;
3830 }
3831 return false;
3832}
3833
3834llvm::SmallString<256>
3835clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
3836 const char *BaseInput) {
3837 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
3838 return StringRef(ModuleOutputEQ->getValue());
3839
3840 SmallString<256> OutputPath;
3841 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
3842 FinalOutput && Args.hasArg(Ids: options::OPT_c))
3843 OutputPath = FinalOutput->getValue();
3844 else {
3845 llvm::sys::fs::current_path(result&: OutputPath);
3846 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
3847 }
3848
3849 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
3850 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
3851 return OutputPath;
3852}
3853
3854static bool RenderModulesOptions(Compilation &C, const Driver &D,
3855 const ArgList &Args, const InputInfo &Input,
3856 const InputInfo &Output, bool HaveStd20,
3857 ArgStringList &CmdArgs) {
3858 const bool IsCXX = types::isCXX(Id: Input.getType());
3859 const bool HaveStdCXXModules = IsCXX && HaveStd20;
3860 bool HaveModules = HaveStdCXXModules;
3861
3862 // -fmodules enables the use of precompiled modules (off by default).
3863 // Users can pass -fno-cxx-modules to turn off modules support for
3864 // C++/Objective-C++ programs.
3865 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
3866 Neg: options::OPT_fno_cxx_modules, Default: true);
3867 bool HaveClangModules = false;
3868 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
3869 if (AllowedInCXX || !IsCXX) {
3870 CmdArgs.push_back(Elt: "-fmodules");
3871 HaveClangModules = true;
3872 }
3873 }
3874
3875 HaveModules |= HaveClangModules;
3876
3877 if (HaveModules && !AllowedInCXX)
3878 CmdArgs.push_back(Elt: "-fno-cxx-modules");
3879
3880 // -fmodule-maps enables implicit reading of module map files. By default,
3881 // this is enabled if we are using Clang's flavor of precompiled modules.
3882 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
3883 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
3884 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
3885
3886 // -fmodules-decluse checks that modules used are declared so (off by default)
3887 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
3888 Neg: options::OPT_fno_modules_decluse);
3889
3890 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3891 // all #included headers are part of modules.
3892 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
3893 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
3894 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
3895
3896 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
3897 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
3898
3899 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3900 bool ImplicitModules = false;
3901 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
3902 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
3903 if (HaveModules)
3904 CmdArgs.push_back(Elt: "-fno-implicit-modules");
3905 } else if (HaveModules) {
3906 ImplicitModules = true;
3907 // -fmodule-cache-path specifies where our implicitly-built module files
3908 // should be written.
3909 SmallString<128> Path;
3910 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
3911 Path = A->getValue();
3912
3913 bool HasPath = true;
3914 if (C.isForDiagnostics()) {
3915 // When generating crash reports, we want to emit the modules along with
3916 // the reproduction sources, so we ignore any provided module path.
3917 Path = Output.getFilename();
3918 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
3919 llvm::sys::path::append(path&: Path, a: "modules");
3920 } else if (Path.empty()) {
3921 // No module path was provided: use the default.
3922 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
3923 }
3924
3925 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3926 // That being said, that failure is unlikely and not caching is harmless.
3927 if (HasPath) {
3928 const char Arg[] = "-fmodules-cache-path=";
3929 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
3930 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
3931 }
3932
3933 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fimplicit_modules_lock_timeout_EQ);
3934 }
3935
3936 if (HaveModules) {
3937 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
3938 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
3939 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
3940 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
3941 Neg: options::OPT_fno_modules_validate_input_files_content,
3942 Default: false))
3943 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
3944 }
3945
3946 // -fmodule-name specifies the module that is currently being built (or
3947 // used for header checking by -fmodule-maps).
3948 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
3949
3950 // -fmodule-map-file can be used to specify files containing module
3951 // definitions.
3952 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
3953
3954 // -fbuiltin-module-map can be used to load the clang
3955 // builtin headers modulemap file.
3956 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
3957 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3958 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
3959 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
3960 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
3961 CmdArgs.push_back(
3962 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
3963 }
3964
3965 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3966 // names to precompiled module files (the module is loaded only if used).
3967 // The -fmodule-file=<file> form can be used to unconditionally load
3968 // precompiled module files (whether used or not).
3969 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3970 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
3971
3972 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3973 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
3974 CmdArgs.push_back(Elt: Args.MakeArgString(
3975 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
3976 A->claim();
3977 }
3978 } else
3979 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
3980
3981 // When building modules and generating crashdumps, we need to dump a module
3982 // dependency VFS alongside the output.
3983 if (HaveClangModules && C.isForDiagnostics()) {
3984 SmallString<128> VFSDir(Output.getFilename());
3985 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
3986 // Add the cache directory as a temp so the crash diagnostics pick it up.
3987 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
3988
3989 llvm::sys::path::append(path&: VFSDir, a: "vfs");
3990 CmdArgs.push_back(Elt: "-module-dependency-dir");
3991 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
3992 }
3993
3994 if (HaveClangModules)
3995 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
3996
3997 // Pass through all -fmodules-ignore-macro arguments.
3998 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
3999 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
4000 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
4001
4002 if (HaveClangModules) {
4003 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
4004
4005 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
4006 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
4007 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
4008 << A->getAsString(Args) << "-fbuild-session-timestamp";
4009
4010 llvm::sys::fs::file_status Status;
4011 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
4012 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
4013 CmdArgs.push_back(Elt: Args.MakeArgString(
4014 Str: "-fbuild-session-timestamp=" +
4015 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4016 d: Status.getLastModificationTime().time_since_epoch())
4017 .count())));
4018 }
4019
4020 if (Args.getLastArg(
4021 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4022 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4023 Ids: options::OPT_fbuild_session_file))
4024 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4025
4026 Args.AddLastArg(Output&: CmdArgs,
4027 Ids: options::OPT_fmodules_validate_once_per_build_session);
4028 }
4029
4030 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4031 Neg: options::OPT_fno_modules_validate_system_headers,
4032 Default: ImplicitModules))
4033 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4034
4035 Args.AddLastArg(Output&: CmdArgs,
4036 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4037 } else {
4038 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4039 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4040 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4041 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4042 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4043 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4044 }
4045
4046 // FIXME: We provisionally don't check ODR violations for decls in the global
4047 // module fragment.
4048 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4049
4050 if (Input.getType() == driver::types::TY_CXXModule ||
4051 Input.getType() == driver::types::TY_PP_CXXModule) {
4052 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4053 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4054
4055 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4056 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4057 else if (!(Args.hasArg(Ids: options::OPT__precompile) ||
4058 Args.hasArg(Ids: options::OPT__precompile_reduced_bmi)) ||
4059 Args.hasArg(Ids: options::OPT_fmodule_output))
4060 // If --precompile is specified, we will always generate a module file if
4061 // we're compiling an importable module unit. This is fine even if the
4062 // compilation process won't reach the point of generating the module file
4063 // (e.g., in the preprocessing mode), since the attached flag
4064 // '-fmodule-output' is useless.
4065 //
4066 // But if '--precompile' is specified, it might be annoying to always
4067 // generate the module file as '--precompile' will generate the module
4068 // file anyway.
4069 CmdArgs.push_back(Elt: Args.MakeArgString(
4070 Str: "-fmodule-output=" +
4071 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4072 }
4073
4074 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4075 Args.hasArg(Ids: options::OPT__precompile) &&
4076 (!Args.hasArg(Ids: options::OPT_o) ||
4077 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4078 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4079 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4080 }
4081
4082 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4083 // other translation units than module units. This is more user friendly to
4084 // allow end uers to enable this feature without asking for help from build
4085 // systems.
4086 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4087 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4088
4089 // We need to include the case the input file is a module file here.
4090 // Since the default compilation model for C++ module interface unit will
4091 // create temporary module file and compile the temporary module file
4092 // to get the object file. Then the `-fmodule-output` flag will be
4093 // brought to the second compilation process. So we have to claim it for
4094 // the case too.
4095 if (Input.getType() == driver::types::TY_CXXModule ||
4096 Input.getType() == driver::types::TY_PP_CXXModule ||
4097 Input.getType() == driver::types::TY_ModuleFile) {
4098 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4099 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4100 }
4101
4102 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4103 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4104
4105 return HaveModules;
4106}
4107
4108static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4109 ArgStringList &CmdArgs) {
4110 // -fsigned-char is default.
4111 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4112 Ids: options::OPT_fno_signed_char,
4113 Ids: options::OPT_funsigned_char,
4114 Ids: options::OPT_fno_unsigned_char)) {
4115 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4116 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4117 CmdArgs.push_back(Elt: "-fno-signed-char");
4118 }
4119 } else if (!isSignedCharDefault(Triple: T)) {
4120 CmdArgs.push_back(Elt: "-fno-signed-char");
4121 }
4122
4123 // The default depends on the language standard.
4124 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4125
4126 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4127 Ids: options::OPT_fno_short_wchar)) {
4128 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4129 CmdArgs.push_back(Elt: "-fwchar-type=short");
4130 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4131 } else {
4132 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4133 CmdArgs.push_back(Elt: "-fwchar-type=int");
4134 if (T.isOSzOS() ||
4135 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4136 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4137 else
4138 CmdArgs.push_back(Elt: "-fsigned-wchar");
4139 }
4140 } else if (T.isOSzOS())
4141 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4142}
4143
4144static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4145 const llvm::Triple &T, const ArgList &Args,
4146 ObjCRuntime &Runtime, bool InferCovariantReturns,
4147 const InputInfo &Input, ArgStringList &CmdArgs) {
4148 const llvm::Triple::ArchType Arch = TC.getArch();
4149
4150 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4151 // is the default. Except for deployment target of 10.5, next runtime is
4152 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4153 if (Runtime.isNonFragile()) {
4154 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4155 Neg: options::OPT_fno_objc_legacy_dispatch,
4156 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4157 if (TC.UseObjCMixedDispatch())
4158 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4159 else
4160 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4161 }
4162 }
4163
4164 // Forward -fobjc-direct-precondition-thunk to cc1
4165 // Defaults to false and needs explict turn on for now
4166 // TODO: switch to default true and needs explict turn off in the future.
4167 // TODO: add support for other runtimes
4168 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4169 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4170 if (Runtime.isNeXTFamily()) {
4171 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4172 } else {
4173 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4174 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4175 }
4176 }
4177
4178 if (types::isObjC(Id: Input.getType())) {
4179 // Pass down -fobjc-msgsend-selector-stubs if present.
4180 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_selector_stubs,
4181 Neg: options::OPT_fno_objc_msgsend_selector_stubs, Default: false))
4182 CmdArgs.push_back(Elt: "-fobjc-msgsend-selector-stubs");
4183
4184 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4185 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_class_selector_stubs,
4186 Neg: options::OPT_fno_objc_msgsend_class_selector_stubs, Default: false))
4187 CmdArgs.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
4188 }
4189
4190 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4191 // to do Array/Dictionary subscripting by default.
4192 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4193 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4194 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4195
4196 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4197 // NOTE: This logic is duplicated in ToolChains.cpp.
4198 if (isObjCAutoRefCount(Args)) {
4199 TC.CheckObjCARC();
4200
4201 CmdArgs.push_back(Elt: "-fobjc-arc");
4202
4203 // FIXME: It seems like this entire block, and several around it should be
4204 // wrapped in isObjC, but for now we just use it here as this is where it
4205 // was being used previously.
4206 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4207 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4208 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4209 else
4210 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4211 }
4212
4213 // Allow the user to enable full exceptions code emission.
4214 // We default off for Objective-C, on for Objective-C++.
4215 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4216 Neg: options::OPT_fno_objc_arc_exceptions,
4217 /*Default=*/types::isCXX(Id: Input.getType())))
4218 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4219 }
4220
4221 // Silence warning for full exception code emission options when explicitly
4222 // set to use no ARC.
4223 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4224 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4225 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4226 }
4227
4228 // Allow the user to control whether messages can be converted to runtime
4229 // functions.
4230 if (types::isObjC(Id: Input.getType())) {
4231 auto *Arg = Args.getLastArg(
4232 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4233 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4234 if (Arg &&
4235 Arg->getOption().matches(
4236 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4237 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4238 }
4239
4240 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4241 // rewriter.
4242 if (InferCovariantReturns)
4243 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4244
4245 // Pass down -fobjc-weak or -fno-objc-weak if present.
4246 if (types::isObjC(Id: Input.getType())) {
4247 auto WeakArg =
4248 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4249 if (!WeakArg) {
4250 // nothing to do
4251 } else if (!Runtime.allowsWeak()) {
4252 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4253 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4254 } else {
4255 WeakArg->render(Args, Output&: CmdArgs);
4256 }
4257 }
4258
4259 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4260 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4261
4262 // Forward constant literal flags to cc1.
4263 if (types::isObjC(Id: Input.getType())) {
4264 bool EnableConstantLiterals =
4265 Args.hasFlag(Pos: options::OPT_fobjc_constant_literals,
4266 Neg: options::OPT_fno_objc_constant_literals,
4267 /*default=*/Default: true) &&
4268 Runtime.hasConstantLiteralClasses();
4269 if (EnableConstantLiterals)
4270 CmdArgs.push_back(Elt: "-fobjc-constant-literals");
4271 if (Args.hasFlag(Pos: options::OPT_fconstant_nsnumber_literals,
4272 Neg: options::OPT_fno_constant_nsnumber_literals,
4273 /*default=*/Default: true) &&
4274 EnableConstantLiterals)
4275 CmdArgs.push_back(Elt: "-fconstant-nsnumber-literals");
4276 if (Args.hasFlag(Pos: options::OPT_fconstant_nsarray_literals,
4277 Neg: options::OPT_fno_constant_nsarray_literals,
4278 /*default=*/Default: true) &&
4279 EnableConstantLiterals)
4280 CmdArgs.push_back(Elt: "-fconstant-nsarray-literals");
4281 if (Args.hasFlag(Pos: options::OPT_fconstant_nsdictionary_literals,
4282 Neg: options::OPT_fno_constant_nsdictionary_literals,
4283 /*default=*/Default: true) &&
4284 EnableConstantLiterals)
4285 CmdArgs.push_back(Elt: "-fconstant-nsdictionary-literals");
4286 }
4287}
4288
4289static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4290 ArgStringList &CmdArgs) {
4291 bool CaretDefault = true;
4292 bool ColumnDefault = true;
4293
4294 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4295 Ids: options::OPT__SLASH_diagnostics_column,
4296 Ids: options::OPT__SLASH_diagnostics_caret)) {
4297 switch (A->getOption().getID()) {
4298 case options::OPT__SLASH_diagnostics_caret:
4299 CaretDefault = true;
4300 ColumnDefault = true;
4301 break;
4302 case options::OPT__SLASH_diagnostics_column:
4303 CaretDefault = false;
4304 ColumnDefault = true;
4305 break;
4306 case options::OPT__SLASH_diagnostics_classic:
4307 CaretDefault = false;
4308 ColumnDefault = false;
4309 break;
4310 }
4311 }
4312
4313 // -fcaret-diagnostics is default.
4314 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4315 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4316 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4317
4318 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4319 Neg: options::OPT_fno_diagnostics_fixit_info);
4320 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4321 Neg: options::OPT_fno_diagnostics_show_option);
4322
4323 if (const Arg *A =
4324 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4325 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4326 CmdArgs.push_back(Elt: A->getValue());
4327 }
4328
4329 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4330 Neg: options::OPT_fno_diagnostics_show_hotness);
4331
4332 if (const Arg *A =
4333 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4334 std::string Opt =
4335 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4336 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4337 }
4338
4339 if (const Arg *A =
4340 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4341 std::string Opt =
4342 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4343 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4344 }
4345
4346 if (const Arg *A =
4347 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_inlining_chain,
4348 Ids: options::OPT_fno_diagnostics_show_inlining_chain)) {
4349 if (A->getOption().matches(ID: options::OPT_fdiagnostics_show_inlining_chain))
4350 CmdArgs.push_back(Elt: "-fdiagnostics-show-inlining-chain");
4351 else
4352 CmdArgs.push_back(Elt: "-fno-diagnostics-show-inlining-chain");
4353 }
4354
4355 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4356 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4357 CmdArgs.push_back(Elt: A->getValue());
4358 if (StringRef(A->getValue()) == "sarif" ||
4359 StringRef(A->getValue()) == "SARIF")
4360 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4361 }
4362
4363 if (const Arg *A = Args.getLastArg(
4364 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4365 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4366 const Option &O = A->getOption();
4367 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4368 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4369 else
4370 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4371 }
4372
4373 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4374
4375 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4376 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4377
4378 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4379 Neg: options::OPT_fno_show_source_location);
4380
4381 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4382 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4383
4384 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4385 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4386
4387 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4388 Default: ColumnDefault))
4389 CmdArgs.push_back(Elt: "-fno-show-column");
4390
4391 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4392 Neg: options::OPT_fno_spell_checking);
4393
4394 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4395}
4396
4397static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4398 const ArgList &Args, ArgStringList &CmdArgs,
4399 unsigned DwarfVersion) {
4400 auto *DwarfFormatArg =
4401 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4402 if (!DwarfFormatArg)
4403 return;
4404
4405 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4406 if (DwarfVersion < 3)
4407 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4408 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4409 else if (!T.isArch64Bit())
4410 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4411 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4412 else if (!T.isOSBinFormatELF())
4413 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4414 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4415 }
4416
4417 DwarfFormatArg->render(Args, Output&: CmdArgs);
4418}
4419
4420static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4421 const ArgList &Args) {
4422 bool NeedsSimpleTemplateNames =
4423 Args.hasFlag(Pos: options::OPT_gsimple_template_names,
4424 Neg: options::OPT_gno_simple_template_names,
4425 Default: TC.getDefaultDebugSimpleTemplateNames());
4426 if (!NeedsSimpleTemplateNames)
4427 return false;
4428
4429 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsimple_template_names))
4430 if (!checkDebugInfoOption(A, Args, D, TC))
4431 return false;
4432
4433 return true;
4434}
4435
4436static void
4437renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4438 const ArgList &Args, types::ID InputType,
4439 ArgStringList &CmdArgs, const InputInfo &Output,
4440 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4441 DwarfFissionKind &DwarfFission) {
4442 bool IRInput = isLLVMIR(Id: InputType);
4443 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4444 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4445 !isOpenCL(Id: InputType);
4446
4447 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4448
4449 // The 'g' groups options involve a somewhat intricate sequence of decisions
4450 // about what to pass from the driver to the frontend, but by the time they
4451 // reach cc1 they've been factored into three well-defined orthogonal choices:
4452 // * what level of debug info to generate
4453 // * what dwarf version to write
4454 // * what debugger tuning to use
4455 // This avoids having to monkey around further in cc1 other than to disable
4456 // codeview if not running in a Windows environment. Perhaps even that
4457 // decision should be made in the driver as well though.
4458 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4459
4460 bool SplitDWARFInlining =
4461 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4462 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4463
4464 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4465 // object file generation and no IR generation, -gN should not be needed. So
4466 // allow -gsplit-dwarf with either -gN or IR input.
4467 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4468 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4469 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4470 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4471 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4472 << TC.getTriple().str();
4473 return;
4474 }
4475 Arg *SplitDWARFArg;
4476 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4477 if (DwarfFission != DwarfFissionKind::None &&
4478 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4479 DwarfFission = DwarfFissionKind::None;
4480 SplitDWARFInlining = false;
4481 }
4482 }
4483 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4484 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4485
4486 // If the last option explicitly specified a debug-info level, use it.
4487 if (checkDebugInfoOption(A, Args, D, TC) &&
4488 A->getOption().matches(ID: options::OPT_gN_Group)) {
4489 DebugInfoKind = debugLevelToInfoKind(A: *A);
4490 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4491 // complicated if you've disabled inline info in the skeleton CUs
4492 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4493 // line-tables-only, so let those compose naturally in that case.
4494 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4495 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4496 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4497 SplitDWARFInlining))
4498 DwarfFission = DwarfFissionKind::None;
4499 }
4500 }
4501
4502 // If a debugger tuning argument appeared, remember it.
4503 bool HasDebuggerTuning = false;
4504 if (const Arg *A =
4505 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4506 HasDebuggerTuning = true;
4507 if (checkDebugInfoOption(A, Args, D, TC)) {
4508 if (A->getOption().matches(ID: options::OPT_glldb))
4509 DebuggerTuning = llvm::DebuggerKind::LLDB;
4510 else if (A->getOption().matches(ID: options::OPT_gsce))
4511 DebuggerTuning = llvm::DebuggerKind::SCE;
4512 else if (A->getOption().matches(ID: options::OPT_gdbx))
4513 DebuggerTuning = llvm::DebuggerKind::DBX;
4514 else
4515 DebuggerTuning = llvm::DebuggerKind::GDB;
4516 }
4517 }
4518
4519 // If a -gdwarf argument appeared, remember it.
4520 bool EmitDwarf = false;
4521 if (const Arg *A = getDwarfNArg(Args))
4522 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4523
4524 bool EmitCodeView = false;
4525 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4526 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4527
4528 // If the user asked for debug info but did not explicitly specify -gcodeview
4529 // or -gdwarf, ask the toolchain for the default format.
4530 if (!EmitCodeView && !EmitDwarf &&
4531 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4532 switch (TC.getDefaultDebugFormat()) {
4533 case llvm::codegenoptions::DIF_CodeView:
4534 EmitCodeView = true;
4535 break;
4536 case llvm::codegenoptions::DIF_DWARF:
4537 EmitDwarf = true;
4538 break;
4539 }
4540 }
4541
4542 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4543 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4544 // be lower than what the user wanted.
4545 if (EmitDwarf) {
4546 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4547 // Clamp effective DWARF version to the max supported by the toolchain.
4548 EffectiveDWARFVersion =
4549 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4550 } else {
4551 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4552 }
4553
4554 // -gline-directives-only supported only for the DWARF debug info.
4555 if (RequestedDWARFVersion == 0 &&
4556 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4557 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4558
4559 // strict DWARF is set to false by default. But for DBX, we need it to be set
4560 // as true by default.
4561 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4562 (void)checkDebugInfoOption(A, Args, D, TC);
4563 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4564 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4565 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4566
4567 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4568 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4569
4570 // Column info is included by default for everything except SCE and
4571 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4572 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4573 // practice, however, the Microsoft debuggers don't handle missing end columns
4574 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4575 // it's better not to include any column info.
4576 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4577 (void)checkDebugInfoOption(A, Args, D, TC);
4578 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4579 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4580 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4581 DebuggerTuning != llvm::DebuggerKind::DBX)))
4582 CmdArgs.push_back(Elt: "-gno-column-info");
4583
4584 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4585 Neg: options::OPT_gno_call_site_info, Default: true))
4586 CmdArgs.push_back(Elt: "-gno-call-site-info");
4587
4588 // FIXME: Move backend command line options to the module.
4589 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4590 // If -gline-tables-only or -gline-directives-only is the last option it
4591 // wins.
4592 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4593 TC)) {
4594 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4595 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4596 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4597 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4598 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4599 }
4600 }
4601 }
4602
4603 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4604 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4605
4606 // After we've dealt with all combinations of things that could
4607 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4608 // figure out if we need to "upgrade" it to standalone debug info.
4609 // We parse these two '-f' options whether or not they will be used,
4610 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4611 bool NeedFullDebug = Args.hasFlag(
4612 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4613 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4614 TC.GetDefaultStandaloneDebug());
4615 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4616 (void)checkDebugInfoOption(A, Args, D, TC);
4617
4618 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4619 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4620 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4621 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4622 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4623 else if (NeedFullDebug)
4624 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4625 }
4626
4627 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4628 Default: false)) {
4629 // Source embedding is a vendor extension to DWARF v5. By now we have
4630 // checked if a DWARF version was stated explicitly, and have otherwise
4631 // fallen back to the target default, so if this is still not at least 5
4632 // we emit an error.
4633 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4634 if (RequestedDWARFVersion < 5)
4635 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4636 << A->getAsString(Args) << "-gdwarf-5";
4637 else if (EffectiveDWARFVersion < 5)
4638 // The toolchain has reduced allowed dwarf version, so we can't enable
4639 // -gembed-source.
4640 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4641 << A->getAsString(Args) << TC.getTripleString() << 5
4642 << EffectiveDWARFVersion;
4643 else if (checkDebugInfoOption(A, Args, D, TC))
4644 CmdArgs.push_back(Elt: "-gembed-source");
4645 }
4646
4647 // Enable Key Instructions by default if we're emitting DWARF, the language is
4648 // plain C or C++, and optimisations are enabled.
4649 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4650 bool KeyInstructionsOnByDefault =
4651 EmitDwarf && PlainCOrCXX && OptLevel &&
4652 !OptLevel->getOption().matches(ID: options::OPT_O0);
4653 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4654 Neg: options::OPT_gno_key_instructions,
4655 Default: KeyInstructionsOnByDefault))
4656 CmdArgs.push_back(Elt: "-gkey-instructions");
4657
4658 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4659 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4660 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4661
4662 if (EmitCodeView) {
4663 CmdArgs.push_back(Elt: "-gcodeview");
4664
4665 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
4666 Neg: options::OPT_gno_codeview_ghash);
4667
4668 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
4669 Neg: options::OPT_gno_codeview_command_line);
4670 }
4671
4672 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
4673 Neg: options::OPT_gno_inline_line_tables);
4674
4675 // When emitting remarks, we need at least debug lines in the output.
4676 if (willEmitRemarks(Args) &&
4677 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4678 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4679
4680 // Adjust the debug info kind for the given toolchain.
4681 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4682
4683 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4684 // set.
4685 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4686 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
4687 ? llvm::DebuggerKind::Default
4688 : DebuggerTuning);
4689
4690 // -fdebug-macro turns on macro debug info generation.
4691 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
4692 Default: false))
4693 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
4694 D, TC))
4695 CmdArgs.push_back(Elt: "-debug-info-macro");
4696
4697 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4698 const auto *PubnamesArg =
4699 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
4700 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
4701 if (DwarfFission != DwarfFissionKind::None ||
4702 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
4703 const bool OptionSet =
4704 (PubnamesArg &&
4705 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
4706 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
4707 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4708 (!PubnamesArg ||
4709 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
4710 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
4711 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
4712 ID: options::OPT_gpubnames)
4713 ? "-gpubnames"
4714 : "-ggnu-pubnames");
4715 }
4716
4717 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4718 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4719 ForwardTemplateParams = true;
4720 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
4721 }
4722
4723 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4724 bool UseDebugTemplateAlias =
4725 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4726 if (const auto *DebugTemplateAlias = Args.getLastArg(
4727 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
4728 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4729 // asks for it we should let them have it (if the target supports it).
4730 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
4731 const auto &Opt = DebugTemplateAlias->getOption();
4732 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
4733 }
4734 }
4735 if (UseDebugTemplateAlias)
4736 CmdArgs.push_back(Elt: "-gtemplate-alias");
4737
4738 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
4739 StringRef v = A->getValue();
4740 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
4741 }
4742
4743 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
4744 Neg: options::OPT_fno_debug_ranges_base_address);
4745
4746 // -gdwarf-aranges turns on the emission of the aranges section in the
4747 // backend.
4748 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
4749 A && checkDebugInfoOption(A, Args, D, TC)) {
4750 CmdArgs.push_back(Elt: "-mllvm");
4751 CmdArgs.push_back(Elt: "-generate-arange-section");
4752 }
4753
4754 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
4755 Neg: options::OPT_fno_force_dwarf_frame);
4756
4757 bool EnableTypeUnits = false;
4758 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
4759 Neg: options::OPT_fno_debug_types_section, Default: false)) {
4760 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4761 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4762 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
4763 ->getAsString(Args)
4764 << T.getTriple();
4765 } else if (checkDebugInfoOption(
4766 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
4767 TC)) {
4768 EnableTypeUnits = true;
4769 CmdArgs.push_back(Elt: "-mllvm");
4770 CmdArgs.push_back(Elt: "-generate-type-units");
4771 }
4772 }
4773
4774 if (const Arg *A =
4775 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
4776 Ids: options::OPT_gno_omit_unreferenced_methods))
4777 (void)checkDebugInfoOption(A, Args, D, TC);
4778 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
4779 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
4780 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4781 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4782 !EnableTypeUnits) {
4783 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
4784 }
4785
4786 // To avoid join/split of directory+filename, the integrated assembler prefers
4787 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4788 // form before DWARF v5.
4789 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
4790 Neg: options::OPT_fno_dwarf_directory_asm,
4791 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4792 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
4793
4794 // Decide how to render forward declarations of template instantiations.
4795 // SCE wants full descriptions, others just get them in the name.
4796 if (ForwardTemplateParams)
4797 CmdArgs.push_back(Elt: "-debug-forward-template-params");
4798
4799 // Do we need to explicitly import anonymous namespaces into the parent
4800 // scope?
4801 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4802 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
4803
4804 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
4805 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4806
4807 // This controls whether or not we perform JustMyCode instrumentation.
4808 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
4809 if (TC.getTriple().isOSBinFormatELF() ||
4810 TC.getTriple().isWindowsMSVCEnvironment()) {
4811 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4812 CmdArgs.push_back(Elt: "-fjmc");
4813 else if (D.IsCLMode())
4814 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4815 << "'/Zi', '/Z7'";
4816 else
4817 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4818 << "-g";
4819 } else {
4820 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
4821 }
4822 }
4823
4824 // Add in -fdebug-compilation-dir if necessary.
4825 const char *DebugCompilationDir =
4826 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
4827
4828 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4829
4830 // Add the output path to the object file for CodeView debug infos.
4831 if (EmitCodeView && Output.isFilename())
4832 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4833 OutputFileName: Output.getFilename());
4834}
4835
4836static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4837 ArgStringList &CmdArgs) {
4838 unsigned RTOptionID = options::OPT__SLASH_MT;
4839
4840 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4841 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4842 // but defining _DEBUG is sticky.
4843 RTOptionID = options::OPT__SLASH_MTd;
4844
4845 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
4846 RTOptionID = A->getOption().getID();
4847
4848 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
4849 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4850 .Case(S: "static", Value: options::OPT__SLASH_MT)
4851 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
4852 .Case(S: "dll", Value: options::OPT__SLASH_MD)
4853 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
4854 .Default(Value: options::OPT__SLASH_MT);
4855 }
4856
4857 StringRef FlagForCRT;
4858 switch (RTOptionID) {
4859 case options::OPT__SLASH_MD:
4860 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4861 CmdArgs.push_back(Elt: "-D_DEBUG");
4862 CmdArgs.push_back(Elt: "-D_MT");
4863 CmdArgs.push_back(Elt: "-D_DLL");
4864 FlagForCRT = "--dependent-lib=msvcrt";
4865 break;
4866 case options::OPT__SLASH_MDd:
4867 CmdArgs.push_back(Elt: "-D_DEBUG");
4868 CmdArgs.push_back(Elt: "-D_MT");
4869 CmdArgs.push_back(Elt: "-D_DLL");
4870 FlagForCRT = "--dependent-lib=msvcrtd";
4871 break;
4872 case options::OPT__SLASH_MT:
4873 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4874 CmdArgs.push_back(Elt: "-D_DEBUG");
4875 CmdArgs.push_back(Elt: "-D_MT");
4876 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4877 FlagForCRT = "--dependent-lib=libcmt";
4878 break;
4879 case options::OPT__SLASH_MTd:
4880 CmdArgs.push_back(Elt: "-D_DEBUG");
4881 CmdArgs.push_back(Elt: "-D_MT");
4882 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4883 FlagForCRT = "--dependent-lib=libcmtd";
4884 break;
4885 default:
4886 llvm_unreachable("Unexpected option ID.");
4887 }
4888
4889 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
4890 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
4891 } else {
4892 CmdArgs.push_back(Elt: FlagForCRT.data());
4893
4894 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4895 // users want. The /Za flag to cl.exe turns this off, but it's not
4896 // implemented in clang.
4897 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
4898 }
4899
4900 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4901 // even if the file doesn't actually refer to any of the routines because
4902 // the CRT itself has incomplete dependency markings.
4903 if (TC.getTriple().isWindowsArm64EC())
4904 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
4905}
4906
4907void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4908 const InputInfo &Output, const InputInfoList &Inputs,
4909 const ArgList &Args, const char *LinkingOutput) const {
4910 const auto &TC = getToolChain();
4911 const llvm::Triple &RawTriple = TC.getTriple();
4912 const llvm::Triple &Triple = TC.getEffectiveTriple();
4913 const std::string &TripleStr = Triple.getTriple();
4914
4915 bool KernelOrKext =
4916 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
4917 const Driver &D = TC.getDriver();
4918 ArgStringList CmdArgs;
4919
4920 assert(Inputs.size() >= 1 && "Must have at least one input.");
4921 // CUDA/HIP compilation may have multiple inputs (source file + results of
4922 // device-side compilations). OpenMP device jobs also take the host IR as a
4923 // second input. Module precompilation accepts a list of header files to
4924 // include as part of the module. API extraction accepts a list of header
4925 // files whose API information is emitted in the output. All other jobs are
4926 // expected to have exactly one input. SYCL compilation only expects a
4927 // single input.
4928 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
4929 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
4930 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
4931 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
4932 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
4933 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
4934 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
4935 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
4936 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
4937 JA.isDeviceOffloading(OKind: Action::OFK_Host));
4938 bool IsHostOffloadingAction =
4939 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
4940 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
4941 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()) &&
4942 Args.hasFlag(Pos: options::OPT_offload_new_driver,
4943 Neg: options::OPT_no_offload_new_driver,
4944 Default: C.getActiveOffloadKinds() != Action::OFK_None));
4945
4946 bool IsRDCMode =
4947 Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
4948
4949 auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
4950 bool IsUsingLTO = LTOMode != LTOK_None;
4951
4952 // Extract API doesn't have a main input file, so invent a fake one as a
4953 // placeholder.
4954 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4955 "extract-api");
4956
4957 const InputInfo &Input =
4958 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4959
4960 InputInfoList ExtractAPIInputs;
4961 InputInfoList HostOffloadingInputs;
4962 const InputInfo *CudaDeviceInput = nullptr;
4963 const InputInfo *OpenMPDeviceInput = nullptr;
4964 for (const InputInfo &I : Inputs) {
4965 if (&I == &Input || I.getType() == types::TY_Nothing) {
4966 // This is the primary input or contains nothing.
4967 } else if (IsExtractAPI) {
4968 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4969 if (I.getType() != ExpectedInputType) {
4970 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
4971 << I.getFilename() << types::getTypeName(Id: I.getType())
4972 << types::getTypeName(Id: ExpectedInputType);
4973 }
4974 ExtractAPIInputs.push_back(Elt: I);
4975 } else if (IsHostOffloadingAction) {
4976 HostOffloadingInputs.push_back(Elt: I);
4977 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4978 CudaDeviceInput = &I;
4979 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4980 OpenMPDeviceInput = &I;
4981 } else {
4982 llvm_unreachable("unexpectedly given multiple inputs");
4983 }
4984 }
4985
4986 const llvm::Triple *AuxTriple =
4987 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4988 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4989 bool IsUEFI = RawTriple.isUEFI();
4990 bool IsIAMCU = RawTriple.isOSIAMCU();
4991
4992 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling in
4993 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4994 // Windows), we need to pass Windows-specific flags to cc1.
4995 if (IsCuda || IsHIP || IsSYCL)
4996 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4997
4998 // C++ is not supported for IAMCU.
4999 if (IsIAMCU && types::isCXX(Id: Input.getType()))
5000 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5001
5002 // Invoke ourselves in -cc1 mode.
5003 //
5004 // FIXME: Implement custom jobs for internal actions.
5005 CmdArgs.push_back(Elt: "-cc1");
5006
5007 // Add the "effective" target triple.
5008 CmdArgs.push_back(Elt: "-triple");
5009 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: TripleStr));
5010
5011 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
5012 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
5013 Args.ClaimAllArgs(Id0: options::OPT_MJ);
5014 } else if (const Arg *GenCDBFragment =
5015 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
5016 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
5017 Target: TripleStr, Output, Input, Args);
5018 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
5019 }
5020
5021 if (IsCuda || IsHIP) {
5022 CmdArgs.push_back(Elt: "-aux-triple");
5023
5024 // We have to pass the triple of the host if compiling for a CUDA/HIP device
5025 // and vice-versa.
5026 if (IsCudaDevice || IsHIPDevice) {
5027 StringRef AuxTripleStr =
5028 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple().str();
5029 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: AuxTripleStr));
5030 } else {
5031 // Host-side compilation.
5032 StringRef AuxTripleStr =
5033 (IsCuda ? C.getOffloadToolChains(Kind: Action::OFK_Cuda).first->second
5034 : C.getOffloadToolChains(Kind: Action::OFK_HIP).first->second)
5035 ->getTriple()
5036 .str();
5037 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: AuxTripleStr));
5038 }
5039
5040 if (JA.isDeviceOffloading(OKind: Action::OFK_HIP) &&
5041 (getToolChain().getTriple().isAMDGPU() ||
5042 (getToolChain().getTriple().isSPIRV() &&
5043 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5044 // Device side compilation printf
5045 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
5046 CmdArgs.push_back(Elt: Args.MakeArgString(
5047 Str: "-mprintf-kind=" +
5048 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
5049 // Force compiler error on invalid conversion specifiers
5050 CmdArgs.push_back(
5051 Elt: Args.MakeArgStringRef(Str: "-Werror=format-invalid-specifier"));
5052 }
5053 }
5054 }
5055
5056 if (IsCuda && !IsCudaDevice) {
5057 // We need to figure out which CUDA version we're compiling for, as that
5058 // determines how we load and launch GPU kernels.
5059 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5060 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5061 assert(CTC && "Expected valid CUDA Toolchain.");
5062 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5063 CmdArgs.push_back(Elt: Args.MakeArgString(
5064 Str: Twine("-target-sdk-version=") +
5065 CudaVersionToString(V: CTC->CudaInstallation.version())));
5066 }
5067
5068 // Optimization level for CodeGen.
5069 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5070 if (A->getOption().matches(ID: options::OPT_O4)) {
5071 CmdArgs.push_back(Elt: "-O3");
5072 D.Diag(DiagID: diag::warn_O4_is_O3);
5073 } else {
5074 A->render(Args, Output&: CmdArgs);
5075 }
5076 }
5077
5078 // Unconditionally claim the printf option now to avoid unused diagnostic.
5079 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5080 PF->claim();
5081
5082 if (IsSYCL) {
5083 if (IsSYCLDevice) {
5084 // Host triple is needed when doing SYCL device compilations.
5085 llvm::Triple AuxT = C.getDefaultToolChain().getTriple();
5086 std::string NormalizedTriple = AuxT.normalize();
5087 CmdArgs.push_back(Elt: "-aux-triple");
5088 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5089
5090 // We want to compile sycl kernels.
5091 CmdArgs.push_back(Elt: "-fsycl-is-device");
5092
5093 // Set O2 optimization level by default
5094 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5095 CmdArgs.push_back(Elt: "-O2");
5096 } else {
5097 // Add any options that are needed specific to SYCL offload while
5098 // performing the host side compilation.
5099
5100 // Let the front-end host compilation flow know about SYCL offload
5101 // compilation.
5102 CmdArgs.push_back(Elt: "-fsycl-is-host");
5103 }
5104
5105 // Set options for both host and device.
5106 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5107 if (SYCLStdArg) {
5108 SYCLStdArg->render(Args, Output&: CmdArgs);
5109 } else {
5110 // Ensure the default version in SYCL mode is 2020.
5111 CmdArgs.push_back(Elt: "-sycl-std=2020");
5112 }
5113 }
5114
5115 if (Args.hasArg(Ids: options::OPT_fclangir))
5116 CmdArgs.push_back(Elt: "-fclangir");
5117
5118 if (IsOpenMPDevice) {
5119 // We have to pass the triple of the host if compiling for an OpenMP device.
5120 std::string NormalizedTriple =
5121 C.getSingleOffloadToolChain<Action::OFK_Host>()
5122 ->getTriple()
5123 .normalize();
5124 CmdArgs.push_back(Elt: "-aux-triple");
5125 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5126 }
5127
5128 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5129 Triple.getArch() == llvm::Triple::thumb)) {
5130 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5131 unsigned Version = 0;
5132 bool Failure =
5133 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5134 if (Failure || Version < 7)
5135 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5136 << TripleStr;
5137 }
5138
5139 // Push all default warning arguments that are specific to
5140 // the given target. These come before user provided warning options
5141 // are provided.
5142 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5143
5144 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5145 if (Triple.isSPIR() || Triple.isSPIRV())
5146 CmdArgs.push_back(Elt: "-Wspir-compat");
5147
5148 // Select the appropriate action.
5149 RewriteKind rewriteKind = RK_None;
5150
5151 bool UnifiedLTO = false;
5152 if (IsUsingLTO) {
5153 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5154 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5155 if (UnifiedLTO)
5156 CmdArgs.push_back(Elt: "-funified-lto");
5157 }
5158
5159 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5160 // it claims when not running an assembler. Otherwise, clang would emit
5161 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5162 // flags while debugging something. That'd be somewhat inconvenient, and it's
5163 // also inconsistent with most other flags -- we don't warn on
5164 // -ffunction-sections not being used in -E mode either for example, even
5165 // though it's not really used either.
5166 if (!isa<AssembleJobAction>(Val: JA)) {
5167 // The args claimed here should match the args used in
5168 // CollectArgsForIntegratedAssembler().
5169 if (TC.useIntegratedAs()) {
5170 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5171 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5172 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5173 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5174 switch (C.getDefaultToolChain().getArch()) {
5175 case llvm::Triple::arm:
5176 case llvm::Triple::armeb:
5177 case llvm::Triple::thumb:
5178 case llvm::Triple::thumbeb:
5179 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5180 break;
5181 default:
5182 break;
5183 }
5184 }
5185 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5186 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5187 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5188 }
5189
5190 bool IsAMDSPIRVForHIPDevice =
5191 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5192 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5193
5194 if (isa<AnalyzeJobAction>(Val: JA)) {
5195 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5196 CmdArgs.push_back(Elt: "-analyze");
5197 } else if (isa<PreprocessJobAction>(Val: JA)) {
5198 if (Output.getType() == types::TY_Dependencies)
5199 CmdArgs.push_back(Elt: "-Eonly");
5200 else {
5201 CmdArgs.push_back(Elt: "-E");
5202 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5203 !Args.hasArg(Ids: options::OPT_g_Group))
5204 CmdArgs.push_back(Elt: "-P");
5205 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5206 CmdArgs.push_back(Elt: "-fdirectives-only");
5207 }
5208 } else if (isa<AssembleJobAction>(Val: JA)) {
5209 CmdArgs.push_back(Elt: "-emit-obj");
5210
5211 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5212
5213 // Also ignore explicit -force_cpusubtype_ALL option.
5214 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5215 } else if (isa<PrecompileJobAction>(Val: JA)) {
5216 if (JA.getType() == types::TY_Nothing)
5217 CmdArgs.push_back(Elt: "-fsyntax-only");
5218 else if (JA.getType() == types::TY_ModuleFile) {
5219 if (Args.hasArg(Ids: options::OPT__precompile_reduced_bmi))
5220 CmdArgs.push_back(Elt: "-emit-reduced-module-interface");
5221 else
5222 CmdArgs.push_back(Elt: "-emit-module-interface");
5223 } else if (JA.getType() == types::TY_HeaderUnit)
5224 CmdArgs.push_back(Elt: "-emit-header-unit");
5225 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5226 CmdArgs.push_back(Elt: "-emit-pch");
5227 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5228 CmdArgs.push_back(Elt: "-verify-pch");
5229 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5230 assert(JA.getType() == types::TY_API_INFO &&
5231 "Extract API actions must generate a API information.");
5232 CmdArgs.push_back(Elt: "-extract-api");
5233
5234 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5235 PrettySGFArg->render(Args, Output&: CmdArgs);
5236
5237 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5238
5239 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5240 ProductNameArg->render(Args, Output&: CmdArgs);
5241 if (Arg *ExtractAPIIgnoresFileArg =
5242 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5243 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5244 if (Arg *EmitExtensionSymbolGraphs =
5245 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5246 if (!SymbolGraphDirArg)
5247 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5248
5249 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5250 }
5251 if (SymbolGraphDirArg)
5252 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5253 } else {
5254 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5255 "Invalid action for clang tool.");
5256 if (JA.getType() == types::TY_Nothing) {
5257 CmdArgs.push_back(Elt: "-fsyntax-only");
5258 } else if (JA.getType() == types::TY_LLVM_IR ||
5259 JA.getType() == types::TY_LTO_IR) {
5260 CmdArgs.push_back(Elt: "-emit-llvm");
5261 } else if (JA.getType() == types::TY_LLVM_BC ||
5262 JA.getType() == types::TY_LTO_BC) {
5263 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5264 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5265 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5266 CmdArgs.push_back(Elt: "-emit-llvm");
5267 } else {
5268 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5269 }
5270 } else if (JA.getType() == types::TY_IFS ||
5271 JA.getType() == types::TY_IFS_CPP) {
5272 StringRef ArgStr =
5273 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5274 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5275 : "ifs-v1";
5276 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5277 CmdArgs.push_back(
5278 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr));
5279 } else if (JA.getType() == types::TY_PP_Asm) {
5280 CmdArgs.push_back(Elt: "-S");
5281 } else if (JA.getType() == types::TY_AST) {
5282 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5283 CmdArgs.push_back(Elt: "-emit-pch");
5284 } else if (JA.getType() == types::TY_ModuleFile) {
5285 CmdArgs.push_back(Elt: "-module-file-info");
5286 } else if (JA.getType() == types::TY_RewrittenObjC) {
5287 CmdArgs.push_back(Elt: "-rewrite-objc");
5288 rewriteKind = RK_NonFragile;
5289 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5290 CmdArgs.push_back(Elt: "-rewrite-objc");
5291 rewriteKind = RK_Fragile;
5292 } else if (JA.getType() == types::TY_CIR) {
5293 CmdArgs.push_back(Elt: "-emit-cir");
5294 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5295 CmdArgs.push_back(Elt: "-emit-obj");
5296 } else {
5297 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5298 }
5299
5300 // Preserve use-list order by default when emitting bitcode, so that
5301 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5302 // same result as running passes here. For LTO, we don't need to preserve
5303 // the use-list order, since serialization to bitcode is part of the flow.
5304 if (JA.getType() == types::TY_LLVM_BC)
5305 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5306
5307 if (IsUsingLTO) {
5308 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
5309 !Args.hasFlag(Pos: options::OPT_offload_new_driver,
5310 Neg: options::OPT_no_offload_new_driver,
5311 Default: C.getActiveOffloadKinds() != Action::OFK_None) &&
5312 !Triple.isAMDGPU()) {
5313 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5314 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5315 Ids: options::OPT_foffload_lto_EQ)
5316 ->getAsString(Args)
5317 << Triple.getTriple();
5318 } else if (Triple.isNVPTX() && !IsRDCMode &&
5319 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5320 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5321 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5322 Ids: options::OPT_foffload_lto_EQ)
5323 ->getAsString(Args)
5324 << "-fno-gpu-rdc";
5325 } else {
5326 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5327 CmdArgs.push_back(Elt: Args.MakeArgString(
5328 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5329 // PS4 uses the legacy LTO API, which does not support some of the
5330 // features enabled by -flto-unit.
5331 if (!RawTriple.isPS4() ||
5332 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5333 CmdArgs.push_back(Elt: "-flto-unit");
5334 }
5335 }
5336 }
5337
5338 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5339
5340 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5341 if (!types::isLLVMIR(Id: Input.getType()))
5342 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5343 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5344 }
5345
5346 if (Triple.isPPC())
5347 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5348 Neg: options::OPT_mno_regnames);
5349
5350 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5351 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5352
5353 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5354 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5355
5356 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5357 Ids: options::OPT_fmemory_profile_EQ,
5358 Ids: options::OPT_fno_memory_profile);
5359 if (MemProfArg &&
5360 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5361 MemProfArg->render(Args, Output&: CmdArgs);
5362
5363 if (auto *MemProfUseArg =
5364 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5365 if (MemProfArg)
5366 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5367 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5368 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5369 Ids: options::OPT_fprofile_generate_EQ))
5370 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5371 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5372 MemProfUseArg->render(Args, Output&: CmdArgs);
5373 }
5374
5375 // Embed-bitcode option.
5376 // Only white-listed flags below are allowed to be embedded.
5377 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5378 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5379 // Add flags implied by -fembed-bitcode.
5380 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5381 // Disable all llvm IR level optimizations.
5382 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5383
5384 // Render target options.
5385 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
5386
5387 // reject options that shouldn't be supported in bitcode
5388 // also reject kernel/kext
5389 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5390 options::OPT_mkernel,
5391 options::OPT_fapple_kext,
5392 options::OPT_ffunction_sections,
5393 options::OPT_fno_function_sections,
5394 options::OPT_fdata_sections,
5395 options::OPT_fno_data_sections,
5396 options::OPT_fbasic_block_sections_EQ,
5397 options::OPT_funique_internal_linkage_names,
5398 options::OPT_fno_unique_internal_linkage_names,
5399 options::OPT_funique_section_names,
5400 options::OPT_fno_unique_section_names,
5401 options::OPT_funique_basic_block_section_names,
5402 options::OPT_fno_unique_basic_block_section_names,
5403 options::OPT_mrestrict_it,
5404 options::OPT_mno_restrict_it,
5405 options::OPT_mstackrealign,
5406 options::OPT_mno_stackrealign,
5407 options::OPT_mstack_alignment,
5408 options::OPT_mcmodel_EQ,
5409 options::OPT_mlong_calls,
5410 options::OPT_mno_long_calls,
5411 options::OPT_ggnu_pubnames,
5412 options::OPT_gdwarf_aranges,
5413 options::OPT_fdebug_types_section,
5414 options::OPT_fno_debug_types_section,
5415 options::OPT_fdwarf_directory_asm,
5416 options::OPT_fno_dwarf_directory_asm,
5417 options::OPT_mrelax_all,
5418 options::OPT_mno_relax_all,
5419 options::OPT_ftrap_function_EQ,
5420 options::OPT_ffixed_r9,
5421 options::OPT_mfix_cortex_a53_835769,
5422 options::OPT_mno_fix_cortex_a53_835769,
5423 options::OPT_ffixed_x18,
5424 options::OPT_mglobal_merge,
5425 options::OPT_mno_global_merge,
5426 options::OPT_mred_zone,
5427 options::OPT_mno_red_zone,
5428 options::OPT_Wa_COMMA,
5429 options::OPT_Xassembler,
5430 options::OPT_mllvm,
5431 options::OPT_mmlir,
5432 };
5433 for (const auto &A : Args)
5434 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5435 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5436
5437 // Render the CodeGen options that need to be passed.
5438 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5439 Neg: options::OPT_fno_optimize_sibling_calls);
5440
5441 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5442 CmdArgs, JA);
5443
5444 // Render ABI arguments
5445 switch (TC.getArch()) {
5446 default: break;
5447 case llvm::Triple::arm:
5448 case llvm::Triple::armeb:
5449 case llvm::Triple::thumbeb:
5450 RenderARMABI(D, Triple, Args, CmdArgs);
5451 break;
5452 case llvm::Triple::aarch64:
5453 case llvm::Triple::aarch64_32:
5454 case llvm::Triple::aarch64_be:
5455 RenderAArch64ABI(Triple, Args, CmdArgs);
5456 break;
5457 }
5458
5459 // Input/Output file.
5460 if (Output.getType() == types::TY_Dependencies) {
5461 // Handled with other dependency code.
5462 } else if (Output.isFilename()) {
5463 CmdArgs.push_back(Elt: "-o");
5464 CmdArgs.push_back(Elt: Output.getFilename());
5465 } else {
5466 assert(Output.isNothing() && "Input output.");
5467 }
5468
5469 for (const auto &II : Inputs) {
5470 addDashXForInput(Args, Input: II, CmdArgs);
5471 if (II.isFilename())
5472 CmdArgs.push_back(Elt: II.getFilename());
5473 else
5474 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5475 }
5476
5477 C.addCommand(C: std::make_unique<Command>(
5478 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getClangProgramPath(),
5479 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5480 return;
5481 }
5482
5483 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5484 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5485
5486 // We normally speed up the clang process a bit by skipping destructors at
5487 // exit, but when we're generating diagnostics we can rely on some of the
5488 // cleanup.
5489 if (!C.isForDiagnostics())
5490 CmdArgs.push_back(Elt: "-disable-free");
5491 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5492
5493#ifdef NDEBUG
5494 const bool IsAssertBuild = false;
5495#else
5496 const bool IsAssertBuild = true;
5497#endif
5498
5499 // Disable the verification pass in no-asserts builds unless otherwise
5500 // specified.
5501 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5502 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5503 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5504 }
5505
5506 // Discard value names in no-asserts builds unless otherwise specified.
5507 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5508 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild)) {
5509 if (Args.hasArg(Ids: options::OPT_fdiscard_value_names) &&
5510 llvm::any_of(Range: Inputs, P: [](const clang::driver::InputInfo &II) {
5511 return types::isLLVMIR(Id: II.getType());
5512 })) {
5513 D.Diag(DiagID: diag::warn_ignoring_fdiscard_for_bitcode);
5514 }
5515 CmdArgs.push_back(Elt: "-discard-value-names");
5516 }
5517
5518 // Set the main file name, so that debug info works even with
5519 // -save-temps.
5520 CmdArgs.push_back(Elt: "-main-file-name");
5521 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5522
5523 // Some flags which affect the language (via preprocessor
5524 // defines).
5525 if (Args.hasArg(Ids: options::OPT_static))
5526 CmdArgs.push_back(Elt: "-static-define");
5527
5528 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5529
5530 if (Args.hasArg(Ids: options::OPT_municode))
5531 CmdArgs.push_back(Elt: "-DUNICODE");
5532
5533 if (isa<AnalyzeJobAction>(Val: JA))
5534 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5535
5536 if (isa<AnalyzeJobAction>(Val: JA) ||
5537 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5538 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5539
5540 // Enable compatilibily mode to avoid analyzer-config related errors.
5541 // Since we can't access frontend flags through hasArg, let's manually iterate
5542 // through them.
5543 bool FoundAnalyzerConfig = false;
5544 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5545 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5546 FoundAnalyzerConfig = true;
5547 break;
5548 }
5549 if (!FoundAnalyzerConfig)
5550 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5551 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5552 FoundAnalyzerConfig = true;
5553 break;
5554 }
5555 if (FoundAnalyzerConfig)
5556 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5557
5558 CheckCodeGenerationOptions(D, Args);
5559
5560 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5561 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5562 if (FunctionAlignment) {
5563 CmdArgs.push_back(Elt: "-function-alignment");
5564 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(FunctionAlignment)));
5565 }
5566
5567 if (const Arg *A =
5568 Args.getLastArg(Ids: options::OPT_fpreferred_function_alignment_EQ)) {
5569 unsigned Value = 0;
5570 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5571 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5572 << A->getAsString(Args) << A->getValue();
5573 else if (!llvm::isPowerOf2_32(Value))
5574 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5575 << A->getAsString(Args) << A->getValue();
5576
5577 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpreferred-function-alignment=" +
5578 Twine(std::min(a: Value, b: 65536u))));
5579 }
5580
5581 // We support -falign-loops=N where N is a power of 2. GCC supports more
5582 // forms.
5583 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5584 unsigned Value = 0;
5585 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5586 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5587 << A->getAsString(Args) << A->getValue();
5588 else if (Value & (Value - 1))
5589 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5590 << A->getAsString(Args) << A->getValue();
5591 // Treat =0 as unspecified (use the target preference).
5592 if (Value)
5593 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5594 Twine(std::min(a: Value, b: 65536u))));
5595 }
5596
5597 if (Triple.isOSzOS()) {
5598 // On z/OS some of the system header feature macros need to
5599 // be defined to enable most cross platform projects to build
5600 // successfully. Ths include the libc++ library. A
5601 // complicating factor is that users can define these
5602 // macros to the same or different values. We need to add
5603 // the definition for these macros to the compilation command
5604 // if the user hasn't already defined them.
5605
5606 auto findMacroDefinition = [&](const std::string &Macro) {
5607 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5608 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5609 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5610 });
5611 };
5612
5613 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5614 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5615 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5616 // _OPEN_DEFAULT is required for XL compat
5617 if (!findMacroDefinition("_OPEN_DEFAULT"))
5618 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5619 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5620 // _XOPEN_SOURCE=600 is required for libcxx.
5621 if (!findMacroDefinition("_XOPEN_SOURCE"))
5622 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5623 }
5624 }
5625
5626 llvm::Reloc::Model RelocationModel;
5627 unsigned PICLevel;
5628 bool IsPIE;
5629 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5630 Arg *LastPICDataRelArg =
5631 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5632 Ids: options::OPT_mpic_data_is_text_relative);
5633 bool NoPICDataIsTextRelative = false;
5634 if (LastPICDataRelArg) {
5635 if (LastPICDataRelArg->getOption().matches(
5636 ID: options::OPT_mno_pic_data_is_text_relative)) {
5637 NoPICDataIsTextRelative = true;
5638 if (!PICLevel)
5639 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5640 << "-mno-pic-data-is-text-relative"
5641 << "-fpic/-fpie";
5642 }
5643 if (!Triple.isSystemZ())
5644 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5645 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5646 : "-mpic-data-is-text-relative")
5647 << RawTriple.str();
5648 }
5649
5650 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5651 RelocationModel == llvm::Reloc::ROPI_RWPI;
5652 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5653 RelocationModel == llvm::Reloc::ROPI_RWPI;
5654
5655 if (Args.hasArg(Ids: options::OPT_mcmse) &&
5656 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
5657 if (IsROPI)
5658 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
5659 if (IsRWPI)
5660 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5661 }
5662
5663 if (IsROPI && types::isCXX(Id: Input.getType()) &&
5664 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
5665 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
5666
5667 const char *RMName = RelocationModelName(Model: RelocationModel);
5668 if (RMName) {
5669 CmdArgs.push_back(Elt: "-mrelocation-model");
5670 CmdArgs.push_back(Elt: RMName);
5671 }
5672 if (PICLevel > 0) {
5673 CmdArgs.push_back(Elt: "-pic-level");
5674 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
5675 if (IsPIE)
5676 CmdArgs.push_back(Elt: "-pic-is-pie");
5677 if (NoPICDataIsTextRelative)
5678 CmdArgs.push_back(Elt: "-mcmodel=medium");
5679 }
5680
5681 if (RelocationModel == llvm::Reloc::ROPI ||
5682 RelocationModel == llvm::Reloc::ROPI_RWPI)
5683 CmdArgs.push_back(Elt: "-fropi");
5684 if (RelocationModel == llvm::Reloc::RWPI ||
5685 RelocationModel == llvm::Reloc::ROPI_RWPI)
5686 CmdArgs.push_back(Elt: "-frwpi");
5687
5688 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
5689 CmdArgs.push_back(Elt: "-meabi");
5690 CmdArgs.push_back(Elt: A->getValue());
5691 }
5692
5693 // -fsemantic-interposition is forwarded to CC1: set the
5694 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5695 // make default visibility external linkage definitions dso_preemptable.
5696 //
5697 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5698 // aliases (make default visibility external linkage definitions dso_local).
5699 // This is the CC1 default for ELF to match COFF/Mach-O.
5700 //
5701 // Otherwise use Clang's traditional behavior: like
5702 // -fno-semantic-interposition but local aliases are not used. So references
5703 // can be interposed if not optimized out.
5704 if (Triple.isOSBinFormatELF()) {
5705 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
5706 Ids: options::OPT_fno_semantic_interposition);
5707 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5708 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5709 bool SupportsLocalAlias =
5710 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5711 if (!A)
5712 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5713 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
5714 A->render(Args, Output&: CmdArgs);
5715 else if (!SupportsLocalAlias)
5716 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5717 }
5718 }
5719
5720 {
5721 std::string Model;
5722 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
5723 if (!TC.isThreadModelSupported(Model: A->getValue()))
5724 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
5725 << A->getValue() << A->getAsString(Args);
5726 Model = A->getValue();
5727 } else
5728 Model = TC.getThreadModel();
5729 if (Model != "posix") {
5730 CmdArgs.push_back(Elt: "-mthread-model");
5731 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
5732 }
5733 }
5734
5735 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
5736 StringRef Name = A->getValue();
5737 if (Name == "SVML") {
5738 if (Triple.getArch() != llvm::Triple::x86 &&
5739 Triple.getArch() != llvm::Triple::x86_64)
5740 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5741 << Name << Triple.getArchName();
5742 } else if (Name == "AMDLIBM") {
5743 if (Triple.getArch() != llvm::Triple::x86 &&
5744 Triple.getArch() != llvm::Triple::x86_64)
5745 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5746 << Name << Triple.getArchName();
5747 } else if (Name == "libmvec") {
5748 if (Triple.getArch() != llvm::Triple::x86 &&
5749 Triple.getArch() != llvm::Triple::x86_64 &&
5750 Triple.getArch() != llvm::Triple::aarch64 &&
5751 Triple.getArch() != llvm::Triple::aarch64_be)
5752 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5753 << Name << Triple.getArchName();
5754 } else if (Name == "SLEEF" || Name == "ArmPL") {
5755 if (Triple.getArch() != llvm::Triple::aarch64 &&
5756 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
5757 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5758 << Name << Triple.getArchName();
5759 }
5760 A->render(Args, Output&: CmdArgs);
5761 }
5762
5763 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
5764 Neg: options::OPT_fno_merge_all_constants, Default: false))
5765 CmdArgs.push_back(Elt: "-fmerge-all-constants");
5766
5767 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
5768 Neg: options::OPT_fno_delete_null_pointer_checks);
5769
5770 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_dse,
5771 Neg: options::OPT_fno_lifetime_dse);
5772
5773 // LLVM Code Generator Options.
5774
5775 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
5776 if (!Triple.isOSAIX() || Triple.isPPC32())
5777 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5778 << A->getSpelling() << RawTriple.str();
5779 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
5780 }
5781
5782 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
5783 // Emit the unsupported option error until the Clang's library integration
5784 // support for 128-bit long double is available for AIX.
5785 if (Triple.isOSAIX())
5786 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5787 << A->getSpelling() << RawTriple.str();
5788 }
5789
5790 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
5791 StringRef V = A->getValue(), V1 = V;
5792 unsigned Size;
5793 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
5794 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5795 << V << A->getOption().getName();
5796 else
5797 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
5798 }
5799
5800 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
5801 Neg: options::OPT_fno_jump_tables);
5802 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
5803 Neg: options::OPT_fno_profile_sample_accurate);
5804 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
5805 Neg: options::OPT_fno_preserve_as_comments);
5806
5807 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
5808 CmdArgs.push_back(Elt: "-mregparm");
5809 CmdArgs.push_back(Elt: A->getValue());
5810 }
5811
5812 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
5813 Ids: options::OPT_msvr4_struct_return)) {
5814 if (!TC.getTriple().isPPC32()) {
5815 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5816 << A->getSpelling() << RawTriple.str();
5817 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
5818 CmdArgs.push_back(Elt: "-maix-struct-return");
5819 } else {
5820 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5821 CmdArgs.push_back(Elt: "-msvr4-struct-return");
5822 }
5823 }
5824
5825 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
5826 Ids: options::OPT_freg_struct_return)) {
5827 if (TC.getArch() != llvm::Triple::x86) {
5828 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5829 << A->getSpelling() << RawTriple.str();
5830 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
5831 CmdArgs.push_back(Elt: "-fpcc-struct-return");
5832 } else {
5833 assert(A->getOption().matches(options::OPT_freg_struct_return));
5834 CmdArgs.push_back(Elt: "-freg-struct-return");
5835 }
5836 }
5837
5838 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
5839 if (Triple.getArch() == llvm::Triple::m68k)
5840 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
5841 else
5842 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
5843 }
5844
5845 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
5846 // enable-matrix is needed by both the LangOpts and by LLVM.
5847 CmdArgs.push_back(Elt: "-fenable-matrix");
5848 CmdArgs.push_back(Elt: "-mllvm");
5849 CmdArgs.push_back(Elt: "-enable-matrix");
5850 // Only handle default layout if matrix is enabled
5851 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
5852 StringRef Val = A->getValue();
5853 if (Val == "row-major" || Val == "column-major") {
5854 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
5855 CmdArgs.push_back(Elt: "-mllvm");
5856 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
5857
5858 } else {
5859 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
5860 }
5861 }
5862 }
5863
5864 CodeGenOptions::FramePointerKind FPKeepKind =
5865 getFramePointerKind(Args, Triple: RawTriple);
5866 const char *FPKeepKindStr = nullptr;
5867 switch (FPKeepKind) {
5868 case CodeGenOptions::FramePointerKind::None:
5869 FPKeepKindStr = "-mframe-pointer=none";
5870 break;
5871 case CodeGenOptions::FramePointerKind::Reserved:
5872 FPKeepKindStr = "-mframe-pointer=reserved";
5873 break;
5874 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
5875 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
5876 break;
5877 case CodeGenOptions::FramePointerKind::NonLeaf:
5878 FPKeepKindStr = "-mframe-pointer=non-leaf";
5879 break;
5880 case CodeGenOptions::FramePointerKind::All:
5881 FPKeepKindStr = "-mframe-pointer=all";
5882 break;
5883 }
5884 assert(FPKeepKindStr && "unknown FramePointerKind");
5885 CmdArgs.push_back(Elt: FPKeepKindStr);
5886
5887 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
5888 Neg: options::OPT_fno_zero_initialized_in_bss);
5889
5890 bool OFastEnabled = isOptimizationLevelFast(Args);
5891 if (OFastEnabled)
5892 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
5893 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5894 // enabled. This alias option is being used to simplify the hasFlag logic.
5895 OptSpecifier StrictAliasingAliasOption =
5896 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5897 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5898 // doesn't do any TBAA.
5899 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
5900 Neg: options::OPT_fno_strict_aliasing,
5901 Default: !IsWindowsMSVC && !IsUEFI))
5902 CmdArgs.push_back(Elt: "-relaxed-aliasing");
5903 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
5904 Default: false))
5905 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
5906 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
5907 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
5908 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
5909 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
5910 Neg: options::OPT_fno_strict_enums);
5911 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
5912 Neg: options::OPT_fno_strict_return);
5913 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
5914 Neg: options::OPT_fno_allow_editor_placeholders);
5915 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
5916 Neg: options::OPT_fno_strict_vtable_pointers);
5917 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
5918 Neg: options::OPT_fno_force_emit_vtables);
5919 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5920 Neg: options::OPT_fno_optimize_sibling_calls);
5921 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
5922 Neg: options::OPT_fno_escaping_block_tail_calls);
5923
5924 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
5925 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
5926
5927 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
5928 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
5929
5930 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
5931 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
5932
5933 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
5934 Ids: options::OPT_fno_disable_block_signature_string);
5935
5936 // Handle segmented stacks.
5937 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
5938 Neg: options::OPT_fno_split_stack);
5939
5940 // -fprotect-parens=0 is default.
5941 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
5942 Neg: options::OPT_fno_protect_parens, Default: false))
5943 CmdArgs.push_back(Elt: "-fprotect-parens");
5944
5945 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5946
5947 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
5948 Neg: options::OPT_fno_atomic_remote_memory);
5949 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
5950 Neg: options::OPT_fno_atomic_fine_grained_memory);
5951 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
5952 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
5953
5954 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
5955 const llvm::Triple::ArchType Arch = TC.getArch();
5956 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5957 StringRef V = A->getValue();
5958 if (V == "64")
5959 CmdArgs.push_back(Elt: "-fextend-arguments=64");
5960 else if (V != "32")
5961 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5962 << A->getValue() << A->getOption().getName();
5963 } else
5964 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5965 << A->getOption().getName() << TripleStr;
5966 }
5967
5968 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
5969 if (TC.getArch() == llvm::Triple::avr)
5970 A->render(Args, Output&: CmdArgs);
5971 else
5972 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5973 << A->getAsString(Args) << TripleStr;
5974 }
5975
5976 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
5977 if (TC.getTriple().isX86())
5978 A->render(Args, Output&: CmdArgs);
5979 else if (TC.getTriple().isPPC() &&
5980 (A->getOption().getID() != options::OPT_mlong_double_80))
5981 A->render(Args, Output&: CmdArgs);
5982 else
5983 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5984 << A->getAsString(Args) << TripleStr;
5985 }
5986
5987 // Decide whether to use verbose asm. Verbose assembly is the default on
5988 // toolchains which have the integrated assembler on by default.
5989 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5990 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
5991 Default: IsIntegratedAssemblerDefault))
5992 CmdArgs.push_back(Elt: "-fno-verbose-asm");
5993
5994 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5995 // use that to indicate the MC default in the backend.
5996 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
5997 StringRef V = A->getValue();
5998 unsigned Num;
5999 if (V == "none")
6000 A->render(Args, Output&: CmdArgs);
6001 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
6002 (V.empty() || (V.consume_front(Prefix: ".") &&
6003 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
6004 A->render(Args, Output&: CmdArgs);
6005 else
6006 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6007 << A->getValue() << A->getOption().getName();
6008 }
6009
6010 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6011 // option to disable integrated-as explicitly.
6012 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
6013 CmdArgs.push_back(Elt: "-no-integrated-as");
6014
6015 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
6016 CmdArgs.push_back(Elt: "-mdebug-pass");
6017 CmdArgs.push_back(Elt: "Structure");
6018 }
6019 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
6020 CmdArgs.push_back(Elt: "-mdebug-pass");
6021 CmdArgs.push_back(Elt: "Arguments");
6022 }
6023
6024 // Enable -mconstructor-aliases except on darwin, where we have to work around
6025 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6026 // code, where aliases aren't supported.
6027 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6028 CmdArgs.push_back(Elt: "-mconstructor-aliases");
6029
6030 // Darwin's kernel doesn't support guard variables; just die if we
6031 // try to use them.
6032 if (KernelOrKext && RawTriple.isOSDarwin())
6033 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
6034
6035 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
6036 Ids: options::OPT_mno_ms_bitfields)) {
6037 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
6038 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
6039 else
6040 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
6041 }
6042
6043 if (Triple.isOSCygMing()) {
6044 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
6045 Neg: options::OPT_fno_auto_import);
6046 }
6047
6048 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
6049 Default: Triple.isX86() && IsWindowsMSVC))
6050 CmdArgs.push_back(Elt: "-fms-volatile");
6051
6052 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6053 // defaults to -fno-direct-access-external-data. Pass the option if different
6054 // from the default.
6055 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
6056 Ids: options::OPT_fno_direct_access_external_data)) {
6057 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
6058 (PICLevel == 0))
6059 A->render(Args, Output&: CmdArgs);
6060 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6061 // Some targets default to -fno-direct-access-external-data even for
6062 // -fno-pic.
6063 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
6064 }
6065
6066 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6067 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
6068
6069 // -fhosted is default.
6070 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6071 // use Freestanding.
6072 bool Freestanding =
6073 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
6074 KernelOrKext;
6075 if (Freestanding)
6076 CmdArgs.push_back(Elt: "-ffreestanding");
6077
6078 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
6079
6080 auto SanitizeArgs = TC.getSanitizerArgs(JobArgs: Args);
6081 Args.AddLastArg(Output&: CmdArgs,
6082 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6083
6084 // This is a coarse approximation of what llvm-gcc actually does, both
6085 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6086 // complicated ways.
6087 bool IsAsyncUnwindTablesDefault =
6088 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6089 bool IsSyncUnwindTablesDefault =
6090 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6091
6092 bool AsyncUnwindTables = Args.hasFlag(
6093 Pos: options::OPT_fasynchronous_unwind_tables,
6094 Neg: options::OPT_fno_asynchronous_unwind_tables,
6095 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6096 !Freestanding);
6097 bool UnwindTables =
6098 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6099 Default: IsSyncUnwindTablesDefault && !Freestanding);
6100 if (AsyncUnwindTables)
6101 CmdArgs.push_back(Elt: "-funwind-tables=2");
6102 else if (UnwindTables)
6103 CmdArgs.push_back(Elt: "-funwind-tables=1");
6104
6105 // Sframe unwind tables are independent of the other types. Although also
6106 // defined for aarch64, only x86_64 support is implemented at the moment.
6107 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6108 if (Triple.isOSBinFormatELF() && Triple.isX86())
6109 CmdArgs.push_back(Elt: "--gsframe");
6110 else
6111 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6112 << A->getOption().getName() << TripleStr;
6113 }
6114
6115 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6116 // `--gpu-use-aux-triple-only` is specified.
6117 if (!Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only) &&
6118 (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {
6119 const ArgList &HostArgs =
6120 C.getArgsForToolChain(TC: nullptr, BoundArch: StringRef(), DeviceOffloadKind: Action::OFK_None);
6121 std::string HostCPU =
6122 getCPUName(D, Args: HostArgs, T: *TC.getAuxTriple(), /*FromAs*/ false);
6123 if (!HostCPU.empty()) {
6124 CmdArgs.push_back(Elt: "-aux-target-cpu");
6125 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6126 }
6127 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6128 /*ForAS*/ false, /*IsAux*/ true);
6129 }
6130
6131 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6132
6133 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6134
6135 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6136 StringRef Value = A->getValue();
6137 unsigned TLSSize = 0;
6138 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6139 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6140 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6141 << A->getOption().getName() << TripleStr;
6142 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6143 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6144 << A->getOption().getName() << Value;
6145 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6146 }
6147
6148 if (isTLSDESCEnabled(TC, Args))
6149 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6150
6151 // Add the target cpu
6152 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6153 if (!CPU.empty()) {
6154 CmdArgs.push_back(Elt: "-target-cpu");
6155 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6156 }
6157
6158 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6159
6160 // Add clang-cl arguments.
6161 types::ID InputType = Input.getType();
6162 if (D.IsCLMode())
6163 AddClangCLArgs(Args, InputType, CmdArgs);
6164
6165 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6166 llvm::codegenoptions::NoDebugInfo;
6167 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6168 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6169 DebugInfoKind, DwarfFission);
6170
6171 // Add the split debug info name to the command lines here so we
6172 // can propagate it to the backend.
6173 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6174 (TC.getTriple().isOSBinFormatELF() ||
6175 TC.getTriple().isOSBinFormatWasm() ||
6176 TC.getTriple().isOSBinFormatCOFF()) &&
6177 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6178 isa<BackendJobAction>(Val: JA));
6179 if (SplitDWARF) {
6180 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6181 CmdArgs.push_back(Elt: "-split-dwarf-file");
6182 CmdArgs.push_back(Elt: SplitDWARFOut);
6183 if (DwarfFission == DwarfFissionKind::Split) {
6184 CmdArgs.push_back(Elt: "-split-dwarf-output");
6185 CmdArgs.push_back(Elt: SplitDWARFOut);
6186 }
6187 }
6188
6189 // Pass the linker version in use.
6190 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6191 CmdArgs.push_back(Elt: "-target-linker-version");
6192 CmdArgs.push_back(Elt: A->getValue());
6193 }
6194
6195 // Explicitly error on some things we know we don't support and can't just
6196 // ignore.
6197 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6198 Arg *Unsupported;
6199 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6200 TC.getArch() == llvm::Triple::x86) {
6201 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6202 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6203 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6204 << Unsupported->getOption().getName();
6205 }
6206 // The faltivec option has been superseded by the maltivec option.
6207 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6208 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6209 << Unsupported->getOption().getName()
6210 << "please use -maltivec and include altivec.h explicitly";
6211 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6212 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6213 << Unsupported->getOption().getName() << "please use -mno-altivec";
6214 }
6215
6216 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6217
6218 if (Args.getLastArg(Ids: options::OPT_H)) {
6219 CmdArgs.push_back(Elt: "-H");
6220 CmdArgs.push_back(Elt: "-sys-header-deps");
6221 }
6222 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6223
6224 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6225 CmdArgs.push_back(Elt: "-header-include-file");
6226 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6227 ? D.CCPrintHeadersFilename.c_str()
6228 : "-");
6229 CmdArgs.push_back(Elt: "-sys-header-deps");
6230 CmdArgs.push_back(Elt: Args.MakeArgString(
6231 Str: "-header-include-format=" +
6232 Twine(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6233 CmdArgs.push_back(Elt: Args.MakeArgString(
6234 Str: "-header-include-filtering=" +
6235 Twine(headerIncludeFilteringKindToString(K: D.CCPrintHeadersFiltering))));
6236 }
6237 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6238 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6239
6240 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6241 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6242 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6243 ? D.CCLogDiagnosticsFilename.c_str()
6244 : "-");
6245 }
6246
6247 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6248 // crashes.
6249 if (D.CCGenDiagnostics)
6250 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6251
6252 // Allow backend to put its diagnostic files in the same place as frontend
6253 // crash diagnostics files.
6254 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6255 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6256 CmdArgs.push_back(Elt: "-mllvm");
6257 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6258 }
6259
6260 bool UseSeparateSections = isUseSeparateSections(Triple);
6261
6262 if (Args.hasFlag(Pos: options::OPT_ffunction_sections,
6263 Neg: options::OPT_fno_function_sections, Default: UseSeparateSections)) {
6264 CmdArgs.push_back(Elt: "-ffunction-sections");
6265 }
6266
6267 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6268 Ids: options::OPT_fno_basic_block_address_map)) {
6269 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6270 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
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
6278 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6279 StringRef Val = A->getValue();
6280 if (Val == "labels") {
6281 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6282 << A->getAsString(Args) << /*hasReplacement=*/true
6283 << "-fbasic-block-address-map";
6284 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6285 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6286 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6287 D.Diag(DiagID: diag::err_drv_invalid_value)
6288 << A->getAsString(Args) << A->getValue();
6289 else
6290 A->render(Args, Output&: CmdArgs);
6291 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6292 // "all" is not supported on AArch64 since branch relaxation creates new
6293 // basic blocks for some cross-section branches.
6294 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6295 D.Diag(DiagID: diag::err_drv_invalid_value)
6296 << A->getAsString(Args) << A->getValue();
6297 else
6298 A->render(Args, Output&: CmdArgs);
6299 } else if (Triple.isNVPTX()) {
6300 // Do not pass the option to the GPU compilation. We still want it enabled
6301 // for the host-side compilation, so seeing it here is not an error.
6302 } else if (Val != "none") {
6303 // =none is allowed everywhere. It's useful for overriding the option
6304 // and is the same as not specifying the option.
6305 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6306 << A->getAsString(Args) << TripleStr;
6307 }
6308 }
6309
6310 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
6311 if (Args.hasFlag(Pos: options::OPT_fdata_sections, Neg: options::OPT_fno_data_sections,
6312 Default: UseSeparateSections || HasDefaultDataSections)) {
6313 CmdArgs.push_back(Elt: "-fdata-sections");
6314 }
6315
6316 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6317 Neg: options::OPT_fno_unique_section_names);
6318 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6319 Neg: options::OPT_fno_separate_named_sections);
6320 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6321 Neg: options::OPT_fno_unique_internal_linkage_names);
6322 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6323 Neg: options::OPT_fno_unique_basic_block_section_names);
6324
6325 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions,
6326 Ids: options::OPT_fno_split_machine_functions)) {
6327 if (!A->getOption().matches(ID: options::OPT_fno_split_machine_functions)) {
6328 // This codegen pass is only available on x86 and AArch64 ELF targets.
6329 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6330 A->render(Args, Output&: CmdArgs);
6331 else
6332 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6333 << A->getAsString(Args) << TripleStr;
6334 }
6335 }
6336
6337 if (Arg *A =
6338 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6339 Ids: options::OPT_fno_partition_static_data_sections)) {
6340 if (!A->getOption().matches(
6341 ID: options::OPT_fno_partition_static_data_sections)) {
6342 // This codegen pass is only available on x86 and AArch64 ELF targets.
6343 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6344 A->render(Args, Output&: CmdArgs);
6345 CmdArgs.push_back(Elt: "-mllvm");
6346 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6347 } else
6348 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6349 << A->getAsString(Args) << TripleStr;
6350 }
6351 }
6352
6353 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6354 Ids: options::OPT_finstrument_functions_after_inlining,
6355 Ids: options::OPT_finstrument_function_entry_bare);
6356 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6357 Ids: options::OPT_fno_convergent_functions);
6358
6359 // NVPTX doesn't support PGO or coverage
6360 if (!Triple.isNVPTX())
6361 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6362
6363 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6364
6365 if (getLastProfileSampleUseArg(Args) &&
6366 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6367 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6368 CmdArgs.push_back(Elt: "-mllvm");
6369 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6370 }
6371
6372 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6373 if (RawTriple.isPS() &&
6374 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6375 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6376 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6377 }
6378
6379 // Pass options for controlling the default header search paths.
6380 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6381 CmdArgs.push_back(Elt: "-nostdsysteminc");
6382 CmdArgs.push_back(Elt: "-nobuiltininc");
6383 } else {
6384 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6385 CmdArgs.push_back(Elt: "-nostdsysteminc");
6386 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6387 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6388 }
6389
6390 // Pass the path to compiler resource files.
6391 CmdArgs.push_back(Elt: "-resource-dir");
6392 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6393
6394 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6395
6396 // Add preprocessing options like -I, -D, etc. if we are using the
6397 // preprocessor.
6398 //
6399 // FIXME: Support -fpreprocessed
6400 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6401 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6402
6403 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6404 // that "The compiler can only warn and ignore the option if not recognized".
6405 // When building with ccache, it will pass -D options to clang even on
6406 // preprocessed inputs and configure concludes that -fPIC is not supported.
6407 Args.ClaimAllArgs(Id0: options::OPT_D);
6408
6409 // Warn about ignored options to clang.
6410 for (const Arg *A :
6411 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6412 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6413 A->claim();
6414 }
6415
6416 for (const Arg *A :
6417 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6418 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6419 A->claim();
6420 }
6421
6422 claimNoWarnArgs(Args);
6423
6424 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6425
6426 for (const Arg *A :
6427 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6428 A->claim();
6429 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6430 unsigned WarningNumber;
6431 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6432 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6433 << A->getAsString(Args) << A->getValue();
6434 continue;
6435 }
6436
6437 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6438 CmdArgs.push_back(Elt: Args.MakeArgString(
6439 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6440 }
6441 continue;
6442 }
6443 A->render(Args, Output&: CmdArgs);
6444 }
6445
6446 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6447
6448 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6449 CmdArgs.push_back(Elt: "-pedantic");
6450 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6451 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6452
6453 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6454 Neg: options::OPT_fno_fixed_point);
6455
6456 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_overflow_behavior_types,
6457 Neg: options::OPT_fno_experimental_overflow_behavior_types);
6458
6459 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6460 A->render(Args, Output&: CmdArgs);
6461
6462 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6463 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6464
6465 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6466 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6467
6468 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6469 A->render(Args, Output&: CmdArgs);
6470
6471 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6472 // (-ansi is equivalent to -std=c89 or -std=c++98).
6473 //
6474 // If a std is supplied, only add -trigraphs if it follows the
6475 // option.
6476 bool ImplyVCPPCVer = false;
6477 bool ImplyVCPPCXXVer = false;
6478 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6479 if (Std) {
6480 if (Std->getOption().matches(ID: options::OPT_ansi))
6481 if (types::isCXX(Id: InputType))
6482 CmdArgs.push_back(Elt: "-std=c++98");
6483 else
6484 CmdArgs.push_back(Elt: "-std=c89");
6485 else
6486 Std->render(Args, Output&: CmdArgs);
6487
6488 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6489 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6490 Ids: options::OPT_ftrigraphs,
6491 Ids: options::OPT_fno_trigraphs))
6492 if (A != Std)
6493 A->render(Args, Output&: CmdArgs);
6494 } else {
6495 // Honor -std-default.
6496 //
6497 // FIXME: Clang doesn't correctly handle -std= when the input language
6498 // doesn't match. For the time being just ignore this for C++ inputs;
6499 // eventually we want to do all the standard defaulting here instead of
6500 // splitting it between the driver and clang -cc1.
6501 if (!types::isCXX(Id: InputType)) {
6502 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6503 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6504 /*Joined=*/true);
6505 } else
6506 ImplyVCPPCVer = true;
6507 }
6508 else if (IsWindowsMSVC)
6509 ImplyVCPPCXXVer = true;
6510
6511 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6512 Ids: options::OPT_fno_trigraphs);
6513 }
6514
6515 // GCC's behavior for -Wwrite-strings is a bit strange:
6516 // * In C, this "warning flag" changes the types of string literals from
6517 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6518 // for the discarded qualifier.
6519 // * In C++, this is just a normal warning flag.
6520 //
6521 // Implementing this warning correctly in C is hard, so we follow GCC's
6522 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6523 // a non-const char* in C, rather than using this crude hack.
6524 if (!types::isCXX(Id: InputType)) {
6525 // FIXME: This should behave just like a warning flag, and thus should also
6526 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6527 Arg *WriteStrings =
6528 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6529 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6530 if (WriteStrings &&
6531 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6532 CmdArgs.push_back(Elt: "-fconst-strings");
6533 }
6534
6535 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6536 // during C++ compilation, which it is by default. GCC keeps this define even
6537 // in the presence of '-w', match this behavior bug-for-bug.
6538 if (types::isCXX(Id: InputType) &&
6539 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6540 Default: true)) {
6541 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6542 }
6543
6544 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6545 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6546 if (Asm->getOption().matches(ID: options::OPT_fasm))
6547 CmdArgs.push_back(Elt: "-fgnu-keywords");
6548 else
6549 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6550 }
6551
6552 if (!ShouldEnableAutolink(Args, TC, JA))
6553 CmdArgs.push_back(Elt: "-fno-autolink");
6554
6555 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6556 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6557 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6558 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6559
6560 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6561
6562 if (Args.hasArg(Ids: options::OPT_fexperimental_new_constant_interpreter))
6563 CmdArgs.push_back(Elt: "-fexperimental-new-constant-interpreter");
6564
6565 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6566 CmdArgs.push_back(Elt: "-fbracket-depth");
6567 CmdArgs.push_back(Elt: A->getValue());
6568 }
6569
6570 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6571 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6572 if (A->getNumValues()) {
6573 StringRef bytes = A->getValue();
6574 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6575 } else
6576 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6577 }
6578
6579 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6580 CmdArgs.push_back(Elt: "-relocatable-pch");
6581
6582 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6583 static const char *kCFABIs[] = {
6584 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6585 };
6586
6587 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6588 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6589 else
6590 A->render(Args, Output&: CmdArgs);
6591 }
6592
6593 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6594 CmdArgs.push_back(Elt: "-fconstant-string-class");
6595 CmdArgs.push_back(Elt: A->getValue());
6596 }
6597
6598 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_array_class_EQ)) {
6599 CmdArgs.push_back(Elt: "-fconstant-array-class");
6600 CmdArgs.push_back(Elt: A->getValue());
6601 }
6602 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_dictionary_class_EQ)) {
6603 CmdArgs.push_back(Elt: "-fconstant-dictionary-class");
6604 CmdArgs.push_back(Elt: A->getValue());
6605 }
6606 if (Arg *A =
6607 Args.getLastArg(Ids: options::OPT_fconstant_integer_number_class_EQ)) {
6608 CmdArgs.push_back(Elt: "-fconstant-integer-number-class");
6609 CmdArgs.push_back(Elt: A->getValue());
6610 }
6611 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_float_number_class_EQ)) {
6612 CmdArgs.push_back(Elt: "-fconstant-float-number-class");
6613 CmdArgs.push_back(Elt: A->getValue());
6614 }
6615 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_double_number_class_EQ)) {
6616 CmdArgs.push_back(Elt: "-fconstant-double-number-class");
6617 CmdArgs.push_back(Elt: A->getValue());
6618 }
6619
6620 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
6621 CmdArgs.push_back(Elt: "-ftabstop");
6622 CmdArgs.push_back(Elt: A->getValue());
6623 }
6624
6625 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
6626 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
6627 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
6628
6629 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
6630 Neg: options::OPT_fno_stack_size_section);
6631
6632 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
6633 CmdArgs.push_back(Elt: "-stack-usage-file");
6634
6635 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
6636 SmallString<128> OutputFilename(OutputOpt->getValue());
6637 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
6638 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
6639 } else
6640 CmdArgs.push_back(
6641 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6642 }
6643
6644 CmdArgs.push_back(Elt: "-ferror-limit");
6645 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
6646 CmdArgs.push_back(Elt: A->getValue());
6647 else
6648 CmdArgs.push_back(Elt: "19");
6649
6650 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
6651 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
6652 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
6653 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
6654 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
6655
6656 // Pass -fmessage-length=.
6657 unsigned MessageLength = 0;
6658 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
6659 StringRef V(A->getValue());
6660 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
6661 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6662 << V << A->getOption().getName();
6663 } else {
6664 // If -fmessage-length=N was not specified, determine whether this is a
6665 // terminal and, if so, implicitly define -fmessage-length appropriately.
6666 MessageLength = llvm::sys::Process::StandardErrColumns();
6667 }
6668 if (MessageLength != 0)
6669 CmdArgs.push_back(
6670 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
6671
6672 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
6673 CmdArgs.push_back(
6674 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
6675
6676 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
6677 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
6678 Twine(A->getValue(N: 0))));
6679
6680 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6681 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
6682 Ids: options::OPT_fvisibility_ms_compat)) {
6683 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
6684 A->render(Args, Output&: CmdArgs);
6685 } else {
6686 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6687 CmdArgs.push_back(Elt: "-fvisibility=hidden");
6688 CmdArgs.push_back(Elt: "-ftype-visibility=default");
6689 }
6690 } else if (IsOpenMPDevice) {
6691 // When compiling for the OpenMP device we want protected visibility by
6692 // default. This prevents the device from accidentally preempting code on
6693 // the host, makes the system more robust, and improves performance.
6694 CmdArgs.push_back(Elt: "-fvisibility=protected");
6695 }
6696
6697 // PS4/PS5 process these options in addClangTargetOptions.
6698 if (!RawTriple.isPS()) {
6699 if (const Arg *A =
6700 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
6701 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
6702 if (A->getOption().matches(
6703 ID: options::OPT_fvisibility_from_dllstorageclass)) {
6704 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
6705 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
6706 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
6707 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
6708 Args.AddLastArg(Output&: CmdArgs,
6709 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6710 }
6711 }
6712 }
6713
6714 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
6715 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
6716 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
6717
6718 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
6719 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
6720
6721 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6722 // -fvisibility-global-new-delete=force-hidden.
6723 if (const Arg *A =
6724 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6725 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6726 << A->getAsString(Args) << /*hasReplacement=*/true
6727 << "-fvisibility-global-new-delete=force-hidden";
6728 }
6729
6730 if (const Arg *A =
6731 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
6732 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6733 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
6734 A->render(Args, Output&: CmdArgs);
6735 } else {
6736 assert(A->getOption().matches(
6737 options::OPT_fvisibility_global_new_delete_hidden));
6738 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
6739 }
6740 }
6741
6742 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
6743
6744 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
6745 Neg: options::OPT_fno_new_infallible, Default: false))
6746 CmdArgs.push_back(Elt: "-fnew-infallible");
6747
6748 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
6749 Neg: options::OPT_foperator_names, Default: false))
6750 CmdArgs.push_back(Elt: "-fno-operator-names");
6751
6752 // Forward -f (flag) options which we can pass directly.
6753 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
6754 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
6755 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
6756 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
6757 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
6758 Ids: options::OPT_fno_raw_string_literals);
6759
6760 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
6761 Default: Triple.hasDefaultEmulatedTLS()))
6762 CmdArgs.push_back(Elt: "-femulated-tls");
6763
6764 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
6765 Neg: options::OPT_fno_check_new);
6766
6767 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
6768 // FIXME: There's no reason for this to be restricted to X86. The backend
6769 // code needs to be changed to include the appropriate function calls
6770 // automatically.
6771 if (!Triple.isX86() && !Triple.isAArch64())
6772 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6773 << A->getAsString(Args) << TripleStr;
6774 }
6775
6776 // AltiVec-like language extensions aren't relevant for assembling.
6777 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
6778 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
6779
6780 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
6781 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
6782
6783 // Forward flags for OpenMP. We don't do this if the current action is an
6784 // device offloading action other than OpenMP.
6785 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
6786 Neg: options::OPT_fno_openmp, Default: false) &&
6787 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6788 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
6789 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
6790 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
6791
6792 // Determine if target-fast optimizations should be enabled
6793 bool TargetFastUsed =
6794 Args.hasFlag(Pos: options::OPT_fopenmp_target_fast,
6795 Neg: options::OPT_fno_openmp_target_fast, Default: OFastEnabled);
6796 switch (D.getOpenMPRuntime(Args)) {
6797 case Driver::OMPRT_OMP:
6798 case Driver::OMPRT_IOMP5:
6799 // Clang can generate useful OpenMP code for these two runtime libraries.
6800 CmdArgs.push_back(Elt: "-fopenmp");
6801
6802 // If no option regarding the use of TLS in OpenMP codegeneration is
6803 // given, decide a default based on the target. Otherwise rely on the
6804 // options and pass the right information to the frontend.
6805 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
6806 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6807 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
6808 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6809 Ids: options::OPT_fno_openmp_simd);
6810 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
6811 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6812 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
6813 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
6814 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
6815 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
6816 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6817 Args.AddAllArgs(Output&: CmdArgs,
6818 Id0: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6819 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
6820 Neg: options::OPT_fno_openmp_optimistic_collapse,
6821 /*Default=*/false))
6822 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
6823
6824 // When in OpenMP offloading mode with NVPTX target, forward
6825 // cuda-mode flag
6826 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
6827 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6828 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
6829
6830 // When in OpenMP offloading mode, enable debugging on the device.
6831 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
6832 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
6833 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
6834 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
6835
6836 // When in OpenMP offloading mode, forward assumptions information about
6837 // thread and team counts in the device.
6838 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
6839 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
6840 /*Default=*/false))
6841 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
6842 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
6843 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
6844 /*Default=*/false))
6845 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
6846
6847 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
6848 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_thread_state,
6849 Neg: options::OPT_fno_openmp_assume_no_thread_state,
6850 /*Default=*/TargetFastUsed))
6851 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
6852
6853 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
6854 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_nested_parallelism,
6855 Neg: options::OPT_fno_openmp_assume_no_nested_parallelism,
6856 /*Default=*/TargetFastUsed))
6857 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
6858
6859 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
6860 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
6861 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
6862 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
6863 break;
6864 default:
6865 // By default, if Clang doesn't know how to generate useful OpenMP code
6866 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6867 // down to the actual compilation.
6868 // FIXME: It would be better to have a mode which *only* omits IR
6869 // generation based on the OpenMP support so that we get consistent
6870 // semantic analysis, etc.
6871 break;
6872 }
6873 } else {
6874 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6875 Ids: options::OPT_fno_openmp_simd);
6876 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6877 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
6878 Neg: options::OPT_fno_openmp_extensions);
6879 }
6880 // Forward the offload runtime change to code generation, liboffload implies
6881 // new driver. Otherwise, check if we should forward the new driver to change
6882 // offloading code generation.
6883 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6884 Neg: options::OPT_fno_offload_via_llvm, Default: false)) {
6885 CmdArgs.append(IL: {"--offload-new-driver", "-foffload-via-llvm"});
6886 } else if (Args.hasFlag(Pos: options::OPT_offload_new_driver,
6887 Neg: options::OPT_no_offload_new_driver,
6888 Default: C.getActiveOffloadKinds() != Action::OFK_None)) {
6889 CmdArgs.push_back(Elt: "--offload-new-driver");
6890 }
6891
6892 const XRayArgs &XRay = TC.getXRayArgs(Args);
6893 XRay.addArgs(TC, Args, CmdArgs, InputType);
6894
6895 for (const auto &Filename :
6896 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
6897 if (D.getVFS().exists(Path: Filename))
6898 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
6899 else
6900 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
6901 }
6902
6903 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
6904 StringRef S0 = A->getValue(), S = S0;
6905 unsigned Size, Offset = 0;
6906 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6907 !Triple.isX86() && !Triple.isSystemZ() &&
6908 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
6909 Triple.getArch() == llvm::Triple::ppc64 ||
6910 Triple.getArch() == llvm::Triple::ppc64le)))
6911 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6912 << A->getAsString(Args) << TripleStr;
6913 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
6914 (!S.empty() &&
6915 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
6916 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
6917 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6918 << S0 << A->getOption().getName();
6919 else if (Size < Offset)
6920 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
6921 else {
6922 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
6923 CmdArgs.push_back(Elt: Args.MakeArgString(
6924 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
6925 if (!S.empty())
6926 CmdArgs.push_back(
6927 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
6928 }
6929 }
6930
6931 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
6932
6933 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
6934 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
6935
6936 for (const auto &A :
6937 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
6938 CmdArgs.push_back(
6939 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
6940
6941 if (TC.SupportsProfiling()) {
6942 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
6943
6944 llvm::Triple::ArchType Arch = TC.getArch();
6945 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
6946 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6947 A->render(Args, Output&: CmdArgs);
6948 else
6949 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6950 << A->getAsString(Args) << TripleStr;
6951 }
6952 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
6953 if (Arch == llvm::Triple::systemz)
6954 A->render(Args, Output&: CmdArgs);
6955 else
6956 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6957 << A->getAsString(Args) << TripleStr;
6958 }
6959 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
6960 if (Arch == llvm::Triple::systemz)
6961 A->render(Args, Output&: CmdArgs);
6962 else
6963 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6964 << A->getAsString(Args) << TripleStr;
6965 }
6966 }
6967
6968 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
6969 if (TC.getTriple().isOSzOS()) {
6970 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6971 << A->getAsString(Args) << TripleStr;
6972 }
6973 }
6974 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
6975 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6976 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6977 << A->getAsString(Args) << TripleStr;
6978 }
6979 }
6980 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
6981 if (A->getOption().matches(ID: options::OPT_p)) {
6982 A->claim();
6983 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
6984 CmdArgs.push_back(Elt: "-pg");
6985 }
6986 }
6987
6988 // Reject AIX-specific link options on other targets.
6989 if (!TC.getTriple().isOSAIX()) {
6990 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
6991 Ids: options::OPT_mxcoff_build_id_EQ)) {
6992 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6993 << A->getSpelling() << TripleStr;
6994 }
6995 }
6996
6997 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
6998 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
6999 CmdArgs.push_back(Elt: "-fapple-kext");
7000
7001 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
7002 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
7003 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
7004 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
7005 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
7006 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
7007 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
7008 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
7009 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
7010 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
7011 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
7012
7013 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
7014 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
7015 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
7016 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
7017 }
7018
7019 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
7020 CmdArgs.push_back(Elt: "-ftrapv-handler");
7021 CmdArgs.push_back(Elt: A->getValue());
7022 }
7023
7024 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
7025
7026 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7027 // clang and flang.
7028 renderCommonIntegerOverflowOptions(Args, CmdArgs);
7029
7030 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
7031 Ids: options::OPT_fno_finite_loops);
7032
7033 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
7034 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
7035 Ids: options::OPT_fno_unroll_loops);
7036 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
7037 Ids: options::OPT_fno_loop_interchange);
7038 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
7039 Neg: options::OPT_fno_experimental_loop_fusion);
7040
7041 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
7042
7043 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
7044
7045 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
7046 Neg: options::OPT_mno_speculative_load_hardening);
7047
7048 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7049 RenderSCPOptions(TC, Args, CmdArgs);
7050 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7051
7052 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
7053
7054 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
7055 Neg: options::OPT_mno_stackrealign);
7056
7057 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
7058 StringRef Value = A->getValue();
7059 int64_t Alignment = 0;
7060 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
7061 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7062 << Value << A->getOption().getName();
7063 else if (Alignment & (Alignment - 1))
7064 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
7065 << A->getAsString(Args) << Value;
7066 else
7067 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
7068 }
7069
7070 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
7071 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
7072
7073 if (!Size.empty())
7074 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
7075 else
7076 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
7077 }
7078
7079 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
7080 Neg: options::OPT_mno_stack_arg_probe);
7081
7082 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
7083 Ids: options::OPT_mno_restrict_it)) {
7084 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
7085 CmdArgs.push_back(Elt: "-mllvm");
7086 CmdArgs.push_back(Elt: "-arm-restrict-it");
7087 } else {
7088 CmdArgs.push_back(Elt: "-mllvm");
7089 CmdArgs.push_back(Elt: "-arm-default-it");
7090 }
7091 }
7092
7093 // Forward -cl options to -cc1
7094 RenderOpenCLOptions(Args, CmdArgs, InputType);
7095
7096 // Forward hlsl options to -cc1
7097 RenderHLSLOptions(Args, CmdArgs, InputType);
7098
7099 // Forward OpenACC options to -cc1
7100 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7101
7102 if (IsHIP) {
7103 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
7104 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
7105 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
7106 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
7107 Neg: options::OPT_fno_gpu_allow_device_init);
7108 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
7109 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
7110 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
7111 Neg: options::OPT_fno_hip_kernel_arg_name);
7112 }
7113
7114 if (IsCuda || IsHIP) {
7115 if (IsRDCMode)
7116 CmdArgs.push_back(Elt: "-fgpu-rdc");
7117 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
7118 Neg: options::OPT_fno_gpu_defer_diag);
7119 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
7120 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
7121 Default: false)) {
7122 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
7123 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
7124 }
7125 }
7126
7127 // Forward --no-offloadlib to -cc1.
7128 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7129 CmdArgs.push_back(Elt: "--no-offloadlib");
7130
7131 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7132 CmdArgs.push_back(
7133 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7134
7135 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7136 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7137 SA->getValue()));
7138 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7139 // Emit IBT endbr64 instructions by default
7140 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7141 // jump-table can generate indirect jumps, which are not permitted
7142 CmdArgs.push_back(Elt: "-fno-jump-tables");
7143 }
7144
7145 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7146 CmdArgs.push_back(
7147 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7148
7149 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7150
7151 // Forward -f options with positive and negative forms; we translate these by
7152 // hand. Do not propagate PGO options to the GPU-side compilations as the
7153 // profile info is for the host-side compilation only.
7154 if (!(IsCudaDevice || IsHIPDevice)) {
7155 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7156 auto *PGOArg = Args.getLastArg(
7157 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7158 Ids: options::OPT_fcs_profile_generate,
7159 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7160 Ids: options::OPT_fprofile_use_EQ);
7161 if (PGOArg)
7162 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7163 << "SampleUse with PGO options";
7164
7165 StringRef fname = A->getValue();
7166 if (!llvm::sys::fs::exists(Path: fname))
7167 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7168 else
7169 A->render(Args, Output&: CmdArgs);
7170 }
7171 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7172
7173 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7174 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7175 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7176 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7177 // off.
7178 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7179 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7180 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7181 }
7182 }
7183 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7184
7185 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7186 Neg: options::OPT_fno_assume_sane_operator_new);
7187
7188 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7189 CmdArgs.push_back(Elt: "-fapinotes");
7190 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7191 Neg: options::OPT_fno_apinotes_modules, Default: false))
7192 CmdArgs.push_back(Elt: "-fapinotes-modules");
7193 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7194
7195 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7196 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7197 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7198
7199 // -fblocks=0 is default.
7200 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7201 Default: TC.IsBlocksDefault()) ||
7202 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7203 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7204 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7205 CmdArgs.push_back(Elt: "-fblocks");
7206
7207 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7208 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7209 }
7210
7211 // -fencode-extended-block-signature=1 is default.
7212 if (TC.IsEncodeExtendedBlockSignatureDefault())
7213 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7214
7215 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7216 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7217 types::isCXX(Id: InputType))
7218 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7219
7220 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7221 /*Default=*/false))
7222 CmdArgs.push_back(Elt: "-fdefer-ts");
7223
7224 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7225 Ids: options::OPT_fno_double_square_bracket_attributes);
7226
7227 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7228 Neg: options::OPT_fno_access_control);
7229 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7230 Neg: options::OPT_fno_elide_constructors);
7231
7232 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7233
7234 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7235 (RTTIMode == ToolChain::RM_Disabled)))
7236 CmdArgs.push_back(Elt: "-fno-rtti");
7237
7238 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7239 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7240 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7241 CmdArgs.push_back(Elt: "-fshort-enums");
7242
7243 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7244
7245 // -fuse-cxa-atexit is default.
7246 if (!Args.hasFlag(
7247 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7248 Default: !RawTriple.isOSAIX() &&
7249 (!RawTriple.isOSWindows() ||
7250 RawTriple.isWindowsCygwinEnvironment()) &&
7251 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7252 RawTriple.hasEnvironment())) ||
7253 KernelOrKext)
7254 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7255
7256 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7257 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7258 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7259 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7260
7261 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7262 Neg: options::OPT_fno_use_line_directives);
7263
7264 // -fno-minimize-whitespace is default.
7265 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7266 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7267 types::ID InputType = Inputs[0].getType();
7268 if (!isDerivedFromC(Id: InputType))
7269 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7270 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7271 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7272 }
7273
7274 // -fno-keep-system-includes is default.
7275 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7276 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7277 types::ID InputType = Inputs[0].getType();
7278 if (!isDerivedFromC(Id: InputType))
7279 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7280 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7281 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7282 }
7283
7284 // -fms-extensions=0 is default.
7285 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7286 Default: IsWindowsMSVC || IsUEFI))
7287 CmdArgs.push_back(Elt: "-fms-extensions");
7288
7289 // -fms-compatibility=0 is default.
7290 bool IsMSVCCompat = Args.hasFlag(
7291 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7292 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7293 Neg: options::OPT_fno_ms_extensions, Default: true)));
7294 if (IsMSVCCompat) {
7295 CmdArgs.push_back(Elt: "-fms-compatibility");
7296 if (!types::isCXX(Id: Input.getType()) &&
7297 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7298 CmdArgs.push_back(Elt: "-fms-define-stdc");
7299 }
7300
7301 // -fms-anonymous-structs is disabled by default.
7302 // Determine whether to enable Microsoft named anonymous struct/union support.
7303 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7304 // where the feature can be:
7305 // - Explicitly enabled via -fms-anonymous-structs.
7306 // - Explicitly disabled via fno-ms-anonymous-structs
7307 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7308 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7309 //
7310 // When multiple relevent options are present, the last option on the command
7311 // line takes precedence. This allows users to selectively override implicit
7312 // enablement. Examples:
7313 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7314 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7315 auto MSAnonymousStructsOptionToUseOrNull =
7316 [](const ArgList &Args) -> const char * {
7317 const char *Option = nullptr;
7318 constexpr const char *Enable = "-fms-anonymous-structs";
7319 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7320
7321 // Iterate through all arguments in order to implement "last flag wins".
7322 for (const Arg *A : Args) {
7323 switch (A->getOption().getID()) {
7324 case options::OPT_fms_anonymous_structs:
7325 A->claim();
7326 Option = Enable;
7327 break;
7328 case options::OPT_fno_ms_anonymous_structs:
7329 A->claim();
7330 Option = Disable;
7331 break;
7332 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7333 // feature.
7334 case options::OPT_fms_extensions:
7335 case options::OPT_fms_compatibility:
7336 Option = Enable;
7337 break;
7338 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7339 // disables the feature.
7340 case options::OPT_fno_ms_extensions:
7341 case options::OPT_fno_ms_compatibility:
7342 Option = Disable;
7343 break;
7344 default:
7345 break;
7346 }
7347 }
7348 return Option;
7349 };
7350
7351 // Only pass a flag to CC1 if a relevant option was seen
7352 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7353 CmdArgs.push_back(Elt: MSAnonOpt);
7354
7355 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7356 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7357 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7358
7359 // Handle -fgcc-version, if present.
7360 VersionTuple GNUCVer;
7361 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7362 // Check that the version has 1 to 3 components and the minor and patch
7363 // versions fit in two decimal digits.
7364 StringRef Val = A->getValue();
7365 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7366 bool Invalid = GNUCVer.tryParse(string: Val);
7367 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7368 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7369 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7370 D.Diag(DiagID: diag::err_drv_invalid_value)
7371 << A->getAsString(Args) << A->getValue();
7372 }
7373 } else if (!IsMSVCCompat) {
7374 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7375 GNUCVer = VersionTuple(4, 2, 1);
7376 }
7377 if (!GNUCVer.empty()) {
7378 CmdArgs.push_back(
7379 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7380 }
7381
7382 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7383 if (!MSVT.empty())
7384 CmdArgs.push_back(
7385 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7386
7387 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7388 if (ImplyVCPPCVer) {
7389 StringRef LanguageStandard;
7390 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7391 Std = StdArg;
7392 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7393 .Case(S: "c11", Value: "-std=c11")
7394 .Case(S: "c17", Value: "-std=c17")
7395 // If you add cases below for spellings that are
7396 // not in LangStandards.def, update
7397 // TransferableCommand::tryParseStdArg() in
7398 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7399 // to match.
7400 // TODO: add c23 when MSVC supports it.
7401 .Case(S: "clatest", Value: "-std=c23")
7402 .Default(Value: "");
7403 if (LanguageStandard.empty())
7404 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7405 << StdArg->getAsString(Args);
7406 }
7407 CmdArgs.push_back(Elt: LanguageStandard.data());
7408 }
7409 if (ImplyVCPPCXXVer) {
7410 StringRef LanguageStandard;
7411 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7412 Std = StdArg;
7413 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7414 .Case(S: "c++14", Value: "-std=c++14")
7415 .Case(S: "c++17", Value: "-std=c++17")
7416 .Case(S: "c++20", Value: "-std=c++20")
7417 // If you add cases below for spellings that are
7418 // not in LangStandards.def, update
7419 // TransferableCommand::tryParseStdArg() in
7420 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7421 // to match.
7422 // TODO add c++23 and c++26 when MSVC supports it.
7423 .Case(S: "c++23preview", Value: "-std=c++23")
7424 .Case(S: "c++latest", Value: "-std=c++26")
7425 .Default(Value: "");
7426 if (LanguageStandard.empty())
7427 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7428 << StdArg->getAsString(Args);
7429 }
7430
7431 if (LanguageStandard.empty()) {
7432 if (IsMSVC2015Compatible)
7433 LanguageStandard = "-std=c++14";
7434 else
7435 LanguageStandard = "-std=c++11";
7436 }
7437
7438 CmdArgs.push_back(Elt: LanguageStandard.data());
7439 }
7440
7441 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7442 Neg: options::OPT_fno_borland_extensions);
7443
7444 // -fno-declspec is default, except for PS4/PS5.
7445 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7446 Default: RawTriple.isPS()))
7447 CmdArgs.push_back(Elt: "-fdeclspec");
7448 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7449 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7450
7451 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7452 // than 19.
7453 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7454 Neg: options::OPT_fno_threadsafe_statics,
7455 Default: !types::isOpenCL(Id: InputType) &&
7456 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7457 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7458
7459 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7460 Default: true))
7461 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7462
7463 // Add -fno-assumptions, if it was specified.
7464 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7465 Default: true))
7466 CmdArgs.push_back(Elt: "-fno-assumptions");
7467
7468 // -fgnu-keywords default varies depending on language; only pass if
7469 // specified.
7470 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7471 Ids: options::OPT_fno_gnu_keywords);
7472
7473 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7474 Neg: options::OPT_fno_gnu89_inline);
7475
7476 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7477 Ids: options::OPT_finline_hint_functions,
7478 Ids: options::OPT_fno_inline_functions);
7479 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7480 if (A->getOption().matches(ID: options::OPT_fno_inline))
7481 A->render(Args, Output&: CmdArgs);
7482 } else if (InlineArg) {
7483 InlineArg->render(Args, Output&: CmdArgs);
7484 }
7485
7486 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7487
7488 // FIXME: Find a better way to determine whether we are in C++20.
7489 bool HaveCxx20 =
7490 Std &&
7491 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7492 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7493 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7494 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7495 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7496 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7497 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++latest") ||
7498 Std->containsValue(Value: "gnu++latest"));
7499 bool HaveModules =
7500 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7501
7502 // -fdelayed-template-parsing is default when targeting MSVC.
7503 // Many old Windows SDK versions require this to parse.
7504 //
7505 // According to
7506 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7507 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7508 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7509 // not enable -fdelayed-template-parsing by default after C++20.
7510 //
7511 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7512 // able to disable this by default at some point.
7513 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7514 Neg: options::OPT_fno_delayed_template_parsing,
7515 Default: IsWindowsMSVC && !HaveCxx20)) {
7516 if (HaveCxx20)
7517 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7518
7519 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7520 }
7521
7522 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7523 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7524 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7525 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7526 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7527 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7528 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7529 Default: false))
7530 CmdArgs.push_back(Elt: "-fmodules-codegen");
7531 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7532 Default: false))
7533 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7534
7535 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7536 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7537 Input, CmdArgs);
7538
7539 if (types::isObjC(Id: Input.getType()) &&
7540 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7541 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7542 Default: !Runtime.isNeXTFamily()))
7543 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7544
7545 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7546 Neg: options::OPT_fno_application_extension, Default: false))
7547 CmdArgs.push_back(Elt: "-fapplication-extension");
7548
7549 // Handle GCC-style exception args.
7550 bool EH = false;
7551 if (!C.getDriver().IsCLMode())
7552 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, objcRuntime: Runtime, CmdArgs);
7553
7554 // Handle exception personalities
7555 Arg *A = Args.getLastArg(
7556 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7557 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions);
7558 if (A) {
7559 const Option &Opt = A->getOption();
7560 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7561 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7562 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7563 CmdArgs.push_back(Elt: "-exception-model=seh");
7564 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
7565 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7566 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
7567 CmdArgs.push_back(Elt: "-exception-model=wasm");
7568 } else {
7569 switch (TC.GetExceptionModel(Args)) {
7570 default:
7571 break;
7572 case llvm::ExceptionHandling::DwarfCFI:
7573 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7574 break;
7575 case llvm::ExceptionHandling::SjLj:
7576 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7577 break;
7578 case llvm::ExceptionHandling::WinEH:
7579 CmdArgs.push_back(Elt: "-exception-model=seh");
7580 break;
7581 }
7582 }
7583
7584 // Unwind v2 (epilog) information for x64 Windows.
7585 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_winx64_eh_unwindv2);
7586
7587 // C++ "sane" operator new.
7588 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7589 Neg: options::OPT_fno_assume_sane_operator_new);
7590
7591 // -fassume-unique-vtables is on by default.
7592 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
7593 Neg: options::OPT_fno_assume_unique_vtables);
7594
7595 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7596 // by default.
7597 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
7598 Ids: options::OPT_fno_sized_deallocation);
7599
7600 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7601 // by default.
7602 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
7603 Ids: options::OPT_fno_aligned_allocation,
7604 Ids: options::OPT_faligned_new_EQ)) {
7605 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
7606 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
7607 else
7608 CmdArgs.push_back(Elt: "-faligned-allocation");
7609 }
7610
7611 // The default new alignment can be specified using a dedicated option or via
7612 // a GCC-compatible option that also turns on aligned allocation.
7613 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
7614 Ids: options::OPT_faligned_new_EQ))
7615 CmdArgs.push_back(
7616 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
7617
7618 // -fconstant-cfstrings is default, and may be subject to argument translation
7619 // on Darwin.
7620 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
7621 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
7622 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
7623 Neg: options::OPT_mno_constant_cfstrings, Default: true))
7624 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
7625
7626 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
7627 Neg: options::OPT_fno_pascal_strings);
7628
7629 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7630 // -fno-pack-struct doesn't apply to -fpack-struct=.
7631 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
7632 CmdArgs.push_back(
7633 Elt: Args.MakeArgString(Str: "-fpack-struct=" + Twine(A->getValue())));
7634 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
7635 Neg: options::OPT_fno_pack_struct, Default: false)) {
7636 CmdArgs.push_back(Elt: "-fpack-struct=1");
7637 }
7638
7639 // Handle -fmax-type-align=N and -fno-type-align
7640 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
7641 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
7642 if (!SkipMaxTypeAlign) {
7643 std::string MaxTypeAlignStr = "-fmax-type-align=";
7644 MaxTypeAlignStr += A->getValue();
7645 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7646 }
7647 } else if (RawTriple.isOSDarwin()) {
7648 if (!SkipMaxTypeAlign) {
7649 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7650 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7651 }
7652 }
7653
7654 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
7655 CmdArgs.push_back(Elt: "-Qn");
7656
7657 // -fno-common is the default, set -fcommon only when that flag is set.
7658 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
7659
7660 // -fsigned-bitfields is default, and clang doesn't yet support
7661 // -funsigned-bitfields.
7662 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
7663 Neg: options::OPT_funsigned_bitfields, Default: true))
7664 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
7665 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
7666
7667 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7668 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
7669 D.Diag(DiagID: diag::err_drv_clang_unsupported)
7670 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
7671
7672 // -finput_charset=UTF-8 is default. Reject others
7673 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
7674 StringRef value = inputCharset->getValue();
7675 if (!value.equals_insensitive(RHS: "utf-8"))
7676 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7677 << value;
7678 }
7679
7680 // -fexec_charset=UTF-8 is default. Reject others
7681 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
7682 StringRef value = execCharset->getValue();
7683 if (!value.equals_insensitive(RHS: "utf-8"))
7684 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7685 << value;
7686 }
7687
7688 RenderDiagnosticsOptions(D, Args, CmdArgs);
7689
7690 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
7691 Neg: options::OPT_fno_asm_blocks);
7692
7693 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
7694 Neg: options::OPT_fno_gnu_inline_asm);
7695
7696 handleVectorizeLoopsArgs(Args, CmdArgs);
7697 handleVectorizeSLPArgs(Args, CmdArgs);
7698
7699 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
7700 if (!VecWidth.empty())
7701 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
7702
7703 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
7704 Args.AddLastArg(Output&: CmdArgs,
7705 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
7706
7707 // -fdollars-in-identifiers default varies depending on platform and
7708 // language; only pass if specified.
7709 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
7710 Ids: options::OPT_fno_dollars_in_identifiers)) {
7711 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
7712 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
7713 else
7714 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
7715 }
7716
7717 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
7718 Neg: options::OPT_fno_apple_pragma_pack);
7719
7720 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7721 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7722 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7723
7724 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
7725 Neg: options::OPT_fno_rewrite_imports, Default: false);
7726 if (RewriteImports)
7727 CmdArgs.push_back(Elt: "-frewrite-imports");
7728
7729 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
7730 Neg: options::OPT_fno_directives_only);
7731
7732 // Enable rewrite includes if the user's asked for it or if we're generating
7733 // diagnostics.
7734 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7735 // nice to enable this when doing a crashdump for modules as well.
7736 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
7737 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
7738 (C.isForDiagnostics() && !HaveModules))
7739 CmdArgs.push_back(Elt: "-frewrite-includes");
7740
7741 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
7742 Neg: options::OPT_fno_zos_extensions, Default: false))
7743 CmdArgs.push_back(Elt: "-fzos-extensions");
7744 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
7745 CmdArgs.push_back(Elt: "-fno-zos-extensions");
7746
7747 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7748 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
7749 Ids: options::OPT_traditional_cpp)) {
7750 if (isa<PreprocessJobAction>(Val: JA))
7751 CmdArgs.push_back(Elt: "-traditional-cpp");
7752 else
7753 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
7754 }
7755
7756 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
7757 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
7758 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
7759
7760 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
7761
7762 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_extract_summaries);
7763 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_tu_summary_file);
7764
7765 // Handle serialized diagnostics.
7766 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
7767 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
7768 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
7769 }
7770
7771 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
7772 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
7773
7774 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
7775 A->render(Args, Output&: CmdArgs);
7776 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
7777 A && A->containsValue(Value: "g")) {
7778 // Set -fextend-variable-liveness=all by default at -Og.
7779 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
7780 }
7781
7782 // Forward -fcomment-block-commands to -cc1.
7783 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
7784 // Forward -fparse-all-comments to -cc1.
7785 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
7786
7787 // Turn -fplugin=name.so into -load name.so
7788 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
7789 CmdArgs.push_back(Elt: "-load");
7790 CmdArgs.push_back(Elt: A->getValue());
7791 A->claim();
7792 }
7793
7794 // Turn -fplugin-arg-pluginname-key=value into
7795 // -plugin-arg-pluginname key=value
7796 // GCC has an actual plugin_argument struct with key/value pairs that it
7797 // passes to its plugins, but we don't, so just pass it on as-is.
7798 //
7799 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7800 // argument key are allowed to contain dashes. GCC therefore only
7801 // allows dashes in the key. We do the same.
7802 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
7803 auto ArgValue = StringRef(A->getValue());
7804 auto FirstDashIndex = ArgValue.find(C: '-');
7805 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
7806 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
7807
7808 A->claim();
7809 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7810 if (PluginName.empty()) {
7811 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7812 } else {
7813 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
7814 << PluginName << A->getAsString(Args);
7815 }
7816 continue;
7817 }
7818
7819 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
7820 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
7821 }
7822
7823 // Forward -fpass-plugin=name.so to -cc1.
7824 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
7825 CmdArgs.push_back(
7826 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
7827 A->claim();
7828 }
7829
7830 // Forward --vfsoverlay to -cc1.
7831 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
7832 CmdArgs.push_back(Elt: "--vfsoverlay");
7833 CmdArgs.push_back(Elt: A->getValue());
7834 A->claim();
7835 }
7836
7837 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
7838 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
7839
7840 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
7841 Neg: options::OPT_fno_experimental_late_parse_attributes);
7842
7843 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
7844 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
7845 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
7846 A->render(Args, Output&: CmdArgs);
7847 else
7848 CmdArgs.push_back(Elt: Args.MakeArgString(
7849 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
7850 }
7851
7852 if (Args.hasFlag(
7853 Pos: options::OPT_fexperimental_allow_pointer_field_protection_attr,
7854 Neg: options::OPT_fno_experimental_allow_pointer_field_protection_attr,
7855 Default: false) ||
7856 Args.hasFlag(Pos: options::OPT_fexperimental_pointer_field_protection_abi,
7857 Neg: options::OPT_fno_experimental_pointer_field_protection_abi,
7858 Default: false))
7859 CmdArgs.push_back(Elt: "-fexperimental-allow-pointer-field-protection-attr");
7860
7861 if (!IsCudaDevice) {
7862 Args.addOptInFlag(
7863 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_abi,
7864 Neg: options::OPT_fno_experimental_pointer_field_protection_abi);
7865 Args.addOptInFlag(
7866 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_tagged,
7867 Neg: options::OPT_fno_experimental_pointer_field_protection_tagged);
7868 }
7869
7870 // Setup statistics file output.
7871 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7872 if (!StatsFile.empty()) {
7873 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
7874 if (D.CCPrintInternalStats)
7875 CmdArgs.push_back(Elt: "-stats-file-append");
7876 }
7877
7878 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7879 // parser.
7880 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
7881 Arg->claim();
7882 // -finclude-default-header flag is for preprocessor,
7883 // do not pass it to other cc1 commands when save-temps is enabled
7884 if (C.getDriver().isSaveTempsEnabled() &&
7885 !isa<PreprocessJobAction>(Val: JA)) {
7886 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7887 continue;
7888 }
7889 CmdArgs.push_back(Elt: Arg->getValue());
7890 }
7891 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
7892 A->claim();
7893
7894 // We translate this by hand to the -cc1 argument, since nightly test uses
7895 // it and developers have been trained to spell it with -mllvm. Both
7896 // spellings are now deprecated and should be removed.
7897 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
7898 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
7899 } else {
7900 A->render(Args, Output&: CmdArgs);
7901 }
7902 }
7903
7904 // This needs to run after -Xclang argument forwarding to pick up the target
7905 // features enabled through -Xclang -target-feature flags.
7906 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
7907
7908 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
7909
7910#if CLANG_ENABLE_CIR
7911 // Forward -mmlir arguments to to the MLIR option parser.
7912 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
7913 A->claim();
7914 A->render(Args, CmdArgs);
7915 }
7916#endif // CLANG_ENABLE_CIR
7917
7918 // With -save-temps, we want to save the unoptimized bitcode output from the
7919 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7920 // by the frontend.
7921 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7922 // has slightly different breakdown between stages.
7923 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7924 // pristine IR generated by the frontend. Ideally, a new compile action should
7925 // be added so both IR can be captured.
7926 if ((C.getDriver().isSaveTempsEnabled() ||
7927 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
7928 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7929 isa<CompileJobAction>(Val: JA))
7930 CmdArgs.push_back(Elt: "-disable-llvm-passes");
7931
7932 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
7933
7934 const char *Exec = D.getClangProgramPath();
7935
7936 // Optionally embed the -cc1 level arguments into the debug info or a
7937 // section, for build analysis.
7938 // Also record command line arguments into the debug info if
7939 // -grecord-gcc-switches options is set on.
7940 // By default, -gno-record-gcc-switches is set on and no recording.
7941 auto GRecordSwitches = false;
7942 auto FRecordSwitches = false;
7943 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches)) {
7944 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
7945 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7946 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
7947 CmdArgs.push_back(Elt: FlagsArgString);
7948 }
7949 if (FRecordSwitches) {
7950 CmdArgs.push_back(Elt: "-record-command-line");
7951 CmdArgs.push_back(Elt: FlagsArgString);
7952 }
7953 }
7954
7955 // Host-side offloading compilation receives all device-side outputs. Include
7956 // them in the host compilation depending on the target. If the host inputs
7957 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7958 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7959 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7960 CmdArgs.push_back(Elt: CudaDeviceInput->getFilename());
7961 } else if (!HostOffloadingInputs.empty()) {
7962 if ((IsCuda || IsHIP) && !IsRDCMode) {
7963 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7964 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7965 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
7966 } else {
7967 for (const InputInfo Input : HostOffloadingInputs)
7968 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
7969 TC.getInputFilename(Input)));
7970 }
7971 }
7972
7973 if (IsCuda) {
7974 if (Args.hasFlag(Pos: options::OPT_fcuda_short_ptr,
7975 Neg: options::OPT_fno_cuda_short_ptr, Default: false))
7976 CmdArgs.push_back(Elt: "-fcuda-short-ptr");
7977 }
7978
7979 if (IsCuda || IsHIP) {
7980 // Determine the original source input.
7981 const Action *SourceAction = &JA;
7982 while (SourceAction->getKind() != Action::InputClass) {
7983 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7984 SourceAction = SourceAction->getInputs()[0];
7985 }
7986 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
7987 if (!CUID.empty())
7988 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
7989
7990 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7991 // be overriden by -fno-gpu-approx-transcendentals.
7992 bool UseApproxTranscendentals = Args.hasFlag(
7993 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
7994 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
7995 Neg: options::OPT_fno_gpu_approx_transcendentals,
7996 Default: UseApproxTranscendentals))
7997 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
7998 } else {
7999 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
8000 Ids: options::OPT_fno_gpu_approx_transcendentals);
8001 }
8002
8003 if (IsHIP) {
8004 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
8005 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
8006 }
8007
8008 Args.AddAllArgs(Output&: CmdArgs,
8009 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8010
8011 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
8012 Ids: options::OPT_fno_offload_uniform_block);
8013
8014 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
8015 Ids: options::OPT_fno_offload_implicit_host_device_templates);
8016
8017 if (IsCudaDevice || IsHIPDevice) {
8018 StringRef InlineThresh =
8019 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
8020 if (!InlineThresh.empty()) {
8021 std::string ArgStr =
8022 std::string("-inline-threshold=") + InlineThresh.str();
8023 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
8024 }
8025 }
8026
8027 if (IsHIPDevice)
8028 Args.addOptOutFlag(Output&: CmdArgs,
8029 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8030 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8031
8032 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8033 // to specify the result of the compile phase on the host, so the meaningful
8034 // device declarations can be identified. Also, -fopenmp-is-target-device is
8035 // passed along to tell the frontend that it is generating code for a device,
8036 // so that only the relevant declarations are emitted.
8037 if (IsOpenMPDevice) {
8038 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
8039 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8040 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
8041 CmdArgs.push_back(Elt: "-fcuda-is-device");
8042
8043 if (OpenMPDeviceInput) {
8044 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
8045 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
8046 }
8047 }
8048
8049 if (Triple.isAMDGPU()) {
8050 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8051
8052 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
8053 Neg: options::OPT_mno_unsafe_fp_atomics);
8054 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
8055 Neg: options::OPT_mno_amdgpu_ieee);
8056 }
8057
8058 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8059
8060 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
8061 Neg: options::OPT_fno_devirtualize_speculatively,
8062 /*Default value*/ Default: false))
8063 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
8064
8065 bool VirtualFunctionElimination =
8066 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
8067 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
8068 if (VirtualFunctionElimination) {
8069 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8070 // in the future).
8071 if (LTOMode != LTOK_Full)
8072 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8073 << "-fvirtual-function-elimination"
8074 << "-flto=full";
8075
8076 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
8077 }
8078
8079 // VFE requires whole-program-vtables, and enables it by default.
8080 bool WholeProgramVTables = Args.hasFlag(
8081 Pos: options::OPT_fwhole_program_vtables,
8082 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
8083 if (VirtualFunctionElimination && !WholeProgramVTables) {
8084 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8085 << "-fno-whole-program-vtables"
8086 << "-fvirtual-function-elimination";
8087 }
8088
8089 if (WholeProgramVTables) {
8090 // PS4 uses the legacy LTO API, which does not support this feature in
8091 // ThinLTO mode.
8092 bool IsPS4 = getToolChain().getTriple().isPS4();
8093
8094 // Check if we passed LTO options but they were suppressed because this is a
8095 // device offloading action, or we passed device offload LTO options which
8096 // were suppressed because this is not the device offload action.
8097 // Check if we are using PS4 in regular LTO mode.
8098 // Otherwise, issue an error.
8099
8100 auto OtherLTOMode =
8101 IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();
8102 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8103
8104 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8105 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
8106 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8107 << "-fwhole-program-vtables"
8108 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8109
8110 // Propagate -fwhole-program-vtables if this is an LTO compile.
8111 if (IsUsingLTO)
8112 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
8113 }
8114
8115 bool DefaultsSplitLTOUnit =
8116 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8117 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8118 (!Triple.isPS4() && UnifiedLTO);
8119 bool SplitLTOUnit =
8120 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
8121 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
8122 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8123 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8124 << "-fsanitize=cfi";
8125 if (SplitLTOUnit)
8126 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
8127
8128 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
8129 Ids: options::OPT_fno_fat_lto_objects)) {
8130 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
8131 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8132 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8133 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8134 << A->getAsString(Args) << TC.getTripleString();
8135 }
8136 CmdArgs.push_back(Elt: Args.MakeArgString(
8137 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8138 CmdArgs.push_back(Elt: "-flto-unit");
8139 CmdArgs.push_back(Elt: "-ffat-lto-objects");
8140 A->render(Args, Output&: CmdArgs);
8141 }
8142 }
8143
8144 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8145
8146 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8147 Ids: options::OPT_fno_force_enable_int128)) {
8148 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8149 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8150 }
8151
8152 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8153 Neg: options::OPT_fno_keep_static_consts);
8154 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8155 Neg: options::OPT_fno_keep_persistent_storage_variables);
8156 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8157 Neg: options::OPT_fno_complete_member_pointers);
8158 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8159 A->render(Args, Output&: CmdArgs);
8160
8161 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8162
8163 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8164
8165 if (Triple.isAArch64() &&
8166 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8167 (Triple.isAndroid() && Triple.isAndroidVersionLT(Major: 23)) ||
8168 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8169 // Disable Function Multiversioning on AArch64 target.
8170 CmdArgs.push_back(Elt: "-target-feature");
8171 CmdArgs.push_back(Elt: "-fmv");
8172 }
8173
8174 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8175 Default: (TC.getTriple().isOSBinFormatELF() ||
8176 TC.getTriple().isOSBinFormatCOFF()) &&
8177 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8178 !TC.getTriple().isOSNetBSD() &&
8179 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8180 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8181 CmdArgs.push_back(Elt: "-faddrsig");
8182
8183 const bool HasDefaultDwarf2CFIASM =
8184 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8185 (EH || UnwindTables || AsyncUnwindTables ||
8186 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8187 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8188 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8189 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8190
8191 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8192 std::string Str = A->getAsString(Args);
8193 if (!TC.getTriple().isOSBinFormatELF())
8194 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8195 << Str << TC.getTripleString();
8196 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8197 }
8198
8199 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8200 // the -cc1 command easier to edit when reproducing compiler crashes.
8201 if (Output.getType() == types::TY_Dependencies) {
8202 // Handled with other dependency code.
8203 } else if (Output.isFilename()) {
8204 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8205 Output.getType() == clang::driver::types::TY_IFS) {
8206 SmallString<128> OutputFilename(Output.getFilename());
8207 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8208 CmdArgs.push_back(Elt: "-o");
8209 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8210 } else {
8211 CmdArgs.push_back(Elt: "-o");
8212 CmdArgs.push_back(Elt: Output.getFilename());
8213 }
8214 } else {
8215 assert(Output.isNothing() && "Invalid output.");
8216 }
8217
8218 addDashXForInput(Args, Input, CmdArgs);
8219
8220 ArrayRef<InputInfo> FrontendInputs = Input;
8221 if (IsExtractAPI)
8222 FrontendInputs = ExtractAPIInputs;
8223 else if (Input.isNothing())
8224 FrontendInputs = {};
8225
8226 for (const InputInfo &Input : FrontendInputs) {
8227 if (Input.isFilename())
8228 CmdArgs.push_back(Elt: Input.getFilename());
8229 else
8230 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8231 }
8232
8233 if (D.CC1Main && !D.CCGenDiagnostics) {
8234 // Invoke the CC1 directly in this process
8235 C.addCommand(C: std::make_unique<CC1Command>(
8236 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8237 args: Output, args: D.getPrependArg()));
8238 } else {
8239 C.addCommand(C: std::make_unique<Command>(
8240 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8241 args: Output, args: D.getPrependArg()));
8242 }
8243
8244 // Make the compile command echo its inputs for /showFilenames.
8245 if (Output.getType() == types::TY_Object &&
8246 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8247 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8248 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8249 }
8250
8251 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8252 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8253 !Args.hasArg(Ids: options::OPT_mfentry))
8254 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8255 << A->getAsString(Args);
8256
8257 // Claim some arguments which clang supports automatically.
8258
8259 // -fpch-preprocess is used with gcc to add a special marker in the output to
8260 // include the PCH file.
8261 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8262
8263 // Claim some arguments which clang doesn't support, but we don't
8264 // care to warn the user about.
8265 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8266 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8267
8268 // Disable warnings for clang -E -emit-llvm foo.c
8269 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8270}
8271
8272Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8273 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8274 // as it is for other tools. Some operations on a Tool actually test
8275 // whether that tool is Clang based on the Tool's Name as a string.
8276 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8277
8278Clang::~Clang() {}
8279
8280/// Add options related to the Objective-C runtime/ABI.
8281///
8282/// Returns true if the runtime is non-fragile.
8283ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8284 const InputInfoList &inputs,
8285 ArgStringList &cmdArgs,
8286 RewriteKind rewriteKind) const {
8287 // Look for the controlling runtime option.
8288 Arg *runtimeArg =
8289 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8290 Ids: options::OPT_fobjc_runtime_EQ);
8291
8292 // Just forward -fobjc-runtime= to the frontend. This supercedes
8293 // options about fragility.
8294 if (runtimeArg &&
8295 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8296 ObjCRuntime runtime;
8297 StringRef value = runtimeArg->getValue();
8298 if (runtime.tryParse(input: value)) {
8299 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8300 << value;
8301 }
8302 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8303 (runtime.getVersion() >= VersionTuple(2, 0)))
8304 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8305 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8306 getToolChain().getDriver().Diag(
8307 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8308 << runtime.getVersion().getMajor();
8309 }
8310
8311 runtimeArg->render(Args: args, Output&: cmdArgs);
8312 return runtime;
8313 }
8314
8315 // Otherwise, we'll need the ABI "version". Version numbers are
8316 // slightly confusing for historical reasons:
8317 // 1 - Traditional "fragile" ABI
8318 // 2 - Non-fragile ABI, version 1
8319 // 3 - Non-fragile ABI, version 2
8320 unsigned objcABIVersion = 1;
8321 // If -fobjc-abi-version= is present, use that to set the version.
8322 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8323 StringRef value = abiArg->getValue();
8324 if (value == "1")
8325 objcABIVersion = 1;
8326 else if (value == "2")
8327 objcABIVersion = 2;
8328 else if (value == "3")
8329 objcABIVersion = 3;
8330 else
8331 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8332 } else {
8333 // Otherwise, determine if we are using the non-fragile ABI.
8334 bool nonFragileABIIsDefault =
8335 (rewriteKind == RK_NonFragile ||
8336 (rewriteKind == RK_None &&
8337 getToolChain().IsObjCNonFragileABIDefault()));
8338 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8339 Neg: options::OPT_fno_objc_nonfragile_abi,
8340 Default: nonFragileABIIsDefault)) {
8341// Determine the non-fragile ABI version to use.
8342#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8343 unsigned nonFragileABIVersion = 1;
8344#else
8345 unsigned nonFragileABIVersion = 2;
8346#endif
8347
8348 if (Arg *abiArg =
8349 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8350 StringRef value = abiArg->getValue();
8351 if (value == "1")
8352 nonFragileABIVersion = 1;
8353 else if (value == "2")
8354 nonFragileABIVersion = 2;
8355 else
8356 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8357 << value;
8358 }
8359
8360 objcABIVersion = 1 + nonFragileABIVersion;
8361 } else {
8362 objcABIVersion = 1;
8363 }
8364 }
8365
8366 // We don't actually care about the ABI version other than whether
8367 // it's non-fragile.
8368 bool isNonFragile = objcABIVersion != 1;
8369
8370 // If we have no runtime argument, ask the toolchain for its default runtime.
8371 // However, the rewriter only really supports the Mac runtime, so assume that.
8372 ObjCRuntime runtime;
8373 if (!runtimeArg) {
8374 switch (rewriteKind) {
8375 case RK_None:
8376 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8377 break;
8378 case RK_Fragile:
8379 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8380 break;
8381 case RK_NonFragile:
8382 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8383 break;
8384 }
8385
8386 // -fnext-runtime
8387 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8388 // On Darwin, make this use the default behavior for the toolchain.
8389 if (getToolChain().getTriple().isOSDarwin()) {
8390 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8391
8392 // Otherwise, build for a generic macosx port.
8393 } else {
8394 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8395 }
8396
8397 // -fgnu-runtime
8398 } else {
8399 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8400 // Legacy behaviour is to target the gnustep runtime if we are in
8401 // non-fragile mode or the GCC runtime in fragile mode.
8402 if (isNonFragile)
8403 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8404 else
8405 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8406 }
8407
8408 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8409 return types::isObjC(Id: input.getType());
8410 }))
8411 cmdArgs.push_back(
8412 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8413 return runtime;
8414}
8415
8416static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8417 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8418 I += HaveDash;
8419 return !HaveDash;
8420}
8421
8422namespace {
8423struct EHFlags {
8424 bool Synch = false;
8425 bool Asynch = false;
8426 bool NoUnwindC = false;
8427};
8428} // end anonymous namespace
8429
8430/// /EH controls whether to run destructor cleanups when exceptions are
8431/// thrown. There are three modifiers:
8432/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8433/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8434/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8435/// - c: Assume that extern "C" functions are implicitly nounwind.
8436/// The default is /EHs-c-, meaning cleanups are disabled.
8437static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8438 bool isWindowsMSVC) {
8439 EHFlags EH;
8440
8441 std::vector<std::string> EHArgs =
8442 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8443 for (const auto &EHVal : EHArgs) {
8444 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8445 switch (EHVal[I]) {
8446 case 'a':
8447 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8448 if (EH.Asynch) {
8449 // Async exceptions are Windows MSVC only.
8450 if (!isWindowsMSVC) {
8451 EH.Asynch = false;
8452 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8453 continue;
8454 }
8455 EH.Synch = false;
8456 }
8457 continue;
8458 case 'c':
8459 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8460 continue;
8461 case 's':
8462 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8463 if (EH.Synch)
8464 EH.Asynch = false;
8465 continue;
8466 default:
8467 break;
8468 }
8469 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8470 break;
8471 }
8472 }
8473 // The /GX, /GX- flags are only processed if there are not /EH flags.
8474 // The default is that /GX is not specified.
8475 if (EHArgs.empty() &&
8476 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8477 /*Default=*/false)) {
8478 EH.Synch = true;
8479 EH.NoUnwindC = true;
8480 }
8481
8482 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8483 EH.Synch = false;
8484 EH.NoUnwindC = false;
8485 EH.Asynch = false;
8486 }
8487
8488 return EH;
8489}
8490
8491void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8492 ArgStringList &CmdArgs) const {
8493 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8494
8495 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8496
8497 if (Arg *ShowIncludes =
8498 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8499 Ids: options::OPT__SLASH_showIncludes_user)) {
8500 CmdArgs.push_back(Elt: "--show-includes");
8501 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8502 CmdArgs.push_back(Elt: "-sys-header-deps");
8503 }
8504
8505 // This controls whether or not we emit RTTI data for polymorphic types.
8506 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8507 /*Default=*/false))
8508 CmdArgs.push_back(Elt: "-fno-rtti-data");
8509
8510 // This controls whether or not we emit stack-protector instrumentation.
8511 // In MSVC, Buffer Security Check (/GS) is on by default.
8512 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8513 /*Default=*/true)) {
8514 CmdArgs.push_back(Elt: "-stack-protector");
8515 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8516 }
8517
8518 const Driver &D = getToolChain().getDriver();
8519
8520 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8521 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8522 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8523 if (types::isCXX(Id: InputType))
8524 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8525 CmdArgs.push_back(Elt: "-fexceptions");
8526 if (EH.Asynch)
8527 CmdArgs.push_back(Elt: "-fasync-exceptions");
8528 }
8529 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8530 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8531
8532 // /EP should expand to -E -P.
8533 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
8534 CmdArgs.push_back(Elt: "-E");
8535 CmdArgs.push_back(Elt: "-P");
8536 }
8537
8538 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
8539 Neg: options::OPT__SLASH_Zc_dllexportInlines,
8540 Default: false)) {
8541 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8542 }
8543
8544 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
8545 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
8546 CmdArgs.push_back(Elt: "-fno-wchar");
8547 }
8548
8549 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8550 llvm::Triple::ArchType Arch = getToolChain().getArch();
8551 std::vector<std::string> Values =
8552 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
8553 if (!Values.empty()) {
8554 llvm::SmallSet<std::string, 4> SupportedArches;
8555 if (Arch == llvm::Triple::x86)
8556 SupportedArches.insert(V: "IA32");
8557
8558 for (auto &V : Values)
8559 if (!SupportedArches.contains(V))
8560 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8561 << std::string("/arch:").append(str: V) << "/kernel";
8562 }
8563
8564 CmdArgs.push_back(Elt: "-fno-rtti");
8565 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
8566 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
8567 << "/kernel";
8568 }
8569
8570 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
8571 Ids: options::OPT__SLASH_vlen_EQ_256,
8572 Ids: options::OPT__SLASH_vlen_EQ_512)) {
8573 llvm::Triple::ArchType AT = getToolChain().getArch();
8574 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8575 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
8576 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8577 "AVX10.2"};
8578
8579 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
8580 if (Arch512.contains(V: Arch))
8581 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
8582 else
8583 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8584 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
8585 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
8586 if (Arch512.contains(V: Arch))
8587 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8588 else if (Arch != "AVX" && Arch != "AVX2")
8589 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8590 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
8591 } else {
8592 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8593 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8594 }
8595 } else {
8596 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
8597 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8598 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8599 }
8600
8601 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
8602 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
8603 if (MostGeneralArg && BestCaseArg)
8604 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8605 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8606
8607 if (MostGeneralArg) {
8608 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
8609 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
8610 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
8611
8612 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8613 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8614 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8615 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8616 << FirstConflict->getAsString(Args)
8617 << SecondConflict->getAsString(Args);
8618
8619 if (SingleArg)
8620 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
8621 else if (MultipleArg)
8622 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
8623 else
8624 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
8625 }
8626
8627 if (Args.hasArg(Ids: options::OPT_regcall4))
8628 CmdArgs.push_back(Elt: "-regcall4");
8629
8630 // Parse the default calling convention options.
8631 if (Arg *CCArg =
8632 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
8633 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
8634 Ids: options::OPT__SLASH_Gregcall)) {
8635 unsigned DCCOptId = CCArg->getOption().getID();
8636 const char *DCCFlag = nullptr;
8637 bool ArchSupported = !isNVPTX;
8638 llvm::Triple::ArchType Arch = getToolChain().getArch();
8639 switch (DCCOptId) {
8640 case options::OPT__SLASH_Gd:
8641 DCCFlag = "-fdefault-calling-conv=cdecl";
8642 break;
8643 case options::OPT__SLASH_Gr:
8644 ArchSupported = Arch == llvm::Triple::x86;
8645 DCCFlag = "-fdefault-calling-conv=fastcall";
8646 break;
8647 case options::OPT__SLASH_Gz:
8648 ArchSupported = Arch == llvm::Triple::x86;
8649 DCCFlag = "-fdefault-calling-conv=stdcall";
8650 break;
8651 case options::OPT__SLASH_Gv:
8652 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8653 DCCFlag = "-fdefault-calling-conv=vectorcall";
8654 break;
8655 case options::OPT__SLASH_Gregcall:
8656 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8657 DCCFlag = "-fdefault-calling-conv=regcall";
8658 break;
8659 }
8660
8661 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8662 if (ArchSupported && DCCFlag)
8663 CmdArgs.push_back(Elt: DCCFlag);
8664 }
8665
8666 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
8667 CmdArgs.push_back(Elt: "-regcall4");
8668
8669 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
8670
8671 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
8672 CmdArgs.push_back(Elt: "-fdiagnostics-format");
8673 CmdArgs.push_back(Elt: "msvc");
8674 }
8675
8676 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
8677 CmdArgs.push_back(Elt: "-fms-kernel");
8678
8679 // Unwind v2 (epilog) information for x64 Windows.
8680 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
8681 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=required");
8682 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
8683 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=best-effort");
8684
8685 // Handle the various /guard options. We don't immediately push back clang
8686 // args since there are /d2 args that can modify the behavior of /guard:cf.
8687 bool HasCFGuard = false;
8688 bool HasCFGuardNoChecks = false;
8689 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
8690 StringRef GuardArgs = A->getValue();
8691 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8692 // "ehcont-".
8693 if (GuardArgs.equals_insensitive(RHS: "cf")) {
8694 // Emit CFG instrumentation and the table of address-taken functions.
8695 HasCFGuard = true;
8696 HasCFGuardNoChecks = false;
8697 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
8698 // Emit only the table of address-taken functions.
8699 HasCFGuard = false;
8700 HasCFGuardNoChecks = true;
8701 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
8702 // Emit EH continuation table.
8703 CmdArgs.push_back(Elt: "-ehcontguard");
8704 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
8705 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
8706 // Do nothing, but we might want to emit a security warning in future.
8707 } else {
8708 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8709 }
8710 A->claim();
8711 }
8712
8713 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
8714 // If CFG is not enabled, it is a no-op.
8715 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardnochecks)) {
8716 if (HasCFGuard) {
8717 HasCFGuard = false;
8718 HasCFGuardNoChecks = true;
8719 }
8720 }
8721
8722 if (HasCFGuard)
8723 CmdArgs.push_back(Elt: "-cfguard");
8724 else if (HasCFGuardNoChecks)
8725 CmdArgs.push_back(Elt: "-cfguard-no-checks");
8726
8727 for (const auto &FuncOverride :
8728 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
8729 CmdArgs.push_back(Elt: Args.MakeArgString(
8730 Str: Twine("-loader-replaceable-function=") + FuncOverride));
8731 }
8732}
8733
8734const char *Clang::getBaseInputName(const ArgList &Args,
8735 const InputInfo &Input) {
8736 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
8737}
8738
8739const char *Clang::getBaseInputStem(const ArgList &Args,
8740 const InputInfoList &Inputs) {
8741 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
8742
8743 if (const char *End = strrchr(s: Str, c: '.'))
8744 return Args.MakeArgString(Str: std::string(Str, End));
8745
8746 return Str;
8747}
8748
8749const char *Clang::getDependencyFileName(const ArgList &Args,
8750 const InputInfoList &Inputs) {
8751 // FIXME: Think about this more.
8752
8753 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
8754 SmallString<128> OutputFilename(OutputOpt->getValue());
8755 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
8756 return Args.MakeArgString(Str: OutputFilename);
8757 }
8758
8759 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
8760}
8761
8762// Begin ClangAs
8763
8764void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8765 ArgStringList &CmdArgs) const {
8766 StringRef CPUName;
8767 StringRef ABIName;
8768 const llvm::Triple &Triple = getToolChain().getTriple();
8769 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8770
8771 CmdArgs.push_back(Elt: "-target-abi");
8772 CmdArgs.push_back(Elt: ABIName.data());
8773}
8774
8775void ClangAs::AddX86TargetArgs(const ArgList &Args,
8776 ArgStringList &CmdArgs) const {
8777 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
8778 /*IsLTO=*/false);
8779
8780 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
8781 StringRef Value = A->getValue();
8782 if (Value == "intel" || Value == "att") {
8783 CmdArgs.push_back(Elt: "-mllvm");
8784 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
8785 } else {
8786 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
8787 << A->getSpelling() << Value;
8788 }
8789 }
8790}
8791
8792void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8793 ArgStringList &CmdArgs) const {
8794 CmdArgs.push_back(Elt: "-target-abi");
8795 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
8796 Triple: getToolChain().getTriple())
8797 .data());
8798}
8799
8800void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8801 ArgStringList &CmdArgs) const {
8802 const llvm::Triple &Triple = getToolChain().getTriple();
8803 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8804
8805 CmdArgs.push_back(Elt: "-target-abi");
8806 CmdArgs.push_back(Elt: ABIName.data());
8807
8808 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8809 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8810 CmdArgs.push_back(Elt: "-mllvm");
8811 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
8812 }
8813}
8814
8815void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8816 const InputInfo &Output, const InputInfoList &Inputs,
8817 const ArgList &Args,
8818 const char *LinkingOutput) const {
8819 ArgStringList CmdArgs;
8820
8821 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8822 const InputInfo &Input = Inputs[0];
8823
8824 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8825 const std::string &TripleStr = Triple.getTriple();
8826 const auto &D = getToolChain().getDriver();
8827
8828 // Don't warn about "clang -w -c foo.s"
8829 Args.ClaimAllArgs(Id0: options::OPT_w);
8830 // and "clang -emit-llvm -c foo.s"
8831 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8832
8833 claimNoWarnArgs(Args);
8834
8835 // Invoke ourselves in -cc1as mode.
8836 //
8837 // FIXME: Implement custom jobs for internal actions.
8838 CmdArgs.push_back(Elt: "-cc1as");
8839
8840 // Add the "effective" target triple.
8841 CmdArgs.push_back(Elt: "-triple");
8842 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
8843
8844 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
8845
8846 // Set the output mode, we currently only expect to be used as a real
8847 // assembler.
8848 CmdArgs.push_back(Elt: "-filetype");
8849 CmdArgs.push_back(Elt: "obj");
8850
8851 // Set the main file name, so that debug info works even with
8852 // -save-temps or preprocessed assembly.
8853 CmdArgs.push_back(Elt: "-main-file-name");
8854 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
8855
8856 // Add the target cpu
8857 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
8858 if (!CPU.empty()) {
8859 CmdArgs.push_back(Elt: "-target-cpu");
8860 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
8861 }
8862
8863 // Add the target features
8864 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
8865
8866 // Ignore explicit -force_cpusubtype_ALL option.
8867 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
8868
8869 // Pass along any -I options so we get proper .include search paths.
8870 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
8871
8872 // Pass along any --embed-dir or similar options so we get proper embed paths.
8873 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
8874
8875 // Determine the original source input.
8876 auto FindSource = [](const Action *S) -> const Action * {
8877 while (S->getKind() != Action::InputClass) {
8878 assert(!S->getInputs().empty() && "unexpected root action!");
8879 S = S->getInputs()[0];
8880 }
8881 return S;
8882 };
8883 const Action *SourceAction = FindSource(&JA);
8884
8885 // Forward -g and handle debug info related flags, assuming we are dealing
8886 // with an actual assembly file.
8887 bool WantDebug = false;
8888 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
8889 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
8890 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
8891 !A->getOption().matches(ID: options::OPT_ggdb0);
8892
8893 // If a -gdwarf argument appeared, remember it.
8894 bool EmitDwarf = false;
8895 if (const Arg *A = getDwarfNArg(Args))
8896 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8897
8898 bool EmitCodeView = false;
8899 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
8900 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8901
8902 // If the user asked for debug info but did not explicitly specify -gcodeview
8903 // or -gdwarf, ask the toolchain for the default format.
8904 if (!EmitCodeView && !EmitDwarf && WantDebug) {
8905 switch (getToolChain().getDefaultDebugFormat()) {
8906 case llvm::codegenoptions::DIF_CodeView:
8907 EmitCodeView = true;
8908 break;
8909 case llvm::codegenoptions::DIF_DWARF:
8910 EmitDwarf = true;
8911 break;
8912 }
8913 }
8914
8915 // If the arguments don't imply DWARF, don't emit any debug info here.
8916 if (!EmitDwarf)
8917 WantDebug = false;
8918
8919 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8920 llvm::codegenoptions::NoDebugInfo;
8921
8922 // Add the -fdebug-compilation-dir flag if needed.
8923 const char *DebugCompilationDir =
8924 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
8925
8926 if (SourceAction->getType() == types::TY_Asm ||
8927 SourceAction->getType() == types::TY_PP_Asm) {
8928 // You might think that it would be ok to set DebugInfoKind outside of
8929 // the guard for source type, however there is a test which asserts
8930 // that some assembler invocation receives no -debug-info-kind,
8931 // and it's not clear whether that test is just overly restrictive.
8932 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8933 : llvm::codegenoptions::NoDebugInfo);
8934
8935 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
8936 CmdArgs);
8937
8938 // Set the AT_producer to the clang version when using the integrated
8939 // assembler on assembly source files.
8940 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
8941 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
8942
8943 // And pass along -I options
8944 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
8945 }
8946 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
8947 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8948 DebuggerTuning: llvm::DebuggerKind::Default);
8949 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
8950 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
8951
8952 // Handle -fPIC et al -- the relocation-model affects the assembler
8953 // for some targets.
8954 llvm::Reloc::Model RelocationModel;
8955 unsigned PICLevel;
8956 bool IsPIE;
8957 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
8958 ParsePICArgs(ToolChain: getToolChain(), Args);
8959
8960 const char *RMName = RelocationModelName(Model: RelocationModel);
8961 if (RMName) {
8962 CmdArgs.push_back(Elt: "-mrelocation-model");
8963 CmdArgs.push_back(Elt: RMName);
8964 }
8965
8966 // Optionally embed the -cc1as level arguments into the debug info, for build
8967 // analysis.
8968 if (getToolChain().UseDwarfDebugFlags()) {
8969 ArgStringList OriginalArgs;
8970 for (const auto &Arg : Args)
8971 Arg->render(Args, Output&: OriginalArgs);
8972
8973 SmallString<256> Flags;
8974 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8975 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
8976 for (const char *OriginalArg : OriginalArgs) {
8977 SmallString<128> EscapedArg;
8978 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
8979 Flags += " ";
8980 Flags += EscapedArg;
8981 }
8982 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8983 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
8984 }
8985
8986 // FIXME: Add -static support, once we have it.
8987
8988 // Add target specific flags.
8989 switch (getToolChain().getArch()) {
8990 default:
8991 break;
8992
8993 case llvm::Triple::mips:
8994 case llvm::Triple::mipsel:
8995 case llvm::Triple::mips64:
8996 case llvm::Triple::mips64el:
8997 AddMIPSTargetArgs(Args, CmdArgs);
8998 break;
8999
9000 case llvm::Triple::x86:
9001 case llvm::Triple::x86_64:
9002 AddX86TargetArgs(Args, CmdArgs);
9003 break;
9004
9005 case llvm::Triple::arm:
9006 case llvm::Triple::armeb:
9007 case llvm::Triple::thumb:
9008 case llvm::Triple::thumbeb:
9009 // This isn't in AddARMTargetArgs because we want to do this for assembly
9010 // only, not C/C++.
9011 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9012 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9013 CmdArgs.push_back(Elt: "-mllvm");
9014 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
9015 }
9016 break;
9017
9018 case llvm::Triple::aarch64:
9019 case llvm::Triple::aarch64_32:
9020 case llvm::Triple::aarch64_be:
9021 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
9022 CmdArgs.push_back(Elt: "-mllvm");
9023 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
9024 }
9025 break;
9026
9027 case llvm::Triple::loongarch32:
9028 case llvm::Triple::loongarch64:
9029 AddLoongArchTargetArgs(Args, CmdArgs);
9030 break;
9031
9032 case llvm::Triple::riscv32:
9033 case llvm::Triple::riscv64:
9034 case llvm::Triple::riscv32be:
9035 case llvm::Triple::riscv64be:
9036 AddRISCVTargetArgs(Args, CmdArgs);
9037 break;
9038
9039 case llvm::Triple::hexagon:
9040 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9041 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9042 CmdArgs.push_back(Elt: "-mllvm");
9043 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
9044 }
9045 break;
9046 }
9047
9048 // Consume all the warning flags. Usually this would be handled more
9049 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9050 // doesn't handle that so rather than warning about unused flags that are
9051 // actually used, we'll lie by omission instead.
9052 // FIXME: Stop lying and consume only the appropriate driver flags
9053 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
9054
9055 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9056 D: getToolChain().getDriver());
9057
9058 // Forward -Xclangas arguments to -cc1as
9059 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
9060 Arg->claim();
9061 CmdArgs.push_back(Elt: Arg->getValue());
9062 }
9063
9064 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
9065
9066 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9067 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9068 OutputFileName: Output.getFilename());
9069
9070 // Fixup any previous commands that use -object-file-name because when we
9071 // generated them, the final .obj name wasn't yet known.
9072 for (Command &J : C.getJobs()) {
9073 if (SourceAction != FindSource(&J.getSource()))
9074 continue;
9075 auto &JArgs = J.getArguments();
9076 for (unsigned I = 0; I < JArgs.size(); ++I) {
9077 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
9078 Output.isFilename()) {
9079 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9080 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
9081 OutputFileName: Output.getFilename());
9082 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
9083 J.replaceArguments(List: NewArgs);
9084 break;
9085 }
9086 }
9087 }
9088
9089 assert(Output.isFilename() && "Unexpected lipo output.");
9090 CmdArgs.push_back(Elt: "-o");
9091 CmdArgs.push_back(Elt: Output.getFilename());
9092
9093 const llvm::Triple &T = getToolChain().getTriple();
9094 Arg *A;
9095 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
9096 T.isOSBinFormatELF()) {
9097 CmdArgs.push_back(Elt: "-split-dwarf-output");
9098 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
9099 }
9100
9101 if (Triple.isAMDGPU())
9102 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9103
9104 assert(Input.isFilename() && "Invalid input.");
9105 CmdArgs.push_back(Elt: Input.getFilename());
9106
9107 const char *Exec = getToolChain().getDriver().getClangProgramPath();
9108 if (D.CC1Main && !D.CCGenDiagnostics) {
9109 // Invoke cc1as directly in this process.
9110 C.addCommand(C: std::make_unique<CC1Command>(
9111 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9112 args: Output, args: D.getPrependArg()));
9113 } else {
9114 C.addCommand(C: std::make_unique<Command>(
9115 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9116 args: Output, args: D.getPrependArg()));
9117 }
9118}
9119
9120// Begin OffloadBundler
9121void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
9122 const InputInfo &Output,
9123 const InputInfoList &Inputs,
9124 const llvm::opt::ArgList &TCArgs,
9125 const char *LinkingOutput) const {
9126 // The version with only one output is expected to refer to a bundling job.
9127 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9128
9129 // The bundling command looks like this:
9130 // clang-offload-bundler -type=bc
9131 // -targets=host-triple,openmp-triple1,openmp-triple2
9132 // -output=output_file
9133 // -input=unbundle_file_host
9134 // -input=unbundle_file_tgt1
9135 // -input=unbundle_file_tgt2
9136
9137 ArgStringList CmdArgs;
9138
9139 // Get the type.
9140 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9141 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
9142
9143 assert(JA.getInputs().size() == Inputs.size() &&
9144 "Not have inputs for all dependence actions??");
9145
9146 // Get the targets.
9147 SmallString<128> Triples;
9148 Triples += "-targets=";
9149 for (unsigned I = 0; I < Inputs.size(); ++I) {
9150 if (I)
9151 Triples += ',';
9152
9153 // Find ToolChain for this input.
9154 Action::OffloadKind CurKind = Action::OFK_Host;
9155 const ToolChain *CurTC = &getToolChain();
9156 const Action *CurDep = JA.getInputs()[I];
9157
9158 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
9159 CurTC = nullptr;
9160 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, const char *) {
9161 assert(CurTC == nullptr && "Expected one dependence!");
9162 CurKind = A->getOffloadingDeviceKind();
9163 CurTC = TC;
9164 });
9165 }
9166 Triples += Action::GetOffloadKindName(Kind: CurKind);
9167 Triples += '-';
9168 Triples +=
9169 CurTC->getTriple().normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9170 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
9171 !StringRef(CurDep->getOffloadingArch()).empty()) {
9172 Triples += '-';
9173 Triples += CurDep->getOffloadingArch();
9174 }
9175
9176 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9177 // with each toolchain.
9178 StringRef GPUArchName;
9179 if (CurKind == Action::OFK_OpenMP) {
9180 // Extract GPUArch from -march argument in TC argument list.
9181 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9182 auto ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9183 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9184 if (Arch) {
9185 GPUArchName = ArchStr.substr(Start: 7);
9186 Triples += "-";
9187 break;
9188 }
9189 }
9190 Triples += GPUArchName.str();
9191 }
9192 }
9193 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9194
9195 // Get bundled file command.
9196 CmdArgs.push_back(
9197 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9198
9199 // Get unbundled files command.
9200 for (unsigned I = 0; I < Inputs.size(); ++I) {
9201 SmallString<128> UB;
9202 UB += "-input=";
9203
9204 // Find ToolChain for this input.
9205 const ToolChain *CurTC = &getToolChain();
9206 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9207 CurTC = nullptr;
9208 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, const char *) {
9209 assert(CurTC == nullptr && "Expected one dependence!");
9210 CurTC = TC;
9211 });
9212 UB += C.addTempFile(
9213 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9214 } else {
9215 UB += CurTC->getInputFilename(Input: Inputs[I]);
9216 }
9217 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9218 }
9219 addOffloadCompressArgs(TCArgs, CmdArgs);
9220 // All the inputs are encoded as commands.
9221 C.addCommand(C: std::make_unique<Command>(
9222 args: JA, args: *this, args: ResponseFileSupport::None(),
9223 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9224 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9225}
9226
9227void OffloadBundler::ConstructJobMultipleOutputs(
9228 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9229 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9230 const char *LinkingOutput) const {
9231 // The version with multiple outputs is expected to refer to a unbundling job.
9232 auto &UA = cast<OffloadUnbundlingJobAction>(Val: JA);
9233
9234 // The unbundling command looks like this:
9235 // clang-offload-bundler -type=bc
9236 // -targets=host-triple,openmp-triple1,openmp-triple2
9237 // -input=input_file
9238 // -output=unbundle_file_host
9239 // -output=unbundle_file_tgt1
9240 // -output=unbundle_file_tgt2
9241 // -unbundle
9242
9243 ArgStringList CmdArgs;
9244
9245 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9246 InputInfo Input = Inputs.front();
9247
9248 // Get the type.
9249 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9250 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Input.getType())));
9251
9252 // Get the targets.
9253 SmallString<128> Triples;
9254 Triples += "-targets=";
9255 auto DepInfo = UA.getDependentActionsInfo();
9256 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9257 if (I)
9258 Triples += ',';
9259
9260 auto &Dep = DepInfo[I];
9261 Triples += Action::GetOffloadKindName(Kind: Dep.DependentOffloadKind);
9262 Triples += '-';
9263 Triples += Dep.DependentToolChain->getTriple().normalize(
9264 Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9265 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9266 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9267 !Dep.DependentBoundArch.empty()) {
9268 Triples += '-';
9269 Triples += Dep.DependentBoundArch;
9270 }
9271 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9272 // with each toolchain.
9273 StringRef GPUArchName;
9274 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
9275 // Extract GPUArch from -march argument in TC argument list.
9276 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9277 StringRef ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9278 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9279 if (Arch) {
9280 GPUArchName = ArchStr.substr(Start: 7);
9281 Triples += "-";
9282 break;
9283 }
9284 }
9285 Triples += GPUArchName.str();
9286 }
9287 }
9288
9289 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9290
9291 // Get bundled file command.
9292 CmdArgs.push_back(
9293 Elt: TCArgs.MakeArgString(Str: Twine("-input=") + Input.getFilename()));
9294
9295 // Get unbundled files command.
9296 for (unsigned I = 0; I < Outputs.size(); ++I) {
9297 SmallString<128> UB;
9298 UB += "-output=";
9299 UB += DepInfo[I].DependentToolChain->getInputFilename(Input: Outputs[I]);
9300 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9301 }
9302 CmdArgs.push_back(Elt: "-unbundle");
9303 CmdArgs.push_back(Elt: "-allow-missing-bundles");
9304 if (TCArgs.hasArg(Ids: options::OPT_v))
9305 CmdArgs.push_back(Elt: "-verbose");
9306
9307 // All the inputs are encoded as commands.
9308 C.addCommand(C: std::make_unique<Command>(
9309 args: JA, args: *this, args: ResponseFileSupport::None(),
9310 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9311 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Outputs));
9312}
9313
9314void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9315 const InputInfo &Output,
9316 const InputInfoList &Inputs,
9317 const llvm::opt::ArgList &Args,
9318 const char *LinkingOutput) const {
9319 ArgStringList CmdArgs;
9320
9321 // Add the output file name.
9322 assert(Output.isFilename() && "Invalid output.");
9323 CmdArgs.push_back(Elt: "-o");
9324 CmdArgs.push_back(Elt: Output.getFilename());
9325
9326 // Create the inputs to bundle the needed metadata.
9327 for (const InputInfo &Input : Inputs) {
9328 const Action *OffloadAction = Input.getAction();
9329 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9330 const ArgList &TCArgs =
9331 C.getArgsForToolChain(TC, BoundArch: OffloadAction->getOffloadingArch(),
9332 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9333 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9334 StringRef Arch = OffloadAction->getOffloadingArch()
9335 ? OffloadAction->getOffloadingArch()
9336 : TCArgs.getLastArgValue(Id: options::OPT_march_EQ);
9337 StringRef Kind =
9338 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9339
9340 ArgStringList Features;
9341 SmallVector<StringRef> FeatureArgs;
9342 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9343 ForAS: false);
9344 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9345 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9346
9347 // TODO: We need to pass in the full target-id and handle it properly in the
9348 // linker wrapper.
9349 SmallVector<std::string> Parts{
9350 "file=" + File.str(),
9351 "triple=" + TC->getTripleString().str(),
9352 "arch=" + (Arch.empty() ? "generic" : Arch.str()),
9353 "kind=" + Kind.str(),
9354 };
9355
9356 if (TC->getDriver().isUsingOffloadLTO())
9357 for (StringRef Feature : FeatureArgs)
9358 Parts.emplace_back(Args: "feature=" + Feature.str());
9359
9360 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9361 }
9362
9363 C.addCommand(C: std::make_unique<Command>(
9364 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(),
9365 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9366 args&: CmdArgs, args: Inputs, args: Output));
9367}
9368
9369void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9370 const InputInfo &Output,
9371 const InputInfoList &Inputs,
9372 const ArgList &Args,
9373 const char *LinkingOutput) const {
9374 using namespace options;
9375
9376 // A list of permitted options that will be forwarded to the embedded device
9377 // compilation job.
9378 const llvm::DenseSet<unsigned> CompilerOptions{
9379 OPT_v,
9380 OPT_cuda_path_EQ,
9381 OPT_rocm_path_EQ,
9382 OPT_hip_path_EQ,
9383 OPT_O_Group,
9384 OPT_g_Group,
9385 OPT_g_flags_Group,
9386 OPT_R_value_Group,
9387 OPT_R_Group,
9388 OPT_Xcuda_ptxas,
9389 OPT_ftime_report,
9390 OPT_ftime_trace,
9391 OPT_ftime_trace_EQ,
9392 OPT_ftime_trace_granularity_EQ,
9393 OPT_ftime_trace_verbose,
9394 OPT_opt_record_file,
9395 OPT_opt_record_format,
9396 OPT_opt_record_passes,
9397 OPT_fsave_optimization_record,
9398 OPT_fsave_optimization_record_EQ,
9399 OPT_fno_save_optimization_record,
9400 OPT_foptimization_record_file_EQ,
9401 OPT_foptimization_record_passes_EQ,
9402 OPT_save_temps,
9403 OPT_save_temps_EQ,
9404 OPT_mcode_object_version_EQ,
9405 OPT_load,
9406 OPT_no_canonical_prefixes,
9407 OPT_fno_lto,
9408 OPT_flto,
9409 OPT_flto_partitions_EQ,
9410 OPT_flto_EQ,
9411 OPT_hipspv_pass_plugin_EQ,
9412 OPT_use_spirv_backend,
9413 OPT_fprofile_generate,
9414 OPT_fprofile_generate_EQ,
9415 OPT_fprofile_instr_generate,
9416 OPT_fprofile_instr_generate_EQ};
9417 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9418 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9419 auto HasProfileRT = TC.getVFS().exists(
9420 Path: TC.getCompilerRT(Args, Component: "profile", Type: ToolChain::FT_Static));
9421 // Don't forward profiling arguments if the toolchain doesn't support it.
9422 // Without this check using it on the host would result in linker errors.
9423 if (!HasProfileRT &&
9424 (A->getOption().matches(ID: OPT_fprofile_generate) ||
9425 A->getOption().matches(ID: OPT_fprofile_generate_EQ) ||
9426 A->getOption().matches(ID: OPT_fprofile_instr_generate) ||
9427 A->getOption().matches(ID: OPT_fprofile_instr_generate_EQ)))
9428 return false;
9429 // Don't forward -mllvm to toolchains that don't support LLVM.
9430 return TC.HasNativeLLVMSupport() || A->getOption().getID() != OPT_mllvm;
9431 };
9432 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9433 const ToolChain &TC) {
9434 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9435 if (A->getOption().matches(ID: OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9436 return false;
9437 return (Set.contains(V: A->getOption().getID()) ||
9438 (A->getOption().getGroup().isValid() &&
9439 Set.contains(V: A->getOption().getGroup().getID()))) &&
9440 ShouldForwardForToolChain(A, TC);
9441 };
9442
9443 ArgStringList CmdArgs;
9444 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9445 Action::OFK_HIP, Action::OFK_SYCL}) {
9446 auto TCRange = C.getOffloadToolChains(Kind);
9447 for (auto &I : llvm::make_range(p: TCRange)) {
9448 const ToolChain *TC = I.second;
9449
9450 // We do not use a bound architecture here so options passed only to a
9451 // specific architecture via -Xarch_<cpu> will not be forwarded.
9452 ArgStringList CompilerArgs;
9453 ArgStringList LinkerArgs;
9454 const DerivedArgList &ToolChainArgs =
9455 C.getArgsForToolChain(TC, /*BoundArch=*/"", DeviceOffloadKind: Kind);
9456 for (Arg *A : ToolChainArgs) {
9457 if (A->getOption().matches(ID: OPT_Zlinker_input))
9458 LinkerArgs.emplace_back(Args: A->getValue());
9459 else if (ShouldForward(CompilerOptions, A, *TC))
9460 A->render(Args, Output&: CompilerArgs);
9461 else if (ShouldForward(LinkerOptions, A, *TC))
9462 A->render(Args, Output&: LinkerArgs);
9463 }
9464
9465 // If the user explicitly requested it via `--offload-arch` we should
9466 // extract it from any static libraries if present.
9467 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ))
9468 CmdArgs.emplace_back(Args: Args.MakeArgString(Str: "--should-extract=" + Arg));
9469
9470 // If this is OpenMP the device linker will need `-lompdevice`.
9471 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9472 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9473 LinkerArgs.emplace_back(Args: "-lompdevice");
9474
9475 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9476 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9477 // flags to normal compilation.
9478 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9479 // flags.
9480 if (TC->getTriple().isSPIRV() &&
9481 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9482 !C.getDriver().isUsingLTO() && !C.getDriver().isUsingOffloadLTO()) {
9483 // For SPIR-V some functions will be defined by the runtime so allow
9484 // unresolved symbols in `spirv-link`.
9485 LinkerArgs.emplace_back(Args: "--allow-partial-linkage");
9486 // Don't optimize out exported symbols.
9487 LinkerArgs.emplace_back(Args: "--create-library");
9488 }
9489
9490 // Forward all of these to the appropriate toolchain.
9491 for (StringRef Arg : CompilerArgs)
9492 CmdArgs.push_back(Elt: Args.MakeArgString(
9493 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9494 for (StringRef Arg : LinkerArgs)
9495 CmdArgs.push_back(Elt: Args.MakeArgString(
9496 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9497
9498 // Forward the LTO mode relying on the Driver's parsing.
9499 if (C.getDriver().getOffloadLTOMode() == LTOK_Full)
9500 CmdArgs.push_back(Elt: Args.MakeArgString(
9501 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9502 else if (C.getDriver().getOffloadLTOMode() == LTOK_Thin) {
9503 CmdArgs.push_back(Elt: Args.MakeArgString(
9504 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9505 if (TC->getTriple().isAMDGPU()) {
9506 CmdArgs.push_back(
9507 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9508 "=-plugin-opt=-force-import-all"));
9509 CmdArgs.push_back(
9510 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9511 "=-plugin-opt=-avail-extern-to-local"));
9512 CmdArgs.push_back(Elt: Args.MakeArgString(
9513 Str: "--device-linker=" + TC->getTripleString() +
9514 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9515 if (Kind == Action::OFK_OpenMP) {
9516 CmdArgs.push_back(
9517 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9518 "=-plugin-opt=-amdgpu-internalize-symbols"));
9519 }
9520 }
9521 }
9522 }
9523 }
9524
9525 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9526 CmdArgs.push_back(
9527 Elt: Args.MakeArgString(Str: "--host-triple=" + AuxTriple->getTriple()));
9528 else
9529 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--host-triple=" +
9530 getToolChain().getTripleString()));
9531
9532 // CMake hack, suppress passing verbose arguments for the special-case HIP
9533 // non-RDC mode compilation. This confuses default CMake implicit linker
9534 // argument parsing when the language is set to HIP and the system linker is
9535 // also `ld.lld`.
9536 if (Args.hasArg(Ids: options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9537 CmdArgs.push_back(Elt: "--wrapper-verbose");
9538 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ))
9539 CmdArgs.push_back(
9540 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
9541
9542 // Construct the link job so we can wrap around it.
9543 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
9544 const auto &LinkCommand = C.getJobs().getJobs().back();
9545
9546 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9547 // wrapper.
9548 for (Arg *A :
9549 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
9550 StringRef Val = A->getValue(N: 0);
9551 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9552 auto WrapperOption =
9553 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9554 if (Val.empty())
9555 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
9556 else
9557 CmdArgs.push_back(Elt: Args.MakeArgString(
9558 Str: WrapperOption +
9559 ToolChain::normalizeOffloadTriple(OrigTT: Val.drop_front()).str() + "=" +
9560 A->getValue(N: 1)));
9561 }
9562 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
9563 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
9564
9565 // Embed bitcode instead of an object in JIT mode.
9566 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
9567 Neg: options::OPT_fno_openmp_target_jit, Default: false))
9568 CmdArgs.push_back(Elt: "--embed-bitcode");
9569
9570 // Save temporary files created by the linker wrapper.
9571 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
9572 Args.hasArg(Ids: options::OPT_save_temps))
9573 CmdArgs.push_back(Elt: "--save-temps");
9574
9575 // Pass in the C library for GPUs if present and not disabled.
9576 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
9577 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
9578 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
9579 Ids: options::OPT_nogpulibc)) {
9580 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
9581 // The device C library is only available for NVPTX and AMDGPU targets
9582 // and we only link it by default for OpenMP currently.
9583 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
9584 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
9585 return;
9586 bool HasLibC = TC.getStdlibIncludePath().has_value();
9587 if (HasLibC) {
9588 CmdArgs.push_back(Elt: Args.MakeArgString(
9589 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9590 CmdArgs.push_back(Elt: Args.MakeArgString(
9591 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9592 }
9593 auto HasCompilerRT = getToolChain().getVFS().exists(
9594 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static,
9595 /*IsFortran=*/false));
9596 if (HasCompilerRT)
9597 CmdArgs.push_back(
9598 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9599 "-lclang_rt.builtins"));
9600
9601 bool HasFlangRT = getToolChain().getVFS().exists(
9602 Path: TC.getCompilerRT(Args, Component: "runtime", Type: ToolChain::FT_Static,
9603 /*IsFortran=*/true));
9604 if (HasFlangRT && C.getDriver().IsFlangMode())
9605 CmdArgs.push_back(
9606 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9607 "-lflang_rt.runtime"));
9608 });
9609 }
9610
9611 // Add the linker arguments to be forwarded by the wrapper.
9612 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
9613 LinkCommand->getExecutable()));
9614
9615 // We use action type to differentiate two use cases of the linker wrapper.
9616 // TY_Image for normal linker wrapper work.
9617 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
9618 assert(JA.getType() == types::TY_HIP_FATBIN ||
9619 JA.getType() == types::TY_Image);
9620 if (JA.getType() == types::TY_HIP_FATBIN) {
9621 CmdArgs.push_back(Elt: "--emit-fatbin-only");
9622 CmdArgs.append(IL: {"-o", Output.getFilename()});
9623 for (auto Input : Inputs)
9624 CmdArgs.push_back(Elt: Input.getFilename());
9625 } else
9626 for (const char *LinkArg : LinkCommand->getArguments())
9627 CmdArgs.push_back(Elt: LinkArg);
9628
9629 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
9630
9631 if (Arg *A = Args.getLastArg(Ids: options::OPT_offload_jobs_EQ)) {
9632 StringRef Val = A->getValue();
9633
9634 if (Val.equals_insensitive(RHS: "jobserver"))
9635 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
9636 else {
9637 int NumThreads;
9638 if (Val.getAsInteger(Radix: 10, Result&: NumThreads) || NumThreads <= 0) {
9639 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
9640 << A->getAsString(Args) << Val;
9641 } else {
9642 CmdArgs.push_back(
9643 Elt: Args.MakeArgString(Str: "--wrapper-jobs=" + Twine(NumThreads)));
9644 }
9645 }
9646 }
9647
9648 // Propagate -no-canonical-prefixes.
9649 if (Args.hasArg(Ids: options::OPT_no_canonical_prefixes))
9650 CmdArgs.push_back(Elt: "--no-canonical-prefixes");
9651
9652 const char *Exec =
9653 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
9654
9655 // Replace the executable and arguments of the link job with the
9656 // wrapper.
9657 LinkCommand->replaceExecutable(Exe: Exec);
9658 LinkCommand->replaceArguments(List: CmdArgs);
9659}
9660