clang 23.0.0git
Clang.cpp
Go to the documentation of this file.
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"
27#include "clang/Basic/Version.h"
28#include "clang/Config/config.h"
29#include "clang/Driver/Action.h"
31#include "clang/Driver/Distro.h"
34#include "clang/Driver/Types.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(options::OPT_C, options::OPT_CC,
72 options::OPT_fminimize_whitespace,
73 options::OPT_fno_minimize_whitespace,
74 options::OPT_fkeep_system_includes,
75 options::OPT_fno_keep_system_includes)) {
76 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
77 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
78 D.Diag(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(options::OPT_static))
88 if (const Arg *A =
89 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
90 D.Diag(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
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.
107 if (JA.isHostOffloading(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(Kind))
112 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
113 }
114}
115
116static bool
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(10, 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(options::OPT_fexceptions);
147 Args.ClaimAllArgs(options::OPT_fno_exceptions);
148 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
149 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
150 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
151 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
152 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
153 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
154 return false;
155 }
156
157 // See if the user explicitly enabled exceptions.
158 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
159 false);
160
161 // Async exceptions are Windows MSVC only.
162 if (Triple.isWindowsMSVCEnvironment()) {
163 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
164 options::OPT_fno_async_exceptions, false);
165 if (EHa) {
166 CmdArgs.push_back("-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(InputType) &&
174 Args.hasFlag(options::OPT_fobjc_exceptions,
175 options::OPT_fno_objc_exceptions, true)) {
176 CmdArgs.push_back("-fobjc-exceptions");
177
178 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
179 }
180
181 if (types::isCXX(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 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
187 options::OPT_fexceptions, options::OPT_fno_exceptions);
188 if (ExceptionArg)
189 CXXExceptionsEnabled =
190 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
191 ExceptionArg->getOption().matches(options::OPT_fexceptions);
192
193 if (CXXExceptionsEnabled) {
194 CmdArgs.push_back("-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(CmdArgs, options::OPT_fignore_exceptions);
204
205 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
206 options::OPT_fno_assume_nothrow_exception_dtor);
207
208 if (EH)
209 CmdArgs.push_back("-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.
220 }
221 // The linker_option directives are intended for host compilation.
224 Default = false;
225 return Args.hasFlag(options::OPT_fautolink, 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(options::OPT_ffile_compilation_dir_EQ,
235 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 Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));
246 StringRef Path(CmdArgs.back());
247 return Path.substr(Path.find('=') + 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(options::OPT_Xclang))
255 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
256 return;
257
258 if (Args.hasArg(options::OPT_object_file_name_EQ))
259 return;
260
261 SmallString<128> ObjFileNameForDebug(OutputFileName);
262 if (ObjFileNameForDebug != "-" &&
263 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
264 (!DebugCompilationDir ||
265 llvm::sys::path::is_absolute(DebugCompilationDir))) {
266 // Make the path absolute in the debug infos like MSVC does.
267 llvm::sys::fs::make_absolute(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(ObjFileNameForDebug)
275 ? llvm::sys::path::Style::native
276 : llvm::sys::path::Style::windows_backslash;
277 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
278 Style);
279 CmdArgs.push_back(
280 Args.MakeArgString(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('='))
288 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
289 else
290 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
291 };
292
293 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
294 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(options::OPT_ffile_prefix_map_EQ,
308 options::OPT_fmacro_prefix_map_EQ)) {
309 StringRef Map = A->getValue();
310 if (!Map.contains('='))
311 D.Diag(diag::err_drv_invalid_argument_to_option)
312 << Map << A->getOption().getName();
313 else
314 CmdArgs.push_back(Args.MakeArgString("-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(options::OPT_ffile_prefix_map_EQ,
323 options::OPT_fcoverage_prefix_map_EQ)) {
324 StringRef Map = A->getValue();
325 if (!Map.contains('='))
326 D.Diag(diag::err_drv_invalid_argument_to_option)
327 << Map << A->getOption().getName();
328 else
329 CmdArgs.push_back(Args.MakeArgString("-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(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
340 return;
341
342 CmdArgs.push_back("-x");
343 if (Args.hasArg(options::OPT_rewrite_objc))
344 CmdArgs.push_back(types::getTypeName(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 case types::TY_CXXStdModule:
353 ClangType = "c++";
354 break;
355 case types::TY_PP_CXXModule:
356 ClangType = "c++-cpp-output";
357 break;
358 default:
359 ClangType = types::getTypeName(Input.getType());
360 break;
361 }
362 CmdArgs.push_back(ClangType);
363 }
364}
365
367 const JobAction &JA, const InputInfo &Output,
368 const ArgList &Args, SanitizerArgs &SanArgs,
369 ArgStringList &CmdArgs) {
370 const Driver &D = TC.getDriver();
371 const llvm::Triple &T = TC.getTriple();
372 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
373 options::OPT_fprofile_generate_EQ,
374 options::OPT_fno_profile_generate);
375 if (PGOGenerateArg &&
376 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
377 PGOGenerateArg = nullptr;
378
379 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
380
381 auto *ProfileGenerateArg = Args.getLastArg(
382 options::OPT_fprofile_instr_generate,
383 options::OPT_fprofile_instr_generate_EQ,
384 options::OPT_fno_profile_instr_generate);
385 if (ProfileGenerateArg &&
386 ProfileGenerateArg->getOption().matches(
387 options::OPT_fno_profile_instr_generate))
388 ProfileGenerateArg = nullptr;
389
390 if (PGOGenerateArg && ProfileGenerateArg)
391 D.Diag(diag::err_drv_argument_not_allowed_with)
392 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
393
394 auto *ProfileUseArg = getLastProfileUseArg(Args);
395
396 if (PGOGenerateArg && ProfileUseArg)
397 D.Diag(diag::err_drv_argument_not_allowed_with)
398 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
399
400 if (ProfileGenerateArg && ProfileUseArg)
401 D.Diag(diag::err_drv_argument_not_allowed_with)
402 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
403
404 if (CSPGOGenerateArg && PGOGenerateArg) {
405 D.Diag(diag::err_drv_argument_not_allowed_with)
406 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
407 PGOGenerateArg = nullptr;
408 }
409
410 if (TC.getTriple().isOSAIX()) {
411 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
412 D.Diag(diag::err_drv_unsupported_opt_for_target)
413 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
414 }
415
416 if (ProfileGenerateArg) {
417 if (ProfileGenerateArg->getOption().matches(
418 options::OPT_fprofile_instr_generate_EQ))
419 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
420 ProfileGenerateArg->getValue()));
421 // The default is to use Clang Instrumentation.
422 CmdArgs.push_back("-fprofile-instrument=clang");
423 if (TC.getTriple().isWindowsMSVCEnvironment() &&
424 Args.hasFlag(options::OPT_frtlib_defaultlib,
425 options::OPT_fno_rtlib_defaultlib, true)) {
426 // Add dependent lib for clang_rt.profile
427 CmdArgs.push_back(Args.MakeArgString(
428 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
429 }
430 }
431
432 if (auto *ColdFuncCoverageArg = Args.getLastArg(
433 options::OPT_fprofile_generate_cold_function_coverage,
434 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
435 SmallString<128> Path(
436 ColdFuncCoverageArg->getOption().matches(
437 options::OPT_fprofile_generate_cold_function_coverage_EQ)
438 ? ColdFuncCoverageArg->getValue()
439 : "");
440 llvm::sys::path::append(Path, "default_%m.profraw");
441 // FIXME: Idealy the file path should be passed through
442 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
443 // shared with other profile use path(see PGOOptions), we need to refactor
444 // PGOOptions to make it work.
445 CmdArgs.push_back("-mllvm");
446 CmdArgs.push_back(Args.MakeArgString(
447 Twine("--instrument-cold-function-only-path=") + Path));
448 CmdArgs.push_back("-mllvm");
449 CmdArgs.push_back("--pgo-instrument-cold-function-only");
450 CmdArgs.push_back("-mllvm");
451 CmdArgs.push_back("--pgo-function-entry-coverage");
452 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
453 }
454
455 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
456 if (!PGOGenerateArg && !CSPGOGenerateArg)
457 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
458 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
459 CmdArgs.push_back("-mllvm");
460 CmdArgs.push_back("--pgo-temporal-instrumentation");
461 }
462
463 Arg *PGOGenArg = nullptr;
464 if (PGOGenerateArg) {
465 assert(!CSPGOGenerateArg);
466 PGOGenArg = PGOGenerateArg;
467 CmdArgs.push_back("-fprofile-instrument=llvm");
468 }
469 if (CSPGOGenerateArg) {
470 assert(!PGOGenerateArg);
471 PGOGenArg = CSPGOGenerateArg;
472 CmdArgs.push_back("-fprofile-instrument=csllvm");
473 }
474 if (PGOGenArg) {
475 if (TC.getTriple().isWindowsMSVCEnvironment() &&
476 Args.hasFlag(options::OPT_frtlib_defaultlib,
477 options::OPT_fno_rtlib_defaultlib, true)) {
478 // Add dependent lib for clang_rt.profile
479 CmdArgs.push_back(Args.MakeArgString(
480 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
481 }
482 if (PGOGenArg->getOption().matches(
483 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
484 : options::OPT_fcs_profile_generate_EQ)) {
485 SmallString<128> Path(PGOGenArg->getValue());
486 llvm::sys::path::append(Path, "default_%m.profraw");
487 CmdArgs.push_back(
488 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
489 }
490 }
491
492 if (ProfileUseArg) {
493 SmallString<128> UsePathBuf;
494 StringRef UsePath;
495 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
496 UsePath = ProfileUseArg->getValue();
497 else if ((ProfileUseArg->getOption().matches(
498 options::OPT_fprofile_use_EQ) ||
499 ProfileUseArg->getOption().matches(
500 options::OPT_fprofile_instr_use))) {
501 UsePathBuf =
502 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
503 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
504 llvm::sys::path::append(UsePathBuf, "default.profdata");
505 UsePath = UsePathBuf;
506 }
507 auto ReaderOrErr =
508 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
509 if (auto E = ReaderOrErr.takeError()) {
510 auto DiagID = D.getDiags().getCustomDiagID(
511 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
512 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
513 D.Diag(DiagID) << UsePath.str() << EI.message();
514 });
515 } else {
516 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
517 std::move(ReaderOrErr.get());
518 StringRef UseKind;
519 // Currently memprof profiles are only added at the IR level. Mark the
520 // profile type as IR in that case as well and the subsequent matching
521 // needs to detect which is available (might be one or both).
522 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
523 if (PGOReader->hasCSIRLevelProfile())
524 UseKind = "csllvm";
525 else
526 UseKind = "llvm";
527 } else
528 UseKind = "clang";
529
530 CmdArgs.push_back(
531 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
532 CmdArgs.push_back(
533 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
534 }
535 }
536
537 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
538 options::OPT_fno_test_coverage, false) ||
539 Args.hasArg(options::OPT_coverage);
540 bool EmitCovData = TC.needsGCovInstrumentation(Args);
541
542 if (Args.hasFlag(options::OPT_fcoverage_mapping,
543 options::OPT_fno_coverage_mapping, false)) {
544 if (!ProfileGenerateArg)
545 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
546 << "-fcoverage-mapping"
547 << "-fprofile-instr-generate";
548
549 CmdArgs.push_back("-fcoverage-mapping");
550 }
551
552 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
553 false)) {
554 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
555 options::OPT_fno_coverage_mapping, false))
556 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
557 << "-fcoverage-mcdc"
558 << "-fcoverage-mapping";
559
560 CmdArgs.push_back("-fcoverage-mcdc");
561 }
562
563 StringRef CoverageCompDir;
564 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
565 options::OPT_fcoverage_compilation_dir_EQ))
566 CoverageCompDir = A->getValue();
567 if (CoverageCompDir.empty()) {
568 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
569 CmdArgs.push_back(
570 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
571 } else
572 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
573 CoverageCompDir));
574
575 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
576 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
577 if (!Args.hasArg(options::OPT_coverage))
578 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
579 << "-fprofile-exclude-files="
580 << "--coverage";
581
582 StringRef v = Arg->getValue();
583 CmdArgs.push_back(
584 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
585 }
586
587 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
588 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
589 if (!Args.hasArg(options::OPT_coverage))
590 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
591 << "-fprofile-filter-files="
592 << "--coverage";
593
594 StringRef v = Arg->getValue();
595 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
596 }
597
598 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
599 StringRef Val = A->getValue();
600 if (Val == "atomic" || Val == "prefer-atomic")
601 CmdArgs.push_back("-fprofile-update=atomic");
602 else if (Val != "single")
603 D.Diag(diag::err_drv_unsupported_option_argument)
604 << A->getSpelling() << Val;
605 }
606 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
607 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
608 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
609 << A->getSpelling()
610 << "-fprofile-generate, -fprofile-instr-generate, or "
611 "-fcs-profile-generate";
612 else {
613 CmdArgs.push_back("-fprofile-continuous");
614 // Platforms that require a bias variable:
615 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
616 CmdArgs.push_back("-mllvm");
617 CmdArgs.push_back("-runtime-counter-relocation");
618 }
619 // -fprofile-instr-generate does not decide the profile file name in the
620 // FE, and so it does not define the filename symbol
621 // (__llvm_profile_filename). Instead, the runtime uses the name
622 // "default.profraw" for the profile file. When continuous mode is ON, we
623 // will create the filename symbol so that we can insert the "%c"
624 // modifier.
625 if (ProfileGenerateArg &&
626 (ProfileGenerateArg->getOption().matches(
627 options::OPT_fprofile_instr_generate) ||
628 (ProfileGenerateArg->getOption().matches(
629 options::OPT_fprofile_instr_generate_EQ) &&
630 strlen(ProfileGenerateArg->getValue()) == 0)))
631 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
632 }
633 }
634
635 int FunctionGroups = 1;
636 int SelectedFunctionGroup = 0;
637 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
638 StringRef Val = A->getValue();
639 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
640 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
641 }
642 if (const auto *A =
643 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
644 StringRef Val = A->getValue();
645 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
646 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
647 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
648 }
649 if (FunctionGroups != 1)
650 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
651 Twine(FunctionGroups)));
652 if (SelectedFunctionGroup != 0)
653 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
654 Twine(SelectedFunctionGroup)));
655
656 // Leave -fprofile-dir= an unused argument unless .gcda emission is
657 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
658 // the flag used. There is no -fno-profile-dir, so the user has no
659 // targeted way to suppress the warning.
660 Arg *FProfileDir = nullptr;
661 if (Args.hasArg(options::OPT_fprofile_arcs) ||
662 Args.hasArg(options::OPT_coverage))
663 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
664
665 // Put the .gcno and .gcda files (if needed) next to the primary output file,
666 // or fall back to a file in the current directory for `clang -c --coverage
667 // d/a.c` in the absence of -o.
668 if (EmitCovNotes || EmitCovData) {
669 SmallString<128> CoverageFilename;
670 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
671 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
672 // path separator.
673 CoverageFilename = DumpDir->getValue();
674 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
675 } else if (Arg *FinalOutput =
676 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
677 CoverageFilename = FinalOutput->getValue();
678 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
679 CoverageFilename = FinalOutput->getValue();
680 } else {
681 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
682 }
683 if (llvm::sys::path::is_relative(CoverageFilename))
684 (void)D.getVFS().makeAbsolute(CoverageFilename);
685 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
686 if (EmitCovNotes) {
687 CmdArgs.push_back(
688 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
689 }
690
691 if (EmitCovData) {
692 if (FProfileDir) {
693 SmallString<128> Gcno = std::move(CoverageFilename);
694 CoverageFilename = FProfileDir->getValue();
695 llvm::sys::path::append(CoverageFilename, Gcno);
696 }
697 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
698 CmdArgs.push_back(
699 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
700 }
701 }
702}
703
704static void
705RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
706 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
707 unsigned DwarfVersion,
708 llvm::DebuggerKind DebuggerTuning) {
709 addDebugInfoKind(CmdArgs, DebugInfoKind);
710 if (DwarfVersion > 0)
711 CmdArgs.push_back(
712 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
713 switch (DebuggerTuning) {
714 case llvm::DebuggerKind::GDB:
715 CmdArgs.push_back("-debugger-tuning=gdb");
716 break;
717 case llvm::DebuggerKind::LLDB:
718 CmdArgs.push_back("-debugger-tuning=lldb");
719 break;
720 case llvm::DebuggerKind::SCE:
721 CmdArgs.push_back("-debugger-tuning=sce");
722 break;
723 case llvm::DebuggerKind::DBX:
724 CmdArgs.push_back("-debugger-tuning=dbx");
725 break;
726 default:
727 break;
728 }
729}
730
731static void RenderDebugInfoCompressionArgs(const ArgList &Args,
732 ArgStringList &CmdArgs,
733 const Driver &D,
734 const ToolChain &TC) {
735 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
736 if (!A)
737 return;
738 if (checkDebugInfoOption(A, Args, D, TC)) {
739 StringRef Value = A->getValue();
740 if (Value == "none") {
741 CmdArgs.push_back("--compress-debug-sections=none");
742 } else if (Value == "zlib") {
743 if (llvm::compression::zlib::isAvailable()) {
744 CmdArgs.push_back(
745 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
746 } else {
747 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
748 }
749 } else if (Value == "zstd") {
750 if (llvm::compression::zstd::isAvailable()) {
751 CmdArgs.push_back(
752 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
753 } else {
754 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
755 }
756 } else {
757 D.Diag(diag::err_drv_unsupported_option_argument)
758 << A->getSpelling() << Value;
759 }
760 }
761}
762
764 const ArgList &Args,
765 ArgStringList &CmdArgs,
766 bool IsCC1As = false) {
767 // If no version was requested by the user, use the default value from the
768 // back end. This is consistent with the value returned from
769 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
770 // requiring the corresponding llvm to have the AMDGPU target enabled,
771 // provided the user (e.g. front end tests) can use the default.
773 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
774 CmdArgs.insert(CmdArgs.begin() + 1,
775 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
776 Twine(CodeObjVer)));
777 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
778 // -cc1as does not accept -mcode-object-version option.
779 if (!IsCC1As)
780 CmdArgs.insert(CmdArgs.begin() + 1,
781 Args.MakeArgString(Twine("-mcode-object-version=") +
782 Twine(CodeObjVer)));
783 }
784}
785
786static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
787 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
788 D.getVFS().getBufferForFile(Path);
789 if (!MemBuf)
790 return false;
791 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
792 if (Magic == llvm::file_magic::unknown)
793 return false;
794 // Return true for both raw Clang AST files and object files which may
795 // contain a __clangast section.
796 if (Magic == llvm::file_magic::clang_ast)
797 return true;
799 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
800 return !Obj.takeError();
801}
802
803static bool gchProbe(const Driver &D, StringRef Path) {
804 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
805 if (!Status)
806 return false;
807
808 if (Status->isDirectory()) {
809 std::error_code EC;
810 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
811 !EC && DI != DE; DI = DI.increment(EC)) {
812 if (maybeHasClangPchSignature(D, DI->path()))
813 return true;
814 }
815 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
816 return false;
817 }
818
819 if (maybeHasClangPchSignature(D, Path))
820 return true;
821 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
822 return false;
823}
824
825void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
826 const Driver &D, const ArgList &Args,
827 ArgStringList &CmdArgs,
828 const InputInfo &Output,
829 const InputInfoList &Inputs) const {
830 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
831
833
834 Args.AddLastArg(CmdArgs, options::OPT_C);
835 Args.AddLastArg(CmdArgs, options::OPT_CC);
836
837 // Handle dependency file generation.
838 Arg *ArgM = Args.getLastArg(options::OPT_MM);
839 if (!ArgM)
840 ArgM = Args.getLastArg(options::OPT_M);
841 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
842 if (!ArgMD)
843 ArgMD = Args.getLastArg(options::OPT_MD);
844
845 // -M and -MM imply -w.
846 if (ArgM)
847 CmdArgs.push_back("-w");
848 else
849 ArgM = ArgMD;
850
851 if (ArgM) {
853 // Determine the output location.
854 const char *DepFile;
855 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
856 DepFile = MF->getValue();
857 C.addFailureResultFile(DepFile, &JA);
858 } else if (Output.getType() == types::TY_Dependencies) {
859 DepFile = Output.getFilename();
860 } else if (!ArgMD) {
861 DepFile = "-";
862 } else {
863 DepFile = getDependencyFileName(Args, Inputs);
864 C.addFailureResultFile(DepFile, &JA);
865 }
866 CmdArgs.push_back("-dependency-file");
867 CmdArgs.push_back(DepFile);
868 }
869 // Cmake generates dependency files using all compilation options specified
870 // by users. Claim those not used for dependency files.
872 Args.ClaimAllArgs(options::OPT_offload_compress);
873 Args.ClaimAllArgs(options::OPT_no_offload_compress);
874 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
875 }
876
877 bool HasTarget = false;
878 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
879 HasTarget = true;
880 A->claim();
881 if (A->getOption().matches(options::OPT_MT)) {
882 A->render(Args, CmdArgs);
883 } else {
884 CmdArgs.push_back("-MT");
885 SmallString<128> Quoted;
886 quoteMakeTarget(A->getValue(), Quoted);
887 CmdArgs.push_back(Args.MakeArgString(Quoted));
888 }
889 }
890
891 // Add a default target if one wasn't specified.
892 if (!HasTarget) {
893 const char *DepTarget;
894
895 // If user provided -o, that is the dependency target, except
896 // when we are only generating a dependency file.
897 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
898 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
899 DepTarget = OutputOpt->getValue();
900 } else {
901 // Otherwise derive from the base input.
902 //
903 // FIXME: This should use the computed output file location.
904 SmallString<128> P(Inputs[0].getBaseInput());
905 llvm::sys::path::replace_extension(P, "o");
906 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
907 }
908
909 CmdArgs.push_back("-MT");
910 SmallString<128> Quoted;
911 quoteMakeTarget(DepTarget, Quoted);
912 CmdArgs.push_back(Args.MakeArgString(Quoted));
913 }
914
915 if (ArgM->getOption().matches(options::OPT_M) ||
916 ArgM->getOption().matches(options::OPT_MD))
917 CmdArgs.push_back("-sys-header-deps");
918
919 // Determine module file deps mode.
920 StringRef ModuleFileDepsVal;
921 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
922 options::OPT_fmodule_file_deps,
923 options::OPT_fno_module_file_deps)) {
924 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
925 ModuleFileDepsVal = A->getValue();
926 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
927 ModuleFileDepsVal = "all";
928 else
929 ModuleFileDepsVal = "none";
930 } else if (isa<PrecompileJobAction>(JA)) {
931 ModuleFileDepsVal = "all";
932 }
933 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
934 CmdArgs.push_back(
935 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
936 }
937
938 if (Args.hasArg(options::OPT_MG)) {
939 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
940 ArgM->getOption().matches(options::OPT_MMD))
941 D.Diag(diag::err_drv_mg_requires_m_or_mm);
942 CmdArgs.push_back("-MG");
943 }
944
945 Args.AddLastArg(CmdArgs, options::OPT_MP);
946 Args.AddLastArg(CmdArgs, options::OPT_MV);
947
948 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
949 // before we -I or -include anything else, because we must pick up the
950 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
951 // rather than from e.g. /usr/local/include.
953 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
955 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
957 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
958
959 // If we are offloading to a target via OpenMP we need to include the
960 // openmp_wrappers folder which contains alternative system headers.
962 !Args.hasArg(options::OPT_nostdinc) &&
963 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
964 true) &&
965 getToolChain().getTriple().isGPU()) {
966 if (!Args.hasArg(options::OPT_nobuiltininc)) {
967 // Add openmp_wrappers/* to our system include path. This lets us wrap
968 // standard library headers.
969 SmallString<128> P(D.ResourceDir);
970 llvm::sys::path::append(P, "include");
971 llvm::sys::path::append(P, "openmp_wrappers");
972 CmdArgs.push_back("-internal-isystem");
973 CmdArgs.push_back(Args.MakeArgString(P));
974 }
975
976 CmdArgs.push_back("-include");
977 CmdArgs.push_back("__clang_openmp_device_functions.h");
978 }
979
980 if (Args.hasArg(options::OPT_foffload_via_llvm)) {
981 // Add llvm_wrappers/* to our system include path. This lets us wrap
982 // standard library headers and other headers.
983 SmallString<128> P(D.ResourceDir);
984 llvm::sys::path::append(P, "include", "llvm_offload_wrappers");
985 CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});
987 CmdArgs.push_back("__llvm_offload_device.h");
988 else
989 CmdArgs.push_back("__llvm_offload_host.h");
990 }
991
992 // Add -i* options, and automatically translate to
993 // -include-pch/-include-pth for transparent PCH support. It's
994 // wonky, but we include looking for .gch so we can support seamless
995 // replacement into a build system already set up to be generating
996 // .gch files.
997
998 if (getToolChain().getDriver().IsCLMode()) {
999 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1000 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1001 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1003 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1004 // -fpch-instantiate-templates is the default when creating
1005 // precomp using /Yc
1006 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1007 options::OPT_fno_pch_instantiate_templates, true))
1008 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1009 }
1010 if (YcArg || YuArg) {
1011 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1012 if (!isa<PrecompileJobAction>(JA)) {
1013 CmdArgs.push_back("-include-pch");
1014 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1015 C, !ThroughHeader.empty()
1016 ? ThroughHeader
1017 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1018 }
1019
1020 if (ThroughHeader.empty()) {
1021 CmdArgs.push_back(Args.MakeArgString(
1022 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1023 } else {
1024 CmdArgs.push_back(
1025 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1026 }
1027 }
1028 }
1029
1030 bool RenderedImplicitInclude = false;
1031 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1032 if (A->getOption().matches(options::OPT_include) &&
1033 D.getProbePrecompiled()) {
1034 // Handling of gcc-style gch precompiled headers.
1035 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1036 RenderedImplicitInclude = true;
1037
1038 bool FoundPCH = false;
1039 SmallString<128> P(A->getValue());
1040 // We want the files to have a name like foo.h.pch. Add a dummy extension
1041 // so that replace_extension does the right thing.
1042 P += ".dummy";
1043 llvm::sys::path::replace_extension(P, "pch");
1044 if (D.getVFS().exists(P))
1045 FoundPCH = true;
1046
1047 if (!FoundPCH) {
1048 // For GCC compat, probe for a file or directory ending in .gch instead.
1049 llvm::sys::path::replace_extension(P, "gch");
1050 FoundPCH = gchProbe(D, P.str());
1051 }
1052
1053 if (FoundPCH) {
1054 if (IsFirstImplicitInclude) {
1055 A->claim();
1056 CmdArgs.push_back("-include-pch");
1057 CmdArgs.push_back(Args.MakeArgString(P));
1058 continue;
1059 } else {
1060 // Ignore the PCH if not first on command line and emit warning.
1061 D.Diag(diag::warn_drv_pch_not_first_include) << P
1062 << A->getAsString(Args);
1063 }
1064 }
1065 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1066 // Handling of paths which must come late. These entries are handled by
1067 // the toolchain itself after the resource dir is inserted in the right
1068 // search order.
1069 // Do not claim the argument so that the use of the argument does not
1070 // silently go unnoticed on toolchains which do not honour the option.
1071 continue;
1072 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1073 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1074 continue;
1075 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1076 // This is used only by the driver. No need to pass to cc1.
1077 continue;
1078 }
1079
1080 // Not translated, render as usual.
1081 A->claim();
1082 A->render(Args, CmdArgs);
1083 }
1084
1085 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1087 // Collect all enabled NVPTX architectures.
1088 std::set<unsigned> ArchIDs;
1089 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1090 const ToolChain *TC = I.second;
1091 for (StringRef Arch :
1092 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1094 if (IsNVIDIAOffloadArch(OA))
1095 ArchIDs.insert(CudaArchToID(OA));
1096 }
1097 }
1098
1099 if (!ArchIDs.empty()) {
1100 SmallString<128> List;
1101 llvm::raw_svector_ostream OS(List);
1102 llvm::interleave(ArchIDs, OS, ",");
1103 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1104 }
1105 }
1106
1107 Args.addAllArgs(CmdArgs,
1108 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1109 options::OPT_F, options::OPT_embed_dir_EQ});
1110
1111 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1112
1113 // FIXME: There is a very unfortunate problem here, some troubled
1114 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1115 // really support that we would have to parse and then translate
1116 // those options. :(
1117 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1118 options::OPT_Xpreprocessor);
1119
1120 // -I- is a deprecated GCC feature, reject it.
1121 if (Arg *A = Args.getLastArg(options::OPT_I_))
1122 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1123
1124 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1125 // -isysroot to the CC1 invocation.
1126 StringRef sysroot = C.getSysRoot();
1127 if (sysroot != "") {
1128 if (!Args.hasArg(options::OPT_isysroot)) {
1129 CmdArgs.push_back("-isysroot");
1130 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1131 }
1132 }
1133
1134 // Parse additional include paths from environment variables.
1135 // FIXME: We should probably sink the logic for handling these from the
1136 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1137 // CPATH - included following the user specified includes (but prior to
1138 // builtin and standard includes).
1139 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1140 // C_INCLUDE_PATH - system includes enabled when compiling C.
1141 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1142 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1143 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1144 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1145 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1146 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1147 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1148
1149 // While adding the include arguments, we also attempt to retrieve the
1150 // arguments of related offloading toolchains or arguments that are specific
1151 // of an offloading programming model.
1152
1153 // Add C++ include arguments, if needed.
1154 if (types::isCXX(Inputs[0].getType())) {
1155 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1157 C, JA, getToolChain(),
1158 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1159 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1160 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1161 });
1162 }
1163
1164 // If we are compiling for a GPU target we want to override the system headers
1165 // with ones created by the 'libc' project if present.
1166 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1167 // OffloadKind as an argument.
1168 if (!Args.hasArg(options::OPT_nostdinc) &&
1169 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1170 true) &&
1171 !Args.hasArg(options::OPT_nobuiltininc) &&
1172 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1173 // TODO: CUDA / HIP include their own headers for some common functions
1174 // implemented here. We'll need to clean those up so they do not conflict.
1175 SmallString<128> P(D.ResourceDir);
1176 llvm::sys::path::append(P, "include");
1177 llvm::sys::path::append(P, "llvm_libc_wrappers");
1178 CmdArgs.push_back("-internal-isystem");
1179 CmdArgs.push_back(Args.MakeArgString(P));
1180 }
1181
1182 // Add system include arguments for all targets but IAMCU.
1183 if (!IsIAMCU)
1185 [&Args, &CmdArgs](const ToolChain &TC) {
1186 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1187 });
1188 else {
1189 // For IAMCU add special include arguments.
1190 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1191 }
1192
1193 addMacroPrefixMapArg(D, Args, CmdArgs);
1194 addCoveragePrefixMapArg(D, Args, CmdArgs);
1195
1196 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1197 options::OPT_fno_file_reproducible);
1198
1199 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1200 CmdArgs.push_back("-source-date-epoch");
1201 CmdArgs.push_back(Args.MakeArgString(Epoch));
1202 }
1203
1204 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1205 options::OPT_fno_define_target_os_macros);
1206}
1207
1208// FIXME: Move to target hook.
1209static bool isSignedCharDefault(const llvm::Triple &Triple) {
1210 switch (Triple.getArch()) {
1211 default:
1212 return true;
1213
1214 case llvm::Triple::aarch64:
1215 case llvm::Triple::aarch64_32:
1216 case llvm::Triple::aarch64_be:
1217 case llvm::Triple::arm:
1218 case llvm::Triple::armeb:
1219 case llvm::Triple::thumb:
1220 case llvm::Triple::thumbeb:
1221 if (Triple.isOSDarwin() || Triple.isOSWindows())
1222 return true;
1223 return false;
1224
1225 case llvm::Triple::ppc:
1226 case llvm::Triple::ppc64:
1227 if (Triple.isOSDarwin())
1228 return true;
1229 return false;
1230
1231 case llvm::Triple::csky:
1232 case llvm::Triple::hexagon:
1233 case llvm::Triple::msp430:
1234 case llvm::Triple::ppcle:
1235 case llvm::Triple::ppc64le:
1236 case llvm::Triple::riscv32:
1237 case llvm::Triple::riscv64:
1238 case llvm::Triple::riscv32be:
1239 case llvm::Triple::riscv64be:
1240 case llvm::Triple::systemz:
1241 case llvm::Triple::xcore:
1242 case llvm::Triple::xtensa:
1243 return false;
1244 }
1245}
1246
1247static bool hasMultipleInvocations(const llvm::Triple &Triple,
1248 const ArgList &Args) {
1249 // Supported only on Darwin where we invoke the compiler multiple times
1250 // followed by an invocation to lipo.
1251 if (!Triple.isOSDarwin())
1252 return false;
1253 // If more than one "-arch <arch>" is specified, we're targeting multiple
1254 // architectures resulting in a fat binary.
1255 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1256}
1257
1258static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1259 const llvm::Triple &Triple) {
1260 // When enabling remarks, we need to error if:
1261 // * The remark file is specified but we're targeting multiple architectures,
1262 // which means more than one remark file is being generated.
1264 bool hasExplicitOutputFile =
1265 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1266 if (hasMultipleInvocations && hasExplicitOutputFile) {
1267 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1268 << "-foptimization-record-file";
1269 return false;
1270 }
1271 return true;
1272}
1273
1274static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1275 const llvm::Triple &Triple,
1276 const InputInfo &Input,
1277 const InputInfo &Output, const JobAction &JA) {
1278 StringRef Format = "yaml";
1279 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1280 Format = A->getValue();
1281
1282 CmdArgs.push_back("-opt-record-file");
1283
1284 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1285 if (A) {
1286 CmdArgs.push_back(A->getValue());
1287 } else {
1288 bool hasMultipleArchs =
1289 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1290 Args.getAllArgValues(options::OPT_arch).size() > 1;
1291
1293
1294 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1295 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1296 F = FinalOutput->getValue();
1297 } else {
1298 if (Format != "yaml" && // For YAML, keep the original behavior.
1299 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1300 Output.isFilename())
1301 F = Output.getFilename();
1302 }
1303
1304 if (F.empty()) {
1305 // Use the input filename.
1306 F = llvm::sys::path::stem(Input.getBaseInput());
1307
1308 // If we're compiling for an offload architecture (i.e. a CUDA device),
1309 // we need to make the file name for the device compilation different
1310 // from the host compilation.
1313 llvm::sys::path::replace_extension(F, "");
1315 Triple.normalize());
1316 F += "-";
1317 F += JA.getOffloadingArch();
1318 }
1319 }
1320
1321 // If we're having more than one "-arch", we should name the files
1322 // differently so that every cc1 invocation writes to a different file.
1323 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1324 // name from the triple.
1325 if (hasMultipleArchs) {
1326 // First, remember the extension.
1327 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1328 // then, remove it.
1329 llvm::sys::path::replace_extension(F, "");
1330 // attach -<arch> to it.
1331 F += "-";
1332 F += Triple.getArchName();
1333 // put back the extension.
1334 llvm::sys::path::replace_extension(F, OldExtension);
1335 }
1336
1337 SmallString<32> Extension;
1338 Extension += "opt.";
1339 Extension += Format;
1340
1341 llvm::sys::path::replace_extension(F, Extension);
1342 CmdArgs.push_back(Args.MakeArgString(F));
1343 }
1344
1345 if (const Arg *A =
1346 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1347 CmdArgs.push_back("-opt-record-passes");
1348 CmdArgs.push_back(A->getValue());
1349 }
1350
1351 if (!Format.empty()) {
1352 CmdArgs.push_back("-opt-record-format");
1353 CmdArgs.push_back(Format.data());
1354 }
1355}
1356
1357void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1358 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1359 options::OPT_fno_aapcs_bitfield_width, true))
1360 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1361
1362 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1363 CmdArgs.push_back("-faapcs-bitfield-load");
1364}
1365
1366namespace {
1367void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1368 const ArgList &Args, ArgStringList &CmdArgs) {
1369 // Select the ABI to use.
1370 // FIXME: Support -meabi.
1371 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1372 const char *ABIName = nullptr;
1373 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1374 ABIName = A->getValue();
1375 else
1376 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1377
1378 CmdArgs.push_back("-target-abi");
1379 CmdArgs.push_back(ABIName);
1380}
1381
1382void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1383 auto StrictAlignIter =
1384 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1385 return Arg == "+strict-align" || Arg == "-strict-align";
1386 });
1387 if (StrictAlignIter != CmdArgs.rend() &&
1388 StringRef(*StrictAlignIter) == "+strict-align")
1389 CmdArgs.push_back("-Wunaligned-access");
1390}
1391}
1392
1393static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1394 ArgStringList &CmdArgs, bool isAArch64) {
1395 const llvm::Triple &Triple = TC.getEffectiveTriple();
1396 const Arg *A = isAArch64
1397 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1398 options::OPT_mbranch_protection_EQ)
1399 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1400 if (!A) {
1401 if (Triple.isOSOpenBSD() && isAArch64) {
1402 CmdArgs.push_back("-msign-return-address=non-leaf");
1403 CmdArgs.push_back("-msign-return-address-key=a_key");
1404 CmdArgs.push_back("-mbranch-target-enforce");
1405 }
1406 return;
1407 }
1408
1409 const Driver &D = TC.getDriver();
1410 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1411 D.Diag(diag::warn_incompatible_branch_protection_option)
1412 << Triple.getArchName();
1413
1414 StringRef Scope, Key;
1415 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1416
1417 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1418 Scope = A->getValue();
1419 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1420 D.Diag(diag::err_drv_unsupported_option_argument)
1421 << A->getSpelling() << Scope;
1422 Key = "a_key";
1423 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1424 BranchProtectionPAuthLR = false;
1425 GuardedControlStack = false;
1426 } else {
1427 StringRef DiagMsg;
1428 llvm::ARM::ParsedBranchProtection PBP;
1429 bool EnablePAuthLR = false;
1430
1431 // To know if we need to enable PAuth-LR As part of the standard branch
1432 // protection option, it needs to be determined if the feature has been
1433 // activated in the `march` argument. This information is stored within the
1434 // CmdArgs variable and can be found using a search.
1435 if (isAArch64) {
1436 auto isPAuthLR = [](const char *member) {
1437 llvm::AArch64::ExtensionInfo pauthlr_extension =
1438 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1439 return pauthlr_extension.PosTargetFeature == member;
1440 };
1441
1442 if (llvm::any_of(CmdArgs, isPAuthLR))
1443 EnablePAuthLR = true;
1444 }
1445 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
1446 EnablePAuthLR))
1447 D.Diag(diag::err_drv_unsupported_option_argument)
1448 << A->getSpelling() << DiagMsg;
1449 if (!isAArch64 && PBP.Key == "b_key")
1450 D.Diag(diag::warn_unsupported_branch_protection)
1451 << "b-key" << A->getAsString(Args);
1452 Scope = PBP.Scope;
1453 Key = PBP.Key;
1454 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1455 IndirectBranches = PBP.BranchTargetEnforcement;
1456 GuardedControlStack = PBP.GuardedControlStack;
1457 }
1458
1459 Arg *PtrauthReturnsArg = Args.getLastArg(options::OPT_fptrauth_returns,
1460 options::OPT_fno_ptrauth_returns);
1461 bool HasPtrauthReturns =
1462 PtrauthReturnsArg &&
1463 PtrauthReturnsArg->getOption().matches(options::OPT_fptrauth_returns);
1464 // GCS is currently untested with ptrauth-returns, but enabling this could be
1465 // allowed in future after testing with a suitable system.
1466 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1467 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1468 D.Diag(diag::err_drv_unsupported_opt_for_target)
1469 << A->getAsString(Args) << Triple.getTriple();
1470 else if (HasPtrauthReturns)
1471 D.Diag(diag::err_drv_incompatible_options)
1472 << A->getAsString(Args) << "-fptrauth-returns";
1473 }
1474
1475 CmdArgs.push_back(
1476 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1477 if (Scope != "none")
1478 CmdArgs.push_back(
1479 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1480 if (BranchProtectionPAuthLR)
1481 CmdArgs.push_back(
1482 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1483 if (IndirectBranches)
1484 CmdArgs.push_back("-mbranch-target-enforce");
1485
1486 if (GuardedControlStack)
1487 CmdArgs.push_back("-mguarded-control-stack");
1488}
1489
1490void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1491 ArgStringList &CmdArgs, bool KernelOrKext) const {
1492 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1493
1494 // Determine floating point ABI from the options & target defaults.
1496 if (ABI == arm::FloatABI::Soft) {
1497 // Floating point operations and argument passing are soft.
1498 // FIXME: This changes CPP defines, we need -target-soft-float.
1499 CmdArgs.push_back("-msoft-float");
1500 CmdArgs.push_back("-mfloat-abi");
1501 CmdArgs.push_back("soft");
1502 } else if (ABI == arm::FloatABI::SoftFP) {
1503 // Floating point operations are hard, but argument passing is soft.
1504 CmdArgs.push_back("-mfloat-abi");
1505 CmdArgs.push_back("soft");
1506 } else {
1507 // Floating point operations and argument passing are hard.
1508 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1509 CmdArgs.push_back("-mfloat-abi");
1510 CmdArgs.push_back("hard");
1511 }
1512
1513 // Forward the -mglobal-merge option for explicit control over the pass.
1514 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1515 options::OPT_mno_global_merge)) {
1516 CmdArgs.push_back("-mllvm");
1517 if (A->getOption().matches(options::OPT_mno_global_merge))
1518 CmdArgs.push_back("-arm-global-merge=false");
1519 else
1520 CmdArgs.push_back("-arm-global-merge=true");
1521 }
1522
1523 if (!Args.hasFlag(options::OPT_mimplicit_float,
1524 options::OPT_mno_implicit_float, true))
1525 CmdArgs.push_back("-no-implicit-float");
1526
1527 if (Args.getLastArg(options::OPT_mcmse))
1528 CmdArgs.push_back("-mcmse");
1529
1530 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1531
1532 // Enable/disable return address signing and indirect branch targets.
1533 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1534
1535 AddUnalignedAccessWarning(CmdArgs);
1536}
1537
1538void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1539 const ArgList &Args, bool KernelOrKext,
1540 ArgStringList &CmdArgs) const {
1541 const ToolChain &TC = getToolChain();
1542
1543 // Add the target features
1544 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1545
1546 // Add target specific flags.
1547 switch (TC.getArch()) {
1548 default:
1549 break;
1550
1551 case llvm::Triple::arm:
1552 case llvm::Triple::armeb:
1553 case llvm::Triple::thumb:
1554 case llvm::Triple::thumbeb:
1555 // Use the effective triple, which takes into account the deployment target.
1556 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1557 break;
1558
1559 case llvm::Triple::aarch64:
1560 case llvm::Triple::aarch64_32:
1561 case llvm::Triple::aarch64_be:
1562 AddAArch64TargetArgs(Args, CmdArgs);
1563 break;
1564
1565 case llvm::Triple::loongarch32:
1566 case llvm::Triple::loongarch64:
1567 AddLoongArchTargetArgs(Args, CmdArgs);
1568 break;
1569
1570 case llvm::Triple::mips:
1571 case llvm::Triple::mipsel:
1572 case llvm::Triple::mips64:
1573 case llvm::Triple::mips64el:
1574 AddMIPSTargetArgs(Args, CmdArgs);
1575 break;
1576
1577 case llvm::Triple::ppc:
1578 case llvm::Triple::ppcle:
1579 case llvm::Triple::ppc64:
1580 case llvm::Triple::ppc64le:
1581 AddPPCTargetArgs(Args, CmdArgs);
1582 break;
1583
1584 case llvm::Triple::riscv32:
1585 case llvm::Triple::riscv64:
1586 case llvm::Triple::riscv32be:
1587 case llvm::Triple::riscv64be:
1588 AddRISCVTargetArgs(Args, CmdArgs);
1589 break;
1590
1591 case llvm::Triple::sparc:
1592 case llvm::Triple::sparcel:
1593 case llvm::Triple::sparcv9:
1594 AddSparcTargetArgs(Args, CmdArgs);
1595 break;
1596
1597 case llvm::Triple::systemz:
1598 AddSystemZTargetArgs(Args, CmdArgs);
1599 break;
1600
1601 case llvm::Triple::x86:
1602 case llvm::Triple::x86_64:
1603 AddX86TargetArgs(Args, CmdArgs);
1604 break;
1605
1606 case llvm::Triple::lanai:
1607 AddLanaiTargetArgs(Args, CmdArgs);
1608 break;
1609
1610 case llvm::Triple::hexagon:
1611 AddHexagonTargetArgs(Args, CmdArgs);
1612 break;
1613
1614 case llvm::Triple::wasm32:
1615 case llvm::Triple::wasm64:
1616 AddWebAssemblyTargetArgs(Args, CmdArgs);
1617 break;
1618
1619 case llvm::Triple::ve:
1620 AddVETargetArgs(Args, CmdArgs);
1621 break;
1622 }
1623}
1624
1625namespace {
1626void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1627 ArgStringList &CmdArgs) {
1628 const char *ABIName = nullptr;
1629 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1630 ABIName = A->getValue();
1631 else if (Triple.isOSDarwin())
1632 ABIName = "darwinpcs";
1633 // TODO: we probably want to have some target hook here.
1634 else if (Triple.isOSLinux() &&
1635 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1636 ABIName = "pauthtest";
1637 else
1638 ABIName = "aapcs";
1639
1640 CmdArgs.push_back("-target-abi");
1641 CmdArgs.push_back(ABIName);
1642}
1643}
1644
1645void Clang::AddAArch64TargetArgs(const ArgList &Args,
1646 ArgStringList &CmdArgs) const {
1647 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1648
1649 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1650 Args.hasArg(options::OPT_mkernel) ||
1651 Args.hasArg(options::OPT_fapple_kext))
1652 CmdArgs.push_back("-disable-red-zone");
1653
1654 if (!Args.hasFlag(options::OPT_mimplicit_float,
1655 options::OPT_mno_implicit_float, true))
1656 CmdArgs.push_back("-no-implicit-float");
1657
1658 RenderAArch64ABI(Triple, Args, CmdArgs);
1659
1660 // Forward the -mglobal-merge option for explicit control over the pass.
1661 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1662 options::OPT_mno_global_merge)) {
1663 CmdArgs.push_back("-mllvm");
1664 if (A->getOption().matches(options::OPT_mno_global_merge))
1665 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1666 else
1667 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1668 }
1669
1670 // Handle -msve_vector_bits=<bits>
1671 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1672 StringRef VScaleMax) {
1673 StringRef Val = A->getValue();
1674 const Driver &D = getToolChain().getDriver();
1675 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1676 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1677 Val == "1024+" || Val == "2048+") {
1678 unsigned Bits = 0;
1679 if (!Val.consume_back("+")) {
1680 bool Invalid = Val.getAsInteger(10, Bits);
1681 (void)Invalid;
1682 assert(!Invalid && "Failed to parse value");
1683 CmdArgs.push_back(
1684 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1685 }
1686
1687 bool Invalid = Val.getAsInteger(10, Bits);
1688 (void)Invalid;
1689 assert(!Invalid && "Failed to parse value");
1690
1691 CmdArgs.push_back(
1692 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1693 } else if (Val == "scalable") {
1694 // Silently drop requests for vector-length agnostic code as it's implied.
1695 } else {
1696 // Handle the unsupported values passed to msve-vector-bits.
1697 D.Diag(diag::err_drv_unsupported_option_argument)
1698 << A->getSpelling() << Val;
1699 }
1700 };
1701 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1702 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1703 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1704 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1705
1706 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1707
1708 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1709 CmdArgs.push_back("-tune-cpu");
1710 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1711 }
1712
1713 AddUnalignedAccessWarning(CmdArgs);
1714
1715 if (Triple.isOSDarwin() ||
1716 (Triple.isOSLinux() &&
1717 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1718 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1719 options::OPT_fno_ptrauth_intrinsics);
1720 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1721 options::OPT_fno_ptrauth_calls);
1722 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1723 options::OPT_fno_ptrauth_returns);
1724 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1725 options::OPT_fno_ptrauth_auth_traps);
1726 Args.addOptInFlag(
1727 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1728 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1729 Args.addOptInFlag(
1730 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1731 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1732 Args.addOptInFlag(
1733 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1734 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1735 Args.addOptInFlag(
1736 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1737 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1738 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1739 options::OPT_fno_ptrauth_indirect_gotos);
1740 }
1741 if (Triple.isOSLinux() &&
1742 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1743 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1744 options::OPT_fno_ptrauth_init_fini);
1745 Args.addOptInFlag(
1746 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1747 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1748 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1749 options::OPT_fno_ptrauth_elf_got);
1750 }
1751 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1752 options::OPT_fno_aarch64_jump_table_hardening);
1753
1754 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1755 options::OPT_fno_ptrauth_objc_isa);
1756 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1757 options::OPT_fno_ptrauth_objc_interface_sel);
1758 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1759 options::OPT_fno_ptrauth_objc_class_ro);
1760
1761 // Enable/disable return address signing and indirect branch targets.
1762 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1763}
1764
1765void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1766 ArgStringList &CmdArgs) const {
1767 const llvm::Triple &Triple = getToolChain().getTriple();
1768
1769 CmdArgs.push_back("-target-abi");
1770 CmdArgs.push_back(
1771 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1772 .data());
1773
1774 // Handle -mtune.
1775 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1776 std::string TuneCPU = A->getValue();
1777 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1778 CmdArgs.push_back("-tune-cpu");
1779 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1780 }
1781
1782 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1783 options::OPT_mno_annotate_tablejump)) {
1784 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1785 CmdArgs.push_back("-mllvm");
1786 CmdArgs.push_back("-loongarch-annotate-tablejump");
1787 }
1788 }
1789}
1790
1791void Clang::AddMIPSTargetArgs(const ArgList &Args,
1792 ArgStringList &CmdArgs) const {
1793 const Driver &D = getToolChain().getDriver();
1794 StringRef CPUName;
1795 StringRef ABIName;
1796 const llvm::Triple &Triple = getToolChain().getTriple();
1797 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1798
1799 CmdArgs.push_back("-target-abi");
1800 CmdArgs.push_back(ABIName.data());
1801
1802 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1803 if (ABI == mips::FloatABI::Soft) {
1804 // Floating point operations and argument passing are soft.
1805 CmdArgs.push_back("-msoft-float");
1806 CmdArgs.push_back("-mfloat-abi");
1807 CmdArgs.push_back("soft");
1808 } else {
1809 // Floating point operations and argument passing are hard.
1810 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1811 CmdArgs.push_back("-mfloat-abi");
1812 CmdArgs.push_back("hard");
1813 }
1814
1815 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1816 options::OPT_mno_ldc1_sdc1)) {
1817 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1818 CmdArgs.push_back("-mllvm");
1819 CmdArgs.push_back("-mno-ldc1-sdc1");
1820 }
1821 }
1822
1823 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1824 options::OPT_mno_check_zero_division)) {
1825 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1826 CmdArgs.push_back("-mllvm");
1827 CmdArgs.push_back("-mno-check-zero-division");
1828 }
1829 }
1830
1831 if (Args.getLastArg(options::OPT_mfix4300)) {
1832 CmdArgs.push_back("-mllvm");
1833 CmdArgs.push_back("-mfix4300");
1834 }
1835
1836 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1837 StringRef v = A->getValue();
1838 CmdArgs.push_back("-mllvm");
1839 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1840 A->claim();
1841 }
1842
1843 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1844 Arg *ABICalls =
1845 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1846
1847 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1848 // -mgpopt is the default for static, -fno-pic environments but these two
1849 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1850 // the only case where -mllvm -mgpopt is passed.
1851 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1852 // passed explicitly when compiling something with -mabicalls
1853 // (implictly) in affect. Currently the warning is in the backend.
1854 //
1855 // When the ABI in use is N64, we also need to determine the PIC mode that
1856 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1857 bool NoABICalls =
1858 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1859
1860 llvm::Reloc::Model RelocationModel;
1861 unsigned PICLevel;
1862 bool IsPIE;
1863 std::tie(RelocationModel, PICLevel, IsPIE) =
1864 ParsePICArgs(getToolChain(), Args);
1865
1866 NoABICalls = NoABICalls ||
1867 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1868
1869 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1870 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1871 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1872 CmdArgs.push_back("-mllvm");
1873 CmdArgs.push_back("-mgpopt");
1874
1875 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1876 options::OPT_mno_local_sdata);
1877 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1878 options::OPT_mno_extern_sdata);
1879 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1880 options::OPT_mno_embedded_data);
1881 if (LocalSData) {
1882 CmdArgs.push_back("-mllvm");
1883 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1884 CmdArgs.push_back("-mlocal-sdata=1");
1885 } else {
1886 CmdArgs.push_back("-mlocal-sdata=0");
1887 }
1888 LocalSData->claim();
1889 }
1890
1891 if (ExternSData) {
1892 CmdArgs.push_back("-mllvm");
1893 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1894 CmdArgs.push_back("-mextern-sdata=1");
1895 } else {
1896 CmdArgs.push_back("-mextern-sdata=0");
1897 }
1898 ExternSData->claim();
1899 }
1900
1901 if (EmbeddedData) {
1902 CmdArgs.push_back("-mllvm");
1903 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1904 CmdArgs.push_back("-membedded-data=1");
1905 } else {
1906 CmdArgs.push_back("-membedded-data=0");
1907 }
1908 EmbeddedData->claim();
1909 }
1910
1911 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1912 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1913
1914 if (GPOpt)
1915 GPOpt->claim();
1916
1917 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1918 StringRef Val = StringRef(A->getValue());
1919 if (mips::hasCompactBranches(CPUName)) {
1920 if (Val == "never" || Val == "always" || Val == "optimal") {
1921 CmdArgs.push_back("-mllvm");
1922 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1923 } else
1924 D.Diag(diag::err_drv_unsupported_option_argument)
1925 << A->getSpelling() << Val;
1926 } else
1927 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1928 }
1929
1930 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1931 options::OPT_mno_relax_pic_calls)) {
1932 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1933 CmdArgs.push_back("-mllvm");
1934 CmdArgs.push_back("-mips-jalr-reloc=0");
1935 }
1936 }
1937}
1938
1939void Clang::AddPPCTargetArgs(const ArgList &Args,
1940 ArgStringList &CmdArgs) const {
1941 const Driver &D = getToolChain().getDriver();
1942 const llvm::Triple &T = getToolChain().getTriple();
1943 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1944 CmdArgs.push_back("-tune-cpu");
1945 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
1946 CmdArgs.push_back(Args.MakeArgString(CPU.str()));
1947 }
1948
1949 // Select the ABI to use.
1950 const char *ABIName = nullptr;
1951 if (T.isOSBinFormatELF()) {
1952 switch (getToolChain().getArch()) {
1953 case llvm::Triple::ppc64: {
1954 if (T.isPPC64ELFv2ABI())
1955 ABIName = "elfv2";
1956 else
1957 ABIName = "elfv1";
1958 break;
1959 }
1960 case llvm::Triple::ppc64le:
1961 ABIName = "elfv2";
1962 break;
1963 default:
1964 break;
1965 }
1966 }
1967
1968 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1969 bool VecExtabi = false;
1970 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1971 StringRef V = A->getValue();
1972 if (V == "ieeelongdouble") {
1973 IEEELongDouble = true;
1974 A->claim();
1975 } else if (V == "ibmlongdouble") {
1976 IEEELongDouble = false;
1977 A->claim();
1978 } else if (V == "vec-default") {
1979 VecExtabi = false;
1980 A->claim();
1981 } else if (V == "vec-extabi") {
1982 VecExtabi = true;
1983 A->claim();
1984 } else if (V == "elfv1") {
1985 ABIName = "elfv1";
1986 A->claim();
1987 } else if (V == "elfv2") {
1988 ABIName = "elfv2";
1989 A->claim();
1990 } else if (V != "altivec")
1991 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1992 // the option if given as we don't have backend support for any targets
1993 // that don't use the altivec abi.
1994 ABIName = A->getValue();
1995 }
1996 if (IEEELongDouble)
1997 CmdArgs.push_back("-mabi=ieeelongdouble");
1998 if (VecExtabi) {
1999 if (!T.isOSAIX())
2000 D.Diag(diag::err_drv_unsupported_opt_for_target)
2001 << "-mabi=vec-extabi" << T.str();
2002 CmdArgs.push_back("-mabi=vec-extabi");
2003 }
2004
2005 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2006 CmdArgs.push_back("-disable-red-zone");
2007
2009 if (FloatABI == ppc::FloatABI::Soft) {
2010 // Floating point operations and argument passing are soft.
2011 CmdArgs.push_back("-msoft-float");
2012 CmdArgs.push_back("-mfloat-abi");
2013 CmdArgs.push_back("soft");
2014 } else {
2015 // Floating point operations and argument passing are hard.
2016 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2017 CmdArgs.push_back("-mfloat-abi");
2018 CmdArgs.push_back("hard");
2019 }
2020
2021 if (ABIName) {
2022 CmdArgs.push_back("-target-abi");
2023 CmdArgs.push_back(ABIName);
2024 }
2025}
2026
2027void Clang::AddRISCVTargetArgs(const ArgList &Args,
2028 ArgStringList &CmdArgs) const {
2029 const llvm::Triple &Triple = getToolChain().getTriple();
2030 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2031
2032 CmdArgs.push_back("-target-abi");
2033 CmdArgs.push_back(ABIName.data());
2034
2035 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2036 CmdArgs.push_back("-msmall-data-limit");
2037 CmdArgs.push_back(A->getValue());
2038 }
2039
2040 if (!Args.hasFlag(options::OPT_mimplicit_float,
2041 options::OPT_mno_implicit_float, true))
2042 CmdArgs.push_back("-no-implicit-float");
2043
2044 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2045 CmdArgs.push_back("-tune-cpu");
2046 if (strcmp(A->getValue(), "native") == 0)
2047 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2048 else
2049 CmdArgs.push_back(A->getValue());
2050 }
2051
2052 // Handle -mrvv-vector-bits=<bits>
2053 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2054 StringRef Val = A->getValue();
2055 const Driver &D = getToolChain().getDriver();
2056
2057 // Get minimum VLen from march.
2058 unsigned MinVLen = 0;
2059 std::string Arch = riscv::getRISCVArch(Args, Triple);
2060 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2061 Arch, /*EnableExperimentalExtensions*/ true);
2062 // Ignore parsing error.
2063 if (!errorToBool(ISAInfo.takeError()))
2064 MinVLen = (*ISAInfo)->getMinVLen();
2065
2066 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2067 // as integer as long as we have a MinVLen.
2068 unsigned Bits = 0;
2069 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2070 Bits = MinVLen;
2071 } else if (!Val.getAsInteger(10, Bits)) {
2072 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2073 // at least MinVLen.
2074 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2075 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2076 Bits = 0;
2077 }
2078
2079 // If we got a valid value try to use it.
2080 if (Bits != 0) {
2081 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2082 CmdArgs.push_back(
2083 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2084 CmdArgs.push_back(
2085 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2086 } else if (Val != "scalable") {
2087 // Handle the unsupported values passed to mrvv-vector-bits.
2088 D.Diag(diag::err_drv_unsupported_option_argument)
2089 << A->getSpelling() << Val;
2090 }
2091 }
2092}
2093
2094void Clang::AddSparcTargetArgs(const ArgList &Args,
2095 ArgStringList &CmdArgs) const {
2097 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2098
2099 if (FloatABI == sparc::FloatABI::Soft) {
2100 // Floating point operations and argument passing are soft.
2101 CmdArgs.push_back("-msoft-float");
2102 CmdArgs.push_back("-mfloat-abi");
2103 CmdArgs.push_back("soft");
2104 } else {
2105 // Floating point operations and argument passing are hard.
2106 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2107 CmdArgs.push_back("-mfloat-abi");
2108 CmdArgs.push_back("hard");
2109 }
2110
2111 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2112 StringRef Name = A->getValue();
2113 std::string TuneCPU;
2114 if (Name == "native")
2115 TuneCPU = std::string(llvm::sys::getHostCPUName());
2116 else
2117 TuneCPU = std::string(Name);
2118
2119 CmdArgs.push_back("-tune-cpu");
2120 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2121 }
2122}
2123
2124void Clang::AddSystemZTargetArgs(const ArgList &Args,
2125 ArgStringList &CmdArgs) const {
2126 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2127 CmdArgs.push_back("-tune-cpu");
2128 if (strcmp(A->getValue(), "native") == 0)
2129 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2130 else
2131 CmdArgs.push_back(A->getValue());
2132 }
2133
2134 bool HasBackchain =
2135 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2136 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2137 options::OPT_mno_packed_stack, false);
2139 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2140 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2141 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2142 const Driver &D = getToolChain().getDriver();
2143 D.Diag(diag::err_drv_unsupported_opt)
2144 << "-mpacked-stack -mbackchain -mhard-float";
2145 }
2146 if (HasBackchain)
2147 CmdArgs.push_back("-mbackchain");
2148 if (HasPackedStack)
2149 CmdArgs.push_back("-mpacked-stack");
2150 if (HasSoftFloat) {
2151 // Floating point operations and argument passing are soft.
2152 CmdArgs.push_back("-msoft-float");
2153 CmdArgs.push_back("-mfloat-abi");
2154 CmdArgs.push_back("soft");
2155 }
2156}
2157
2158void Clang::AddX86TargetArgs(const ArgList &Args,
2159 ArgStringList &CmdArgs) const {
2160 const Driver &D = getToolChain().getDriver();
2161 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2162
2163 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2164 Args.hasArg(options::OPT_mkernel) ||
2165 Args.hasArg(options::OPT_fapple_kext))
2166 CmdArgs.push_back("-disable-red-zone");
2167
2168 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2169 options::OPT_mno_tls_direct_seg_refs, true))
2170 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2171
2172 // Default to avoid implicit floating-point for kernel/kext code, but allow
2173 // that to be overridden with -mno-soft-float.
2174 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2175 Args.hasArg(options::OPT_fapple_kext));
2176 if (Arg *A = Args.getLastArg(
2177 options::OPT_msoft_float, options::OPT_mno_soft_float,
2178 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2179 const Option &O = A->getOption();
2180 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2181 O.matches(options::OPT_msoft_float));
2182 }
2183 if (NoImplicitFloat)
2184 CmdArgs.push_back("-no-implicit-float");
2185
2186 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2187 StringRef Value = A->getValue();
2188 if (Value == "intel" || Value == "att") {
2189 CmdArgs.push_back("-mllvm");
2190 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2191 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2192 } else {
2193 D.Diag(diag::err_drv_unsupported_option_argument)
2194 << A->getSpelling() << Value;
2195 }
2196 } else if (D.IsCLMode()) {
2197 CmdArgs.push_back("-mllvm");
2198 CmdArgs.push_back("-x86-asm-syntax=intel");
2199 }
2200
2201 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2202 options::OPT_mno_skip_rax_setup))
2203 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2204 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2205
2206 // Set flags to support MCU ABI.
2207 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2208 CmdArgs.push_back("-mfloat-abi");
2209 CmdArgs.push_back("soft");
2210 CmdArgs.push_back("-mstack-alignment=4");
2211 }
2212
2213 // Handle -mtune.
2214
2215 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2216 std::string TuneCPU;
2217 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2218 TuneCPU = "generic";
2219
2220 // Override based on -mtune.
2221 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2222 StringRef Name = A->getValue();
2223
2224 if (Name == "native") {
2225 Name = llvm::sys::getHostCPUName();
2226 if (!Name.empty())
2227 TuneCPU = std::string(Name);
2228 } else
2229 TuneCPU = std::string(Name);
2230 }
2231
2232 if (!TuneCPU.empty()) {
2233 CmdArgs.push_back("-tune-cpu");
2234 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2235 }
2236}
2237
2238void Clang::AddHexagonTargetArgs(const ArgList &Args,
2239 ArgStringList &CmdArgs) const {
2240 CmdArgs.push_back("-mqdsp6-compat");
2241 CmdArgs.push_back("-Wreturn-type");
2242
2244 CmdArgs.push_back("-mllvm");
2245 CmdArgs.push_back(
2246 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2247 }
2248
2249 if (!Args.hasArg(options::OPT_fno_short_enums))
2250 CmdArgs.push_back("-fshort-enums");
2251 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2252 CmdArgs.push_back("-mllvm");
2253 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2254 }
2255 CmdArgs.push_back("-mllvm");
2256 CmdArgs.push_back("-machine-sink-split=0");
2257}
2258
2259void Clang::AddLanaiTargetArgs(const ArgList &Args,
2260 ArgStringList &CmdArgs) const {
2261 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2262 StringRef CPUName = A->getValue();
2263
2264 CmdArgs.push_back("-target-cpu");
2265 CmdArgs.push_back(Args.MakeArgString(CPUName));
2266 }
2267 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2268 StringRef Value = A->getValue();
2269 // Only support mregparm=4 to support old usage. Report error for all other
2270 // cases.
2271 int Mregparm;
2272 if (Value.getAsInteger(10, Mregparm)) {
2273 if (Mregparm != 4) {
2275 diag::err_drv_unsupported_option_argument)
2276 << A->getSpelling() << Value;
2277 }
2278 }
2279 }
2280}
2281
2282void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2283 ArgStringList &CmdArgs) const {
2284 // Default to "hidden" visibility.
2285 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2286 options::OPT_fvisibility_ms_compat))
2287 CmdArgs.push_back("-fvisibility=hidden");
2288}
2289
2290void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2291 // Floating point operations and argument passing are hard.
2292 CmdArgs.push_back("-mfloat-abi");
2293 CmdArgs.push_back("hard");
2294}
2295
2296void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2297 StringRef Target, const InputInfo &Output,
2298 const InputInfo &Input, const ArgList &Args) const {
2299 // If this is a dry run, do not create the compilation database file.
2300 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2301 return;
2302
2303 using llvm::yaml::escape;
2304 const Driver &D = getToolChain().getDriver();
2305
2306 if (!CompilationDatabase) {
2307 std::error_code EC;
2308 auto File = std::make_unique<llvm::raw_fd_ostream>(
2309 Filename, EC,
2310 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2311 if (EC) {
2312 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2313 << EC.message();
2314 return;
2315 }
2316 CompilationDatabase = std::move(File);
2317 }
2318 auto &CDB = *CompilationDatabase;
2319 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2320 if (!CWD)
2321 CWD = ".";
2322 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2323 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2324 if (Output.isFilename())
2325 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2326 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2327 SmallString<128> Buf;
2328 Buf = "-x";
2329 Buf += types::getTypeName(Input.getType());
2330 CDB << ", \"" << escape(Buf) << "\"";
2331 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2332 Buf = "--sysroot=";
2333 Buf += D.SysRoot;
2334 CDB << ", \"" << escape(Buf) << "\"";
2335 }
2336 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2337 if (Output.isFilename())
2338 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2339 for (auto &A: Args) {
2340 auto &O = A->getOption();
2341 // Skip language selection, which is positional.
2342 if (O.getID() == options::OPT_x)
2343 continue;
2344 // Skip writing dependency output and the compilation database itself.
2345 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2346 continue;
2347 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2348 continue;
2349 // Skip inputs.
2350 if (O.getKind() == Option::InputClass)
2351 continue;
2352 // Skip output.
2353 if (O.getID() == options::OPT_o)
2354 continue;
2355 // All other arguments are quoted and appended.
2356 ArgStringList ASL;
2357 A->render(Args, ASL);
2358 for (auto &it: ASL)
2359 CDB << ", \"" << escape(it) << "\"";
2360 }
2361 Buf = "--target=";
2362 Buf += Target;
2363 CDB << ", \"" << escape(Buf) << "\"]},\n";
2364}
2365
2366void Clang::DumpCompilationDatabaseFragmentToDir(
2367 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2368 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2369 // If this is a dry run, do not create the compilation database file.
2370 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2371 return;
2372
2373 if (CompilationDatabase)
2374 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2375
2376 SmallString<256> Path = Dir;
2377 const auto &Driver = C.getDriver();
2378 Driver.getVFS().makeAbsolute(Path);
2379 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2380 if (Err) {
2381 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2382 return;
2383 }
2384
2385 llvm::sys::path::append(
2386 Path,
2387 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2388 int FD;
2389 SmallString<256> TempPath;
2390 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2391 llvm::sys::fs::OF_Text);
2392 if (Err) {
2393 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2394 return;
2395 }
2396 CompilationDatabase =
2397 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2398 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2399}
2400
2401static bool CheckARMImplicitITArg(StringRef Value) {
2402 return Value == "always" || Value == "never" || Value == "arm" ||
2403 Value == "thumb";
2404}
2405
2406static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2407 StringRef Value) {
2408 CmdArgs.push_back("-mllvm");
2409 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2410}
2411
2413 const ArgList &Args,
2414 ArgStringList &CmdArgs,
2415 const Driver &D) {
2416 // Default to -mno-relax-all.
2417 //
2418 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2419 // cannot be done by assembler branch relaxation as it needs a free temporary
2420 // register. Because of this, branch relaxation is handled by a MachineIR pass
2421 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2422 // MachineIR branch relaxation inaccurate and it will miss cases where an
2423 // indirect branch is necessary.
2424 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2425 options::OPT_mno_relax_all);
2426
2427 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2428 options::OPT_mno_incremental_linker_compatible);
2429
2430 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2431
2432 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2433 options::OPT_fno_emit_compact_unwind_non_canonical);
2434
2435 // If you add more args here, also add them to the block below that
2436 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2437
2438 // When passing -I arguments to the assembler we sometimes need to
2439 // unconditionally take the next argument. For example, when parsing
2440 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2441 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2442 // arg after parsing the '-I' arg.
2443 bool TakeNextArg = false;
2444
2445 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2446 bool IsELF = Triple.isOSBinFormatELF();
2447 bool Crel = false, ExperimentalCrel = false;
2448 StringRef RelocSectionSym;
2449 bool SFrame = false, ExperimentalSFrame = false;
2450 bool ImplicitMapSyms = false;
2451 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2452 bool UseNoExecStack = false;
2453 bool Msa = false;
2454 const char *MipsTargetFeature = nullptr;
2455 llvm::SmallVector<const char *> SparcTargetFeatures;
2456 StringRef ImplicitIt;
2457 for (const Arg *A :
2458 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2459 options::OPT_mimplicit_it_EQ)) {
2460 A->claim();
2461
2462 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2463 switch (C.getDefaultToolChain().getArch()) {
2464 case llvm::Triple::arm:
2465 case llvm::Triple::armeb:
2466 case llvm::Triple::thumb:
2467 case llvm::Triple::thumbeb:
2468 // Only store the value; the last value set takes effect.
2469 ImplicitIt = A->getValue();
2470 if (!CheckARMImplicitITArg(ImplicitIt))
2471 D.Diag(diag::err_drv_unsupported_option_argument)
2472 << A->getSpelling() << ImplicitIt;
2473 continue;
2474 default:
2475 break;
2476 }
2477 }
2478
2479 for (StringRef Value : A->getValues()) {
2480 if (TakeNextArg) {
2481 CmdArgs.push_back(Value.data());
2482 TakeNextArg = false;
2483 continue;
2484 }
2485
2486 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2487 Value == "-mbig-obj")
2488 continue; // LLVM handles bigobj automatically
2489
2490 auto Equal = Value.split('=');
2491 auto checkArg = [&](bool ValidTarget,
2492 std::initializer_list<const char *> Set) {
2493 if (!ValidTarget) {
2494 D.Diag(diag::err_drv_unsupported_opt_for_target)
2495 << (Twine("-Wa,") + Equal.first + "=").str()
2496 << Triple.getTriple();
2497 } else if (!llvm::is_contained(Set, Equal.second)) {
2498 D.Diag(diag::err_drv_unsupported_option_argument)
2499 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2500 }
2501 };
2502 switch (C.getDefaultToolChain().getArch()) {
2503 default:
2504 break;
2505 case llvm::Triple::x86:
2506 case llvm::Triple::x86_64:
2507 if (Equal.first == "-mrelax-relocations" ||
2508 Equal.first == "--mrelax-relocations") {
2509 UseRelaxRelocations = Equal.second == "yes";
2510 checkArg(IsELF, {"yes", "no"});
2511 continue;
2512 }
2513 if (Value == "-msse2avx") {
2514 CmdArgs.push_back("-msse2avx");
2515 continue;
2516 }
2517 break;
2518 case llvm::Triple::wasm32:
2519 case llvm::Triple::wasm64:
2520 if (Value == "--no-type-check") {
2521 CmdArgs.push_back("-mno-type-check");
2522 continue;
2523 }
2524 break;
2525 case llvm::Triple::thumb:
2526 case llvm::Triple::thumbeb:
2527 case llvm::Triple::arm:
2528 case llvm::Triple::armeb:
2529 if (Equal.first == "-mimplicit-it") {
2530 // Only store the value; the last value set takes effect.
2531 ImplicitIt = Equal.second;
2532 checkArg(true, {"always", "never", "arm", "thumb"});
2533 continue;
2534 }
2535 if (Value == "-mthumb")
2536 // -mthumb has already been processed in ComputeLLVMTriple()
2537 // recognize but skip over here.
2538 continue;
2539 break;
2540 case llvm::Triple::aarch64:
2541 case llvm::Triple::aarch64_be:
2542 case llvm::Triple::aarch64_32:
2543 if (Equal.first == "-mmapsyms") {
2544 ImplicitMapSyms = Equal.second == "implicit";
2545 checkArg(IsELF, {"default", "implicit"});
2546 continue;
2547 }
2548 break;
2549 case llvm::Triple::mips:
2550 case llvm::Triple::mipsel:
2551 case llvm::Triple::mips64:
2552 case llvm::Triple::mips64el:
2553 if (Value == "--trap") {
2554 CmdArgs.push_back("-target-feature");
2555 CmdArgs.push_back("+use-tcc-in-div");
2556 continue;
2557 }
2558 if (Value == "--break") {
2559 CmdArgs.push_back("-target-feature");
2560 CmdArgs.push_back("-use-tcc-in-div");
2561 continue;
2562 }
2563 if (Value.starts_with("-msoft-float")) {
2564 CmdArgs.push_back("-target-feature");
2565 CmdArgs.push_back("+soft-float");
2566 continue;
2567 }
2568 if (Value.starts_with("-mhard-float")) {
2569 CmdArgs.push_back("-target-feature");
2570 CmdArgs.push_back("-soft-float");
2571 continue;
2572 }
2573 if (Value == "-mmsa") {
2574 Msa = true;
2575 continue;
2576 }
2577 if (Value == "-mno-msa") {
2578 Msa = false;
2579 continue;
2580 }
2581 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2582 .Case("-mips1", "+mips1")
2583 .Case("-mips2", "+mips2")
2584 .Case("-mips3", "+mips3")
2585 .Case("-mips4", "+mips4")
2586 .Case("-mips5", "+mips5")
2587 .Case("-mips32", "+mips32")
2588 .Case("-mips32r2", "+mips32r2")
2589 .Case("-mips32r3", "+mips32r3")
2590 .Case("-mips32r5", "+mips32r5")
2591 .Case("-mips32r6", "+mips32r6")
2592 .Case("-mips64", "+mips64")
2593 .Case("-mips64r2", "+mips64r2")
2594 .Case("-mips64r3", "+mips64r3")
2595 .Case("-mips64r5", "+mips64r5")
2596 .Case("-mips64r6", "+mips64r6")
2597 .Default(nullptr);
2598 if (MipsTargetFeature)
2599 continue;
2600 break;
2601
2602 case llvm::Triple::sparc:
2603 case llvm::Triple::sparcel:
2604 case llvm::Triple::sparcv9:
2605 if (Value == "--undeclared-regs") {
2606 // LLVM already allows undeclared use of G registers, so this option
2607 // becomes a no-op. This solely exists for GNU compatibility.
2608 // TODO implement --no-undeclared-regs
2609 continue;
2610 }
2611 SparcTargetFeatures =
2612 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2613 .Case("-Av8", {"-v8plus"})
2614 .Case("-Av8plus", {"+v8plus", "+v9"})
2615 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2616 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2617 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2618 .Case("-Av9", {"+v9"})
2619 .Case("-Av9a", {"+v9", "+vis"})
2620 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2621 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2622 .Default({});
2623 if (!SparcTargetFeatures.empty())
2624 continue;
2625 break;
2626 }
2627
2628 if (Value == "-force_cpusubtype_ALL") {
2629 // Do nothing, this is the default and we don't support anything else.
2630 } else if (Value == "-L") {
2631 CmdArgs.push_back("-msave-temp-labels");
2632 } else if (Value == "--fatal-warnings") {
2633 CmdArgs.push_back("-massembler-fatal-warnings");
2634 } else if (Value == "--no-warn" || Value == "-W") {
2635 CmdArgs.push_back("-massembler-no-warn");
2636 } else if (Value == "--noexecstack") {
2637 UseNoExecStack = true;
2638 } else if (Value.starts_with("-compress-debug-sections") ||
2639 Value.starts_with("--compress-debug-sections") ||
2640 Value == "-nocompress-debug-sections" ||
2641 Value == "--nocompress-debug-sections") {
2642 CmdArgs.push_back(Value.data());
2643 } else if (Value == "--crel") {
2644 Crel = true;
2645 } else if (Value == "--no-crel") {
2646 Crel = false;
2647 } else if (Value == "--allow-experimental-crel") {
2648 ExperimentalCrel = true;
2649 } else if (Value.starts_with("--reloc-section-sym=")) {
2650 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2651 } else if (Value.starts_with("-I")) {
2652 CmdArgs.push_back(Value.data());
2653 // We need to consume the next argument if the current arg is a plain
2654 // -I. The next arg will be the include directory.
2655 if (Value == "-I")
2656 TakeNextArg = true;
2657 } else if (Value.starts_with("-gdwarf-")) {
2658 // "-gdwarf-N" options are not cc1as options.
2659 unsigned DwarfVersion = DwarfVersionNum(Value);
2660 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2661 CmdArgs.push_back(Value.data());
2662 } else {
2663 RenderDebugEnablingArgs(Args, CmdArgs,
2664 llvm::codegenoptions::DebugInfoConstructor,
2665 DwarfVersion, llvm::DebuggerKind::Default);
2666 }
2667 } else if (Value == "--gsframe") {
2668 SFrame = true;
2669 } else if (Value == "--allow-experimental-sframe") {
2670 ExperimentalSFrame = true;
2671 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2672 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2673 // Do nothing, we'll validate it later.
2674 } else if (Value == "-defsym" || Value == "--defsym") {
2675 if (A->getNumValues() != 2) {
2676 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2677 break;
2678 }
2679 const char *S = A->getValue(1);
2680 auto Pair = StringRef(S).split('=');
2681 auto Sym = Pair.first;
2682 auto SVal = Pair.second;
2683
2684 if (Sym.empty() || SVal.empty()) {
2685 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2686 break;
2687 }
2688 int64_t IVal;
2689 if (SVal.getAsInteger(0, IVal)) {
2690 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2691 break;
2692 }
2693 CmdArgs.push_back("--defsym");
2694 TakeNextArg = true;
2695 } else if (Value == "-fdebug-compilation-dir") {
2696 CmdArgs.push_back("-fdebug-compilation-dir");
2697 TakeNextArg = true;
2698 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2699 // The flag is a -Wa / -Xassembler argument and Options doesn't
2700 // parse the argument, so this isn't automatically aliased to
2701 // -fdebug-compilation-dir (without '=') here.
2702 CmdArgs.push_back("-fdebug-compilation-dir");
2703 CmdArgs.push_back(Value.data());
2704 } else if (Value == "--version") {
2705 D.PrintVersion(C, llvm::outs());
2706 } else {
2707 D.Diag(diag::err_drv_unsupported_option_argument)
2708 << A->getSpelling() << Value;
2709 }
2710 }
2711 }
2712 if (ImplicitIt.size())
2713 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2714 if (Crel) {
2715 if (!ExperimentalCrel)
2716 D.Diag(diag::err_drv_experimental_crel);
2717 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2718 CmdArgs.push_back("--crel");
2719 } else {
2720 D.Diag(diag::err_drv_unsupported_opt_for_target)
2721 << "-Wa,--crel" << D.getTargetTriple();
2722 }
2723 }
2724 if (!RelocSectionSym.empty()) {
2725 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2726 RelocSectionSym != "none")
2727 D.Diag(diag::err_drv_invalid_value)
2728 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2729 << RelocSectionSym;
2730 else if (Triple.isOSBinFormatELF())
2731 CmdArgs.push_back(
2732 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2733 else
2734 D.Diag(diag::err_drv_unsupported_opt_for_target)
2735 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2736 }
2737 if (SFrame) {
2738 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2739 if (!ExperimentalSFrame)
2740 D.Diag(diag::err_drv_experimental_sframe);
2741 else
2742 CmdArgs.push_back("--gsframe");
2743 } else {
2744 D.Diag(diag::err_drv_unsupported_opt_for_target)
2745 << "-Wa,--gsframe" << D.getTargetTriple();
2746 }
2747 }
2748 if (ImplicitMapSyms)
2749 CmdArgs.push_back("-mmapsyms=implicit");
2750 if (Msa)
2751 CmdArgs.push_back("-mmsa");
2752 if (!UseRelaxRelocations)
2753 CmdArgs.push_back("-mrelax-relocations=no");
2754 if (UseNoExecStack)
2755 CmdArgs.push_back("-mnoexecstack");
2756 if (MipsTargetFeature != nullptr) {
2757 CmdArgs.push_back("-target-feature");
2758 CmdArgs.push_back(MipsTargetFeature);
2759 }
2760
2761 for (const char *Feature : SparcTargetFeatures) {
2762 CmdArgs.push_back("-target-feature");
2763 CmdArgs.push_back(Feature);
2764 }
2765
2766 // forward -fembed-bitcode to assmebler
2767 if (C.getDriver().embedBitcodeEnabled() ||
2768 C.getDriver().embedBitcodeMarkerOnly())
2769 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2770
2771 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2772 CmdArgs.push_back("-as-secure-log-file");
2773 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2774 }
2775}
2776
2777static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2778 bool OFastEnabled, const ArgList &Args,
2779 ArgStringList &CmdArgs,
2780 const JobAction &JA) {
2781 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2782 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2783 llvm::StringLiteral("SLEEF")};
2784 bool NoMathErrnoWasImpliedByVecLib = false;
2785 const Arg *VecLibArg = nullptr;
2786 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2787 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2788
2789 // Handle various floating point optimization flags, mapping them to the
2790 // appropriate LLVM code generation flags. This is complicated by several
2791 // "umbrella" flags, so we do this by stepping through the flags incrementally
2792 // adjusting what we think is enabled/disabled, then at the end setting the
2793 // LLVM flags based on the final state.
2794 bool HonorINFs = true;
2795 bool HonorNaNs = true;
2796 bool ApproxFunc = false;
2797 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2798 bool MathErrno = TC.IsMathErrnoDefault();
2799 bool AssociativeMath = false;
2800 bool ReciprocalMath = false;
2801 bool SignedZeros = true;
2802 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2803 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2804 // overriden by ffp-exception-behavior?
2805 bool RoundingFPMath = false;
2806 // -ffp-model values: strict, fast, precise
2807 StringRef FPModel = "";
2808 // -ffp-exception-behavior options: strict, maytrap, ignore
2809 StringRef FPExceptionBehavior = "";
2810 // -ffp-eval-method options: double, extended, source
2811 StringRef FPEvalMethod = "";
2812 llvm::DenormalMode DenormalFPMath =
2813 TC.getDefaultDenormalModeForType(Args, JA);
2814 llvm::DenormalMode DenormalFP32Math =
2815 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2816
2817 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2818 // If one wasn't given by the user, don't pass it here.
2819 StringRef FPContract;
2820 StringRef LastSeenFfpContractOption;
2821 StringRef LastFpContractOverrideOption;
2822 bool SeenUnsafeMathModeOption = false;
2825 FPContract = "on";
2826 bool StrictFPModel = false;
2827 StringRef Float16ExcessPrecision = "";
2828 StringRef BFloat16ExcessPrecision = "";
2830 std::string ComplexRangeStr;
2831 StringRef LastComplexRangeOption;
2832
2833 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2834 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2835 if (Aggressive) {
2836 HonorINFs = false;
2837 HonorNaNs = false;
2839 LastComplexRangeOption, Range);
2840 } else {
2841 HonorINFs = true;
2842 HonorNaNs = true;
2843 setComplexRange(D, CallerOption,
2845 LastComplexRangeOption, Range);
2846 }
2847 MathErrno = false;
2848 AssociativeMath = true;
2849 ReciprocalMath = true;
2850 ApproxFunc = true;
2851 SignedZeros = false;
2852 TrappingMath = false;
2853 RoundingFPMath = false;
2854 FPExceptionBehavior = "";
2855 FPContract = "fast";
2856 SeenUnsafeMathModeOption = true;
2857 };
2858
2859 // Lambda to consolidate common handling for fp-contract
2860 auto restoreFPContractState = [&]() {
2861 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2862 // For other targets, if the state has been changed by one of the
2863 // unsafe-math umbrella options a subsequent -fno-fast-math or
2864 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2865 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2866 // option. If we have not seen an unsafe-math option or -ffp-contract,
2867 // we leave the FPContract state unchanged.
2870 if (LastSeenFfpContractOption != "")
2871 FPContract = LastSeenFfpContractOption;
2872 else if (SeenUnsafeMathModeOption)
2873 FPContract = "on";
2874 }
2875 // In this case, we're reverting to the last explicit fp-contract option
2876 // or the platform default
2877 LastFpContractOverrideOption = "";
2878 };
2879
2880 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2881 CmdArgs.push_back("-mlimit-float-precision");
2882 CmdArgs.push_back(A->getValue());
2883 }
2884
2885 for (const Arg *A : Args) {
2886 llvm::scope_exit CheckMathErrnoForVecLib(
2887 [&, MathErrnoBeforeArg = MathErrno] {
2888 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
2889 ArgThatEnabledMathErrnoAfterVecLib = A;
2890 });
2891
2892 switch (A->getOption().getID()) {
2893 // If this isn't an FP option skip the claim below
2894 default: continue;
2895
2896 case options::OPT_fcx_limited_range:
2897 setComplexRange(D, A->getSpelling(),
2899 LastComplexRangeOption, Range);
2900 break;
2901 case options::OPT_fno_cx_limited_range:
2902 setComplexRange(D, A->getSpelling(),
2904 LastComplexRangeOption, Range);
2905 break;
2906 case options::OPT_fcx_fortran_rules:
2907 setComplexRange(D, A->getSpelling(),
2909 LastComplexRangeOption, Range);
2910 break;
2911 case options::OPT_fno_cx_fortran_rules:
2912 setComplexRange(D, A->getSpelling(),
2914 LastComplexRangeOption, Range);
2915 break;
2916 case options::OPT_fcomplex_arithmetic_EQ: {
2918 StringRef Val = A->getValue();
2919 if (Val == "full")
2921 else if (Val == "improved")
2923 else if (Val == "promoted")
2925 else if (Val == "basic")
2927 else {
2928 D.Diag(diag::err_drv_unsupported_option_argument)
2929 << A->getSpelling() << Val;
2930 break;
2931 }
2932 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
2933 LastComplexRangeOption, Range);
2934 break;
2935 }
2936 case options::OPT_ffp_model_EQ: {
2937 // If -ffp-model= is seen, reset to fno-fast-math
2938 HonorINFs = true;
2939 HonorNaNs = true;
2940 ApproxFunc = false;
2941 // Turning *off* -ffast-math restores the toolchain default.
2942 MathErrno = TC.IsMathErrnoDefault();
2943 AssociativeMath = false;
2944 ReciprocalMath = false;
2945 SignedZeros = true;
2946
2947 StringRef Val = A->getValue();
2948 if (OFastEnabled && Val != "aggressive") {
2949 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
2950 D.Diag(clang::diag::warn_drv_overriding_option)
2951 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2952 break;
2953 }
2954 StrictFPModel = false;
2955 if (!FPModel.empty() && FPModel != Val)
2956 D.Diag(clang::diag::warn_drv_overriding_option)
2957 << Args.MakeArgString("-ffp-model=" + FPModel)
2958 << Args.MakeArgString("-ffp-model=" + Val);
2959 if (Val == "fast") {
2960 FPModel = Val;
2961 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
2962 // applyFastMath sets fp-contract="fast"
2963 LastFpContractOverrideOption = "-ffp-model=fast";
2964 } else if (Val == "aggressive") {
2965 FPModel = Val;
2966 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
2967 // applyFastMath sets fp-contract="fast"
2968 LastFpContractOverrideOption = "-ffp-model=aggressive";
2969 } else if (Val == "precise") {
2970 FPModel = Val;
2971 FPContract = "on";
2972 LastFpContractOverrideOption = "-ffp-model=precise";
2973 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
2975 LastComplexRangeOption, Range);
2976 } else if (Val == "strict") {
2977 StrictFPModel = true;
2978 FPExceptionBehavior = "strict";
2979 FPModel = Val;
2980 FPContract = "off";
2981 LastFpContractOverrideOption = "-ffp-model=strict";
2982 TrappingMath = true;
2983 RoundingFPMath = true;
2984 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
2986 LastComplexRangeOption, Range);
2987 } else
2988 D.Diag(diag::err_drv_unsupported_option_argument)
2989 << A->getSpelling() << Val;
2990 break;
2991 }
2992
2993 // Options controlling individual features
2994 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2995 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2996 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2997 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2998 case options::OPT_fapprox_func: ApproxFunc = true; break;
2999 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3000 case options::OPT_fmath_errno: MathErrno = true; break;
3001 case options::OPT_fno_math_errno: MathErrno = false; break;
3002 case options::OPT_fassociative_math: AssociativeMath = true; break;
3003 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3004 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3005 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3006 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3007 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3008 case options::OPT_ftrapping_math:
3009 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3010 FPExceptionBehavior != "strict")
3011 // Warn that previous value of option is overridden.
3012 D.Diag(clang::diag::warn_drv_overriding_option)
3013 << Args.MakeArgString("-ffp-exception-behavior=" +
3014 FPExceptionBehavior)
3015 << "-ftrapping-math";
3016 TrappingMath = true;
3017 TrappingMathPresent = true;
3018 FPExceptionBehavior = "strict";
3019 break;
3020 case options::OPT_fveclib:
3021 VecLibArg = A;
3022 NoMathErrnoWasImpliedByVecLib =
3023 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3024 if (NoMathErrnoWasImpliedByVecLib)
3025 MathErrno = false;
3026 break;
3027 case options::OPT_fno_trapping_math:
3028 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3029 FPExceptionBehavior != "ignore")
3030 // Warn that previous value of option is overridden.
3031 D.Diag(clang::diag::warn_drv_overriding_option)
3032 << Args.MakeArgString("-ffp-exception-behavior=" +
3033 FPExceptionBehavior)
3034 << "-fno-trapping-math";
3035 TrappingMath = false;
3036 TrappingMathPresent = true;
3037 FPExceptionBehavior = "ignore";
3038 break;
3039
3040 case options::OPT_frounding_math:
3041 RoundingFPMath = true;
3042 break;
3043
3044 case options::OPT_fno_rounding_math:
3045 RoundingFPMath = false;
3046 break;
3047
3048 case options::OPT_fdenormal_fp_math_EQ:
3049 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3050 DenormalFP32Math = DenormalFPMath;
3051 if (!DenormalFPMath.isValid()) {
3052 D.Diag(diag::err_drv_invalid_value)
3053 << A->getAsString(Args) << A->getValue();
3054 }
3055 break;
3056
3057 case options::OPT_fdenormal_fp_math_f32_EQ:
3058 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3059 if (!DenormalFP32Math.isValid()) {
3060 D.Diag(diag::err_drv_invalid_value)
3061 << A->getAsString(Args) << A->getValue();
3062 }
3063 break;
3064
3065 // Validate and pass through -ffp-contract option.
3066 case options::OPT_ffp_contract: {
3067 StringRef Val = A->getValue();
3068 if (Val == "fast" || Val == "on" || Val == "off" ||
3069 Val == "fast-honor-pragmas") {
3070 if (Val != FPContract && LastFpContractOverrideOption != "") {
3071 D.Diag(clang::diag::warn_drv_overriding_option)
3072 << LastFpContractOverrideOption
3073 << Args.MakeArgString("-ffp-contract=" + Val);
3074 }
3075
3076 FPContract = Val;
3077 LastSeenFfpContractOption = Val;
3078 LastFpContractOverrideOption = "";
3079 } else
3080 D.Diag(diag::err_drv_unsupported_option_argument)
3081 << A->getSpelling() << Val;
3082 break;
3083 }
3084
3085 // Validate and pass through -ffp-exception-behavior option.
3086 case options::OPT_ffp_exception_behavior_EQ: {
3087 StringRef Val = A->getValue();
3088 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3089 FPExceptionBehavior != Val)
3090 // Warn that previous value of option is overridden.
3091 D.Diag(clang::diag::warn_drv_overriding_option)
3092 << Args.MakeArgString("-ffp-exception-behavior=" +
3093 FPExceptionBehavior)
3094 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3095 TrappingMath = TrappingMathPresent = false;
3096 if (Val == "ignore" || Val == "maytrap")
3097 FPExceptionBehavior = Val;
3098 else if (Val == "strict") {
3099 FPExceptionBehavior = Val;
3100 TrappingMath = TrappingMathPresent = true;
3101 } else
3102 D.Diag(diag::err_drv_unsupported_option_argument)
3103 << A->getSpelling() << Val;
3104 break;
3105 }
3106
3107 // Validate and pass through -ffp-eval-method option.
3108 case options::OPT_ffp_eval_method_EQ: {
3109 StringRef Val = A->getValue();
3110 if (Val == "double" || Val == "extended" || Val == "source")
3111 FPEvalMethod = Val;
3112 else
3113 D.Diag(diag::err_drv_unsupported_option_argument)
3114 << A->getSpelling() << Val;
3115 break;
3116 }
3117
3118 case options::OPT_fexcess_precision_EQ: {
3119 StringRef Val = A->getValue();
3120 const llvm::Triple::ArchType Arch = TC.getArch();
3121 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3122 if (Val == "standard" || Val == "fast")
3123 Float16ExcessPrecision = Val;
3124 // To make it GCC compatible, allow the value of "16" which
3125 // means disable excess precision, the same meaning than clang's
3126 // equivalent value "none".
3127 else if (Val == "16")
3128 Float16ExcessPrecision = "none";
3129 else
3130 D.Diag(diag::err_drv_unsupported_option_argument)
3131 << A->getSpelling() << Val;
3132 } else {
3133 if (!(Val == "standard" || Val == "fast"))
3134 D.Diag(diag::err_drv_unsupported_option_argument)
3135 << A->getSpelling() << Val;
3136 }
3137 BFloat16ExcessPrecision = Float16ExcessPrecision;
3138 break;
3139 }
3140 case options::OPT_ffinite_math_only:
3141 HonorINFs = false;
3142 HonorNaNs = false;
3143 break;
3144 case options::OPT_fno_finite_math_only:
3145 HonorINFs = true;
3146 HonorNaNs = true;
3147 break;
3148
3149 case options::OPT_funsafe_math_optimizations:
3150 AssociativeMath = true;
3151 ReciprocalMath = true;
3152 SignedZeros = false;
3153 ApproxFunc = true;
3154 TrappingMath = false;
3155 FPExceptionBehavior = "";
3156 FPContract = "fast";
3157 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3158 SeenUnsafeMathModeOption = true;
3159 break;
3160 case options::OPT_fno_unsafe_math_optimizations:
3161 AssociativeMath = false;
3162 ReciprocalMath = false;
3163 SignedZeros = true;
3164 ApproxFunc = false;
3165 restoreFPContractState();
3166 break;
3167
3168 case options::OPT_Ofast:
3169 // If -Ofast is the optimization level, then -ffast-math should be enabled
3170 if (!OFastEnabled)
3171 continue;
3172 [[fallthrough]];
3173 case options::OPT_ffast_math:
3174 applyFastMath(true, A->getSpelling());
3175 if (A->getOption().getID() == options::OPT_Ofast)
3176 LastFpContractOverrideOption = "-Ofast";
3177 else
3178 LastFpContractOverrideOption = "-ffast-math";
3179 break;
3180 case options::OPT_fno_fast_math:
3181 HonorINFs = true;
3182 HonorNaNs = true;
3183 // Turning on -ffast-math (with either flag) removes the need for
3184 // MathErrno. However, turning *off* -ffast-math merely restores the
3185 // toolchain default (which may be false).
3186 MathErrno = TC.IsMathErrnoDefault();
3187 AssociativeMath = false;
3188 ReciprocalMath = false;
3189 ApproxFunc = false;
3190 SignedZeros = true;
3191 restoreFPContractState();
3193 setComplexRange(D, A->getSpelling(),
3195 LastComplexRangeOption, Range);
3196 else
3198 LastComplexRangeOption = "";
3199 LastFpContractOverrideOption = "";
3200 break;
3201 } // End switch (A->getOption().getID())
3202
3203 // The StrictFPModel local variable is needed to report warnings
3204 // in the way we intend. If -ffp-model=strict has been used, we
3205 // want to report a warning for the next option encountered that
3206 // takes us out of the settings described by fp-model=strict, but
3207 // we don't want to continue issuing warnings for other conflicting
3208 // options after that.
3209 if (StrictFPModel) {
3210 // If -ffp-model=strict has been specified on command line but
3211 // subsequent options conflict then emit warning diagnostic.
3212 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3213 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3214 FPContract == "off")
3215 // OK: Current Arg doesn't conflict with -ffp-model=strict
3216 ;
3217 else {
3218 StrictFPModel = false;
3219 FPModel = "";
3220 // The warning for -ffp-contract would have been reported by the
3221 // OPT_ffp_contract_EQ handler above. A special check here is needed
3222 // to avoid duplicating the warning.
3223 auto RHS = (A->getNumValues() == 0)
3224 ? A->getSpelling()
3225 : Args.MakeArgString(A->getSpelling() + A->getValue());
3226 if (A->getSpelling() != "-ffp-contract=") {
3227 if (RHS != "-ffp-model=strict")
3228 D.Diag(clang::diag::warn_drv_overriding_option)
3229 << "-ffp-model=strict" << RHS;
3230 }
3231 }
3232 }
3233
3234 // If we handled this option claim it
3235 A->claim();
3236 }
3237
3238 if (!HonorINFs)
3239 CmdArgs.push_back("-menable-no-infs");
3240
3241 if (!HonorNaNs)
3242 CmdArgs.push_back("-menable-no-nans");
3243
3244 if (ApproxFunc)
3245 CmdArgs.push_back("-fapprox-func");
3246
3247 if (MathErrno) {
3248 CmdArgs.push_back("-fmath-errno");
3249 if (NoMathErrnoWasImpliedByVecLib)
3250 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3251 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3252 << VecLibArg->getAsString(Args);
3253 }
3254
3255 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3256 !TrappingMath)
3257 CmdArgs.push_back("-funsafe-math-optimizations");
3258
3259 if (!SignedZeros)
3260 CmdArgs.push_back("-fno-signed-zeros");
3261
3262 if (AssociativeMath && !SignedZeros && !TrappingMath)
3263 CmdArgs.push_back("-mreassociate");
3264
3265 if (ReciprocalMath)
3266 CmdArgs.push_back("-freciprocal-math");
3267
3268 if (TrappingMath) {
3269 // FP Exception Behavior is also set to strict
3270 assert(FPExceptionBehavior == "strict");
3271 }
3272
3273 // The default is IEEE.
3274 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3275 llvm::SmallString<64> DenormFlag;
3276 llvm::raw_svector_ostream ArgStr(DenormFlag);
3277 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3278 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3279 }
3280
3281 // Add f32 specific denormal mode flag if it's different.
3282 if (DenormalFP32Math != DenormalFPMath) {
3283 llvm::SmallString<64> DenormFlag;
3284 llvm::raw_svector_ostream ArgStr(DenormFlag);
3285 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3286 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3287 }
3288
3289 if (!FPContract.empty())
3290 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3291
3292 if (RoundingFPMath)
3293 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3294 else
3295 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3296
3297 if (!FPExceptionBehavior.empty())
3298 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3299 FPExceptionBehavior));
3300
3301 if (!FPEvalMethod.empty())
3302 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3303
3304 if (!Float16ExcessPrecision.empty())
3305 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3306 Float16ExcessPrecision));
3307 if (!BFloat16ExcessPrecision.empty())
3308 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3309 BFloat16ExcessPrecision));
3310
3311 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3312 if (!Recip.empty())
3313 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3314
3315 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3316 // individual features enabled by -ffast-math instead of the option itself as
3317 // that's consistent with gcc's behaviour.
3318 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3319 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3320 CmdArgs.push_back("-ffast-math");
3321
3322 // Handle __FINITE_MATH_ONLY__ similarly.
3323 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3324 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3325 // -menable-no-nans are set by the user.
3326 bool shouldAddFiniteMathOnly = false;
3327 if (!HonorINFs && !HonorNaNs) {
3328 shouldAddFiniteMathOnly = true;
3329 } else {
3330 bool InfValues = true;
3331 bool NanValues = true;
3332 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3333 StringRef ArgValue = Arg->getValue();
3334 if (ArgValue == "-menable-no-nans")
3335 NanValues = false;
3336 else if (ArgValue == "-menable-no-infs")
3337 InfValues = false;
3338 }
3339 if (!NanValues && !InfValues)
3340 shouldAddFiniteMathOnly = true;
3341 }
3342 if (shouldAddFiniteMathOnly) {
3343 CmdArgs.push_back("-ffinite-math-only");
3344 }
3345 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3346 CmdArgs.push_back("-mfpmath");
3347 CmdArgs.push_back(A->getValue());
3348 }
3349
3350 // Disable a codegen optimization for floating-point casts.
3351 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3352 options::OPT_fstrict_float_cast_overflow, false))
3353 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3354
3356 ComplexRangeStr = renderComplexRangeOption(Range);
3357 if (!ComplexRangeStr.empty()) {
3358 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3359 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3360 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3361 complexRangeKindToStr(Range)));
3362 }
3363 if (Args.hasArg(options::OPT_fcx_limited_range))
3364 CmdArgs.push_back("-fcx-limited-range");
3365 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3366 CmdArgs.push_back("-fcx-fortran-rules");
3367 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3368 CmdArgs.push_back("-fno-cx-limited-range");
3369 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3370 CmdArgs.push_back("-fno-cx-fortran-rules");
3371}
3372
3373static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3374 const llvm::Triple &Triple,
3375 const InputInfo &Input) {
3376 // Add default argument set.
3377 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3378 CmdArgs.push_back("-analyzer-checker=core");
3379 CmdArgs.push_back("-analyzer-checker=apiModeling");
3380
3381 if (!Triple.isWindowsMSVCEnvironment()) {
3382 CmdArgs.push_back("-analyzer-checker=unix");
3383 } else {
3384 // Enable "unix" checkers that also work on Windows.
3385 CmdArgs.push_back("-analyzer-checker=unix.API");
3386 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3387 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3388 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3389 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3390 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3391 }
3392
3393 // Disable some unix checkers for PS4/PS5.
3394 if (Triple.isPS()) {
3395 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3396 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3397 }
3398
3399 if (Triple.isOSDarwin()) {
3400 CmdArgs.push_back("-analyzer-checker=osx");
3401 CmdArgs.push_back(
3402 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3403 }
3404 else if (Triple.isOSFuchsia())
3405 CmdArgs.push_back("-analyzer-checker=fuchsia");
3406
3407 CmdArgs.push_back("-analyzer-checker=deadcode");
3408
3409 if (types::isCXX(Input.getType()))
3410 CmdArgs.push_back("-analyzer-checker=cplusplus");
3411
3412 if (!Triple.isPS()) {
3413 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3414 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3415 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3416 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3417 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3418 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3419 }
3420
3421 // Default nullability checks.
3422 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3423 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3424 }
3425
3426 // Set the output format. The default is plist, for (lame) historical reasons.
3427 CmdArgs.push_back("-analyzer-output");
3428 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3429 CmdArgs.push_back(A->getValue());
3430 else
3431 CmdArgs.push_back("plist");
3432
3433 // Disable the presentation of standard compiler warnings when using
3434 // --analyze. We only want to show static analyzer diagnostics or frontend
3435 // errors.
3436 CmdArgs.push_back("-w");
3437
3438 // Add -Xanalyzer arguments when running as analyzer.
3439 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3440}
3441
3442static bool isValidSymbolName(StringRef S) {
3443 if (S.empty())
3444 return false;
3445
3446 if (std::isdigit(S[0]))
3447 return false;
3448
3449 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3450}
3451
3452static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3453 const ArgList &Args, ArgStringList &CmdArgs,
3454 bool KernelOrKext) {
3455 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3456
3457 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3458 // doesn't even have a stack!
3459 if (EffectiveTriple.isNVPTX())
3460 return;
3461
3462 // -stack-protector=0 is default.
3464 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3465 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3466
3467 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3468 options::OPT_fstack_protector_all,
3469 options::OPT_fstack_protector_strong,
3470 options::OPT_fstack_protector)) {
3471 if (A->getOption().matches(options::OPT_fstack_protector))
3472 StackProtectorLevel =
3473 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3474 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3475 StackProtectorLevel = LangOptions::SSPStrong;
3476 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3477 StackProtectorLevel = LangOptions::SSPReq;
3478
3479 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3480 D.Diag(diag::warn_drv_unsupported_option_for_target)
3481 << A->getSpelling() << EffectiveTriple.getTriple();
3482 StackProtectorLevel = DefaultStackProtectorLevel;
3483 }
3484 } else {
3485 StackProtectorLevel = DefaultStackProtectorLevel;
3486 }
3487
3488 if (StackProtectorLevel) {
3489 CmdArgs.push_back("-stack-protector");
3490 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3491 }
3492
3493 // --param ssp-buffer-size=
3494 for (const Arg *A : Args.filtered(options::OPT__param)) {
3495 StringRef Str(A->getValue());
3496 if (Str.consume_front("ssp-buffer-size=")) {
3497 if (StackProtectorLevel) {
3498 CmdArgs.push_back("-stack-protector-buffer-size");
3499 // FIXME: Verify the argument is a valid integer.
3500 CmdArgs.push_back(Args.MakeArgString(Str));
3501 }
3502 A->claim();
3503 }
3504 }
3505
3506 const std::string &TripleStr = EffectiveTriple.getTriple();
3507 StringRef GuardValue;
3508 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3509 GuardValue = A->getValue();
3510 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3511 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3512 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3513 !EffectiveTriple.isSystemZ())
3514 D.Diag(diag::err_drv_unsupported_opt_for_target)
3515 << A->getAsString(Args) << TripleStr;
3516 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3517 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3518 GuardValue != "tls" && GuardValue != "global") {
3519 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3520 << A->getOption().getName() << GuardValue << "tls global";
3521 return;
3522 }
3523 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3524 GuardValue == "tls") {
3525 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3526 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3527 << A->getAsString(Args);
3528 return;
3529 }
3530 // Check whether the target subarch supports the hardware TLS register
3531 if (!arm::isHardTPSupported(EffectiveTriple)) {
3532 D.Diag(diag::err_target_unsupported_tp_hard)
3533 << EffectiveTriple.getArchName();
3534 return;
3535 }
3536 // Check whether the user asked for something other than -mtp=cp15
3537 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3538 StringRef Value = A->getValue();
3539 if (Value != "cp15") {
3540 D.Diag(diag::err_drv_argument_not_allowed_with)
3541 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3542 return;
3543 }
3544 }
3545 CmdArgs.push_back("-target-feature");
3546 CmdArgs.push_back("+read-tp-tpidruro");
3547 }
3548 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3549 GuardValue != "global") {
3550 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3551 << A->getOption().getName() << GuardValue << "sysreg global";
3552 return;
3553 }
3554 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3555 if (GuardValue != "tls" && GuardValue != "global") {
3556 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3557 << A->getOption().getName() << GuardValue << "tls global";
3558 return;
3559 }
3560 if (GuardValue == "tls") {
3561 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3562 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3563 << A->getAsString(Args);
3564 return;
3565 }
3566 }
3567 }
3568 A->render(Args, CmdArgs);
3569 }
3570
3571 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3572 StringRef Value = A->getValue();
3573 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3574 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3575 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3576 D.Diag(diag::err_drv_unsupported_opt_for_target)
3577 << A->getAsString(Args) << TripleStr;
3578 int Offset;
3579 if (Value.getAsInteger(10, Offset)) {
3580 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3581 return;
3582 }
3583 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3584 (Offset < 0 || Offset > 0xfffff)) {
3585 D.Diag(diag::err_drv_invalid_int_value)
3586 << A->getOption().getName() << Value;
3587 return;
3588 }
3589 A->render(Args, CmdArgs);
3590 }
3591
3592 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3593 StringRef Value = A->getValue();
3594 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3595 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3596 D.Diag(diag::err_drv_unsupported_opt_for_target)
3597 << A->getAsString(Args) << TripleStr;
3598 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3599 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3600 << A->getOption().getName() << Value << "fs gs";
3601 return;
3602 }
3603 if (EffectiveTriple.isAArch64() &&
3604 llvm::StringSwitch<bool>(Value)
3605 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3606 "tpidr_el2", "far_el1", "far_el2"},
3607 false)
3608 .Default(true)) {
3609 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3610 << A->getOption().getName() << Value
3611 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3612 return;
3613 }
3614 if (EffectiveTriple.isRISCV() && Value != "tp") {
3615 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3616 << A->getOption().getName() << Value << "tp";
3617 return;
3618 }
3619 if (EffectiveTriple.isPPC64() && Value != "r13") {
3620 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3621 << A->getOption().getName() << Value << "r13";
3622 return;
3623 }
3624 if (EffectiveTriple.isPPC32() && Value != "r2") {
3625 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3626 << A->getOption().getName() << Value << "r2";
3627 return;
3628 }
3629 A->render(Args, CmdArgs);
3630 }
3631
3632 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3633 StringRef Value = A->getValue();
3634 if (!isValidSymbolName(Value)) {
3635 D.Diag(diag::err_drv_argument_only_allowed_with)
3636 << A->getOption().getName() << "legal symbol name";
3637 return;
3638 }
3639 A->render(Args, CmdArgs);
3640 }
3641
3642 if (Arg *A =
3643 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3644 if (!EffectiveTriple.isAArch64())
3645 D.Diag(diag::err_drv_unsupported_opt_for_target)
3646 << A->getAsString(Args) << TripleStr;
3647 StringRef Value = A->getValue();
3648 unsigned Width;
3649 if (Value.getAsInteger(10, Width)) {
3650 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3651 return;
3652 }
3653 if (Width != 4 && Width != 8) {
3654 D.Diag(diag::err_drv_invalid_int_value)
3655 << A->getOption().getName() << Value;
3656 }
3657 }
3658 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3659 if (!EffectiveTriple.isSystemZ()) {
3660 D.Diag(diag::err_drv_unsupported_opt_for_target)
3661 << A->getAsString(Args) << TripleStr;
3662 return;
3663 }
3664 if (GuardValue != "global") {
3665 D.Diag(diag::err_drv_argument_only_allowed_with)
3666 << "-mstack-protector-guard-record"
3667 << "-mstack-protector-guard=global";
3668 return;
3669 }
3670 A->render(Args, CmdArgs);
3671 }
3672}
3673
3674static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3675 ArgStringList &CmdArgs) {
3676 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3677
3678 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3679 !EffectiveTriple.isOSFuchsia())
3680 return;
3681
3682 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3683 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3684 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3685 return;
3686
3687 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3688 options::OPT_fno_stack_clash_protection);
3689}
3690
3692 const ToolChain &TC,
3693 const ArgList &Args,
3694 ArgStringList &CmdArgs) {
3695 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3696 StringRef TrivialAutoVarInit = "";
3697
3698 for (const Arg *A : Args) {
3699 switch (A->getOption().getID()) {
3700 default:
3701 continue;
3702 case options::OPT_ftrivial_auto_var_init: {
3703 A->claim();
3704 StringRef Val = A->getValue();
3705 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3706 TrivialAutoVarInit = Val;
3707 else
3708 D.Diag(diag::err_drv_unsupported_option_argument)
3709 << A->getSpelling() << Val;
3710 break;
3711 }
3712 }
3713 }
3714
3715 if (TrivialAutoVarInit.empty())
3716 switch (DefaultTrivialAutoVarInit) {
3718 break;
3720 TrivialAutoVarInit = "pattern";
3721 break;
3723 TrivialAutoVarInit = "zero";
3724 break;
3725 }
3726
3727 if (!TrivialAutoVarInit.empty()) {
3728 CmdArgs.push_back(
3729 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3730 }
3731
3732 if (Arg *A =
3733 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3734 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3735 StringRef(
3736 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3737 "uninitialized")
3738 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3739 A->claim();
3740 StringRef Val = A->getValue();
3741 if (std::stoi(Val.str()) <= 0)
3742 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3743 CmdArgs.push_back(
3744 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3745 }
3746
3747 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3748 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3749 StringRef(
3750 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3751 "uninitialized")
3752 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3753 A->claim();
3754 StringRef Val = A->getValue();
3755 if (std::stoi(Val.str()) <= 0)
3756 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3757 CmdArgs.push_back(
3758 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3759 }
3760}
3761
3762static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3763 types::ID InputType) {
3764 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3765 // for denormal flushing handling based on the target.
3766 const unsigned ForwardedArguments[] = {
3767 options::OPT_cl_opt_disable,
3768 options::OPT_cl_strict_aliasing,
3769 options::OPT_cl_single_precision_constant,
3770 options::OPT_cl_finite_math_only,
3771 options::OPT_cl_kernel_arg_info,
3772 options::OPT_cl_unsafe_math_optimizations,
3773 options::OPT_cl_fast_relaxed_math,
3774 options::OPT_cl_mad_enable,
3775 options::OPT_cl_no_signed_zeros,
3776 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3777 options::OPT_cl_uniform_work_group_size
3778 };
3779
3780 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3781 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3782 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3783 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3784 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3785 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3786 }
3787
3788 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3789 CmdArgs.push_back("-menable-no-infs");
3790 CmdArgs.push_back("-menable-no-nans");
3791 }
3792
3793 for (const auto &Arg : ForwardedArguments)
3794 if (const auto *A = Args.getLastArg(Arg))
3795 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3796
3797 // Only add the default headers if we are compiling OpenCL sources.
3798 if ((types::isOpenCL(InputType) ||
3799 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3800 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3801 CmdArgs.push_back("-finclude-default-header");
3802 CmdArgs.push_back("-fdeclare-opencl-builtins");
3803 }
3804}
3805
3806static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3807 types::ID InputType) {
3808 const unsigned ForwardedArguments[] = {
3809 options::OPT_hlsl_all_resources_bound,
3810 options::OPT_dxil_validator_version,
3811 options::OPT_res_may_alias,
3812 options::OPT_D,
3813 options::OPT_I,
3814 options::OPT_O,
3815 options::OPT_emit_llvm,
3816 options::OPT_emit_obj,
3817 options::OPT_disable_llvm_passes,
3818 options::OPT_fnative_half_type,
3819 options::OPT_fnative_int16_type,
3820 options::OPT_fmatrix_memory_layout_EQ,
3821 options::OPT_hlsl_entrypoint,
3822 options::OPT_fdx_rootsignature_define,
3823 options::OPT_fdx_rootsignature_version,
3824 options::OPT_fhlsl_spv_use_unknown_image_format,
3825 options::OPT_fhlsl_spv_enable_maximal_reconvergence};
3826 if (!types::isHLSL(InputType))
3827 return;
3828 for (const auto &Arg : ForwardedArguments)
3829 if (const auto *A = Args.getLastArg(Arg))
3830 A->renderAsInput(Args, CmdArgs);
3831 // Add the default headers if dxc_no_stdinc is not set.
3832 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3833 !Args.hasArg(options::OPT_nostdinc))
3834 CmdArgs.push_back("-finclude-default-header");
3835}
3836
3837static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3838 ArgStringList &CmdArgs, types::ID InputType) {
3839 if (!Args.hasArg(options::OPT_fopenacc))
3840 return;
3841
3842 CmdArgs.push_back("-fopenacc");
3843}
3844
3845static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3846 const ArgList &Args, ArgStringList &CmdArgs) {
3847 // -fbuiltin is default unless -mkernel is used.
3848 bool UseBuiltins =
3849 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3850 !Args.hasArg(options::OPT_mkernel));
3851 if (!UseBuiltins)
3852 CmdArgs.push_back("-fno-builtin");
3853
3854 // -ffreestanding implies -fno-builtin.
3855 if (Args.hasArg(options::OPT_ffreestanding))
3856 UseBuiltins = false;
3857
3858 // Process the -fno-builtin-* options.
3859 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3860 A->claim();
3861
3862 // If -fno-builtin is specified, then there's no need to pass the option to
3863 // the frontend.
3864 if (UseBuiltins)
3865 A->render(Args, CmdArgs);
3866 }
3867}
3868
3870 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3871 Twine Path{Str};
3872 Path.toVector(Result);
3873 return Path.getSingleStringRef() != "";
3874 }
3875 if (llvm::sys::path::cache_directory(Result)) {
3876 llvm::sys::path::append(Result, "clang");
3877 llvm::sys::path::append(Result, "ModuleCache");
3878 return true;
3879 }
3880 return false;
3881}
3882
3885 const char *BaseInput) {
3886 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
3887 return StringRef(ModuleOutputEQ->getValue());
3888
3889 SmallString<256> OutputPath;
3890 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3891 FinalOutput && Args.hasArg(options::OPT_c))
3892 OutputPath = FinalOutput->getValue();
3893 else {
3894 llvm::sys::fs::current_path(OutputPath);
3895 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
3896 }
3897
3898 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
3899 llvm::sys::path::replace_extension(OutputPath, Extension);
3900 return OutputPath;
3901}
3902
3904 const ArgList &Args, const InputInfo &Input,
3905 const InputInfo &Output, bool HaveStd20,
3906 ArgStringList &CmdArgs) {
3907 const bool IsCXX = types::isCXX(Input.getType());
3908 const bool HaveStdCXXModules = IsCXX && HaveStd20;
3909 bool HaveModules = HaveStdCXXModules;
3910
3911 // -fmodules enables the use of precompiled modules (off by default).
3912 // Users can pass -fno-cxx-modules to turn off modules support for
3913 // C++/Objective-C++ programs.
3914 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3915 options::OPT_fno_cxx_modules, true);
3916 bool HaveClangModules = false;
3917 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3918 if (AllowedInCXX || !IsCXX) {
3919 CmdArgs.push_back("-fmodules");
3920 HaveClangModules = true;
3921 }
3922 }
3923
3924 HaveModules |= HaveClangModules;
3925
3926 if (HaveModules && !AllowedInCXX)
3927 CmdArgs.push_back("-fno-cxx-modules");
3928
3929 // -fmodule-maps enables implicit reading of module map files. By default,
3930 // this is enabled if we are using Clang's flavor of precompiled modules.
3931 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3932 options::OPT_fno_implicit_module_maps, HaveClangModules))
3933 CmdArgs.push_back("-fimplicit-module-maps");
3934
3935 // -fmodules-decluse checks that modules used are declared so (off by default)
3936 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3937 options::OPT_fno_modules_decluse);
3938
3939 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3940 // all #included headers are part of modules.
3941 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3942 options::OPT_fno_modules_strict_decluse, false))
3943 CmdArgs.push_back("-fmodules-strict-decluse");
3944
3945 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
3946 options::OPT_fno_modulemap_allow_subdirectory_search);
3947
3948 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3949 bool ImplicitModules = false;
3950 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3951 options::OPT_fno_implicit_modules, HaveClangModules)) {
3952 if (HaveModules)
3953 CmdArgs.push_back("-fno-implicit-modules");
3954 } else if (HaveModules) {
3955 ImplicitModules = true;
3956 // -fmodule-cache-path specifies where our implicitly-built module files
3957 // should be written.
3958 SmallString<128> Path;
3959 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3960 Path = A->getValue();
3961
3962 bool HasPath = true;
3963 if (C.isForDiagnostics()) {
3964 // When generating crash reports, we want to emit the modules along with
3965 // the reproduction sources, so we ignore any provided module path.
3966 Path = Output.getFilename();
3967 llvm::sys::path::replace_extension(Path, ".cache");
3968 llvm::sys::path::append(Path, "modules");
3969 } else if (Path.empty()) {
3970 // No module path was provided: use the default.
3971 HasPath = Driver::getDefaultModuleCachePath(Path);
3972 }
3973
3974 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3975 // That being said, that failure is unlikely and not caching is harmless.
3976 if (HasPath) {
3977 const char Arg[] = "-fmodules-cache-path=";
3978 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3979 CmdArgs.push_back(Args.MakeArgString(Path));
3980 }
3981
3982 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
3983 }
3984
3985 if (HaveModules) {
3986 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3987 options::OPT_fno_prebuilt_implicit_modules, false))
3988 CmdArgs.push_back("-fprebuilt-implicit-modules");
3989 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3990 options::OPT_fno_modules_validate_input_files_content,
3991 false))
3992 CmdArgs.push_back("-fvalidate-ast-input-files-content");
3993 }
3994
3995 // -fmodule-name specifies the module that is currently being built (or
3996 // used for header checking by -fmodule-maps).
3997 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3998
3999 // -fmodule-map-file can be used to specify files containing module
4000 // definitions.
4001 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4002
4003 // -fbuiltin-module-map can be used to load the clang
4004 // builtin headers modulemap file.
4005 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4006 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4007 llvm::sys::path::append(BuiltinModuleMap, "include");
4008 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4009 if (llvm::sys::fs::exists(BuiltinModuleMap))
4010 CmdArgs.push_back(
4011 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4012 }
4013
4014 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4015 // names to precompiled module files (the module is loaded only if used).
4016 // The -fmodule-file=<file> form can be used to unconditionally load
4017 // precompiled module files (whether used or not).
4018 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4019 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4020
4021 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4022 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4023 CmdArgs.push_back(Args.MakeArgString(
4024 std::string("-fprebuilt-module-path=") + A->getValue()));
4025 A->claim();
4026 }
4027 } else
4028 Args.ClaimAllArgs(options::OPT_fmodule_file);
4029
4030 // When building modules and generating crashdumps, we need to dump a module
4031 // dependency VFS alongside the output.
4032 if (HaveClangModules && C.isForDiagnostics()) {
4033 SmallString<128> VFSDir(Output.getFilename());
4034 llvm::sys::path::replace_extension(VFSDir, ".cache");
4035 // Add the cache directory as a temp so the crash diagnostics pick it up.
4036 C.addTempFile(Args.MakeArgString(VFSDir));
4037
4038 llvm::sys::path::append(VFSDir, "vfs");
4039 CmdArgs.push_back("-module-dependency-dir");
4040 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4041 }
4042
4043 if (HaveClangModules)
4044 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4045
4046 // Pass through all -fmodules-ignore-macro arguments.
4047 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4048 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4049 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4050
4051 if (HaveClangModules) {
4052 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4053
4054 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4055 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4056 D.Diag(diag::err_drv_argument_not_allowed_with)
4057 << A->getAsString(Args) << "-fbuild-session-timestamp";
4058
4059 llvm::sys::fs::file_status Status;
4060 if (llvm::sys::fs::status(A->getValue(), Status))
4061 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4062 CmdArgs.push_back(Args.MakeArgString(
4063 "-fbuild-session-timestamp=" +
4064 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4065 Status.getLastModificationTime().time_since_epoch())
4066 .count())));
4067 }
4068
4069 if (Args.getLastArg(
4070 options::OPT_fmodules_validate_once_per_build_session)) {
4071 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4072 options::OPT_fbuild_session_file))
4073 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4074
4075 Args.AddLastArg(CmdArgs,
4076 options::OPT_fmodules_validate_once_per_build_session);
4077 }
4078
4079 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4080 options::OPT_fno_modules_validate_system_headers,
4081 ImplicitModules))
4082 CmdArgs.push_back("-fmodules-validate-system-headers");
4083
4084 Args.AddLastArg(CmdArgs,
4085 options::OPT_fmodules_disable_diagnostic_validation);
4086 } else {
4087 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4088 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4089 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4090 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4091 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4092 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4093 }
4094
4095 // FIXME: We provisionally don't check ODR violations for decls in the global
4096 // module fragment.
4097 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4098
4099 if (Input.getType() == driver::types::TY_CXXModule ||
4100 Input.getType() == driver::types::TY_PP_CXXModule) {
4101 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4102 CmdArgs.push_back("-fmodules-reduced-bmi");
4103
4104 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4105 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4106 else if (!(Args.hasArg(options::OPT__precompile) ||
4107 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4108 Args.hasArg(options::OPT_fmodule_output))
4109 // If --precompile is specified, we will always generate a module file if
4110 // we're compiling an importable module unit. This is fine even if the
4111 // compilation process won't reach the point of generating the module file
4112 // (e.g., in the preprocessing mode), since the attached flag
4113 // '-fmodule-output' is useless.
4114 //
4115 // But if '--precompile' is specified, it might be annoying to always
4116 // generate the module file as '--precompile' will generate the module
4117 // file anyway.
4118 CmdArgs.push_back(Args.MakeArgString(
4119 "-fmodule-output=" +
4121 }
4122
4123 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4124 Args.hasArg(options::OPT__precompile) &&
4125 (!Args.hasArg(options::OPT_o) ||
4126 Args.getLastArg(options::OPT_o)->getValue() ==
4128 D.Diag(diag::err_drv_reduced_module_output_overrided);
4129 }
4130
4131 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4132 // other translation units than module units. This is more user friendly to
4133 // allow end uers to enable this feature without asking for help from build
4134 // systems.
4135 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4136 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4137
4138 // We need to include the case the input file is a module file here.
4139 // Since the default compilation model for C++ module interface unit will
4140 // create temporary module file and compile the temporary module file
4141 // to get the object file. Then the `-fmodule-output` flag will be
4142 // brought to the second compilation process. So we have to claim it for
4143 // the case too.
4144 if (Input.getType() == driver::types::TY_CXXModule ||
4145 Input.getType() == driver::types::TY_PP_CXXModule ||
4146 Input.getType() == driver::types::TY_ModuleFile) {
4147 Args.ClaimAllArgs(options::OPT_fmodule_output);
4148 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4149 }
4150
4151 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4152 CmdArgs.push_back("-fmodules-embed-all-files");
4153
4154 return HaveModules;
4155}
4156
4157static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4158 ArgStringList &CmdArgs) {
4159 // -fsigned-char is default.
4160 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4161 options::OPT_fno_signed_char,
4162 options::OPT_funsigned_char,
4163 options::OPT_fno_unsigned_char)) {
4164 if (A->getOption().matches(options::OPT_funsigned_char) ||
4165 A->getOption().matches(options::OPT_fno_signed_char)) {
4166 CmdArgs.push_back("-fno-signed-char");
4167 }
4168 } else if (!isSignedCharDefault(T)) {
4169 CmdArgs.push_back("-fno-signed-char");
4170 }
4171
4172 // The default depends on the language standard.
4173 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4174
4175 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4176 options::OPT_fno_short_wchar)) {
4177 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4178 CmdArgs.push_back("-fwchar-type=short");
4179 CmdArgs.push_back("-fno-signed-wchar");
4180 } else {
4181 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4182 CmdArgs.push_back("-fwchar-type=int");
4183 if (T.isOSzOS() ||
4184 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4185 CmdArgs.push_back("-fno-signed-wchar");
4186 else
4187 CmdArgs.push_back("-fsigned-wchar");
4188 }
4189 } else if (T.isOSzOS())
4190 CmdArgs.push_back("-fno-signed-wchar");
4191}
4192
4193static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4194 const llvm::Triple &T, const ArgList &Args,
4195 ObjCRuntime &Runtime, bool InferCovariantReturns,
4196 const InputInfo &Input, ArgStringList &CmdArgs) {
4197 const llvm::Triple::ArchType Arch = TC.getArch();
4198
4199 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4200 // is the default. Except for deployment target of 10.5, next runtime is
4201 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4202 if (Runtime.isNonFragile()) {
4203 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4204 options::OPT_fno_objc_legacy_dispatch,
4206 if (TC.UseObjCMixedDispatch())
4207 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4208 else
4209 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4210 }
4211 }
4212
4213 // Forward -fobjc-direct-precondition-thunk to cc1
4214 // Defaults to false and needs explict turn on for now
4215 // TODO: switch to default true and needs explict turn off in the future.
4216 // TODO: add support for other runtimes
4217 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4218 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4219 if (Runtime.isNeXTFamily()) {
4220 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4221 } else {
4222 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4223 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4224 }
4225 }
4226
4227 if (types::isObjC(Input.getType())) {
4228 // Pass down -fobjc-msgsend-selector-stubs if present.
4229 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4230 options::OPT_fno_objc_msgsend_selector_stubs, false))
4231 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4232
4233 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4234 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4235 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4236 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4237 }
4238
4239 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4240 // to do Array/Dictionary subscripting by default.
4241 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4242 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4243 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4244
4245 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4246 // NOTE: This logic is duplicated in ToolChains.cpp.
4247 if (isObjCAutoRefCount(Args)) {
4248 TC.CheckObjCARC();
4249
4250 CmdArgs.push_back("-fobjc-arc");
4251
4252 // FIXME: It seems like this entire block, and several around it should be
4253 // wrapped in isObjC, but for now we just use it here as this is where it
4254 // was being used previously.
4255 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4257 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4258 else
4259 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4260 }
4261
4262 // Allow the user to enable full exceptions code emission.
4263 // We default off for Objective-C, on for Objective-C++.
4264 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4265 options::OPT_fno_objc_arc_exceptions,
4266 /*Default=*/types::isCXX(Input.getType())))
4267 CmdArgs.push_back("-fobjc-arc-exceptions");
4268 }
4269
4270 // Silence warning for full exception code emission options when explicitly
4271 // set to use no ARC.
4272 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4273 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4274 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4275 }
4276
4277 // Allow the user to control whether messages can be converted to runtime
4278 // functions.
4279 if (types::isObjC(Input.getType())) {
4280 auto *Arg = Args.getLastArg(
4281 options::OPT_fobjc_convert_messages_to_runtime_calls,
4282 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4283 if (Arg &&
4284 Arg->getOption().matches(
4285 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4286 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4287 }
4288
4289 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4290 // rewriter.
4291 if (InferCovariantReturns)
4292 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4293
4294 // Pass down -fobjc-weak or -fno-objc-weak if present.
4295 if (types::isObjC(Input.getType())) {
4296 auto WeakArg =
4297 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4298 if (!WeakArg) {
4299 // nothing to do
4300 } else if (!Runtime.allowsWeak()) {
4301 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4302 D.Diag(diag::err_objc_weak_unsupported);
4303 } else {
4304 WeakArg->render(Args, CmdArgs);
4305 }
4306 }
4307
4308 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4309 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4310
4311 // Forward constant literal flags to cc1.
4312 if (types::isObjC(Input.getType())) {
4313 bool EnableConstantLiterals =
4314 Args.hasFlag(options::OPT_fobjc_constant_literals,
4315 options::OPT_fno_objc_constant_literals,
4316 /*default=*/false) &&
4317 Runtime.hasConstantLiteralClasses();
4318 if (EnableConstantLiterals)
4319 CmdArgs.push_back("-fobjc-constant-literals");
4320 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4321 options::OPT_fno_constant_nsnumber_literals,
4322 /*default=*/true) &&
4323 EnableConstantLiterals)
4324 CmdArgs.push_back("-fconstant-nsnumber-literals");
4325 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4326 options::OPT_fno_constant_nsarray_literals,
4327 /*default=*/true) &&
4328 EnableConstantLiterals)
4329 CmdArgs.push_back("-fconstant-nsarray-literals");
4330 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4331 options::OPT_fno_constant_nsdictionary_literals,
4332 /*default=*/true) &&
4333 EnableConstantLiterals)
4334 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4335 }
4336}
4337
4338static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4339 ArgStringList &CmdArgs) {
4340 bool CaretDefault = true;
4341 bool ColumnDefault = true;
4342
4343 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4344 options::OPT__SLASH_diagnostics_column,
4345 options::OPT__SLASH_diagnostics_caret)) {
4346 switch (A->getOption().getID()) {
4347 case options::OPT__SLASH_diagnostics_caret:
4348 CaretDefault = true;
4349 ColumnDefault = true;
4350 break;
4351 case options::OPT__SLASH_diagnostics_column:
4352 CaretDefault = false;
4353 ColumnDefault = true;
4354 break;
4355 case options::OPT__SLASH_diagnostics_classic:
4356 CaretDefault = false;
4357 ColumnDefault = false;
4358 break;
4359 }
4360 }
4361
4362 // -fcaret-diagnostics is default.
4363 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4364 options::OPT_fno_caret_diagnostics, CaretDefault))
4365 CmdArgs.push_back("-fno-caret-diagnostics");
4366
4367 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4368 options::OPT_fno_diagnostics_fixit_info);
4369 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4370 options::OPT_fno_diagnostics_show_option);
4371
4372 if (const Arg *A =
4373 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4374 CmdArgs.push_back("-fdiagnostics-show-category");
4375 CmdArgs.push_back(A->getValue());
4376 }
4377
4378 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4379 options::OPT_fno_diagnostics_show_hotness);
4380
4381 if (const Arg *A =
4382 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4383 std::string Opt =
4384 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4385 CmdArgs.push_back(Args.MakeArgString(Opt));
4386 }
4387
4388 if (const Arg *A =
4389 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4390 std::string Opt =
4391 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4392 CmdArgs.push_back(Args.MakeArgString(Opt));
4393 }
4394
4395 if (const Arg *A =
4396 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4397 options::OPT_fno_diagnostics_show_inlining_chain)) {
4398 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4399 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4400 else
4401 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4402 }
4403
4404 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4405 CmdArgs.push_back("-fdiagnostics-format");
4406 CmdArgs.push_back(A->getValue());
4407 if (StringRef(A->getValue()) == "sarif" ||
4408 StringRef(A->getValue()) == "SARIF")
4409 D.Diag(diag::warn_drv_sarif_format_unstable);
4410 }
4411
4412 if (const Arg *A = Args.getLastArg(
4413 options::OPT_fdiagnostics_show_note_include_stack,
4414 options::OPT_fno_diagnostics_show_note_include_stack)) {
4415 const Option &O = A->getOption();
4416 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4417 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4418 else
4419 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4420 }
4421
4422 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4423
4424 if (Args.hasArg(options::OPT_fansi_escape_codes))
4425 CmdArgs.push_back("-fansi-escape-codes");
4426
4427 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4428 options::OPT_fno_show_source_location);
4429
4430 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4431 options::OPT_fno_diagnostics_show_line_numbers);
4432
4433 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4434 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4435
4436 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4437 ColumnDefault))
4438 CmdArgs.push_back("-fno-show-column");
4439
4440 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4441 options::OPT_fno_spell_checking);
4442
4443 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4444}
4445
4446static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4447 const ArgList &Args, ArgStringList &CmdArgs,
4448 unsigned DwarfVersion) {
4449 auto *DwarfFormatArg =
4450 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4451 if (!DwarfFormatArg)
4452 return;
4453
4454 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4455 if (DwarfVersion < 3)
4456 D.Diag(diag::err_drv_argument_only_allowed_with)
4457 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4458 else if (!T.isArch64Bit())
4459 D.Diag(diag::err_drv_argument_only_allowed_with)
4460 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4461 else if (!T.isOSBinFormatELF())
4462 D.Diag(diag::err_drv_argument_only_allowed_with)
4463 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4464 }
4465
4466 DwarfFormatArg->render(Args, CmdArgs);
4467}
4468
4469static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4470 const ArgList &Args) {
4471 bool NeedsSimpleTemplateNames =
4472 Args.hasFlag(options::OPT_gsimple_template_names,
4473 options::OPT_gno_simple_template_names,
4475 if (!NeedsSimpleTemplateNames)
4476 return false;
4477
4478 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4479 if (!checkDebugInfoOption(A, Args, D, TC))
4480 return false;
4481
4482 return true;
4483}
4484
4485static void
4486renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4487 const ArgList &Args, types::ID InputType,
4488 ArgStringList &CmdArgs, const InputInfo &Output,
4489 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4490 DwarfFissionKind &DwarfFission) {
4491 bool IRInput = isLLVMIR(InputType);
4492 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4493 !isHIP(InputType) && !isObjC(InputType) &&
4494 !isOpenCL(InputType);
4495
4496 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4497
4498 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4499 options::OPT_fno_debug_record_sysroot, true))
4500 CmdArgs.push_back("-fno-debug-record-sysroot");
4501
4502 // The 'g' groups options involve a somewhat intricate sequence of decisions
4503 // about what to pass from the driver to the frontend, but by the time they
4504 // reach cc1 they've been factored into three well-defined orthogonal choices:
4505 // * what level of debug info to generate
4506 // * what dwarf version to write
4507 // * what debugger tuning to use
4508 // This avoids having to monkey around further in cc1 other than to disable
4509 // codeview if not running in a Windows environment. Perhaps even that
4510 // decision should be made in the driver as well though.
4511 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4512
4513 bool SplitDWARFInlining =
4514 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4515 options::OPT_fno_split_dwarf_inlining, false);
4516
4517 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4518 // object file generation and no IR generation, -gN should not be needed. So
4519 // allow -gsplit-dwarf with either -gN or IR input.
4520 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4521 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4522 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4523 D.Diag(diag::err_drv_unsupported_opt_for_target)
4524 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4525 << TC.getTriple().str();
4526 return;
4527 }
4528 Arg *SplitDWARFArg;
4529 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4530 if (DwarfFission != DwarfFissionKind::None &&
4531 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4532 DwarfFission = DwarfFissionKind::None;
4533 SplitDWARFInlining = false;
4534 }
4535 }
4536 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4537 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4538
4539 // If the last option explicitly specified a debug-info level, use it.
4540 if (checkDebugInfoOption(A, Args, D, TC) &&
4541 A->getOption().matches(options::OPT_gN_Group)) {
4542 DebugInfoKind = debugLevelToInfoKind(*A);
4543 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4544 // complicated if you've disabled inline info in the skeleton CUs
4545 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4546 // line-tables-only, so let those compose naturally in that case.
4547 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4548 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4549 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4550 SplitDWARFInlining))
4551 DwarfFission = DwarfFissionKind::None;
4552 }
4553 }
4554
4555 // If a debugger tuning argument appeared, remember it.
4556 bool HasDebuggerTuning = false;
4557 if (const Arg *A =
4558 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4559 HasDebuggerTuning = true;
4560 if (checkDebugInfoOption(A, Args, D, TC)) {
4561 if (A->getOption().matches(options::OPT_glldb))
4562 DebuggerTuning = llvm::DebuggerKind::LLDB;
4563 else if (A->getOption().matches(options::OPT_gsce))
4564 DebuggerTuning = llvm::DebuggerKind::SCE;
4565 else if (A->getOption().matches(options::OPT_gdbx))
4566 DebuggerTuning = llvm::DebuggerKind::DBX;
4567 else
4568 DebuggerTuning = llvm::DebuggerKind::GDB;
4569 }
4570 }
4571
4572 // If a -gdwarf argument appeared, remember it.
4573 bool EmitDwarf = false;
4574 if (const Arg *A = getDwarfNArg(Args))
4575 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4576
4577 bool EmitCodeView = false;
4578 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4579 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4580
4581 // If the user asked for debug info but did not explicitly specify -gcodeview
4582 // or -gdwarf, ask the toolchain for the default format.
4583 if (!EmitCodeView && !EmitDwarf &&
4584 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4585 switch (TC.getDefaultDebugFormat()) {
4586 case llvm::codegenoptions::DIF_CodeView:
4587 EmitCodeView = true;
4588 break;
4589 case llvm::codegenoptions::DIF_DWARF:
4590 EmitDwarf = true;
4591 break;
4592 }
4593 }
4594
4595 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4596 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4597 // be lower than what the user wanted.
4598 if (EmitDwarf) {
4599 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4600 // Clamp effective DWARF version to the max supported by the toolchain.
4601 EffectiveDWARFVersion =
4602 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4603 } else {
4604 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4605 }
4606
4607 // -gline-directives-only supported only for the DWARF debug info.
4608 if (RequestedDWARFVersion == 0 &&
4609 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4610 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4611
4612 // strict DWARF is set to false by default. But for DBX, we need it to be set
4613 // as true by default.
4614 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4615 (void)checkDebugInfoOption(A, Args, D, TC);
4616 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4617 DebuggerTuning == llvm::DebuggerKind::DBX))
4618 CmdArgs.push_back("-gstrict-dwarf");
4619
4620 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4621 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4622
4623 // Column info is included by default for everything except SCE and
4624 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4625 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4626 // practice, however, the Microsoft debuggers don't handle missing end columns
4627 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4628 // it's better not to include any column info.
4629 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4630 (void)checkDebugInfoOption(A, Args, D, TC);
4631 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4632 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4633 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4634 DebuggerTuning != llvm::DebuggerKind::DBX)))
4635 CmdArgs.push_back("-gno-column-info");
4636
4637 if (!Args.hasFlag(options::OPT_gcall_site_info,
4638 options::OPT_gno_call_site_info, true))
4639 CmdArgs.push_back("-gno-call-site-info");
4640
4641 // FIXME: Move backend command line options to the module.
4642 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4643 // If -gline-tables-only or -gline-directives-only is the last option it
4644 // wins.
4645 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4646 TC)) {
4647 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4648 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4649 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4650 CmdArgs.push_back("-dwarf-ext-refs");
4651 CmdArgs.push_back("-fmodule-format=obj");
4652 }
4653 }
4654 }
4655
4656 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4657 CmdArgs.push_back("-fsplit-dwarf-inlining");
4658
4659 // After we've dealt with all combinations of things that could
4660 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4661 // figure out if we need to "upgrade" it to standalone debug info.
4662 // We parse these two '-f' options whether or not they will be used,
4663 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4664 bool NeedFullDebug = Args.hasFlag(
4665 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4666 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4668 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4669 (void)checkDebugInfoOption(A, Args, D, TC);
4670
4671 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4672 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4673 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4674 options::OPT_feliminate_unused_debug_types, false))
4675 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4676 else if (NeedFullDebug)
4677 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4678 }
4679
4680 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4681 false)) {
4682 // Source embedding is a vendor extension to DWARF v5. By now we have
4683 // checked if a DWARF version was stated explicitly, and have otherwise
4684 // fallen back to the target default, so if this is still not at least 5
4685 // we emit an error.
4686 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4687 if (RequestedDWARFVersion < 5)
4688 D.Diag(diag::err_drv_argument_only_allowed_with)
4689 << A->getAsString(Args) << "-gdwarf-5";
4690 else if (EffectiveDWARFVersion < 5)
4691 // The toolchain has reduced allowed dwarf version, so we can't enable
4692 // -gembed-source.
4693 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4694 << A->getAsString(Args) << TC.getTripleString() << 5
4695 << EffectiveDWARFVersion;
4696 else if (checkDebugInfoOption(A, Args, D, TC))
4697 CmdArgs.push_back("-gembed-source");
4698 }
4699
4700 // Enable Key Instructions by default if we're emitting DWARF, the language is
4701 // plain C or C++, and optimisations are enabled.
4702 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4703 bool KeyInstructionsOnByDefault =
4704 EmitDwarf && PlainCOrCXX && OptLevel &&
4705 !OptLevel->getOption().matches(options::OPT_O0);
4706 if (Args.hasFlag(options::OPT_gkey_instructions,
4707 options::OPT_gno_key_instructions,
4708 KeyInstructionsOnByDefault))
4709 CmdArgs.push_back("-gkey-instructions");
4710
4711 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4712 options::OPT_gno_structor_decl_linkage_names, true))
4713 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4714
4715 if (EmitCodeView) {
4716 CmdArgs.push_back("-gcodeview");
4717
4718 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4719 options::OPT_gno_codeview_ghash);
4720
4721 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4722 options::OPT_gno_codeview_command_line);
4723 }
4724
4725 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4726 options::OPT_gno_inline_line_tables);
4727
4728 // When emitting remarks, we need at least debug lines in the output.
4729 if (willEmitRemarks(Args) &&
4730 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4731 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4732
4733 // Adjust the debug info kind for the given toolchain.
4734 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4735
4736 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4737 // set.
4738 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4739 T.isOSAIX() && !HasDebuggerTuning
4740 ? llvm::DebuggerKind::Default
4741 : DebuggerTuning);
4742
4743 // -fdebug-macro turns on macro debug info generation.
4744 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4745 false))
4746 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4747 D, TC))
4748 CmdArgs.push_back("-debug-info-macro");
4749
4750 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4751 const auto *PubnamesArg =
4752 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4753 options::OPT_gpubnames, options::OPT_gno_pubnames);
4754 if (DwarfFission != DwarfFissionKind::None ||
4755 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4756 const bool OptionSet =
4757 (PubnamesArg &&
4758 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4759 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4760 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4761 (!PubnamesArg ||
4762 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4763 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4764 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4765 options::OPT_gpubnames)
4766 ? "-gpubnames"
4767 : "-ggnu-pubnames");
4768 }
4769
4770 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4771 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4772 ForwardTemplateParams = true;
4773 CmdArgs.push_back("-gsimple-template-names=simple");
4774 }
4775
4776 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4777 bool UseDebugTemplateAlias =
4778 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4779 if (const auto *DebugTemplateAlias = Args.getLastArg(
4780 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4781 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4782 // asks for it we should let them have it (if the target supports it).
4783 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4784 const auto &Opt = DebugTemplateAlias->getOption();
4785 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4786 }
4787 }
4788 if (UseDebugTemplateAlias)
4789 CmdArgs.push_back("-gtemplate-alias");
4790
4791 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4792 StringRef v = A->getValue();
4793 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4794 }
4795
4796 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4797 options::OPT_fno_debug_ranges_base_address);
4798
4799 // -gdwarf-aranges turns on the emission of the aranges section in the
4800 // backend.
4801 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4802 A && checkDebugInfoOption(A, Args, D, TC)) {
4803 CmdArgs.push_back("-mllvm");
4804 CmdArgs.push_back("-generate-arange-section");
4805 }
4806
4807 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4808 options::OPT_fno_force_dwarf_frame);
4809
4810 bool EnableTypeUnits = false;
4811 if (Args.hasFlag(options::OPT_fdebug_types_section,
4812 options::OPT_fno_debug_types_section, false)) {
4813 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4814 D.Diag(diag::err_drv_unsupported_opt_for_target)
4815 << Args.getLastArg(options::OPT_fdebug_types_section)
4816 ->getAsString(Args)
4817 << T.getTriple();
4818 } else if (checkDebugInfoOption(
4819 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4820 TC)) {
4821 EnableTypeUnits = true;
4822 CmdArgs.push_back("-mllvm");
4823 CmdArgs.push_back("-generate-type-units");
4824 }
4825 }
4826
4827 if (const Arg *A =
4828 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4829 options::OPT_gno_omit_unreferenced_methods))
4830 (void)checkDebugInfoOption(A, Args, D, TC);
4831 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4832 options::OPT_gno_omit_unreferenced_methods, false) &&
4833 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4834 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4835 !EnableTypeUnits) {
4836 CmdArgs.push_back("-gomit-unreferenced-methods");
4837 }
4838
4839 // To avoid join/split of directory+filename, the integrated assembler prefers
4840 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4841 // form before DWARF v5.
4842 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4843 options::OPT_fno_dwarf_directory_asm,
4844 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4845 CmdArgs.push_back("-fno-dwarf-directory-asm");
4846
4847 // Decide how to render forward declarations of template instantiations.
4848 // SCE wants full descriptions, others just get them in the name.
4849 if (ForwardTemplateParams)
4850 CmdArgs.push_back("-debug-forward-template-params");
4851
4852 // Do we need to explicitly import anonymous namespaces into the parent
4853 // scope?
4854 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4855 CmdArgs.push_back("-dwarf-explicit-import");
4856
4857 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4858 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4859
4860 // This controls whether or not we perform JustMyCode instrumentation.
4861 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4862 if (TC.getTriple().isOSBinFormatELF() ||
4863 TC.getTriple().isWindowsMSVCEnvironment()) {
4864 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4865 CmdArgs.push_back("-fjmc");
4866 else if (D.IsCLMode())
4867 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4868 << "'/Zi', '/Z7'";
4869 else
4870 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4871 << "-g";
4872 } else {
4873 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4874 }
4875 }
4876
4877 // Add in -fdebug-compilation-dir if necessary.
4878 const char *DebugCompilationDir =
4879 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4880
4881 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4882
4883 // Add the output path to the object file for CodeView debug infos.
4884 if (EmitCodeView && Output.isFilename())
4885 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4886 Output.getFilename());
4887}
4888
4889static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4890 ArgStringList &CmdArgs) {
4891 unsigned RTOptionID = options::OPT__SLASH_MT;
4892
4893 if (Args.hasArg(options::OPT__SLASH_LDd))
4894 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4895 // but defining _DEBUG is sticky.
4896 RTOptionID = options::OPT__SLASH_MTd;
4897
4898 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4899 RTOptionID = A->getOption().getID();
4900
4901 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4902 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4903 .Case("static", options::OPT__SLASH_MT)
4904 .Case("static_dbg", options::OPT__SLASH_MTd)
4905 .Case("dll", options::OPT__SLASH_MD)
4906 .Case("dll_dbg", options::OPT__SLASH_MDd)
4907 .Default(options::OPT__SLASH_MT);
4908 }
4909
4910 StringRef FlagForCRT;
4911 switch (RTOptionID) {
4912 case options::OPT__SLASH_MD:
4913 if (Args.hasArg(options::OPT__SLASH_LDd))
4914 CmdArgs.push_back("-D_DEBUG");
4915 CmdArgs.push_back("-D_MT");
4916 CmdArgs.push_back("-D_DLL");
4917 FlagForCRT = "--dependent-lib=msvcrt";
4918 break;
4919 case options::OPT__SLASH_MDd:
4920 CmdArgs.push_back("-D_DEBUG");
4921 CmdArgs.push_back("-D_MT");
4922 CmdArgs.push_back("-D_DLL");
4923 FlagForCRT = "--dependent-lib=msvcrtd";
4924 break;
4925 case options::OPT__SLASH_MT:
4926 if (Args.hasArg(options::OPT__SLASH_LDd))
4927 CmdArgs.push_back("-D_DEBUG");
4928 CmdArgs.push_back("-D_MT");
4929 CmdArgs.push_back("-flto-visibility-public-std");
4930 FlagForCRT = "--dependent-lib=libcmt";
4931 break;
4932 case options::OPT__SLASH_MTd:
4933 CmdArgs.push_back("-D_DEBUG");
4934 CmdArgs.push_back("-D_MT");
4935 CmdArgs.push_back("-flto-visibility-public-std");
4936 FlagForCRT = "--dependent-lib=libcmtd";
4937 break;
4938 default:
4939 llvm_unreachable("Unexpected option ID.");
4940 }
4941
4942 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4943 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4944 } else {
4945 CmdArgs.push_back(FlagForCRT.data());
4946
4947 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4948 // users want. The /Za flag to cl.exe turns this off, but it's not
4949 // implemented in clang.
4950 CmdArgs.push_back("--dependent-lib=oldnames");
4951 }
4952
4953 // SYCL: Add SYCL runtime library dependency
4954 // SYCL runtime is a required dependency similar to CRT, so we use
4955 // --dependent-lib to embed it in the object file metadata
4956 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
4957 !Args.hasArg(options::OPT_nolibsycl) &&
4958 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
4959
4960 // Determine debug vs release based on CRT flags
4961 bool IsDebugBuild = false;
4962
4963 // Check -fms-runtime-lib=dll_dbg
4964 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4965 StringRef RuntimeVal = A->getValue();
4966 if (RuntimeVal == "dll_dbg")
4967 IsDebugBuild = true;
4968 }
4969
4970 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
4971 // overriding options (e.g., /MDd /MD -> /MD wins)
4972 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
4973 if (A->getOption().matches(options::OPT__SLASH_MDd))
4974 IsDebugBuild = true;
4975 }
4976
4977 // Add appropriate SYCL runtime library dependency
4978 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
4979 : "--dependent-lib=LLVMSYCL");
4980 }
4981
4982 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4983 // even if the file doesn't actually refer to any of the routines because
4984 // the CRT itself has incomplete dependency markings.
4985 if (TC.getTriple().isWindowsArm64EC())
4986 CmdArgs.push_back("--dependent-lib=softintrin");
4987}
4988
4990 const InputInfo &Output, const InputInfoList &Inputs,
4991 const ArgList &Args, const char *LinkingOutput) const {
4992 const auto &TC = getToolChain();
4993 const llvm::Triple &RawTriple = TC.getTriple();
4994 const llvm::Triple &Triple = TC.getEffectiveTriple();
4995 const std::string &TripleStr = Triple.getTriple();
4996
4997 bool KernelOrKext =
4998 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4999 const Driver &D = TC.getDriver();
5000 ArgStringList CmdArgs;
5001
5002 assert(Inputs.size() >= 1 && "Must have at least one input.");
5003 // CUDA/HIP compilation may have multiple inputs (source file + results of
5004 // device-side compilations). OpenMP device jobs also take the host IR as a
5005 // second input. Module precompilation accepts a list of header files to
5006 // include as part of the module. API extraction accepts a list of header
5007 // files whose API information is emitted in the output. All other jobs are
5008 // expected to have exactly one input. SYCL compilation only expects a
5009 // single input.
5010 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5011 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5012 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5013 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5014 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5015 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5016 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5017 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5018 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5020 bool IsHostOffloadingAction =
5023 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
5024 Args.hasFlag(options::OPT_offload_new_driver,
5025 options::OPT_no_offload_new_driver,
5026 C.getActiveOffloadKinds() != Action::OFK_None));
5027
5028 bool IsRDCMode =
5029 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
5030
5031 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5032 bool IsUsingLTO = LTOMode != LTOK_None;
5033
5034 // Extract API doesn't have a main input file, so invent a fake one as a
5035 // placeholder.
5036 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5037 "extract-api");
5038
5039 const InputInfo &Input =
5040 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5041
5042 InputInfoList ExtractAPIInputs;
5043 InputInfoList HostOffloadingInputs;
5044 const InputInfo *CudaDeviceInput = nullptr;
5045 const InputInfo *OpenMPDeviceInput = nullptr;
5046 for (const InputInfo &I : Inputs) {
5047 if (&I == &Input || I.getType() == types::TY_Nothing) {
5048 // This is the primary input or contains nothing.
5049 } else if (IsExtractAPI) {
5050 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5051 if (I.getType() != ExpectedInputType) {
5052 D.Diag(diag::err_drv_extract_api_wrong_kind)
5053 << I.getFilename() << types::getTypeName(I.getType())
5054 << types::getTypeName(ExpectedInputType);
5055 }
5056 ExtractAPIInputs.push_back(I);
5057 } else if (IsHostOffloadingAction) {
5058 HostOffloadingInputs.push_back(I);
5059 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5060 CudaDeviceInput = &I;
5061 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5062 OpenMPDeviceInput = &I;
5063 } else {
5064 llvm_unreachable("unexpectedly given multiple inputs");
5065 }
5066 }
5067
5068 bool IsUEFI = RawTriple.isUEFI();
5069 bool IsIAMCU = RawTriple.isOSIAMCU();
5070
5071 // C++ is not supported for IAMCU.
5072 if (IsIAMCU && types::isCXX(Input.getType()))
5073 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5074
5075 // Invoke ourselves in -cc1 mode.
5076 //
5077 // FIXME: Implement custom jobs for internal actions.
5078 CmdArgs.push_back("-cc1");
5079
5080 // Add the "effective" target triple.
5081 CmdArgs.push_back("-triple");
5082 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5083
5084 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5085
5086 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5087 if (AuxTriple) {
5088 CmdArgs.push_back("-aux-triple");
5089 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5090
5091 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5092 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5093 // Windows), we need to pass Windows-specific flags to cc1.
5094 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5096 // Figure out the device side triple for the host-side compilation.
5097 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5098 ++I) {
5100 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5101 if (OffloadToolChains.first == OffloadToolChains.second)
5102 continue;
5103
5104 const llvm::Triple &DeviceAuxTriple =
5105 OffloadToolChains.first->second->getTriple();
5106 CmdArgs.push_back("-aux-triple");
5107 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5108 break;
5109 }
5110 }
5111
5112 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5113 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5114 Args.ClaimAllArgs(options::OPT_MJ);
5115 } else if (const Arg *GenCDBFragment =
5116 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5117 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5118 TripleStr, Output, Input, Args);
5119 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5120 }
5121
5122 if ((getToolChain().getTriple().isAMDGPU() ||
5123 (getToolChain().getTriple().isSPIRV() &&
5124 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5125 // Device side compilation printf
5126 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5127 CmdArgs.push_back(Args.MakeArgString(
5128 "-mprintf-kind=" +
5129 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5130 // Force compiler error on invalid conversion specifiers
5131 CmdArgs.push_back(
5132 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5133 }
5134 }
5135
5136 if (IsCuda && !IsCudaDevice) {
5137 // We need to figure out which CUDA version we're compiling for, as that
5138 // determines how we load and launch GPU kernels.
5139 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5140 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5141 assert(CTC && "Expected valid CUDA Toolchain.");
5142 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5143 CmdArgs.push_back(Args.MakeArgString(
5144 Twine("-target-sdk-version=") +
5145 CudaVersionToString(CTC->CudaInstallation.version())));
5146 }
5147
5148 // Optimization level for CodeGen.
5149 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5150 if (A->getOption().matches(options::OPT_O4)) {
5151 CmdArgs.push_back("-O3");
5152 D.Diag(diag::warn_O4_is_O3);
5153 } else {
5154 A->render(Args, CmdArgs);
5155 }
5156 }
5157
5158 // Unconditionally claim the printf option now to avoid unused diagnostic.
5159 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5160 PF->claim();
5161
5162 if (IsSYCL) {
5163 if (IsSYCLDevice) {
5164 // We want to compile sycl kernels.
5165 CmdArgs.push_back("-fsycl-is-device");
5166
5167 // Set O2 optimization level by default
5168 if (!Args.getLastArg(options::OPT_O_Group))
5169 CmdArgs.push_back("-O2");
5170 } else {
5171 // Add any options that are needed specific to SYCL offload while
5172 // performing the host side compilation.
5173
5174 // Let the front-end host compilation flow know about SYCL offload
5175 // compilation.
5176 CmdArgs.push_back("-fsycl-is-host");
5177 }
5178
5179 // Set options for both host and device.
5180 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5181 if (SYCLStdArg) {
5182 SYCLStdArg->render(Args, CmdArgs);
5183 } else {
5184 // Ensure the default version in SYCL mode is 2020.
5185 CmdArgs.push_back("-sycl-std=2020");
5186 }
5187 }
5188
5189 if (Args.hasArg(options::OPT_fclangir))
5190 CmdArgs.push_back("-fclangir");
5191
5192 if (IsOpenMPDevice) {
5193 // We have to pass the triple of the host if compiling for an OpenMP device.
5194 std::string NormalizedTriple =
5195 C.getSingleOffloadToolChain<Action::OFK_Host>()
5196 ->getTriple()
5197 .normalize();
5198 CmdArgs.push_back("-aux-triple");
5199 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5200 }
5201
5202 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5203 Triple.getArch() == llvm::Triple::thumb)) {
5204 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5205 unsigned Version = 0;
5206 bool Failure =
5207 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5208 if (Failure || Version < 7)
5209 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5210 << TripleStr;
5211 }
5212
5213 // Push all default warning arguments that are specific to
5214 // the given target. These come before user provided warning options
5215 // are provided.
5216 TC.addClangWarningOptions(CmdArgs);
5217
5218 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5219 if (Triple.isSPIR() || Triple.isSPIRV())
5220 CmdArgs.push_back("-Wspir-compat");
5221
5222 // Select the appropriate action.
5223 RewriteKind rewriteKind = RK_None;
5224
5225 bool UnifiedLTO = false;
5226 if (IsUsingLTO) {
5227 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5228 options::OPT_fno_unified_lto, Triple.isPS());
5229 if (UnifiedLTO)
5230 CmdArgs.push_back("-funified-lto");
5231 }
5232
5233 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5234 // it claims when not running an assembler. Otherwise, clang would emit
5235 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5236 // flags while debugging something. That'd be somewhat inconvenient, and it's
5237 // also inconsistent with most other flags -- we don't warn on
5238 // -ffunction-sections not being used in -E mode either for example, even
5239 // though it's not really used either.
5240 if (!isa<AssembleJobAction>(JA)) {
5241 // The args claimed here should match the args used in
5242 // CollectArgsForIntegratedAssembler().
5243 if (TC.useIntegratedAs()) {
5244 Args.ClaimAllArgs(options::OPT_mrelax_all);
5245 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5246 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5247 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5248 switch (C.getDefaultToolChain().getArch()) {
5249 case llvm::Triple::arm:
5250 case llvm::Triple::armeb:
5251 case llvm::Triple::thumb:
5252 case llvm::Triple::thumbeb:
5253 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5254 break;
5255 default:
5256 break;
5257 }
5258 }
5259 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5260 Args.ClaimAllArgs(options::OPT_Xassembler);
5261 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5262 }
5263
5264 bool IsAMDSPIRVForHIPDevice =
5265 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5266 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5267
5268 if (isa<AnalyzeJobAction>(JA)) {
5269 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5270 CmdArgs.push_back("-analyze");
5271 } else if (isa<PreprocessJobAction>(JA)) {
5272 if (Output.getType() == types::TY_Dependencies)
5273 CmdArgs.push_back("-Eonly");
5274 else {
5275 CmdArgs.push_back("-E");
5276 if (Args.hasArg(options::OPT_rewrite_objc) &&
5277 !Args.hasArg(options::OPT_g_Group))
5278 CmdArgs.push_back("-P");
5279 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5280 CmdArgs.push_back("-fdirectives-only");
5281 }
5282 } else if (isa<AssembleJobAction>(JA)) {
5283 CmdArgs.push_back("-emit-obj");
5284
5285 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5286
5287 // Also ignore explicit -force_cpusubtype_ALL option.
5288 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5289 } else if (isa<PrecompileJobAction>(JA)) {
5290 if (JA.getType() == types::TY_Nothing)
5291 CmdArgs.push_back("-fsyntax-only");
5292 else if (JA.getType() == types::TY_ModuleFile) {
5293 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5294 ((Input.getType() == types::TY_CXXStdModule ||
5295 Input.getType() == types::TY_PP_CXXStdModule) &&
5296 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5297 CmdArgs.push_back("-emit-reduced-module-interface");
5298 else
5299 CmdArgs.push_back("-emit-module-interface");
5300 } else if (JA.getType() == types::TY_HeaderUnit)
5301 CmdArgs.push_back("-emit-header-unit");
5302 else if (!Args.hasArg(options::OPT_ignore_pch))
5303 CmdArgs.push_back("-emit-pch");
5304 } else if (isa<VerifyPCHJobAction>(JA)) {
5305 CmdArgs.push_back("-verify-pch");
5306 } else if (isa<ExtractAPIJobAction>(JA)) {
5307 assert(JA.getType() == types::TY_API_INFO &&
5308 "Extract API actions must generate a API information.");
5309 CmdArgs.push_back("-extract-api");
5310
5311 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5312 PrettySGFArg->render(Args, CmdArgs);
5313
5314 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5315
5316 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5317 ProductNameArg->render(Args, CmdArgs);
5318 if (Arg *ExtractAPIIgnoresFileArg =
5319 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5320 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5321 if (Arg *EmitExtensionSymbolGraphs =
5322 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5323 if (!SymbolGraphDirArg)
5324 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5325
5326 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5327 }
5328 if (SymbolGraphDirArg)
5329 SymbolGraphDirArg->render(Args, CmdArgs);
5330 } else {
5331 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5332 "Invalid action for clang tool.");
5333 if (JA.getType() == types::TY_Nothing) {
5334 CmdArgs.push_back("-fsyntax-only");
5335 } else if (JA.getType() == types::TY_LLVM_IR ||
5336 JA.getType() == types::TY_LTO_IR) {
5337 CmdArgs.push_back("-emit-llvm");
5338 } else if (JA.getType() == types::TY_LLVM_BC ||
5339 JA.getType() == types::TY_LTO_BC) {
5340 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5341 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5342 Args.hasArg(options::OPT_emit_llvm)) {
5343 CmdArgs.push_back("-emit-llvm");
5344 } else {
5345 CmdArgs.push_back("-emit-llvm-bc");
5346 }
5347 } else if (JA.getType() == types::TY_IFS ||
5348 JA.getType() == types::TY_IFS_CPP) {
5349 StringRef ArgStr =
5350 Args.hasArg(options::OPT_interface_stub_version_EQ)
5351 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5352 : "ifs-v1";
5353 CmdArgs.push_back("-emit-interface-stubs");
5354 CmdArgs.push_back(
5355 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5356 } else if (JA.getType() == types::TY_PP_Asm) {
5357 CmdArgs.push_back("-S");
5358 } else if (JA.getType() == types::TY_AST) {
5359 if (!Args.hasArg(options::OPT_ignore_pch))
5360 CmdArgs.push_back("-emit-pch");
5361 } else if (JA.getType() == types::TY_ModuleFile) {
5362 CmdArgs.push_back("-module-file-info");
5363 } else if (JA.getType() == types::TY_RewrittenObjC) {
5364 CmdArgs.push_back("-rewrite-objc");
5365 rewriteKind = RK_NonFragile;
5366 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5367 CmdArgs.push_back("-rewrite-objc");
5368 rewriteKind = RK_Fragile;
5369 } else if (JA.getType() == types::TY_CIR) {
5370 CmdArgs.push_back("-emit-cir");
5371 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5372 CmdArgs.push_back("-emit-obj");
5373 } else {
5374 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5375 }
5376
5377 // Preserve use-list order by default when emitting bitcode, so that
5378 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5379 // same result as running passes here. For LTO, we don't need to preserve
5380 // the use-list order, since serialization to bitcode is part of the flow.
5381 if (JA.getType() == types::TY_LLVM_BC)
5382 CmdArgs.push_back("-emit-llvm-uselists");
5383
5384 if (IsUsingLTO) {
5385 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5386 !Args.hasFlag(options::OPT_offload_new_driver,
5387 options::OPT_no_offload_new_driver,
5388 C.getActiveOffloadKinds() != Action::OFK_None) &&
5389 !Triple.isAMDGPU()) {
5390 D.Diag(diag::err_drv_unsupported_opt_for_target)
5391 << Args.getLastArg(options::OPT_foffload_lto,
5392 options::OPT_foffload_lto_EQ)
5393 ->getAsString(Args)
5394 << Triple.getTriple();
5395 } else if (Triple.isNVPTX() && !IsRDCMode &&
5397 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5398 << Args.getLastArg(options::OPT_foffload_lto,
5399 options::OPT_foffload_lto_EQ)
5400 ->getAsString(Args)
5401 << "-fno-gpu-rdc";
5402 } else {
5403 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5404 CmdArgs.push_back(Args.MakeArgString(
5405 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5406 // PS4 uses the legacy LTO API, which does not support some of the
5407 // features enabled by -flto-unit.
5408 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5409 CmdArgs.push_back("-flto-unit");
5410 }
5411 }
5412 }
5413
5414 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5415
5416 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5417 if (!types::isLLVMIR(Input.getType()))
5418 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5419 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5420 }
5421
5422 if (Triple.isPPC())
5423 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5424 options::OPT_mno_regnames);
5425
5426 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5427 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5428
5429 if (Args.getLastArg(options::OPT_save_temps_EQ))
5430 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5431
5432 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5433 options::OPT_fmemory_profile_EQ,
5434 options::OPT_fno_memory_profile);
5435 if (MemProfArg &&
5436 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5437 MemProfArg->render(Args, CmdArgs);
5438
5439 if (auto *MemProfUseArg =
5440 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5441 if (MemProfArg)
5442 D.Diag(diag::err_drv_argument_not_allowed_with)
5443 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5444 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5445 options::OPT_fprofile_generate_EQ))
5446 D.Diag(diag::err_drv_argument_not_allowed_with)
5447 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5448 MemProfUseArg->render(Args, CmdArgs);
5449 }
5450
5451 // Embed-bitcode option.
5452 // Only white-listed flags below are allowed to be embedded.
5453 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5455 // Add flags implied by -fembed-bitcode.
5456 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5457 // Disable all llvm IR level optimizations.
5458 CmdArgs.push_back("-disable-llvm-passes");
5459
5460 // Render target options.
5461 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5462
5463 // reject options that shouldn't be supported in bitcode
5464 // also reject kernel/kext
5465 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5466 options::OPT_mkernel,
5467 options::OPT_fapple_kext,
5468 options::OPT_ffunction_sections,
5469 options::OPT_fno_function_sections,
5470 options::OPT_fdata_sections,
5471 options::OPT_fno_data_sections,
5472 options::OPT_fbasic_block_sections_EQ,
5473 options::OPT_funique_internal_linkage_names,
5474 options::OPT_fno_unique_internal_linkage_names,
5475 options::OPT_funique_section_names,
5476 options::OPT_fno_unique_section_names,
5477 options::OPT_funique_basic_block_section_names,
5478 options::OPT_fno_unique_basic_block_section_names,
5479 options::OPT_mrestrict_it,
5480 options::OPT_mno_restrict_it,
5481 options::OPT_mstackrealign,
5482 options::OPT_mno_stackrealign,
5483 options::OPT_mstack_alignment,
5484 options::OPT_mcmodel_EQ,
5485 options::OPT_mlong_calls,
5486 options::OPT_mno_long_calls,
5487 options::OPT_ggnu_pubnames,
5488 options::OPT_gdwarf_aranges,
5489 options::OPT_fdebug_types_section,
5490 options::OPT_fno_debug_types_section,
5491 options::OPT_fdwarf_directory_asm,
5492 options::OPT_fno_dwarf_directory_asm,
5493 options::OPT_mrelax_all,
5494 options::OPT_mno_relax_all,
5495 options::OPT_ftrap_function_EQ,
5496 options::OPT_ffixed_r9,
5497 options::OPT_mfix_cortex_a53_835769,
5498 options::OPT_mno_fix_cortex_a53_835769,
5499 options::OPT_ffixed_x18,
5500 options::OPT_mglobal_merge,
5501 options::OPT_mno_global_merge,
5502 options::OPT_mred_zone,
5503 options::OPT_mno_red_zone,
5504 options::OPT_Wa_COMMA,
5505 options::OPT_Xassembler,
5506 options::OPT_mllvm,
5507 options::OPT_mmlir,
5508 };
5509 for (const auto &A : Args)
5510 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5511 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5512
5513 // Render the CodeGen options that need to be passed.
5514 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5515 options::OPT_fno_optimize_sibling_calls);
5516
5518 CmdArgs, JA);
5519
5520 // Render ABI arguments
5521 switch (TC.getArch()) {
5522 default: break;
5523 case llvm::Triple::arm:
5524 case llvm::Triple::armeb:
5525 case llvm::Triple::thumbeb:
5526 RenderARMABI(D, Triple, Args, CmdArgs);
5527 break;
5528 case llvm::Triple::aarch64:
5529 case llvm::Triple::aarch64_32:
5530 case llvm::Triple::aarch64_be:
5531 RenderAArch64ABI(Triple, Args, CmdArgs);
5532 break;
5533 }
5534
5535 // Input/Output file.
5536 if (Output.getType() == types::TY_Dependencies) {
5537 // Handled with other dependency code.
5538 } else if (Output.isFilename()) {
5539 CmdArgs.push_back("-o");
5540 CmdArgs.push_back(Output.getFilename());
5541 } else {
5542 assert(Output.isNothing() && "Input output.");
5543 }
5544
5545 for (const auto &II : Inputs) {
5546 addDashXForInput(Args, II, CmdArgs);
5547 if (II.isFilename())
5548 CmdArgs.push_back(II.getFilename());
5549 else
5550 II.getInputArg().renderAsInput(Args, CmdArgs);
5551 }
5552
5553 C.addCommand(std::make_unique<Command>(
5555 CmdArgs, Inputs, Output, D.getPrependArg()));
5556 return;
5557 }
5558
5559 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5560 CmdArgs.push_back("-fembed-bitcode=marker");
5561
5562 // We normally speed up the clang process a bit by skipping destructors at
5563 // exit, but when we're generating diagnostics we can rely on some of the
5564 // cleanup.
5565 if (!C.isForDiagnostics())
5566 CmdArgs.push_back("-disable-free");
5567 CmdArgs.push_back("-clear-ast-before-backend");
5568
5569#ifdef NDEBUG
5570 const bool IsAssertBuild = false;
5571#else
5572 const bool IsAssertBuild = true;
5573#endif
5574
5575 // Disable the verification pass in no-asserts builds unless otherwise
5576 // specified.
5577 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5578 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5579 CmdArgs.push_back("-disable-llvm-verifier");
5580 }
5581
5582 // Discard value names in no-asserts builds unless otherwise specified.
5583 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5584 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5585 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5586 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5587 return types::isLLVMIR(II.getType());
5588 })) {
5589 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5590 }
5591 CmdArgs.push_back("-discard-value-names");
5592 }
5593
5594 // Set the main file name, so that debug info works even with
5595 // -save-temps.
5596 CmdArgs.push_back("-main-file-name");
5597 CmdArgs.push_back(getBaseInputName(Args, Input));
5598
5599 // Some flags which affect the language (via preprocessor
5600 // defines).
5601 if (Args.hasArg(options::OPT_static))
5602 CmdArgs.push_back("-static-define");
5603
5604 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5605
5606 if (Args.hasArg(options::OPT_municode))
5607 CmdArgs.push_back("-DUNICODE");
5608
5609 if (isa<AnalyzeJobAction>(JA))
5610 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5611
5612 if (isa<AnalyzeJobAction>(JA) ||
5613 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5614 CmdArgs.push_back("-setup-static-analyzer");
5615
5616 // Enable compatilibily mode to avoid analyzer-config related errors.
5617 // Since we can't access frontend flags through hasArg, let's manually iterate
5618 // through them.
5619 bool FoundAnalyzerConfig = false;
5620 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5621 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5622 FoundAnalyzerConfig = true;
5623 break;
5624 }
5625 if (!FoundAnalyzerConfig)
5626 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5627 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5628 FoundAnalyzerConfig = true;
5629 break;
5630 }
5631 if (FoundAnalyzerConfig)
5632 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5633
5635
5636 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5637 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5638 if (FunctionAlignment) {
5639 CmdArgs.push_back("-function-alignment");
5640 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5641 }
5642
5643 if (const Arg *A =
5644 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5645 unsigned Value = 0;
5646 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5647 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5648 << A->getAsString(Args) << A->getValue();
5649 else if (!llvm::isPowerOf2_32(Value))
5650 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5651 << A->getAsString(Args) << A->getValue();
5652
5653 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5654 Twine(std::min(Value, 65536u))));
5655 }
5656
5657 // We support -falign-loops=N where N is a power of 2. GCC supports more
5658 // forms.
5659 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5660 unsigned Value = 0;
5661 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5662 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5663 << A->getAsString(Args) << A->getValue();
5664 else if (Value & (Value - 1))
5665 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5666 << A->getAsString(Args) << A->getValue();
5667 // Treat =0 as unspecified (use the target preference).
5668 if (Value)
5669 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5670 Twine(std::min(Value, 65536u))));
5671 }
5672
5673 if (Triple.isOSzOS()) {
5674 // On z/OS some of the system header feature macros need to
5675 // be defined to enable most cross platform projects to build
5676 // successfully. Ths include the libc++ library. A
5677 // complicating factor is that users can define these
5678 // macros to the same or different values. We need to add
5679 // the definition for these macros to the compilation command
5680 // if the user hasn't already defined them.
5681
5682 auto findMacroDefinition = [&](const std::string &Macro) {
5683 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5684 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5685 return M == Macro || M.find(Macro + '=') != std::string::npos;
5686 });
5687 };
5688
5689 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5690 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5691 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5692 // _OPEN_DEFAULT is required for XL compat
5693 if (!findMacroDefinition("_OPEN_DEFAULT"))
5694 CmdArgs.push_back("-D_OPEN_DEFAULT");
5695 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5696 // _XOPEN_SOURCE=600 is required for libcxx.
5697 if (!findMacroDefinition("_XOPEN_SOURCE"))
5698 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5699 }
5700 }
5701
5702 llvm::Reloc::Model RelocationModel;
5703 unsigned PICLevel;
5704 bool IsPIE;
5705 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5706 Arg *LastPICDataRelArg =
5707 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5708 options::OPT_mpic_data_is_text_relative);
5709 bool NoPICDataIsTextRelative = false;
5710 if (LastPICDataRelArg) {
5711 if (LastPICDataRelArg->getOption().matches(
5712 options::OPT_mno_pic_data_is_text_relative)) {
5713 NoPICDataIsTextRelative = true;
5714 if (!PICLevel)
5715 D.Diag(diag::err_drv_argument_only_allowed_with)
5716 << "-mno-pic-data-is-text-relative"
5717 << "-fpic/-fpie";
5718 }
5719 if (!Triple.isSystemZ())
5720 D.Diag(diag::err_drv_unsupported_opt_for_target)
5721 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5722 : "-mpic-data-is-text-relative")
5723 << RawTriple.str();
5724 }
5725
5726 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5727 RelocationModel == llvm::Reloc::ROPI_RWPI;
5728 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5729 RelocationModel == llvm::Reloc::ROPI_RWPI;
5730
5731 if (Args.hasArg(options::OPT_mcmse) &&
5732 !Args.hasArg(options::OPT_fallow_unsupported)) {
5733 if (IsROPI)
5734 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5735 if (IsRWPI)
5736 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5737 }
5738
5739 if (IsROPI && types::isCXX(Input.getType()) &&
5740 !Args.hasArg(options::OPT_fallow_unsupported))
5741 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5742
5743 const char *RMName = RelocationModelName(RelocationModel);
5744 if (RMName) {
5745 CmdArgs.push_back("-mrelocation-model");
5746 CmdArgs.push_back(RMName);
5747 }
5748 if (PICLevel > 0) {
5749 CmdArgs.push_back("-pic-level");
5750 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5751 if (IsPIE)
5752 CmdArgs.push_back("-pic-is-pie");
5753 if (NoPICDataIsTextRelative)
5754 CmdArgs.push_back("-mcmodel=medium");
5755 }
5756
5757 if (RelocationModel == llvm::Reloc::ROPI ||
5758 RelocationModel == llvm::Reloc::ROPI_RWPI)
5759 CmdArgs.push_back("-fropi");
5760 if (RelocationModel == llvm::Reloc::RWPI ||
5761 RelocationModel == llvm::Reloc::ROPI_RWPI)
5762 CmdArgs.push_back("-frwpi");
5763
5764 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5765 CmdArgs.push_back("-meabi");
5766 CmdArgs.push_back(A->getValue());
5767 }
5768
5769 // -fsemantic-interposition is forwarded to CC1: set the
5770 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5771 // make default visibility external linkage definitions dso_preemptable.
5772 //
5773 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5774 // aliases (make default visibility external linkage definitions dso_local).
5775 // This is the CC1 default for ELF to match COFF/Mach-O.
5776 //
5777 // Otherwise use Clang's traditional behavior: like
5778 // -fno-semantic-interposition but local aliases are not used. So references
5779 // can be interposed if not optimized out.
5780 if (Triple.isOSBinFormatELF()) {
5781 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5782 options::OPT_fno_semantic_interposition);
5783 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5784 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5785 bool SupportsLocalAlias =
5786 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5787 if (!A)
5788 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5789 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5790 A->render(Args, CmdArgs);
5791 else if (!SupportsLocalAlias)
5792 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5793 }
5794 }
5795
5796 {
5797 std::string Model;
5798 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5799 if (!TC.isThreadModelSupported(A->getValue()))
5800 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5801 << A->getValue() << A->getAsString(Args);
5802 Model = A->getValue();
5803 } else
5804 Model = TC.getThreadModel();
5805 if (Model != "posix") {
5806 CmdArgs.push_back("-mthread-model");
5807 CmdArgs.push_back(Args.MakeArgString(Model));
5808 }
5809 }
5810
5811 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5812 StringRef Name = A->getValue();
5813 if (Name == "SVML") {
5814 if (Triple.getArch() != llvm::Triple::x86 &&
5815 Triple.getArch() != llvm::Triple::x86_64)
5816 D.Diag(diag::err_drv_unsupported_opt_for_target)
5817 << Name << Triple.getArchName();
5818 } else if (Name == "AMDLIBM") {
5819 if (Triple.getArch() != llvm::Triple::x86 &&
5820 Triple.getArch() != llvm::Triple::x86_64)
5821 D.Diag(diag::err_drv_unsupported_opt_for_target)
5822 << Name << Triple.getArchName();
5823 } else if (Name == "libmvec") {
5824 if (Triple.getArch() != llvm::Triple::x86 &&
5825 Triple.getArch() != llvm::Triple::x86_64 &&
5826 Triple.getArch() != llvm::Triple::aarch64 &&
5827 Triple.getArch() != llvm::Triple::aarch64_be)
5828 D.Diag(diag::err_drv_unsupported_opt_for_target)
5829 << Name << Triple.getArchName();
5830 } else if (Name == "SLEEF" || Name == "ArmPL") {
5831 if (Triple.getArch() != llvm::Triple::aarch64 &&
5832 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
5833 D.Diag(diag::err_drv_unsupported_opt_for_target)
5834 << Name << Triple.getArchName();
5835 }
5836 A->render(Args, CmdArgs);
5837 }
5838
5839 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5840 options::OPT_fno_merge_all_constants, false))
5841 CmdArgs.push_back("-fmerge-all-constants");
5842
5843 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5844 options::OPT_fno_delete_null_pointer_checks);
5845
5846 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
5847 options::OPT_fno_lifetime_dse);
5848
5849 // LLVM Code Generator Options.
5850
5851 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5852 if (!Triple.isOSAIX() || Triple.isPPC32())
5853 D.Diag(diag::err_drv_unsupported_opt_for_target)
5854 << A->getSpelling() << RawTriple.str();
5855 CmdArgs.push_back("-mabi=quadword-atomics");
5856 }
5857
5858 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5859 // Emit the unsupported option error until the Clang's library integration
5860 // support for 128-bit long double is available for AIX.
5861 if (Triple.isOSAIX())
5862 D.Diag(diag::err_drv_unsupported_opt_for_target)
5863 << A->getSpelling() << RawTriple.str();
5864 }
5865
5866 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5867 StringRef V = A->getValue(), V1 = V;
5868 unsigned Size;
5869 if (V1.consumeInteger(10, Size) || !V1.empty())
5870 D.Diag(diag::err_drv_invalid_argument_to_option)
5871 << V << A->getOption().getName();
5872 else
5873 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5874 }
5875
5876 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5877 options::OPT_fno_jump_tables);
5878 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5879 options::OPT_fno_profile_sample_accurate);
5880 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5881 options::OPT_fno_preserve_as_comments);
5882
5883 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5884 CmdArgs.push_back("-mregparm");
5885 CmdArgs.push_back(A->getValue());
5886 }
5887
5888 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5889 options::OPT_msvr4_struct_return)) {
5890 if (!TC.getTriple().isPPC32()) {
5891 D.Diag(diag::err_drv_unsupported_opt_for_target)
5892 << A->getSpelling() << RawTriple.str();
5893 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5894 CmdArgs.push_back("-maix-struct-return");
5895 } else {
5896 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5897 CmdArgs.push_back("-msvr4-struct-return");
5898 }
5899 }
5900
5901 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5902 options::OPT_freg_struct_return)) {
5903 if (TC.getArch() != llvm::Triple::x86) {
5904 D.Diag(diag::err_drv_unsupported_opt_for_target)
5905 << A->getSpelling() << RawTriple.str();
5906 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5907 CmdArgs.push_back("-fpcc-struct-return");
5908 } else {
5909 assert(A->getOption().matches(options::OPT_freg_struct_return));
5910 CmdArgs.push_back("-freg-struct-return");
5911 }
5912 }
5913
5914 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5915 if (Triple.getArch() == llvm::Triple::m68k)
5916 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5917 else
5918 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5919 }
5920
5921 if (Args.hasArg(options::OPT_fenable_matrix)) {
5922 // enable-matrix is needed by both the LangOpts and by LLVM.
5923 CmdArgs.push_back("-fenable-matrix");
5924 CmdArgs.push_back("-mllvm");
5925 CmdArgs.push_back("-enable-matrix");
5926 // Only handle default layout if matrix is enabled
5927 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
5928 StringRef Val = A->getValue();
5929 if (Val == "row-major" || Val == "column-major") {
5930 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
5931 CmdArgs.push_back("-mllvm");
5932 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
5933
5934 } else {
5935 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
5936 }
5937 }
5938 }
5939
5941 getFramePointerKind(Args, RawTriple);
5942 const char *FPKeepKindStr = nullptr;
5943 switch (FPKeepKind) {
5945 FPKeepKindStr = "-mframe-pointer=none";
5946 break;
5948 FPKeepKindStr = "-mframe-pointer=reserved";
5949 break;
5951 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
5952 break;
5954 FPKeepKindStr = "-mframe-pointer=non-leaf";
5955 break;
5957 FPKeepKindStr = "-mframe-pointer=all";
5958 break;
5959 }
5960 assert(FPKeepKindStr && "unknown FramePointerKind");
5961 CmdArgs.push_back(FPKeepKindStr);
5962
5963 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5964 options::OPT_fno_zero_initialized_in_bss);
5965
5966 bool OFastEnabled = isOptimizationLevelFast(Args);
5967 if (Args.hasArg(options::OPT_Ofast))
5968 D.Diag(diag::warn_drv_deprecated_arg_ofast);
5969 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5970 // enabled. This alias option is being used to simplify the hasFlag logic.
5971 OptSpecifier StrictAliasingAliasOption =
5972 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5973 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5974 // doesn't do any TBAA.
5975 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5976 options::OPT_fno_strict_aliasing,
5977 !IsWindowsMSVC && !IsUEFI))
5978 CmdArgs.push_back("-relaxed-aliasing");
5979 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
5980 false))
5981 CmdArgs.push_back("-no-pointer-tbaa");
5982 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5983 options::OPT_fno_struct_path_tbaa, true))
5984 CmdArgs.push_back("-no-struct-path-tbaa");
5985
5986 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
5987 options::OPT_fno_strict_bool,
5988 options::OPT_fno_strict_bool_EQ)) {
5989 StringRef BFM = "";
5990 if (A->getOption().matches(options::OPT_fstrict_bool))
5991 BFM = "strict";
5992 else if (A->getOption().matches(options::OPT_fno_strict_bool))
5993 BFM = "nonstrict";
5994 else if (A->getValue() == StringRef("truncate"))
5995 BFM = "truncate";
5996 else if (A->getValue() == StringRef("nonzero"))
5997 BFM = "nonzero";
5998 else
5999 D.Diag(diag::err_drv_invalid_value)
6000 << A->getAsString(Args) << A->getValue();
6001 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6002 } else if (KernelOrKext) {
6003 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6004 CmdArgs.push_back("-load-bool-from-mem=truncate");
6005 }
6006
6007 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6008 options::OPT_fno_strict_enums);
6009 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6010 options::OPT_fno_strict_return);
6011 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6012 options::OPT_fno_allow_editor_placeholders);
6013 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6014 options::OPT_fno_strict_vtable_pointers);
6015 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6016 options::OPT_fno_force_emit_vtables);
6017 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6018 options::OPT_fno_optimize_sibling_calls);
6019 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6020 options::OPT_fno_escaping_block_tail_calls);
6021
6022 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6023 options::OPT_fno_fine_grained_bitfield_accesses);
6024
6025 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6026 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6027
6028 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6029 options::OPT_fno_experimental_omit_vtable_rtti);
6030
6031 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6032 options::OPT_fno_disable_block_signature_string);
6033
6034 // Handle segmented stacks.
6035 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6036 options::OPT_fno_split_stack);
6037
6038 // -fprotect-parens=0 is default.
6039 if (Args.hasFlag(options::OPT_fprotect_parens,
6040 options::OPT_fno_protect_parens, false))
6041 CmdArgs.push_back("-fprotect-parens");
6042
6043 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6044
6045 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6046 options::OPT_fno_atomic_remote_memory);
6047 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6048 options::OPT_fno_atomic_fine_grained_memory);
6049 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6050 options::OPT_fno_atomic_ignore_denormal_mode);
6051
6052 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6053 const llvm::Triple::ArchType Arch = TC.getArch();
6054 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6055 StringRef V = A->getValue();
6056 if (V == "64")
6057 CmdArgs.push_back("-fextend-arguments=64");
6058 else if (V != "32")
6059 D.Diag(diag::err_drv_invalid_argument_to_option)
6060 << A->getValue() << A->getOption().getName();
6061 } else
6062 D.Diag(diag::err_drv_unsupported_opt_for_target)
6063 << A->getOption().getName() << TripleStr;
6064 }
6065
6066 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6067 if (TC.getArch() == llvm::Triple::avr)
6068 A->render(Args, CmdArgs);
6069 else
6070 D.Diag(diag::err_drv_unsupported_opt_for_target)
6071 << A->getAsString(Args) << TripleStr;
6072 }
6073
6074 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6075 if (TC.getTriple().isX86())
6076 A->render(Args, CmdArgs);
6077 else if (TC.getTriple().isPPC() &&
6078 (A->getOption().getID() != options::OPT_mlong_double_80))
6079 A->render(Args, CmdArgs);
6080 else
6081 D.Diag(diag::err_drv_unsupported_opt_for_target)
6082 << A->getAsString(Args) << TripleStr;
6083 }
6084
6085 // Decide whether to use verbose asm. Verbose assembly is the default on
6086 // toolchains which have the integrated assembler on by default.
6087 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6088 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6089 IsIntegratedAssemblerDefault))
6090 CmdArgs.push_back("-fno-verbose-asm");
6091
6092 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6093 // use that to indicate the MC default in the backend.
6094 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6095 StringRef V = A->getValue();
6096 unsigned Num;
6097 if (V == "none")
6098 A->render(Args, CmdArgs);
6099 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6100 (V.empty() || (V.consume_front(".") &&
6101 !V.consumeInteger(10, Num) && V.empty())))
6102 A->render(Args, CmdArgs);
6103 else
6104 D.Diag(diag::err_drv_invalid_argument_to_option)
6105 << A->getValue() << A->getOption().getName();
6106 }
6107
6108 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6109 // option to disable integrated-as explicitly.
6111 CmdArgs.push_back("-no-integrated-as");
6112
6113 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6114 CmdArgs.push_back("-mdebug-pass");
6115 CmdArgs.push_back("Structure");
6116 }
6117 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6118 CmdArgs.push_back("-mdebug-pass");
6119 CmdArgs.push_back("Arguments");
6120 }
6121
6122 // Enable -mconstructor-aliases except on darwin, where we have to work around
6123 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6124 // code, where aliases aren't supported.
6125 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6126 CmdArgs.push_back("-mconstructor-aliases");
6127
6128 // Darwin's kernel doesn't support guard variables; just die if we
6129 // try to use them.
6130 if (KernelOrKext && RawTriple.isOSDarwin())
6131 CmdArgs.push_back("-fforbid-guard-variables");
6132
6133 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6134 options::OPT_mno_ms_bitfields)) {
6135 if (A->getOption().matches(options::OPT_mms_bitfields))
6136 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6137 else
6138 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6139 }
6140
6141 if (Triple.isOSCygMing()) {
6142 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6143 options::OPT_fno_auto_import);
6144 }
6145
6146 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6147 Triple.isX86() && IsWindowsMSVC))
6148 CmdArgs.push_back("-fms-volatile");
6149
6150 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6151 // defaults to -fno-direct-access-external-data. Pass the option if different
6152 // from the default.
6153 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6154 options::OPT_fno_direct_access_external_data)) {
6155 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6156 (PICLevel == 0))
6157 A->render(Args, CmdArgs);
6158 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6159 // Some targets default to -fno-direct-access-external-data even for
6160 // -fno-pic.
6161 CmdArgs.push_back("-fno-direct-access-external-data");
6162 }
6163
6164 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6165 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6166
6167 // -fhosted is default.
6168 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6169 // use Freestanding.
6170 bool Freestanding =
6171 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6172 KernelOrKext;
6173 if (Freestanding)
6174 CmdArgs.push_back("-ffreestanding");
6175
6176 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6177
6178 const char *OffloadArch = JA.getOffloadingArch();
6179 auto SanitizeArgs = TC.getSanitizerArgs(Args, OffloadArch ? OffloadArch : "",
6181 Args.AddLastArg(CmdArgs,
6182 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6183
6184 // This is a coarse approximation of what llvm-gcc actually does, both
6185 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6186 // complicated ways.
6187 bool IsAsyncUnwindTablesDefault =
6189 bool IsSyncUnwindTablesDefault =
6191
6192 bool AsyncUnwindTables = Args.hasFlag(
6193 options::OPT_fasynchronous_unwind_tables,
6194 options::OPT_fno_asynchronous_unwind_tables,
6195 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6196 !Freestanding);
6197 bool UnwindTables =
6198 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6199 IsSyncUnwindTablesDefault && !Freestanding);
6200 if (AsyncUnwindTables)
6201 CmdArgs.push_back("-funwind-tables=2");
6202 else if (UnwindTables)
6203 CmdArgs.push_back("-funwind-tables=1");
6204
6205 // Sframe unwind tables are independent of the other types. Although also
6206 // defined for aarch64, only x86_64 support is implemented at the moment.
6207 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6208 if (Triple.isOSBinFormatELF() && Triple.isX86())
6209 CmdArgs.push_back("--gsframe");
6210 else
6211 D.Diag(diag::err_drv_unsupported_opt_for_target)
6212 << A->getOption().getName() << TripleStr;
6213 }
6214
6215 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6216 // `--gpu-use-aux-triple-only` is specified.
6217 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6218 const ArgList &HostArgs =
6219 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
6220 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6221 if (!HostCPU.empty()) {
6222 CmdArgs.push_back("-aux-target-cpu");
6223 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6224 }
6225 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6226 /*ForAS*/ false, /*IsAux*/ true);
6227 }
6228
6229 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
6230
6231 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6232
6233 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6234 StringRef Value = A->getValue();
6235 unsigned TLSSize = 0;
6236 Value.getAsInteger(10, TLSSize);
6237 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6238 D.Diag(diag::err_drv_unsupported_opt_for_target)
6239 << A->getOption().getName() << TripleStr;
6240 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6241 D.Diag(diag::err_drv_invalid_int_value)
6242 << A->getOption().getName() << Value;
6243 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6244 }
6245
6246 if (isTLSDESCEnabled(TC, Args))
6247 CmdArgs.push_back("-enable-tlsdesc");
6248
6249 // Add the target cpu
6250 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6251 if (!CPU.empty()) {
6252 CmdArgs.push_back("-target-cpu");
6253 CmdArgs.push_back(Args.MakeArgString(CPU));
6254 }
6255
6256 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6257
6258 // Add clang-cl arguments.
6259 types::ID InputType = Input.getType();
6260 if (D.IsCLMode())
6261 AddClangCLArgs(Args, InputType, CmdArgs);
6262
6263 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6264 llvm::codegenoptions::NoDebugInfo;
6266 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6267 DebugInfoKind, DwarfFission);
6268
6269 // Add the split debug info name to the command lines here so we
6270 // can propagate it to the backend.
6271 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6272 (TC.getTriple().isOSBinFormatELF() ||
6273 TC.getTriple().isOSBinFormatWasm() ||
6274 TC.getTriple().isOSBinFormatCOFF()) &&
6277 if (SplitDWARF) {
6278 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6279 CmdArgs.push_back("-split-dwarf-file");
6280 CmdArgs.push_back(SplitDWARFOut);
6281 if (DwarfFission == DwarfFissionKind::Split) {
6282 CmdArgs.push_back("-split-dwarf-output");
6283 CmdArgs.push_back(SplitDWARFOut);
6284 }
6285 }
6286
6287 // Pass the linker version in use.
6288 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6289 CmdArgs.push_back("-target-linker-version");
6290 CmdArgs.push_back(A->getValue());
6291 }
6292
6293 // Explicitly error on some things we know we don't support and can't just
6294 // ignore.
6295 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6296 Arg *Unsupported;
6297 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6298 TC.getArch() == llvm::Triple::x86) {
6299 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6300 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6301 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6302 << Unsupported->getOption().getName();
6303 }
6304 // The faltivec option has been superseded by the maltivec option.
6305 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6306 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6307 << Unsupported->getOption().getName()
6308 << "please use -maltivec and include altivec.h explicitly";
6309 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6310 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6311 << Unsupported->getOption().getName() << "please use -mno-altivec";
6312 }
6313
6314 Args.AddAllArgs(CmdArgs, options::OPT_v);
6315
6316 if (Args.getLastArg(options::OPT_H)) {
6317 CmdArgs.push_back("-H");
6318 CmdArgs.push_back("-sys-header-deps");
6319 }
6320 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6321
6323 CmdArgs.push_back("-header-include-file");
6324 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6325 ? D.CCPrintHeadersFilename.c_str()
6326 : "-");
6327 CmdArgs.push_back("-sys-header-deps");
6328 CmdArgs.push_back(Args.MakeArgString(
6329 "-header-include-format=" +
6331 CmdArgs.push_back(Args.MakeArgString(
6332 "-header-include-filtering=" +
6334 }
6335 Args.AddLastArg(CmdArgs, options::OPT_P);
6336 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6337
6338 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6339 CmdArgs.push_back("-diagnostic-log-file");
6340 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6341 ? D.CCLogDiagnosticsFilename.c_str()
6342 : "-");
6343 }
6344
6345 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6346 // crashes.
6347 if (D.CCGenDiagnostics)
6348 CmdArgs.push_back("-disable-pragma-debug-crash");
6349
6350 // Allow backend to put its diagnostic files in the same place as frontend
6351 // crash diagnostics files.
6352 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6353 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6354 CmdArgs.push_back("-mllvm");
6355 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6356 }
6357
6358 addSeparateSectionFlags(Triple, Args, CmdArgs);
6359
6360 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6361 options::OPT_fno_basic_block_address_map)) {
6362 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6363 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6364 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6365 A->render(Args, CmdArgs);
6366 } else {
6367 D.Diag(diag::err_drv_unsupported_opt_for_target)
6368 << A->getAsString(Args) << TripleStr;
6369 }
6370 }
6371
6372 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6373 StringRef Val = A->getValue();
6374 if (Val == "labels") {
6375 D.Diag(diag::warn_drv_deprecated_arg)
6376 << A->getAsString(Args) << /*hasReplacement=*/true
6377 << "-fbasic-block-address-map";
6378 CmdArgs.push_back("-fbasic-block-address-map");
6379 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6380 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6381 D.Diag(diag::err_drv_invalid_value)
6382 << A->getAsString(Args) << A->getValue();
6383 else
6384 A->render(Args, CmdArgs);
6385 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6386 // "all" is not supported on AArch64 since branch relaxation creates new
6387 // basic blocks for some cross-section branches.
6388 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6389 D.Diag(diag::err_drv_invalid_value)
6390 << A->getAsString(Args) << A->getValue();
6391 else
6392 A->render(Args, CmdArgs);
6393 } else if (Triple.isNVPTX()) {
6394 // Do not pass the option to the GPU compilation. We still want it enabled
6395 // for the host-side compilation, so seeing it here is not an error.
6396 } else if (Val != "none") {
6397 // =none is allowed everywhere. It's useful for overriding the option
6398 // and is the same as not specifying the option.
6399 D.Diag(diag::err_drv_unsupported_opt_for_target)
6400 << A->getAsString(Args) << TripleStr;
6401 }
6402 }
6403
6404 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6405 options::OPT_fno_unique_section_names);
6406 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6407 options::OPT_fno_separate_named_sections);
6408 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6409 options::OPT_fno_unique_internal_linkage_names);
6410 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6411 options::OPT_fno_unique_basic_block_section_names);
6412
6413 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6414 options::OPT_fno_split_machine_functions)) {
6415 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
6416 // This codegen pass is only available on x86 and AArch64 ELF targets.
6417 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6418 A->render(Args, CmdArgs);
6419 else
6420 D.Diag(diag::err_drv_unsupported_opt_for_target)
6421 << A->getAsString(Args) << TripleStr;
6422 }
6423 }
6424
6425 if (Arg *A =
6426 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6427 options::OPT_fno_partition_static_data_sections)) {
6428 if (!A->getOption().matches(
6429 options::OPT_fno_partition_static_data_sections)) {
6430 // This codegen pass is only available on x86 and AArch64 ELF targets.
6431 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6432 A->render(Args, CmdArgs);
6433 CmdArgs.push_back("-mllvm");
6434 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6435 } else
6436 D.Diag(diag::err_drv_unsupported_opt_for_target)
6437 << A->getAsString(Args) << TripleStr;
6438 }
6439 }
6440
6441 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6442 options::OPT_finstrument_functions_after_inlining,
6443 options::OPT_finstrument_function_entry_bare);
6444 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6445 options::OPT_fno_convergent_functions);
6446
6447 // NVPTX doesn't support PGO or coverage
6448 if (!Triple.isNVPTX())
6449 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6450
6451 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6452
6453 if (getLastProfileSampleUseArg(Args) &&
6454 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6455 options::OPT_fno_sample_profile_use_profi, true)) {
6456 CmdArgs.push_back("-mllvm");
6457 CmdArgs.push_back("-sample-profile-use-profi");
6458 }
6459
6460 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6461 if (RawTriple.isPS() &&
6462 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6463 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6464 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6465 }
6466
6467 // Pass options for controlling the default header search paths.
6468 if (Args.hasArg(options::OPT_nostdinc)) {
6469 CmdArgs.push_back("-nostdsysteminc");
6470 CmdArgs.push_back("-nobuiltininc");
6471 } else {
6472 if (Args.hasArg(options::OPT_nostdlibinc))
6473 CmdArgs.push_back("-nostdsysteminc");
6474 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6475 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6476 }
6477
6478 // Pass the path to compiler resource files.
6479 CmdArgs.push_back("-resource-dir");
6480 CmdArgs.push_back(D.ResourceDir.c_str());
6481
6482 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6483
6484 // Add preprocessing options like -I, -D, etc. if we are using the
6485 // preprocessor.
6486 //
6487 // FIXME: Support -fpreprocessed
6489 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6490
6491 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6492 // that "The compiler can only warn and ignore the option if not recognized".
6493 // When building with ccache, it will pass -D options to clang even on
6494 // preprocessed inputs and configure concludes that -fPIC is not supported.
6495 Args.ClaimAllArgs(options::OPT_D);
6496
6497 // Warn about ignored options to clang.
6498 for (const Arg *A :
6499 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6500 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6501 A->claim();
6502 }
6503
6504 for (const Arg *A :
6505 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6506 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6507 A->claim();
6508 }
6509
6510 claimNoWarnArgs(Args);
6511
6512 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6513
6514 for (const Arg *A :
6515 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6516 A->claim();
6517 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6518 unsigned WarningNumber;
6519 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6520 D.Diag(diag::err_drv_invalid_int_value)
6521 << A->getAsString(Args) << A->getValue();
6522 continue;
6523 }
6524
6525 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6526 CmdArgs.push_back(Args.MakeArgString(
6527 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6528 }
6529 continue;
6530 }
6531 A->render(Args, CmdArgs);
6532 }
6533
6534 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6535
6536 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6537 CmdArgs.push_back("-pedantic");
6538 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6539 Args.AddLastArg(CmdArgs, options::OPT_w);
6540
6541 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6542 options::OPT_fno_fixed_point);
6543
6544 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6545 options::OPT_fno_experimental_overflow_behavior_types);
6546
6547 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6548 A->render(Args, CmdArgs);
6549
6550 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6551 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6552
6553 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6554 options::OPT_fno_experimental_omit_vtable_rtti);
6555
6556 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6557 A->render(Args, CmdArgs);
6558
6559 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6560 // (-ansi is equivalent to -std=c89 or -std=c++98).
6561 //
6562 // If a std is supplied, only add -trigraphs if it follows the
6563 // option.
6564 bool ImplyVCPPCVer = false;
6565 bool ImplyVCPPCXXVer = false;
6566 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6567 if (Std) {
6568 if (Std->getOption().matches(options::OPT_ansi))
6569 if (types::isCXX(InputType))
6570 CmdArgs.push_back("-std=c++98");
6571 else
6572 CmdArgs.push_back("-std=c89");
6573 else {
6574 if (IsSYCL) {
6575 const LangStandard *LangStd =
6576 LangStandard::getLangStandardForName(Std->getValue());
6577 if (LangStd) {
6578 // Use of -std= with 'C' is not supported for SYCL.
6579 if (LangStd->getLanguage() == Language::C)
6580 D.Diag(diag::err_drv_argument_not_allowed_with)
6581 << Std->getAsString(Args) << "-fsycl";
6582 // SYCL requires C++17 or later.
6583 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6584 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6585 }
6586 }
6587 Std->render(Args, CmdArgs);
6588 }
6589
6590 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6591 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6592 options::OPT_ftrigraphs,
6593 options::OPT_fno_trigraphs))
6594 if (A != Std)
6595 A->render(Args, CmdArgs);
6596 } else {
6597 // Honor -std-default.
6598 //
6599 // FIXME: Clang doesn't correctly handle -std= when the input language
6600 // doesn't match. For the time being just ignore this for C++ inputs;
6601 // eventually we want to do all the standard defaulting here instead of
6602 // splitting it between the driver and clang -cc1.
6603 if (!types::isCXX(InputType)) {
6604 if (!Args.hasArg(options::OPT__SLASH_std)) {
6605 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6606 /*Joined=*/true);
6607 } else
6608 ImplyVCPPCVer = true;
6609 }
6610 else if (IsWindowsMSVC)
6611 ImplyVCPPCXXVer = true;
6612
6613 if (IsSYCL && types::isCXX(InputType) &&
6614 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6615 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6616 // on the command line will override. On Windows MSVC, this is handled
6617 // by the ImplyVCPPCXXVer path below.
6618 CmdArgs.push_back("-std=c++17");
6619
6620 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6621 options::OPT_fno_trigraphs);
6622 }
6623
6624 // GCC's behavior for -Wwrite-strings is a bit strange:
6625 // * In C, this "warning flag" changes the types of string literals from
6626 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6627 // for the discarded qualifier.
6628 // * In C++, this is just a normal warning flag.
6629 //
6630 // Implementing this warning correctly in C is hard, so we follow GCC's
6631 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6632 // a non-const char* in C, rather than using this crude hack.
6633 if (!types::isCXX(InputType)) {
6634 // FIXME: This should behave just like a warning flag, and thus should also
6635 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6636 Arg *WriteStrings =
6637 Args.getLastArg(options::OPT_Wwrite_strings,
6638 options::OPT_Wno_write_strings, options::OPT_w);
6639 if (WriteStrings &&
6640 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6641 CmdArgs.push_back("-fconst-strings");
6642 }
6643
6644 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6645 // during C++ compilation, which it is by default. GCC keeps this define even
6646 // in the presence of '-w', match this behavior bug-for-bug.
6647 if (types::isCXX(InputType) &&
6648 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6649 true)) {
6650 CmdArgs.push_back("-fdeprecated-macro");
6651 }
6652
6653 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6654 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6655 if (Asm->getOption().matches(options::OPT_fasm))
6656 CmdArgs.push_back("-fgnu-keywords");
6657 else
6658 CmdArgs.push_back("-fno-gnu-keywords");
6659 }
6660
6661 if (!ShouldEnableAutolink(Args, TC, JA))
6662 CmdArgs.push_back("-fno-autolink");
6663
6664 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6665 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6666 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6667 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6668
6669 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6670
6671 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6672 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6673
6674 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6675 CmdArgs.push_back("-fbracket-depth");
6676 CmdArgs.push_back(A->getValue());
6677 }
6678
6679 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6680 options::OPT_Wlarge_by_value_copy_def)) {
6681 if (A->getNumValues()) {
6682 StringRef bytes = A->getValue();
6683 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6684 } else
6685 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6686 }
6687
6688 if (Args.hasArg(options::OPT_relocatable_pch))
6689 CmdArgs.push_back("-relocatable-pch");
6690
6691 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6692 static const char *kCFABIs[] = {
6693 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6694 };
6695
6696 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6697 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6698 else
6699 A->render(Args, CmdArgs);
6700 }
6701
6702 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6703 CmdArgs.push_back("-fconstant-string-class");
6704 CmdArgs.push_back(A->getValue());
6705 }
6706
6707 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6708 CmdArgs.push_back("-fconstant-array-class");
6709 CmdArgs.push_back(A->getValue());
6710 }
6711 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6712 CmdArgs.push_back("-fconstant-dictionary-class");
6713 CmdArgs.push_back(A->getValue());
6714 }
6715 if (Arg *A =
6716 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6717 CmdArgs.push_back("-fconstant-integer-number-class");
6718 CmdArgs.push_back(A->getValue());
6719 }
6720 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6721 CmdArgs.push_back("-fconstant-float-number-class");
6722 CmdArgs.push_back(A->getValue());
6723 }
6724 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6725 CmdArgs.push_back("-fconstant-double-number-class");
6726 CmdArgs.push_back(A->getValue());
6727 }
6728
6729 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6730 CmdArgs.push_back("-ftabstop");
6731 CmdArgs.push_back(A->getValue());
6732 }
6733
6734 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
6735 options::OPT_fno_experimental_call_graph_section, false))
6736 CmdArgs.push_back("-fexperimental-call-graph-section");
6737
6738 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6739 options::OPT_fno_stack_size_section);
6740
6741 if (Args.hasArg(options::OPT_fstack_usage)) {
6742 CmdArgs.push_back("-stack-usage-file");
6743
6744 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6745 SmallString<128> OutputFilename(OutputOpt->getValue());
6746 llvm::sys::path::replace_extension(OutputFilename, "su");
6747 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6748 } else
6749 CmdArgs.push_back(
6750 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6751 }
6752
6753 CmdArgs.push_back("-ferror-limit");
6754 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6755 CmdArgs.push_back(A->getValue());
6756 else
6757 CmdArgs.push_back("19");
6758
6759 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6760 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6761 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6762 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6763 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6764
6765 // Pass -fmessage-length=.
6766 unsigned MessageLength = 0;
6767 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6768 StringRef V(A->getValue());
6769 if (V.getAsInteger(0, MessageLength))
6770 D.Diag(diag::err_drv_invalid_argument_to_option)
6771 << V << A->getOption().getName();
6772 } else {
6773 // If -fmessage-length=N was not specified, determine whether this is a
6774 // terminal and, if so, implicitly define -fmessage-length appropriately.
6775 MessageLength = llvm::sys::Process::StandardErrColumns();
6776 }
6777 if (MessageLength != 0)
6778 CmdArgs.push_back(
6779 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6780
6781 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6782 CmdArgs.push_back(
6783 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6784
6785 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6786 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6787 Twine(A->getValue(0))));
6788
6789 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6790 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6791 options::OPT_fvisibility_ms_compat)) {
6792 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6793 A->render(Args, CmdArgs);
6794 } else {
6795 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6796 CmdArgs.push_back("-fvisibility=hidden");
6797 CmdArgs.push_back("-ftype-visibility=default");
6798 }
6799 } else if (IsOpenMPDevice) {
6800 // When compiling for the OpenMP device we want protected visibility by
6801 // default. This prevents the device from accidentally preempting code on
6802 // the host, makes the system more robust, and improves performance.
6803 CmdArgs.push_back("-fvisibility=protected");
6804 }
6805
6806 // PS4/PS5 process these options in addClangTargetOptions.
6807 if (!RawTriple.isPS()) {
6808 if (const Arg *A =
6809 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6810 options::OPT_fno_visibility_from_dllstorageclass)) {
6811 if (A->getOption().matches(
6812 options::OPT_fvisibility_from_dllstorageclass)) {
6813 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6814 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6815 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6816 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6817 Args.AddLastArg(CmdArgs,
6818 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6819 }
6820 }
6821 }
6822
6823 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6824 options::OPT_fno_visibility_inlines_hidden, false))
6825 CmdArgs.push_back("-fvisibility-inlines-hidden");
6826
6827 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6828 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6829
6830 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6831 // -fvisibility-global-new-delete=force-hidden.
6832 if (const Arg *A =
6833 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
6834 D.Diag(diag::warn_drv_deprecated_arg)
6835 << A->getAsString(Args) << /*hasReplacement=*/true
6836 << "-fvisibility-global-new-delete=force-hidden";
6837 }
6838
6839 if (const Arg *A =
6840 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
6841 options::OPT_fvisibility_global_new_delete_hidden)) {
6842 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
6843 A->render(Args, CmdArgs);
6844 } else {
6845 assert(A->getOption().matches(
6846 options::OPT_fvisibility_global_new_delete_hidden));
6847 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
6848 }
6849 }
6850
6851 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6852
6853 if (Args.hasFlag(options::OPT_fnew_infallible,
6854 options::OPT_fno_new_infallible, false))
6855 CmdArgs.push_back("-fnew-infallible");
6856
6857 if (Args.hasFlag(options::OPT_fno_operator_names,
6858 options::OPT_foperator_names, false))
6859 CmdArgs.push_back("-fno-operator-names");
6860
6861 // Forward -f (flag) options which we can pass directly.
6862 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6863 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6864 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6865 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6866 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
6867 options::OPT_fno_raw_string_literals);
6868
6869 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6870 Triple.hasDefaultEmulatedTLS()))
6871 CmdArgs.push_back("-femulated-tls");
6872
6873 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6874 options::OPT_fno_check_new);
6875
6876 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6877 // FIXME: There's no reason for this to be restricted to X86. The backend
6878 // code needs to be changed to include the appropriate function calls
6879 // automatically.
6880 if (!Triple.isX86() && !Triple.isAArch64())
6881 D.Diag(diag::err_drv_unsupported_opt_for_target)
6882 << A->getAsString(Args) << TripleStr;
6883 }
6884
6885 // AltiVec-like language extensions aren't relevant for assembling.
6886 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6887 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6888
6889 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6890 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6891
6892 // Forward flags for OpenMP. We don't do this if the current action is an
6893 // device offloading action other than OpenMP.
6894 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6895 options::OPT_fno_openmp, false) &&
6896 !Args.hasFlag(options::OPT_foffload_via_llvm,
6897 options::OPT_fno_offload_via_llvm, false) &&
6900
6901 // Determine if target-fast optimizations should be enabled
6902 bool TargetFastUsed =
6903 Args.hasFlag(options::OPT_fopenmp_target_fast,
6904 options::OPT_fno_openmp_target_fast, OFastEnabled);
6905 switch (D.getOpenMPRuntime(Args)) {
6906 case Driver::OMPRT_OMP:
6908 // Clang can generate useful OpenMP code for these two runtime libraries.
6909 CmdArgs.push_back("-fopenmp");
6910
6911 // If no option regarding the use of TLS in OpenMP codegeneration is
6912 // given, decide a default based on the target. Otherwise rely on the
6913 // options and pass the right information to the frontend.
6914 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6915 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6916 CmdArgs.push_back("-fnoopenmp-use-tls");
6917 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6918 options::OPT_fno_openmp_simd);
6919 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6920 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6921 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6922 options::OPT_fno_openmp_extensions, /*Default=*/true))
6923 CmdArgs.push_back("-fno-openmp-extensions");
6924 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6925 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6926 Args.AddAllArgs(CmdArgs,
6927 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6928 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6929 options::OPT_fno_openmp_optimistic_collapse,
6930 /*Default=*/false))
6931 CmdArgs.push_back("-fopenmp-optimistic-collapse");
6932
6933 // When in OpenMP offloading mode with NVPTX target, forward
6934 // cuda-mode flag
6935 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6936 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6937 CmdArgs.push_back("-fopenmp-cuda-mode");
6938
6939 // When in OpenMP offloading mode, enable debugging on the device.
6940 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6941 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6942 options::OPT_fno_openmp_target_debug, /*Default=*/false))
6943 CmdArgs.push_back("-fopenmp-target-debug");
6944
6945 // When in OpenMP offloading mode, forward assumptions information about
6946 // thread and team counts in the device.
6947 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6948 options::OPT_fno_openmp_assume_teams_oversubscription,
6949 /*Default=*/false))
6950 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6951 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6952 options::OPT_fno_openmp_assume_threads_oversubscription,
6953 /*Default=*/false))
6954 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6955
6956 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
6957 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
6958 options::OPT_fno_openmp_assume_no_thread_state,
6959 /*Default=*/TargetFastUsed))
6960 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6961
6962 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
6963 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
6964 options::OPT_fno_openmp_assume_no_nested_parallelism,
6965 /*Default=*/TargetFastUsed))
6966 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6967
6968 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6969 CmdArgs.push_back("-fopenmp-offload-mandatory");
6970 if (Args.hasArg(options::OPT_fopenmp_force_usm))
6971 CmdArgs.push_back("-fopenmp-force-usm");
6972 break;
6973 default:
6974 // By default, if Clang doesn't know how to generate useful OpenMP code
6975 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6976 // down to the actual compilation.
6977 // FIXME: It would be better to have a mode which *only* omits IR
6978 // generation based on the OpenMP support so that we get consistent
6979 // semantic analysis, etc.
6980 break;
6981 }
6982 } else {
6983 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6984 options::OPT_fno_openmp_simd);
6985 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6986 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6987 options::OPT_fno_openmp_extensions);
6988 }
6989 // Forward the offload runtime change to code generation, liboffload implies
6990 // new driver. Otherwise, check if we should forward the new driver to change
6991 // offloading code generation.
6992 if (Args.hasFlag(options::OPT_foffload_via_llvm,
6993 options::OPT_fno_offload_via_llvm, false)) {
6994 CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});
6995 } else if (Args.hasFlag(options::OPT_offload_new_driver,
6996 options::OPT_no_offload_new_driver,
6997 C.getActiveOffloadKinds() != Action::OFK_None)) {
6998 CmdArgs.push_back("--offload-new-driver");
6999 }
7000
7001 const XRayArgs &XRay = TC.getXRayArgs(Args);
7002 XRay.addArgs(TC, Args, CmdArgs, InputType);
7003
7004 for (const auto &Filename :
7005 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7006 if (D.getVFS().exists(Filename))
7007 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7008 else
7009 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7010 }
7011
7012 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7013 StringRef S0 = A->getValue(), S = S0;
7014 unsigned Size, Offset = 0;
7015 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7016 !Triple.isX86() && !Triple.isSystemZ() &&
7017 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7018 Triple.getArch() == llvm::Triple::ppc64 ||
7019 Triple.getArch() == llvm::Triple::ppc64le)))
7020 D.Diag(diag::err_drv_unsupported_opt_for_target)
7021 << A->getAsString(Args) << TripleStr;
7022 else if (S.consumeInteger(10, Size) ||
7023 (!S.empty() &&
7024 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7025 (!S.empty() && (!S.consume_front(",") || S.empty())))
7026 D.Diag(diag::err_drv_invalid_argument_to_option)
7027 << S0 << A->getOption().getName();
7028 else if (Size < Offset)
7029 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7030 else {
7031 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7032 CmdArgs.push_back(Args.MakeArgString(
7033 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7034 if (!S.empty())
7035 CmdArgs.push_back(
7036 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7037 }
7038 }
7039
7040 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7041
7042 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7043 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7044
7045 for (const auto &A :
7046 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7047 CmdArgs.push_back(
7048 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7049
7050 if (TC.SupportsProfiling()) {
7051 Args.AddLastArg(CmdArgs, options::OPT_pg);
7052
7053 llvm::Triple::ArchType Arch = TC.getArch();
7054 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7055 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7056 A->render(Args, CmdArgs);
7057 else
7058 D.Diag(diag::err_drv_unsupported_opt_for_target)
7059 << A->getAsString(Args) << TripleStr;
7060 }
7061 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7062 if (Arch == llvm::Triple::systemz)
7063 A->render(Args, CmdArgs);
7064 else
7065 D.Diag(diag::err_drv_unsupported_opt_for_target)
7066 << A->getAsString(Args) << TripleStr;
7067 }
7068 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7069 if (Arch == llvm::Triple::systemz)
7070 A->render(Args, CmdArgs);
7071 else
7072 D.Diag(diag::err_drv_unsupported_opt_for_target)
7073 << A->getAsString(Args) << TripleStr;
7074 }
7075 }
7076
7077 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7078 if (TC.getTriple().isOSzOS()) {
7079 D.Diag(diag::err_drv_unsupported_opt_for_target)
7080 << A->getAsString(Args) << TripleStr;
7081 }
7082 }
7083 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7084 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7085 D.Diag(diag::err_drv_unsupported_opt_for_target)
7086 << A->getAsString(Args) << TripleStr;
7087 }
7088 }
7089 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7090 if (A->getOption().matches(options::OPT_p)) {
7091 A->claim();
7092 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7093 CmdArgs.push_back("-pg");
7094 }
7095 }
7096
7097 // Reject AIX-specific link options on other targets.
7098 if (!TC.getTriple().isOSAIX()) {
7099 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7100 options::OPT_mxcoff_build_id_EQ)) {
7101 D.Diag(diag::err_drv_unsupported_opt_for_target)
7102 << A->getSpelling() << TripleStr;
7103 }
7104 }
7105
7106 if (Args.getLastArg(options::OPT_fapple_kext) ||
7107 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7108 CmdArgs.push_back("-fapple-kext");
7109
7110 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7111 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7112 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7113 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7114 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7115 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7116 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7117 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7118 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7119 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7120 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7121
7122 if (const char *Name = C.getTimeTraceFile(&JA)) {
7123 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7124 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7125 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7126 }
7127
7128 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7129 CmdArgs.push_back("-ftrapv-handler");
7130 CmdArgs.push_back(A->getValue());
7131 }
7132
7133 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7134
7135 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7136 options::OPT_fno_finite_loops);
7137
7138 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7139 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7140 options::OPT_fno_unroll_loops);
7141 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7142 options::OPT_fno_loop_interchange);
7143 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7144 options::OPT_fno_experimental_loop_fusion);
7145
7146 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7147
7148 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7149
7150 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7151 options::OPT_mno_speculative_load_hardening);
7152
7153 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7154 RenderSCPOptions(TC, Args, CmdArgs);
7155 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7156
7157 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7158
7159 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7160 options::OPT_mno_stackrealign);
7161
7162 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7163 StringRef Value = A->getValue();
7164 int64_t Alignment = 0;
7165 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7166 D.Diag(diag::err_drv_invalid_argument_to_option)
7167 << Value << A->getOption().getName();
7168 else if (Alignment & (Alignment - 1))
7169 D.Diag(diag::err_drv_alignment_not_power_of_two)
7170 << A->getAsString(Args) << Value;
7171 else
7172 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7173 }
7174
7175 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7176 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7177
7178 if (!Size.empty())
7179 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7180 else
7181 CmdArgs.push_back("-mstack-probe-size=0");
7182 }
7183
7184 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7185 options::OPT_mno_stack_arg_probe);
7186
7187 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7188 options::OPT_mno_restrict_it)) {
7189 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7190 CmdArgs.push_back("-mllvm");
7191 CmdArgs.push_back("-arm-restrict-it");
7192 } else {
7193 CmdArgs.push_back("-mllvm");
7194 CmdArgs.push_back("-arm-default-it");
7195 }
7196 }
7197
7198 // Forward -cl options to -cc1
7199 RenderOpenCLOptions(Args, CmdArgs, InputType);
7200
7201 // Forward hlsl options to -cc1
7202 RenderHLSLOptions(Args, CmdArgs, InputType);
7203
7204 // Forward OpenACC options to -cc1
7205 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7206
7207 if (IsHIP) {
7208 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7209 options::OPT_fno_hip_new_launch_api, true))
7210 CmdArgs.push_back("-fhip-new-launch-api");
7211 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7212 options::OPT_fno_gpu_allow_device_init);
7213 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7214 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7215 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7216 options::OPT_fno_hip_kernel_arg_name);
7217 }
7218
7219 if (IsCuda || IsHIP) {
7220 if (IsRDCMode)
7221 CmdArgs.push_back("-fgpu-rdc");
7222 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7223 options::OPT_fno_gpu_defer_diag);
7224 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7225 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7226 false)) {
7227 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7228 CmdArgs.push_back("-fgpu-defer-diag");
7229 }
7230 }
7231
7232 // Forward --no-offloadlib to -cc1.
7233 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7234 CmdArgs.push_back("--no-offloadlib");
7235
7236 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7237 CmdArgs.push_back(
7238 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7239
7240 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7241 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7242 SA->getValue()));
7243 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7244 // Emit IBT endbr64 instructions by default
7245 CmdArgs.push_back("-fcf-protection=branch");
7246 // jump-table can generate indirect jumps, which are not permitted
7247 CmdArgs.push_back("-fno-jump-tables");
7248 }
7249
7250 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7251 CmdArgs.push_back(
7252 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7253
7254 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7255
7256 // Forward -f options with positive and negative forms; we translate these by
7257 // hand. Do not propagate PGO options to the GPU-side compilations as the
7258 // profile info is for the host-side compilation only.
7259 if (!(IsCudaDevice || IsHIPDevice)) {
7260 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7261 auto *PGOArg = Args.getLastArg(
7262 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7263 options::OPT_fcs_profile_generate,
7264 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7265 options::OPT_fprofile_use_EQ);
7266 if (PGOArg)
7267 D.Diag(diag::err_drv_argument_not_allowed_with)
7268 << "SampleUse with PGO options";
7269
7270 StringRef fname = A->getValue();
7271 if (!llvm::sys::fs::exists(fname))
7272 D.Diag(diag::err_drv_no_such_file) << fname;
7273 else
7274 A->render(Args, CmdArgs);
7275 }
7276 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7277
7278 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7279 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7280 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7281 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7282 // off.
7283 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7284 options::OPT_fno_unique_internal_linkage_names, true))
7285 CmdArgs.push_back("-funique-internal-linkage-names");
7286 }
7287 }
7288 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7289
7290 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7291 options::OPT_fno_assume_sane_operator_new);
7292
7293 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7294 CmdArgs.push_back("-fapinotes");
7295 if (Args.hasFlag(options::OPT_fapinotes_modules,
7296 options::OPT_fno_apinotes_modules, false))
7297 CmdArgs.push_back("-fapinotes-modules");
7298 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7299
7300 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7301 options::OPT_fno_swift_version_independent_apinotes, false))
7302 CmdArgs.push_back("-fswift-version-independent-apinotes");
7303
7304 // -fblocks=0 is default.
7305 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7306 TC.IsBlocksDefault()) ||
7307 (Args.hasArg(options::OPT_fgnu_runtime) &&
7308 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7309 !Args.hasArg(options::OPT_fno_blocks))) {
7310 CmdArgs.push_back("-fblocks");
7311
7312 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7313 CmdArgs.push_back("-fblocks-runtime-optional");
7314 }
7315
7316 // -fencode-extended-block-signature=1 is default.
7318 CmdArgs.push_back("-fencode-extended-block-signature");
7319
7320 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7321 options::OPT_fno_coro_aligned_allocation, false) &&
7322 types::isCXX(InputType))
7323 CmdArgs.push_back("-fcoro-aligned-allocation");
7324
7325 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7326 /*Default=*/false))
7327 CmdArgs.push_back("-fdefer-ts");
7328
7329 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7330 options::OPT_fno_double_square_bracket_attributes);
7331
7332 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7333 options::OPT_fno_access_control);
7334 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7335 options::OPT_fno_elide_constructors);
7336
7337 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7338
7339 if (KernelOrKext || (types::isCXX(InputType) &&
7340 (RTTIMode == ToolChain::RM_Disabled)))
7341 CmdArgs.push_back("-fno-rtti");
7342
7343 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7344 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7345 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7346 CmdArgs.push_back("-fshort-enums");
7347
7348 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7349
7350 // -fuse-cxa-atexit is default.
7351 if (!Args.hasFlag(
7352 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7353 !RawTriple.isOSAIX() &&
7354 (!RawTriple.isOSWindows() ||
7355 RawTriple.isWindowsCygwinEnvironment()) &&
7356 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7357 RawTriple.hasEnvironment())) ||
7358 KernelOrKext)
7359 CmdArgs.push_back("-fno-use-cxa-atexit");
7360
7361 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7362 options::OPT_fno_register_global_dtors_with_atexit,
7363 RawTriple.isOSDarwin() && !KernelOrKext))
7364 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7365
7366 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7367 options::OPT_fno_use_line_directives);
7368
7369 // -fno-minimize-whitespace is default.
7370 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7371 options::OPT_fno_minimize_whitespace, false)) {
7372 types::ID InputType = Inputs[0].getType();
7373 if (!isDerivedFromC(InputType))
7374 D.Diag(diag::err_drv_opt_unsupported_input_type)
7375 << "-fminimize-whitespace" << types::getTypeName(InputType);
7376 CmdArgs.push_back("-fminimize-whitespace");
7377 }
7378
7379 // -fno-keep-system-includes is default.
7380 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7381 options::OPT_fno_keep_system_includes, false)) {
7382 types::ID InputType = Inputs[0].getType();
7383 if (!isDerivedFromC(InputType))
7384 D.Diag(diag::err_drv_opt_unsupported_input_type)
7385 << "-fkeep-system-includes" << types::getTypeName(InputType);
7386 CmdArgs.push_back("-fkeep-system-includes");
7387 }
7388
7389 // -fms-extensions=0 is default.
7390 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7391 IsWindowsMSVC || IsUEFI))
7392 CmdArgs.push_back("-fms-extensions");
7393
7394 // -fms-compatibility=0 is default.
7395 bool IsMSVCCompat = Args.hasFlag(
7396 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7397 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7398 options::OPT_fno_ms_extensions, true)));
7399 if (IsMSVCCompat) {
7400 CmdArgs.push_back("-fms-compatibility");
7401 if (!types::isCXX(Input.getType()) &&
7402 Args.hasArg(options::OPT_fms_define_stdc))
7403 CmdArgs.push_back("-fms-define-stdc");
7404 }
7405
7406 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7407 // clang and flang.
7408 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7409
7410 // -fms-anonymous-structs is disabled by default.
7411 // Determine whether to enable Microsoft named anonymous struct/union support.
7412 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7413 // where the feature can be:
7414 // - Explicitly enabled via -fms-anonymous-structs.
7415 // - Explicitly disabled via fno-ms-anonymous-structs
7416 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7417 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7418 //
7419 // When multiple relevent options are present, the last option on the command
7420 // line takes precedence. This allows users to selectively override implicit
7421 // enablement. Examples:
7422 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7423 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7424 auto MSAnonymousStructsOptionToUseOrNull =
7425 [](const ArgList &Args) -> const char * {
7426 const char *Option = nullptr;
7427 constexpr const char *Enable = "-fms-anonymous-structs";
7428 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7429
7430 // Iterate through all arguments in order to implement "last flag wins".
7431 for (const Arg *A : Args) {
7432 switch (A->getOption().getID()) {
7433 case options::OPT_fms_anonymous_structs:
7434 A->claim();
7435 Option = Enable;
7436 break;
7437 case options::OPT_fno_ms_anonymous_structs:
7438 A->claim();
7439 Option = Disable;
7440 break;
7441 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7442 // feature.
7443 case options::OPT_fms_extensions:
7444 case options::OPT_fms_compatibility:
7445 Option = Enable;
7446 break;
7447 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7448 // disables the feature.
7449 case options::OPT_fno_ms_extensions:
7450 case options::OPT_fno_ms_compatibility:
7451 Option = Disable;
7452 break;
7453 default:
7454 break;
7455 }
7456 }
7457 return Option;
7458 };
7459
7460 // Only pass a flag to CC1 if a relevant option was seen
7461 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7462 CmdArgs.push_back(MSAnonOpt);
7463
7464 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7465 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7466 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7467
7468 // Handle -fgcc-version, if present.
7469 VersionTuple GNUCVer;
7470 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7471 // Check that the version has 1 to 3 components and the minor and patch
7472 // versions fit in two decimal digits.
7473 StringRef Val = A->getValue();
7474 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7475 bool Invalid = GNUCVer.tryParse(Val);
7476 unsigned Minor = GNUCVer.getMinor().value_or(0);
7477 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7478 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7479 D.Diag(diag::err_drv_invalid_value)
7480 << A->getAsString(Args) << A->getValue();
7481 }
7482 } else if (!IsMSVCCompat) {
7483 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7484 GNUCVer = VersionTuple(4, 2, 1);
7485 }
7486 if (!GNUCVer.empty()) {
7487 CmdArgs.push_back(
7488 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7489 }
7490
7491 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7492 if (!MSVT.empty())
7493 CmdArgs.push_back(
7494 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7495
7496 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7497 if (ImplyVCPPCVer) {
7498 StringRef LanguageStandard;
7499 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7500 Std = StdArg;
7501 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7502 .Case("c11", "-std=c11")
7503 .Case("c17", "-std=c17")
7504 // If you add cases below for spellings that are
7505 // not in LangStandards.def, update
7506 // TransferableCommand::tryParseStdArg() in
7507 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7508 // to match.
7509 // TODO: add c23 when MSVC supports it.
7510 .Case("clatest", "-std=c23")
7511 .Default("");
7512 if (LanguageStandard.empty())
7513 D.Diag(clang::diag::warn_drv_unused_argument)
7514 << StdArg->getAsString(Args);
7515 }
7516 CmdArgs.push_back(LanguageStandard.data());
7517 }
7518 if (ImplyVCPPCXXVer) {
7519 StringRef LanguageStandard;
7520 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7521 Std = StdArg;
7522 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7523 .Case("c++14", "-std=c++14")
7524 .Case("c++17", "-std=c++17")
7525 .Case("c++20", "-std=c++20")
7526 // If you add cases below for spellings that are
7527 // not in LangStandards.def, update
7528 // TransferableCommand::tryParseStdArg() in
7529 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7530 // to match.
7531 // TODO add c++23 and c++26 when MSVC supports it.
7532 .Case("c++23preview", "-std=c++23")
7533 .Case("c++latest", "-std=c++26")
7534 .Default("");
7535 if (IsSYCL) {
7536 const LangStandard *LangStd =
7537 LangStandard::getLangStandardForName(StdArg->getValue());
7538 if (LangStd) {
7539 // Use of /std: with 'C' is not supported for SYCL.
7540 if (LangStd->getLanguage() == Language::C)
7541 D.Diag(diag::err_drv_argument_not_allowed_with)
7542 << StdArg->getAsString(Args) << "-fsycl";
7543 // SYCL requires C++17 or later.
7544 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7545 D.Diag(diag::err_drv_sycl_requires_cxx17)
7546 << StdArg->getAsString(Args);
7547 }
7548 }
7549 if (LanguageStandard.empty())
7550 D.Diag(clang::diag::warn_drv_unused_argument)
7551 << StdArg->getAsString(Args);
7552 }
7553
7554 if (LanguageStandard.empty()) {
7555 if (IsSYCL)
7556 // For SYCL, C++17 is the default.
7557 LanguageStandard = "-std=c++17";
7558 else if (IsMSVC2015Compatible)
7559 LanguageStandard = "-std=c++14";
7560 else
7561 LanguageStandard = "-std=c++11";
7562 }
7563
7564 CmdArgs.push_back(LanguageStandard.data());
7565 }
7566
7567 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7568 options::OPT_fno_borland_extensions);
7569
7570 // -fno-declspec is default, except for PS4/PS5.
7571 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7572 RawTriple.isPS()))
7573 CmdArgs.push_back("-fdeclspec");
7574 else if (Args.hasArg(options::OPT_fno_declspec))
7575 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7576
7577 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7578 // than 19.
7579 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7580 options::OPT_fno_threadsafe_statics,
7581 !types::isOpenCL(InputType) &&
7582 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7583 CmdArgs.push_back("-fno-threadsafe-statics");
7584
7585 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7586 true))
7587 CmdArgs.push_back("-fno-ms-tls-guards");
7588
7589 // Add -fno-assumptions, if it was specified.
7590 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7591 true))
7592 CmdArgs.push_back("-fno-assumptions");
7593
7594 // -fgnu-keywords default varies depending on language; only pass if
7595 // specified.
7596 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7597 options::OPT_fno_gnu_keywords);
7598
7599 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7600 options::OPT_fno_gnu89_inline);
7601
7602 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7603 options::OPT_finline_hint_functions,
7604 options::OPT_fno_inline_functions);
7605 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7606 if (A->getOption().matches(options::OPT_fno_inline))
7607 A->render(Args, CmdArgs);
7608 } else if (InlineArg) {
7609 InlineArg->render(Args, CmdArgs);
7610 }
7611
7612 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7613
7614 // FIXME: Find a better way to determine whether we are in C++20.
7615 bool HaveCxx20 =
7616 Std &&
7617 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7618 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7619 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7620 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7621 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7622 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7623 Std->containsValue("gnu++26") || Std->containsValue("c++latest") ||
7624 Std->containsValue("gnu++latest"));
7625 bool HaveModules =
7626 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7627
7628 // -fdelayed-template-parsing is default when targeting MSVC.
7629 // Many old Windows SDK versions require this to parse.
7630 //
7631 // According to
7632 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7633 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7634 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7635 // not enable -fdelayed-template-parsing by default after C++20.
7636 //
7637 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7638 // able to disable this by default at some point.
7639 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7640 options::OPT_fno_delayed_template_parsing,
7641 IsWindowsMSVC && !HaveCxx20)) {
7642 if (HaveCxx20)
7643 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7644
7645 CmdArgs.push_back("-fdelayed-template-parsing");
7646 }
7647
7648 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7649 options::OPT_fno_pch_validate_input_files_content, false))
7650 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7651 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7652 options::OPT_fno_pch_instantiate_templates, false))
7653 CmdArgs.push_back("-fpch-instantiate-templates");
7654 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7655 false))
7656 CmdArgs.push_back("-fmodules-codegen");
7657 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7658 false))
7659 CmdArgs.push_back("-fmodules-debuginfo");
7660
7661 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7662 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7663 Input, CmdArgs);
7664
7665 if (types::isObjC(Input.getType()) &&
7666 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7667 options::OPT_fno_objc_encode_cxx_class_template_spec,
7668 !Runtime.isNeXTFamily()))
7669 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7670
7671 if (Args.hasFlag(options::OPT_fapplication_extension,
7672 options::OPT_fno_application_extension, false))
7673 CmdArgs.push_back("-fapplication-extension");
7674
7675 // Handle GCC-style exception args.
7676 bool EH = false;
7677 if (!C.getDriver().IsCLMode())
7678 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
7679
7680 // Handle exception personalities
7681 Arg *A = Args.getLastArg(
7682 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7683 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7684 if (A) {
7685 const Option &Opt = A->getOption();
7686 if (Opt.matches(options::OPT_fsjlj_exceptions))
7687 CmdArgs.push_back("-exception-model=sjlj");
7688 if (Opt.matches(options::OPT_fseh_exceptions))
7689 CmdArgs.push_back("-exception-model=seh");
7690 if (Opt.matches(options::OPT_fdwarf_exceptions))
7691 CmdArgs.push_back("-exception-model=dwarf");
7692 if (Opt.matches(options::OPT_fwasm_exceptions))
7693 CmdArgs.push_back("-exception-model=wasm");
7694 } else {
7695 switch (TC.GetExceptionModel(Args)) {
7696 default:
7697 break;
7698 case llvm::ExceptionHandling::DwarfCFI:
7699 CmdArgs.push_back("-exception-model=dwarf");
7700 break;
7701 case llvm::ExceptionHandling::SjLj:
7702 CmdArgs.push_back("-exception-model=sjlj");
7703 break;
7704 case llvm::ExceptionHandling::WinEH:
7705 CmdArgs.push_back("-exception-model=seh");
7706 break;
7707 }
7708 }
7709
7710 // Unwind v2 (epilog) information for x64 Windows.
7711 Args.AddLastArg(CmdArgs, options::OPT_winx64_eh_unwindv2);
7712
7713 // Control Flow Guard mechanism for Windows.
7714 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
7715
7716 // C++ "sane" operator new.
7717 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7718 options::OPT_fno_assume_sane_operator_new);
7719
7720 // -fassume-unique-vtables is on by default.
7721 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7722 options::OPT_fno_assume_unique_vtables);
7723
7724 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7725 // by default.
7726 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7727 options::OPT_fno_sized_deallocation);
7728
7729 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7730 // by default.
7731 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7732 options::OPT_fno_aligned_allocation,
7733 options::OPT_faligned_new_EQ)) {
7734 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7735 CmdArgs.push_back("-fno-aligned-allocation");
7736 else
7737 CmdArgs.push_back("-faligned-allocation");
7738 }
7739
7740 // The default new alignment can be specified using a dedicated option or via
7741 // a GCC-compatible option that also turns on aligned allocation.
7742 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7743 options::OPT_faligned_new_EQ))
7744 CmdArgs.push_back(
7745 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7746
7747 // -fconstant-cfstrings is default, and may be subject to argument translation
7748 // on Darwin.
7749 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7750 options::OPT_fno_constant_cfstrings, true) ||
7751 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7752 options::OPT_mno_constant_cfstrings, true))
7753 CmdArgs.push_back("-fno-constant-cfstrings");
7754
7755 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7756 options::OPT_fno_pascal_strings);
7757
7758 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7759 // -fno-pack-struct doesn't apply to -fpack-struct=.
7760 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7761 CmdArgs.push_back(
7762 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
7763 } else if (Args.hasFlag(options::OPT_fpack_struct,
7764 options::OPT_fno_pack_struct, false)) {
7765 CmdArgs.push_back("-fpack-struct=1");
7766 }
7767
7768 // Handle -fmax-type-align=N and -fno-type-align
7769 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7770 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7771 if (!SkipMaxTypeAlign) {
7772 std::string MaxTypeAlignStr = "-fmax-type-align=";
7773 MaxTypeAlignStr += A->getValue();
7774 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7775 }
7776 } else if (RawTriple.isOSDarwin()) {
7777 if (!SkipMaxTypeAlign) {
7778 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7779 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7780 }
7781 }
7782
7783 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7784 CmdArgs.push_back("-Qn");
7785
7786 // -fno-common is the default, set -fcommon only when that flag is set.
7787 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7788
7789 // -fsigned-bitfields is default, and clang doesn't yet support
7790 // -funsigned-bitfields.
7791 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7792 options::OPT_funsigned_bitfields, true))
7793 D.Diag(diag::warn_drv_clang_unsupported)
7794 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7795
7796 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7797 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7798 D.Diag(diag::err_drv_clang_unsupported)
7799 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7800
7801 // -finput_charset=UTF-8 is default. Reject others
7802 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7803 StringRef value = inputCharset->getValue();
7804 if (!value.equals_insensitive("utf-8"))
7805 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7806 << value;
7807 }
7808
7809 // -fexec_charset=UTF-8 is default. Reject others
7810 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7811 StringRef value = execCharset->getValue();
7812 if (!value.equals_insensitive("utf-8"))
7813 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7814 << value;
7815 }
7816
7817 RenderDiagnosticsOptions(D, Args, CmdArgs);
7818
7819 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7820 options::OPT_fno_asm_blocks);
7821
7822 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7823 options::OPT_fno_gnu_inline_asm);
7824
7825 handleVectorizeLoopsArgs(Args, CmdArgs);
7826 handleVectorizeSLPArgs(Args, CmdArgs);
7827
7828 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
7829 if (!VecWidth.empty())
7830 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
7831
7832 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7833 Args.AddLastArg(CmdArgs,
7834 options::OPT_fsanitize_undefined_strip_path_components_EQ);
7835
7836 // -fdollars-in-identifiers default varies depending on platform and
7837 // language; only pass if specified.
7838 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7839 options::OPT_fno_dollars_in_identifiers)) {
7840 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7841 CmdArgs.push_back("-fdollars-in-identifiers");
7842 else
7843 CmdArgs.push_back("-fno-dollars-in-identifiers");
7844 }
7845
7846 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7847 options::OPT_fno_apple_pragma_pack);
7848
7849 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7850 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7851 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7852
7853 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7854 options::OPT_fno_rewrite_imports, false);
7855 if (RewriteImports)
7856 CmdArgs.push_back("-frewrite-imports");
7857
7858 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7859 options::OPT_fno_directives_only);
7860
7861 // Enable rewrite includes if the user's asked for it or if we're generating
7862 // diagnostics.
7863 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7864 // nice to enable this when doing a crashdump for modules as well.
7865 if (Args.hasFlag(options::OPT_frewrite_includes,
7866 options::OPT_fno_rewrite_includes, false) ||
7867 (C.isForDiagnostics() && !HaveModules))
7868 CmdArgs.push_back("-frewrite-includes");
7869
7870 if (Args.hasFlag(options::OPT_fzos_extensions,
7871 options::OPT_fno_zos_extensions, false))
7872 CmdArgs.push_back("-fzos-extensions");
7873 else if (Args.hasArg(options::OPT_fno_zos_extensions))
7874 CmdArgs.push_back("-fno-zos-extensions");
7875
7876 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7877 if (Arg *A = Args.getLastArg(options::OPT_traditional,
7878 options::OPT_traditional_cpp)) {
7880 CmdArgs.push_back("-traditional-cpp");
7881 else
7882 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7883 }
7884
7885 Args.AddLastArg(CmdArgs, options::OPT_dM);
7886 Args.AddLastArg(CmdArgs, options::OPT_dD);
7887 Args.AddLastArg(CmdArgs, options::OPT_dI);
7888
7889 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7890
7891 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
7892 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
7893
7894 // Handle serialized diagnostics.
7895 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7896 CmdArgs.push_back("-serialize-diagnostic-file");
7897 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7898 }
7899
7900 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7901 CmdArgs.push_back("-fretain-comments-from-system-headers");
7902
7903 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
7904 A->render(Args, CmdArgs);
7905 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
7906 A && A->containsValue("g")) {
7907 // Set -fextend-variable-liveness=all by default at -Og.
7908 CmdArgs.push_back("-fextend-variable-liveness=all");
7909 }
7910
7911 // Forward -fcomment-block-commands to -cc1.
7912 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7913 // Forward -fparse-all-comments to -cc1.
7914 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7915
7916 // Turn -fplugin=name.so into -load name.so
7917 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7918 CmdArgs.push_back("-load");
7919 CmdArgs.push_back(A->getValue());
7920 A->claim();
7921 }
7922
7923 // Turn -fplugin-arg-pluginname-key=value into
7924 // -plugin-arg-pluginname key=value
7925 // GCC has an actual plugin_argument struct with key/value pairs that it
7926 // passes to its plugins, but we don't, so just pass it on as-is.
7927 //
7928 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7929 // argument key are allowed to contain dashes. GCC therefore only
7930 // allows dashes in the key. We do the same.
7931 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7932 auto ArgValue = StringRef(A->getValue());
7933 auto FirstDashIndex = ArgValue.find('-');
7934 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7935 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7936
7937 A->claim();
7938 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7939 if (PluginName.empty()) {
7940 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7941 } else {
7942 D.Diag(diag::warn_drv_missing_plugin_arg)
7943 << PluginName << A->getAsString(Args);
7944 }
7945 continue;
7946 }
7947
7948 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7949 CmdArgs.push_back(Args.MakeArgString(Arg));
7950 }
7951
7952 // Forward -fpass-plugin=name.so to -cc1.
7953 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7954 CmdArgs.push_back(
7955 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7956 A->claim();
7957 }
7958
7959 // Forward --vfsoverlay to -cc1.
7960 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7961 CmdArgs.push_back("--vfsoverlay");
7962 CmdArgs.push_back(A->getValue());
7963 A->claim();
7964 }
7965
7966 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7967 options::OPT_fno_safe_buffer_usage_suggestions);
7968
7969 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
7970 options::OPT_fno_experimental_late_parse_attributes);
7971
7972 if (Args.hasFlag(options::OPT_funique_source_file_names,
7973 options::OPT_fno_unique_source_file_names, false)) {
7974 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
7975 A->render(Args, CmdArgs);
7976 else
7977 CmdArgs.push_back(Args.MakeArgString(
7978 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
7979 }
7980
7981 if (Args.hasFlag(
7982 options::OPT_fexperimental_allow_pointer_field_protection_attr,
7983 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
7984 false) ||
7985 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
7986 options::OPT_fno_experimental_pointer_field_protection_abi,
7987 false))
7988 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
7989
7990 if (!IsCudaDevice) {
7991 Args.addOptInFlag(
7992 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
7993 options::OPT_fno_experimental_pointer_field_protection_abi);
7994 Args.addOptInFlag(
7995 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
7996 options::OPT_fno_experimental_pointer_field_protection_tagged);
7997 }
7998
7999 // Setup statistics file output.
8000 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8001 if (!StatsFile.empty()) {
8002 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8004 CmdArgs.push_back("-stats-file-append");
8005 }
8006
8007 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8008 // parser.
8009 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8010 Arg->claim();
8011 // -finclude-default-header flag is for preprocessor,
8012 // do not pass it to other cc1 commands when save-temps is enabled
8013 if (C.getDriver().isSaveTempsEnabled() &&
8015 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8016 continue;
8017 }
8018 CmdArgs.push_back(Arg->getValue());
8019 }
8020 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8021 A->claim();
8022
8023 // We translate this by hand to the -cc1 argument, since nightly test uses
8024 // it and developers have been trained to spell it with -mllvm. Both
8025 // spellings are now deprecated and should be removed.
8026 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8027 CmdArgs.push_back("-disable-llvm-optzns");
8028 } else {
8029 A->render(Args, CmdArgs);
8030 }
8031 }
8032
8033 // This needs to run after -Xclang argument forwarding to pick up the target
8034 // features enabled through -Xclang -target-feature flags.
8035 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8036
8037 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8038
8039#if CLANG_ENABLE_CIR
8040 // Forward -mmlir arguments to to the MLIR option parser.
8041 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8042 A->claim();
8043 A->render(Args, CmdArgs);
8044 }
8045#endif // CLANG_ENABLE_CIR
8046
8047 // With -save-temps, we want to save the unoptimized bitcode output from the
8048 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8049 // by the frontend.
8050 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8051 // has slightly different breakdown between stages.
8052 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8053 // pristine IR generated by the frontend. Ideally, a new compile action should
8054 // be added so both IR can be captured.
8055 if ((C.getDriver().isSaveTempsEnabled() ||
8057 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8059 CmdArgs.push_back("-disable-llvm-passes");
8060
8061 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8062
8063 const char *Exec = D.getDriverProgramPath();
8064
8065 // Optionally embed the -cc1 level arguments into the debug info or a
8066 // section, for build analysis.
8067 // Also record command line arguments into the debug info if
8068 // -grecord-gcc-switches options is set on.
8069 // By default, -gno-record-gcc-switches is set on and no recording.
8070 auto GRecordSwitches = false;
8071 auto FRecordSwitches = false;
8072 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches)) {
8073 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8074 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8075 CmdArgs.push_back("-dwarf-debug-flags");
8076 CmdArgs.push_back(FlagsArgString);
8077 }
8078 if (FRecordSwitches) {
8079 CmdArgs.push_back("-record-command-line");
8080 CmdArgs.push_back(FlagsArgString);
8081 }
8082 }
8083
8084 // Host-side offloading compilation receives all device-side outputs. Include
8085 // them in the host compilation depending on the target. If the host inputs
8086 // are not empty we use the new-driver scheme, otherwise use the old scheme.
8087 if ((IsCuda || IsHIP) && CudaDeviceInput) {
8088 CmdArgs.push_back("-fcuda-include-gpubinary");
8089 CmdArgs.push_back(CudaDeviceInput->getFilename());
8090 } else if (!HostOffloadingInputs.empty()) {
8091 if ((IsCuda || IsHIP) && !IsRDCMode) {
8092 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8093 CmdArgs.push_back("-fcuda-include-gpubinary");
8094 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8095 } else {
8096 for (const InputInfo Input : HostOffloadingInputs)
8097 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8098 TC.getInputFilename(Input)));
8099 }
8100 }
8101
8102 if (IsCuda) {
8103 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
8104 options::OPT_fno_cuda_short_ptr, false))
8105 CmdArgs.push_back("-fcuda-short-ptr");
8106 }
8107
8108 if (IsCuda || IsHIP) {
8109 // Determine the original source input.
8110 const Action *SourceAction = &JA;
8111 while (SourceAction->getKind() != Action::InputClass) {
8112 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8113 SourceAction = SourceAction->getInputs()[0];
8114 }
8115 auto CUID = cast<InputAction>(SourceAction)->getId();
8116 if (!CUID.empty())
8117 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8118
8119 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8120 // be overriden by -fno-gpu-approx-transcendentals.
8121 bool UseApproxTranscendentals = Args.hasFlag(
8122 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8123 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8124 options::OPT_fno_gpu_approx_transcendentals,
8125 UseApproxTranscendentals))
8126 CmdArgs.push_back("-fgpu-approx-transcendentals");
8127 } else {
8128 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8129 options::OPT_fno_gpu_approx_transcendentals);
8130 }
8131
8132 if (IsHIP) {
8133 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8134 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8135 }
8136
8137 Args.AddAllArgs(CmdArgs,
8138 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8139
8140 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8141 options::OPT_fno_offload_uniform_block);
8142
8143 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8144 options::OPT_fno_offload_implicit_host_device_templates);
8145
8146 if (IsCudaDevice || IsHIPDevice) {
8147 StringRef InlineThresh =
8148 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8149 if (!InlineThresh.empty()) {
8150 std::string ArgStr =
8151 std::string("-inline-threshold=") + InlineThresh.str();
8152 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8153 }
8154 }
8155
8156 if (IsHIPDevice)
8157 Args.addOptOutFlag(CmdArgs,
8158 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8159 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8160
8161 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8162 // to specify the result of the compile phase on the host, so the meaningful
8163 // device declarations can be identified. Also, -fopenmp-is-target-device is
8164 // passed along to tell the frontend that it is generating code for a device,
8165 // so that only the relevant declarations are emitted.
8166 if (IsOpenMPDevice) {
8167 CmdArgs.push_back("-fopenmp-is-target-device");
8168 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8169 if (Args.hasArg(options::OPT_foffload_via_llvm))
8170 CmdArgs.push_back("-fcuda-is-device");
8171
8172 if (OpenMPDeviceInput) {
8173 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8174 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8175 }
8176 }
8177
8178 if (Triple.isAMDGPU() ||
8179 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8180 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8181
8182 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8183 options::OPT_mno_unsafe_fp_atomics);
8184 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8185 options::OPT_mno_amdgpu_ieee);
8186 }
8187
8188 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8189
8190 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8191 options::OPT_fno_devirtualize_speculatively,
8192 /*Default value*/ false))
8193 CmdArgs.push_back("-fdevirtualize-speculatively");
8194
8195 bool VirtualFunctionElimination =
8196 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8197 options::OPT_fno_virtual_function_elimination, false);
8198 if (VirtualFunctionElimination) {
8199 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8200 // in the future).
8201 if (LTOMode != LTOK_Full)
8202 D.Diag(diag::err_drv_argument_only_allowed_with)
8203 << "-fvirtual-function-elimination"
8204 << "-flto=full";
8205
8206 CmdArgs.push_back("-fvirtual-function-elimination");
8207 }
8208
8209 // VFE requires whole-program-vtables, and enables it by default.
8210 bool WholeProgramVTables = Args.hasFlag(
8211 options::OPT_fwhole_program_vtables,
8212 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8213 if (VirtualFunctionElimination && !WholeProgramVTables) {
8214 D.Diag(diag::err_drv_argument_not_allowed_with)
8215 << "-fno-whole-program-vtables"
8216 << "-fvirtual-function-elimination";
8217 }
8218
8219 if (WholeProgramVTables) {
8220 // PS4 uses the legacy LTO API, which does not support this feature in
8221 // ThinLTO mode.
8222 bool IsPS4 = getToolChain().getTriple().isPS4();
8223
8224 // Check if we passed LTO options but they were suppressed because this is a
8225 // device offloading action, or we passed device offload LTO options which
8226 // were suppressed because this is not the device offload action.
8227 // Check if we are using PS4 in regular LTO mode.
8228 // Otherwise, issue an error.
8229
8230 auto OtherLTOMode = TC.getLTOMode(
8231 Args, IsDeviceOffloadAction ? Action::OFK_None
8232 : static_cast<Action::OffloadKind>(
8233 C.getActiveOffloadKinds()));
8234 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8235
8236 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8237 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8238 D.Diag(diag::err_drv_argument_only_allowed_with)
8239 << "-fwhole-program-vtables"
8240 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8241
8242 // Propagate -fwhole-program-vtables if this is an LTO compile.
8243 if (IsUsingLTO)
8244 CmdArgs.push_back("-fwhole-program-vtables");
8245 }
8246
8247 bool DefaultsSplitLTOUnit =
8248 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8249 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8250 (!Triple.isPS4() && UnifiedLTO);
8251 bool SplitLTOUnit =
8252 Args.hasFlag(options::OPT_fsplit_lto_unit,
8253 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8254 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8255 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8256 << "-fsanitize=cfi";
8257 if (SplitLTOUnit)
8258 CmdArgs.push_back("-fsplit-lto-unit");
8259
8260 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8261 options::OPT_fno_fat_lto_objects)) {
8262 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8263 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8264 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8265 D.Diag(diag::err_drv_unsupported_opt_for_target)
8266 << A->getAsString(Args) << TC.getTripleString();
8267 }
8268 CmdArgs.push_back(Args.MakeArgString(
8269 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8270 CmdArgs.push_back("-flto-unit");
8271 CmdArgs.push_back("-ffat-lto-objects");
8272 A->render(Args, CmdArgs);
8273 }
8274 }
8275
8276 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8277
8278 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8279 options::OPT_fno_force_enable_int128)) {
8280 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8281 CmdArgs.push_back("-fforce-enable-int128");
8282 }
8283
8284 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8285 options::OPT_fno_keep_static_consts);
8286 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8287 options::OPT_fno_keep_persistent_storage_variables);
8288 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8289 options::OPT_fno_complete_member_pointers);
8290 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8291 A->render(Args, CmdArgs);
8292
8293 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8294
8295 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8296
8297 if (Triple.isAArch64() &&
8298 (Args.hasArg(options::OPT_mno_fmv) ||
8299 (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
8300 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8301 // Disable Function Multiversioning on AArch64 target.
8302 CmdArgs.push_back("-target-feature");
8303 CmdArgs.push_back("-fmv");
8304 }
8305
8306 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8307 (TC.getTriple().isOSBinFormatELF() ||
8308 TC.getTriple().isOSBinFormatCOFF()) &&
8309 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8310 !TC.getTriple().isOSNetBSD() &&
8311 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8312 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8313 CmdArgs.push_back("-faddrsig");
8314
8315 const bool HasDefaultDwarf2CFIASM =
8316 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8317 (EH || UnwindTables || AsyncUnwindTables ||
8318 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8319 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8320 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8321 CmdArgs.push_back("-fdwarf2-cfi-asm");
8322
8323 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8324 std::string Str = A->getAsString(Args);
8325 if (!TC.getTriple().isOSBinFormatELF())
8326 D.Diag(diag::err_drv_unsupported_opt_for_target)
8327 << Str << TC.getTripleString();
8328 CmdArgs.push_back(Args.MakeArgString(Str));
8329 }
8330
8331 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8332 // the -cc1 command easier to edit when reproducing compiler crashes.
8333 if (Output.getType() == types::TY_Dependencies) {
8334 // Handled with other dependency code.
8335 } else if (Output.isFilename()) {
8336 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8337 Output.getType() == clang::driver::types::TY_IFS) {
8338 SmallString<128> OutputFilename(Output.getFilename());
8339 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8340 CmdArgs.push_back("-o");
8341 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8342 } else {
8343 CmdArgs.push_back("-o");
8344 CmdArgs.push_back(Output.getFilename());
8345 }
8346 } else {
8347 assert(Output.isNothing() && "Invalid output.");
8348 }
8349
8350 addDashXForInput(Args, Input, CmdArgs);
8351
8352 ArrayRef<InputInfo> FrontendInputs = Input;
8353 if (IsExtractAPI)
8354 FrontendInputs = ExtractAPIInputs;
8355 else if (Input.isNothing())
8356 FrontendInputs = {};
8357
8358 for (const InputInfo &Input : FrontendInputs) {
8359 if (Input.isFilename())
8360 CmdArgs.push_back(Input.getFilename());
8361 else
8362 Input.getInputArg().renderAsInput(Args, CmdArgs);
8363 }
8364
8365 if (D.CC1Main && !D.CCGenDiagnostics) {
8366 // Invoke the CC1 directly in this process
8367 C.addCommand(std::make_unique<CC1Command>(
8368 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8369 Output, D.getPrependArg()));
8370 } else {
8371 C.addCommand(std::make_unique<Command>(
8372 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8373 Output, D.getPrependArg()));
8374 }
8375
8376 // Make the compile command echo its inputs for /showFilenames.
8377 if (Output.getType() == types::TY_Object &&
8378 Args.hasFlag(options::OPT__SLASH_showFilenames,
8379 options::OPT__SLASH_showFilenames_, false)) {
8380 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8381 }
8382
8383 if (Arg *A = Args.getLastArg(options::OPT_pg))
8384 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8385 !Args.hasArg(options::OPT_mfentry))
8386 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8387 << A->getAsString(Args);
8388
8389 // Claim some arguments which clang supports automatically.
8390
8391 // -fpch-preprocess is used with gcc to add a special marker in the output to
8392 // include the PCH file.
8393 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8394
8395 // Claim some arguments which clang doesn't support, but we don't
8396 // care to warn the user about.
8397 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8398 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8399
8400 // Disable warnings for clang -E -emit-llvm foo.c
8401 Args.ClaimAllArgs(options::OPT_emit_llvm);
8402}
8403
8404Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8405 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8406 // as it is for other tools. Some operations on a Tool actually test
8407 // whether that tool is Clang based on the Tool's Name as a string.
8408 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8409
8411
8412/// Add options related to the Objective-C runtime/ABI.
8413///
8414/// Returns true if the runtime is non-fragile.
8415ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8416 const InputInfoList &inputs,
8417 ArgStringList &cmdArgs,
8418 RewriteKind rewriteKind) const {
8419 // Look for the controlling runtime option.
8420 Arg *runtimeArg =
8421 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8422 options::OPT_fobjc_runtime_EQ);
8423
8424 // Just forward -fobjc-runtime= to the frontend. This supercedes
8425 // options about fragility.
8426 if (runtimeArg &&
8427 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8428 ObjCRuntime runtime;
8429 StringRef value = runtimeArg->getValue();
8430 if (runtime.tryParse(value)) {
8431 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8432 << value;
8433 }
8434 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8435 (runtime.getVersion() >= VersionTuple(2, 0)))
8436 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8437 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8439 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8440 << runtime.getVersion().getMajor();
8441 }
8442
8443 runtimeArg->render(args, cmdArgs);
8444 return runtime;
8445 }
8446
8447 // Otherwise, we'll need the ABI "version". Version numbers are
8448 // slightly confusing for historical reasons:
8449 // 1 - Traditional "fragile" ABI
8450 // 2 - Non-fragile ABI, version 1
8451 // 3 - Non-fragile ABI, version 2
8452 unsigned objcABIVersion = 1;
8453 // If -fobjc-abi-version= is present, use that to set the version.
8454 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8455 StringRef value = abiArg->getValue();
8456 if (value == "1")
8457 objcABIVersion = 1;
8458 else if (value == "2")
8459 objcABIVersion = 2;
8460 else if (value == "3")
8461 objcABIVersion = 3;
8462 else
8463 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8464 } else {
8465 // Otherwise, determine if we are using the non-fragile ABI.
8466 bool nonFragileABIIsDefault =
8467 (rewriteKind == RK_NonFragile ||
8468 (rewriteKind == RK_None &&
8470 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8471 options::OPT_fno_objc_nonfragile_abi,
8472 nonFragileABIIsDefault)) {
8473// Determine the non-fragile ABI version to use.
8474#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8475 unsigned nonFragileABIVersion = 1;
8476#else
8477 unsigned nonFragileABIVersion = 2;
8478#endif
8479
8480 if (Arg *abiArg =
8481 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8482 StringRef value = abiArg->getValue();
8483 if (value == "1")
8484 nonFragileABIVersion = 1;
8485 else if (value == "2")
8486 nonFragileABIVersion = 2;
8487 else
8488 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8489 << value;
8490 }
8491
8492 objcABIVersion = 1 + nonFragileABIVersion;
8493 } else {
8494 objcABIVersion = 1;
8495 }
8496 }
8497
8498 // We don't actually care about the ABI version other than whether
8499 // it's non-fragile.
8500 bool isNonFragile = objcABIVersion != 1;
8501
8502 // If we have no runtime argument, ask the toolchain for its default runtime.
8503 // However, the rewriter only really supports the Mac runtime, so assume that.
8504 ObjCRuntime runtime;
8505 if (!runtimeArg) {
8506 switch (rewriteKind) {
8507 case RK_None:
8508 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8509 break;
8510 case RK_Fragile:
8511 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8512 break;
8513 case RK_NonFragile:
8514 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8515 break;
8516 }
8517
8518 // -fnext-runtime
8519 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8520 // On Darwin, make this use the default behavior for the toolchain.
8521 if (getToolChain().getTriple().isOSDarwin()) {
8522 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8523
8524 // Otherwise, build for a generic macosx port.
8525 } else {
8526 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8527 }
8528
8529 // -fgnu-runtime
8530 } else {
8531 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8532 // Legacy behaviour is to target the gnustep runtime if we are in
8533 // non-fragile mode or the GCC runtime in fragile mode.
8534 if (isNonFragile)
8535 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8536 else
8537 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8538 }
8539
8540 if (llvm::any_of(inputs, [](const InputInfo &input) {
8541 return types::isObjC(input.getType());
8542 }))
8543 cmdArgs.push_back(
8544 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8545 return runtime;
8546}
8547
8548static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8549 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8550 I += HaveDash;
8551 return !HaveDash;
8552}
8553
8554namespace {
8555struct EHFlags {
8556 bool Synch = false;
8557 bool Asynch = false;
8558 bool NoUnwindC = false;
8559};
8560} // end anonymous namespace
8561
8562/// /EH controls whether to run destructor cleanups when exceptions are
8563/// thrown. There are three modifiers:
8564/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8565/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8566/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8567/// - c: Assume that extern "C" functions are implicitly nounwind.
8568/// The default is /EHs-c-, meaning cleanups are disabled.
8569static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8570 bool isWindowsMSVC) {
8571 EHFlags EH;
8572
8573 std::vector<std::string> EHArgs =
8574 Args.getAllArgValues(options::OPT__SLASH_EH);
8575 for (const auto &EHVal : EHArgs) {
8576 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8577 switch (EHVal[I]) {
8578 case 'a':
8579 EH.Asynch = maybeConsumeDash(EHVal, I);
8580 if (EH.Asynch) {
8581 // Async exceptions are Windows MSVC only.
8582 if (!isWindowsMSVC) {
8583 EH.Asynch = false;
8584 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8585 continue;
8586 }
8587 EH.Synch = false;
8588 }
8589 continue;
8590 case 'c':
8591 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8592 continue;
8593 case 's':
8594 EH.Synch = maybeConsumeDash(EHVal, I);
8595 if (EH.Synch)
8596 EH.Asynch = false;
8597 continue;
8598 default:
8599 break;
8600 }
8601 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8602 break;
8603 }
8604 }
8605 // The /GX, /GX- flags are only processed if there are not /EH flags.
8606 // The default is that /GX is not specified.
8607 if (EHArgs.empty() &&
8608 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8609 /*Default=*/false)) {
8610 EH.Synch = true;
8611 EH.NoUnwindC = true;
8612 }
8613
8614 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8615 EH.Synch = false;
8616 EH.NoUnwindC = false;
8617 EH.Asynch = false;
8618 }
8619
8620 return EH;
8621}
8622
8623void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8624 ArgStringList &CmdArgs) const {
8625 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8626
8627 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8628
8629 if (Arg *ShowIncludes =
8630 Args.getLastArg(options::OPT__SLASH_showIncludes,
8631 options::OPT__SLASH_showIncludes_user)) {
8632 CmdArgs.push_back("--show-includes");
8633 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8634 CmdArgs.push_back("-sys-header-deps");
8635 }
8636
8637 // This controls whether or not we emit RTTI data for polymorphic types.
8638 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8639 /*Default=*/false))
8640 CmdArgs.push_back("-fno-rtti-data");
8641
8642 // This controls whether or not we emit stack-protector instrumentation.
8643 // In MSVC, Buffer Security Check (/GS) is on by default.
8644 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8645 /*Default=*/true)) {
8646 CmdArgs.push_back("-stack-protector");
8647 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8648 }
8649
8650 const Driver &D = getToolChain().getDriver();
8651
8652 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8653 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8654 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8655 if (types::isCXX(InputType))
8656 CmdArgs.push_back("-fcxx-exceptions");
8657 CmdArgs.push_back("-fexceptions");
8658 if (EH.Asynch)
8659 CmdArgs.push_back("-fasync-exceptions");
8660 }
8661 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8662 CmdArgs.push_back("-fexternc-nounwind");
8663
8664 // /EP should expand to -E -P.
8665 if (Args.hasArg(options::OPT__SLASH_EP)) {
8666 CmdArgs.push_back("-E");
8667 CmdArgs.push_back("-P");
8668 }
8669
8670 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8671 options::OPT__SLASH_Zc_dllexportInlines,
8672 false)) {
8673 CmdArgs.push_back("-fno-dllexport-inlines");
8674 }
8675
8676 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8677 options::OPT__SLASH_Zc_wchar_t, false)) {
8678 CmdArgs.push_back("-fno-wchar");
8679 }
8680
8681 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8682 llvm::Triple::ArchType Arch = getToolChain().getArch();
8683 std::vector<std::string> Values =
8684 Args.getAllArgValues(options::OPT__SLASH_arch);
8685 if (!Values.empty()) {
8686 llvm::SmallSet<std::string, 4> SupportedArches;
8687 if (Arch == llvm::Triple::x86)
8688 SupportedArches.insert("IA32");
8689
8690 for (auto &V : Values)
8691 if (!SupportedArches.contains(V))
8692 D.Diag(diag::err_drv_argument_not_allowed_with)
8693 << std::string("/arch:").append(V) << "/kernel";
8694 }
8695
8696 CmdArgs.push_back("-fno-rtti");
8697 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8698 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8699 << "/kernel";
8700 }
8701
8702 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
8703 options::OPT__SLASH_vlen_EQ_256,
8704 options::OPT__SLASH_vlen_EQ_512)) {
8705 llvm::Triple::ArchType AT = getToolChain().getArch();
8706 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8707 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
8708 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8709 "AVX10.2"};
8710
8711 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
8712 if (Arch512.contains(Arch))
8713 CmdArgs.push_back("-mprefer-vector-width=512");
8714 else
8715 D.Diag(diag::warn_drv_argument_not_allowed_with)
8716 << "/vlen=512" << std::string("/arch:").append(Arch);
8717 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
8718 if (Arch512.contains(Arch))
8719 CmdArgs.push_back("-mprefer-vector-width=256");
8720 else if (Arch != "AVX" && Arch != "AVX2")
8721 D.Diag(diag::warn_drv_argument_not_allowed_with)
8722 << "/vlen=256" << std::string("/arch:").append(Arch);
8723 } else {
8724 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8725 CmdArgs.push_back("-mprefer-vector-width=256");
8726 }
8727 } else {
8728 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
8729 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8730 CmdArgs.push_back("-mprefer-vector-width=256");
8731 CmdArgs.push_back("-target-feature");
8732 CmdArgs.push_back("-amx-tile");
8733 }
8734 if (Arch == "AVX10.2") {
8735 CmdArgs.push_back("-target-feature");
8736 CmdArgs.push_back("+avx10.2");
8737 }
8738 }
8739
8740 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8741 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8742 if (MostGeneralArg && BestCaseArg)
8743 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8744 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8745
8746 if (MostGeneralArg) {
8747 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8748 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8749 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8750
8751 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8752 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8753 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8754 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8755 << FirstConflict->getAsString(Args)
8756 << SecondConflict->getAsString(Args);
8757
8758 if (SingleArg)
8759 CmdArgs.push_back("-fms-memptr-rep=single");
8760 else if (MultipleArg)
8761 CmdArgs.push_back("-fms-memptr-rep=multiple");
8762 else
8763 CmdArgs.push_back("-fms-memptr-rep=virtual");
8764 }
8765
8766 if (Args.hasArg(options::OPT_regcall4))
8767 CmdArgs.push_back("-regcall4");
8768
8769 // Parse the default calling convention options.
8770 if (Arg *CCArg =
8771 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8772 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8773 options::OPT__SLASH_Gregcall)) {
8774 unsigned DCCOptId = CCArg->getOption().getID();
8775 const char *DCCFlag = nullptr;
8776 bool ArchSupported = !isNVPTX;
8777 llvm::Triple::ArchType Arch = getToolChain().getArch();
8778 switch (DCCOptId) {
8779 case options::OPT__SLASH_Gd:
8780 DCCFlag = "-fdefault-calling-conv=cdecl";
8781 break;
8782 case options::OPT__SLASH_Gr:
8783 ArchSupported = Arch == llvm::Triple::x86;
8784 DCCFlag = "-fdefault-calling-conv=fastcall";
8785 break;
8786 case options::OPT__SLASH_Gz:
8787 ArchSupported = Arch == llvm::Triple::x86;
8788 DCCFlag = "-fdefault-calling-conv=stdcall";
8789 break;
8790 case options::OPT__SLASH_Gv:
8791 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8792 DCCFlag = "-fdefault-calling-conv=vectorcall";
8793 break;
8794 case options::OPT__SLASH_Gregcall:
8795 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8796 DCCFlag = "-fdefault-calling-conv=regcall";
8797 break;
8798 }
8799
8800 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8801 if (ArchSupported && DCCFlag)
8802 CmdArgs.push_back(DCCFlag);
8803 }
8804
8805 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8806 CmdArgs.push_back("-regcall4");
8807
8808 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8809
8810 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8811 CmdArgs.push_back("-fdiagnostics-format");
8812 CmdArgs.push_back("msvc");
8813 }
8814
8815 if (Args.hasArg(options::OPT__SLASH_kernel))
8816 CmdArgs.push_back("-fms-kernel");
8817
8818 // Unwind v2 (epilog) information for x64 Windows.
8819 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
8820 CmdArgs.push_back("-fwinx64-eh-unwindv2=required");
8821 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
8822 CmdArgs.push_back("-fwinx64-eh-unwindv2=best-effort");
8823
8824 // Handle the various /guard options. We don't immediately push back clang
8825 // args since there are /d2 args that can modify the behavior of /guard:cf.
8826 bool HasCFGuard = false;
8827 bool HasCFGuardNoChecks = false;
8828 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8829 StringRef GuardArgs = A->getValue();
8830 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8831 // "ehcont-".
8832 if (GuardArgs.equals_insensitive("cf")) {
8833 // Emit CFG instrumentation and the table of address-taken functions.
8834 HasCFGuard = true;
8835 HasCFGuardNoChecks = false;
8836 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8837 // Emit only the table of address-taken functions.
8838 HasCFGuard = false;
8839 HasCFGuardNoChecks = true;
8840 } else if (GuardArgs.equals_insensitive("ehcont")) {
8841 // Emit EH continuation table.
8842 CmdArgs.push_back("-ehcontguard");
8843 } else if (GuardArgs.equals_insensitive("cf-") ||
8844 GuardArgs.equals_insensitive("ehcont-")) {
8845 // Do nothing, but we might want to emit a security warning in future.
8846 } else {
8847 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8848 }
8849 A->claim();
8850 }
8851
8852 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
8853 // If CFG is not enabled, it is a no-op.
8854 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
8855 if (HasCFGuard) {
8856 HasCFGuard = false;
8857 HasCFGuardNoChecks = true;
8858 }
8859 }
8860
8861 if (HasCFGuard)
8862 CmdArgs.push_back("-cfguard");
8863 else if (HasCFGuardNoChecks)
8864 CmdArgs.push_back("-cfguard-no-checks");
8865
8866 // Control Flow Guard mechanism for Windows.
8867 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
8868 CmdArgs.push_back("-fwin-cfg-mechanism=check");
8869 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
8870 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
8871
8872 for (const auto &FuncOverride :
8873 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
8874 CmdArgs.push_back(Args.MakeArgString(
8875 Twine("-loader-replaceable-function=") + FuncOverride));
8876 }
8877}
8878
8879const char *Clang::getBaseInputName(const ArgList &Args,
8880 const InputInfo &Input) {
8881 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
8882}
8883
8884const char *Clang::getBaseInputStem(const ArgList &Args,
8885 const InputInfoList &Inputs) {
8886 const char *Str = getBaseInputName(Args, Inputs[0]);
8887
8888 if (const char *End = strrchr(Str, '.'))
8889 return Args.MakeArgString(std::string(Str, End));
8890
8891 return Str;
8892}
8893
8894const char *Clang::getDependencyFileName(const ArgList &Args,
8895 const InputInfoList &Inputs) {
8896 // FIXME: Think about this more.
8897
8898 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8899 SmallString<128> OutputFilename(OutputOpt->getValue());
8900 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8901 return Args.MakeArgString(OutputFilename);
8902 }
8903
8904 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8905}
8906
8907// Begin ClangAs
8908
8909void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8910 ArgStringList &CmdArgs) const {
8911 StringRef CPUName;
8912 StringRef ABIName;
8913 const llvm::Triple &Triple = getToolChain().getTriple();
8914 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8915
8916 CmdArgs.push_back("-target-abi");
8917 CmdArgs.push_back(ABIName.data());
8918}
8919
8920void ClangAs::AddX86TargetArgs(const ArgList &Args,
8921 ArgStringList &CmdArgs) const {
8922 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8923 /*IsLTO=*/false);
8924
8925 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8926 StringRef Value = A->getValue();
8927 if (Value == "intel" || Value == "att") {
8928 CmdArgs.push_back("-mllvm");
8929 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8930 } else {
8931 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8932 << A->getSpelling() << Value;
8933 }
8934 }
8935}
8936
8937void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8938 ArgStringList &CmdArgs) const {
8939 CmdArgs.push_back("-target-abi");
8940 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8942 .data());
8943}
8944
8945void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8946 ArgStringList &CmdArgs) const {
8947 const llvm::Triple &Triple = getToolChain().getTriple();
8948 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8949
8950 CmdArgs.push_back("-target-abi");
8951 CmdArgs.push_back(ABIName.data());
8952
8953 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8954 options::OPT_mno_default_build_attributes, true)) {
8955 CmdArgs.push_back("-mllvm");
8956 CmdArgs.push_back("-riscv-add-build-attributes");
8957 }
8958}
8959
8961 const InputInfo &Output, const InputInfoList &Inputs,
8962 const ArgList &Args,
8963 const char *LinkingOutput) const {
8964 ArgStringList CmdArgs;
8965
8966 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8967 const InputInfo &Input = Inputs[0];
8968
8969 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8970 const std::string &TripleStr = Triple.getTriple();
8971 const auto &D = getToolChain().getDriver();
8972
8973 // Don't warn about "clang -w -c foo.s"
8974 Args.ClaimAllArgs(options::OPT_w);
8975 // and "clang -emit-llvm -c foo.s"
8976 Args.ClaimAllArgs(options::OPT_emit_llvm);
8977
8978 claimNoWarnArgs(Args);
8979
8980 // Invoke ourselves in -cc1as mode.
8981 //
8982 // FIXME: Implement custom jobs for internal actions.
8983 CmdArgs.push_back("-cc1as");
8984
8985 // Add the "effective" target triple.
8986 CmdArgs.push_back("-triple");
8987 CmdArgs.push_back(Args.MakeArgString(TripleStr));
8988
8990
8991 // Set the output mode, we currently only expect to be used as a real
8992 // assembler.
8993 CmdArgs.push_back("-filetype");
8994 CmdArgs.push_back("obj");
8995
8996 // Set the main file name, so that debug info works even with
8997 // -save-temps or preprocessed assembly.
8998 CmdArgs.push_back("-main-file-name");
8999 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9000
9001 // Add the target cpu
9002 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9003 if (!CPU.empty()) {
9004 CmdArgs.push_back("-target-cpu");
9005 CmdArgs.push_back(Args.MakeArgString(CPU));
9006 }
9007
9008 // Add the target features
9009 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9010
9011 // Ignore explicit -force_cpusubtype_ALL option.
9012 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9013
9014 // Pass along any -I options so we get proper .include search paths.
9015 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9016
9017 // Pass along any --embed-dir or similar options so we get proper embed paths.
9018 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9019
9020 // Determine the original source input.
9021 auto FindSource = [](const Action *S) -> const Action * {
9022 while (S->getKind() != Action::InputClass) {
9023 assert(!S->getInputs().empty() && "unexpected root action!");
9024 S = S->getInputs()[0];
9025 }
9026 return S;
9027 };
9028 const Action *SourceAction = FindSource(&JA);
9029
9030 // Forward -g and handle debug info related flags, assuming we are dealing
9031 // with an actual assembly file.
9032 bool WantDebug = false;
9033 Args.ClaimAllArgs(options::OPT_g_Group);
9034 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9035 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9036 !A->getOption().matches(options::OPT_ggdb0);
9037
9038 // If a -gdwarf argument appeared, remember it.
9039 bool EmitDwarf = false;
9040 if (const Arg *A = getDwarfNArg(Args))
9041 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9042
9043 bool EmitCodeView = false;
9044 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9045 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9046
9047 // If the user asked for debug info but did not explicitly specify -gcodeview
9048 // or -gdwarf, ask the toolchain for the default format.
9049 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9050 switch (getToolChain().getDefaultDebugFormat()) {
9051 case llvm::codegenoptions::DIF_CodeView:
9052 EmitCodeView = true;
9053 break;
9054 case llvm::codegenoptions::DIF_DWARF:
9055 EmitDwarf = true;
9056 break;
9057 }
9058 }
9059
9060 // If the arguments don't imply DWARF, don't emit any debug info here.
9061 if (!EmitDwarf)
9062 WantDebug = false;
9063
9064 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9065 llvm::codegenoptions::NoDebugInfo;
9066
9067 // Add the -fdebug-compilation-dir flag if needed.
9068 const char *DebugCompilationDir =
9069 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9070
9071 if (SourceAction->getType() == types::TY_Asm ||
9072 SourceAction->getType() == types::TY_PP_Asm) {
9073 // You might think that it would be ok to set DebugInfoKind outside of
9074 // the guard for source type, however there is a test which asserts
9075 // that some assembler invocation receives no -debug-info-kind,
9076 // and it's not clear whether that test is just overly restrictive.
9077 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9078 : llvm::codegenoptions::NoDebugInfo);
9079
9080 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9081 CmdArgs);
9082
9083 // Set the AT_producer to the clang version when using the integrated
9084 // assembler on assembly source files.
9085 CmdArgs.push_back("-dwarf-debug-producer");
9086 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9087
9088 // And pass along -I options
9089 Args.AddAllArgs(CmdArgs, options::OPT_I);
9090 }
9091 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9092 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9093 llvm::DebuggerKind::Default);
9094 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9095 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9096
9097 // Handle -fPIC et al -- the relocation-model affects the assembler
9098 // for some targets.
9099 llvm::Reloc::Model RelocationModel;
9100 unsigned PICLevel;
9101 bool IsPIE;
9102 std::tie(RelocationModel, PICLevel, IsPIE) =
9103 ParsePICArgs(getToolChain(), Args);
9104
9105 const char *RMName = RelocationModelName(RelocationModel);
9106 if (RMName) {
9107 CmdArgs.push_back("-mrelocation-model");
9108 CmdArgs.push_back(RMName);
9109 }
9110
9111 // Optionally embed the -cc1as level arguments into the debug info, for build
9112 // analysis.
9113 if (getToolChain().UseDwarfDebugFlags()) {
9114 ArgStringList OriginalArgs;
9115 for (const auto &Arg : Args)
9116 Arg->render(Args, OriginalArgs);
9117
9118 SmallString<256> Flags;
9119 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9120 escapeSpacesAndBackslashes(Exec, Flags);
9121 for (const char *OriginalArg : OriginalArgs) {
9122 SmallString<128> EscapedArg;
9123 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9124 Flags += " ";
9125 Flags += EscapedArg;
9126 }
9127 CmdArgs.push_back("-dwarf-debug-flags");
9128 CmdArgs.push_back(Args.MakeArgString(Flags));
9129 }
9130
9131 // FIXME: Add -static support, once we have it.
9132
9133 // Add target specific flags.
9134 switch (getToolChain().getArch()) {
9135 default:
9136 break;
9137
9138 case llvm::Triple::mips:
9139 case llvm::Triple::mipsel:
9140 case llvm::Triple::mips64:
9141 case llvm::Triple::mips64el:
9142 AddMIPSTargetArgs(Args, CmdArgs);
9143 break;
9144
9145 case llvm::Triple::x86:
9146 case llvm::Triple::x86_64:
9147 AddX86TargetArgs(Args, CmdArgs);
9148 break;
9149
9150 case llvm::Triple::arm:
9151 case llvm::Triple::armeb:
9152 case llvm::Triple::thumb:
9153 case llvm::Triple::thumbeb:
9154 // This isn't in AddARMTargetArgs because we want to do this for assembly
9155 // only, not C/C++.
9156 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9157 options::OPT_mno_default_build_attributes, true)) {
9158 CmdArgs.push_back("-mllvm");
9159 CmdArgs.push_back("-arm-add-build-attributes");
9160 }
9161 break;
9162
9163 case llvm::Triple::aarch64:
9164 case llvm::Triple::aarch64_32:
9165 case llvm::Triple::aarch64_be:
9166 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9167 CmdArgs.push_back("-mllvm");
9168 CmdArgs.push_back("-aarch64-mark-bti-property");
9169 }
9170 break;
9171
9172 case llvm::Triple::loongarch32:
9173 case llvm::Triple::loongarch64:
9174 AddLoongArchTargetArgs(Args, CmdArgs);
9175 break;
9176
9177 case llvm::Triple::riscv32:
9178 case llvm::Triple::riscv64:
9179 case llvm::Triple::riscv32be:
9180 case llvm::Triple::riscv64be:
9181 AddRISCVTargetArgs(Args, CmdArgs);
9182 break;
9183
9184 case llvm::Triple::hexagon:
9185 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9186 options::OPT_mno_default_build_attributes, true)) {
9187 CmdArgs.push_back("-mllvm");
9188 CmdArgs.push_back("-hexagon-add-build-attributes");
9189 }
9190 break;
9191 }
9192
9193 // Consume all the warning flags. Usually this would be handled more
9194 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9195 // doesn't handle that so rather than warning about unused flags that are
9196 // actually used, we'll lie by omission instead.
9197 // FIXME: Stop lying and consume only the appropriate driver flags
9198 Args.ClaimAllArgs(options::OPT_W_Group);
9199
9200 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9201 getToolChain().getDriver());
9202
9203 // Forward -Xclangas arguments to -cc1as
9204 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9205 Arg->claim();
9206 CmdArgs.push_back(Arg->getValue());
9207 }
9208
9209 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9210
9211 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9212 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9213 Output.getFilename());
9214
9215 // Fixup any previous commands that use -object-file-name because when we
9216 // generated them, the final .obj name wasn't yet known.
9217 for (Command &J : C.getJobs()) {
9218 if (SourceAction != FindSource(&J.getSource()))
9219 continue;
9220 auto &JArgs = J.getArguments();
9221 for (unsigned I = 0; I < JArgs.size(); ++I) {
9222 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9223 Output.isFilename()) {
9224 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9225 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9226 Output.getFilename());
9227 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9228 J.replaceArguments(NewArgs);
9229 break;
9230 }
9231 }
9232 }
9233
9234 assert(Output.isFilename() && "Unexpected lipo output.");
9235 CmdArgs.push_back("-o");
9236 CmdArgs.push_back(Output.getFilename());
9237
9238 const llvm::Triple &T = getToolChain().getTriple();
9239 Arg *A;
9240 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9241 T.isOSBinFormatELF()) {
9242 CmdArgs.push_back("-split-dwarf-output");
9243 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9244 }
9245
9246 if (Triple.isAMDGPU())
9247 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9248
9249 assert(Input.isFilename() && "Invalid input.");
9250 CmdArgs.push_back(Input.getFilename());
9251
9252 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9253 if (D.CC1Main && !D.CCGenDiagnostics) {
9254 // Invoke cc1as directly in this process.
9255 C.addCommand(std::make_unique<CC1Command>(
9256 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9257 Output, D.getPrependArg()));
9258 } else {
9259 C.addCommand(std::make_unique<Command>(
9260 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9261 Output, D.getPrependArg()));
9262 }
9263}
9264
9265// Begin OffloadBundler
9267 const InputInfo &Output,
9268 const InputInfoList &Inputs,
9269 const llvm::opt::ArgList &TCArgs,
9270 const char *LinkingOutput) const {
9271 // The version with only one output is expected to refer to a bundling job.
9272 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9273
9274 // The bundling command looks like this:
9275 // clang-offload-bundler -type=bc
9276 // -targets=host-triple,openmp-triple1,openmp-triple2
9277 // -output=output_file
9278 // -input=unbundle_file_host
9279 // -input=unbundle_file_tgt1
9280 // -input=unbundle_file_tgt2
9281
9282 ArgStringList CmdArgs;
9283
9284 // Get the type.
9285 CmdArgs.push_back(TCArgs.MakeArgString(
9286 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9287
9288 assert(JA.getInputs().size() == Inputs.size() &&
9289 "Not have inputs for all dependence actions??");
9290
9291 // Get the targets.
9292 SmallString<128> Triples;
9293 Triples += "-targets=";
9294 for (unsigned I = 0; I < Inputs.size(); ++I) {
9295 if (I)
9296 Triples += ',';
9297
9298 // Find ToolChain for this input.
9300 const ToolChain *CurTC = &getToolChain();
9301 const Action *CurDep = JA.getInputs()[I];
9302
9303 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9304 CurTC = nullptr;
9305 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
9306 assert(CurTC == nullptr && "Expected one dependence!");
9307 CurKind = A->getOffloadingDeviceKind();
9308 CurTC = TC;
9309 });
9310 }
9311 Triples += Action::GetOffloadKindName(CurKind);
9312 Triples += '-';
9313 Triples +=
9314 CurTC->getTriple().normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9315 if (CurKind != Action::OFK_Host &&
9316 !StringRef(CurDep->getOffloadingArch()).empty()) {
9317 Triples += '-';
9318 Triples += CurDep->getOffloadingArch();
9319 }
9320 }
9321 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9322
9323 // Get bundled file command.
9324 CmdArgs.push_back(
9325 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9326
9327 // Get unbundled files command.
9328 for (unsigned I = 0; I < Inputs.size(); ++I) {
9330 UB += "-input=";
9331
9332 // Find ToolChain for this input.
9333 const ToolChain *CurTC = &getToolChain();
9334 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9335 CurTC = nullptr;
9336 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
9337 assert(CurTC == nullptr && "Expected one dependence!");
9338 CurTC = TC;
9339 });
9340 UB += C.addTempFile(
9341 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9342 } else {
9343 UB += CurTC->getInputFilename(Inputs[I]);
9344 }
9345 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9346 }
9347 addOffloadCompressArgs(TCArgs, CmdArgs);
9348 // All the inputs are encoded as commands.
9349 C.addCommand(std::make_unique<Command>(
9350 JA, *this, ResponseFileSupport::None(),
9351 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9352 CmdArgs, ArrayRef<InputInfo>(), Output));
9353}
9354
9356 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9357 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9358 const char *LinkingOutput) const {
9359 // The version with multiple outputs is expected to refer to a unbundling job.
9360 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
9361
9362 // The unbundling command looks like this:
9363 // clang-offload-bundler -type=bc
9364 // -targets=host-triple,openmp-triple1,openmp-triple2
9365 // -input=input_file
9366 // -output=unbundle_file_host
9367 // -output=unbundle_file_tgt1
9368 // -output=unbundle_file_tgt2
9369 // -unbundle
9370
9371 ArgStringList CmdArgs;
9372
9373 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9374 InputInfo Input = Inputs.front();
9375
9376 // Get the type.
9377 CmdArgs.push_back(TCArgs.MakeArgString(
9378 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
9379
9380 // Get the targets.
9381 SmallString<128> Triples;
9382 Triples += "-targets=";
9383 auto DepInfo = UA.getDependentActionsInfo();
9384 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9385 if (I)
9386 Triples += ',';
9387
9388 auto &Dep = DepInfo[I];
9389 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
9390 Triples += '-';
9391 Triples += Dep.DependentToolChain->getTriple().normalize(
9392 llvm::Triple::CanonicalForm::FOUR_IDENT);
9393 if (Dep.DependentOffloadKind != Action::OFK_Host &&
9394 !Dep.DependentBoundArch.empty()) {
9395 Triples += '-';
9396 Triples += Dep.DependentBoundArch;
9397 }
9398 }
9399
9400 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9401
9402 // Get bundled file command.
9403 CmdArgs.push_back(
9404 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
9405
9406 // Get unbundled files command.
9407 for (unsigned I = 0; I < Outputs.size(); ++I) {
9409 UB += "-output=";
9410 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
9411 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9412 }
9413 CmdArgs.push_back("-unbundle");
9414 CmdArgs.push_back("-allow-missing-bundles");
9415 if (TCArgs.hasArg(options::OPT_v))
9416 CmdArgs.push_back("-verbose");
9417
9418 // All the inputs are encoded as commands.
9419 C.addCommand(std::make_unique<Command>(
9420 JA, *this, ResponseFileSupport::None(),
9421 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9422 CmdArgs, ArrayRef<InputInfo>(), Outputs));
9423}
9424
9426 const InputInfo &Output,
9427 const InputInfoList &Inputs,
9428 const llvm::opt::ArgList &Args,
9429 const char *LinkingOutput) const {
9430 ArgStringList CmdArgs;
9431
9432 // Add the output file name.
9433 assert(Output.isFilename() && "Invalid output.");
9434 CmdArgs.push_back("-o");
9435 CmdArgs.push_back(Output.getFilename());
9436
9437 // Create the inputs to bundle the needed metadata.
9438 for (const InputInfo &Input : Inputs) {
9439 const Action *OffloadAction = Input.getAction();
9441 const ArgList &TCArgs =
9442 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9444 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9445 StringRef Arch = OffloadAction->getOffloadingArch()
9447 : TCArgs.getLastArgValue(options::OPT_march_EQ);
9448 StringRef Kind =
9450
9451 ArgStringList Features;
9452 SmallVector<StringRef> FeatureArgs;
9453 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9454 false);
9455 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9456 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9457
9458 // TODO: We need to pass in the full target-id and handle it properly in the
9459 // linker wrapper.
9461 "file=" + File.str(),
9462 "triple=" + TC->getTripleString().str(),
9463 "arch=" + (Arch.empty() ? "generic" : Arch.str()),
9464 "kind=" + Kind.str(),
9465 };
9466
9468 for (StringRef Feature : FeatureArgs)
9469 Parts.emplace_back("feature=" + Feature.str());
9470
9471 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9472 }
9473
9474 C.addCommand(std::make_unique<Command>(
9476 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9477 CmdArgs, Inputs, Output));
9478}
9479
9480// Options that need the profile compiler-rt library on the target toolchain.
9481// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9482// too.
9483static bool requiresProfileRT(unsigned ID) {
9484 switch (ID) {
9485 case options::OPT_fprofile_generate:
9486 case options::OPT_fprofile_generate_EQ:
9487 case options::OPT_fprofile_instr_generate:
9488 case options::OPT_fprofile_instr_generate_EQ:
9489 case options::OPT_fcoverage_mapping:
9490 case options::OPT_fno_coverage_mapping:
9491 case options::OPT_fcoverage_compilation_dir_EQ:
9492 case options::OPT_ffile_compilation_dir_EQ:
9493 case options::OPT_fcoverage_prefix_map_EQ:
9494 return true;
9495 default:
9496 return false;
9497 }
9498}
9499
9500// Options that need the ubsan compiler-rt library on the target toolchain.
9501static bool requiresUBSanRT(unsigned ID) {
9502 switch (ID) {
9503 case options::OPT_fsanitize_EQ:
9504 case options::OPT_fno_sanitize_EQ:
9505 case options::OPT_fsanitize_minimal_runtime:
9506 case options::OPT_fno_sanitize_minimal_runtime:
9507 return true;
9508 default:
9509 return false;
9510 }
9511}
9512
9514 const InputInfo &Output,
9515 const InputInfoList &Inputs,
9516 const ArgList &Args,
9517 const char *LinkingOutput) const {
9518 using namespace options;
9519
9520 // A list of permitted options that will be forwarded to the embedded device
9521 // compilation job.
9522 const llvm::DenseSet<unsigned> CompilerOptions{
9523 OPT_v,
9524 OPT_hip_path_EQ,
9525 OPT_O_Group,
9526 OPT_g_Group,
9527 OPT_g_flags_Group,
9528 OPT_R_value_Group,
9529 OPT_R_Group,
9530 OPT_Xcuda_ptxas,
9531 OPT_ftime_report,
9532 OPT_ftime_trace,
9533 OPT_ftime_trace_EQ,
9534 OPT_ftime_trace_granularity_EQ,
9535 OPT_ftime_trace_verbose,
9536 OPT_opt_record_file,
9537 OPT_opt_record_format,
9538 OPT_opt_record_passes,
9539 OPT_fsave_optimization_record,
9540 OPT_fsave_optimization_record_EQ,
9541 OPT_fno_save_optimization_record,
9542 OPT_foptimization_record_file_EQ,
9543 OPT_foptimization_record_passes_EQ,
9544 OPT_save_temps,
9545 OPT_save_temps_EQ,
9546 OPT_mcode_object_version_EQ,
9547 OPT_load,
9548 OPT_no_canonical_prefixes,
9549 OPT_fno_lto,
9550 OPT_flto,
9551 OPT_flto_partitions_EQ,
9552 OPT_flto_EQ,
9553 OPT_hipspv_pass_plugin_EQ,
9554 OPT_use_spirv_backend,
9555 OPT_fmultilib_flag,
9556 OPT_fprofile_generate,
9557 OPT_fprofile_generate_EQ,
9558 OPT_fprofile_instr_generate,
9559 OPT_fprofile_instr_generate_EQ,
9560 OPT_fcoverage_mapping,
9561 OPT_fno_coverage_mapping,
9562 OPT_fcoverage_compilation_dir_EQ,
9563 OPT_ffile_compilation_dir_EQ,
9564 OPT_fcoverage_prefix_map_EQ,
9565 OPT_fsanitize_EQ,
9566 OPT_fno_sanitize_EQ,
9567 OPT_fsanitize_minimal_runtime,
9568 OPT_fno_sanitize_minimal_runtime,
9569 OPT_fsanitize_trap_EQ,
9570 OPT_fno_sanitize_trap_EQ};
9571 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9572 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9573 return TC.getVFS().exists(
9574 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9575 };
9576 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9577 unsigned ID = A->getOption().getID();
9578 // Don't forward profiling arguments if the toolchain doesn't support it.
9579 // Without this check using it on the host would result in linker errors.
9580 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9581 // together to avoid a device cc1 diagnostic.
9582 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9583 return false;
9584 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9585 // Without this check using it on the host would result in linker errors.
9586 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal"))
9587 return false;
9588 // Don't forward -mllvm to toolchains that don't support LLVM.
9589 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9590 };
9591 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9592 const ToolChain &TC) {
9593 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9594 if (A->getOption().matches(OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9595 return false;
9596 return (Set.contains(A->getOption().getID()) ||
9597 (A->getOption().getGroup().isValid() &&
9598 Set.contains(A->getOption().getGroup().getID()))) &&
9599 ShouldForwardForToolChain(A, TC);
9600 };
9601
9602 ArgStringList CmdArgs;
9605 auto TCRange = C.getOffloadToolChains(Kind);
9606 for (auto &I : llvm::make_range(TCRange)) {
9607 const ToolChain *TC = I.second;
9608
9609 // We do not use a bound architecture here so options passed only to a
9610 // specific architecture via -Xarch_<cpu> will not be forwarded.
9611 ArgStringList CompilerArgs;
9612 ArgStringList LinkerArgs;
9613 const DerivedArgList &ToolChainArgs =
9614 C.getArgsForToolChain(TC, /*BoundArch=*/"", Kind);
9615 for (Arg *A : ToolChainArgs) {
9616 if (A->getOption().matches(OPT_Zlinker_input))
9617 LinkerArgs.emplace_back(A->getValue());
9618 else if (ShouldForward(CompilerOptions, A, *TC))
9619 A->render(Args, CompilerArgs);
9620 else if (ShouldForward(LinkerOptions, A, *TC))
9621 A->render(Args, LinkerArgs);
9622 }
9623
9624 // If the user explicitly requested it via `--offload-arch` we should
9625 // extract it from any static libraries if present.
9626 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))
9627 CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));
9628
9629 // If this is OpenMP the device linker will need `-lompdevice`.
9630 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9631 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9632 LinkerArgs.emplace_back("-lompdevice");
9633
9634 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9635 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9636 // flags to normal compilation.
9637 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9638 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9639 if (TC->getTriple().isSPIRV() &&
9640 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9641 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9642 // For SPIR-V some functions will be defined by the runtime so allow
9643 // unresolved symbols in `spirv-link`.
9644 LinkerArgs.emplace_back("--allow-partial-linkage");
9645 // Don't optimize out exported symbols.
9646 LinkerArgs.emplace_back("--create-library");
9647 }
9648
9649 // Forward all of these to the appropriate toolchain.
9650 for (StringRef Arg : CompilerArgs)
9651 CmdArgs.push_back(Args.MakeArgString(
9652 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9653 for (StringRef Arg : LinkerArgs)
9654 CmdArgs.push_back(Args.MakeArgString(
9655 "--device-linker=" + TC->getTripleString() + "=" + Arg));
9656
9657 // Forward the LTO mode for this toolchain.
9658 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
9659 if (DeviceLTOMode == LTOK_Full)
9660 CmdArgs.push_back(Args.MakeArgString(
9661 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9662 else if (DeviceLTOMode == LTOK_Thin) {
9663 CmdArgs.push_back(Args.MakeArgString(
9664 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9665 if (TC->getTriple().isAMDGPU()) {
9666 CmdArgs.push_back(
9667 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9668 "=-plugin-opt=-force-import-all"));
9669 CmdArgs.push_back(
9670 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9671 "=-plugin-opt=-avail-extern-to-local"));
9672 CmdArgs.push_back(Args.MakeArgString(
9673 "--device-linker=" + TC->getTripleString() +
9674 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9675 if (Kind == Action::OFK_OpenMP) {
9676 CmdArgs.push_back(
9677 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9678 "=-plugin-opt=-amdgpu-internalize-symbols"));
9679 }
9680 }
9681 }
9682
9683 if (JA.getType() == types::TY_HIP_FATBIN && Kind == Action::OFK_HIP) {
9684 // Non-RDC HIP uses the conventional non-LTO pipeline unless the user
9685 // opts into offload LTO.
9686 bool UsesProfileGenerate = Args.hasArg(
9687 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
9688 options::OPT_fprofile_instr_generate,
9689 options::OPT_fprofile_instr_generate_EQ);
9690 if (TC->getLTOMode(Args, Kind) == LTOK_None && !UsesProfileGenerate)
9691 CmdArgs.push_back("--no-lto");
9692 }
9693 }
9694 }
9695
9696 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9697 CmdArgs.push_back(
9698 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
9699 else
9700 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
9701 getToolChain().getTripleString()));
9702
9703 // CMake hack, suppress passing verbose arguments for the special-case HIP
9704 // non-RDC mode compilation. This confuses default CMake implicit linker
9705 // argument parsing when the language is set to HIP and the system linker is
9706 // also `ld.lld`.
9707 if (Args.hasArg(options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9708 CmdArgs.push_back("--wrapper-verbose");
9709 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
9710 CmdArgs.push_back(
9711 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
9712 CmdArgs.push_back(Args.MakeArgString(
9713 Twine("--device-compiler=--cuda-path=") + A->getValue()));
9714 }
9715 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
9716 CmdArgs.push_back(Args.MakeArgString(
9717 Twine("--device-compiler=--rocm-path=") + A->getValue()));
9718 }
9719
9720 // Construct the link job so we can wrap around it.
9721 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9722 const auto &LinkCommand = C.getJobs().getJobs().back();
9723
9724 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9725 // wrapper.
9726 for (Arg *A :
9727 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
9728 StringRef Val = A->getValue(0);
9729 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9730 auto WrapperOption =
9731 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9732 if (Val.empty())
9733 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
9734 else
9735 CmdArgs.push_back(Args.MakeArgString(
9736 WrapperOption +
9737 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
9738 A->getValue(1)));
9739 }
9740 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
9741 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9742
9743 // Embed bitcode instead of an object in JIT mode.
9744 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
9745 options::OPT_fno_openmp_target_jit, false))
9746 CmdArgs.push_back("--embed-bitcode");
9747
9748 // Save temporary files created by the linker wrapper.
9749 if (Args.hasArg(options::OPT_save_temps_EQ) ||
9750 Args.hasArg(options::OPT_save_temps))
9751 CmdArgs.push_back("--save-temps");
9752
9753 // Pass in the C library for GPUs if present and not disabled.
9754 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
9755 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
9756 options::OPT_nodefaultlibs, options::OPT_nolibc,
9757 options::OPT_nogpulibc)) {
9758 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
9759 // The device C library is only available for NVPTX and AMDGPU targets
9760 // and we only link it by default for OpenMP currently.
9761 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
9763 return;
9764 bool HasLibC = TC.getStdlibIncludePath().has_value();
9765 if (HasLibC) {
9766 CmdArgs.push_back(Args.MakeArgString(
9767 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9768 CmdArgs.push_back(Args.MakeArgString(
9769 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9770 }
9771 auto HasCompilerRT = getToolChain().getVFS().exists(
9772 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
9773 /*IsFortran=*/false));
9774 if (HasCompilerRT)
9775 CmdArgs.push_back(
9776 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
9777 "-lclang_rt.builtins"));
9778
9779 bool HasFlangRT = getToolChain().getVFS().exists(
9780 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
9781 /*IsFortran=*/true));
9782 if (HasFlangRT && C.getDriver().IsFlangMode())
9783 CmdArgs.push_back(
9784 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
9785 "-lflang_rt.runtime"));
9786 });
9787 }
9788
9789 // Add the linker arguments to be forwarded by the wrapper.
9790 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
9791 LinkCommand->getExecutable()));
9792
9793 // We use action type to differentiate two use cases of the linker wrapper.
9794 // TY_Image for normal linker wrapper work.
9795 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
9796 assert(JA.getType() == types::TY_HIP_FATBIN ||
9797 JA.getType() == types::TY_Image);
9798 if (JA.getType() == types::TY_HIP_FATBIN) {
9799 CmdArgs.push_back("--emit-fatbin-only");
9800 CmdArgs.append({"-o", Output.getFilename()});
9801 for (auto Input : Inputs)
9802 CmdArgs.push_back(Input.getFilename());
9803 } else {
9804 for (const char *LinkArg : LinkCommand->getArguments())
9805 CmdArgs.push_back(LinkArg);
9806 }
9807
9808 addOffloadCompressArgs(Args, CmdArgs);
9809
9810 if (Arg *A = Args.getLastArg(options::OPT_offload_jobs_EQ)) {
9811 StringRef Val = A->getValue();
9812
9813 if (Val.equals_insensitive("jobserver"))
9814 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
9815 else {
9816 int NumThreads;
9817 if (Val.getAsInteger(10, NumThreads) || NumThreads <= 0) {
9818 C.getDriver().Diag(diag::err_drv_invalid_int_value)
9819 << A->getAsString(Args) << Val;
9820 } else {
9821 CmdArgs.push_back(
9822 Args.MakeArgString("--wrapper-jobs=" + Twine(NumThreads)));
9823 }
9824 }
9825 }
9826
9827 // Propagate -no-canonical-prefixes.
9828 if (Args.hasArg(options::OPT_no_canonical_prefixes))
9829 CmdArgs.push_back("--no-canonical-prefixes");
9830
9831 const char *Exec =
9832 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
9833
9834 // Replace the executable and arguments of the link job with the
9835 // wrapper.
9836 LinkCommand->replaceExecutable(Exec);
9837 LinkCommand->replaceArguments(CmdArgs);
9838}
#define V(N, I)
static StringRef bytes(const std::vector< T, Allocator > &v)
static void RenderDebugInfoCompressionArgs(const ArgList &Args, ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
Definition Clang.cpp:731
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3762
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition Clang.cpp:117
static void renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, types::ID InputType, ArgStringList &CmdArgs, const InputInfo &Output, llvm::codegenoptions::DebugInfoKind &DebugInfoKind, DwarfFissionKind &DwarfFission)
Definition Clang.cpp:4486
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4157
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:705
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4889
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9483
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4338
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:786
static bool addExceptionArgs(const ArgList &Args, types::ID InputType, const ToolChain &TC, bool KernelOrKext, const ObjCRuntime &objcRuntime, ArgStringList &CmdArgs)
Adds exception related arguments to the driver command arguments.
Definition Clang.cpp:137
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:70
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1357
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1209
static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args, bool isWindowsMSVC)
/EH controls whether to run destructor cleanups when exceptions are thrown.
Definition Clang.cpp:8569
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:803
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3837
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4469
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2401
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1247
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:763
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:335
static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3806
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition Clang.cpp:4446
static void RenderObjCOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, ObjCRuntime &Runtime, bool InferCovariantReturns, const InputInfo &Input, ArgStringList &CmdArgs)
Definition Clang.cpp:4193
static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the coverage file path prefix map.
Definition Clang.cpp:320
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition Clang.cpp:2406
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1258
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2412
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:3903
static void forAllAssociatedToolChains(Compilation &C, const JobAction &JA, const ToolChain &RegularToolChain, llvm::function_ref< void(const ToolChain &)> Work)
Apply Work on the current tool chain RegularToolChain and any other offloading tool chain that is ass...
Definition Clang.cpp:97
static bool isValidSymbolName(StringRef S)
Definition Clang.cpp:3442
static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the macro file path prefix map.
Definition Clang.cpp:305
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1274
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition Clang.cpp:250
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition Clang.cpp:1393
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3452
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3845
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3674
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3691
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8548
static const char * addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs, const llvm::vfs::FileSystem &VFS)
Add a CC1 option to specify the debug compilation directory.
Definition Clang.cpp:230
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:85
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC, const JobAction &JA)
Definition Clang.cpp:213
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9501
static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the debug file path prefix map.
Definition Clang.cpp:284
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition Clang.cpp:3373
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2777
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:366
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
TokenType getType() const
Returns the token's type, e.g.
Defines enums used when emitting included header information.
Defines the clang::LangOptions interface.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
Defines version macros and version-related utility functions for Clang.
static StringRef getWarningOptionForGroup(diag::Group)
Given a group ID, returns the flag that toggles the group.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:914
ComplexRangeKind
Controls the various implementations for complex multiplication and.
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ CX_None
No range rule is enabled.
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool allowsWeak() const
Does this runtime allow the use of __weak?
bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch)
The default dispatch mechanism to use for the specified architecture.
Kind getKind() const
Definition ObjCRuntime.h:77
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
bool hasConstantLiteralClasses() const
Are Foundation backed constant literal classes supported?
const VersionTuple & getVersion() const
Definition ObjCRuntime.h:78
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition ObjCRuntime.h:82
std::string getAsString() const
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition ObjCRuntime.h:56
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition ObjCRuntime.h:53
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Scope(Scope *Parent, unsigned ScopeFlags, DiagnosticsEngine &Diag)
Definition Scope.h:263
Action - Represent an abstract compilation step to perform.
Definition Action.h:47
const char * getOffloadingArch() const
Definition Action.h:216
types::ID getType() const
Definition Action.h:153
const ToolChain * getOffloadingToolChain() const
Definition Action.h:217
static std::string GetOffloadingFileNamePrefix(OffloadKind Kind, StringRef NormalizedTriple, bool CreatePrefixForHost=false)
Return a string that can be used as prefix in order to generate unique files for each offloading kind...
Definition Action.cpp:148
ActionClass getKind() const
Definition Action.h:152
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:164
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:215
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:223
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:226
ActionList & getInputs()
Definition Action.h:155
unsigned getOffloadingHostActiveKinds() const
Definition Action.h:211
bool isOffloading(OffloadKind OKind) const
Definition Action.h:229
Command - An executable path/name and argument vector to execute.
Definition Job.h:106
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:45
std::pair< const_offload_toolchains_iterator, const_offload_toolchains_iterator > const_offload_toolchains_range
Distro - Helper class for detecting and classifying Linux distributions.
Definition Distro.h:23
bool IsGentoo() const
Definition Distro.h:134
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:94
std::string SysRoot
sysroot, if present
Definition Driver.h:194
DiagnosticsEngine & getDiags() const
Definition Driver.h:408
const char * getPrependArg() const
Definition Driver.h:419
CC1ToolFunc CC1Main
Definition Driver.h:290
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:845
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:230
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:268
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:3869
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:272
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:158
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:282
llvm::SmallVector< StringRef > getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, Action::OffloadKind Kind, const ToolChain &TC) const
Returns the set of bound architectures active for this offload kind.
Definition Driver.cpp:4898
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:7019
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2431
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:430
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:218
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:215
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:178
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:410
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:154
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:144
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:251
std::string getTargetTriple() const
Definition Driver.h:427
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:257
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:172
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:224
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:221
bool getProbePrecompiled() const
Definition Driver.h:416
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getBaseInput() const
Definition InputInfo.h:78
const llvm::opt::Arg & getInputArg() const
Definition InputInfo.h:87
const char * getFilename() const
Definition InputInfo.h:83
bool isNothing() const
Definition InputInfo.h:74
const Action * getAction() const
The action for which this InputInfo was created. May be null.
Definition InputInfo.h:80
bool isFilename() const
Definition InputInfo.h:75
types::ID getType() const
Definition InputInfo.h:77
An offload action combines host or/and device actions according to the programming model implementati...
Definition Action.h:273
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:95
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:904
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:657
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
virtual unsigned getMaxDwarfVersion() const
Definition ToolChain.h:666
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:690
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
virtual llvm::DenormalMode getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs, const JobAction &JA, const llvm::fltSemantics *FPType=nullptr) const
Returns the output denormal handling type in the default floating point environment for the given FPT...
Definition ToolChain.h:896
virtual UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const
How detailed should the unwind tables be by default.
virtual std::string getInputFilename(const InputInfo &Input) const
Some toolchains need to modify the file name, for example to replace the extension for object files w...
virtual llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const
Get the default debug info format. Typically, this is DWARF.
Definition ToolChain.h:648
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:520
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:301
const Driver & getDriver() const
Definition ToolChain.h:285
RTTIMode getRTTIMode() const
Definition ToolChain.h:368
llvm::vfs::FileSystem & getVFS() const
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
virtual llvm::DebuggerKind getDefaultDebuggerTuning() const
Definition ToolChain.h:679
void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set the specified include paths ...
LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:313
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:541
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
virtual bool IsMathErrnoDefault() const
IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
Definition ToolChain.h:512
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:701
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:672
const llvm::Triple & getTriple() const
Definition ToolChain.h:287
bool defaultToIEEELongDouble() const
Check whether use IEEE binary128 as long double format by default.
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
virtual bool getDefaultDebugSimpleTemplateNames() const
Returns true if this toolchain adds '-gsimple-template-names=simple' by default when generating debug...
Definition ToolChain.h:676
const XRayArgs getXRayArgs(const llvm::opt::ArgList &) const
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
StringRef getTripleString() const
Definition ToolChain.h:310
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:535
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:742
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:654
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:642
virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific HIP includes.
virtual bool canSplitThinLTOUnit() const
Returns true when it's possible to split LTO unit to use whole program devirtualization and CFI santi...
Definition ToolChain.h:891
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
virtual void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific SYCL includes.
virtual bool UseObjCMixedDispatch() const
UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the mixed dispatch method be use...
Definition ToolChain.h:524
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
std::optional< std::string > getStdlibIncludePath() const
virtual void addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const
Add options that need to be passed to cc1as for this target.
virtual bool IsIntegratedAssemblerDefault() const
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition ToolChain.h:487
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
virtual void CheckObjCARC() const
Complain if this tool chain doesn't support Objective-C ARC.
Definition ToolChain.h:645
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
virtual bool IsEncodeExtendedBlockSignatureDefault() const
IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable -fencode-extended-block-signature...
Definition ToolChain.h:516
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:483
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, StringRef BoundArch="", Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
virtual const llvm::Triple * getAuxTriple() const
Get the toolchain's aux triple, if it has one.
Definition ToolChain.h:294
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:509
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
const ToolChain & getToolChain() const
Definition Tool.h:52
Tool(const char *Name, const char *ShortName, const ToolChain &TC)
Definition Tool.cpp:14
const char * getShortName() const
Definition Tool.h:50
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
Definition XRayArgs.cpp:181
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:610
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:8937
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:8920
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:8945
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:8960
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:8909
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:8879
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8404
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:8894
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:8884
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:4989
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:9513
void ConstructJobMultipleOutputs(Compilation &C, const JobAction &JA, const InputInfoList &Outputs, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
Construct jobs to perform the action JA, writing to the Outputs and with Inputs, and add the jobs to ...
Definition Clang.cpp:9355
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:9266
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:9425
void addSanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addProfileRTArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
std::optional< std::string > getAArch64TargetTuneCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition AArch64.cpp:117
bool isHardTPSupported(const llvm::Triple &Triple)
Definition ARM.cpp:210
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
StringRef getLoongArchABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::string postProcessTargetCPUString(const std::string &CPU, const llvm::Triple &Triple)
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
bool hasCompactBranches(StringRef &CPU)
Definition Mips.cpp:441
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
FloatABI getPPCFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:269
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
FloatABI getSparcFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
FloatABI getSystemZFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
void addX86AlignBranchArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsLTO, const StringRef PluginOptPrefix="")
void addMachineOutlinerArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple, bool IsLTO, const StringRef PluginOptPrefix="")
unsigned ParseFunctionAlignment(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs)
void addMCModel(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple, const llvm::Reloc::Model &RelocationModel, llvm::opt::ArgStringList &CmdArgs)
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
void handleVectorizeSLPArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fslp-vectorize based on the optimization level selected.
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
void getTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForAS, bool IsAux=false)
std::string complexRangeKindToStr(LangOptions::ComplexRangeKind Range)
void handleColorDiagnosticsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Handle the -f{no}-color-diagnostics and -f{no}-diagnostics-colors options.
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine)
Check if the command line should be recorded in the object file.
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
llvm::SmallString< 256 > getCXX20NamedModuleOutputPath(const llvm::opt::ArgList &Args, const char *BaseInput)
void setComplexRange(const Driver &D, StringRef NewOpt, LangOptions::ComplexRangeKind NewRange, StringRef &LastOpt, LangOptions::ComplexRangeKind &Range)
bool haveAMDGPUCodeObjectVersionArgument(const Driver &D, const llvm::opt::ArgList &Args)
bool isTLSDESCEnabled(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addDebugInfoForProfilingArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
llvm::opt::Arg * getLastCSProfileGenerateArg(const llvm::opt::ArgList &Args)
void renderGlobalISelOptions(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
std::string renderComplexRangeOption(LangOptions::ComplexRangeKind Range)
DwarfFissionKind getDebugFissionKind(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::Arg *&Arg)
const char * renderEscapedCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args)
Join the args in the given ArgList, escape spaces and backslashes and return the joined string.
void renderCommonIntegerOverflowOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsMSVCCompat)
bool checkDebugInfoOption(const llvm::opt::Arg *A, const llvm::opt::ArgList &Args, const Driver &D, const ToolChain &TC)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
unsigned DwarfVersionNum(StringRef ArgValue)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
const llvm::opt::Arg * getDwarfNArg(const llvm::opt::ArgList &Args)
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
void addSeparateSectionFlags(const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Append -ffunction-sections / -fdata-sections to CmdArgs when the corresponding flags are enabled (exp...
void handleVectorizeLoopsArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fvectorize based on the optimization level selected.
void escapeSpacesAndBackslashes(const char *Arg, llvm::SmallVectorImpl< char > &Res)
Add backslashes to escape spaces and other backslashes.
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
const char * RelocationModelName(llvm::Reloc::Model Model)
void addOpenMPHostOffloadingArgs(const Compilation &C, const JobAction &JA, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds offloading options for OpenMP host compilation to CmdArgs.
bool isHLSL(ID Id)
isHLSL - Is this an HLSL input.
Definition Types.cpp:326
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:237
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition Types.cpp:53
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition Types.cpp:289
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition Types.cpp:49
bool isOpenCL(ID Id)
isOpenCL - Is this an "OpenCL" input.
Definition Types.cpp:250
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:328
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition Types.cpp:81
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition Types.cpp:262
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:50
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool willEmitRemarks(const llvm::opt::ArgList &Args)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
The JSON file list parser is used to communicate input to InstallAPI.
std::optional< diag::Group > diagGroupFromCLWarningID(unsigned)
For cl.exe warning IDs that cleany map to clang diagnostic groups, returns the corresponding group.
bool isa(CodeGen::Address addr)
Definition Address.h:330
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
const char * headerIncludeFormatKindToString(HeaderIncludeFormatKind K)
unsigned CudaArchToID(OffloadArch Arch)
Get the numeric ID (e.g. 700) of a CUDA architecture.
Definition Cuda.cpp:186
StringRef parseMPreferVectorWidthOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
const char * headerIncludeFilteringKindToString(HeaderIncludeFilteringKind K)
@ C
Languages that the frontend can parse and compile.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
static bool IsNVIDIAOffloadArch(OffloadArch A)
const char * CudaVersionToString(CudaVersion V)
Definition Cuda.cpp:56
OffloadArch StringToOffloadArch(llvm::StringRef S)
LanguageStandard
Supported language standards for parsing and formatting C++ constructs.
Definition Format.h:5800
U cast(CodeGen::Address addr)
Definition Address.h:327
StringRef parseMRecipOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition Version.cpp:96
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:36
LangStandard - Information about the properties of a particular language standard.
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
static const LangStandard * getLangStandardForName(StringRef Name)
bool isCPlusPlus17() const
isCPlusPlus17 - Language is a C++17 variant (or later).
clang::Language getLanguage() const
Get the language that this standard describes.
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:78
static constexpr ResponseFileSupport AtFileUTF8()
Definition Job.h:85