clang 24.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/Error.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/Process.h"
54#include "llvm/Support/YAMLParser.h"
55#include "llvm/TargetParser/AArch64TargetParser.h"
56#include "llvm/TargetParser/ARMTargetParserCommon.h"
57#include "llvm/TargetParser/Host.h"
58#include "llvm/TargetParser/LoongArchTargetParser.h"
59#include "llvm/TargetParser/PPCTargetParser.h"
60#include "llvm/TargetParser/RISCVISAInfo.h"
61#include "llvm/TargetParser/RISCVTargetParser.h"
62#include <cctype>
63#include <iterator>
64
65using namespace clang::driver;
66using namespace clang::driver::tools;
67using namespace clang;
68using namespace llvm::opt;
69
70static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
71 if (Arg *A = Args.getLastArg(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 bool IsDeviceOffloadAction,
140 const ObjCRuntime &objcRuntime,
141 ArgStringList &CmdArgs) {
142 const llvm::Triple &Triple = TC.getTriple();
143
144 if (KernelOrKext) {
145 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
146 // arguments now to avoid warnings about unused arguments.
147 Args.ClaimAllArgs(options::OPT_fexceptions);
148 Args.ClaimAllArgs(options::OPT_fno_exceptions);
149 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
150 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
151 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
152 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
153 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
154 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
155 return false;
156 }
157
158 // See if the user explicitly enabled exceptions.
159 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
160 false);
161
162 // Async exceptions are Windows MSVC only.
163 if (Triple.isWindowsMSVCEnvironment()) {
164 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
165 options::OPT_fno_async_exceptions, false);
166 if (EHa) {
167 CmdArgs.push_back("-fasync-exceptions");
168 EH = true;
169 }
170 }
171
172 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
173 // is not necessarily sensible, but follows GCC.
174 if (types::isObjC(InputType) &&
175 Args.hasFlag(options::OPT_fobjc_exceptions,
176 options::OPT_fno_objc_exceptions, true)) {
177 CmdArgs.push_back("-fobjc-exceptions");
178
179 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
180 }
181
182 if (types::isCXX(InputType)) {
183 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
184 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
185 !Triple.isPS() && !Triple.isDriverKit() &&
186 !(Triple.isGPU() && !IsDeviceOffloadAction);
187 Arg *ExceptionArg = Args.getLastArg(
188 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
189 options::OPT_fexceptions, options::OPT_fno_exceptions);
190 if (ExceptionArg)
191 CXXExceptionsEnabled =
192 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
193 ExceptionArg->getOption().matches(options::OPT_fexceptions);
194
195 if (CXXExceptionsEnabled) {
196 CmdArgs.push_back("-fcxx-exceptions");
197
198 EH = true;
199 }
200 }
201
202 // OPT_fignore_exceptions means exception could still be thrown,
203 // but no clean up or catch would happen in current module.
204 // So we do not set EH to false.
205 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
206
207 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
208 options::OPT_fno_assume_nothrow_exception_dtor);
209
210 if (EH)
211 CmdArgs.push_back("-fexceptions");
212 return EH;
213}
214
215static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
216 const JobAction &JA) {
217 bool Default = true;
218 if (TC.getTriple().isOSDarwin()) {
219 // The native darwin assembler doesn't support the linker_option directives,
220 // so we disable them if we think the .s file will be passed to it.
222 }
223 // The linker_option directives are intended for host compilation.
226 Default = false;
227 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
228 Default);
229}
230
231/// Add a CC1 option to specify the debug compilation directory.
232static const char *addDebugCompDirArg(const ArgList &Args,
233 ArgStringList &CmdArgs,
234 const llvm::vfs::FileSystem &VFS) {
235 std::string DebugCompDir;
236 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
237 options::OPT_fdebug_compilation_dir_EQ))
238 DebugCompDir = A->getValue();
239
240 if (DebugCompDir.empty()) {
241 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
242 DebugCompDir = std::move(*CWD);
243 else
244 return nullptr;
245 }
246 CmdArgs.push_back(
247 Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));
248 StringRef Path(CmdArgs.back());
249 return Path.substr(Path.find('=') + 1).data();
250}
251
252static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
253 const char *DebugCompilationDir,
254 const char *OutputFileName) {
255 // No need to generate a value for -object-file-name if it was provided.
256 for (auto *Arg : Args.filtered(options::OPT_Xclang))
257 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
258 return;
259
260 if (Args.hasArg(options::OPT_object_file_name_EQ))
261 return;
262
263 SmallString<128> ObjFileNameForDebug(OutputFileName);
264 if (ObjFileNameForDebug != "-" &&
265 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
266 (!DebugCompilationDir ||
267 llvm::sys::path::is_absolute(DebugCompilationDir))) {
268 // Make the path absolute in the debug infos like MSVC does.
269 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
270 }
271 // If the object file name is a relative path, then always use Windows
272 // backslash style as -object-file-name is used for embedding object file path
273 // in codeview and it can only be generated when targeting on Windows.
274 // Otherwise, just use native absolute path.
275 llvm::sys::path::Style Style =
276 llvm::sys::path::is_absolute(ObjFileNameForDebug)
277 ? llvm::sys::path::Style::native
278 : llvm::sys::path::Style::windows_backslash;
279 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
280 Style);
281 CmdArgs.push_back(
282 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
283}
284
285/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
286static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
287 const ArgList &Args, ArgStringList &CmdArgs) {
288 auto AddOneArg = [&](StringRef Map, StringRef Name) {
289 if (!Map.contains('='))
290 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
291 else
292 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
293 };
294
295 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
296 options::OPT_fdebug_prefix_map_EQ)) {
297 AddOneArg(A->getValue(), A->getOption().getName());
298 A->claim();
299 }
300 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
301 if (GlobalRemapEntry.empty())
302 return;
303 AddOneArg(GlobalRemapEntry, "environment");
304}
305
306/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
307static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
308 ArgStringList &CmdArgs) {
309 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
310 options::OPT_fmacro_prefix_map_EQ)) {
311 StringRef Map = A->getValue();
312 if (!Map.contains('='))
313 D.Diag(diag::err_drv_invalid_argument_to_option)
314 << Map << A->getOption().getName();
315 else
316 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
317 A->claim();
318 }
319}
320
321/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
322static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
323 ArgStringList &CmdArgs) {
324 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
325 options::OPT_fcoverage_prefix_map_EQ)) {
326 StringRef Map = A->getValue();
327 if (!Map.contains('='))
328 D.Diag(diag::err_drv_invalid_argument_to_option)
329 << Map << A->getOption().getName();
330 else
331 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
332 A->claim();
333 }
334}
335
336/// Add -x lang to \p CmdArgs for \p Input.
337static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
338 ArgStringList &CmdArgs) {
339 // When using -verify-pch, we don't want to provide the type
340 // 'precompiled-header' if it was inferred from the file extension
341 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
342 return;
343
344 CmdArgs.push_back("-x");
345 if (Args.hasArg(options::OPT_rewrite_objc))
346 CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));
347 else {
348 // Map the driver type to the frontend type. This is mostly an identity
349 // mapping, except that the distinction between module interface units
350 // and other source files does not exist at the frontend layer.
351 const char *ClangType;
352 switch (Input.getType()) {
353 case types::TY_CXXModule:
354 case types::TY_CXXStdModule:
355 ClangType = "c++";
356 break;
357 case types::TY_PP_CXXModule:
358 ClangType = "c++-cpp-output";
359 break;
360 case types::TY_CIRBC:
361 ClangType = "cir";
362 break;
363 default:
364 ClangType = types::getTypeName(Input.getType());
365 break;
366 }
367 CmdArgs.push_back(ClangType);
368 }
369}
370
372 const JobAction &JA, const InputInfo &Output,
373 const ArgList &Args, SanitizerArgs &SanArgs,
374 ArgStringList &CmdArgs) {
375 const Driver &D = TC.getDriver();
376 const llvm::Triple &T = TC.getTriple();
377 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
378 options::OPT_fprofile_generate_EQ,
379 options::OPT_fno_profile_generate);
380 if (PGOGenerateArg &&
381 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
382 PGOGenerateArg = nullptr;
383
384 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
385
386 auto *ProfileGenerateArg = Args.getLastArg(
387 options::OPT_fprofile_instr_generate,
388 options::OPT_fprofile_instr_generate_EQ,
389 options::OPT_fno_profile_instr_generate);
390 if (ProfileGenerateArg &&
391 ProfileGenerateArg->getOption().matches(
392 options::OPT_fno_profile_instr_generate))
393 ProfileGenerateArg = nullptr;
394
395 if (PGOGenerateArg && ProfileGenerateArg)
396 D.Diag(diag::err_drv_argument_not_allowed_with)
397 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
398
399 auto *ProfileUseArg = getLastProfileUseArg(Args);
400
401 if (PGOGenerateArg && ProfileUseArg)
402 D.Diag(diag::err_drv_argument_not_allowed_with)
403 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
404
405 if (ProfileGenerateArg && ProfileUseArg)
406 D.Diag(diag::err_drv_argument_not_allowed_with)
407 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
408
409 if (CSPGOGenerateArg && PGOGenerateArg) {
410 D.Diag(diag::err_drv_argument_not_allowed_with)
411 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
412 PGOGenerateArg = nullptr;
413 }
414
415 if (TC.getTriple().isOSAIX()) {
416 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
417 D.Diag(diag::err_drv_unsupported_opt_for_target)
418 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
419 }
420
421 if (ProfileGenerateArg) {
422 if (ProfileGenerateArg->getOption().matches(
423 options::OPT_fprofile_instr_generate_EQ))
424 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
425 ProfileGenerateArg->getValue()));
426 // The default is to use Clang Instrumentation.
427 CmdArgs.push_back("-fprofile-instrument=clang");
428 if (TC.getTriple().isWindowsMSVCEnvironment() &&
429 Args.hasFlag(options::OPT_frtlib_defaultlib,
430 options::OPT_fno_rtlib_defaultlib, true)) {
431 // Add dependent lib for clang_rt.profile
432 CmdArgs.push_back(Args.MakeArgString(
433 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
434 }
435 }
436
437 if (auto *ColdFuncCoverageArg = Args.getLastArg(
438 options::OPT_fprofile_generate_cold_function_coverage,
439 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
440 SmallString<128> Path(
441 ColdFuncCoverageArg->getOption().matches(
442 options::OPT_fprofile_generate_cold_function_coverage_EQ)
443 ? ColdFuncCoverageArg->getValue()
444 : "");
445 llvm::sys::path::append(Path, "default_%m.profraw");
446 // FIXME: Idealy the file path should be passed through
447 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
448 // shared with other profile use path(see PGOOptions), we need to refactor
449 // PGOOptions to make it work.
450 CmdArgs.push_back("-mllvm");
451 CmdArgs.push_back(Args.MakeArgString(
452 Twine("--instrument-cold-function-only-path=") + Path));
453 CmdArgs.push_back("-mllvm");
454 CmdArgs.push_back("--pgo-instrument-cold-function-only");
455 CmdArgs.push_back("-mllvm");
456 CmdArgs.push_back("--pgo-function-entry-coverage");
457 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
458 }
459
460 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
461 if (!PGOGenerateArg && !CSPGOGenerateArg)
462 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
463 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
464 CmdArgs.push_back("-mllvm");
465 CmdArgs.push_back("--pgo-temporal-instrumentation");
466 }
467
468 Arg *PGOGenArg = nullptr;
469 if (PGOGenerateArg) {
470 assert(!CSPGOGenerateArg);
471 PGOGenArg = PGOGenerateArg;
472 CmdArgs.push_back("-fprofile-instrument=llvm");
473 }
474 if (CSPGOGenerateArg) {
475 assert(!PGOGenerateArg);
476 PGOGenArg = CSPGOGenerateArg;
477 CmdArgs.push_back("-fprofile-instrument=csllvm");
478 }
479 if (PGOGenArg) {
480 if (TC.getTriple().isWindowsMSVCEnvironment() &&
481 Args.hasFlag(options::OPT_frtlib_defaultlib,
482 options::OPT_fno_rtlib_defaultlib, true)) {
483 // Add dependent lib for clang_rt.profile
484 CmdArgs.push_back(Args.MakeArgString(
485 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
486 }
487 if (PGOGenArg->getOption().matches(
488 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
489 : options::OPT_fcs_profile_generate_EQ)) {
490 SmallString<128> Path(PGOGenArg->getValue());
491 llvm::sys::path::append(Path, "default_%m.profraw");
492 CmdArgs.push_back(
493 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
494 }
495 }
496
497 if (ProfileUseArg) {
498 SmallString<128> UsePathBuf;
499 StringRef UsePath;
500 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
501 UsePath = ProfileUseArg->getValue();
502 else if ((ProfileUseArg->getOption().matches(
503 options::OPT_fprofile_use_EQ) ||
504 ProfileUseArg->getOption().matches(
505 options::OPT_fprofile_instr_use))) {
506 UsePathBuf =
507 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
508 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
509 llvm::sys::path::append(UsePathBuf, "default.profdata");
510 UsePath = UsePathBuf;
511 }
512 auto ReaderOrErr =
513 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
514 if (auto E = ReaderOrErr.takeError()) {
515 auto DiagID = D.getDiags().getCustomDiagID(
516 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
517 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
518 D.Diag(DiagID) << UsePath.str() << EI.message();
519 });
520 } else {
521 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
522 std::move(ReaderOrErr.get());
523 StringRef UseKind;
524 // Currently memprof profiles are only added at the IR level. Mark the
525 // profile type as IR in that case as well and the subsequent matching
526 // needs to detect which is available (might be one or both).
527 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
528 if (PGOReader->hasCSIRLevelProfile())
529 UseKind = "csllvm";
530 else
531 UseKind = "llvm";
532 } else
533 UseKind = "clang";
534
535 CmdArgs.push_back(
536 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
537 CmdArgs.push_back(
538 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
539 }
540 }
541
542 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
543 options::OPT_fno_test_coverage, false) ||
544 Args.hasArg(options::OPT_coverage);
545 bool EmitCovData = TC.needsGCovInstrumentation(Args);
546
547 if (Args.hasFlag(options::OPT_fcoverage_mapping,
548 options::OPT_fno_coverage_mapping, false)) {
549 if (!ProfileGenerateArg)
550 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
551 << "-fcoverage-mapping"
552 << "-fprofile-instr-generate";
553
554 CmdArgs.push_back("-fcoverage-mapping");
555 }
556
557 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
558 false)) {
559 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
560 options::OPT_fno_coverage_mapping, false))
561 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
562 << "-fcoverage-mcdc"
563 << "-fcoverage-mapping";
564
565 CmdArgs.push_back("-fcoverage-mcdc");
566 }
567
568 StringRef CoverageCompDir;
569 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
570 options::OPT_fcoverage_compilation_dir_EQ))
571 CoverageCompDir = A->getValue();
572 if (CoverageCompDir.empty()) {
573 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
574 CmdArgs.push_back(
575 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
576 } else
577 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
578 CoverageCompDir));
579
580 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
581 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
582 if (!Args.hasArg(options::OPT_coverage))
583 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
584 << "-fprofile-exclude-files="
585 << "--coverage";
586
587 StringRef v = Arg->getValue();
588 CmdArgs.push_back(
589 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
590 }
591
592 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
593 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
594 if (!Args.hasArg(options::OPT_coverage))
595 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
596 << "-fprofile-filter-files="
597 << "--coverage";
598
599 StringRef v = Arg->getValue();
600 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
601 }
602
603 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
604 StringRef Val = A->getValue();
605 if (Val == "atomic" || Val == "prefer-atomic")
606 CmdArgs.push_back("-fprofile-update=atomic");
607 else if (Val != "single")
608 D.Diag(diag::err_drv_unsupported_option_argument)
609 << A->getSpelling() << Val;
610 }
611 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
612 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
613 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
614 << A->getSpelling()
615 << "-fprofile-generate, -fprofile-instr-generate, or "
616 "-fcs-profile-generate";
617 else {
618 CmdArgs.push_back("-fprofile-continuous");
619 // Platforms that require a bias variable:
620 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
621 CmdArgs.push_back("-mllvm");
622 CmdArgs.push_back("-runtime-counter-relocation");
623 }
624 // -fprofile-instr-generate does not decide the profile file name in the
625 // FE, and so it does not define the filename symbol
626 // (__llvm_profile_filename). Instead, the runtime uses the name
627 // "default.profraw" for the profile file. When continuous mode is ON, we
628 // will create the filename symbol so that we can insert the "%c"
629 // modifier.
630 if (ProfileGenerateArg &&
631 (ProfileGenerateArg->getOption().matches(
632 options::OPT_fprofile_instr_generate) ||
633 (ProfileGenerateArg->getOption().matches(
634 options::OPT_fprofile_instr_generate_EQ) &&
635 strlen(ProfileGenerateArg->getValue()) == 0)))
636 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
637 }
638 }
639
640 int FunctionGroups = 1;
641 int SelectedFunctionGroup = 0;
642 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
643 StringRef Val = A->getValue();
644 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
645 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
646 }
647 if (const auto *A =
648 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
649 StringRef Val = A->getValue();
650 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
651 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
652 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
653 }
654 if (FunctionGroups != 1)
655 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
656 Twine(FunctionGroups)));
657 if (SelectedFunctionGroup != 0)
658 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
659 Twine(SelectedFunctionGroup)));
660
661 // Leave -fprofile-dir= an unused argument unless .gcda emission is
662 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
663 // the flag used. There is no -fno-profile-dir, so the user has no
664 // targeted way to suppress the warning.
665 Arg *FProfileDir = nullptr;
666 if (Args.hasArg(options::OPT_fprofile_arcs) ||
667 Args.hasArg(options::OPT_coverage))
668 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
669
670 // Put the .gcno and .gcda files (if needed) next to the primary output file,
671 // or fall back to a file in the current directory for `clang -c --coverage
672 // d/a.c` in the absence of -o.
673 if (EmitCovNotes || EmitCovData) {
674 SmallString<128> CoverageFilename;
675 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
676 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
677 // path separator.
678 CoverageFilename = DumpDir->getValue();
679 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
680 } else if (Arg *FinalOutput =
681 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
682 CoverageFilename = FinalOutput->getValue();
683 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
684 CoverageFilename = FinalOutput->getValue();
685 } else {
686 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
687 }
688 if (llvm::sys::path::is_relative(CoverageFilename))
689 (void)D.getVFS().makeAbsolute(CoverageFilename);
690 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
691 if (EmitCovNotes) {
692 CmdArgs.push_back(
693 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
694 }
695
696 if (EmitCovData) {
697 if (FProfileDir) {
698 SmallString<128> Gcno = std::move(CoverageFilename);
699 CoverageFilename = FProfileDir->getValue();
700 llvm::sys::path::append(CoverageFilename, Gcno);
701 }
702 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
703 CmdArgs.push_back(
704 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
705 }
706 }
707}
708
709static void
710RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
711 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
712 unsigned DwarfVersion,
713 llvm::DebuggerKind DebuggerTuning) {
714 addDebugInfoKind(CmdArgs, DebugInfoKind);
715 if (DwarfVersion > 0)
716 CmdArgs.push_back(
717 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
718 switch (DebuggerTuning) {
719 case llvm::DebuggerKind::GDB:
720 CmdArgs.push_back("-debugger-tuning=gdb");
721 break;
722 case llvm::DebuggerKind::LLDB:
723 CmdArgs.push_back("-debugger-tuning=lldb");
724 break;
725 case llvm::DebuggerKind::SCE:
726 CmdArgs.push_back("-debugger-tuning=sce");
727 break;
728 case llvm::DebuggerKind::DBX:
729 CmdArgs.push_back("-debugger-tuning=dbx");
730 break;
731 default:
732 break;
733 }
734}
735
737 const ArgList &Args,
738 ArgStringList &CmdArgs,
739 bool IsCC1As = false) {
740 // If no version was requested by the user, use the default value from the
741 // back end. This is consistent with the value returned from
742 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
743 // requiring the corresponding llvm to have the AMDGPU target enabled,
744 // provided the user (e.g. front end tests) can use the default.
746 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
747 CmdArgs.insert(CmdArgs.begin() + 1,
748 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
749 Twine(CodeObjVer)));
750 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
751 // -cc1as does not accept -mcode-object-version option.
752 if (!IsCC1As)
753 CmdArgs.insert(CmdArgs.begin() + 1,
754 Args.MakeArgString(Twine("-mcode-object-version=") +
755 Twine(CodeObjVer)));
756 }
757}
758
759static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
760 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
761 D.getVFS().getBufferForFile(Path);
762 if (!MemBuf)
763 return false;
764 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
765 if (Magic == llvm::file_magic::unknown)
766 return false;
767 // Return true for both raw Clang AST files and object files which may
768 // contain a __clangast section.
769 if (Magic == llvm::file_magic::clang_ast)
770 return true;
772 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
773 return !Obj.takeError();
774}
775
776static bool gchProbe(const Driver &D, StringRef Path) {
777 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
778 if (!Status)
779 return false;
780
781 if (Status->isDirectory()) {
782 std::error_code EC;
783 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
784 !EC && DI != DE; DI = DI.increment(EC)) {
785 if (maybeHasClangPchSignature(D, DI->path()))
786 return true;
787 }
788 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
789 return false;
790 }
791
792 if (maybeHasClangPchSignature(D, Path))
793 return true;
794 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
795 return false;
796}
797
798void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
799 const Driver &D, const ArgList &Args,
800 ArgStringList &CmdArgs,
801 const InputInfo &Output,
802 const InputInfoList &Inputs) const {
803 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
804
806
807 Args.AddLastArg(CmdArgs, options::OPT_C);
808 Args.AddLastArg(CmdArgs, options::OPT_CC);
809
810 // Handle dependency file generation.
811 Arg *ArgM = Args.getLastArg(options::OPT_MM);
812 if (!ArgM)
813 ArgM = Args.getLastArg(options::OPT_M);
814 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
815 if (!ArgMD)
816 ArgMD = Args.getLastArg(options::OPT_MD);
817
818 // -M and -MM imply -w.
819 if (ArgM)
820 CmdArgs.push_back("-w");
821 else
822 ArgM = ArgMD;
823
824 if (ArgM) {
826 // Determine the output location.
827 const char *DepFile;
828 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
829 DepFile = MF->getValue();
830 C.addFailureResultFile(DepFile, &JA);
831 } else if (Output.getType() == types::TY_Dependencies) {
832 DepFile = Output.getFilename();
833 } else if (!ArgMD) {
834 DepFile = "-";
835 } else {
836 DepFile = getDependencyFileName(Args, Inputs);
837 C.addFailureResultFile(DepFile, &JA);
838 }
839 CmdArgs.push_back("-dependency-file");
840 CmdArgs.push_back(DepFile);
841 }
842 // Cmake generates dependency files using all compilation options specified
843 // by users. Claim those not used for dependency files.
845 Args.ClaimAllArgs(options::OPT_offload_compress);
846 Args.ClaimAllArgs(options::OPT_no_offload_compress);
847 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
848 }
849
850 bool HasTarget = false;
851 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
852 HasTarget = true;
853 A->claim();
854 if (A->getOption().matches(options::OPT_MT)) {
855 A->render(Args, CmdArgs);
856 } else {
857 CmdArgs.push_back("-MT");
858 SmallString<128> Quoted;
859 quoteMakeTarget(A->getValue(), Quoted);
860 CmdArgs.push_back(Args.MakeArgString(Quoted));
861 }
862 }
863
864 // Add a default target if one wasn't specified.
865 if (!HasTarget) {
866 const char *DepTarget;
867
868 // If user provided -o, that is the dependency target, except
869 // when we are only generating a dependency file.
870 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
871 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
872 DepTarget = OutputOpt->getValue();
873 } else {
874 // Otherwise derive from the base input.
875 //
876 // FIXME: This should use the computed output file location.
877 SmallString<128> P(Inputs[0].getBaseInput());
878 llvm::sys::path::replace_extension(P, "o");
879 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
880 }
881
882 CmdArgs.push_back("-MT");
883 SmallString<128> Quoted;
884 quoteMakeTarget(DepTarget, Quoted);
885 CmdArgs.push_back(Args.MakeArgString(Quoted));
886 }
887
888 if (ArgM->getOption().matches(options::OPT_M) ||
889 ArgM->getOption().matches(options::OPT_MD))
890 CmdArgs.push_back("-sys-header-deps");
891
892 // Determine module file deps mode.
893 StringRef ModuleFileDepsVal;
894 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
895 options::OPT_fmodule_file_deps,
896 options::OPT_fno_module_file_deps)) {
897 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
898 ModuleFileDepsVal = A->getValue();
899 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
900 ModuleFileDepsVal = "all";
901 else
902 ModuleFileDepsVal = "none";
903 } else if (isa<PrecompileJobAction>(JA)) {
904 ModuleFileDepsVal = "all";
905 }
906 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
907 CmdArgs.push_back(
908 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
909 }
910
911 if (Args.hasArg(options::OPT_MG)) {
912 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
913 ArgM->getOption().matches(options::OPT_MMD))
914 D.Diag(diag::err_drv_mg_requires_m_or_mm);
915 CmdArgs.push_back("-MG");
916 }
917
918 Args.AddLastArg(CmdArgs, options::OPT_MP);
919 Args.AddLastArg(CmdArgs, options::OPT_MV);
920
921 bool UsesLLVMOffloading = Args.hasFlag(
922 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
923 bool UsesOffloadInclude =
924 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc, true);
925 bool NoBuiltinInc = Args.hasArg(options::OPT_nobuiltininc);
926
927 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
928 // want to pull in our wrappers instead of the vendor headers.
929 if (UsesLLVMOffloading) {
930 if (UsesOffloadInclude && !NoBuiltinInc) {
931 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
932 StringRef RuntimeHeader) {
933 SmallString<128> OffloadInclude(D.Dir);
934 llvm::sys::path::append(OffloadInclude, "..", "include", "offload");
935 if (!IncludeSubdir.empty())
936 llvm::sys::path::append(OffloadInclude, IncludeSubdir);
937 CmdArgs.append({"-internal-isystem", Args.MakeArgString(OffloadInclude),
938 "-include", Args.MakeArgString(RuntimeHeader)});
939 };
940 auto AddForcedInclude = [&](StringRef Header) {
941 CmdArgs.push_back("-include");
942 CmdArgs.push_back(Args.MakeArgString(Header));
943 };
944 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
945 AddForcedInclude("__clang_gpu_builtin_vars.h");
946 AddForcedInclude("__clang_gpu_device_functions.h");
947 AddForcedInclude("__clang_gpu_intrinsics.h");
949 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
951 !Args.hasArg(options::OPT_nohipwrapperinc)) {
952 // HIP code commonly includes this as "hip/hip_runtime.h".
953 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
954 }
955 }
956 } else {
957 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
958 // happen before we -I or -include anything else, because we must pick up
959 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
960 // installation, rather than from e.g. /usr/local/include.
962 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
964 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
966 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
967
968 // If we are offloading to a target via OpenMP we need to include the
969 // openmp_wrappers folder which contains alternative system headers.
971 !Args.hasArg(options::OPT_nostdinc) && UsesOffloadInclude &&
972 getToolChain().getTriple().isGPU()) {
973 if (!NoBuiltinInc) {
974 // Add openmp_wrappers/* to our system include path. This lets us
975 // wrap standard library headers.
976 SmallString<128> P(D.ResourceDir);
977 llvm::sys::path::append(P, "include");
978 llvm::sys::path::append(P, "openmp_wrappers");
979 CmdArgs.push_back("-internal-isystem");
980 CmdArgs.push_back(Args.MakeArgString(P));
981 }
982
983 CmdArgs.push_back("-include");
984 CmdArgs.push_back("__clang_openmp_device_functions.h");
985 }
986 }
987
988 // Add -i* options, and automatically translate to
989 // -include-pch/-include-pth for transparent PCH support. It's
990 // wonky, but we include looking for .gch so we can support seamless
991 // replacement into a build system already set up to be generating
992 // .gch files.
993
994 if (getToolChain().getDriver().IsCLMode()) {
995 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
996 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
997 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
999 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1000 // -fpch-instantiate-templates is the default when creating
1001 // precomp using /Yc
1002 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1003 options::OPT_fno_pch_instantiate_templates, true))
1004 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1005 }
1006 if (YcArg || YuArg) {
1007 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1008 if (!isa<PrecompileJobAction>(JA)) {
1009 CmdArgs.push_back("-include-pch");
1010 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1011 C, !ThroughHeader.empty()
1012 ? ThroughHeader
1013 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1014 }
1015
1016 if (ThroughHeader.empty()) {
1017 CmdArgs.push_back(Args.MakeArgString(
1018 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1019 } else {
1020 CmdArgs.push_back(
1021 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1022 }
1023 }
1024 }
1025
1026 bool RenderedImplicitInclude = false;
1027 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1028 if (A->getOption().matches(options::OPT_include) &&
1029 D.getProbePrecompiled()) {
1030 // Handling of gcc-style gch precompiled headers.
1031 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1032 RenderedImplicitInclude = true;
1033
1034 bool FoundPCH = false;
1035 SmallString<128> P(A->getValue());
1036 // We want the files to have a name like foo.h.pch. Add a dummy extension
1037 // so that replace_extension does the right thing.
1038 P += ".dummy";
1039 llvm::sys::path::replace_extension(P, "pch");
1040 if (D.getVFS().exists(P))
1041 FoundPCH = true;
1042
1043 if (!FoundPCH) {
1044 // For GCC compat, probe for a file or directory ending in .gch instead.
1045 llvm::sys::path::replace_extension(P, "gch");
1046 FoundPCH = gchProbe(D, P.str());
1047 }
1048
1049 if (FoundPCH) {
1050 if (IsFirstImplicitInclude) {
1051 A->claim();
1052 CmdArgs.push_back("-include-pch");
1053 CmdArgs.push_back(Args.MakeArgString(P));
1054 continue;
1055 } else {
1056 // Ignore the PCH if not first on command line and emit warning.
1057 D.Diag(diag::warn_drv_pch_not_first_include) << P
1058 << A->getAsString(Args);
1059 }
1060 }
1061 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1062 // Handling of paths which must come late. These entries are handled by
1063 // the toolchain itself after the resource dir is inserted in the right
1064 // search order.
1065 // Do not claim the argument so that the use of the argument does not
1066 // silently go unnoticed on toolchains which do not honour the option.
1067 continue;
1068 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1069 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1070 continue;
1071 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1072 // This is used only by the driver. No need to pass to cc1.
1073 continue;
1074 }
1075
1076 // Not translated, render as usual.
1077 A->claim();
1078 A->render(Args, CmdArgs);
1079 }
1080
1081 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1083 // Collect all enabled NVPTX architectures.
1084 std::set<unsigned> ArchIDs;
1085 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1086 const ToolChain *TC = I.second;
1087 for (BoundArch Arch :
1088 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1089 if (Arch.Arch.isNVPTX())
1090 ArchIDs.insert(CudaArchToID(Arch.Arch));
1091 }
1092 }
1093
1094 if (!ArchIDs.empty()) {
1095 SmallString<128> List;
1096 llvm::raw_svector_ostream OS(List);
1097 llvm::interleave(ArchIDs, OS, ",");
1098 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1099 }
1100 }
1101
1102 Args.addAllArgs(CmdArgs,
1103 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1104 options::OPT_F, options::OPT_embed_dir_EQ});
1105
1106 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1107
1108 // FIXME: There is a very unfortunate problem here, some troubled
1109 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1110 // really support that we would have to parse and then translate
1111 // those options. :(
1112 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1113 options::OPT_Xpreprocessor);
1114
1115 // -I- is a deprecated GCC feature, reject it.
1116 if (Arg *A = Args.getLastArg(options::OPT_I_))
1117 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1118
1119 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1120 // -isysroot to the CC1 invocation.
1121 StringRef sysroot = C.getSysRoot();
1122 if (sysroot != "") {
1123 if (!Args.hasArg(options::OPT_isysroot)) {
1124 CmdArgs.push_back("-isysroot");
1125 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1126 }
1127 }
1128
1129 // Parse additional include paths from environment variables.
1130 // FIXME: We should probably sink the logic for handling these from the
1131 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1132 // CPATH - included following the user specified includes (but prior to
1133 // builtin and standard includes).
1134 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1135 // C_INCLUDE_PATH - system includes enabled when compiling C.
1136 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1137 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1138 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1139 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1140 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1141 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1142 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1143
1144 // While adding the include arguments, we also attempt to retrieve the
1145 // arguments of related offloading toolchains or arguments that are specific
1146 // of an offloading programming model.
1147
1148 // Add C++ include arguments, if needed.
1149 if (types::isCXX(Inputs[0].getType())) {
1150 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1152 C, JA, getToolChain(),
1153 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1154 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1155 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1156 });
1157 }
1158
1159 // If we are compiling for a GPU target with the LLVM environment we want to
1160 // override the system headers with ones created by the 'libc' project if
1161 // present.
1162 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1163 // OffloadKind as an argument.
1164 bool OffloadUsesLLVMLibc =
1165 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1166 (C.getActiveOffloadKinds() != Action::OFK_None &&
1167 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
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) && OffloadUsesLLVMLibc) {
1172 SmallString<128> P(D.ResourceDir);
1173 llvm::sys::path::append(P, "include");
1174 llvm::sys::path::append(P, "llvm_libc_wrappers");
1175 CmdArgs.push_back("-internal-isystem");
1176 CmdArgs.push_back(Args.MakeArgString(P));
1177 }
1178
1179 // Add system include arguments for all targets but IAMCU.
1180 if (!IsIAMCU)
1182 [&Args, &CmdArgs](const ToolChain &TC) {
1183 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1184 });
1185 else {
1186 // For IAMCU add special include arguments.
1187 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1188 }
1189
1190 addMacroPrefixMapArg(D, Args, CmdArgs);
1191 addCoveragePrefixMapArg(D, Args, CmdArgs);
1192
1193 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1194 options::OPT_fno_file_reproducible);
1195
1196 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1197 CmdArgs.push_back("-source-date-epoch");
1198 CmdArgs.push_back(Args.MakeArgString(Epoch));
1199 }
1200
1201 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1202 options::OPT_fno_define_target_os_macros);
1203}
1204
1205// FIXME: Move to target hook.
1206static bool isSignedCharDefault(const llvm::Triple &Triple) {
1207 switch (Triple.getArch()) {
1208 default:
1209 return true;
1210
1211 case llvm::Triple::aarch64:
1212 case llvm::Triple::aarch64_32:
1213 case llvm::Triple::aarch64_be:
1214 case llvm::Triple::arm:
1215 case llvm::Triple::armeb:
1216 case llvm::Triple::thumb:
1217 case llvm::Triple::thumbeb:
1218 if (Triple.isOSDarwin() || Triple.isOSWindows())
1219 return true;
1220 return false;
1221
1222 case llvm::Triple::ppc:
1223 case llvm::Triple::ppc64:
1224 if (Triple.isOSDarwin())
1225 return true;
1226 return false;
1227
1228 case llvm::Triple::csky:
1229 case llvm::Triple::hexagon:
1230 case llvm::Triple::msp430:
1231 case llvm::Triple::ppcle:
1232 case llvm::Triple::ppc64le:
1233 case llvm::Triple::riscv32:
1234 case llvm::Triple::riscv64:
1235 case llvm::Triple::riscv32be:
1236 case llvm::Triple::riscv64be:
1237 case llvm::Triple::systemz:
1238 case llvm::Triple::xcore:
1239 case llvm::Triple::xtensa:
1240 return false;
1241 }
1242}
1243
1244static bool hasMultipleInvocations(const llvm::Triple &Triple,
1245 const ArgList &Args) {
1246 // Supported only on Darwin where we invoke the compiler multiple times
1247 // followed by an invocation to lipo.
1248 if (!Triple.isOSDarwin())
1249 return false;
1250 // If more than one "-arch <arch>" is specified, we're targeting multiple
1251 // architectures resulting in a fat binary.
1252 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1253}
1254
1255static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1256 const llvm::Triple &Triple) {
1257 // When enabling remarks, we need to error if:
1258 // * The remark file is specified but we're targeting multiple architectures,
1259 // which means more than one remark file is being generated.
1261 bool hasExplicitOutputFile =
1262 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1263 if (hasMultipleInvocations && hasExplicitOutputFile) {
1264 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1265 << "-foptimization-record-file";
1266 return false;
1267 }
1268 return true;
1269}
1270
1271static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1272 const llvm::Triple &Triple,
1273 const InputInfo &Input,
1274 const InputInfo &Output, const JobAction &JA) {
1275 StringRef Format = "yaml";
1276 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1277 Format = A->getValue();
1278
1279 CmdArgs.push_back("-opt-record-file");
1280
1281 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1282 if (A) {
1283 CmdArgs.push_back(A->getValue());
1284 } else {
1285 bool hasMultipleArchs =
1286 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1287 Args.getAllArgValues(options::OPT_arch).size() > 1;
1288
1290
1291 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1292 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1293 F = FinalOutput->getValue();
1294 } else {
1295 if (Format != "yaml" && // For YAML, keep the original behavior.
1296 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1297 Output.isFilename())
1298 F = Output.getFilename();
1299 }
1300
1301 if (F.empty()) {
1302 // Use the input filename.
1303 F = llvm::sys::path::stem(Input.getBaseInput());
1304
1305 // If we're compiling for an offload architecture (i.e. a CUDA device),
1306 // we need to make the file name for the device compilation different
1307 // from the host compilation.
1310 llvm::sys::path::replace_extension(F, "");
1312 Triple.str());
1313 F += "-";
1314 F += JA.getOffloadingArch().ArchName;
1315 }
1316 }
1317
1318 // If we're having more than one "-arch", we should name the files
1319 // differently so that every cc1 invocation writes to a different file.
1320 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1321 // name from the triple.
1322 if (hasMultipleArchs) {
1323 // First, remember the extension.
1324 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1325 // then, remove it.
1326 llvm::sys::path::replace_extension(F, "");
1327 // attach -<arch> to it.
1328 F += "-";
1329 F += Triple.getArchName();
1330 // put back the extension.
1331 llvm::sys::path::replace_extension(F, OldExtension);
1332 }
1333
1334 SmallString<32> Extension;
1335 Extension += "opt.";
1336 Extension += Format;
1337
1338 llvm::sys::path::replace_extension(F, Extension);
1339 CmdArgs.push_back(Args.MakeArgString(F));
1340 }
1341
1342 if (const Arg *A =
1343 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1344 CmdArgs.push_back("-opt-record-passes");
1345 CmdArgs.push_back(A->getValue());
1346 }
1347
1348 if (!Format.empty()) {
1349 CmdArgs.push_back("-opt-record-format");
1350 CmdArgs.push_back(Format.data());
1351 }
1352}
1353
1354void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1355 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1356 options::OPT_fno_aapcs_bitfield_width, true))
1357 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1358
1359 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1360 CmdArgs.push_back("-faapcs-bitfield-load");
1361}
1362
1363namespace {
1364void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1365 const ArgList &Args, ArgStringList &CmdArgs) {
1366 // Select the ABI to use.
1367 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1368 const char *ABIName = nullptr;
1369 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1370 ABIName = A->getValue();
1371 else
1372 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1373
1374 CmdArgs.push_back("-target-abi");
1375 CmdArgs.push_back(ABIName);
1376}
1377
1378void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1379 auto StrictAlignIter =
1380 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1381 return Arg == "+strict-align" || Arg == "-strict-align";
1382 });
1383 if (StrictAlignIter != CmdArgs.rend() &&
1384 StringRef(*StrictAlignIter) == "+strict-align")
1385 CmdArgs.push_back("-Wunaligned-access");
1386}
1387}
1388
1389static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1390 ArgStringList &CmdArgs, bool isAArch64) {
1391 const llvm::Triple &Triple = TC.getEffectiveTriple();
1392 const Arg *A = isAArch64
1393 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1394 options::OPT_mbranch_protection_EQ)
1395 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1396 if (!A) {
1397 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1398 CmdArgs.push_back("-msign-return-address=non-leaf");
1399 CmdArgs.push_back("-msign-return-address-key=a_key");
1400 CmdArgs.push_back("-mbranch-target-enforce");
1401 }
1402 return;
1403 }
1404
1405 const Driver &D = TC.getDriver();
1406 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1407 D.Diag(diag::warn_incompatible_branch_protection_option)
1408 << Triple.getArchName();
1409
1410 StringRef Scope, Key;
1411 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1412
1413 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1414 Scope = A->getValue();
1415 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1416 D.Diag(diag::err_drv_unsupported_option_argument)
1417 << A->getSpelling() << Scope;
1418 // This spelling cannot express a key, and AArch64 Windows only supports
1419 // B-key, so default to it there as parseBranchProtection() does.
1420 Key = isAArch64 && Triple.isOSWindows() ? "b_key" : "a_key";
1421 IndirectBranches =
1422 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1423 BranchProtectionPAuthLR = false;
1424 GuardedControlStack = false;
1425 } else {
1426 StringRef DiagMsg;
1427 llvm::ARM::ParsedBranchProtection PBP;
1428 bool EnablePAuthLR = false;
1429
1430 // To know if we need to enable PAuth-LR As part of the standard branch
1431 // protection option, it needs to be determined if the feature has been
1432 // activated in the `march` argument. This information is stored within the
1433 // CmdArgs variable and can be found using a search.
1434 if (isAArch64) {
1435 auto isPAuthLR = [](const char *member) {
1436 llvm::AArch64::ExtensionInfo pauthlr_extension =
1437 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1438 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1439 member;
1440 };
1441
1442 if (llvm::any_of(CmdArgs, isPAuthLR))
1443 EnablePAuthLR = true;
1444 }
1445 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg, Triple,
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::AddAMDGPUTargetArgs(const ArgList &Args,
1539 ArgStringList &CmdArgs) const {
1540 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1541 if (Arg *A = Args.getLastArg(options::OPT_mxnack, options::OPT_mno_xnack))
1542 A->render(Args, CmdArgs);
1543 if (Arg *A = Args.getLastArg(options::OPT_msramecc, options::OPT_mno_sramecc))
1544 A->render(Args, CmdArgs);
1545}
1546
1547void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1548 const ArgList &Args, bool KernelOrKext,
1549 ArgStringList &CmdArgs) const {
1550 const ToolChain &TC = getToolChain();
1551
1552 // Add the target features
1553 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1554
1555 // Add target specific flags.
1556 switch (TC.getArch()) {
1557 default:
1558 break;
1559
1560 case llvm::Triple::arm:
1561 case llvm::Triple::armeb:
1562 case llvm::Triple::thumb:
1563 case llvm::Triple::thumbeb:
1564 // Use the effective triple, which takes into account the deployment target.
1565 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1566 break;
1567
1568 case llvm::Triple::aarch64:
1569 case llvm::Triple::aarch64_32:
1570 case llvm::Triple::aarch64_be:
1571 AddAArch64TargetArgs(Args, CmdArgs);
1572 break;
1573
1574 case llvm::Triple::amdgpu:
1575 AddAMDGPUTargetArgs(Args, CmdArgs);
1576 break;
1577
1578 case llvm::Triple::loongarch32:
1579 case llvm::Triple::loongarch64:
1580 AddLoongArchTargetArgs(Args, CmdArgs);
1581 break;
1582
1583 case llvm::Triple::mips:
1584 case llvm::Triple::mipsel:
1585 case llvm::Triple::mips64:
1586 case llvm::Triple::mips64el:
1587 AddMIPSTargetArgs(Args, CmdArgs);
1588 break;
1589
1590 case llvm::Triple::ppc:
1591 case llvm::Triple::ppcle:
1592 case llvm::Triple::ppc64:
1593 case llvm::Triple::ppc64le:
1594 AddPPCTargetArgs(Args, CmdArgs);
1595 break;
1596
1597 case llvm::Triple::riscv32:
1598 case llvm::Triple::riscv64:
1599 case llvm::Triple::riscv32be:
1600 case llvm::Triple::riscv64be:
1601 AddRISCVTargetArgs(Args, CmdArgs);
1602 break;
1603
1604 case llvm::Triple::sparc:
1605 case llvm::Triple::sparcel:
1606 case llvm::Triple::sparcv9:
1607 AddSparcTargetArgs(Args, CmdArgs);
1608 break;
1609
1610 case llvm::Triple::systemz:
1611 AddSystemZTargetArgs(Args, CmdArgs);
1612 break;
1613
1614 case llvm::Triple::x86:
1615 case llvm::Triple::x86_64:
1616 AddX86TargetArgs(Args, CmdArgs);
1617 break;
1618
1619 case llvm::Triple::lanai:
1620 AddLanaiTargetArgs(Args, CmdArgs);
1621 break;
1622
1623 case llvm::Triple::hexagon:
1624 AddHexagonTargetArgs(Args, CmdArgs);
1625 break;
1626
1627 case llvm::Triple::wasm32:
1628 case llvm::Triple::wasm64:
1629 AddWebAssemblyTargetArgs(Args, CmdArgs);
1630 break;
1631
1632 case llvm::Triple::ve:
1633 AddVETargetArgs(Args, CmdArgs);
1634 break;
1635 }
1636}
1637
1638namespace {
1639void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1640 ArgStringList &CmdArgs) {
1641 const char *ABIName = nullptr;
1642 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1643 ABIName = A->getValue();
1644 else if (Triple.isOSDarwin())
1645 ABIName = "darwinpcs";
1646 // TODO: we probably want to have some target hook here.
1647 else if (Triple.isOSLinux() &&
1648 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1649 ABIName = "pauthtest";
1650 else
1651 ABIName = "aapcs";
1652
1653 CmdArgs.push_back("-target-abi");
1654 CmdArgs.push_back(ABIName);
1655}
1656}
1657
1658void Clang::AddAArch64TargetArgs(const ArgList &Args,
1659 ArgStringList &CmdArgs) const {
1660 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1661
1662 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1663 Args.hasArg(options::OPT_mkernel) ||
1664 Args.hasArg(options::OPT_fapple_kext))
1665 CmdArgs.push_back("-disable-red-zone");
1666
1667 if (!Args.hasFlag(options::OPT_mimplicit_float,
1668 options::OPT_mno_implicit_float, true))
1669 CmdArgs.push_back("-no-implicit-float");
1670
1671 RenderAArch64ABI(Triple, Args, CmdArgs);
1672
1673 // Forward the -mglobal-merge option for explicit control over the pass.
1674 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1675 options::OPT_mno_global_merge)) {
1676 CmdArgs.push_back("-mllvm");
1677 if (A->getOption().matches(options::OPT_mno_global_merge))
1678 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1679 else
1680 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1681 }
1682
1683 // Handle -msve_vector_bits=<bits>
1684 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1685 StringRef VScaleMax) {
1686 StringRef Val = A->getValue();
1687 const Driver &D = getToolChain().getDriver();
1688 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1689 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1690 Val == "1024+" || Val == "2048+") {
1691 unsigned Bits = 0;
1692 if (!Val.consume_back("+")) {
1693 bool Invalid = Val.getAsInteger(10, Bits);
1694 (void)Invalid;
1695 assert(!Invalid && "Failed to parse value");
1696 CmdArgs.push_back(
1697 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1698 }
1699
1700 bool Invalid = Val.getAsInteger(10, Bits);
1701 (void)Invalid;
1702 assert(!Invalid && "Failed to parse value");
1703
1704 CmdArgs.push_back(
1705 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1706 } else if (Val == "scalable") {
1707 // Silently drop requests for vector-length agnostic code as it's implied.
1708 } else {
1709 // Handle the unsupported values passed to msve-vector-bits.
1710 D.Diag(diag::err_drv_unsupported_option_argument)
1711 << A->getSpelling() << Val;
1712 }
1713 };
1714 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1715 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1716 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1717 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1718
1719 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1720
1721 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1722 CmdArgs.push_back("-tune-cpu");
1723 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1724 }
1725
1726 AddUnalignedAccessWarning(CmdArgs);
1727
1728 if (Triple.isOSDarwin() ||
1729 (Triple.isOSLinux() &&
1730 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1731 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1732 options::OPT_fno_ptrauth_intrinsics);
1733 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1734 options::OPT_fno_ptrauth_calls);
1735 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1736 options::OPT_fno_ptrauth_returns);
1737 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1738 options::OPT_fno_ptrauth_auth_traps);
1739 Args.addOptInFlag(
1740 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1741 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1742 Args.addOptInFlag(
1743 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1744 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1745 Args.addOptInFlag(
1746 CmdArgs, options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1747 options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1748 Args.addOptInFlag(
1749 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1750 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1751 Args.addOptInFlag(
1752 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1753 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1754 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1755 options::OPT_fno_ptrauth_indirect_gotos);
1756 }
1757 if (Triple.isOSLinux() &&
1758 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1759 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1760 options::OPT_fno_ptrauth_init_fini);
1761 Args.addOptInFlag(
1762 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1763 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1764 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1765 options::OPT_fno_ptrauth_elf_got);
1766 }
1767 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1768 options::OPT_fno_aarch64_jump_table_hardening);
1769
1770 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1771 options::OPT_fno_ptrauth_objc_isa);
1772 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1773 options::OPT_fno_ptrauth_objc_interface_sel);
1774 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1775 options::OPT_fno_ptrauth_objc_class_ro);
1776
1777 // Enable/disable return address signing and indirect branch targets.
1778 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1779}
1780
1781void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1782 ArgStringList &CmdArgs) const {
1783 const llvm::Triple &Triple = getToolChain().getTriple();
1784
1785 CmdArgs.push_back("-target-abi");
1786 CmdArgs.push_back(
1787 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1788 .data());
1789
1790 // Handle -mtune.
1791 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1792 std::string TuneCPU = A->getValue();
1793 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1794 CmdArgs.push_back("-tune-cpu");
1795 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1796 }
1797
1798 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1799 options::OPT_mno_annotate_tablejump)) {
1800 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1801 CmdArgs.push_back("-mllvm");
1802 CmdArgs.push_back("-loongarch-annotate-tablejump");
1803 }
1804 }
1805}
1806
1807void Clang::AddMIPSTargetArgs(const ArgList &Args,
1808 ArgStringList &CmdArgs) const {
1809 const Driver &D = getToolChain().getDriver();
1810 StringRef CPUName;
1811 StringRef ABIName;
1812 const llvm::Triple &Triple = getToolChain().getTriple();
1813 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1814
1815 CmdArgs.push_back("-target-abi");
1816 CmdArgs.push_back(ABIName.data());
1817
1818 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1819 if (ABI == mips::FloatABI::Soft) {
1820 // Floating point operations and argument passing are soft.
1821 CmdArgs.push_back("-msoft-float");
1822 CmdArgs.push_back("-mfloat-abi");
1823 CmdArgs.push_back("soft");
1824 } else {
1825 // Floating point operations and argument passing are hard.
1826 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1827 CmdArgs.push_back("-mfloat-abi");
1828 CmdArgs.push_back("hard");
1829 }
1830
1831 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1832 options::OPT_mno_ldc1_sdc1)) {
1833 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1834 CmdArgs.push_back("-mllvm");
1835 CmdArgs.push_back("-mno-ldc1-sdc1");
1836 }
1837 }
1838
1839 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1840 options::OPT_mno_check_zero_division)) {
1841 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1842 CmdArgs.push_back("-mllvm");
1843 CmdArgs.push_back("-mno-check-zero-division");
1844 }
1845 }
1846
1847 if (Args.getLastArg(options::OPT_mfix4300)) {
1848 CmdArgs.push_back("-mllvm");
1849 CmdArgs.push_back("-mfix4300");
1850 }
1851
1852 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1853 StringRef v = A->getValue();
1854 CmdArgs.push_back("-mllvm");
1855 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1856 A->claim();
1857 }
1858
1859 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1860 Arg *ABICalls =
1861 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1862
1863 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1864 // -mgpopt is the default for static, -fno-pic environments but these two
1865 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1866 // the only case where -mllvm -mgpopt is passed.
1867 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1868 // passed explicitly when compiling something with -mabicalls
1869 // (implictly) in affect. Currently the warning is in the backend.
1870 //
1871 // When the ABI in use is N64, we also need to determine the PIC mode that
1872 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1873 bool NoABICalls =
1874 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1875
1876 llvm::Reloc::Model RelocationModel;
1877 unsigned PICLevel;
1878 bool IsPIE;
1879 std::tie(RelocationModel, PICLevel, IsPIE) =
1880 ParsePICArgs(getToolChain(), Args);
1881
1882 NoABICalls = NoABICalls ||
1883 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1884
1885 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1886 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1887 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1888 CmdArgs.push_back("-mllvm");
1889 CmdArgs.push_back("-mgpopt");
1890
1891 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1892 options::OPT_mno_local_sdata);
1893 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1894 options::OPT_mno_extern_sdata);
1895 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1896 options::OPT_mno_embedded_data);
1897 if (LocalSData) {
1898 CmdArgs.push_back("-mllvm");
1899 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1900 CmdArgs.push_back("-mlocal-sdata=1");
1901 } else {
1902 CmdArgs.push_back("-mlocal-sdata=0");
1903 }
1904 LocalSData->claim();
1905 }
1906
1907 if (ExternSData) {
1908 CmdArgs.push_back("-mllvm");
1909 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1910 CmdArgs.push_back("-mextern-sdata=1");
1911 } else {
1912 CmdArgs.push_back("-mextern-sdata=0");
1913 }
1914 ExternSData->claim();
1915 }
1916
1917 if (EmbeddedData) {
1918 CmdArgs.push_back("-mllvm");
1919 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1920 CmdArgs.push_back("-membedded-data=1");
1921 } else {
1922 CmdArgs.push_back("-membedded-data=0");
1923 }
1924 EmbeddedData->claim();
1925 }
1926
1927 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1928 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1929
1930 if (GPOpt)
1931 GPOpt->claim();
1932
1933 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1934 StringRef Val = StringRef(A->getValue());
1935 if (mips::hasCompactBranches(CPUName)) {
1936 if (Val == "never" || Val == "always" || Val == "optimal") {
1937 CmdArgs.push_back("-mllvm");
1938 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1939 } else
1940 D.Diag(diag::err_drv_unsupported_option_argument)
1941 << A->getSpelling() << Val;
1942 } else
1943 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1944 }
1945
1946 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1947 options::OPT_mno_relax_pic_calls)) {
1948 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1949 CmdArgs.push_back("-mllvm");
1950 CmdArgs.push_back("-mips-jalr-reloc=0");
1951 }
1952 }
1953}
1954
1955void Clang::AddPPCTargetArgs(const ArgList &Args,
1956 ArgStringList &CmdArgs) const {
1957 const Driver &D = getToolChain().getDriver();
1958 const llvm::Triple &T = getToolChain().getTriple();
1959 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1960 CmdArgs.push_back("-tune-cpu");
1961 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
1962 CmdArgs.push_back(Args.MakeArgString(CPU));
1963 }
1964
1965 // Select the ABI to use.
1966 const char *ABIName = nullptr;
1967 if (T.isOSBinFormatELF()) {
1968 switch (getToolChain().getArch()) {
1969 case llvm::Triple::ppc64: {
1970 if (T.isPPC64ELFv2ABI())
1971 ABIName = "elfv2";
1972 else
1973 ABIName = "elfv1";
1974 break;
1975 }
1976 case llvm::Triple::ppc64le:
1977 ABIName = "elfv2";
1978 break;
1979 default:
1980 break;
1981 }
1982 }
1983
1984 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1985 bool VecExtabi = false;
1986 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1987 StringRef V = A->getValue();
1988 if (V == "ieeelongdouble") {
1989 IEEELongDouble = true;
1990 A->claim();
1991 } else if (V == "ibmlongdouble") {
1992 IEEELongDouble = false;
1993 A->claim();
1994 } else if (V == "vec-default") {
1995 VecExtabi = false;
1996 A->claim();
1997 } else if (V == "vec-extabi") {
1998 VecExtabi = true;
1999 A->claim();
2000 } else if (V == "elfv1") {
2001 ABIName = "elfv1";
2002 A->claim();
2003 } else if (V == "elfv2") {
2004 ABIName = "elfv2";
2005 A->claim();
2006 } else if (V != "altivec")
2007 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2008 // the option if given as we don't have backend support for any targets
2009 // that don't use the altivec abi.
2010 ABIName = A->getValue();
2011 }
2012 if (IEEELongDouble)
2013 CmdArgs.push_back("-mabi=ieeelongdouble");
2014 if (VecExtabi) {
2015 if (!T.isOSAIX())
2016 D.Diag(diag::err_drv_unsupported_opt_for_target)
2017 << "-mabi=vec-extabi" << T.str();
2018 CmdArgs.push_back("-mabi=vec-extabi");
2019 }
2020
2021 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2022 CmdArgs.push_back("-disable-red-zone");
2023
2025 if (FloatABI == ppc::FloatABI::Soft) {
2026 // Floating point operations and argument passing are soft.
2027 CmdArgs.push_back("-msoft-float");
2028 CmdArgs.push_back("-mfloat-abi");
2029 CmdArgs.push_back("soft");
2030 } else {
2031 // Floating point operations and argument passing are hard.
2032 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2033 CmdArgs.push_back("-mfloat-abi");
2034 CmdArgs.push_back("hard");
2035 }
2036
2037 if (ABIName) {
2038 CmdArgs.push_back("-target-abi");
2039 CmdArgs.push_back(ABIName);
2040 }
2041}
2042
2043void Clang::AddRISCVTargetArgs(const ArgList &Args,
2044 ArgStringList &CmdArgs) const {
2045 const llvm::Triple &Triple = getToolChain().getTriple();
2046 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2047
2048 CmdArgs.push_back("-target-abi");
2049 CmdArgs.push_back(ABIName.data());
2050
2051 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2052 CmdArgs.push_back("-msmall-data-limit");
2053 CmdArgs.push_back(A->getValue());
2054 }
2055
2056 if (!Args.hasFlag(options::OPT_mimplicit_float,
2057 options::OPT_mno_implicit_float, true))
2058 CmdArgs.push_back("-no-implicit-float");
2059
2060 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2061 if (!TuneCPU)
2062 return;
2063 if (!TuneCPU->empty()) {
2064 CmdArgs.push_back("-tune-cpu");
2065 // TuneCPU might or might not be the original -mtune string, so we
2066 // have to create a new copy here.
2067 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2068 }
2069
2070 // Handle -mrvv-vector-bits=<bits>
2071 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2072 StringRef Val = A->getValue();
2073 const Driver &D = getToolChain().getDriver();
2074
2075 // Get minimum VLen from march.
2076 unsigned MinVLen = 0;
2077 std::string Arch = riscv::getRISCVArch(Args, Triple);
2078 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2079 Arch, /*EnableExperimentalExtensions*/ true);
2080 // Ignore parsing error.
2081 if (!errorToBool(ISAInfo.takeError()))
2082 MinVLen = (*ISAInfo)->getMinVLen();
2083
2084 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2085 // as integer as long as we have a MinVLen.
2086 unsigned Bits = 0;
2087 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2088 Bits = MinVLen;
2089 } else if (!Val.getAsInteger(10, Bits)) {
2090 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2091 // at least MinVLen.
2092 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2093 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2094 Bits = 0;
2095 }
2096
2097 // If we got a valid value try to use it.
2098 if (Bits != 0) {
2099 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2100 CmdArgs.push_back(
2101 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2102 CmdArgs.push_back(
2103 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2104 } else if (Val != "scalable") {
2105 // Handle the unsupported values passed to mrvv-vector-bits.
2106 D.Diag(diag::err_drv_unsupported_option_argument)
2107 << A->getSpelling() << Val;
2108 }
2109 }
2110}
2111
2112void Clang::AddSparcTargetArgs(const ArgList &Args,
2113 ArgStringList &CmdArgs) const {
2115 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2116
2117 if (FloatABI == sparc::FloatABI::Soft) {
2118 // Floating point operations and argument passing are soft.
2119 CmdArgs.push_back("-msoft-float");
2120 CmdArgs.push_back("-mfloat-abi");
2121 CmdArgs.push_back("soft");
2122 } else {
2123 // Floating point operations and argument passing are hard.
2124 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2125 CmdArgs.push_back("-mfloat-abi");
2126 CmdArgs.push_back("hard");
2127 }
2128
2129 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2130 StringRef Name = A->getValue();
2131 std::string TuneCPU;
2132 if (Name == "native")
2133 TuneCPU = std::string(llvm::sys::getHostCPUName());
2134 else
2135 TuneCPU = std::string(Name);
2136
2137 CmdArgs.push_back("-tune-cpu");
2138 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2139 }
2140}
2141
2142void Clang::AddSystemZTargetArgs(const ArgList &Args,
2143 ArgStringList &CmdArgs) const {
2144 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2145 CmdArgs.push_back("-tune-cpu");
2146 if (strcmp(A->getValue(), "native") == 0)
2147 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2148 else
2149 CmdArgs.push_back(A->getValue());
2150 }
2151
2152 bool HasBackchain =
2153 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2154 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2155 options::OPT_mno_packed_stack, false);
2157 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2158 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2159
2160 // Only hard float ABI (-mhard-float) is supported on z/OS.
2161 const Driver &D = getToolChain().getDriver();
2162 const llvm::Triple &Triple = getToolChain().getTriple();
2163 if (HasSoftFloat && Triple.isOSzOS()) {
2164 D.Diag(diag::err_drv_unsupported_opt_for_target)
2165 << "-msoft-float" << Triple.str();
2166 }
2167 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2168 D.Diag(diag::err_drv_unsupported_opt)
2169 << "-mpacked-stack -mbackchain -mhard-float";
2170 }
2171 if (HasBackchain)
2172 CmdArgs.push_back("-mbackchain");
2173 if (HasPackedStack)
2174 CmdArgs.push_back("-mpacked-stack");
2175 if (HasSoftFloat) {
2176 // Floating point operations and argument passing are soft.
2177 CmdArgs.push_back("-msoft-float");
2178 CmdArgs.push_back("-mfloat-abi");
2179 CmdArgs.push_back("soft");
2180 }
2181
2182 if (Triple.isOSzOS())
2183 Args.AddLastArg(CmdArgs, options::OPT_mzos_ppa1_name,
2184 options::OPT_mno_zos_ppa1_name);
2185}
2186
2187void Clang::AddX86TargetArgs(const ArgList &Args,
2188 ArgStringList &CmdArgs) const {
2189 const Driver &D = getToolChain().getDriver();
2190 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2191
2192 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2193 Args.hasArg(options::OPT_mkernel) ||
2194 Args.hasArg(options::OPT_fapple_kext))
2195 CmdArgs.push_back("-disable-red-zone");
2196
2197 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2198 options::OPT_mno_tls_direct_seg_refs, true))
2199 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2200
2201 // Default to avoid implicit floating-point for kernel/kext code, but allow
2202 // that to be overridden with -mno-soft-float.
2203 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2204 Args.hasArg(options::OPT_fapple_kext));
2205 if (Arg *A = Args.getLastArg(
2206 options::OPT_msoft_float, options::OPT_mno_soft_float,
2207 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2208 const Option &O = A->getOption();
2209 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2210 O.matches(options::OPT_msoft_float));
2211 }
2212 if (NoImplicitFloat)
2213 CmdArgs.push_back("-no-implicit-float");
2214
2215 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2216 StringRef Value = A->getValue();
2217 if (Value == "intel" || Value == "att") {
2218 CmdArgs.push_back("-mllvm");
2219 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2220 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2221 } else {
2222 D.Diag(diag::err_drv_unsupported_option_argument)
2223 << A->getSpelling() << Value;
2224 }
2225 } else if (D.IsCLMode()) {
2226 CmdArgs.push_back("-mllvm");
2227 CmdArgs.push_back("-x86-asm-syntax=intel");
2228 }
2229
2230 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2231 options::OPT_mno_skip_rax_setup))
2232 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2233 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2234
2235 // Set flags to support MCU ABI.
2236 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2237 CmdArgs.push_back("-mfloat-abi");
2238 CmdArgs.push_back("soft");
2239 CmdArgs.push_back("-mstack-alignment=4");
2240 }
2241
2242 // Handle -mtune.
2243
2244 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2245 std::string TuneCPU;
2246 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2247 TuneCPU = "generic";
2248
2249 // Override based on -mtune.
2250 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2251 StringRef Name = A->getValue();
2252
2253 if (Name == "native") {
2254 Name = llvm::sys::getHostCPUName();
2255 if (!Name.empty())
2256 TuneCPU = std::string(Name);
2257 } else
2258 TuneCPU = std::string(Name);
2259 }
2260
2261 if (!TuneCPU.empty()) {
2262 CmdArgs.push_back("-tune-cpu");
2263 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2264 }
2265}
2266
2267static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2268 size_t Index = Option.find(Delimiter);
2269 if (Index != StringRef::npos)
2270 Option = Option.substr(0, Index);
2271 return Option;
2272}
2273
2274static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2275 Opt = getOptionName(Opt);
2276 if (CmdArgs.size() < 2)
2277 return;
2278
2279 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2280 StringRef Option = *It;
2281 if (!Option.starts_with(Opt))
2282 continue;
2283 Option = getOptionName(Option);
2284 if (Option != Opt)
2285 continue;
2286 if (StringRef(*(It - 1)) != "-mllvm")
2287 continue;
2288
2289 It = CmdArgs.erase(It);
2290 CmdArgs.erase(It - 1);
2291 return;
2292 }
2293}
2294
2295static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2296 checkAndRemoveLLVMArg(CmdArgs, A);
2297 CmdArgs.push_back("-mllvm");
2298 CmdArgs.push_back(A);
2299}
2300
2301static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2302 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2303 StringRef Option = *It;
2304 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2305 It = CmdArgs.erase(It);
2306 Ie = CmdArgs.end();
2307 } else {
2308 ++It;
2309 }
2310 }
2311
2312 CmdArgs.push_back("-menable-no-infs");
2313 CmdArgs.push_back("-menable-no-nans");
2314 CmdArgs.push_back("-fapprox-func");
2315 CmdArgs.push_back("-funsafe-math-optimizations");
2316 CmdArgs.push_back("-fno-signed-zeros");
2317 CmdArgs.push_back("-mreassociate");
2318 CmdArgs.push_back("-freciprocal-math");
2319 CmdArgs.push_back("-ffp-contract=fast");
2320 CmdArgs.push_back("-ffast-math");
2321 CmdArgs.push_back("-ffinite-math-only");
2322 CmdArgs.push_back("-D__FAST_MATH__");
2323 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2324}
2325
2326static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2327 ArgStringList &CmdArgs) {
2328 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2329 bool HasHVX = HvxVerOpt.has_value();
2330 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2331 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2332 options::OPT_mhexagon_hvx_ieee_fp) ||
2333 !HasHVX)
2334 return;
2335 unsigned HvxVerNum = 0;
2336 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2337 HvxVerNum = 0;
2338
2339 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2340 options::OPT_mhexagon_hvx_qfloat_EQ,
2341 options::OPT_mhexagon_hvx_ieee_fp)) {
2342 if (HvxVerNum >= 79) {
2343 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2344 const char *Mode =
2345 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2346 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2347 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2348 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2349 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2350 .Default(nullptr);
2351 if (!Mode) {
2352 D.Diag(diag::err_drv_invalid_value)
2353 << A->getAsString(Args) << A->getValue();
2354 return;
2355 }
2356 pushBackLLVMArg(CmdArgs, Mode);
2357 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2359 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2360 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2362 } else {
2363 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2364 }
2365 } else {
2366 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2367 options::OPT_mhexagon_hvx_qfloat_EQ,
2368 options::OPT_mno_hexagon_hvx_qfloat);
2369 QFloatArg &&
2370 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2371 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2372 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2373 << (std::string("HVX ") + HvxVer +
2374 "; falling back to legacy qfloat mode");
2375 }
2376 }
2377 }
2378}
2379
2380void Clang::AddHexagonTargetArgs(const ArgList &Args,
2381 ArgStringList &CmdArgs) const {
2382 CmdArgs.push_back("-mqdsp6-compat");
2383 CmdArgs.push_back("-Wreturn-type");
2384
2386 CmdArgs.push_back("-mllvm");
2387 CmdArgs.push_back(
2388 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2389 }
2390
2391 if (!Args.hasArg(options::OPT_fno_short_enums))
2392 CmdArgs.push_back("-fshort-enums");
2393 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2394 CmdArgs.push_back("-mllvm");
2395 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2396 }
2397 CmdArgs.push_back("-mllvm");
2398 CmdArgs.push_back("-machine-sink-split=0");
2399
2400 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2401}
2402
2403void Clang::AddLanaiTargetArgs(const ArgList &Args,
2404 ArgStringList &CmdArgs) const {
2405 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2406 StringRef CPUName = A->getValue();
2407
2408 CmdArgs.push_back("-target-cpu");
2409 CmdArgs.push_back(Args.MakeArgString(CPUName));
2410 }
2411 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2412 StringRef Value = A->getValue();
2413 // Only support mregparm=4 to support old usage. Report error for all other
2414 // cases.
2415 int Mregparm;
2416 if (Value.getAsInteger(10, Mregparm)) {
2417 if (Mregparm != 4) {
2419 diag::err_drv_unsupported_option_argument)
2420 << A->getSpelling() << Value;
2421 }
2422 }
2423 }
2424}
2425
2426void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2427 ArgStringList &CmdArgs) const {
2428 // Default to "hidden" visibility.
2429 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2430 options::OPT_fvisibility_ms_compat))
2431 CmdArgs.push_back("-fvisibility=hidden");
2432}
2433
2434void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2435 // Floating point operations and argument passing are hard.
2436 CmdArgs.push_back("-mfloat-abi");
2437 CmdArgs.push_back("hard");
2438}
2439
2440void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2441 StringRef Target, const InputInfo &Output,
2442 const InputInfo &Input, const ArgList &Args) const {
2443 // If this is a dry run, do not create the compilation database file.
2444 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2445 return;
2446
2447 using llvm::yaml::escape;
2448 const Driver &D = getToolChain().getDriver();
2449
2450 if (!CompilationDatabase) {
2451 std::error_code EC;
2452 auto File = std::make_unique<llvm::raw_fd_ostream>(
2453 Filename, EC,
2454 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2455 if (EC) {
2456 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2457 << EC.message();
2458 return;
2459 }
2460 CompilationDatabase = std::move(File);
2461 }
2462 auto &CDB = *CompilationDatabase;
2463 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2464 if (!CWD)
2465 CWD = ".";
2466 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2467 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2468 if (Output.isFilename())
2469 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2470 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2471 SmallString<128> Buf;
2472 Buf = "-x";
2473 Buf += types::getTypeName(Input.getType());
2474 CDB << ", \"" << escape(Buf) << "\"";
2475 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2476 Buf = "--sysroot=";
2477 Buf += D.SysRoot;
2478 CDB << ", \"" << escape(Buf) << "\"";
2479 }
2480 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2481 if (Output.isFilename())
2482 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2483 for (auto &A: Args) {
2484 auto &O = A->getOption();
2485 // Skip language selection, which is positional.
2486 if (O.getID() == options::OPT_x)
2487 continue;
2488 // Skip writing dependency output and the compilation database itself.
2489 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2490 continue;
2491 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2492 continue;
2493 // Skip inputs.
2494 if (O.getKind() == Option::InputClass)
2495 continue;
2496 // Skip output.
2497 if (O.getID() == options::OPT_o)
2498 continue;
2499 // All other arguments are quoted and appended.
2500 ArgStringList ASL;
2501 A->render(Args, ASL);
2502 for (auto &it: ASL)
2503 CDB << ", \"" << escape(it) << "\"";
2504 }
2505 Buf = "--target=";
2506 Buf += Target;
2507 CDB << ", \"" << escape(Buf) << "\"]},\n";
2508}
2509
2510void Clang::DumpCompilationDatabaseFragmentToDir(
2511 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2512 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2513 // If this is a dry run, do not create the compilation database file.
2514 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2515 return;
2516
2517 if (CompilationDatabase)
2518 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2519
2520 SmallString<256> Path = Dir;
2521 const auto &Driver = C.getDriver();
2522 Driver.getVFS().makeAbsolute(Path);
2523 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2524 if (Err) {
2525 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2526 return;
2527 }
2528
2529 llvm::sys::path::append(
2530 Path,
2531 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2532 int FD;
2533 SmallString<256> TempPath;
2534 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2535 llvm::sys::fs::OF_Text);
2536 if (Err) {
2537 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2538 return;
2539 }
2540 CompilationDatabase =
2541 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2542 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2543}
2544
2545static bool CheckARMImplicitITArg(StringRef Value) {
2546 return Value == "always" || Value == "never" || Value == "arm" ||
2547 Value == "thumb";
2548}
2549
2550static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2551 StringRef Value) {
2552 CmdArgs.push_back("-mllvm");
2553 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2554}
2555
2557 const ArgList &Args,
2558 ArgStringList &CmdArgs,
2559 const Driver &D) {
2560 // Default to -mno-relax-all.
2561 //
2562 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2563 // cannot be done by assembler branch relaxation as it needs a free temporary
2564 // register. Because of this, branch relaxation is handled by a MachineIR pass
2565 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2566 // MachineIR branch relaxation inaccurate and it will miss cases where an
2567 // indirect branch is necessary.
2568 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2569 options::OPT_mno_relax_all);
2570
2571 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2572 options::OPT_mno_incremental_linker_compatible);
2573
2574 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2575
2576 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2577 options::OPT_fno_emit_compact_unwind_non_canonical);
2578
2579 // If you add more args here, also add them to the block below that
2580 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2581
2582 // When passing -I arguments to the assembler we sometimes need to
2583 // unconditionally take the next argument. For example, when parsing
2584 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2585 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2586 // arg after parsing the '-I' arg.
2587 bool TakeNextArg = false;
2588
2589 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2590 bool IsELF = Triple.isOSBinFormatELF();
2591 bool Crel = false, ExperimentalCrel = false;
2592 StringRef RelocSectionSym;
2593 bool SFrame = false, ExperimentalSFrame = false;
2594 bool ImplicitMapSyms = false;
2595 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2596 bool UseNoExecStack = false;
2597 bool Msa = false;
2598 const char *MipsTargetFeature = nullptr;
2599 llvm::SmallVector<const char *> SparcTargetFeatures;
2600 StringRef ImplicitIt;
2601 for (const Arg *A :
2602 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2603 options::OPT_mimplicit_it_EQ)) {
2604 A->claim();
2605
2606 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2607 switch (C.getDefaultToolChain().getArch()) {
2608 case llvm::Triple::arm:
2609 case llvm::Triple::armeb:
2610 case llvm::Triple::thumb:
2611 case llvm::Triple::thumbeb:
2612 // Only store the value; the last value set takes effect.
2613 ImplicitIt = A->getValue();
2614 if (!CheckARMImplicitITArg(ImplicitIt))
2615 D.Diag(diag::err_drv_unsupported_option_argument)
2616 << A->getSpelling() << ImplicitIt;
2617 continue;
2618 default:
2619 break;
2620 }
2621 }
2622
2623 for (StringRef Value : A->getValues()) {
2624 if (TakeNextArg) {
2625 CmdArgs.push_back(Value.data());
2626 TakeNextArg = false;
2627 continue;
2628 }
2629
2630 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2631 Value == "-mbig-obj")
2632 continue; // LLVM handles bigobj automatically
2633
2634 auto Equal = Value.split('=');
2635 auto checkArg = [&](bool ValidTarget,
2636 std::initializer_list<const char *> Set) {
2637 if (!ValidTarget) {
2638 D.Diag(diag::err_drv_unsupported_opt_for_target)
2639 << (Twine("-Wa,") + Equal.first + "=").str()
2640 << Triple.getTriple();
2641 } else if (!llvm::is_contained(Set, Equal.second)) {
2642 D.Diag(diag::err_drv_unsupported_option_argument)
2643 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2644 }
2645 };
2646 switch (C.getDefaultToolChain().getArch()) {
2647 default:
2648 break;
2649 case llvm::Triple::x86:
2650 case llvm::Triple::x86_64:
2651 if (Equal.first == "-mrelax-relocations" ||
2652 Equal.first == "--mrelax-relocations") {
2653 UseRelaxRelocations = Equal.second == "yes";
2654 checkArg(IsELF, {"yes", "no"});
2655 continue;
2656 }
2657 if (Value == "-msse2avx") {
2658 CmdArgs.push_back("-msse2avx");
2659 continue;
2660 }
2661 break;
2662 case llvm::Triple::wasm32:
2663 case llvm::Triple::wasm64:
2664 if (Value == "--no-type-check") {
2665 CmdArgs.push_back("-mno-type-check");
2666 continue;
2667 }
2668 break;
2669 case llvm::Triple::thumb:
2670 case llvm::Triple::thumbeb:
2671 case llvm::Triple::arm:
2672 case llvm::Triple::armeb:
2673 if (Equal.first == "-mimplicit-it") {
2674 // Only store the value; the last value set takes effect.
2675 ImplicitIt = Equal.second;
2676 checkArg(true, {"always", "never", "arm", "thumb"});
2677 continue;
2678 }
2679 if (Value == "-mthumb")
2680 // -mthumb has already been processed in ComputeLLVMTriple()
2681 // recognize but skip over here.
2682 continue;
2683 break;
2684 case llvm::Triple::aarch64:
2685 case llvm::Triple::aarch64_be:
2686 case llvm::Triple::aarch64_32:
2687 if (Equal.first == "-mmapsyms") {
2688 ImplicitMapSyms = Equal.second == "implicit";
2689 checkArg(IsELF, {"default", "implicit"});
2690 continue;
2691 }
2692 break;
2693 case llvm::Triple::mips:
2694 case llvm::Triple::mipsel:
2695 case llvm::Triple::mips64:
2696 case llvm::Triple::mips64el:
2697 if (Value == "--trap") {
2698 CmdArgs.push_back("-target-feature");
2699 CmdArgs.push_back("+use-tcc-in-div");
2700 continue;
2701 }
2702 if (Value == "--break") {
2703 CmdArgs.push_back("-target-feature");
2704 CmdArgs.push_back("-use-tcc-in-div");
2705 continue;
2706 }
2707 if (Value.starts_with("-msoft-float")) {
2708 CmdArgs.push_back("-target-feature");
2709 CmdArgs.push_back("+soft-float");
2710 continue;
2711 }
2712 if (Value.starts_with("-mhard-float")) {
2713 CmdArgs.push_back("-target-feature");
2714 CmdArgs.push_back("-soft-float");
2715 continue;
2716 }
2717 if (Value == "-mmsa") {
2718 Msa = true;
2719 continue;
2720 }
2721 if (Value == "-mno-msa") {
2722 Msa = false;
2723 continue;
2724 }
2725 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2726 .Case("-mips1", "+mips1")
2727 .Case("-mips2", "+mips2")
2728 .Case("-mips3", "+mips3")
2729 .Case("-mips4", "+mips4")
2730 .Case("-mips5", "+mips5")
2731 .Case("-mips32", "+mips32")
2732 .Case("-mips32r2", "+mips32r2")
2733 .Case("-mips32r3", "+mips32r3")
2734 .Case("-mips32r5", "+mips32r5")
2735 .Case("-mips32r6", "+mips32r6")
2736 .Case("-mips64", "+mips64")
2737 .Case("-mips64r2", "+mips64r2")
2738 .Case("-mips64r3", "+mips64r3")
2739 .Case("-mips64r5", "+mips64r5")
2740 .Case("-mips64r6", "+mips64r6")
2741 .Default(nullptr);
2742 if (MipsTargetFeature)
2743 continue;
2744 break;
2745
2746 case llvm::Triple::sparc:
2747 case llvm::Triple::sparcel:
2748 case llvm::Triple::sparcv9:
2749 if (Value == "--undeclared-regs") {
2750 // LLVM already allows undeclared use of G registers, so this option
2751 // becomes a no-op. This solely exists for GNU compatibility.
2752 // TODO implement --no-undeclared-regs
2753 continue;
2754 }
2755 SparcTargetFeatures =
2756 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2757 .Case("-Av8", {"-v8plus"})
2758 .Case("-Av8plus", {"+v8plus", "+v9"})
2759 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2760 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2761 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2762 .Case("-Av9", {"+v9"})
2763 .Case("-Av9a", {"+v9", "+vis"})
2764 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2765 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2766 .Default({});
2767 if (!SparcTargetFeatures.empty())
2768 continue;
2769 break;
2770 }
2771
2772 if (Value == "-force_cpusubtype_ALL") {
2773 // Do nothing, this is the default and we don't support anything else.
2774 } else if (Value == "-L") {
2775 CmdArgs.push_back("-msave-temp-labels");
2776 } else if (Value == "--fatal-warnings") {
2777 CmdArgs.push_back("-massembler-fatal-warnings");
2778 } else if (Value == "--no-warn" || Value == "-W") {
2779 CmdArgs.push_back("-massembler-no-warn");
2780 } else if (Value == "--noexecstack") {
2781 UseNoExecStack = true;
2782 } else if (Value.starts_with("-compress-debug-sections") ||
2783 Value.starts_with("--compress-debug-sections") ||
2784 Value == "-nocompress-debug-sections" ||
2785 Value == "--nocompress-debug-sections") {
2786 CmdArgs.push_back(Value.data());
2787 } else if (Value == "--crel") {
2788 Crel = true;
2789 } else if (Value == "--no-crel") {
2790 Crel = false;
2791 } else if (Value == "--allow-experimental-crel") {
2792 ExperimentalCrel = true;
2793 } else if (Value.starts_with("--reloc-section-sym=")) {
2794 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2795 } else if (Value.starts_with("-I")) {
2796 CmdArgs.push_back(Value.data());
2797 // We need to consume the next argument if the current arg is a plain
2798 // -I. The next arg will be the include directory.
2799 if (Value == "-I")
2800 TakeNextArg = true;
2801 } else if (Value.starts_with("-gdwarf-")) {
2802 // "-gdwarf-N" options are not cc1as options.
2803 unsigned DwarfVersion = DwarfVersionNum(Value);
2804 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2805 CmdArgs.push_back(Value.data());
2806 } else {
2807 RenderDebugEnablingArgs(Args, CmdArgs,
2808 llvm::codegenoptions::DebugInfoConstructor,
2809 DwarfVersion, llvm::DebuggerKind::Default);
2810 }
2811 } else if (Value == "--gsframe") {
2812 SFrame = true;
2813 } else if (Value == "--allow-experimental-sframe") {
2814 ExperimentalSFrame = true;
2815 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2816 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2817 // Do nothing, we'll validate it later.
2818 } else if (Value == "-defsym" || Value == "--defsym") {
2819 if (A->getNumValues() != 2) {
2820 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2821 break;
2822 }
2823 const char *S = A->getValue(1);
2824 auto Pair = StringRef(S).split('=');
2825 auto Sym = Pair.first;
2826 auto SVal = Pair.second;
2827
2828 if (Sym.empty() || SVal.empty()) {
2829 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2830 break;
2831 }
2832 int64_t IVal;
2833 if (SVal.getAsInteger(0, IVal)) {
2834 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2835 break;
2836 }
2837 CmdArgs.push_back("--defsym");
2838 TakeNextArg = true;
2839 } else if (Value == "-fdebug-compilation-dir") {
2840 CmdArgs.push_back("-fdebug-compilation-dir");
2841 TakeNextArg = true;
2842 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2843 // The flag is a -Wa / -Xassembler argument and Options doesn't
2844 // parse the argument, so this isn't automatically aliased to
2845 // -fdebug-compilation-dir (without '=') here.
2846 CmdArgs.push_back("-fdebug-compilation-dir");
2847 CmdArgs.push_back(Value.data());
2848 } else if (Value == "--version") {
2849 D.PrintVersion(C, llvm::outs());
2850 } else {
2851 D.Diag(diag::err_drv_unsupported_option_argument)
2852 << A->getSpelling() << Value;
2853 }
2854 }
2855 }
2856 if (ImplicitIt.size())
2857 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2858 if (Crel) {
2859 if (!ExperimentalCrel)
2860 D.Diag(diag::err_drv_experimental_crel);
2861 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2862 CmdArgs.push_back("--crel");
2863 } else {
2864 D.Diag(diag::err_drv_unsupported_opt_for_target)
2865 << "-Wa,--crel" << D.getTargetTriple();
2866 }
2867 }
2868 if (!RelocSectionSym.empty()) {
2869 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2870 RelocSectionSym != "none")
2871 D.Diag(diag::err_drv_invalid_value)
2872 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2873 << RelocSectionSym;
2874 else if (Triple.isOSBinFormatELF())
2875 CmdArgs.push_back(
2876 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2877 else
2878 D.Diag(diag::err_drv_unsupported_opt_for_target)
2879 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2880 }
2881 if (SFrame) {
2882 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2883 if (!ExperimentalSFrame)
2884 D.Diag(diag::err_drv_experimental_sframe);
2885 else
2886 CmdArgs.push_back("--gsframe");
2887 } else {
2888 D.Diag(diag::err_drv_unsupported_opt_for_target)
2889 << "-Wa,--gsframe" << D.getTargetTriple();
2890 }
2891 }
2892 if (ImplicitMapSyms)
2893 CmdArgs.push_back("-mmapsyms=implicit");
2894 if (Msa)
2895 CmdArgs.push_back("-mmsa");
2896 if (!UseRelaxRelocations)
2897 CmdArgs.push_back("-mrelax-relocations=no");
2898 if (UseNoExecStack)
2899 CmdArgs.push_back("-mnoexecstack");
2900 if (MipsTargetFeature != nullptr) {
2901 CmdArgs.push_back("-target-feature");
2902 CmdArgs.push_back(MipsTargetFeature);
2903 }
2904
2905 for (const char *Feature : SparcTargetFeatures) {
2906 CmdArgs.push_back("-target-feature");
2907 CmdArgs.push_back(Feature);
2908 }
2909
2910 // forward -fembed-bitcode to assmebler
2911 if (C.getDriver().embedBitcodeEnabled() ||
2912 C.getDriver().embedBitcodeMarkerOnly())
2913 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2914
2915 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2916 CmdArgs.push_back("-as-secure-log-file");
2917 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2918 }
2919}
2920
2921static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2922 bool OFastEnabled, const ArgList &Args,
2923 ArgStringList &CmdArgs,
2924 const JobAction &JA) {
2925 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2926 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2927 llvm::StringLiteral("SLEEF")};
2928 bool NoMathErrnoWasImpliedByVecLib = false;
2929 const Arg *VecLibArg = nullptr;
2930 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2931 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2932
2933 // Handle various floating point optimization flags, mapping them to the
2934 // appropriate LLVM code generation flags. This is complicated by several
2935 // "umbrella" flags, so we do this by stepping through the flags incrementally
2936 // adjusting what we think is enabled/disabled, then at the end setting the
2937 // LLVM flags based on the final state.
2938 bool HonorINFs = true;
2939 bool HonorNaNs = true;
2940 bool ApproxFunc = false;
2941 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2942 bool MathErrno = TC.IsMathErrnoDefault();
2943 bool AssociativeMath = false;
2944 bool ReciprocalMath = false;
2945 bool SignedZeros = true;
2946 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2947 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2948 // overriden by ffp-exception-behavior?
2949 bool RoundingFPMath = false;
2950 // -ffp-model values: strict, fast, precise
2951 StringRef FPModel = "";
2952 // -ffp-exception-behavior options: strict, maytrap, ignore
2953 StringRef FPExceptionBehavior = "";
2954 // -ffp-eval-method options: double, extended, source
2955 StringRef FPEvalMethod = "";
2956 llvm::DenormalMode DenormalFPMath =
2957 TC.getDefaultDenormalModeForType(Args, JA);
2958 llvm::DenormalMode DenormalFP32Math =
2959 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2960
2961 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2962 // If one wasn't given by the user, don't pass it here.
2963 StringRef FPContract;
2964 StringRef LastSeenFfpContractOption;
2965 StringRef LastFpContractOverrideOption;
2966 bool SeenUnsafeMathModeOption = false;
2969 FPContract = "on";
2970 bool StrictFPModel = false;
2971 StringRef Float16ExcessPrecision = "";
2972 StringRef BFloat16ExcessPrecision = "";
2974 std::string ComplexRangeStr;
2975 StringRef LastComplexRangeOption;
2976
2977 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2978 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2979 if (Aggressive) {
2980 HonorINFs = false;
2981 HonorNaNs = false;
2983 LastComplexRangeOption, Range);
2984 } else {
2985 HonorINFs = true;
2986 HonorNaNs = true;
2987 setComplexRange(D, CallerOption,
2989 LastComplexRangeOption, Range);
2990 }
2991 MathErrno = false;
2992 AssociativeMath = true;
2993 ReciprocalMath = true;
2994 ApproxFunc = true;
2995 SignedZeros = false;
2996 TrappingMath = false;
2997 RoundingFPMath = false;
2998 FPExceptionBehavior = "";
2999 FPContract = "fast";
3000 SeenUnsafeMathModeOption = true;
3001 };
3002
3003 // Lambda to consolidate common handling for fp-contract
3004 auto restoreFPContractState = [&]() {
3005 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3006 // For other targets, if the state has been changed by one of the
3007 // unsafe-math umbrella options a subsequent -fno-fast-math or
3008 // -fno-unsafe-math-optimizations option reverts to the last value seen for
3009 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3010 // option. If we have not seen an unsafe-math option or -ffp-contract,
3011 // we leave the FPContract state unchanged.
3014 if (LastSeenFfpContractOption != "")
3015 FPContract = LastSeenFfpContractOption;
3016 else if (SeenUnsafeMathModeOption)
3017 FPContract = "on";
3018 }
3019 // In this case, we're reverting to the last explicit fp-contract option
3020 // or the platform default
3021 LastFpContractOverrideOption = "";
3022 };
3023
3024 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3025 CmdArgs.push_back("-mlimit-float-precision");
3026 CmdArgs.push_back(A->getValue());
3027 }
3028
3029 for (const Arg *A : Args) {
3030 llvm::scope_exit CheckMathErrnoForVecLib(
3031 [&, MathErrnoBeforeArg = MathErrno] {
3032 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3033 ArgThatEnabledMathErrnoAfterVecLib = A;
3034 });
3035
3036 switch (A->getOption().getID()) {
3037 // If this isn't an FP option skip the claim below
3038 default: continue;
3039
3040 case options::OPT_fcx_limited_range:
3041 setComplexRange(D, A->getSpelling(),
3043 LastComplexRangeOption, Range);
3044 break;
3045 case options::OPT_fno_cx_limited_range:
3046 setComplexRange(D, A->getSpelling(),
3048 LastComplexRangeOption, Range);
3049 break;
3050 case options::OPT_fcx_fortran_rules:
3051 setComplexRange(D, A->getSpelling(),
3053 LastComplexRangeOption, Range);
3054 break;
3055 case options::OPT_fno_cx_fortran_rules:
3056 setComplexRange(D, A->getSpelling(),
3058 LastComplexRangeOption, Range);
3059 break;
3060 case options::OPT_fcomplex_arithmetic_EQ: {
3062 StringRef Val = A->getValue();
3063 if (Val == "full")
3065 else if (Val == "improved")
3067 else if (Val == "promoted")
3069 else if (Val == "basic")
3071 else {
3072 D.Diag(diag::err_drv_unsupported_option_argument)
3073 << A->getSpelling() << Val;
3074 break;
3075 }
3076 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3077 LastComplexRangeOption, Range);
3078 break;
3079 }
3080 case options::OPT_ffp_model_EQ: {
3081 // If -ffp-model= is seen, reset to fno-fast-math
3082 HonorINFs = true;
3083 HonorNaNs = true;
3084 ApproxFunc = false;
3085 // Turning *off* -ffast-math restores the toolchain default.
3086 MathErrno = TC.IsMathErrnoDefault();
3087 AssociativeMath = false;
3088 ReciprocalMath = false;
3089 SignedZeros = true;
3090
3091 StringRef Val = A->getValue();
3092 if (OFastEnabled && Val != "aggressive") {
3093 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3094 D.Diag(clang::diag::warn_drv_overriding_option)
3095 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3096 break;
3097 }
3098 StrictFPModel = false;
3099 if (!FPModel.empty() && FPModel != Val)
3100 D.Diag(clang::diag::warn_drv_overriding_option)
3101 << Args.MakeArgString("-ffp-model=" + FPModel)
3102 << Args.MakeArgString("-ffp-model=" + Val);
3103 if (Val == "fast") {
3104 FPModel = Val;
3105 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3106 // applyFastMath sets fp-contract="fast"
3107 LastFpContractOverrideOption = "-ffp-model=fast";
3108 } else if (Val == "aggressive") {
3109 FPModel = Val;
3110 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3111 // applyFastMath sets fp-contract="fast"
3112 LastFpContractOverrideOption = "-ffp-model=aggressive";
3113 } else if (Val == "precise") {
3114 FPModel = Val;
3115 FPContract = "on";
3116 LastFpContractOverrideOption = "-ffp-model=precise";
3117 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3119 LastComplexRangeOption, Range);
3120 } else if (Val == "strict") {
3121 StrictFPModel = true;
3122 FPExceptionBehavior = "strict";
3123 FPModel = Val;
3124 FPContract = "off";
3125 LastFpContractOverrideOption = "-ffp-model=strict";
3126 TrappingMath = true;
3127 RoundingFPMath = true;
3128 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3130 LastComplexRangeOption, Range);
3131 } else
3132 D.Diag(diag::err_drv_unsupported_option_argument)
3133 << A->getSpelling() << Val;
3134 break;
3135 }
3136
3137 // Options controlling individual features
3138 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3139 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3140 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3141 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3142 case options::OPT_fapprox_func: ApproxFunc = true; break;
3143 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3144 case options::OPT_fmath_errno: MathErrno = true; break;
3145 case options::OPT_fno_math_errno: MathErrno = false; break;
3146 case options::OPT_fassociative_math: AssociativeMath = true; break;
3147 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3148 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3149 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3150 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3151 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3152 case options::OPT_ftrapping_math:
3153 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3154 FPExceptionBehavior != "strict")
3155 // Warn that previous value of option is overridden.
3156 D.Diag(clang::diag::warn_drv_overriding_option)
3157 << Args.MakeArgString("-ffp-exception-behavior=" +
3158 FPExceptionBehavior)
3159 << "-ftrapping-math";
3160 TrappingMath = true;
3161 TrappingMathPresent = true;
3162 FPExceptionBehavior = "strict";
3163 break;
3164 case options::OPT_fveclib:
3165 VecLibArg = A;
3166 NoMathErrnoWasImpliedByVecLib =
3167 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3168 if (NoMathErrnoWasImpliedByVecLib)
3169 MathErrno = false;
3170 break;
3171 case options::OPT_fno_trapping_math:
3172 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3173 FPExceptionBehavior != "ignore")
3174 // Warn that previous value of option is overridden.
3175 D.Diag(clang::diag::warn_drv_overriding_option)
3176 << Args.MakeArgString("-ffp-exception-behavior=" +
3177 FPExceptionBehavior)
3178 << "-fno-trapping-math";
3179 TrappingMath = false;
3180 TrappingMathPresent = true;
3181 FPExceptionBehavior = "ignore";
3182 break;
3183
3184 case options::OPT_frounding_math:
3185 RoundingFPMath = true;
3186 break;
3187
3188 case options::OPT_fno_rounding_math:
3189 RoundingFPMath = false;
3190 break;
3191
3192 case options::OPT_fdenormal_fp_math_EQ:
3193 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3194 DenormalFP32Math = DenormalFPMath;
3195 if (!DenormalFPMath.isValid()) {
3196 D.Diag(diag::err_drv_invalid_value)
3197 << A->getAsString(Args) << A->getValue();
3198 }
3199 break;
3200
3201 case options::OPT_fdenormal_fp_math_f32_EQ:
3202 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3203 if (!DenormalFP32Math.isValid()) {
3204 D.Diag(diag::err_drv_invalid_value)
3205 << A->getAsString(Args) << A->getValue();
3206 }
3207 break;
3208
3209 // Validate and pass through -ffp-contract option.
3210 case options::OPT_ffp_contract: {
3211 StringRef Val = A->getValue();
3212 if (Val == "fast" || Val == "on" || Val == "off" ||
3213 Val == "fast-honor-pragmas") {
3214 if (Val != FPContract && LastFpContractOverrideOption != "") {
3215 D.Diag(clang::diag::warn_drv_overriding_option)
3216 << LastFpContractOverrideOption
3217 << Args.MakeArgString("-ffp-contract=" + Val);
3218 }
3219
3220 FPContract = Val;
3221 LastSeenFfpContractOption = Val;
3222 LastFpContractOverrideOption = "";
3223 } else
3224 D.Diag(diag::err_drv_unsupported_option_argument)
3225 << A->getSpelling() << Val;
3226 break;
3227 }
3228
3229 // Validate and pass through -ffp-exception-behavior option.
3230 case options::OPT_ffp_exception_behavior_EQ: {
3231 StringRef Val = A->getValue();
3232 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3233 FPExceptionBehavior != Val)
3234 // Warn that previous value of option is overridden.
3235 D.Diag(clang::diag::warn_drv_overriding_option)
3236 << Args.MakeArgString("-ffp-exception-behavior=" +
3237 FPExceptionBehavior)
3238 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3239 TrappingMath = TrappingMathPresent = false;
3240 if (Val == "ignore" || Val == "maytrap")
3241 FPExceptionBehavior = Val;
3242 else if (Val == "strict") {
3243 FPExceptionBehavior = Val;
3244 TrappingMath = TrappingMathPresent = true;
3245 } else
3246 D.Diag(diag::err_drv_unsupported_option_argument)
3247 << A->getSpelling() << Val;
3248 break;
3249 }
3250
3251 // Validate and pass through -ffp-eval-method option.
3252 case options::OPT_ffp_eval_method_EQ: {
3253 StringRef Val = A->getValue();
3254 if (Val == "double" || Val == "extended" || Val == "source")
3255 FPEvalMethod = Val;
3256 else
3257 D.Diag(diag::err_drv_unsupported_option_argument)
3258 << A->getSpelling() << Val;
3259 break;
3260 }
3261
3262 case options::OPT_fexcess_precision_EQ: {
3263 StringRef Val = A->getValue();
3264 const llvm::Triple::ArchType Arch = TC.getArch();
3265 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3266 if (Val == "standard" || Val == "fast")
3267 Float16ExcessPrecision = Val;
3268 // To make it GCC compatible, allow the value of "16" which
3269 // means disable excess precision, the same meaning than clang's
3270 // equivalent value "none".
3271 else if (Val == "16")
3272 Float16ExcessPrecision = "none";
3273 else
3274 D.Diag(diag::err_drv_unsupported_option_argument)
3275 << A->getSpelling() << Val;
3276 } else {
3277 if (!(Val == "standard" || Val == "fast"))
3278 D.Diag(diag::err_drv_unsupported_option_argument)
3279 << A->getSpelling() << Val;
3280 }
3281 BFloat16ExcessPrecision = Float16ExcessPrecision;
3282 break;
3283 }
3284 case options::OPT_ffinite_math_only:
3285 HonorINFs = false;
3286 HonorNaNs = false;
3287 break;
3288 case options::OPT_fno_finite_math_only:
3289 HonorINFs = true;
3290 HonorNaNs = true;
3291 break;
3292
3293 case options::OPT_funsafe_math_optimizations:
3294 AssociativeMath = true;
3295 ReciprocalMath = true;
3296 SignedZeros = false;
3297 ApproxFunc = true;
3298 TrappingMath = false;
3299 FPExceptionBehavior = "";
3300 FPContract = "fast";
3301 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3302 SeenUnsafeMathModeOption = true;
3303 break;
3304 case options::OPT_fno_unsafe_math_optimizations:
3305 AssociativeMath = false;
3306 ReciprocalMath = false;
3307 SignedZeros = true;
3308 ApproxFunc = false;
3309 restoreFPContractState();
3310 break;
3311
3312 case options::OPT_cl_fast_relaxed_math:
3313 applyFastMath(true, A->getSpelling());
3314 break;
3315
3316 case options::OPT_Ofast:
3317 // If -Ofast is the optimization level, then -ffast-math should be enabled
3318 if (!OFastEnabled)
3319 continue;
3320 [[fallthrough]];
3321 case options::OPT_ffast_math:
3322 applyFastMath(true, A->getSpelling());
3323 if (A->getOption().getID() == options::OPT_Ofast)
3324 LastFpContractOverrideOption = "-Ofast";
3325 else
3326 LastFpContractOverrideOption = "-ffast-math";
3327 break;
3328 case options::OPT_fno_fast_math:
3329 HonorINFs = true;
3330 HonorNaNs = true;
3331 // Turning on -ffast-math (with either flag) removes the need for
3332 // MathErrno. However, turning *off* -ffast-math merely restores the
3333 // toolchain default (which may be false).
3334 MathErrno = TC.IsMathErrnoDefault();
3335 AssociativeMath = false;
3336 ReciprocalMath = false;
3337 ApproxFunc = false;
3338 SignedZeros = true;
3339 restoreFPContractState();
3341 setComplexRange(D, A->getSpelling(),
3343 LastComplexRangeOption, Range);
3344 else
3346 LastComplexRangeOption = "";
3347 LastFpContractOverrideOption = "";
3348 break;
3349 } // End switch (A->getOption().getID())
3350
3351 // The StrictFPModel local variable is needed to report warnings
3352 // in the way we intend. If -ffp-model=strict has been used, we
3353 // want to report a warning for the next option encountered that
3354 // takes us out of the settings described by fp-model=strict, but
3355 // we don't want to continue issuing warnings for other conflicting
3356 // options after that.
3357 if (StrictFPModel) {
3358 // If -ffp-model=strict has been specified on command line but
3359 // subsequent options conflict then emit warning diagnostic.
3360 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3361 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3362 FPContract == "off")
3363 // OK: Current Arg doesn't conflict with -ffp-model=strict
3364 ;
3365 else {
3366 StrictFPModel = false;
3367 FPModel = "";
3368 // The warning for -ffp-contract would have been reported by the
3369 // OPT_ffp_contract_EQ handler above. A special check here is needed
3370 // to avoid duplicating the warning.
3371 auto RHS = (A->getNumValues() == 0)
3372 ? A->getSpelling()
3373 : Args.MakeArgString(A->getSpelling() + A->getValue());
3374 if (A->getSpelling() != "-ffp-contract=") {
3375 if (RHS != "-ffp-model=strict")
3376 D.Diag(clang::diag::warn_drv_overriding_option)
3377 << "-ffp-model=strict" << RHS;
3378 }
3379 }
3380 }
3381
3382 // If we handled this option claim it
3383 A->claim();
3384 }
3385
3386 if (!HonorINFs)
3387 CmdArgs.push_back("-menable-no-infs");
3388
3389 if (!HonorNaNs)
3390 CmdArgs.push_back("-menable-no-nans");
3391
3392 if (ApproxFunc)
3393 CmdArgs.push_back("-fapprox-func");
3394
3395 if (MathErrno) {
3396 CmdArgs.push_back("-fmath-errno");
3397 if (NoMathErrnoWasImpliedByVecLib)
3398 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3399 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3400 << VecLibArg->getAsString(Args);
3401 }
3402
3403 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3404 !TrappingMath)
3405 CmdArgs.push_back("-funsafe-math-optimizations");
3406
3407 if (!SignedZeros)
3408 CmdArgs.push_back("-fno-signed-zeros");
3409
3410 if (AssociativeMath && !SignedZeros && !TrappingMath)
3411 CmdArgs.push_back("-mreassociate");
3412
3413 if (ReciprocalMath)
3414 CmdArgs.push_back("-freciprocal-math");
3415
3416 if (TrappingMath) {
3417 // FP Exception Behavior is also set to strict
3418 assert(FPExceptionBehavior == "strict");
3419 }
3420
3421 // The default is IEEE.
3422 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3423 llvm::SmallString<64> DenormFlag;
3424 llvm::raw_svector_ostream ArgStr(DenormFlag);
3425 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3426 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3427 }
3428
3429 // Add f32 specific denormal mode flag if it's different.
3430 if (DenormalFP32Math != DenormalFPMath) {
3431 llvm::SmallString<64> DenormFlag;
3432 llvm::raw_svector_ostream ArgStr(DenormFlag);
3433 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3434 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3435 }
3436
3437 if (!FPContract.empty())
3438 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3439
3440 if (RoundingFPMath)
3441 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3442 else
3443 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3444
3445 if (!FPExceptionBehavior.empty())
3446 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3447 FPExceptionBehavior));
3448
3449 if (!FPEvalMethod.empty())
3450 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3451
3452 if (!Float16ExcessPrecision.empty())
3453 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3454 Float16ExcessPrecision));
3455 if (!BFloat16ExcessPrecision.empty())
3456 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3457 BFloat16ExcessPrecision));
3458
3459 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3460 if (!Recip.empty())
3461 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3462
3463 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3464 // individual features enabled by -ffast-math instead of the option itself as
3465 // that's consistent with gcc's behaviour.
3466 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3467 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3468 CmdArgs.push_back("-ffast-math");
3469
3470 // Handle __FINITE_MATH_ONLY__ similarly.
3471 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3472 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3473 // -menable-no-nans are set by the user.
3474 bool shouldAddFiniteMathOnly = false;
3475 if (!HonorINFs && !HonorNaNs) {
3476 shouldAddFiniteMathOnly = true;
3477 } else {
3478 bool InfValues = true;
3479 bool NanValues = true;
3480 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3481 StringRef ArgValue = Arg->getValue();
3482 if (ArgValue == "-menable-no-nans")
3483 NanValues = false;
3484 else if (ArgValue == "-menable-no-infs")
3485 InfValues = false;
3486 }
3487 if (!NanValues && !InfValues)
3488 shouldAddFiniteMathOnly = true;
3489 }
3490 if (shouldAddFiniteMathOnly) {
3491 CmdArgs.push_back("-ffinite-math-only");
3492 }
3493 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3494 CmdArgs.push_back("-mfpmath");
3495 CmdArgs.push_back(A->getValue());
3496 }
3497
3498 // Disable a codegen optimization for floating-point casts.
3499 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3500 options::OPT_fstrict_float_cast_overflow, false))
3501 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3502
3504 ComplexRangeStr = renderComplexRangeOption(Range);
3505 if (!ComplexRangeStr.empty()) {
3506 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3507 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3508 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3509 complexRangeKindToStr(Range)));
3510 }
3511 if (Args.hasArg(options::OPT_fcx_limited_range))
3512 CmdArgs.push_back("-fcx-limited-range");
3513 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3514 CmdArgs.push_back("-fcx-fortran-rules");
3515 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3516 CmdArgs.push_back("-fno-cx-limited-range");
3517 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3518 CmdArgs.push_back("-fno-cx-fortran-rules");
3519}
3520
3521static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3522 const llvm::Triple &Triple,
3523 const InputInfo &Input) {
3524 // Add default argument set.
3525 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3526 CmdArgs.push_back("-analyzer-checker=core");
3527 CmdArgs.push_back("-analyzer-checker=apiModeling");
3528
3529 if (!Triple.isWindowsMSVCEnvironment()) {
3530 CmdArgs.push_back("-analyzer-checker=unix");
3531 } else {
3532 // Enable "unix" checkers that also work on Windows.
3533 CmdArgs.push_back("-analyzer-checker=unix.API");
3534 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3535 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3536 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3537 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3538 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3539 }
3540
3541 // Disable some unix checkers for PS4/PS5.
3542 if (Triple.isPS()) {
3543 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3544 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3545 }
3546
3547 if (Triple.isOSDarwin()) {
3548 CmdArgs.push_back("-analyzer-checker=osx");
3549 CmdArgs.push_back(
3550 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3551 }
3552 else if (Triple.isOSFuchsia())
3553 CmdArgs.push_back("-analyzer-checker=fuchsia");
3554
3555 CmdArgs.push_back("-analyzer-checker=deadcode");
3556
3557 if (types::isCXX(Input.getType()))
3558 CmdArgs.push_back("-analyzer-checker=cplusplus");
3559
3560 if (!Triple.isPS()) {
3561 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3562 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3563 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3564 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3565 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3566 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3567 }
3568
3569 // Default nullability checks.
3570 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3571 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3572 }
3573
3574 // Set the output format. The default is plist, for (lame) historical reasons.
3575 CmdArgs.push_back("-analyzer-output");
3576 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3577 CmdArgs.push_back(A->getValue());
3578 else
3579 CmdArgs.push_back("plist");
3580
3581 // Disable the presentation of standard compiler warnings when using
3582 // --analyze. We only want to show static analyzer diagnostics or frontend
3583 // errors.
3584 CmdArgs.push_back("-w");
3585
3586 // Add -Xanalyzer arguments when running as analyzer.
3587 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3588}
3589
3590static bool isValidSymbolName(StringRef S) {
3591 if (S.empty())
3592 return false;
3593
3594 if (std::isdigit(S[0]))
3595 return false;
3596
3597 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3598}
3599
3600static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3601 const ArgList &Args, ArgStringList &CmdArgs,
3602 bool KernelOrKext) {
3603 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3604
3605 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3606 // doesn't even have a stack!
3607 if (EffectiveTriple.isNVPTX())
3608 return;
3609
3610 // -stack-protector=0 is default.
3612 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3613 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3614
3615 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3616 options::OPT_fstack_protector_all,
3617 options::OPT_fstack_protector_strong,
3618 options::OPT_fstack_protector)) {
3619 if (A->getOption().matches(options::OPT_fstack_protector))
3620 StackProtectorLevel =
3621 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3622 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3623 StackProtectorLevel = LangOptions::SSPStrong;
3624 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3625 StackProtectorLevel = LangOptions::SSPReq;
3626
3627 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3628 D.Diag(diag::warn_drv_unsupported_option_for_target)
3629 << A->getSpelling() << EffectiveTriple.getTriple();
3630 StackProtectorLevel = DefaultStackProtectorLevel;
3631 }
3632 } else {
3633 StackProtectorLevel = DefaultStackProtectorLevel;
3634 }
3635
3636 if (StackProtectorLevel) {
3637 CmdArgs.push_back("-stack-protector");
3638 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3639 }
3640
3641 // --param ssp-buffer-size=
3642 for (const Arg *A : Args.filtered(options::OPT__param)) {
3643 StringRef Str(A->getValue());
3644 if (Str.consume_front("ssp-buffer-size=")) {
3645 if (StackProtectorLevel) {
3646 CmdArgs.push_back("-stack-protector-buffer-size");
3647 // FIXME: Verify the argument is a valid integer.
3648 CmdArgs.push_back(Args.MakeArgString(Str));
3649 }
3650 A->claim();
3651 }
3652 }
3653
3654 const std::string &TripleStr = EffectiveTriple.getTriple();
3655 StringRef GuardValue;
3656 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3657 GuardValue = A->getValue();
3658 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3659 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3660 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3661 !EffectiveTriple.isSystemZ())
3662 D.Diag(diag::err_drv_unsupported_opt_for_target)
3663 << A->getAsString(Args) << TripleStr;
3664 // z/OS only supports the tls mode.
3665 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3666 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3667 << A->getOption().getName() << GuardValue << "tls";
3668 return;
3669 }
3670 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3671 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3672 GuardValue != "tls" && GuardValue != "global") {
3673 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3674 << A->getOption().getName() << GuardValue << "tls global";
3675 return;
3676 }
3677 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3678 GuardValue == "tls") {
3679 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3680 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3681 << A->getAsString(Args);
3682 return;
3683 }
3684 // Check whether the target subarch supports the hardware TLS register
3685 if (!arm::isHardTPSupported(EffectiveTriple)) {
3686 D.Diag(diag::err_target_unsupported_tp_hard)
3687 << EffectiveTriple.getArchName();
3688 return;
3689 }
3690 // Check whether the user asked for something other than -mtp=cp15
3691 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3692 StringRef Value = A->getValue();
3693 if (Value != "cp15") {
3694 D.Diag(diag::err_drv_argument_not_allowed_with)
3695 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3696 return;
3697 }
3698 }
3699 CmdArgs.push_back("-target-feature");
3700 CmdArgs.push_back("+read-tp-tpidruro");
3701 }
3702 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3703 GuardValue != "global") {
3704 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3705 << A->getOption().getName() << GuardValue << "sysreg global";
3706 return;
3707 }
3708 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3709 if (GuardValue != "tls" && GuardValue != "global") {
3710 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3711 << A->getOption().getName() << GuardValue << "tls global";
3712 return;
3713 }
3714 if (GuardValue == "tls") {
3715 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3716 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3717 << A->getAsString(Args);
3718 return;
3719 }
3720 }
3721 }
3722 A->render(Args, CmdArgs);
3723 }
3724
3725 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3726 StringRef Value = A->getValue();
3727 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3728 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3729 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3730 D.Diag(diag::err_drv_unsupported_opt_for_target)
3731 << A->getAsString(Args) << TripleStr;
3732 int Offset;
3733 if (Value.getAsInteger(10, Offset)) {
3734 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3735 return;
3736 }
3737 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3738 (Offset < 0 || Offset > 0xfffff)) {
3739 D.Diag(diag::err_drv_invalid_int_value)
3740 << A->getOption().getName() << Value;
3741 return;
3742 }
3743 A->render(Args, CmdArgs);
3744 }
3745
3746 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3747 StringRef Value = A->getValue();
3748 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3749 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3750 D.Diag(diag::err_drv_unsupported_opt_for_target)
3751 << A->getAsString(Args) << TripleStr;
3752 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3753 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3754 << A->getOption().getName() << Value << "fs gs";
3755 return;
3756 }
3757 if (EffectiveTriple.isAArch64() &&
3758 llvm::StringSwitch<bool>(Value)
3759 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3760 "tpidr_el2", "far_el1", "far_el2"},
3761 false)
3762 .Default(true)) {
3763 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3764 << A->getOption().getName() << Value
3765 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3766 return;
3767 }
3768 if (EffectiveTriple.isRISCV() && Value != "tp") {
3769 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3770 << A->getOption().getName() << Value << "tp";
3771 return;
3772 }
3773 if (EffectiveTriple.isPPC64() && Value != "r13") {
3774 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3775 << A->getOption().getName() << Value << "r13";
3776 return;
3777 }
3778 if (EffectiveTriple.isPPC32() && Value != "r2") {
3779 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3780 << A->getOption().getName() << Value << "r2";
3781 return;
3782 }
3783 A->render(Args, CmdArgs);
3784 }
3785
3786 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3787 StringRef Value = A->getValue();
3788 if (!isValidSymbolName(Value)) {
3789 D.Diag(diag::err_drv_argument_only_allowed_with)
3790 << A->getOption().getName() << "legal symbol name";
3791 return;
3792 }
3793 A->render(Args, CmdArgs);
3794 }
3795
3796 if (Arg *A =
3797 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3798 if (!EffectiveTriple.isAArch64())
3799 D.Diag(diag::err_drv_unsupported_opt_for_target)
3800 << A->getAsString(Args) << TripleStr;
3801 StringRef Value = A->getValue();
3802 unsigned Width;
3803 if (Value.getAsInteger(10, Width)) {
3804 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3805 return;
3806 }
3807 if (Width != 4 && Width != 8) {
3808 D.Diag(diag::err_drv_invalid_int_value)
3809 << A->getOption().getName() << Value;
3810 }
3811 }
3812 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3813 if (!EffectiveTriple.isSystemZ()) {
3814 D.Diag(diag::err_drv_unsupported_opt_for_target)
3815 << A->getAsString(Args) << TripleStr;
3816 return;
3817 }
3818 if (GuardValue != "global") {
3819 D.Diag(diag::err_drv_argument_only_allowed_with)
3820 << "-mstack-protector-guard-record"
3821 << "-mstack-protector-guard=global";
3822 return;
3823 }
3824 A->render(Args, CmdArgs);
3825 }
3826}
3827
3828static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3829 ArgStringList &CmdArgs) {
3830 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3831
3832 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3833 !EffectiveTriple.isOSFuchsia())
3834 return;
3835
3836 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3837 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3838 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3839 return;
3840
3841 if (Args.hasFlag(options::OPT_fstack_clash_protection,
3842 options::OPT_fno_stack_clash_protection,
3843 EffectiveTriple.isAndroid()))
3844 CmdArgs.push_back("-fstack-clash-protection");
3845}
3846
3848 const ToolChain &TC,
3849 const ArgList &Args,
3850 ArgStringList &CmdArgs) {
3851 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3852 StringRef TrivialAutoVarInit = "";
3853
3854 for (const Arg *A : Args) {
3855 switch (A->getOption().getID()) {
3856 default:
3857 continue;
3858 case options::OPT_ftrivial_auto_var_init: {
3859 A->claim();
3860 StringRef Val = A->getValue();
3861 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3862 TrivialAutoVarInit = Val;
3863 else
3864 D.Diag(diag::err_drv_unsupported_option_argument)
3865 << A->getSpelling() << Val;
3866 break;
3867 }
3868 }
3869 }
3870
3871 if (TrivialAutoVarInit.empty())
3872 switch (DefaultTrivialAutoVarInit) {
3874 break;
3876 TrivialAutoVarInit = "pattern";
3877 break;
3879 TrivialAutoVarInit = "zero";
3880 break;
3881 }
3882
3883 if (!TrivialAutoVarInit.empty()) {
3884 CmdArgs.push_back(
3885 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3886 }
3887
3888 if (Arg *A =
3889 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3890 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3891 StringRef(
3892 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3893 "uninitialized")
3894 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3895 A->claim();
3896 StringRef Val = A->getValue();
3897 if (std::stoi(Val.str()) <= 0)
3898 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3899 CmdArgs.push_back(
3900 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3901 }
3902
3903 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3904 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3905 StringRef(
3906 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3907 "uninitialized")
3908 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3909 A->claim();
3910 StringRef Val = A->getValue();
3911 if (std::stoi(Val.str()) <= 0)
3912 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3913 CmdArgs.push_back(
3914 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3915 }
3916}
3917
3918static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3919 types::ID InputType) {
3920 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3921 // for denormal flushing handling based on the target.
3922 const unsigned ForwardedArguments[] = {
3923 options::OPT_cl_opt_disable,
3924 options::OPT_cl_strict_aliasing,
3925 options::OPT_cl_single_precision_constant,
3926 options::OPT_cl_finite_math_only,
3927 options::OPT_cl_kernel_arg_info,
3928 options::OPT_cl_unsafe_math_optimizations,
3929 options::OPT_cl_fast_relaxed_math,
3930 options::OPT_cl_mad_enable,
3931 options::OPT_cl_no_signed_zeros,
3932 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3933 options::OPT_cl_uniform_work_group_size
3934 };
3935
3936 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3937 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3938 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3939 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3940 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3941 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3942 }
3943
3944 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3945 CmdArgs.push_back("-menable-no-infs");
3946 CmdArgs.push_back("-menable-no-nans");
3947 }
3948
3949 for (const auto &Arg : ForwardedArguments)
3950 if (const auto *A = Args.getLastArg(Arg))
3951 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3952
3953 // Only add the default headers if we are compiling OpenCL sources.
3954 if ((types::isOpenCL(InputType) ||
3955 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3956 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3957 CmdArgs.push_back("-finclude-default-header");
3958 CmdArgs.push_back("-fdeclare-opencl-builtins");
3959 }
3960}
3961
3962static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
3963 ArgStringList &CmdArgs, types::ID InputType) {
3964 const unsigned ForwardedArguments[] = {
3965 options::OPT_hlsl_all_resources_bound,
3966 options::OPT_dxil_validator_version,
3967 options::OPT_res_may_alias,
3968 options::OPT_D,
3969 options::OPT_I,
3970 options::OPT_O,
3971 options::OPT_emit_llvm,
3972 options::OPT_emit_obj,
3973 options::OPT_disable_llvm_passes,
3974 options::OPT_fnative_half_type,
3975 options::OPT_fnative_int16_type,
3976 options::OPT_fmatrix_memory_layout_EQ,
3977 options::OPT_hlsl_entrypoint,
3978 options::OPT_fdx_rootsignature_define,
3979 options::OPT_fdx_rootsignature_version,
3980 options::OPT_fhlsl_spv_use_unknown_image_format,
3981 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
3982 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
3983 options::OPT_fhlsl_spv_preserve_interface};
3984 if (!types::isHLSL(InputType))
3985 return;
3986 for (const auto &Arg : ForwardedArguments)
3987 if (const auto *A = Args.getLastArg(Arg))
3988 A->renderAsInput(Args, CmdArgs);
3989 // Add the default headers if dxc_no_stdinc is not set.
3990 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3991 !Args.hasArg(options::OPT_nostdinc))
3992 CmdArgs.push_back("-finclude-default-header");
3993
3994 if (Args.hasArg(options::OPT_dxc_Zss)) {
3995 if (Args.hasArg(options::OPT_dxc_Zsb))
3996 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
3997 CmdArgs.push_back("-mllvm");
3998 CmdArgs.push_back("-dx-Zss");
3999 }
4000 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
4001 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
4002 if (Args.hasArg(options::OPT_dxc_source_in_debug_module)) {
4003 CmdArgs.push_back("-mllvm");
4004 CmdArgs.push_back("--dx-source-in-debug-module");
4005 }
4006 if (Args.hasArg(options::OPT_dxc_Qstrip_debug)) {
4007 CmdArgs.push_back("-mllvm");
4008 CmdArgs.push_back("--dx-strip-debug");
4009 }
4010 if (Args.hasArg(options::OPT_dxc_Qpdb_in_private)) {
4011 CmdArgs.push_back("-mllvm");
4012 CmdArgs.push_back("--dx-pdb-in-private");
4013 }
4014}
4015
4016static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4017 ArgStringList &CmdArgs, types::ID InputType) {
4018 if (!Args.hasArg(options::OPT_fopenacc))
4019 return;
4020
4021 CmdArgs.push_back("-fopenacc");
4022}
4023
4024static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4025 const ArgList &Args, ArgStringList &CmdArgs) {
4026 // -fbuiltin is default unless -mkernel is used.
4027 bool UseBuiltins =
4028 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4029 !Args.hasArg(options::OPT_mkernel));
4030 if (!UseBuiltins)
4031 CmdArgs.push_back("-fno-builtin");
4032
4033 // -ffreestanding implies -fno-builtin.
4034 if (Args.hasArg(options::OPT_ffreestanding))
4035 UseBuiltins = false;
4036
4037 // Process the -fno-builtin-* options.
4038 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4039 A->claim();
4040
4041 // If -fno-builtin is specified, then there's no need to pass the option to
4042 // the frontend.
4043 if (UseBuiltins)
4044 A->render(Args, CmdArgs);
4045 }
4046}
4047
4049 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4050 Twine Path{Str};
4051 Path.toVector(Result);
4052 return Path.getSingleStringRef() != "";
4053 }
4054 if (llvm::sys::path::cache_directory(Result)) {
4055 llvm::sys::path::append(Result, "clang");
4056 llvm::sys::path::append(Result, "ModuleCache");
4057 return true;
4058 }
4059 return false;
4060}
4061
4064 const char *BaseInput) {
4065 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4066 return StringRef(ModuleOutputEQ->getValue());
4067
4068 SmallString<256> OutputPath;
4069 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4070 FinalOutput && Args.hasArg(options::OPT_c))
4071 OutputPath = FinalOutput->getValue();
4072 else {
4073 llvm::sys::fs::current_path(OutputPath);
4074 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4075 }
4076
4077 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4078 llvm::sys::path::replace_extension(OutputPath, Extension);
4079 return OutputPath;
4080}
4081
4083 const ArgList &Args, const InputInfo &Input,
4084 const InputInfo &Output, bool HaveStd20,
4085 ArgStringList &CmdArgs) {
4086 const bool IsCXX = types::isCXX(Input.getType());
4087 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4088 bool HaveModules = HaveStdCXXModules;
4089
4090 // -fmodules enables the use of precompiled modules (off by default).
4091 // Users can pass -fno-cxx-modules to turn off modules support for
4092 // C++/Objective-C++ programs.
4093 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4094 options::OPT_fno_cxx_modules, true);
4095 bool HaveClangModules = false;
4096 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4097 if (AllowedInCXX || !IsCXX) {
4098 CmdArgs.push_back("-fmodules");
4099 HaveClangModules = true;
4100 }
4101 }
4102
4103 HaveModules |= HaveClangModules;
4104
4105 if (HaveModules && !AllowedInCXX)
4106 CmdArgs.push_back("-fno-cxx-modules");
4107
4108 // -fmodule-maps enables implicit reading of module map files. By default,
4109 // this is enabled if we are using Clang's flavor of precompiled modules.
4110 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4111 options::OPT_fno_implicit_module_maps, HaveClangModules))
4112 CmdArgs.push_back("-fimplicit-module-maps");
4113
4114 // -fmodules-decluse checks that modules used are declared so (off by default)
4115 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4116 options::OPT_fno_modules_decluse);
4117
4118 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4119 // all #included headers are part of modules.
4120 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4121 options::OPT_fno_modules_strict_decluse, false))
4122 CmdArgs.push_back("-fmodules-strict-decluse");
4123
4124 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4125 options::OPT_fno_modulemap_allow_subdirectory_search);
4126
4127 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4128 bool ImplicitModules = false;
4129 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4130 options::OPT_fno_implicit_modules, HaveClangModules)) {
4131 if (HaveModules)
4132 CmdArgs.push_back("-fno-implicit-modules");
4133 } else if (HaveModules) {
4134 ImplicitModules = true;
4135 // -fmodule-cache-path specifies where our implicitly-built module files
4136 // should be written.
4137 SmallString<128> Path;
4138 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4139 Path = A->getValue();
4140
4141 bool HasPath = true;
4142 if (C.isForDiagnostics()) {
4143 // When generating crash reports, we want to emit the modules along with
4144 // the reproduction sources, so we ignore any provided module path.
4145 Path = Output.getFilename();
4146 llvm::sys::path::replace_extension(Path, ".cache");
4147 llvm::sys::path::append(Path, "modules");
4148 } else if (Path.empty()) {
4149 // No module path was provided: use the default.
4150 HasPath = Driver::getDefaultModuleCachePath(Path);
4151 }
4152
4153 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4154 // That being said, that failure is unlikely and not caching is harmless.
4155 if (HasPath) {
4156 const char Arg[] = "-fmodules-cache-path=";
4157 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4158 CmdArgs.push_back(Args.MakeArgString(Path));
4159 }
4160
4161 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4162 }
4163
4164 if (HaveModules) {
4165 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4166 options::OPT_fno_prebuilt_implicit_modules, false))
4167 CmdArgs.push_back("-fprebuilt-implicit-modules");
4168 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4169 options::OPT_fno_modules_validate_input_files_content,
4170 false))
4171 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4172 }
4173
4174 // -fmodule-name specifies the module that is currently being built (or
4175 // used for header checking by -fmodule-maps).
4176 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4177
4178 // -fmodule-map-file can be used to specify files containing module
4179 // definitions.
4180 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4181
4182 // -fbuiltin-module-map can be used to load the clang
4183 // builtin headers modulemap file.
4184 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4185 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4186 llvm::sys::path::append(BuiltinModuleMap, "include");
4187 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4188 if (llvm::sys::fs::exists(BuiltinModuleMap))
4189 CmdArgs.push_back(
4190 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4191 }
4192
4193 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4194 // names to precompiled module files (the module is loaded only if used).
4195 // The -fmodule-file=<file> form can be used to unconditionally load
4196 // precompiled module files (whether used or not).
4197 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4198 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4199
4200 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4201 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4202 CmdArgs.push_back(Args.MakeArgString(
4203 std::string("-fprebuilt-module-path=") + A->getValue()));
4204 A->claim();
4205 }
4206 } else
4207 Args.ClaimAllArgs(options::OPT_fmodule_file);
4208
4209 // When building modules and generating crashdumps, we need to dump a module
4210 // dependency VFS alongside the output.
4211 if (HaveClangModules && C.isForDiagnostics()) {
4212 SmallString<128> VFSDir(Output.getFilename());
4213 llvm::sys::path::replace_extension(VFSDir, ".cache");
4214 // Add the cache directory as a temp so the crash diagnostics pick it up.
4215 C.addTempFile(Args.MakeArgString(VFSDir));
4216
4217 llvm::sys::path::append(VFSDir, "vfs");
4218 CmdArgs.push_back("-module-dependency-dir");
4219 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4220 }
4221
4222 if (HaveClangModules)
4223 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4224
4225 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4226 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_search_path);
4227 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4228 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4229
4230 if (HaveClangModules) {
4231 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4232
4233 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4234 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4235 D.Diag(diag::err_drv_argument_not_allowed_with)
4236 << A->getAsString(Args) << "-fbuild-session-timestamp";
4237
4238 llvm::sys::fs::file_status Status;
4239 if (llvm::sys::fs::status(A->getValue(), Status))
4240 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4241 CmdArgs.push_back(Args.MakeArgString(
4242 "-fbuild-session-timestamp=" +
4243 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4244 Status.getLastModificationTime().time_since_epoch())
4245 .count())));
4246 }
4247
4248 if (Args.getLastArg(
4249 options::OPT_fmodules_validate_once_per_build_session)) {
4250 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4251 options::OPT_fbuild_session_file))
4252 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4253
4254 Args.AddLastArg(CmdArgs,
4255 options::OPT_fmodules_validate_once_per_build_session);
4256 }
4257
4258 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4259 options::OPT_fno_modules_validate_system_headers,
4260 ImplicitModules))
4261 CmdArgs.push_back("-fmodules-validate-system-headers");
4262
4263 if (Args.hasFlag(options::OPT_fmodules_validate_directory_dependencies,
4264 options::OPT_fno_modules_validate_directory_dependencies,
4265 false))
4266 CmdArgs.push_back("-fmodules-validate-directory-dependencies");
4267
4268 Args.AddLastArg(CmdArgs,
4269 options::OPT_fmodules_disable_diagnostic_validation);
4270 } else {
4271 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4272 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4273 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4274 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4275 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4276 Args.ClaimAllArgs(options::OPT_fmodules_validate_directory_dependencies);
4277 Args.ClaimAllArgs(options::OPT_fno_modules_validate_directory_dependencies);
4278 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4279 }
4280
4281 // FIXME: We provisionally don't check ODR violations for decls in the global
4282 // module fragment.
4283 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4284
4285 if (Input.getType() == driver::types::TY_CXXModule ||
4286 Input.getType() == driver::types::TY_PP_CXXModule) {
4287 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4288 CmdArgs.push_back("-fmodules-reduced-bmi");
4289
4290 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4291 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4292 else if (!(Args.hasArg(options::OPT__precompile) ||
4293 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4294 Args.hasArg(options::OPT_fmodule_output))
4295 // If --precompile is specified, we will always generate a module file if
4296 // we're compiling an importable module unit. This is fine even if the
4297 // compilation process won't reach the point of generating the module file
4298 // (e.g., in the preprocessing mode), since the attached flag
4299 // '-fmodule-output' is useless.
4300 //
4301 // But if '--precompile' is specified, it might be annoying to always
4302 // generate the module file as '--precompile' will generate the module
4303 // file anyway.
4304 CmdArgs.push_back(Args.MakeArgString(
4305 "-fmodule-output=" +
4307 }
4308
4309 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4310 Args.hasArg(options::OPT__precompile) &&
4311 (!Args.hasArg(options::OPT_o) ||
4312 Args.getLastArg(options::OPT_o)->getValue() ==
4314 D.Diag(diag::err_drv_reduced_module_output_overrided);
4315 }
4316
4317 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4318 // other translation units than module units. This is more user friendly to
4319 // allow end uers to enable this feature without asking for help from build
4320 // systems.
4321 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4322 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4323
4324 // We need to include the case the input file is a module file here.
4325 // Since the default compilation model for C++ module interface unit will
4326 // create temporary module file and compile the temporary module file
4327 // to get the object file. Then the `-fmodule-output` flag will be
4328 // brought to the second compilation process. So we have to claim it for
4329 // the case too.
4330 if (Input.getType() == driver::types::TY_CXXModule ||
4331 Input.getType() == driver::types::TY_PP_CXXModule ||
4332 Input.getType() == driver::types::TY_ModuleFile) {
4333 Args.ClaimAllArgs(options::OPT_fmodule_output);
4334 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4335 }
4336
4337 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4338 CmdArgs.push_back("-fmodules-embed-all-files");
4339
4340 return HaveModules;
4341}
4342
4343static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4344 ArgStringList &CmdArgs) {
4345 // -fsigned-char is default.
4346 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4347 options::OPT_fno_signed_char,
4348 options::OPT_funsigned_char,
4349 options::OPT_fno_unsigned_char)) {
4350 if (A->getOption().matches(options::OPT_funsigned_char) ||
4351 A->getOption().matches(options::OPT_fno_signed_char)) {
4352 CmdArgs.push_back("-fno-signed-char");
4353 }
4354 } else if (!isSignedCharDefault(T)) {
4355 CmdArgs.push_back("-fno-signed-char");
4356 }
4357
4358 // The default depends on the language standard.
4359 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4360
4361 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4362 options::OPT_fno_short_wchar)) {
4363 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4364 CmdArgs.push_back("-fwchar-type=short");
4365 CmdArgs.push_back("-fno-signed-wchar");
4366 } else {
4367 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4368 CmdArgs.push_back("-fwchar-type=int");
4369 if (T.isOSzOS() ||
4370 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4371 CmdArgs.push_back("-fno-signed-wchar");
4372 else
4373 CmdArgs.push_back("-fsigned-wchar");
4374 }
4375 } else if (T.isOSzOS())
4376 CmdArgs.push_back("-fno-signed-wchar");
4377}
4378
4379static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4380 const llvm::Triple &T, const ArgList &Args,
4381 ObjCRuntime &Runtime, bool InferCovariantReturns,
4382 const InputInfo &Input, ArgStringList &CmdArgs) {
4383 const llvm::Triple::ArchType Arch = TC.getArch();
4384
4385 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4386 // is the default. Except for deployment target of 10.5, next runtime is
4387 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4388 if (Runtime.isNonFragile()) {
4389 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4390 options::OPT_fno_objc_legacy_dispatch,
4392 if (TC.UseObjCMixedDispatch())
4393 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4394 else
4395 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4396 }
4397 }
4398
4399 // Forward -fobjc-direct-precondition-thunk to cc1
4400 // Defaults to false and needs explict turn on for now
4401 // TODO: switch to default true and needs explict turn off in the future.
4402 // TODO: add support for other runtimes
4403 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4404 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4405 if (Runtime.isNeXTFamily()) {
4406 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4407 } else {
4408 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4409 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4410 }
4411 }
4412
4413 if (types::isObjC(Input.getType())) {
4414 // Pass down -fobjc-msgsend-selector-stubs if present.
4415 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4416 options::OPT_fno_objc_msgsend_selector_stubs, false))
4417 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4418
4419 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4420 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4421 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4422 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4423 }
4424
4425 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4426 // to do Array/Dictionary subscripting by default.
4427 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4428 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4429 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4430
4431 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4432 // NOTE: This logic is duplicated in ToolChains.cpp.
4433 if (isObjCAutoRefCount(Args)) {
4434 TC.CheckObjCARC();
4435
4436 CmdArgs.push_back("-fobjc-arc");
4437
4438 // FIXME: It seems like this entire block, and several around it should be
4439 // wrapped in isObjC, but for now we just use it here as this is where it
4440 // was being used previously.
4441 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4443 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4444 else
4445 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4446 }
4447
4448 // Allow the user to enable full exceptions code emission.
4449 // We default off for Objective-C, on for Objective-C++.
4450 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4451 options::OPT_fno_objc_arc_exceptions,
4452 /*Default=*/types::isCXX(Input.getType())))
4453 CmdArgs.push_back("-fobjc-arc-exceptions");
4454 }
4455
4456 // Silence warning for full exception code emission options when explicitly
4457 // set to use no ARC.
4458 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4459 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4460 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4461 }
4462
4463 // Allow the user to control whether messages can be converted to runtime
4464 // functions.
4465 if (types::isObjC(Input.getType())) {
4466 auto *Arg = Args.getLastArg(
4467 options::OPT_fobjc_convert_messages_to_runtime_calls,
4468 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4469 if (Arg &&
4470 Arg->getOption().matches(
4471 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4472 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4473 }
4474
4475 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4476 // rewriter.
4477 if (InferCovariantReturns)
4478 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4479
4480 // Pass down -fobjc-weak or -fno-objc-weak if present.
4481 if (types::isObjC(Input.getType())) {
4482 auto WeakArg =
4483 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4484 if (!WeakArg) {
4485 // nothing to do
4486 } else if (!Runtime.allowsWeak()) {
4487 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4488 D.Diag(diag::err_objc_weak_unsupported);
4489 } else {
4490 WeakArg->render(Args, CmdArgs);
4491 }
4492 }
4493
4494 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4495 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4496
4497 // Forward constant literal flags to cc1.
4498 if (types::isObjC(Input.getType())) {
4499 bool EnableConstantLiterals =
4500 Args.hasFlag(options::OPT_fobjc_constant_literals,
4501 options::OPT_fno_objc_constant_literals,
4502 /*default=*/true) &&
4503 Runtime.hasConstantLiteralClasses();
4504 if (EnableConstantLiterals)
4505 CmdArgs.push_back("-fobjc-constant-literals");
4506 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4507 options::OPT_fno_constant_nsnumber_literals,
4508 /*default=*/true) &&
4509 EnableConstantLiterals)
4510 CmdArgs.push_back("-fconstant-nsnumber-literals");
4511 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4512 options::OPT_fno_constant_nsarray_literals,
4513 /*default=*/true) &&
4514 EnableConstantLiterals)
4515 CmdArgs.push_back("-fconstant-nsarray-literals");
4516 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4517 options::OPT_fno_constant_nsdictionary_literals,
4518 /*default=*/true) &&
4519 EnableConstantLiterals)
4520 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4521 }
4522}
4523
4524static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4525 ArgStringList &CmdArgs) {
4526 bool CaretDefault = true;
4527 bool ColumnDefault = true;
4528
4529 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4530 options::OPT__SLASH_diagnostics_column,
4531 options::OPT__SLASH_diagnostics_caret)) {
4532 switch (A->getOption().getID()) {
4533 case options::OPT__SLASH_diagnostics_caret:
4534 CaretDefault = true;
4535 ColumnDefault = true;
4536 break;
4537 case options::OPT__SLASH_diagnostics_column:
4538 CaretDefault = false;
4539 ColumnDefault = true;
4540 break;
4541 case options::OPT__SLASH_diagnostics_classic:
4542 CaretDefault = false;
4543 ColumnDefault = false;
4544 break;
4545 }
4546 }
4547
4548 // -fcaret-diagnostics is default.
4549 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4550 options::OPT_fno_caret_diagnostics, CaretDefault))
4551 CmdArgs.push_back("-fno-caret-diagnostics");
4552
4553 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4554 options::OPT_fno_diagnostics_fixit_info);
4555 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4556 options::OPT_fno_diagnostics_show_option);
4557
4558 if (const Arg *A =
4559 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4560 CmdArgs.push_back("-fdiagnostics-show-category");
4561 CmdArgs.push_back(A->getValue());
4562 }
4563
4564 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4565 options::OPT_fno_diagnostics_show_hotness);
4566
4567 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_safety_c,
4568 options::OPT_fno_lifetime_safety_c);
4569
4570 if (const Arg *A =
4571 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4572 std::string Opt =
4573 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4574 CmdArgs.push_back(Args.MakeArgString(Opt));
4575 }
4576
4577 if (const Arg *A =
4578 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4579 std::string Opt =
4580 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4581 CmdArgs.push_back(Args.MakeArgString(Opt));
4582 }
4583
4584 if (const Arg *A =
4585 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4586 options::OPT_fno_diagnostics_show_inlining_chain)) {
4587 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4588 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4589 else
4590 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4591 }
4592
4593 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4594 CmdArgs.push_back("-fdiagnostics-format");
4595 CmdArgs.push_back(A->getValue());
4596 if (StringRef(A->getValue()) == "sarif" ||
4597 StringRef(A->getValue()) == "SARIF")
4598 D.Diag(diag::warn_drv_sarif_format_unstable);
4599 }
4600
4601 if (const Arg *A = Args.getLastArg(
4602 options::OPT_fdiagnostics_show_note_include_stack,
4603 options::OPT_fno_diagnostics_show_note_include_stack)) {
4604 const Option &O = A->getOption();
4605 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4606 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4607 else
4608 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4609 }
4610
4611 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4612
4613 if (Args.hasArg(options::OPT_fansi_escape_codes))
4614 CmdArgs.push_back("-fansi-escape-codes");
4615
4616 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4617 options::OPT_fno_show_source_location);
4618
4619 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4620 options::OPT_fno_diagnostics_show_line_numbers);
4621
4622 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4623 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4624
4625 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4626 ColumnDefault))
4627 CmdArgs.push_back("-fno-show-column");
4628
4629 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4630 options::OPT_fno_spell_checking);
4631
4632 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4633}
4634
4635static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4636 const ArgList &Args, ArgStringList &CmdArgs,
4637 unsigned DwarfVersion) {
4638 auto *DwarfFormatArg =
4639 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4640 if (!DwarfFormatArg)
4641 return;
4642
4643 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4644 if (DwarfVersion < 3)
4645 D.Diag(diag::err_drv_argument_only_allowed_with)
4646 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4647 else if (!T.isArch64Bit())
4648 D.Diag(diag::err_drv_argument_only_allowed_with)
4649 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4650 else if (!T.isOSBinFormatELF())
4651 D.Diag(diag::err_drv_argument_only_allowed_with)
4652 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4653 }
4654
4655 DwarfFormatArg->render(Args, CmdArgs);
4656}
4657
4658static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4659 const ArgList &Args) {
4660 bool NeedsSimpleTemplateNames =
4661 Args.hasFlag(options::OPT_gsimple_template_names,
4662 options::OPT_gno_simple_template_names,
4664 if (!NeedsSimpleTemplateNames)
4665 return false;
4666
4667 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4668 if (!checkDebugInfoOption(A, Args, D, TC))
4669 return false;
4670
4671 return true;
4672}
4673
4674static void
4675renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4676 const ArgList &Args, types::ID InputType,
4677 ArgStringList &CmdArgs, const InputInfo &Output,
4678 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4679 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4680 bool IRInput = isLLVMIR(InputType);
4681 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4682 !isHIP(InputType) && !isObjC(InputType) &&
4683 !isOpenCL(InputType);
4684
4685 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4686
4687 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4688 options::OPT_fno_debug_record_sysroot, true))
4689 CmdArgs.push_back("-fno-debug-record-sysroot");
4690
4691 // The 'g' groups options involve a somewhat intricate sequence of decisions
4692 // about what to pass from the driver to the frontend, but by the time they
4693 // reach cc1 they've been factored into three well-defined orthogonal choices:
4694 // * what level of debug info to generate
4695 // * what dwarf version to write
4696 // * what debugger tuning to use
4697 // This avoids having to monkey around further in cc1 other than to disable
4698 // codeview if not running in a Windows environment. Perhaps even that
4699 // decision should be made in the driver as well though.
4700 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4701
4702 bool SplitDWARFInlining =
4703 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4704 options::OPT_fno_split_dwarf_inlining, false);
4705
4706 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4707 // object file generation and no IR generation, -gN should not be needed. So
4708 // allow -gsplit-dwarf with either -gN or IR input.
4709 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4710 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4711 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4712 D.Diag(diag::err_drv_unsupported_opt_for_target)
4713 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4714 << TC.getTripleString();
4715 return;
4716 }
4717 Arg *SplitDWARFArg;
4718 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4719 if (DwarfFission != DwarfFissionKind::None &&
4720 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4721 DwarfFission = DwarfFissionKind::None;
4722 SplitDWARFInlining = false;
4723 }
4724 }
4725 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4726 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4727
4728 // If the last option explicitly specified a debug-info level, use it.
4729 if (checkDebugInfoOption(A, Args, D, TC) &&
4730 A->getOption().matches(options::OPT_gN_Group)) {
4731 DebugInfoKind = debugLevelToInfoKind(*A);
4732 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4733 // complicated if you've disabled inline info in the skeleton CUs
4734 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4735 // line-tables-only, so let those compose naturally in that case.
4736 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4737 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4738 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4739 SplitDWARFInlining))
4740 DwarfFission = DwarfFissionKind::None;
4741 }
4742 }
4743
4744 // If a debugger tuning argument appeared, remember it.
4745 bool HasDebuggerTuning = false;
4746 if (const Arg *A =
4747 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4748 HasDebuggerTuning = true;
4749 if (checkDebugInfoOption(A, Args, D, TC)) {
4750 if (A->getOption().matches(options::OPT_glldb))
4751 DebuggerTuning = llvm::DebuggerKind::LLDB;
4752 else if (A->getOption().matches(options::OPT_gsce))
4753 DebuggerTuning = llvm::DebuggerKind::SCE;
4754 else if (A->getOption().matches(options::OPT_gdbx))
4755 DebuggerTuning = llvm::DebuggerKind::DBX;
4756 else
4757 DebuggerTuning = llvm::DebuggerKind::GDB;
4758 }
4759 }
4760
4761 // If a -gdwarf argument appeared, remember it.
4762 bool EmitDwarf = false;
4763 if (const Arg *A = getDwarfNArg(Args))
4764 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4765
4766 bool EmitCodeView = false;
4767 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4768 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4769
4770 // If the user asked for debug info but did not explicitly specify -gcodeview
4771 // or -gdwarf, ask the toolchain for the default format.
4772 if (!EmitCodeView && !EmitDwarf &&
4773 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4774 switch (TC.getDefaultDebugFormat()) {
4775 case llvm::codegenoptions::DIF_CodeView:
4776 EmitCodeView = true;
4777 break;
4778 case llvm::codegenoptions::DIF_DWARF:
4779 EmitDwarf = true;
4780 break;
4781 }
4782 }
4783
4784 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4785 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4786 // be lower than what the user wanted.
4787 if (EmitDwarf) {
4788 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4789 // Clamp effective DWARF version to the max supported by the toolchain.
4790 EffectiveDWARFVersion =
4791 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4792 } else {
4793 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4794 }
4795
4796 // -gline-directives-only supported only for the DWARF debug info.
4797 if (RequestedDWARFVersion == 0 &&
4798 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4799 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4800
4801 // strict DWARF is set to false by default. But for DBX, we need it to be set
4802 // as true by default.
4803 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4804 (void)checkDebugInfoOption(A, Args, D, TC);
4805 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4806 DebuggerTuning == llvm::DebuggerKind::DBX))
4807 CmdArgs.push_back("-gstrict-dwarf");
4808
4809 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4810 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4811
4812 // Column info is included by default for everything except SCE and
4813 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4814 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4815 // practice, however, the Microsoft debuggers don't handle missing end columns
4816 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4817 // it's better not to include any column info.
4818 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4819 (void)checkDebugInfoOption(A, Args, D, TC);
4820 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4821 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4822 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4823 DebuggerTuning != llvm::DebuggerKind::DBX)))
4824 CmdArgs.push_back("-gno-column-info");
4825
4826 if (!Args.hasFlag(options::OPT_gcall_site_info,
4827 options::OPT_gno_call_site_info, true))
4828 CmdArgs.push_back("-gno-call-site-info");
4829
4830 // FIXME: Move backend command line options to the module.
4831 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4832 // If -gline-tables-only or -gline-directives-only is the last option it
4833 // wins.
4834 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4835 TC)) {
4836 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4837 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4838 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4839 CmdArgs.push_back("-dwarf-ext-refs");
4840 CmdArgs.push_back("-fmodule-format=obj");
4841 }
4842 }
4843 }
4844
4845 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4846 CmdArgs.push_back("-fsplit-dwarf-inlining");
4847
4848 // After we've dealt with all combinations of things that could
4849 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4850 // figure out if we need to "upgrade" it to standalone debug info.
4851 // We parse these two '-f' options whether or not they will be used,
4852 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4853 bool NeedFullDebug = Args.hasFlag(
4854 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4855 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4857 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4858 (void)checkDebugInfoOption(A, Args, D, TC);
4859
4860 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4861 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4862 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4863 options::OPT_feliminate_unused_debug_types, false))
4864 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4865 else if (NeedFullDebug)
4866 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4867 }
4868
4869 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4870 false)) {
4871 // Source embedding is a vendor extension to DWARF v5. By now we have
4872 // checked if a DWARF version was stated explicitly, and have otherwise
4873 // fallen back to the target default, so if this is still not at least 5
4874 // we emit an error.
4875 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4876 if (RequestedDWARFVersion < 5)
4877 D.Diag(diag::err_drv_argument_only_allowed_with)
4878 << A->getAsString(Args) << "-gdwarf-5";
4879 else if (EffectiveDWARFVersion < 5)
4880 // The toolchain has reduced allowed dwarf version, so we can't enable
4881 // -gembed-source.
4882 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4883 << A->getAsString(Args) << TC.getTripleString() << 5
4884 << EffectiveDWARFVersion;
4885 else if (checkDebugInfoOption(A, Args, D, TC))
4886 CmdArgs.push_back("-gembed-source");
4887 }
4888
4889 // Enable Key Instructions by default if we're emitting DWARF, the language is
4890 // plain C or C++, and optimisations are enabled.
4891 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4892 bool KeyInstructionsOnByDefault =
4893 EmitDwarf && PlainCOrCXX && OptLevel &&
4894 !OptLevel->getOption().matches(options::OPT_O0);
4895 if (Args.hasFlag(options::OPT_gkey_instructions,
4896 options::OPT_gno_key_instructions,
4897 KeyInstructionsOnByDefault))
4898 CmdArgs.push_back("-gkey-instructions");
4899
4900 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4901 options::OPT_gno_structor_decl_linkage_names, true))
4902 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4903
4904 if (Args.hasFlag(options::OPT_fdynamic_debugging,
4905 options::OPT_fno_dynamic_debugging, false)) {
4906 // As this is an experimental feature we can afford to be strict about
4907 // supported configurations.
4908 // NOTE on adding target support, consider adding "tail-pad-to-size"
4909 // support in `llvm::prepareForDynamicDebugging`.
4910 if (!TC.getTriple().isX86())
4911 D.Diag(diag::err_drv_unsupported_opt_for_target)
4912 << Args.getLastArg(options::OPT_fdynamic_debugging)->getAsString(Args)
4913 << T.getTriple();
4914 if (IsUsingLTO)
4915 D.Diag(diag::err_drv_dyndbg_lto);
4916 if (DwarfFission != DwarfFissionKind::None)
4917 D.Diag(diag::err_drv_dyndbg_incompatible)
4918 << Args.getLastArg(options::OPT_gsplit_dwarf)->getAsString(Args);
4919 // There's no fundamental reason why IR input should be incompatible, but
4920 // it would add some complexity, and reducing the test matrix is valuable.
4921 if (IRInput)
4922 D.Diag(diag::err_drv_dyndbg_ir);
4923
4924 // Disable composition with sanitizers for now.
4925 if (auto *San = Args.getLastArg(options::OPT_fsanitize_EQ))
4926 D.Diag(diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4927
4928 if (!EmitDwarf)
4929 D.Diag(diag::warn_drv_dyndbg_req_debug);
4930 else
4931 CmdArgs.push_back("-fdynamic-debugging");
4932 }
4933
4934 if (EmitCodeView) {
4935 CmdArgs.push_back("-gcodeview");
4936
4937 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4938 options::OPT_gno_codeview_ghash);
4939
4940 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4941 options::OPT_gno_codeview_command_line);
4942 }
4943
4944 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4945 options::OPT_gno_inline_line_tables);
4946
4947 // When emitting remarks, we need at least debug lines in the output.
4948 if (willEmitRemarks(Args) &&
4949 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4950 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4951
4952 // Adjust the debug info kind for the given toolchain.
4953 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4954
4955 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4956 // set.
4957 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4958 T.isOSAIX() && !HasDebuggerTuning
4959 ? llvm::DebuggerKind::Default
4960 : DebuggerTuning);
4961
4962 // -fdebug-macro turns on macro debug info generation.
4963 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4964 false))
4965 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4966 D, TC))
4967 CmdArgs.push_back("-debug-info-macro");
4968
4969 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4970 const auto *PubnamesArg =
4971 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4972 options::OPT_gpubnames, options::OPT_gno_pubnames);
4973 if (DwarfFission != DwarfFissionKind::None ||
4974 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4975 const bool OptionSet =
4976 (PubnamesArg &&
4977 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4978 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4979 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4980 (!PubnamesArg ||
4981 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4982 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4983 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4984 options::OPT_gpubnames)
4985 ? "-gpubnames"
4986 : "-ggnu-pubnames");
4987 }
4988
4989 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4990 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4991 ForwardTemplateParams = true;
4992 CmdArgs.push_back("-gsimple-template-names=simple");
4993 }
4994
4995 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4996 bool UseDebugTemplateAlias =
4997 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4998 if (const auto *DebugTemplateAlias = Args.getLastArg(
4999 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
5000 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
5001 // asks for it we should let them have it (if the target supports it).
5002 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
5003 const auto &Opt = DebugTemplateAlias->getOption();
5004 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
5005 }
5006 }
5007 if (UseDebugTemplateAlias)
5008 CmdArgs.push_back("-gtemplate-alias");
5009
5010 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
5011 StringRef v = A->getValue();
5012 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
5013 }
5014
5015 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
5016 options::OPT_fno_debug_ranges_base_address);
5017
5018 // -gdwarf-aranges turns on the emission of the aranges section in the
5019 // backend.
5020 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
5021 A && checkDebugInfoOption(A, Args, D, TC)) {
5022 CmdArgs.push_back("-mllvm");
5023 CmdArgs.push_back("-generate-arange-section");
5024 }
5025
5026 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
5027 options::OPT_fno_force_dwarf_frame);
5028
5029 bool EnableTypeUnits = false;
5030 if (Args.hasFlag(options::OPT_fdebug_types_section,
5031 options::OPT_fno_debug_types_section, false)) {
5032 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5033 D.Diag(diag::err_drv_unsupported_opt_for_target)
5034 << Args.getLastArg(options::OPT_fdebug_types_section)
5035 ->getAsString(Args)
5036 << T.getTriple();
5037 } else if (checkDebugInfoOption(
5038 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
5039 TC)) {
5040 EnableTypeUnits = true;
5041 CmdArgs.push_back("-mllvm");
5042 CmdArgs.push_back("-generate-type-units");
5043 }
5044 }
5045
5046 if (const Arg *A =
5047 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
5048 options::OPT_gno_omit_unreferenced_methods))
5049 (void)checkDebugInfoOption(A, Args, D, TC);
5050 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
5051 options::OPT_gno_omit_unreferenced_methods, false) &&
5052 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5053 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5054 !EnableTypeUnits) {
5055 CmdArgs.push_back("-gomit-unreferenced-methods");
5056 }
5057
5058 // To avoid join/split of directory+filename, the integrated assembler prefers
5059 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5060 // form before DWARF v5.
5061 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
5062 options::OPT_fno_dwarf_directory_asm,
5063 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5064 CmdArgs.push_back("-fno-dwarf-directory-asm");
5065
5066 // Decide how to render forward declarations of template instantiations.
5067 // SCE wants full descriptions, others just get them in the name.
5068 if (ForwardTemplateParams)
5069 CmdArgs.push_back("-debug-forward-template-params");
5070
5071 // Do we need to explicitly import anonymous namespaces into the parent
5072 // scope?
5073 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5074 CmdArgs.push_back("-dwarf-explicit-import");
5075
5076 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
5077 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5078
5079 // This controls whether or not we perform JustMyCode instrumentation.
5080 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5081 if (TC.getTriple().isOSBinFormatELF() ||
5082 TC.getTriple().isWindowsMSVCEnvironment()) {
5083 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5084 CmdArgs.push_back("-fjmc");
5085 else if (D.IsCLMode())
5086 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5087 << "'/Zi', '/Z7'";
5088 else
5089 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5090 << "-g";
5091 } else {
5092 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5093 }
5094 }
5095
5096 // Add in -fdebug-compilation-dir if necessary.
5097 const char *DebugCompilationDir =
5098 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5099
5100 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5101
5102 // Add the output path to the object file for CodeView debug infos.
5103 if (EmitCodeView && Output.isFilename())
5104 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5105 Output.getFilename());
5106}
5107
5108static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5109 ArgStringList &CmdArgs) {
5110 unsigned RTOptionID = options::OPT__SLASH_MT;
5111
5112 if (Args.hasArg(options::OPT__SLASH_LDd))
5113 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5114 // but defining _DEBUG is sticky.
5115 RTOptionID = options::OPT__SLASH_MTd;
5116
5117 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5118 RTOptionID = A->getOption().getID();
5119
5120 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5121 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5122 .Case("static", options::OPT__SLASH_MT)
5123 .Case("static_dbg", options::OPT__SLASH_MTd)
5124 .Case("dll", options::OPT__SLASH_MD)
5125 .Case("dll_dbg", options::OPT__SLASH_MDd)
5126 .Default(options::OPT__SLASH_MT);
5127 }
5128
5129 StringRef FlagForCRT;
5130 switch (RTOptionID) {
5131 case options::OPT__SLASH_MD:
5132 if (Args.hasArg(options::OPT__SLASH_LDd))
5133 CmdArgs.push_back("-D_DEBUG");
5134 CmdArgs.push_back("-D_MT");
5135 CmdArgs.push_back("-D_DLL");
5136 FlagForCRT = "--dependent-lib=msvcrt";
5137 break;
5138 case options::OPT__SLASH_MDd:
5139 CmdArgs.push_back("-D_DEBUG");
5140 CmdArgs.push_back("-D_MT");
5141 CmdArgs.push_back("-D_DLL");
5142 FlagForCRT = "--dependent-lib=msvcrtd";
5143 break;
5144 case options::OPT__SLASH_MT:
5145 if (Args.hasArg(options::OPT__SLASH_LDd))
5146 CmdArgs.push_back("-D_DEBUG");
5147 CmdArgs.push_back("-D_MT");
5148 CmdArgs.push_back("-flto-visibility-public-std");
5149 FlagForCRT = "--dependent-lib=libcmt";
5150 break;
5151 case options::OPT__SLASH_MTd:
5152 CmdArgs.push_back("-D_DEBUG");
5153 CmdArgs.push_back("-D_MT");
5154 CmdArgs.push_back("-flto-visibility-public-std");
5155 FlagForCRT = "--dependent-lib=libcmtd";
5156 break;
5157 default:
5158 llvm_unreachable("Unexpected option ID.");
5159 }
5160
5161 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5162 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5163 } else {
5164 CmdArgs.push_back(FlagForCRT.data());
5165
5166 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5167 // users want. The /Za flag to cl.exe turns this off, but it's not
5168 // implemented in clang.
5169 CmdArgs.push_back("--dependent-lib=oldnames");
5170 }
5171
5172 // SYCL: Add SYCL runtime library dependency
5173 // SYCL runtime is a required dependency similar to CRT, so we use
5174 // --dependent-lib to embed it in the object file metadata
5175 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5176 !Args.hasArg(options::OPT_nolibsycl) &&
5177 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5178
5179 // Determine debug vs release based on CRT flags
5180 bool IsDebugBuild = false;
5181
5182 // Check -fms-runtime-lib=dll_dbg
5183 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5184 StringRef RuntimeVal = A->getValue();
5185 if (RuntimeVal == "dll_dbg")
5186 IsDebugBuild = true;
5187 }
5188
5189 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5190 // overriding options (e.g., /MDd /MD -> /MD wins)
5191 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5192 if (A->getOption().matches(options::OPT__SLASH_MDd))
5193 IsDebugBuild = true;
5194 }
5195
5196 // Add appropriate SYCL runtime library dependency
5197 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5198 : "--dependent-lib=LLVMSYCL");
5199 }
5200
5201 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5202 // even if the file doesn't actually refer to any of the routines because
5203 // the CRT itself has incomplete dependency markings.
5204 if (TC.getTriple().isWindowsArm64EC())
5205 CmdArgs.push_back("--dependent-lib=softintrin");
5206}
5207
5209 const InputInfo &Output, const InputInfoList &Inputs,
5210 const ArgList &Args, const char *LinkingOutput) const {
5211 const auto &TC = getToolChain();
5212 const llvm::Triple &RawTriple = TC.getTriple();
5213 const llvm::Triple &Triple = TC.getEffectiveTriple();
5214 const std::string &TripleStr = Triple.getTriple();
5215
5216 bool KernelOrKext =
5217 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5218 const Driver &D = TC.getDriver();
5219 ArgStringList CmdArgs;
5220
5221 assert(Inputs.size() >= 1 && "Must have at least one input.");
5222 // CUDA/HIP compilation may have multiple inputs (source file + results of
5223 // device-side compilations). OpenMP device jobs also take the host IR as a
5224 // second input. Module precompilation accepts a list of header files to
5225 // include as part of the module. API extraction accepts a list of header
5226 // files whose API information is emitted in the output. All other jobs are
5227 // expected to have exactly one input. SYCL compilation only expects a
5228 // single input.
5229 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5230 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5231 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5232 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5233 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5234 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5235 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5236 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5237 bool UsesLLVMOffloading = Args.hasFlag(
5238 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
5239 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5241 bool IsHostOffloadingAction =
5244 (JA.isHostOffloading(C.getActiveOffloadKinds()));
5245
5246 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5247 bool IsRDCMode = Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5248 /*Default=*/IsSYCL);
5249
5250 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5251 bool IsUsingLTO = LTOMode != LTOK_None;
5252
5253 // Extract API doesn't have a main input file, so invent a fake one as a
5254 // placeholder.
5255 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5256 "extract-api");
5257
5258 const InputInfo &Input =
5259 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5260
5261 InputInfoList ExtractAPIInputs;
5262 InputInfoList HostOffloadingInputs;
5263 const InputInfo *OpenMPDeviceInput = nullptr;
5264 for (const InputInfo &I : Inputs) {
5265 if (&I == &Input || I.getType() == types::TY_Nothing) {
5266 // This is the primary input or contains nothing.
5267 } else if (IsExtractAPI) {
5268 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5269 if (I.getType() != ExpectedInputType) {
5270 D.Diag(diag::err_drv_extract_api_wrong_kind)
5271 << I.getFilename() << types::getTypeName(I.getType())
5272 << types::getTypeName(ExpectedInputType);
5273 }
5274 ExtractAPIInputs.push_back(I);
5275 } else if (IsHostOffloadingAction) {
5276 HostOffloadingInputs.push_back(I);
5277 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5278 OpenMPDeviceInput = &I;
5279 } else {
5280 llvm_unreachable("unexpectedly given multiple inputs");
5281 }
5282 }
5283
5284 bool IsUEFI = RawTriple.isUEFI();
5285 bool IsIAMCU = RawTriple.isOSIAMCU();
5286
5287 // C++ is not supported for IAMCU.
5288 if (IsIAMCU && types::isCXX(Input.getType()))
5289 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5290
5291 // Invoke ourselves in -cc1 mode.
5292 //
5293 // FIXME: Implement custom jobs for internal actions.
5294 CmdArgs.push_back("-cc1");
5295
5296 // Add the "effective" target triple.
5297 CmdArgs.push_back("-triple");
5298 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5299
5300 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5301
5302 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5303 if (AuxTriple) {
5304 CmdArgs.push_back("-aux-triple");
5305 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5306
5307 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5308 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5309 // Windows), we need to pass Windows-specific flags to cc1.
5310 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5312 // Figure out the device side triple for the host-side compilation.
5313 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5314 ++I) {
5316 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5317 if (OffloadToolChains.first == OffloadToolChains.second)
5318 continue;
5319
5320 const llvm::Triple &DeviceAuxTriple =
5321 OffloadToolChains.first->second->getTriple();
5322 CmdArgs.push_back("-aux-triple");
5323 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5324 break;
5325 }
5326 }
5327
5328 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5329 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5330 Args.ClaimAllArgs(options::OPT_MJ);
5331 } else if (const Arg *GenCDBFragment =
5332 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5333 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5334 TripleStr, Output, Input, Args);
5335 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5336 }
5337
5338 if ((getToolChain().getTriple().isAMDGPU() ||
5339 (getToolChain().getTriple().isSPIRV() &&
5340 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5341 // Device side compilation printf
5342 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5343 CmdArgs.push_back(Args.MakeArgString(
5344 "-mprintf-kind=" +
5345 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5346 // Force compiler error on invalid conversion specifiers
5347 CmdArgs.push_back(
5348 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5349 }
5350 }
5351
5352 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5353 // We need to figure out which CUDA version we're compiling for, as that
5354 // determines how we load and launch GPU kernels.
5355 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5356 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5357 assert(CTC && "Expected valid CUDA Toolchain.");
5358 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5359 CmdArgs.push_back(Args.MakeArgString(
5360 Twine("-target-sdk-version=") +
5361 CudaVersionToString(CTC->CudaInstallation.version())));
5362 }
5363
5364 // Optimization level for CodeGen.
5365 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5366 if (A->getOption().matches(options::OPT_O4)) {
5367 CmdArgs.push_back("-O3");
5368 D.Diag(diag::warn_O4_is_O3);
5369 } else {
5370 A->render(Args, CmdArgs);
5371 }
5372 }
5373
5374 // Unconditionally claim the printf option now to avoid unused diagnostic.
5375 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5376 PF->claim();
5377
5378 if (IsSYCL) {
5379 if (IsSYCLDevice) {
5380 // We want to compile sycl kernels.
5381 CmdArgs.push_back("-fsycl-is-device");
5382
5383 // Set O2 optimization level by default
5384 if (!Args.getLastArg(options::OPT_O_Group))
5385 CmdArgs.push_back("-O2");
5386 } else {
5387 // Add any options that are needed specific to SYCL offload while
5388 // performing the host side compilation.
5389
5390 // Let the front-end host compilation flow know about SYCL offload
5391 // compilation.
5392 CmdArgs.push_back("-fsycl-is-host");
5393 }
5394
5395 // Set options for both host and device.
5396 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5397 if (SYCLStdArg) {
5398 SYCLStdArg->render(Args, CmdArgs);
5399 } else {
5400 // Ensure the default version in SYCL mode is 2020.
5401 CmdArgs.push_back("-sycl-std=2020");
5402 }
5403 }
5404
5405 if (Args.hasFlag(options::OPT_fclangir, options::OPT_fno_clangir, false))
5406 CmdArgs.push_back("-fclangir");
5407
5408 if (IsOpenMPDevice) {
5409 // We have to pass the triple of the host if compiling for an OpenMP device.
5410 const llvm::Triple &HostTriple =
5411 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5412 CmdArgs.push_back("-aux-triple");
5413 CmdArgs.push_back(HostTriple.str().c_str());
5414 }
5415
5416 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5417 Triple.getArch() == llvm::Triple::thumb)) {
5418 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5419 unsigned Version = 0;
5420 bool Failure =
5421 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5422 if (Failure || Version < 7)
5423 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5424 << TripleStr;
5425 }
5426
5427 // Push all default warning arguments that are specific to
5428 // the given target. These come before user provided warning options
5429 // are provided.
5430 TC.addClangWarningOptions(CmdArgs);
5431
5432 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5433 if (Triple.isSPIR() || Triple.isSPIRV())
5434 CmdArgs.push_back("-Wspir-compat");
5435
5436 // Select the appropriate action.
5437 RewriteKind rewriteKind = RK_None;
5438
5439 bool UnifiedLTO = false;
5440 if (IsUsingLTO) {
5441 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5442 options::OPT_fno_unified_lto, Triple.isPS());
5443 if (UnifiedLTO)
5444 CmdArgs.push_back("-funified-lto");
5445 }
5446
5447 if (Args.hasArg(options::OPT_fdefined_pointer_subtraction))
5448 CmdArgs.push_back("-fdefined-pointer-subtraction");
5449
5450 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5451 // it claims when not running an assembler. Otherwise, clang would emit
5452 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5453 // flags while debugging something. That'd be somewhat inconvenient, and it's
5454 // also inconsistent with most other flags -- we don't warn on
5455 // -ffunction-sections not being used in -E mode either for example, even
5456 // though it's not really used either.
5457 if (!isa<AssembleJobAction>(JA)) {
5458 // The args claimed here should match the args used in
5459 // CollectArgsForIntegratedAssembler().
5460 if (TC.useIntegratedAs()) {
5461 Args.ClaimAllArgs(options::OPT_mrelax_all);
5462 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5463 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5464 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5465 switch (C.getDefaultToolChain().getArch()) {
5466 case llvm::Triple::arm:
5467 case llvm::Triple::armeb:
5468 case llvm::Triple::thumb:
5469 case llvm::Triple::thumbeb:
5470 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5471 break;
5472 default:
5473 break;
5474 }
5475 }
5476 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5477 Args.ClaimAllArgs(options::OPT_Xassembler);
5478 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5479 }
5480
5481 bool IsAMDSPIRVForHIPDevice =
5482 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5483 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5484
5485 if (isa<AnalyzeJobAction>(JA)) {
5486 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5487 CmdArgs.push_back("-analyze");
5488 } else if (isa<PreprocessJobAction>(JA)) {
5489 if (Output.getType() == types::TY_Dependencies)
5490 CmdArgs.push_back("-Eonly");
5491 else {
5492 CmdArgs.push_back("-E");
5493 if (Args.hasArg(options::OPT_rewrite_objc) &&
5494 !Args.hasArg(options::OPT_g_Group))
5495 CmdArgs.push_back("-P");
5496 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5497 CmdArgs.push_back("-fdirectives-only");
5498 }
5499 } else if (isa<AssembleJobAction>(JA)) {
5500 CmdArgs.push_back("-emit-obj");
5501
5502 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5503
5504 // Also ignore explicit -force_cpusubtype_ALL option.
5505 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5506 } else if (isa<PrecompileJobAction>(JA)) {
5507 if (JA.getType() == types::TY_Nothing)
5508 CmdArgs.push_back("-fsyntax-only");
5509 else if (JA.getType() == types::TY_ModuleFile) {
5510 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5511 ((Input.getType() == types::TY_CXXStdModule ||
5512 Input.getType() == types::TY_PP_CXXStdModule) &&
5513 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5514 CmdArgs.push_back("-emit-reduced-module-interface");
5515 else
5516 CmdArgs.push_back("-emit-module-interface");
5517 } else if (JA.getType() == types::TY_HeaderUnit)
5518 CmdArgs.push_back("-emit-header-unit");
5519 else if (!Args.hasArg(options::OPT_ignore_pch))
5520 CmdArgs.push_back("-emit-pch");
5521 } else if (isa<VerifyPCHJobAction>(JA)) {
5522 CmdArgs.push_back("-verify-pch");
5523 } else if (isa<ExtractAPIJobAction>(JA)) {
5524 assert(JA.getType() == types::TY_API_INFO &&
5525 "Extract API actions must generate a API information.");
5526 CmdArgs.push_back("-extract-api");
5527
5528 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5529 PrettySGFArg->render(Args, CmdArgs);
5530
5531 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5532
5533 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5534 ProductNameArg->render(Args, CmdArgs);
5535 if (Arg *ExtractAPIIgnoresFileArg =
5536 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5537 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5538 if (Arg *EmitExtensionSymbolGraphs =
5539 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5540 if (!SymbolGraphDirArg)
5541 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5542
5543 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5544 }
5545 if (SymbolGraphDirArg)
5546 SymbolGraphDirArg->render(Args, CmdArgs);
5547 } else {
5548 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5549 "Invalid action for clang tool.");
5550 if (JA.getType() == types::TY_Nothing) {
5551 CmdArgs.push_back("-fsyntax-only");
5552 } else if (JA.getType() == types::TY_LLVM_IR ||
5553 JA.getType() == types::TY_LTO_IR) {
5554 CmdArgs.push_back("-emit-llvm");
5555 } else if (JA.getType() == types::TY_LLVM_BC ||
5556 JA.getType() == types::TY_LTO_BC) {
5557 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5558 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5559 Args.hasArg(options::OPT_emit_llvm)) {
5560 CmdArgs.push_back("-emit-llvm");
5561 } else {
5562 CmdArgs.push_back("-emit-llvm-bc");
5563 }
5564 } else if (JA.getType() == types::TY_IFS ||
5565 JA.getType() == types::TY_IFS_CPP) {
5566 StringRef ArgStr =
5567 Args.hasArg(options::OPT_interface_stub_version_EQ)
5568 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5569 : "ifs-v1";
5570 CmdArgs.push_back("-emit-interface-stubs");
5571 CmdArgs.push_back(
5572 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5573 } else if (JA.getType() == types::TY_PP_Asm) {
5574 CmdArgs.push_back("-S");
5575 } else if (JA.getType() == types::TY_AST) {
5576 if (!Args.hasArg(options::OPT_ignore_pch))
5577 CmdArgs.push_back("-emit-pch");
5578 } else if (JA.getType() == types::TY_ModuleFile) {
5579 CmdArgs.push_back("-module-file-info");
5580 } else if (JA.getType() == types::TY_RewrittenObjC) {
5581 CmdArgs.push_back("-rewrite-objc");
5582 rewriteKind = RK_NonFragile;
5583 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5584 CmdArgs.push_back("-rewrite-objc");
5585 rewriteKind = RK_Fragile;
5586 } else if (JA.getType() == types::TY_CIR) {
5587 CmdArgs.push_back("-emit-cir");
5588 } else if (JA.getType() == types::TY_CIRBC) {
5589 CmdArgs.push_back("-emit-cir-bc");
5590 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5591 CmdArgs.push_back("-emit-obj");
5592 } else {
5593 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5594 }
5595
5596 // Preserve use-list order by default when emitting bitcode, so that
5597 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5598 // same result as running passes here. For LTO, we don't need to preserve
5599 // the use-list order, since serialization to bitcode is part of the flow.
5600 if (JA.getType() == types::TY_LLVM_BC)
5601 CmdArgs.push_back("-emit-llvm-uselists");
5602
5603 if (IsUsingLTO) {
5604 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5605 options::OPT_foffload_lto_EQ);
5606 if (Triple.isNVPTX() && !IsRDCMode &&
5608 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5609 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5610 << "-fno-gpu-rdc";
5611 } else {
5612 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5613 CmdArgs.push_back(Args.MakeArgString(
5614 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5615 // PS4 uses the legacy LTO API, which does not support some of the
5616 // features enabled by -flto-unit.
5617 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5618 CmdArgs.push_back("-flto-unit");
5619 }
5620 }
5621 }
5622
5623 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5624
5625 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5626 if (!types::isLLVMIR(Input.getType()))
5627 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5628 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5629 }
5630
5631 if (Triple.isPPC())
5632 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5633 options::OPT_mno_regnames);
5634
5635 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5636 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5637
5638 if (Args.getLastArg(options::OPT_save_temps_EQ))
5639 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5640
5641 if (Args.getLastArg(options::OPT_save_dynamic_debugging_temps))
5642 Args.AddLastArg(CmdArgs, options::OPT_save_dynamic_debugging_temps);
5643
5644 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5645 options::OPT_fmemory_profile_EQ,
5646 options::OPT_fno_memory_profile);
5647 if (MemProfArg &&
5648 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5649 MemProfArg->render(Args, CmdArgs);
5650
5651 if (auto *MemProfUseArg =
5652 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5653 if (MemProfArg)
5654 D.Diag(diag::err_drv_argument_not_allowed_with)
5655 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5656 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5657 options::OPT_fprofile_generate_EQ))
5658 D.Diag(diag::err_drv_argument_not_allowed_with)
5659 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5660 MemProfUseArg->render(Args, CmdArgs);
5661 }
5662
5663 auto *CopyProfArg =
5664 Args.getLastArg(options::OPT_fcopyprof, options::OPT_fno_copyprof);
5665 if (CopyProfArg &&
5666 !CopyProfArg->getOption().matches(options::OPT_fno_copyprof)) {
5667 CopyProfArg->render(Args, CmdArgs);
5668 Args.AddLastArg(CmdArgs, options::OPT_fcopyprof_static_size_threshold_EQ);
5669 }
5670
5671 // Embed-bitcode option.
5672 // Only white-listed flags below are allowed to be embedded.
5673 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5675 // Add flags implied by -fembed-bitcode.
5676 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5677 // Disable all llvm IR level optimizations.
5678 CmdArgs.push_back("-disable-llvm-passes");
5679
5680 // Render target options.
5681 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5683
5684 // reject options that shouldn't be supported in bitcode
5685 // also reject kernel/kext
5686 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5687 options::OPT_mkernel,
5688 options::OPT_fapple_kext,
5689 options::OPT_ffunction_sections,
5690 options::OPT_fno_function_sections,
5691 options::OPT_fdata_sections,
5692 options::OPT_fno_data_sections,
5693 options::OPT_fbasic_block_sections_EQ,
5694 options::OPT_funique_internal_linkage_names,
5695 options::OPT_fno_unique_internal_linkage_names,
5696 options::OPT_funique_section_names,
5697 options::OPT_fno_unique_section_names,
5698 options::OPT_funique_basic_block_section_names,
5699 options::OPT_fno_unique_basic_block_section_names,
5700 options::OPT_mrestrict_it,
5701 options::OPT_mno_restrict_it,
5702 options::OPT_mstackrealign,
5703 options::OPT_mno_stackrealign,
5704 options::OPT_mstack_alignment,
5705 options::OPT_mcmodel_EQ,
5706 options::OPT_mlong_calls,
5707 options::OPT_mno_long_calls,
5708 options::OPT_ggnu_pubnames,
5709 options::OPT_gdwarf_aranges,
5710 options::OPT_fdebug_types_section,
5711 options::OPT_fno_debug_types_section,
5712 options::OPT_fdwarf_directory_asm,
5713 options::OPT_fno_dwarf_directory_asm,
5714 options::OPT_mrelax_all,
5715 options::OPT_mno_relax_all,
5716 options::OPT_ftrap_function_EQ,
5717 options::OPT_ffixed_r9,
5718 options::OPT_mfix_cortex_a53_835769,
5719 options::OPT_mno_fix_cortex_a53_835769,
5720 options::OPT_ffixed_x18,
5721 options::OPT_mglobal_merge,
5722 options::OPT_mno_global_merge,
5723 options::OPT_mred_zone,
5724 options::OPT_mno_red_zone,
5725 options::OPT_Wa_COMMA,
5726 options::OPT_Xassembler,
5727 options::OPT_mllvm,
5728 options::OPT_mmlir,
5729 };
5730 for (const auto &A : Args)
5731 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5732 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5733
5734 // Render the CodeGen options that need to be passed.
5735 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5736 options::OPT_fno_optimize_sibling_calls);
5737
5739 CmdArgs, JA);
5740
5741 // Render ABI arguments
5742 switch (TC.getArch()) {
5743 default: break;
5744 case llvm::Triple::arm:
5745 case llvm::Triple::armeb:
5746 case llvm::Triple::thumbeb:
5747 RenderARMABI(D, Triple, Args, CmdArgs);
5748 break;
5749 case llvm::Triple::aarch64:
5750 case llvm::Triple::aarch64_32:
5751 case llvm::Triple::aarch64_be:
5752 RenderAArch64ABI(Triple, Args, CmdArgs);
5753 break;
5754 }
5755
5756 // Input/Output file.
5757 if (Output.getType() == types::TY_Dependencies) {
5758 // Handled with other dependency code.
5759 } else if (Output.isFilename()) {
5760 CmdArgs.push_back("-o");
5761 CmdArgs.push_back(Output.getFilename());
5762 } else {
5763 assert(Output.isNothing() && "Input output.");
5764 }
5765
5766 for (const auto &II : Inputs) {
5767 addDashXForInput(Args, II, CmdArgs);
5768 if (II.isFilename())
5769 CmdArgs.push_back(II.getFilename());
5770 else
5771 II.getInputArg().renderAsInput(Args, CmdArgs);
5772 }
5773
5774 C.addCommand(std::make_unique<Command>(
5776 CmdArgs, Inputs, Output, D.getPrependArg()));
5777 return;
5778 }
5779
5780 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5781 CmdArgs.push_back("-fembed-bitcode=marker");
5782
5783 // We normally speed up the clang process a bit by skipping destructors at
5784 // exit, but when we're generating diagnostics we can rely on some of the
5785 // cleanup.
5786 if (!C.isForDiagnostics())
5787 CmdArgs.push_back("-disable-free");
5788 CmdArgs.push_back("-clear-ast-before-backend");
5789
5790#ifdef NDEBUG
5791 const bool IsAssertBuild = false;
5792#else
5793 const bool IsAssertBuild = true;
5794#endif
5795
5796 // Disable the verification pass in no-asserts builds unless otherwise
5797 // specified.
5798 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5799 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5800 CmdArgs.push_back("-disable-llvm-verifier");
5801 }
5802
5803 // Discard value names in no-asserts builds unless otherwise specified.
5804 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5805 options::OPT_fno_discard_value_names, !IsAssertBuild))
5806 CmdArgs.push_back("-discard-value-names");
5807
5808 // Set the main file name, so that debug info works even with
5809 // -save-temps.
5810 CmdArgs.push_back("-main-file-name");
5811 CmdArgs.push_back(getBaseInputName(Args, Input));
5812
5813 // Some flags which affect the language (via preprocessor
5814 // defines).
5815 if (Args.hasArg(options::OPT_static))
5816 CmdArgs.push_back("-static-define");
5817
5818 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5819
5820 if (Args.hasArg(options::OPT_municode))
5821 CmdArgs.push_back("-DUNICODE");
5822
5823 if (isa<AnalyzeJobAction>(JA))
5824 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5825
5826 if (isa<AnalyzeJobAction>(JA) ||
5827 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5828 CmdArgs.push_back("-setup-static-analyzer");
5829
5830 // Enable compatilibily mode to avoid analyzer-config related errors.
5831 // Since we can't access frontend flags through hasArg, let's manually iterate
5832 // through them.
5833 bool FoundAnalyzerConfig = false;
5834 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5835 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5836 FoundAnalyzerConfig = true;
5837 break;
5838 }
5839 if (!FoundAnalyzerConfig)
5840 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5841 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5842 FoundAnalyzerConfig = true;
5843 break;
5844 }
5845 if (FoundAnalyzerConfig)
5846 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5847
5849
5850 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5851 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5852 if (FunctionAlignment) {
5853 CmdArgs.push_back("-function-alignment");
5854 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5855 }
5856
5857 if (const Arg *A =
5858 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5859 unsigned Value = 0;
5860 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5861 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5862 << A->getAsString(Args) << A->getValue();
5863 else if (!llvm::isPowerOf2_32(Value))
5864 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5865 << A->getAsString(Args) << A->getValue();
5866
5867 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5868 Twine(std::min(Value, 65536u))));
5869 }
5870
5871 // We support -falign-loops=N where N is a power of 2. GCC supports more
5872 // forms.
5873 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5874 unsigned Value = 0;
5875 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5876 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5877 << A->getAsString(Args) << A->getValue();
5878 else if (Value & (Value - 1))
5879 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5880 << A->getAsString(Args) << A->getValue();
5881 // Treat =0 as unspecified (use the target preference).
5882 if (Value)
5883 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5884 Twine(std::min(Value, 65536u))));
5885 }
5886
5887 if (Triple.isOSzOS()) {
5888 // On z/OS some of the system header feature macros need to
5889 // be defined to enable most cross platform projects to build
5890 // successfully. Ths include the libc++ library. A
5891 // complicating factor is that users can define these
5892 // macros to the same or different values. We need to add
5893 // the definition for these macros to the compilation command
5894 // if the user hasn't already defined them.
5895
5896 auto findMacroDefinition = [&](const std::string &Macro) {
5897 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5898 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5899 return M == Macro || M.find(Macro + '=') != std::string::npos;
5900 });
5901 };
5902
5903 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5904 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5905 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5906 // _OPEN_DEFAULT is required for XL compat
5907 if (!findMacroDefinition("_OPEN_DEFAULT"))
5908 CmdArgs.push_back("-D_OPEN_DEFAULT");
5909 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5910 // _XOPEN_SOURCE=600 is required for libcxx.
5911 if (!findMacroDefinition("_XOPEN_SOURCE"))
5912 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5913 }
5914 }
5915
5916 llvm::Reloc::Model RelocationModel;
5917 unsigned PICLevel;
5918 bool IsPIE;
5919 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5920 Arg *LastPICDataRelArg =
5921 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5922 options::OPT_mpic_data_is_text_relative);
5923 bool NoPICDataIsTextRelative = false;
5924 if (LastPICDataRelArg) {
5925 if (LastPICDataRelArg->getOption().matches(
5926 options::OPT_mno_pic_data_is_text_relative)) {
5927 NoPICDataIsTextRelative = true;
5928 if (!PICLevel)
5929 D.Diag(diag::err_drv_argument_only_allowed_with)
5930 << "-mno-pic-data-is-text-relative"
5931 << "-fpic/-fpie";
5932 }
5933 if (!Triple.isSystemZ())
5934 D.Diag(diag::err_drv_unsupported_opt_for_target)
5935 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5936 : "-mpic-data-is-text-relative")
5937 << RawTriple.str();
5938 }
5939
5940 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5941 RelocationModel == llvm::Reloc::ROPI_RWPI;
5942 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5943 RelocationModel == llvm::Reloc::ROPI_RWPI;
5944
5945 if (Args.hasArg(options::OPT_mcmse) &&
5946 !Args.hasArg(options::OPT_fallow_unsupported)) {
5947 if (IsROPI)
5948 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5949 if (IsRWPI)
5950 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5951 }
5952
5953 if (IsROPI && types::isCXX(Input.getType()) &&
5954 !Args.hasArg(options::OPT_fallow_unsupported))
5955 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5956
5957 const char *RMName = RelocationModelName(RelocationModel);
5958 if (RMName) {
5959 CmdArgs.push_back("-mrelocation-model");
5960 CmdArgs.push_back(RMName);
5961 }
5962 if (PICLevel > 0) {
5963 CmdArgs.push_back("-pic-level");
5964 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5965 if (IsPIE)
5966 CmdArgs.push_back("-pic-is-pie");
5967 if (NoPICDataIsTextRelative)
5968 CmdArgs.push_back("-mcmodel=medium");
5969 }
5970
5971 if (RelocationModel == llvm::Reloc::ROPI ||
5972 RelocationModel == llvm::Reloc::ROPI_RWPI)
5973 CmdArgs.push_back("-fropi");
5974 if (RelocationModel == llvm::Reloc::RWPI ||
5975 RelocationModel == llvm::Reloc::ROPI_RWPI)
5976 CmdArgs.push_back("-frwpi");
5977
5978 // -meabi=gnu/5 are encoded in the cc1 -triple environment; forward only other
5979 // values (e.g. 4, which has no triple representation, and invalid values).
5980 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5981 StringRef Value = A->getValue();
5982 if (Value != "gnu" && Value != "5") {
5983 CmdArgs.push_back("-meabi");
5984 CmdArgs.push_back(A->getValue());
5985 }
5986 }
5987
5988 // -fsemantic-interposition is forwarded to CC1: set the
5989 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5990 // make default visibility external linkage definitions dso_preemptable.
5991 //
5992 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5993 // aliases (make default visibility external linkage definitions dso_local).
5994 // This is the CC1 default for ELF to match COFF/Mach-O.
5995 //
5996 // Otherwise use Clang's traditional behavior: like
5997 // -fno-semantic-interposition but local aliases are not used. So references
5998 // can be interposed if not optimized out.
5999 if (Triple.isOSBinFormatELF()) {
6000 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
6001 options::OPT_fno_semantic_interposition);
6002 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
6003 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
6004 bool SupportsLocalAlias =
6005 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
6006 if (!A)
6007 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6008 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
6009 A->render(Args, CmdArgs);
6010 else if (!SupportsLocalAlias)
6011 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6012 }
6013 }
6014
6015 {
6016 std::string Model;
6017 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
6018 if (!TC.isThreadModelSupported(A->getValue()))
6019 D.Diag(diag::err_drv_invalid_thread_model_for_target)
6020 << A->getValue() << A->getAsString(Args);
6021 Model = A->getValue();
6022 } else
6023 Model = TC.getThreadModel();
6024 if (Model != "posix") {
6025 CmdArgs.push_back("-mthread-model");
6026 CmdArgs.push_back(Args.MakeArgString(Model));
6027 }
6028 }
6029
6030 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6031 StringRef Name = A->getValue();
6032 if (Name == "SVML") {
6033 if (Triple.getArch() != llvm::Triple::x86 &&
6034 Triple.getArch() != llvm::Triple::x86_64)
6035 D.Diag(diag::err_drv_unsupported_opt_for_target)
6036 << Name << Triple.getArchName();
6037 } else if (Name == "AMDLIBM") {
6038 if (Triple.getArch() != llvm::Triple::x86 &&
6039 Triple.getArch() != llvm::Triple::x86_64)
6040 D.Diag(diag::err_drv_unsupported_opt_for_target)
6041 << Name << Triple.getArchName();
6042 } else if (Name == "libmvec") {
6043 if (Triple.getArch() != llvm::Triple::x86 &&
6044 Triple.getArch() != llvm::Triple::x86_64 &&
6045 Triple.getArch() != llvm::Triple::aarch64 &&
6046 Triple.getArch() != llvm::Triple::aarch64_be)
6047 D.Diag(diag::err_drv_unsupported_opt_for_target)
6048 << Name << Triple.getArchName();
6049 } else if (Name == "SLEEF" || Name == "ArmPL") {
6050 if (Triple.getArch() != llvm::Triple::aarch64 &&
6051 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6052 D.Diag(diag::err_drv_unsupported_opt_for_target)
6053 << Name << Triple.getArchName();
6054 }
6055 A->render(Args, CmdArgs);
6056 }
6057
6058 if (Args.hasFlag(options::OPT_fmerge_all_constants,
6059 options::OPT_fno_merge_all_constants, false))
6060 CmdArgs.push_back("-fmerge-all-constants");
6061
6062 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
6063 options::OPT_fno_delete_null_pointer_checks);
6064
6065 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
6066 options::OPT_fno_lifetime_dse);
6067
6068 // LLVM Code Generator Options.
6069
6070 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
6071 if (!Triple.isOSAIX() || Triple.isPPC32())
6072 D.Diag(diag::err_drv_unsupported_opt_for_target)
6073 << A->getSpelling() << RawTriple.str();
6074 CmdArgs.push_back("-mabi=quadword-atomics");
6075 }
6076
6077 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
6078 // Emit the unsupported option error until the Clang's library integration
6079 // support for 128-bit long double is available for AIX.
6080 if (Triple.isOSAIX())
6081 D.Diag(diag::err_drv_unsupported_opt_for_target)
6082 << A->getSpelling() << RawTriple.str();
6083 }
6084
6085 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6086 StringRef V = A->getValue(), V1 = V;
6087 unsigned Size;
6088 if (V1.consumeInteger(10, Size) || !V1.empty())
6089 D.Diag(diag::err_drv_invalid_argument_to_option)
6090 << V << A->getOption().getName();
6091 else
6092 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6093 }
6094
6095 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6096 options::OPT_fno_jump_tables);
6097 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6098 options::OPT_fno_profile_sample_accurate);
6099 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6100 options::OPT_fno_preserve_as_comments);
6101
6102 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6103 CmdArgs.push_back("-mregparm");
6104 CmdArgs.push_back(A->getValue());
6105 }
6106
6107 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6108 options::OPT_msvr4_struct_return)) {
6109 if (!TC.getTriple().isPPC32()) {
6110 D.Diag(diag::err_drv_unsupported_opt_for_target)
6111 << A->getSpelling() << RawTriple.str();
6112 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6113 CmdArgs.push_back("-maix-struct-return");
6114 } else {
6115 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6116 CmdArgs.push_back("-msvr4-struct-return");
6117 }
6118 }
6119
6120 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6121 options::OPT_freg_struct_return)) {
6122 if (TC.getArch() != llvm::Triple::x86) {
6123 D.Diag(diag::err_drv_unsupported_opt_for_target)
6124 << A->getSpelling() << RawTriple.str();
6125 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6126 CmdArgs.push_back("-fpcc-struct-return");
6127 } else {
6128 assert(A->getOption().matches(options::OPT_freg_struct_return));
6129 CmdArgs.push_back("-freg-struct-return");
6130 }
6131 }
6132
6133 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6134 if (Triple.getArch() == llvm::Triple::m68k)
6135 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6136 else
6137 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6138 }
6139
6140 if (Args.hasArg(options::OPT_fenable_matrix)) {
6141 // enable-matrix is needed by both the LangOpts and by LLVM.
6142 CmdArgs.push_back("-fenable-matrix");
6143 CmdArgs.push_back("-mllvm");
6144 CmdArgs.push_back("-enable-matrix");
6145 // Only handle default layout if matrix is enabled
6146 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6147 StringRef Val = A->getValue();
6148 if (Val == "row-major" || Val == "column-major") {
6149 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6150 CmdArgs.push_back("-mllvm");
6151 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6152
6153 } else {
6154 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6155 }
6156 }
6157 }
6158
6160 getFramePointerKind(Args, RawTriple);
6161 const char *FPKeepKindStr = nullptr;
6162 switch (FPKeepKind) {
6164 FPKeepKindStr = "-mframe-pointer=none";
6165 break;
6167 FPKeepKindStr = "-mframe-pointer=reserved";
6168 break;
6170 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6171 break;
6173 FPKeepKindStr = "-mframe-pointer=non-leaf";
6174 break;
6176 FPKeepKindStr = "-mframe-pointer=all";
6177 break;
6178 }
6179 assert(FPKeepKindStr && "unknown FramePointerKind");
6180 CmdArgs.push_back(FPKeepKindStr);
6181
6182 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6183 options::OPT_fno_zero_initialized_in_bss);
6184
6185 bool OFastEnabled = isOptimizationLevelFast(Args);
6186 if (Args.hasArg(options::OPT_Ofast))
6187 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6188 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6189 // enabled. This alias option is being used to simplify the hasFlag logic.
6190 OptSpecifier StrictAliasingAliasOption =
6191 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6192 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6193 // doesn't do any TBAA.
6194 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6195 options::OPT_fno_strict_aliasing,
6196 !IsWindowsMSVC && !IsUEFI))
6197 CmdArgs.push_back("-relaxed-aliasing");
6198 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6199 false))
6200 CmdArgs.push_back("-no-pointer-tbaa");
6201 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6202 options::OPT_fno_struct_path_tbaa, true))
6203 CmdArgs.push_back("-no-struct-path-tbaa");
6204
6205 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6206 options::OPT_fno_strict_bool,
6207 options::OPT_fno_strict_bool_EQ)) {
6208 StringRef BFM = "";
6209 if (A->getOption().matches(options::OPT_fstrict_bool))
6210 BFM = "strict";
6211 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6212 BFM = "nonstrict";
6213 else if (A->getValue() == StringRef("truncate"))
6214 BFM = "truncate";
6215 else if (A->getValue() == StringRef("nonzero"))
6216 BFM = "nonzero";
6217 else
6218 D.Diag(diag::err_drv_invalid_value)
6219 << A->getAsString(Args) << A->getValue();
6220 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6221 } else if (KernelOrKext) {
6222 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6223 CmdArgs.push_back("-load-bool-from-mem=truncate");
6224 }
6225
6226 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6227 options::OPT_fno_strict_enums);
6228 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6229 options::OPT_fno_strict_return);
6230 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6231 options::OPT_fno_allow_editor_placeholders);
6232 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6233 options::OPT_fno_strict_vtable_pointers);
6234 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6235 options::OPT_fno_force_emit_vtables);
6236 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6237 options::OPT_fno_optimize_sibling_calls);
6238 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6239 options::OPT_fno_escaping_block_tail_calls);
6240
6241 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6242 options::OPT_fno_fine_grained_bitfield_accesses);
6243
6244 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6245 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6246
6247 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6248 options::OPT_fno_experimental_omit_vtable_rtti);
6249
6250 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6251 options::OPT_fno_disable_block_signature_string);
6252
6253 // Handle segmented stacks.
6254 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6255 options::OPT_fno_split_stack);
6256
6257 // -fprotect-parens=0 is default.
6258 if (Args.hasFlag(options::OPT_fprotect_parens,
6259 options::OPT_fno_protect_parens, false))
6260 CmdArgs.push_back("-fprotect-parens");
6261
6262 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6263
6264 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6265 options::OPT_fno_atomic_remote_memory);
6266 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6267 options::OPT_fno_atomic_fine_grained_memory);
6268 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6269 options::OPT_fno_atomic_ignore_denormal_mode);
6270
6271 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6272 const llvm::Triple::ArchType Arch = TC.getArch();
6273 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6274 StringRef V = A->getValue();
6275 if (V == "64")
6276 CmdArgs.push_back("-fextend-arguments=64");
6277 else if (V != "32")
6278 D.Diag(diag::err_drv_invalid_argument_to_option)
6279 << A->getValue() << A->getOption().getName();
6280 } else
6281 D.Diag(diag::err_drv_unsupported_opt_for_target)
6282 << A->getOption().getName() << TripleStr;
6283 }
6284
6285 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6286 if (TC.getArch() == llvm::Triple::avr)
6287 A->render(Args, CmdArgs);
6288 else
6289 D.Diag(diag::err_drv_unsupported_opt_for_target)
6290 << A->getAsString(Args) << TripleStr;
6291 }
6292
6293 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6294 if (TC.getTriple().isX86())
6295 A->render(Args, CmdArgs);
6296 else if (TC.getTriple().isPPC() &&
6297 (A->getOption().getID() != options::OPT_mlong_double_80))
6298 A->render(Args, CmdArgs);
6299 else
6300 D.Diag(diag::err_drv_unsupported_opt_for_target)
6301 << A->getAsString(Args) << TripleStr;
6302 }
6303
6304 // Decide whether to use verbose asm. Verbose assembly is the default on
6305 // toolchains which have the integrated assembler on by default.
6306 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6307 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6308 IsIntegratedAssemblerDefault))
6309 CmdArgs.push_back("-fno-verbose-asm");
6310
6311 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6312 // use that to indicate the MC default in the backend.
6313 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6314 StringRef V = A->getValue();
6315 unsigned Num;
6316 if (V == "none")
6317 A->render(Args, CmdArgs);
6318 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6319 (V.empty() || (V.consume_front(".") &&
6320 !V.consumeInteger(10, Num) && V.empty())))
6321 A->render(Args, CmdArgs);
6322 else
6323 D.Diag(diag::err_drv_invalid_argument_to_option)
6324 << A->getValue() << A->getOption().getName();
6325 }
6326
6327 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6328 // option to disable integrated-as explicitly.
6330 CmdArgs.push_back("-no-integrated-as");
6331
6332 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6333 CmdArgs.push_back("-mdebug-pass");
6334 CmdArgs.push_back("Structure");
6335 }
6336 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6337 CmdArgs.push_back("-mdebug-pass");
6338 CmdArgs.push_back("Arguments");
6339 }
6340
6341 // Enable -mconstructor-aliases except on darwin, where we have to work around
6342 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6343 // code, where aliases aren't supported.
6344 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6345 CmdArgs.push_back("-mconstructor-aliases");
6346
6347 // Darwin's kernel doesn't support guard variables; just die if we
6348 // try to use them.
6349 if (KernelOrKext && RawTriple.isOSDarwin())
6350 CmdArgs.push_back("-fforbid-guard-variables");
6351
6352 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6353 options::OPT_mno_ms_bitfields)) {
6354 if (A->getOption().matches(options::OPT_mms_bitfields))
6355 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6356 else
6357 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6358 }
6359
6360 if (Triple.isOSCygMing()) {
6361 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6362 options::OPT_fno_auto_import);
6363 }
6364
6365 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6366 Triple.isX86() && IsWindowsMSVC))
6367 CmdArgs.push_back("-fms-volatile");
6368
6369 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6370 // defaults to -fno-direct-access-external-data. Pass the option if different
6371 // from the default.
6372 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6373 options::OPT_fno_direct_access_external_data)) {
6374 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6375 (PICLevel == 0))
6376 A->render(Args, CmdArgs);
6377 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6378 // Some targets default to -fno-direct-access-external-data even for
6379 // -fno-pic.
6380 CmdArgs.push_back("-fno-direct-access-external-data");
6381 }
6382
6383 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6384 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6385
6386 // -fhosted is default.
6387 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6388 // use Freestanding.
6389 bool Freestanding =
6390 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6391 KernelOrKext;
6392 if (Freestanding)
6393 CmdArgs.push_back("-ffreestanding");
6394
6395 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6396
6398 auto SanitizeArgs =
6400 Args.AddLastArg(CmdArgs,
6401 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6402
6403 // This is a coarse approximation of what llvm-gcc actually does, both
6404 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6405 // complicated ways.
6406 bool IsAsyncUnwindTablesDefault =
6408 bool IsSyncUnwindTablesDefault =
6410
6411 bool AsyncUnwindTables = Args.hasFlag(
6412 options::OPT_fasynchronous_unwind_tables,
6413 options::OPT_fno_asynchronous_unwind_tables,
6414 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6415 !Freestanding);
6416 bool UnwindTables =
6417 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6418 IsSyncUnwindTablesDefault && !Freestanding);
6419 if (AsyncUnwindTables)
6420 CmdArgs.push_back("-funwind-tables=2");
6421 else if (UnwindTables)
6422 CmdArgs.push_back("-funwind-tables=1");
6423
6424 // Sframe unwind tables are independent of the other types. Although also
6425 // defined for aarch64, only x86_64 support is implemented at the moment.
6426 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6427 if (Triple.isOSBinFormatELF() && Triple.isX86())
6428 CmdArgs.push_back("--gsframe");
6429 else
6430 D.Diag(diag::err_drv_unsupported_opt_for_target)
6431 << A->getOption().getName() << TripleStr;
6432 }
6433
6434 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6435 // `--gpu-use-aux-triple-only` is specified.
6436 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6437 const ArgList &HostArgs =
6438 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6439 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6440 if (!HostCPU.empty()) {
6441 CmdArgs.push_back("-aux-target-cpu");
6442 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6443 }
6444 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6445 /*ForAS*/ false, /*IsAux*/ true);
6446 }
6447
6448 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6450
6451 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6452
6453 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6454 StringRef Value = A->getValue();
6455 unsigned TLSSize = 0;
6456 Value.getAsInteger(10, TLSSize);
6457 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6458 D.Diag(diag::err_drv_unsupported_opt_for_target)
6459 << A->getOption().getName() << TripleStr;
6460 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6461 D.Diag(diag::err_drv_invalid_int_value)
6462 << A->getOption().getName() << Value;
6463 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6464 }
6465
6466 if (isTLSDESCEnabled(TC, Args))
6467 CmdArgs.push_back("-enable-tlsdesc");
6468
6469 // Add the target cpu
6470 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6471 if (!CPU.empty()) {
6472 CmdArgs.push_back("-target-cpu");
6473 CmdArgs.push_back(Args.MakeArgString(CPU));
6474 }
6475
6476 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6477
6478 // Add clang-cl arguments.
6479 types::ID InputType = Input.getType();
6480 if (D.IsCLMode())
6481 AddClangCLArgs(Args, InputType, CmdArgs);
6482
6483 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6484 llvm::codegenoptions::NoDebugInfo;
6486 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6487 DebugInfoKind, DwarfFission, IsUsingLTO);
6488
6489 // Add the split debug info name to the command lines here so we
6490 // can propagate it to the backend.
6491 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6492 (TC.getTriple().isOSBinFormatELF() ||
6493 TC.getTriple().isOSBinFormatWasm() ||
6494 TC.getTriple().isOSBinFormatCOFF()) &&
6497 if (SplitDWARF) {
6498 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6499 CmdArgs.push_back("-split-dwarf-file");
6500 CmdArgs.push_back(SplitDWARFOut);
6501 if (DwarfFission == DwarfFissionKind::Split) {
6502 CmdArgs.push_back("-split-dwarf-output");
6503 CmdArgs.push_back(SplitDWARFOut);
6504 }
6505 }
6506
6507 // Pass the linker version in use.
6508 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6509 CmdArgs.push_back("-target-linker-version");
6510 CmdArgs.push_back(A->getValue());
6511 }
6512
6513 // Explicitly error on some things we know we don't support and can't just
6514 // ignore.
6515 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6516 Arg *Unsupported;
6517 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6518 TC.getArch() == llvm::Triple::x86) {
6519 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6520 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6521 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6522 << Unsupported->getOption().getName();
6523 }
6524 // The faltivec option has been superseded by the maltivec option.
6525 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6526 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6527 << Unsupported->getOption().getName()
6528 << "please use -maltivec and include altivec.h explicitly";
6529 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6530 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6531 << Unsupported->getOption().getName() << "please use -mno-altivec";
6532 }
6533
6534 Args.AddAllArgs(CmdArgs, options::OPT_v);
6535
6536 if (Args.getLastArg(options::OPT_H)) {
6537 CmdArgs.push_back("-H");
6538 CmdArgs.push_back("-sys-header-deps");
6539 }
6540 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6541
6543 CmdArgs.push_back("-header-include-file");
6544 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6545 ? D.CCPrintHeadersFilename.c_str()
6546 : "-");
6547 CmdArgs.push_back("-sys-header-deps");
6548 CmdArgs.push_back(Args.MakeArgString(
6549 "-header-include-format=" +
6551 CmdArgs.push_back(Args.MakeArgString(
6552 "-header-include-filtering=" +
6554 }
6555 Args.AddLastArg(CmdArgs, options::OPT_P);
6556 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6557
6558 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6559 CmdArgs.push_back("-diagnostic-log-file");
6560 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6561 ? D.CCLogDiagnosticsFilename.c_str()
6562 : "-");
6563 }
6564
6565 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6566 // crashes.
6567 if (D.CCGenDiagnostics)
6568 CmdArgs.push_back("-disable-pragma-debug-crash");
6569
6570 // Allow backend to put its diagnostic files in the same place as frontend
6571 // crash diagnostics files.
6572 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6573 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6574 CmdArgs.push_back("-mllvm");
6575 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6576 }
6577
6578 addSeparateSectionFlags(Triple, Args, CmdArgs);
6579
6580 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6581 options::OPT_fno_basic_block_address_map)) {
6582 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6583 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6584 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6585 A->render(Args, CmdArgs);
6586 } else {
6587 D.Diag(diag::err_drv_unsupported_opt_for_target)
6588 << A->getAsString(Args) << TripleStr;
6589 }
6590 }
6591
6592 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6593 StringRef Val = A->getValue();
6594 if (Val == "labels") {
6595 D.Diag(diag::warn_drv_deprecated_arg)
6596 << A->getAsString(Args) << /*hasReplacement=*/true
6597 << "-fbasic-block-address-map";
6598 CmdArgs.push_back("-fbasic-block-address-map");
6599 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6600 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6601 D.Diag(diag::err_drv_invalid_value)
6602 << A->getAsString(Args) << A->getValue();
6603 else
6604 A->render(Args, CmdArgs);
6605 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6606 // "all" is not supported on AArch64 since branch relaxation creates new
6607 // basic blocks for some cross-section branches.
6608 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6609 D.Diag(diag::err_drv_invalid_value)
6610 << A->getAsString(Args) << A->getValue();
6611 else
6612 A->render(Args, CmdArgs);
6613 } else if (Triple.isNVPTX()) {
6614 // Do not pass the option to the GPU compilation. We still want it enabled
6615 // for the host-side compilation, so seeing it here is not an error.
6616 } else if (Val != "none") {
6617 // =none is allowed everywhere. It's useful for overriding the option
6618 // and is the same as not specifying the option.
6619 D.Diag(diag::err_drv_unsupported_opt_for_target)
6620 << A->getAsString(Args) << TripleStr;
6621 }
6622 }
6623
6624 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6625 options::OPT_fno_unique_section_names);
6626 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6627 options::OPT_fno_separate_named_sections);
6628 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6629 options::OPT_fno_unique_internal_linkage_names);
6630 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6631 options::OPT_fno_unique_basic_block_section_names);
6632
6633 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6634
6635 if (Arg *A =
6636 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6637 options::OPT_fno_partition_static_data_sections)) {
6638 if (!A->getOption().matches(
6639 options::OPT_fno_partition_static_data_sections)) {
6640 // This codegen pass is only available on x86 and AArch64 ELF targets.
6641 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6642 A->render(Args, CmdArgs);
6643 CmdArgs.push_back("-mllvm");
6644 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6645 } else
6646 D.Diag(diag::err_drv_unsupported_opt_for_target)
6647 << A->getAsString(Args) << TripleStr;
6648 }
6649 }
6650
6651 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6652 options::OPT_finstrument_functions_after_inlining,
6653 options::OPT_finstrument_function_entry_bare);
6654 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6655 options::OPT_fno_convergent_functions);
6656
6657 // NVPTX doesn't support PGO or coverage
6658 if (!Triple.isNVPTX())
6659 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6660
6661 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6662
6663 if (getLastProfileSampleUseArg(Args) &&
6664 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6665 options::OPT_fno_sample_profile_use_profi, true)) {
6666 CmdArgs.push_back("-mllvm");
6667 CmdArgs.push_back("-sample-profile-use-profi");
6668 }
6669
6670 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6671 if (RawTriple.isPS() &&
6672 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6673 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6674 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6675 }
6676
6677 // Pass options for controlling the default header search paths.
6678 if (Args.hasArg(options::OPT_nostdinc)) {
6679 CmdArgs.push_back("-nostdsysteminc");
6680 CmdArgs.push_back("-nobuiltininc");
6681 } else {
6682 if (Args.hasArg(options::OPT_nostdlibinc))
6683 CmdArgs.push_back("-nostdsysteminc");
6684 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6685 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6686 }
6687
6688 // Pass the path to compiler resource files.
6689 CmdArgs.push_back("-resource-dir");
6690 CmdArgs.push_back(D.ResourceDir.c_str());
6691
6692 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6693
6694 // Add preprocessing options like -I, -D, etc. if we are using the
6695 // preprocessor.
6696 //
6697 // FIXME: Support -fpreprocessed
6699 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6700
6701 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6702 // that "The compiler can only warn and ignore the option if not recognized".
6703 // When building with ccache, it will pass -D options to clang even on
6704 // preprocessed inputs and configure concludes that -fPIC is not supported.
6705 Args.ClaimAllArgs(options::OPT_D);
6706
6707 // Warn about ignored options to clang.
6708 for (const Arg *A :
6709 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6710 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6711 A->claim();
6712 }
6713
6714 for (const Arg *A :
6715 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6716 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6717 A->claim();
6718 }
6719
6720 claimNoWarnArgs(Args);
6721
6722 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6723
6724 for (const Arg *A :
6725 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6726 A->claim();
6727 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6728 unsigned WarningNumber;
6729 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6730 D.Diag(diag::err_drv_invalid_int_value)
6731 << A->getAsString(Args) << A->getValue();
6732 continue;
6733 }
6734
6735 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6736 CmdArgs.push_back(Args.MakeArgString(
6737 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6738 }
6739 continue;
6740 }
6741 A->render(Args, CmdArgs);
6742 }
6743
6744 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6745
6746 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6747 CmdArgs.push_back("-pedantic");
6748 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6749 Args.AddLastArg(CmdArgs, options::OPT_w);
6750
6751 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6752 options::OPT_fno_fixed_point);
6753
6754 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6755 options::OPT_fno_experimental_overflow_behavior_types);
6756
6757 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6758 A->render(Args, CmdArgs);
6759
6760 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6761 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6762
6763 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6764 options::OPT_fno_experimental_omit_vtable_rtti);
6765
6766 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6767 A->render(Args, CmdArgs);
6768
6769 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6770 // (-ansi is equivalent to -std=c89 or -std=c++98).
6771 //
6772 // If a std is supplied, only add -trigraphs if it follows the
6773 // option.
6774 bool ImplyVCPPCVer = false;
6775 bool ImplyVCPPCXXVer = false;
6776 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6777 if (Std) {
6778 if (Std->getOption().matches(options::OPT_ansi))
6779 if (types::isCXX(InputType))
6780 CmdArgs.push_back("-std=c++98");
6781 else
6782 CmdArgs.push_back("-std=c89");
6783 else {
6784 if (IsSYCL) {
6785 const LangStandard *LangStd =
6786 LangStandard::getLangStandardForName(Std->getValue());
6787 if (LangStd) {
6788 // Use of -std= with 'C' is not supported for SYCL.
6789 if (LangStd->getLanguage() == Language::C)
6790 D.Diag(diag::err_drv_argument_not_allowed_with)
6791 << Std->getAsString(Args) << "-fsycl";
6792 // SYCL requires C++17 or later.
6793 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6794 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6795 }
6796 }
6797 Std->render(Args, CmdArgs);
6798 }
6799
6800 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6801 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6802 options::OPT_ftrigraphs,
6803 options::OPT_fno_trigraphs))
6804 if (A != Std)
6805 A->render(Args, CmdArgs);
6806 } else {
6807 // Honor -std-default.
6808 //
6809 // FIXME: Clang doesn't correctly handle -std= when the input language
6810 // doesn't match. For the time being just ignore this for C++ inputs;
6811 // eventually we want to do all the standard defaulting here instead of
6812 // splitting it between the driver and clang -cc1.
6813 if (!types::isCXX(InputType)) {
6814 if (!Args.hasArg(options::OPT__SLASH_std)) {
6815 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6816 /*Joined=*/true);
6817 } else
6818 ImplyVCPPCVer = true;
6819 }
6820 else if (IsWindowsMSVC)
6821 ImplyVCPPCXXVer = true;
6822
6823 if (IsSYCL && types::isCXX(InputType) &&
6824 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6825 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6826 // on the command line will override. On Windows MSVC, this is handled
6827 // by the ImplyVCPPCXXVer path below.
6828 CmdArgs.push_back("-std=c++17");
6829
6830 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6831 options::OPT_fno_trigraphs);
6832 }
6833
6834 // GCC's behavior for -Wwrite-strings is a bit strange:
6835 // * In C, this "warning flag" changes the types of string literals from
6836 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6837 // for the discarded qualifier.
6838 // * In C++, this is just a normal warning flag.
6839 //
6840 // Implementing this warning correctly in C is hard, so we follow GCC's
6841 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6842 // a non-const char* in C, rather than using this crude hack.
6843 if (!types::isCXX(InputType)) {
6844 // FIXME: This should behave just like a warning flag, and thus should also
6845 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6846 Arg *WriteStrings =
6847 Args.getLastArg(options::OPT_Wwrite_strings,
6848 options::OPT_Wno_write_strings, options::OPT_w);
6849 if (WriteStrings &&
6850 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6851 CmdArgs.push_back("-fconst-strings");
6852 }
6853
6854 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6855 // during C++ compilation, which it is by default. GCC keeps this define even
6856 // in the presence of '-w', match this behavior bug-for-bug.
6857 if (types::isCXX(InputType) &&
6858 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6859 true)) {
6860 CmdArgs.push_back("-fdeprecated-macro");
6861 }
6862
6863 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6864 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6865 if (Asm->getOption().matches(options::OPT_fasm))
6866 CmdArgs.push_back("-fgnu-keywords");
6867 else
6868 CmdArgs.push_back("-fno-gnu-keywords");
6869 }
6870
6871 if (!ShouldEnableAutolink(Args, TC, JA))
6872 CmdArgs.push_back("-fno-autolink");
6873
6874 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6875 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6876 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6877 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6878
6879 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6880
6881 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6882 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6883 Args.AddLastArg(CmdArgs,
6884 options::OPT_fno_experimental_new_constant_interpreter);
6885 } else {
6886 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6887 Args.AddLastArg(CmdArgs,
6888 options::OPT_fexperimental_new_constant_interpreter);
6889 }
6890
6891 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6892 CmdArgs.push_back("-fbracket-depth");
6893 CmdArgs.push_back(A->getValue());
6894 }
6895
6896 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6897 options::OPT_Wlarge_by_value_copy_def)) {
6898 if (A->getNumValues()) {
6899 StringRef bytes = A->getValue();
6900 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6901 } else
6902 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6903 }
6904
6905 if (Args.hasArg(options::OPT_relocatable_pch))
6906 CmdArgs.push_back("-relocatable-pch");
6907
6908 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6909 static const char *kCFABIs[] = {
6910 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6911 };
6912
6913 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6914 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6915 else
6916 A->render(Args, CmdArgs);
6917 }
6918
6919 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6920 CmdArgs.push_back("-fconstant-string-class");
6921 CmdArgs.push_back(A->getValue());
6922 }
6923
6924 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6925 CmdArgs.push_back("-fconstant-array-class");
6926 CmdArgs.push_back(A->getValue());
6927 }
6928 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6929 CmdArgs.push_back("-fconstant-dictionary-class");
6930 CmdArgs.push_back(A->getValue());
6931 }
6932 if (Arg *A =
6933 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6934 CmdArgs.push_back("-fconstant-integer-number-class");
6935 CmdArgs.push_back(A->getValue());
6936 }
6937 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6938 CmdArgs.push_back("-fconstant-float-number-class");
6939 CmdArgs.push_back(A->getValue());
6940 }
6941 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6942 CmdArgs.push_back("-fconstant-double-number-class");
6943 CmdArgs.push_back(A->getValue());
6944 }
6945
6946 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6947 CmdArgs.push_back("-ftabstop");
6948 CmdArgs.push_back(A->getValue());
6949 }
6950
6951 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
6952 options::OPT_fno_experimental_call_graph_section, false))
6953 CmdArgs.push_back("-fexperimental-call-graph-section");
6954
6955 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6956 options::OPT_fno_stack_size_section);
6957
6958 if (Args.hasArg(options::OPT_fstack_usage)) {
6959 CmdArgs.push_back("-stack-usage-file");
6960
6961 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6962 SmallString<128> OutputFilename(OutputOpt->getValue());
6963 llvm::sys::path::replace_extension(OutputFilename, "su");
6964 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6965 } else
6966 CmdArgs.push_back(
6967 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6968 }
6969
6970 CmdArgs.push_back("-ferror-limit");
6971 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6972 CmdArgs.push_back(A->getValue());
6973 else
6974 CmdArgs.push_back("19");
6975
6976 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6977 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6978 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6979 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6980 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6981
6982 // Pass -fmessage-length=.
6983 unsigned MessageLength = 0;
6984 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6985 StringRef V(A->getValue());
6986 if (V.getAsInteger(0, MessageLength))
6987 D.Diag(diag::err_drv_invalid_argument_to_option)
6988 << V << A->getOption().getName();
6989 } else {
6990 // If -fmessage-length=N was not specified, determine whether this is a
6991 // terminal and, if so, implicitly define -fmessage-length appropriately.
6992 MessageLength = llvm::sys::Process::StandardErrColumns();
6993 }
6994 if (MessageLength != 0)
6995 CmdArgs.push_back(
6996 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6997
6998 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6999 CmdArgs.push_back(
7000 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
7001
7002 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
7003 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
7004 Twine(A->getValue(0))));
7005
7006 // -fvisibility= and -fvisibility-ms-compat are of a piece.
7007 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
7008 options::OPT_fvisibility_ms_compat)) {
7009 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
7010 A->render(Args, CmdArgs);
7011 } else {
7012 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
7013 CmdArgs.push_back("-fvisibility=hidden");
7014 CmdArgs.push_back("-ftype-visibility=default");
7015 }
7016 } else if (IsOpenMPDevice) {
7017 // When compiling for the OpenMP device we want protected visibility by
7018 // default. This prevents the device from accidentally preempting code on
7019 // the host, makes the system more robust, and improves performance.
7020 CmdArgs.push_back("-fvisibility=protected");
7021 }
7022
7023 // PS4/PS5 process these options in addClangTargetOptions.
7024 if (!RawTriple.isPS()) {
7025 if (const Arg *A =
7026 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
7027 options::OPT_fno_visibility_from_dllstorageclass)) {
7028 if (A->getOption().matches(
7029 options::OPT_fvisibility_from_dllstorageclass)) {
7030 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
7031 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
7032 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
7033 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
7034 Args.AddLastArg(CmdArgs,
7035 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7036 }
7037 }
7038 }
7039
7040 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
7041 options::OPT_fno_visibility_inlines_hidden, false))
7042 CmdArgs.push_back("-fvisibility-inlines-hidden");
7043
7044 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
7045 options::OPT_fno_visibility_inlines_hidden_static_local_var);
7046
7047 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7048 // -fvisibility-global-new-delete=force-hidden.
7049 if (const Arg *A =
7050 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
7051 D.Diag(diag::warn_drv_deprecated_arg)
7052 << A->getAsString(Args) << /*hasReplacement=*/true
7053 << "-fvisibility-global-new-delete=force-hidden";
7054 }
7055
7056 if (const Arg *A =
7057 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
7058 options::OPT_fvisibility_global_new_delete_hidden)) {
7059 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
7060 A->render(Args, CmdArgs);
7061 } else {
7062 assert(A->getOption().matches(
7063 options::OPT_fvisibility_global_new_delete_hidden));
7064 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
7065 }
7066 }
7067
7068 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
7069
7070 if (Args.hasFlag(options::OPT_fnew_infallible,
7071 options::OPT_fno_new_infallible, false))
7072 CmdArgs.push_back("-fnew-infallible");
7073
7074 if (Args.hasFlag(options::OPT_fno_operator_names,
7075 options::OPT_foperator_names, false))
7076 CmdArgs.push_back("-fno-operator-names");
7077
7078 // Forward -f (flag) options which we can pass directly.
7079 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7080 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7081 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7082 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7083 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7084 options::OPT_fno_raw_string_literals);
7085
7086 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7087 Triple.hasDefaultEmulatedTLS()))
7088 CmdArgs.push_back("-femulated-tls");
7089
7090 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7091 options::OPT_fno_check_new);
7092
7093 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7094 // FIXME: There's no reason for this to be restricted to some backend.
7095 // The backend code needs to be changed to include the appropriate function
7096 // calls automatically.
7097 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7098 D.Diag(diag::err_drv_unsupported_opt_for_target)
7099 << A->getAsString(Args) << TripleStr;
7100 }
7101
7102 // AltiVec-like language extensions aren't relevant for assembling.
7103 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7104 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7105
7106 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7107 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7108
7109 // Forward flags for OpenMP. We don't do this if the current action is an
7110 // device offloading action other than OpenMP.
7111 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7112 options::OPT_fno_openmp, false) &&
7113 !Args.hasFlag(options::OPT_foffload_via_llvm,
7114 options::OPT_fno_offload_via_llvm, false) &&
7117
7118 // Determine if target-fast optimizations should be enabled
7119 bool TargetFastUsed =
7120 Args.hasFlag(options::OPT_fopenmp_target_fast,
7121 options::OPT_fno_openmp_target_fast, OFastEnabled);
7122 switch (D.getOpenMPRuntime(Args)) {
7123 case Driver::OMPRT_OMP:
7125 // Clang can generate useful OpenMP code for these two runtime libraries.
7126 CmdArgs.push_back("-fopenmp");
7127
7128 // If no option regarding the use of TLS in OpenMP codegeneration is
7129 // given, decide a default based on the target. Otherwise rely on the
7130 // options and pass the right information to the frontend.
7131 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7132 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7133 CmdArgs.push_back("-fnoopenmp-use-tls");
7134 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7135 options::OPT_fno_openmp_simd);
7136 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7137 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7138 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7139 options::OPT_fno_openmp_extensions, /*Default=*/true))
7140 CmdArgs.push_back("-fno-openmp-extensions");
7141 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7142 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7143 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7144 // effect: the teams reduction buffer is sized at kernel launch by the
7145 // offload plugin to match the actual number of teams. Honoring a
7146 // smaller user-supplied value would silently truncate the buffer for
7147 // larger launches.
7148 if (Arg *A = Args.getLastArg(
7149 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7150 D.Diag(diag::warn_drv_deprecated_custom)
7151 << A->getAsString(Args)
7152 << "the value is ignored; the teams reduction buffer is sized "
7153 "automatically at kernel launch";
7154 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7155 options::OPT_fno_openmp_optimistic_collapse,
7156 /*Default=*/false))
7157 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7158
7159 // When in OpenMP offloading mode with NVPTX target, forward
7160 // cuda-mode flag
7161 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7162 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7163 CmdArgs.push_back("-fopenmp-cuda-mode");
7164
7165 // When in OpenMP offloading mode, enable debugging on the device.
7166 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7167 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7168 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7169 CmdArgs.push_back("-fopenmp-target-debug");
7170
7171 // When in OpenMP offloading mode, forward assumptions information about
7172 // thread and team counts in the device.
7173 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7174 options::OPT_fno_openmp_assume_teams_oversubscription,
7175 /*Default=*/TargetFastUsed))
7176 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7177 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7178 options::OPT_fno_openmp_assume_threads_oversubscription,
7179 /*Default=*/TargetFastUsed))
7180 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7181
7182 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7183 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7184 options::OPT_fno_openmp_assume_no_thread_state,
7185 /*Default=*/TargetFastUsed))
7186 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7187
7188 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7189 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7190 options::OPT_fno_openmp_assume_no_nested_parallelism,
7191 /*Default=*/TargetFastUsed))
7192 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7193
7194 // Handle -fopenmp-target-atomic-reduction.
7195 if (Args.hasFlag(options::OPT_fopenmp_target_atomic_reduction,
7196 options::OPT_fno_openmp_target_atomic_reduction,
7197 /*Default=*/false))
7198 CmdArgs.push_back("-fopenmp-target-atomic-reduction");
7199
7200 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7201 CmdArgs.push_back("-fopenmp-offload-mandatory");
7202 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7203 CmdArgs.push_back("-fopenmp-force-usm");
7204 break;
7205 default:
7206 // By default, if Clang doesn't know how to generate useful OpenMP code
7207 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7208 // down to the actual compilation.
7209 // FIXME: It would be better to have a mode which *only* omits IR
7210 // generation based on the OpenMP support so that we get consistent
7211 // semantic analysis, etc.
7212 break;
7213 }
7214 } else {
7215 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7216 options::OPT_fno_openmp_simd);
7217 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7218 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7219 options::OPT_fno_openmp_extensions);
7220 }
7221 // Forward '-foffload-via-llvm' to code generation to target the LLVM/Offload
7222 // runtime.
7223 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7224 options::OPT_fno_offload_via_llvm, false))
7225 CmdArgs.push_back("-foffload-via-llvm");
7226
7227 const XRayArgs &XRay = TC.getXRayArgs(Args);
7228 XRay.addArgs(TC, Args, CmdArgs, InputType);
7229
7230 for (const auto &Filename :
7231 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7232 if (D.getVFS().exists(Filename))
7233 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7234 else
7235 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7236 }
7237
7238 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7239 StringRef S0 = A->getValue(), S = S0;
7240 unsigned Size, Offset = 0;
7241 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7242 !Triple.isX86() && !Triple.isSystemZ() &&
7243 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7244 Triple.getArch() == llvm::Triple::ppc64 ||
7245 Triple.getArch() == llvm::Triple::ppc64le)))
7246 D.Diag(diag::err_drv_unsupported_opt_for_target)
7247 << A->getAsString(Args) << TripleStr;
7248 else if (S.consumeInteger(10, Size) ||
7249 (!S.empty() &&
7250 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7251 (!S.empty() && (!S.consume_front(",") || S.empty())))
7252 D.Diag(diag::err_drv_invalid_argument_to_option)
7253 << S0 << A->getOption().getName();
7254 else if (Size < Offset)
7255 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7256 else {
7257 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7258 CmdArgs.push_back(Args.MakeArgString(
7259 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7260 if (!S.empty())
7261 CmdArgs.push_back(
7262 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7263 }
7264 }
7265
7266 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7267
7268 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7269 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7270
7271 for (const auto &A :
7272 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7273 CmdArgs.push_back(
7274 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7275
7276 if (TC.SupportsProfiling()) {
7277 Args.AddLastArg(CmdArgs, options::OPT_pg);
7278
7279 llvm::Triple::ArchType Arch = TC.getArch();
7280 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7281 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7282 A->render(Args, CmdArgs);
7283 else
7284 D.Diag(diag::err_drv_unsupported_opt_for_target)
7285 << A->getAsString(Args) << TripleStr;
7286 }
7287 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7288 if (Arch == llvm::Triple::systemz)
7289 A->render(Args, CmdArgs);
7290 else
7291 D.Diag(diag::err_drv_unsupported_opt_for_target)
7292 << A->getAsString(Args) << TripleStr;
7293 }
7294 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7295 if (Arch == llvm::Triple::systemz)
7296 A->render(Args, CmdArgs);
7297 else
7298 D.Diag(diag::err_drv_unsupported_opt_for_target)
7299 << A->getAsString(Args) << TripleStr;
7300 }
7301 }
7302
7303 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7304 if (TC.getTriple().isOSzOS()) {
7305 D.Diag(diag::err_drv_unsupported_opt_for_target)
7306 << A->getAsString(Args) << TripleStr;
7307 }
7308 }
7309 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7310 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7311 D.Diag(diag::err_drv_unsupported_opt_for_target)
7312 << A->getAsString(Args) << TripleStr;
7313 }
7314 }
7315 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7316 if (A->getOption().matches(options::OPT_p)) {
7317 A->claim();
7318 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7319 CmdArgs.push_back("-pg");
7320 }
7321 }
7322
7323 // Reject AIX-specific link options on other targets.
7324 if (!TC.getTriple().isOSAIX()) {
7325 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7326 options::OPT_mxcoff_build_id_EQ)) {
7327 D.Diag(diag::err_drv_unsupported_opt_for_target)
7328 << A->getSpelling() << TripleStr;
7329 }
7330 }
7331
7332 if (Args.getLastArg(options::OPT_fapple_kext) ||
7333 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7334 CmdArgs.push_back("-fapple-kext");
7335
7336 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7337 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7338 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7339 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7340 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7341 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7342 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7343 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7344 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7345 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7346 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7347
7348 if (const char *Name = C.getTimeTraceFile(&JA)) {
7349 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7350 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7351 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7352 }
7353
7354 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7355 CmdArgs.push_back("-ftrapv-handler");
7356 CmdArgs.push_back(A->getValue());
7357 }
7358
7359 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7360
7361 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7362 options::OPT_fno_finite_loops);
7363
7364 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7365 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7366 options::OPT_fno_unroll_loops);
7367 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7368 options::OPT_fno_loop_interchange);
7369 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7370 options::OPT_fno_experimental_loop_fusion);
7371
7372 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7373
7374 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7375
7376 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7377 options::OPT_mno_speculative_load_hardening);
7378
7379 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7380 RenderSCPOptions(TC, Args, CmdArgs);
7381 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7382
7383 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7384
7385 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7386 options::OPT_mno_stackrealign);
7387
7388 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7389 StringRef Value = A->getValue();
7390 int64_t Alignment = 0;
7391 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7392 D.Diag(diag::err_drv_invalid_argument_to_option)
7393 << Value << A->getOption().getName();
7394 else if (Alignment & (Alignment - 1))
7395 D.Diag(diag::err_drv_alignment_not_power_of_two)
7396 << A->getAsString(Args) << Value;
7397 else
7398 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7399 }
7400
7401 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7402 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7403
7404 if (!Size.empty())
7405 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7406 else
7407 CmdArgs.push_back("-mstack-probe-size=0");
7408 }
7409
7410 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7411 options::OPT_mno_stack_arg_probe);
7412
7413 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7414 options::OPT_mno_restrict_it)) {
7415 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7416 CmdArgs.push_back("-mllvm");
7417 CmdArgs.push_back("-arm-restrict-it");
7418 } else {
7419 CmdArgs.push_back("-mllvm");
7420 CmdArgs.push_back("-arm-default-it");
7421 }
7422 }
7423
7424 // Forward -cl options to -cc1
7425 RenderOpenCLOptions(Args, CmdArgs, InputType);
7426
7427 // Forward hlsl options to -cc1
7428 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7429
7430 // Forward OpenACC options to -cc1
7431 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7432
7433 if (IsHIP) {
7434 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7435 options::OPT_fno_hip_new_launch_api, true))
7436 CmdArgs.push_back("-fhip-new-launch-api");
7437 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7438 options::OPT_fno_gpu_allow_device_init);
7439 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7440 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7441 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7442 options::OPT_fno_hip_kernel_arg_name);
7443 }
7444
7445 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7446 CmdArgs.push_back("-fgpu-rdc");
7447
7448 if (IsCuda || IsHIP) {
7449 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7450 options::OPT_fno_gpu_defer_diag);
7451 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7452 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7453 false)) {
7454 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7455 CmdArgs.push_back("-fgpu-defer-diag");
7456 }
7457 }
7458
7459 // Forward --no-offloadlib to -cc1.
7460 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7461 CmdArgs.push_back("--no-offloadlib");
7462
7463 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7464 CmdArgs.push_back(
7465 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7466
7467 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7468 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7469 SA->getValue()));
7470 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7471 // Emit IBT endbr64 instructions by default
7472 CmdArgs.push_back("-fcf-protection=branch");
7473 // jump-table can generate indirect jumps, which are not permitted
7474 CmdArgs.push_back("-fno-jump-tables");
7475 }
7476
7477 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7478 CmdArgs.push_back(
7479 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7480
7481 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7482
7483 // Forward -f options with positive and negative forms; we translate these by
7484 // hand. Do not propagate PGO options to the GPU-side compilations as the
7485 // profile info is for the host-side compilation only.
7486 if (!(IsCudaDevice || IsHIPDevice)) {
7487 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7488 auto *PGOArg = Args.getLastArg(
7489 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7490 options::OPT_fcs_profile_generate,
7491 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7492 options::OPT_fprofile_use_EQ);
7493 if (PGOArg)
7494 D.Diag(diag::err_drv_argument_not_allowed_with)
7495 << "SampleUse with PGO options";
7496
7497 StringRef fname = A->getValue();
7498 if (!llvm::sys::fs::exists(fname))
7499 D.Diag(diag::err_drv_no_such_file) << fname;
7500 else
7501 A->render(Args, CmdArgs);
7502 }
7503 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7504
7505 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7506 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7507 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7508 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7509 // off.
7510 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7511 options::OPT_fno_unique_internal_linkage_names, true))
7512 CmdArgs.push_back("-funique-internal-linkage-names");
7513 }
7514 }
7515 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7516
7517 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7518 options::OPT_fno_assume_sane_operator_new);
7519
7520 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7521 CmdArgs.push_back("-fapinotes");
7522 if (Args.hasFlag(options::OPT_fapinotes_modules,
7523 options::OPT_fno_apinotes_modules, false))
7524 CmdArgs.push_back("-fapinotes-modules");
7525 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7526
7527 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7528 options::OPT_fno_swift_version_independent_apinotes, false))
7529 CmdArgs.push_back("-fswift-version-independent-apinotes");
7530
7531 // -fblocks=0 is default.
7532 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7533 TC.IsBlocksDefault()) ||
7534 (Args.hasArg(options::OPT_fgnu_runtime) &&
7535 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7536 !Args.hasArg(options::OPT_fno_blocks))) {
7537 CmdArgs.push_back("-fblocks");
7538
7539 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7540 CmdArgs.push_back("-fblocks-runtime-optional");
7541 }
7542
7543 // -fencode-extended-block-signature=1 is default.
7545 CmdArgs.push_back("-fencode-extended-block-signature");
7546
7547 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7548 options::OPT_fno_coro_aligned_allocation, false) &&
7549 types::isCXX(InputType))
7550 CmdArgs.push_back("-fcoro-aligned-allocation");
7551
7552 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7553 /*Default=*/false))
7554 CmdArgs.push_back("-fdefer-ts");
7555
7556 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7557 options::OPT_fno_double_square_bracket_attributes);
7558
7559 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7560 options::OPT_fno_access_control);
7561 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7562 options::OPT_fno_elide_constructors);
7563
7564 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7565
7566 if (KernelOrKext || (types::isCXX(InputType) &&
7567 (RTTIMode == ToolChain::RM_Disabled)))
7568 CmdArgs.push_back("-fno-rtti");
7569
7570 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7571 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7572 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7573 CmdArgs.push_back("-fshort-enums");
7574
7575 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7576
7577 // -fuse-cxa-atexit is default.
7578 if (!Args.hasFlag(
7579 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7580 !RawTriple.isOSAIX() &&
7581 (!RawTriple.isOSWindows() ||
7582 RawTriple.isWindowsCygwinEnvironment()) &&
7583 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7584 RawTriple.hasEnvironment())) ||
7585 KernelOrKext)
7586 CmdArgs.push_back("-fno-use-cxa-atexit");
7587
7588 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7589 options::OPT_fno_register_global_dtors_with_atexit,
7590 RawTriple.isOSDarwin() && !KernelOrKext))
7591 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7592
7593 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7594 options::OPT_fno_use_line_directives);
7595
7596 // -fno-minimize-whitespace is default.
7597 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7598 options::OPT_fno_minimize_whitespace, false)) {
7599 types::ID InputType = Inputs[0].getType();
7600 if (!isDerivedFromC(InputType))
7601 D.Diag(diag::err_drv_opt_unsupported_input_type)
7602 << "-fminimize-whitespace" << types::getTypeName(InputType);
7603 CmdArgs.push_back("-fminimize-whitespace");
7604 }
7605
7606 // -fno-keep-system-includes is default.
7607 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7608 options::OPT_fno_keep_system_includes, false)) {
7609 types::ID InputType = Inputs[0].getType();
7610 if (!isDerivedFromC(InputType))
7611 D.Diag(diag::err_drv_opt_unsupported_input_type)
7612 << "-fkeep-system-includes" << types::getTypeName(InputType);
7613 CmdArgs.push_back("-fkeep-system-includes");
7614 }
7615
7616 // -fms-extensions=0 is default.
7617 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7618 IsWindowsMSVC || IsUEFI))
7619 CmdArgs.push_back("-fms-extensions");
7620
7621 // -fms-compatibility=0 is default.
7622 bool IsMSVCCompat = Args.hasFlag(
7623 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7624 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7625 options::OPT_fno_ms_extensions, true)));
7626 if (IsMSVCCompat) {
7627 CmdArgs.push_back("-fms-compatibility");
7628 if (!types::isCXX(Input.getType()) &&
7629 Args.hasArg(options::OPT_fms_define_stdc))
7630 CmdArgs.push_back("-fms-define-stdc");
7631 }
7632
7633 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7634 // clang and flang.
7635 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7636
7637 // -fms-anonymous-structs is disabled by default.
7638 // Determine whether to enable Microsoft named anonymous struct/union support.
7639 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7640 // where the feature can be:
7641 // - Explicitly enabled via -fms-anonymous-structs.
7642 // - Explicitly disabled via fno-ms-anonymous-structs
7643 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7644 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7645 //
7646 // When multiple relevent options are present, the last option on the command
7647 // line takes precedence. This allows users to selectively override implicit
7648 // enablement. Examples:
7649 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7650 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7651 auto MSAnonymousStructsOptionToUseOrNull =
7652 [](const ArgList &Args) -> const char * {
7653 const char *Option = nullptr;
7654 constexpr const char *Enable = "-fms-anonymous-structs";
7655 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7656
7657 // Iterate through all arguments in order to implement "last flag wins".
7658 for (const Arg *A : Args) {
7659 switch (A->getOption().getID()) {
7660 case options::OPT_fms_anonymous_structs:
7661 A->claim();
7662 Option = Enable;
7663 break;
7664 case options::OPT_fno_ms_anonymous_structs:
7665 A->claim();
7666 Option = Disable;
7667 break;
7668 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7669 // feature.
7670 case options::OPT_fms_extensions:
7671 case options::OPT_fms_compatibility:
7672 Option = Enable;
7673 break;
7674 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7675 // disables the feature.
7676 case options::OPT_fno_ms_extensions:
7677 case options::OPT_fno_ms_compatibility:
7678 Option = Disable;
7679 break;
7680 default:
7681 break;
7682 }
7683 }
7684 return Option;
7685 };
7686
7687 // Only pass a flag to CC1 if a relevant option was seen
7688 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7689 CmdArgs.push_back(MSAnonOpt);
7690
7691 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7692 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7693 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7694
7695 // Handle -fgcc-version, if present.
7696 VersionTuple GNUCVer;
7697 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7698 // Check that the version has 1 to 3 components and the minor and patch
7699 // versions fit in two decimal digits.
7700 StringRef Val = A->getValue();
7701 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7702 bool Invalid = GNUCVer.tryParse(Val);
7703 unsigned Minor = GNUCVer.getMinor().value_or(0);
7704 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7705 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7706 D.Diag(diag::err_drv_invalid_value)
7707 << A->getAsString(Args) << A->getValue();
7708 }
7709 } else if (!IsMSVCCompat) {
7710 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7711 GNUCVer = VersionTuple(4, 2, 1);
7712 }
7713 if (!GNUCVer.empty()) {
7714 CmdArgs.push_back(
7715 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7716 }
7717
7718 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7719 if (!MSVT.empty())
7720 CmdArgs.push_back(
7721 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7722
7723 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7724 if (ImplyVCPPCVer) {
7725 StringRef LanguageStandard;
7726 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7727 Std = StdArg;
7728 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7729 .Case("c11", "-std=c11")
7730 .Case("c17", "-std=c17")
7731 // If you add cases below for spellings that are
7732 // not in LangStandards.def, update
7733 // TransferableCommand::tryParseStdArg() in
7734 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7735 // to match.
7736 // TODO: add c23 when MSVC supports it.
7737 .Case("clatest", "-std=c23")
7738 .Default("");
7739 if (LanguageStandard.empty())
7740 D.Diag(clang::diag::warn_drv_unused_argument)
7741 << StdArg->getAsString(Args);
7742 }
7743 CmdArgs.push_back(LanguageStandard.data());
7744 }
7745 if (ImplyVCPPCXXVer) {
7746 StringRef LanguageStandard;
7747 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7748 Std = StdArg;
7749 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7750 .Case("c++14", "-std=c++14")
7751 .Case("c++17", "-std=c++17")
7752 .Case("c++20", "-std=c++20")
7753 // If you add cases below for spellings that are
7754 // not in LangStandards.def, update
7755 // TransferableCommand::tryParseStdArg() in
7756 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7757 // to match.
7758 // TODO add c++23, c++26, c++29 when MSVC supports
7759 // it.
7760 .Case("c++23preview", "-std=c++23")
7761 .Case("c++26preview", "-std=c++26")
7762 .Case("c++latest", "-std=c++2d")
7763 .Default("");
7764 if (IsSYCL) {
7765 const LangStandard *LangStd =
7766 LangStandard::getLangStandardForName(StdArg->getValue());
7767 if (LangStd) {
7768 // Use of /std: with 'C' is not supported for SYCL.
7769 if (LangStd->getLanguage() == Language::C)
7770 D.Diag(diag::err_drv_argument_not_allowed_with)
7771 << StdArg->getAsString(Args) << "-fsycl";
7772 // SYCL requires C++17 or later.
7773 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7774 D.Diag(diag::err_drv_sycl_requires_cxx17)
7775 << StdArg->getAsString(Args);
7776 }
7777 }
7778 if (LanguageStandard.empty())
7779 D.Diag(clang::diag::warn_drv_unused_argument)
7780 << StdArg->getAsString(Args);
7781 }
7782
7783 if (LanguageStandard.empty()) {
7784 if (IsSYCL)
7785 // For SYCL, C++17 is the default.
7786 LanguageStandard = "-std=c++17";
7787 else if (IsMSVC2015Compatible)
7788 LanguageStandard = "-std=c++14";
7789 else
7790 LanguageStandard = "-std=c++11";
7791 }
7792
7793 CmdArgs.push_back(LanguageStandard.data());
7794 }
7795
7796 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7797 options::OPT_fno_borland_extensions);
7798
7799 // -fno-declspec is default, except for PS4/PS5.
7800 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7801 RawTriple.isPS()))
7802 CmdArgs.push_back("-fdeclspec");
7803 else if (Args.hasArg(options::OPT_fno_declspec))
7804 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7805
7806 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7807 // than 19.
7808 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7809 options::OPT_fno_threadsafe_statics,
7810 !types::isOpenCL(InputType) &&
7811 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7812 CmdArgs.push_back("-fno-threadsafe-statics");
7813
7814 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7815 true))
7816 CmdArgs.push_back("-fno-ms-tls-guards");
7817
7818 // Add -fno-assumptions, if it was specified.
7819 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7820 true))
7821 CmdArgs.push_back("-fno-assumptions");
7822
7823 // -fgnu-keywords default varies depending on language; only pass if
7824 // specified.
7825 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7826 options::OPT_fno_gnu_keywords);
7827
7828 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7829 options::OPT_fno_gnu89_inline);
7830
7831 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7832 options::OPT_finline_hint_functions,
7833 options::OPT_fno_inline_functions);
7834 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7835 if (A->getOption().matches(options::OPT_fno_inline))
7836 A->render(Args, CmdArgs);
7837 } else if (InlineArg) {
7838 InlineArg->render(Args, CmdArgs);
7839 }
7840
7841 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7842
7843 // FIXME: Find a better way to determine whether we are in C++20.
7844 bool HaveCxx20 =
7845 Std &&
7846 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7847 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7848 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7849 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7850 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7851 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7852 Std->containsValue("gnu++26") || Std->containsValue("c++26preview") ||
7853 Std->containsValue("c++2d") || Std->containsValue("gnu++2d") ||
7854 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7855 bool HaveModules =
7856 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7857
7858 // -fdelayed-template-parsing is default when targeting MSVC.
7859 // Many old Windows SDK versions require this to parse.
7860 //
7861 // According to
7862 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7863 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7864 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7865 // not enable -fdelayed-template-parsing by default after C++20.
7866 //
7867 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7868 // able to disable this by default at some point.
7869 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7870 options::OPT_fno_delayed_template_parsing,
7871 IsWindowsMSVC && !HaveCxx20)) {
7872 if (HaveCxx20)
7873 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7874
7875 CmdArgs.push_back("-fdelayed-template-parsing");
7876 }
7877
7878 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7879 options::OPT_fno_pch_validate_input_files_content, false))
7880 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7881 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7882 options::OPT_fno_pch_instantiate_templates, false))
7883 CmdArgs.push_back("-fpch-instantiate-templates");
7884 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7885 false))
7886 CmdArgs.push_back("-fmodules-codegen");
7887 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7888 false))
7889 CmdArgs.push_back("-fmodules-debuginfo");
7890
7891 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7892 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7893 Input, CmdArgs);
7894
7895 if (types::isObjC(Input.getType()) &&
7896 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7897 options::OPT_fno_objc_encode_cxx_class_template_spec,
7898 !Runtime.isNeXTFamily()))
7899 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7900
7901 if (Args.hasFlag(options::OPT_fapplication_extension,
7902 options::OPT_fno_application_extension, false))
7903 CmdArgs.push_back("-fapplication-extension");
7904
7905 // Handle GCC-style exception args.
7906 bool EH = false;
7907 if (!C.getDriver().IsCLMode())
7908 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7909 IsDeviceOffloadAction, Runtime, CmdArgs);
7910
7911 // Handle exception personalities
7912 Arg *A = Args.getLastArg(
7913 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7914 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions,
7915 options::OPT_femscripten_exceptions);
7916 if (A) {
7917 const Option &Opt = A->getOption();
7918 if (Opt.matches(options::OPT_fsjlj_exceptions))
7919 CmdArgs.push_back("-exception-model=sjlj");
7920 if (Opt.matches(options::OPT_fseh_exceptions))
7921 CmdArgs.push_back("-exception-model=seh");
7922 if (Opt.matches(options::OPT_fdwarf_exceptions))
7923 CmdArgs.push_back("-exception-model=dwarf");
7924 if (Opt.matches(options::OPT_fwasm_exceptions))
7925 CmdArgs.push_back("-exception-model=wasm");
7926 if (Opt.matches(options::OPT_femscripten_exceptions))
7927 CmdArgs.push_back("-exception-model=emscripten");
7928 } else {
7929 switch (TC.GetExceptionModel(Args)) {
7930 default:
7931 break;
7932 case llvm::ExceptionHandling::DwarfCFI:
7933 CmdArgs.push_back("-exception-model=dwarf");
7934 break;
7935 case llvm::ExceptionHandling::SjLj:
7936 CmdArgs.push_back("-exception-model=sjlj");
7937 break;
7938 case llvm::ExceptionHandling::WinEH:
7939 CmdArgs.push_back("-exception-model=seh");
7940 break;
7941 }
7942 }
7943
7944 // Unwind information version for x64 Windows.
7945 // Forward the new unified flag if present, otherwise translate legacy flags.
7946 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
7947 A->claim();
7948 CmdArgs.push_back(
7949 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
7950 } else if (const Arg *A =
7951 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
7952 A->claim();
7953 StringRef Val = A->getValue();
7954 if (Val == "best-effort")
7955 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
7956 else if (Val == "required")
7957 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
7958 // "disabled" maps to v1 default, nothing to forward.
7959 else if (Val != "disabled")
7960 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
7961 }
7962
7963 // Control Flow Guard mechanism for Windows.
7964 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
7965
7966 // C++ "sane" operator new.
7967 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7968 options::OPT_fno_assume_sane_operator_new);
7969
7970 // -fassume-unique-vtables is on by default.
7971 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7972 options::OPT_fno_assume_unique_vtables);
7973
7974 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7975 // by default.
7976 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7977 options::OPT_fno_sized_deallocation);
7978
7979 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7980 // by default.
7981 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7982 options::OPT_fno_aligned_allocation,
7983 options::OPT_faligned_new_EQ)) {
7984 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7985 CmdArgs.push_back("-fno-aligned-allocation");
7986 else
7987 CmdArgs.push_back("-faligned-allocation");
7988 }
7989
7990 // The default new alignment can be specified using a dedicated option or via
7991 // a GCC-compatible option that also turns on aligned allocation.
7992 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7993 options::OPT_faligned_new_EQ))
7994 CmdArgs.push_back(
7995 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7996
7997 // -fconstant-cfstrings is default, and may be subject to argument translation
7998 // on Darwin.
7999 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
8000 options::OPT_fno_constant_cfstrings, true) ||
8001 !Args.hasFlag(options::OPT_mconstant_cfstrings,
8002 options::OPT_mno_constant_cfstrings, true))
8003 CmdArgs.push_back("-fno-constant-cfstrings");
8004
8005 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
8006 options::OPT_fno_pascal_strings);
8007
8008 // Honor -fpack-struct= and -fpack-struct, if given. Note that
8009 // -fno-pack-struct doesn't apply to -fpack-struct=.
8010 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
8011 CmdArgs.push_back(
8012 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
8013 } else if (Args.hasFlag(options::OPT_fpack_struct,
8014 options::OPT_fno_pack_struct, false)) {
8015 CmdArgs.push_back("-fpack-struct=1");
8016 }
8017
8018 // Handle -fmax-type-align=N and -fno-type-align
8019 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
8020 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
8021 if (!SkipMaxTypeAlign) {
8022 std::string MaxTypeAlignStr = "-fmax-type-align=";
8023 MaxTypeAlignStr += A->getValue();
8024 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8025 }
8026 } else if (RawTriple.isOSDarwin()) {
8027 if (!SkipMaxTypeAlign) {
8028 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8029 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8030 }
8031 }
8032
8033 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
8034 CmdArgs.push_back("-Qn");
8035
8036 // -fno-common is the default, set -fcommon only when that flag is set.
8037 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
8038
8039 // -fsigned-bitfields is default, and clang doesn't yet support
8040 // -funsigned-bitfields.
8041 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
8042 options::OPT_funsigned_bitfields, true))
8043 D.Diag(diag::warn_drv_clang_unsupported)
8044 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
8045
8046 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8047 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
8048 D.Diag(diag::err_drv_clang_unsupported)
8049 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
8050
8051 // -finput_charset=UTF-8 is default. Reject others
8052 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
8053 StringRef value = inputCharset->getValue();
8054 if (!value.equals_insensitive("utf-8"))
8055 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8056 << value;
8057 }
8058
8059 // -fexec_charset=UTF-8 is default. Reject others
8060 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
8061 StringRef value = execCharset->getValue();
8062 if (!value.equals_insensitive("utf-8"))
8063 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8064 << value;
8065 }
8066
8067 RenderDiagnosticsOptions(D, Args, CmdArgs);
8068
8069 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
8070 options::OPT_fno_asm_blocks);
8071
8072 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
8073 options::OPT_fno_gnu_inline_asm);
8074
8075 handleVectorizeLoopsArgs(Args, CmdArgs);
8076 handleVectorizeSLPArgs(Args, CmdArgs);
8077
8078 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8079 if (!VecWidth.empty())
8080 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8081
8082 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8083 Args.AddLastArg(CmdArgs,
8084 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8085
8086 // -fdollars-in-identifiers default varies depending on platform and
8087 // language; only pass if specified.
8088 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8089 options::OPT_fno_dollars_in_identifiers)) {
8090 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8091 CmdArgs.push_back("-fdollars-in-identifiers");
8092 else
8093 CmdArgs.push_back("-fno-dollars-in-identifiers");
8094 }
8095
8096 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8097 options::OPT_fno_apple_pragma_pack);
8098
8099 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8100 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8101 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8102
8103 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8104 options::OPT_fno_rewrite_imports, false);
8105 if (RewriteImports)
8106 CmdArgs.push_back("-frewrite-imports");
8107
8108 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8109 options::OPT_fno_directives_only);
8110
8111 // Enable rewrite includes if the user's asked for it or if we're generating
8112 // diagnostics.
8113 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8114 // nice to enable this when doing a crashdump for modules as well.
8115 if (Args.hasFlag(options::OPT_frewrite_includes,
8116 options::OPT_fno_rewrite_includes, false) ||
8117 (C.isForDiagnostics() && !HaveModules))
8118 CmdArgs.push_back("-frewrite-includes");
8119
8120 if (Args.hasFlag(options::OPT_fzos_extensions,
8121 options::OPT_fno_zos_extensions, false))
8122 CmdArgs.push_back("-fzos-extensions");
8123 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8124 CmdArgs.push_back("-fno-zos-extensions");
8125
8126 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8127 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8128 options::OPT_traditional_cpp)) {
8130 CmdArgs.push_back("-traditional-cpp");
8131 else
8132 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8133 }
8134
8135 Args.AddLastArg(CmdArgs, options::OPT_dM);
8136 Args.AddLastArg(CmdArgs, options::OPT_dD);
8137 Args.AddLastArg(CmdArgs, options::OPT_dI);
8138
8139 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8140
8141 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8142 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8143 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8144 Args.AddLastArg(CmdArgs, options::OPT__ssaf_include_local_entities);
8145 Args.AddLastArg(CmdArgs, options::OPT__ssaf_no_extract_from_system_headers);
8146 Args.AddLastArg(CmdArgs, options::OPT__ssaf_source_transformation);
8147 Args.AddLastArg(CmdArgs, options::OPT__ssaf_global_scope_analysis_result);
8148 Args.AddLastArg(CmdArgs, options::OPT__ssaf_link_unit_id);
8149 Args.AddLastArg(CmdArgs, options::OPT__ssaf_src_edit_file);
8150 Args.AddLastArg(CmdArgs, options::OPT__ssaf_transformation_report_file);
8151
8152 // Handle serialized diagnostics.
8153 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8154 CmdArgs.push_back("-serialize-diagnostic-file");
8155 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8156 }
8157
8158 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8159 CmdArgs.push_back("-fretain-comments-from-system-headers");
8160
8161 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8162 A->render(Args, CmdArgs);
8163 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8164 A && A->containsValue("g")) {
8165 // Set -fextend-variable-liveness=all by default at -Og.
8166 CmdArgs.push_back("-fextend-variable-liveness=all");
8167 }
8168
8169 // Forward -fcomment-block-commands to -cc1.
8170 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8171 // Forward -fparse-all-comments to -cc1.
8172 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8173 // Forward -fretain-comments to -cc1.
8174 Args.AddAllArgs(CmdArgs, options::OPT_fretain_comments);
8175
8176 // Turn -fplugin=name.so into -load name.so
8177 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8178 CmdArgs.push_back("-load");
8179 CmdArgs.push_back(A->getValue());
8180 A->claim();
8181 }
8182
8183 // Turn -fplugin-arg-pluginname-key=value into
8184 // -plugin-arg-pluginname key=value
8185 // GCC has an actual plugin_argument struct with key/value pairs that it
8186 // passes to its plugins, but we don't, so just pass it on as-is.
8187 //
8188 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8189 // argument key are allowed to contain dashes. GCC therefore only
8190 // allows dashes in the key. We do the same.
8191 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8192 auto ArgValue = StringRef(A->getValue());
8193 auto FirstDashIndex = ArgValue.find('-');
8194 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8195 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8196
8197 A->claim();
8198 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8199 if (PluginName.empty()) {
8200 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8201 } else {
8202 D.Diag(diag::warn_drv_missing_plugin_arg)
8203 << PluginName << A->getAsString(Args);
8204 }
8205 continue;
8206 }
8207
8208 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8209 CmdArgs.push_back(Args.MakeArgString(Arg));
8210 }
8211
8212 // Forward -fpass-plugin=name.so to -cc1.
8213 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8214 CmdArgs.push_back(
8215 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8216 A->claim();
8217 }
8218
8219 // Forward --vfsoverlay to -cc1.
8220 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8221 CmdArgs.push_back("--vfsoverlay");
8222 CmdArgs.push_back(A->getValue());
8223 A->claim();
8224 }
8225
8226 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8227 options::OPT_fno_safe_buffer_usage_suggestions);
8228
8229 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8230 options::OPT_fno_experimental_late_parse_attributes);
8231
8232 if (Args.hasFlag(options::OPT_funique_source_file_names,
8233 options::OPT_fno_unique_source_file_names, false)) {
8234 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8235 A->render(Args, CmdArgs);
8236 else
8237 CmdArgs.push_back(Args.MakeArgString(
8238 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8239 }
8240
8241 if (Args.hasFlag(
8242 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8243 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8244 false) ||
8245 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8246 options::OPT_fno_experimental_pointer_field_protection_abi,
8247 false))
8248 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8249
8250 if (!IsCudaDevice) {
8251 Args.addOptInFlag(
8252 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8253 options::OPT_fno_experimental_pointer_field_protection_abi);
8254 Args.addOptInFlag(
8255 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8256 options::OPT_fno_experimental_pointer_field_protection_tagged);
8257 }
8258
8259 // Setup statistics file output.
8260 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8261 if (!StatsFile.empty()) {
8262 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8264 CmdArgs.push_back("-stats-file-append");
8265 }
8266
8267 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8268 // parser.
8269 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8270 Arg->claim();
8271 // -finclude-default-header flag is for preprocessor,
8272 // do not pass it to other cc1 commands when save-temps is enabled
8273 if (C.getDriver().isSaveTempsEnabled() &&
8275 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8276 continue;
8277 }
8278 CmdArgs.push_back(Arg->getValue());
8279 }
8280 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8281 A->claim();
8282
8283 // We translate this by hand to the -cc1 argument, since nightly test uses
8284 // it and developers have been trained to spell it with -mllvm. Both
8285 // spellings are now deprecated and should be removed.
8286 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8287 CmdArgs.push_back("-disable-llvm-optzns");
8288 } else {
8289 A->render(Args, CmdArgs);
8290 }
8291 }
8292
8293 // This needs to run after -Xclang argument forwarding to pick up the target
8294 // features enabled through -Xclang -target-feature flags.
8295 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8296
8297 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8298
8299#if CLANG_ENABLE_CIR
8300 // Forward -mmlir arguments to to the MLIR option parser.
8301 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8302 A->claim();
8303 A->render(Args, CmdArgs);
8304 }
8305#endif // CLANG_ENABLE_CIR
8306
8307 // With -save-temps, we want to save the unoptimized bitcode output from the
8308 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8309 // by the frontend.
8310 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8311 // has slightly different breakdown between stages.
8312 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8313 // pristine IR generated by the frontend. Ideally, a new compile action should
8314 // be added so both IR can be captured.
8315 if ((C.getDriver().isSaveTempsEnabled() ||
8317 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8319 CmdArgs.push_back("-disable-llvm-passes");
8320
8321 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8322
8323 const char *Exec = D.getDriverProgramPath();
8324
8325 // Optionally embed the -cc1 level arguments into the debug info or a
8326 // section, for build analysis.
8327 // Also record command line arguments into the debug info if
8328 // -grecord-gcc-switches options is set on.
8329 // By default, -gno-record-gcc-switches is set on and no recording.
8330 auto GRecordSwitches = false;
8331 auto FRecordSwitches = false;
8332 bool DXRecordSwitches = false;
8333 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8334 DXRecordSwitches)) {
8335 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8336 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8337 CmdArgs.push_back("-dwarf-debug-flags");
8338 CmdArgs.push_back(FlagsArgString);
8339 }
8340 if (FRecordSwitches) {
8341 CmdArgs.push_back("-record-command-line");
8342 CmdArgs.push_back(FlagsArgString);
8343 }
8344 if (DXRecordSwitches) {
8345 CmdArgs.push_back("-fdx-record-command-line");
8346 CmdArgs.push_back(FlagsArgString);
8347 }
8348 }
8349
8350 // Host-side offloading compilation receives all device-side outputs. Include
8351 // them in the host compilation depending on the target.
8352 if (!HostOffloadingInputs.empty()) {
8353 bool UseOffloadIncludeBinary =
8354 (IsCuda || IsHIP) &&
8355 (!IsRDCMode || Args.hasArg(options::OPT_cuda_emit_nvcc_abi)) &&
8356 !UsesLLVMOffloading;
8357 UseOffloadIncludeBinary |= IsSYCL && !IsRDCMode;
8358 if (UseOffloadIncludeBinary) {
8359 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8360 CmdArgs.push_back("-foffload-include-binary");
8361 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8362 } else {
8363 for (const InputInfo Input : HostOffloadingInputs)
8364 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8365 TC.getInputFilename(Input)));
8366 }
8367 }
8368
8369 if (IsCuda) {
8370 if (Args.hasArg(options::OPT_cuda_emit_nvcc_abi))
8371 CmdArgs.push_back("--cuda-emit-nvcc-abi");
8372 }
8373
8374 if (IsCuda || IsHIP) {
8375 // Determine the original source input.
8376 const Action *SourceAction = &JA;
8377 while (SourceAction->getKind() != Action::InputClass) {
8378 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8379 SourceAction = SourceAction->getInputs()[0];
8380 }
8381 auto CUID = cast<InputAction>(SourceAction)->getId();
8382 if (!CUID.empty())
8383 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8384
8385 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8386 // be overriden by -fno-gpu-approx-transcendentals.
8387 bool UseApproxTranscendentals = Args.hasFlag(
8388 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8389 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8390 options::OPT_fno_gpu_approx_transcendentals,
8391 UseApproxTranscendentals))
8392 CmdArgs.push_back("-fgpu-approx-transcendentals");
8393 } else {
8394 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8395 options::OPT_fno_gpu_approx_transcendentals);
8396 }
8397
8398 if (IsHIP) {
8399 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8400 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8401 }
8402
8403 Args.AddAllArgs(CmdArgs,
8404 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8405
8406 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8407 options::OPT_fno_offload_uniform_block);
8408
8409 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8410 options::OPT_fno_offload_implicit_host_device_templates);
8411
8412 if (IsCudaDevice || IsHIPDevice) {
8413 StringRef InlineThresh =
8414 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8415 if (!InlineThresh.empty()) {
8416 std::string ArgStr =
8417 std::string("-inline-threshold=") + InlineThresh.str();
8418 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8419 }
8420 }
8421
8422 if (IsHIPDevice)
8423 Args.addOptOutFlag(CmdArgs,
8424 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8425 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8426
8427 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8428 // to specify the result of the compile phase on the host, so the meaningful
8429 // device declarations can be identified. Also, -fopenmp-is-target-device is
8430 // passed along to tell the frontend that it is generating code for a device,
8431 // so that only the relevant declarations are emitted.
8432 if (IsOpenMPDevice) {
8433 CmdArgs.push_back("-fopenmp-is-target-device");
8434 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8435 if (Args.hasArg(options::OPT_foffload_via_llvm))
8436 CmdArgs.push_back("-fcuda-is-device");
8437
8438 if (OpenMPDeviceInput) {
8439 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8440 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8441 }
8442 }
8443
8444 if (Triple.isAMDGPU() ||
8445 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8446 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8447
8448 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8449 options::OPT_mno_unsafe_fp_atomics);
8450 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8451 options::OPT_mno_amdgpu_ieee);
8452 }
8453
8454 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8455
8456 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8457 options::OPT_fno_devirtualize_speculatively,
8458 /*Default value*/ false))
8459 CmdArgs.push_back("-fdevirtualize-speculatively");
8460
8461 bool VirtualFunctionElimination =
8462 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8463 options::OPT_fno_virtual_function_elimination, false);
8464 if (VirtualFunctionElimination) {
8465 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8466 // in the future).
8467 if (LTOMode != LTOK_Full)
8468 D.Diag(diag::err_drv_argument_only_allowed_with)
8469 << "-fvirtual-function-elimination"
8470 << "-flto=full";
8471
8472 CmdArgs.push_back("-fvirtual-function-elimination");
8473 }
8474
8475 // VFE requires whole-program-vtables, and enables it by default.
8476 bool WholeProgramVTables = Args.hasFlag(
8477 options::OPT_fwhole_program_vtables,
8478 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8479 if (VirtualFunctionElimination && !WholeProgramVTables) {
8480 D.Diag(diag::err_drv_argument_not_allowed_with)
8481 << "-fno-whole-program-vtables"
8482 << "-fvirtual-function-elimination";
8483 }
8484
8485 if (WholeProgramVTables) {
8486 // PS4 uses the legacy LTO API, which does not support this feature in
8487 // ThinLTO mode.
8488 bool IsPS4 = getToolChain().getTriple().isPS4();
8489
8490 // Check if we passed LTO options but they were suppressed because this is a
8491 // device offloading action, or we passed device offload LTO options which
8492 // were suppressed because this is not the device offload action.
8493 // Check if we are using PS4 in regular LTO mode.
8494 // Otherwise, issue an error.
8495
8496 auto OtherLTOMode = TC.getLTOMode(
8497 Args, IsDeviceOffloadAction ? Action::OFK_None
8498 : static_cast<Action::OffloadKind>(
8499 C.getActiveOffloadKinds()));
8500 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8501
8502 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8503 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8504 D.Diag(diag::err_drv_argument_only_allowed_with)
8505 << "-fwhole-program-vtables"
8506 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8507
8508 // Propagate -fwhole-program-vtables if this is an LTO compile.
8509 if (IsUsingLTO)
8510 CmdArgs.push_back("-fwhole-program-vtables");
8511 }
8512
8513 bool DefaultsSplitLTOUnit =
8514 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8515 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8516 (!Triple.isPS4() && UnifiedLTO);
8517 bool SplitLTOUnit =
8518 Args.hasFlag(options::OPT_fsplit_lto_unit,
8519 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8520 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8521 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8522 << "-fsanitize=cfi";
8523 if (SplitLTOUnit)
8524 CmdArgs.push_back("-fsplit-lto-unit");
8525
8526 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8527 options::OPT_fno_fat_lto_objects)) {
8528 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8529 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8530 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8531 D.Diag(diag::err_drv_unsupported_opt_for_target)
8532 << A->getAsString(Args) << TC.getTripleString();
8533 }
8534 CmdArgs.push_back(Args.MakeArgString(
8535 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8536 CmdArgs.push_back("-flto-unit");
8537 CmdArgs.push_back("-ffat-lto-objects");
8538 A->render(Args, CmdArgs);
8539 }
8540 }
8541
8542 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8543
8544 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8545 options::OPT_fno_force_enable_int128)) {
8546 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8547 CmdArgs.push_back("-fforce-enable-int128");
8548 }
8549
8550 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8551 options::OPT_fno_keep_static_consts);
8552 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8553 options::OPT_fno_keep_persistent_storage_variables);
8554 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_inline_functions,
8555 options::OPT_fno_keep_inline_functions);
8556 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8557 options::OPT_fno_complete_member_pointers);
8558 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8559 A->render(Args, CmdArgs);
8560
8561 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8562
8563 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8564
8565 if (Triple.isAArch64() &&
8566 (Args.hasArg(options::OPT_mno_fmv) ||
8567 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8568 // Disable Function Multiversioning on AArch64 target.
8569 CmdArgs.push_back("-target-feature");
8570 CmdArgs.push_back("-fmv");
8571 }
8572
8573 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8574 (TC.getTriple().isOSBinFormatELF() ||
8575 TC.getTriple().isOSBinFormatCOFF()) &&
8576 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8577 !TC.getTriple().isOSNetBSD() &&
8578 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8579 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8580 CmdArgs.push_back("-faddrsig");
8581
8582 const bool HasDefaultDwarf2CFIASM =
8583 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8584 (EH || UnwindTables || AsyncUnwindTables ||
8585 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8586 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8587 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8588 CmdArgs.push_back("-fdwarf2-cfi-asm");
8589
8590 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8591 std::string Str = A->getAsString(Args);
8592 if (!TC.getTriple().isOSBinFormatELF())
8593 D.Diag(diag::err_drv_unsupported_opt_for_target)
8594 << Str << TC.getTripleString();
8595 CmdArgs.push_back(Args.MakeArgString(Str));
8596 }
8597
8598 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8599 // the -cc1 command easier to edit when reproducing compiler crashes.
8600 if (Output.getType() == types::TY_Dependencies) {
8601 // Handled with other dependency code.
8602 } else if (Output.isFilename()) {
8603 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8604 Output.getType() == clang::driver::types::TY_IFS) {
8605 SmallString<128> OutputFilename(Output.getFilename());
8606 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8607 CmdArgs.push_back("-o");
8608 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8609 } else {
8610 CmdArgs.push_back("-o");
8611 CmdArgs.push_back(Output.getFilename());
8612 }
8613 } else {
8614 assert(Output.isNothing() && "Invalid output.");
8615 }
8616
8617 addDashXForInput(Args, Input, CmdArgs);
8618
8619 ArrayRef<InputInfo> FrontendInputs = Input;
8620 if (IsExtractAPI)
8621 FrontendInputs = ExtractAPIInputs;
8622 else if (Input.isNothing())
8623 FrontendInputs = {};
8624
8625 for (const InputInfo &Input : FrontendInputs) {
8626 if (Input.isFilename())
8627 CmdArgs.push_back(Input.getFilename());
8628 else
8629 Input.getInputArg().renderAsInput(Args, CmdArgs);
8630 }
8631
8632 if (D.CC1Main && !D.CCGenDiagnostics) {
8633 // Invoke the CC1 directly in this process
8634 C.addCommand(std::make_unique<CC1Command>(
8635 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8636 Output, D.getPrependArg()));
8637 } else {
8638 C.addCommand(std::make_unique<Command>(
8639 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8640 Output, D.getPrependArg()));
8641 }
8642
8643 // Make the compile command echo its inputs for /showFilenames.
8644 if (Output.getType() == types::TY_Object &&
8645 Args.hasFlag(options::OPT__SLASH_showFilenames,
8646 options::OPT__SLASH_showFilenames_, false)) {
8647 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8648 }
8649
8650 if (Arg *A = Args.getLastArg(options::OPT_pg))
8651 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8652 !Args.hasArg(options::OPT_mfentry))
8653 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8654 << A->getAsString(Args);
8655
8656 // Claim some arguments which clang supports automatically.
8657
8658 // -fpch-preprocess is used with gcc to add a special marker in the output to
8659 // include the PCH file.
8660 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8661
8662 // Claim some arguments which clang doesn't support, but we don't
8663 // care to warn the user about.
8664 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8665 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8666
8667 // Disable warnings for clang -E -emit-llvm foo.c
8668 Args.ClaimAllArgs(options::OPT_emit_llvm);
8669}
8670
8671Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8672 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8673 // as it is for other tools. Some operations on a Tool actually test
8674 // whether that tool is Clang based on the Tool's Name as a string.
8675 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8676
8678
8679/// Add options related to the Objective-C runtime/ABI.
8680///
8681/// Returns true if the runtime is non-fragile.
8682ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8683 const InputInfoList &inputs,
8684 ArgStringList &cmdArgs,
8685 RewriteKind rewriteKind) const {
8686 // Look for the controlling runtime option.
8687 Arg *runtimeArg =
8688 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8689 options::OPT_fobjc_runtime_EQ);
8690
8691 // Just forward -fobjc-runtime= to the frontend. This supercedes
8692 // options about fragility.
8693 if (runtimeArg &&
8694 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8695 ObjCRuntime runtime;
8696 StringRef value = runtimeArg->getValue();
8697 if (runtime.tryParse(value)) {
8698 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8699 << value;
8700 }
8701 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8702 (runtime.getVersion() >= VersionTuple(2, 0)))
8703 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8704 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8705 !getToolChain().getTriple().isOSBinFormatWasm()) {
8707 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8708 << runtime.getVersion().getMajor();
8709 }
8710
8711 runtimeArg->render(args, cmdArgs);
8712 return runtime;
8713 }
8714
8715 // Otherwise, we'll need the ABI "version". Version numbers are
8716 // slightly confusing for historical reasons:
8717 // 1 - Traditional "fragile" ABI
8718 // 2 - Non-fragile ABI, version 1
8719 // 3 - Non-fragile ABI, version 2
8720 unsigned objcABIVersion = 1;
8721 // If -fobjc-abi-version= is present, use that to set the version.
8722 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8723 StringRef value = abiArg->getValue();
8724 if (value == "1")
8725 objcABIVersion = 1;
8726 else if (value == "2")
8727 objcABIVersion = 2;
8728 else if (value == "3")
8729 objcABIVersion = 3;
8730 else
8731 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8732 } else {
8733 // Otherwise, determine if we are using the non-fragile ABI.
8734 bool nonFragileABIIsDefault =
8735 (rewriteKind == RK_NonFragile ||
8736 (rewriteKind == RK_None &&
8738 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8739 options::OPT_fno_objc_nonfragile_abi,
8740 nonFragileABIIsDefault)) {
8741// Determine the non-fragile ABI version to use.
8742#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8743 unsigned nonFragileABIVersion = 1;
8744#else
8745 unsigned nonFragileABIVersion = 2;
8746#endif
8747
8748 if (Arg *abiArg =
8749 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8750 StringRef value = abiArg->getValue();
8751 if (value == "1")
8752 nonFragileABIVersion = 1;
8753 else if (value == "2")
8754 nonFragileABIVersion = 2;
8755 else
8756 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8757 << value;
8758 }
8759
8760 objcABIVersion = 1 + nonFragileABIVersion;
8761 } else {
8762 objcABIVersion = 1;
8763 }
8764 }
8765
8766 // We don't actually care about the ABI version other than whether
8767 // it's non-fragile.
8768 bool isNonFragile = objcABIVersion != 1;
8769
8770 // If we have no runtime argument, ask the toolchain for its default runtime.
8771 // However, the rewriter only really supports the Mac runtime, so assume that.
8772 ObjCRuntime runtime;
8773 if (!runtimeArg) {
8774 switch (rewriteKind) {
8775 case RK_None:
8776 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8777 break;
8778 case RK_Fragile:
8779 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8780 break;
8781 case RK_NonFragile:
8782 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8783 break;
8784 }
8785
8786 // -fnext-runtime
8787 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8788 // On Darwin, make this use the default behavior for the toolchain.
8789 if (getToolChain().getTriple().isOSDarwin()) {
8790 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8791
8792 // Otherwise, build for a generic macosx port.
8793 } else {
8794 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8795 }
8796
8797 // -fgnu-runtime
8798 } else {
8799 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8800 // Legacy behaviour is to target the gnustep runtime if we are in
8801 // non-fragile mode or the GCC runtime in fragile mode.
8802 if (isNonFragile)
8803 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8804 else
8805 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8806 }
8807
8808 if (llvm::any_of(inputs, [](const InputInfo &input) {
8809 return types::isObjC(input.getType());
8810 }))
8811 cmdArgs.push_back(
8812 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8813 return runtime;
8814}
8815
8816static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8817 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8818 I += HaveDash;
8819 return !HaveDash;
8820}
8821
8822namespace {
8823struct EHFlags {
8824 bool Synch = false;
8825 bool Asynch = false;
8826 bool NoUnwindC = false;
8827};
8828} // end anonymous namespace
8829
8830/// /EH controls whether to run destructor cleanups when exceptions are
8831/// thrown. There are three modifiers:
8832/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8833/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8834/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8835/// - c: Assume that extern "C" functions are implicitly nounwind.
8836/// The default is /EHs-c-, meaning cleanups are disabled.
8837static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8838 bool isWindowsMSVC) {
8839 EHFlags EH;
8840
8841 std::vector<std::string> EHArgs =
8842 Args.getAllArgValues(options::OPT__SLASH_EH);
8843 for (const auto &EHVal : EHArgs) {
8844 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8845 switch (EHVal[I]) {
8846 case 'a':
8847 EH.Asynch = maybeConsumeDash(EHVal, I);
8848 if (EH.Asynch) {
8849 // Async exceptions are Windows MSVC only.
8850 if (!isWindowsMSVC) {
8851 EH.Asynch = false;
8852 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8853 continue;
8854 }
8855 EH.Synch = false;
8856 }
8857 continue;
8858 case 'c':
8859 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8860 continue;
8861 case 's':
8862 EH.Synch = maybeConsumeDash(EHVal, I);
8863 if (EH.Synch)
8864 EH.Asynch = false;
8865 continue;
8866 default:
8867 break;
8868 }
8869 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8870 break;
8871 }
8872 }
8873 // The /GX, /GX- flags are only processed if there are not /EH flags.
8874 // The default is that /GX is not specified.
8875 if (EHArgs.empty() &&
8876 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8877 /*Default=*/false)) {
8878 EH.Synch = true;
8879 EH.NoUnwindC = true;
8880 }
8881
8882 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8883 EH.Synch = false;
8884 EH.NoUnwindC = false;
8885 EH.Asynch = false;
8886 }
8887
8888 return EH;
8889}
8890
8891void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8892 ArgStringList &CmdArgs) const {
8893 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8894
8895 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8896
8897 if (Arg *ShowIncludes =
8898 Args.getLastArg(options::OPT__SLASH_showIncludes,
8899 options::OPT__SLASH_showIncludes_user)) {
8900 CmdArgs.push_back("--show-includes");
8901 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8902 CmdArgs.push_back("-sys-header-deps");
8903 }
8904
8905 // This controls whether or not we emit RTTI data for polymorphic types.
8906 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8907 /*Default=*/false))
8908 CmdArgs.push_back("-fno-rtti-data");
8909
8910 // This controls whether or not we emit stack-protector instrumentation.
8911 // In MSVC, Buffer Security Check (/GS) is on by default.
8912 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8913 /*Default=*/true)) {
8914 CmdArgs.push_back("-stack-protector");
8915 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8916 }
8917
8918 const Driver &D = getToolChain().getDriver();
8919
8920 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8921 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8922 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8923 if (types::isCXX(InputType))
8924 CmdArgs.push_back("-fcxx-exceptions");
8925 CmdArgs.push_back("-fexceptions");
8926 if (EH.Asynch)
8927 CmdArgs.push_back("-fasync-exceptions");
8928 }
8929 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8930 CmdArgs.push_back("-fexternc-nounwind");
8931
8932 // /EP should expand to -E -P.
8933 if (Args.hasArg(options::OPT__SLASH_EP)) {
8934 CmdArgs.push_back("-E");
8935 CmdArgs.push_back("-P");
8936 }
8937
8938 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8939 options::OPT__SLASH_Zc_dllexportInlines,
8940 false)) {
8941 CmdArgs.push_back("-fno-dllexport-inlines");
8942 }
8943
8944 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8945 options::OPT__SLASH_Zc_wchar_t, false)) {
8946 CmdArgs.push_back("-fno-wchar");
8947 }
8948
8949 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8950 llvm::Triple::ArchType Arch = getToolChain().getArch();
8951 std::vector<std::string> Values =
8952 Args.getAllArgValues(options::OPT__SLASH_arch);
8953 if (!Values.empty()) {
8954 llvm::SmallSet<std::string, 4> SupportedArches;
8955 if (Arch == llvm::Triple::x86)
8956 SupportedArches.insert("IA32");
8957
8958 for (auto &V : Values)
8959 if (!SupportedArches.contains(V))
8960 D.Diag(diag::err_drv_argument_not_allowed_with)
8961 << std::string("/arch:").append(V) << "/kernel";
8962 }
8963
8964 CmdArgs.push_back("-fno-rtti");
8965 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8966 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8967 << "/kernel";
8968 }
8969
8970 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
8971 options::OPT__SLASH_vlen_EQ_256,
8972 options::OPT__SLASH_vlen_EQ_512)) {
8973 llvm::Triple::ArchType AT = getToolChain().getArch();
8974 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8975 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
8976 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8977 "AVX10.2"};
8978
8979 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
8980 if (Arch512.contains(Arch))
8981 CmdArgs.push_back("-mprefer-vector-width=512");
8982 else
8983 D.Diag(diag::warn_drv_argument_not_allowed_with)
8984 << "/vlen=512" << std::string("/arch:").append(Arch);
8985 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
8986 if (Arch512.contains(Arch))
8987 CmdArgs.push_back("-mprefer-vector-width=256");
8988 else if (Arch != "AVX" && Arch != "AVX2")
8989 D.Diag(diag::warn_drv_argument_not_allowed_with)
8990 << "/vlen=256" << std::string("/arch:").append(Arch);
8991 } else {
8992 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8993 CmdArgs.push_back("-mprefer-vector-width=256");
8994 }
8995 } else {
8996 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
8997 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8998 CmdArgs.push_back("-mprefer-vector-width=256");
8999 CmdArgs.push_back("-target-feature");
9000 CmdArgs.push_back("-amx-tile");
9001 }
9002 if (Arch == "AVX10.2") {
9003 CmdArgs.push_back("-target-feature");
9004 CmdArgs.push_back("+avx10.2");
9005 }
9006 }
9007
9008 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
9009 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
9010 if (MostGeneralArg && BestCaseArg)
9011 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9012 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
9013
9014 if (MostGeneralArg) {
9015 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
9016 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
9017 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
9018
9019 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9020 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9021 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9022 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9023 << FirstConflict->getAsString(Args)
9024 << SecondConflict->getAsString(Args);
9025
9026 if (SingleArg)
9027 CmdArgs.push_back("-fms-memptr-rep=single");
9028 else if (MultipleArg)
9029 CmdArgs.push_back("-fms-memptr-rep=multiple");
9030 else
9031 CmdArgs.push_back("-fms-memptr-rep=virtual");
9032 }
9033
9034 if (Args.hasArg(options::OPT_regcall4))
9035 CmdArgs.push_back("-regcall4");
9036
9037 // Parse the default calling convention options.
9038 if (Arg *CCArg =
9039 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
9040 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
9041 options::OPT__SLASH_Gregcall)) {
9042 unsigned DCCOptId = CCArg->getOption().getID();
9043 const char *DCCFlag = nullptr;
9044 bool ArchSupported = !isNVPTX;
9045 llvm::Triple::ArchType Arch = getToolChain().getArch();
9046 switch (DCCOptId) {
9047 case options::OPT__SLASH_Gd:
9048 DCCFlag = "-fdefault-calling-conv=cdecl";
9049 break;
9050 case options::OPT__SLASH_Gr:
9051 ArchSupported = Arch == llvm::Triple::x86;
9052 DCCFlag = "-fdefault-calling-conv=fastcall";
9053 break;
9054 case options::OPT__SLASH_Gz:
9055 ArchSupported = Arch == llvm::Triple::x86;
9056 DCCFlag = "-fdefault-calling-conv=stdcall";
9057 break;
9058 case options::OPT__SLASH_Gv:
9059 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9060 DCCFlag = "-fdefault-calling-conv=vectorcall";
9061 break;
9062 case options::OPT__SLASH_Gregcall:
9063 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9064 DCCFlag = "-fdefault-calling-conv=regcall";
9065 break;
9066 }
9067
9068 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9069 if (ArchSupported && DCCFlag)
9070 CmdArgs.push_back(DCCFlag);
9071 }
9072
9073 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
9074 CmdArgs.push_back("-regcall4");
9075
9076 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
9077
9078 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
9079 CmdArgs.push_back("-fdiagnostics-format");
9080 CmdArgs.push_back("msvc");
9081 }
9082
9083 if (Args.hasArg(options::OPT__SLASH_kernel))
9084 CmdArgs.push_back("-fms-kernel");
9085
9086 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9087 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9088 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9089 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9090 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9091 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9092
9093 // Handle the various /guard options. We don't immediately push back clang
9094 // args since there are /d2 args that can modify the behavior of /guard:cf.
9095 bool HasCFGuard = false;
9096 bool HasCFGuardNoChecks = false;
9097 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9098 StringRef GuardArgs = A->getValue();
9099 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9100 // "ehcont-".
9101 if (GuardArgs.equals_insensitive("cf")) {
9102 // Emit CFG instrumentation and the table of address-taken functions.
9103 HasCFGuard = true;
9104 HasCFGuardNoChecks = false;
9105 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9106 // Emit only the table of address-taken functions.
9107 HasCFGuard = false;
9108 HasCFGuardNoChecks = true;
9109 } else if (GuardArgs.equals_insensitive("ehcont")) {
9110 // Emit EH continuation table.
9111 CmdArgs.push_back("-ehcontguard");
9112 } else if (GuardArgs.equals_insensitive("cf-") ||
9113 GuardArgs.equals_insensitive("ehcont-")) {
9114 // Do nothing, but we might want to emit a security warning in future.
9115 } else {
9116 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9117 }
9118 A->claim();
9119 }
9120
9121 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9122 // If CFG is not enabled, it is a no-op.
9123 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9124 if (HasCFGuard) {
9125 HasCFGuard = false;
9126 HasCFGuardNoChecks = true;
9127 }
9128 }
9129
9130 if (HasCFGuard)
9131 CmdArgs.push_back("-cfguard");
9132 else if (HasCFGuardNoChecks)
9133 CmdArgs.push_back("-cfguard-no-checks");
9134
9135 // Control Flow Guard mechanism for Windows.
9136 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9137 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9138 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9139 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9140
9141 for (const auto &FuncOverride :
9142 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9143 CmdArgs.push_back(Args.MakeArgString(
9144 Twine("-loader-replaceable-function=") + FuncOverride));
9145 }
9146
9147 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9148 CmdArgs.push_back("-Wdate-time");
9149
9150 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9151 D.Diag(diag::err_drv_argument_not_allowed_with)
9152 << "/experimental:deterministic"
9153 << "/Brepro-";
9154 }
9155 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9156 // deterministic result, but we force this timestamp to 0, which also
9157 // produces deterministic result.
9158 CmdArgs.push_back("-mno-incremental-linker-compatible");
9159 }
9160
9161 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9162 options::OPT__SLASH_d1nodatetime_, false);
9163
9164 if (HasNoDateTime)
9165 CmdArgs.push_back("-init-datetime-macros=undefined");
9166
9167 // /Brepro is an alias for -mincremental-linker-compatible option.
9168 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9169 options::OPT_mno_incremental_linker_compatible,
9170 getToolChain()
9171 .getTriple()
9172 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9173 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9174 // This option does not allow the user redefinitions for these macros.
9175 if (!HasNoDateTime)
9176 CmdArgs.push_back("-init-datetime-macros=literalone");
9177 }
9178}
9179
9180const char *Clang::getBaseInputName(const ArgList &Args,
9181 const InputInfo &Input) {
9182 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9183}
9184
9185const char *Clang::getBaseInputStem(const ArgList &Args,
9186 const InputInfoList &Inputs) {
9187 const char *Str = getBaseInputName(Args, Inputs[0]);
9188
9189 if (const char *End = strrchr(Str, '.'))
9190 return Args.MakeArgString(std::string(Str, End));
9191
9192 return Str;
9193}
9194
9195const char *Clang::getDependencyFileName(const ArgList &Args,
9196 const InputInfoList &Inputs) {
9197 // FIXME: Think about this more.
9198
9199 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9200 SmallString<128> OutputFilename(OutputOpt->getValue());
9201 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9202 return Args.MakeArgString(OutputFilename);
9203 }
9204
9205 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9206}
9207
9208// Begin ClangAs
9209
9210void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9211 ArgStringList &CmdArgs) const {
9212 StringRef CPUName;
9213 StringRef ABIName;
9214 const llvm::Triple &Triple = getToolChain().getTriple();
9215 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9216
9217 CmdArgs.push_back("-target-abi");
9218 CmdArgs.push_back(ABIName.data());
9219}
9220
9221void ClangAs::AddX86TargetArgs(const ArgList &Args,
9222 ArgStringList &CmdArgs) const {
9223 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9224 /*IsLTO=*/false);
9225
9226 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9227 StringRef Value = A->getValue();
9228 if (Value == "intel" || Value == "att") {
9229 CmdArgs.push_back("-mllvm");
9230 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9231 } else {
9232 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9233 << A->getSpelling() << Value;
9234 }
9235 }
9236}
9237
9238void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9239 ArgStringList &CmdArgs) const {
9240 CmdArgs.push_back("-target-abi");
9241 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9243 .data());
9244}
9245
9246void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9247 ArgStringList &CmdArgs) const {
9248 const llvm::Triple &Triple = getToolChain().getTriple();
9249 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9250
9251 CmdArgs.push_back("-target-abi");
9252 CmdArgs.push_back(ABIName.data());
9253
9254 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9255 options::OPT_mno_default_build_attributes, true)) {
9256 CmdArgs.push_back("-mllvm");
9257 CmdArgs.push_back("-riscv-add-build-attributes");
9258 }
9259}
9260
9262 const InputInfo &Output, const InputInfoList &Inputs,
9263 const ArgList &Args,
9264 const char *LinkingOutput) const {
9265 ArgStringList CmdArgs;
9266
9267 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9268 const InputInfo &Input = Inputs[0];
9269
9270 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9271 const std::string &TripleStr = Triple.getTriple();
9272 const auto &D = getToolChain().getDriver();
9273
9274 // Don't warn about "clang -w -c foo.s"
9275 Args.ClaimAllArgs(options::OPT_w);
9276 // and "clang -emit-llvm -c foo.s"
9277 Args.ClaimAllArgs(options::OPT_emit_llvm);
9278
9279 claimNoWarnArgs(Args);
9280
9281 // Invoke ourselves in -cc1as mode.
9282 //
9283 // FIXME: Implement custom jobs for internal actions.
9284 CmdArgs.push_back("-cc1as");
9285
9286 // Add the "effective" target triple.
9287 CmdArgs.push_back("-triple");
9288 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9289
9291
9292 // Set the output mode, we currently only expect to be used as a real
9293 // assembler.
9294 CmdArgs.push_back("-filetype");
9295 CmdArgs.push_back("obj");
9296
9297 // Set the main file name, so that debug info works even with
9298 // -save-temps or preprocessed assembly.
9299 CmdArgs.push_back("-main-file-name");
9300 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9301
9302 // Add the target cpu
9303 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9304 if (!CPU.empty()) {
9305 CmdArgs.push_back("-target-cpu");
9306 CmdArgs.push_back(Args.MakeArgString(CPU));
9307 }
9308
9309 // Add the target features
9310 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9311
9312 // Ignore explicit -force_cpusubtype_ALL option.
9313 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9314
9315 // Pass along any -I options so we get proper .include search paths.
9316 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9317
9318 // Pass along any --embed-dir or similar options so we get proper embed paths.
9319 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9320
9321 // Determine the original source input.
9322 auto FindSource = [](const Action *S) -> const Action * {
9323 while (S->getKind() != Action::InputClass) {
9324 assert(!S->getInputs().empty() && "unexpected root action!");
9325 S = S->getInputs()[0];
9326 }
9327 return S;
9328 };
9329 const Action *SourceAction = FindSource(&JA);
9330
9331 // Forward -g and handle debug info related flags, assuming we are dealing
9332 // with an actual assembly file.
9333 bool WantDebug = false;
9334 Args.ClaimAllArgs(options::OPT_g_Group);
9335 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9336 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9337 !A->getOption().matches(options::OPT_ggdb0);
9338
9339 // If a -gdwarf argument appeared, remember it.
9340 bool EmitDwarf = false;
9341 if (const Arg *A = getDwarfNArg(Args))
9342 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9343
9344 bool EmitCodeView = false;
9345 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9346 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9347
9348 // If the user asked for debug info but did not explicitly specify -gcodeview
9349 // or -gdwarf, ask the toolchain for the default format.
9350 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9351 switch (getToolChain().getDefaultDebugFormat()) {
9352 case llvm::codegenoptions::DIF_CodeView:
9353 EmitCodeView = true;
9354 break;
9355 case llvm::codegenoptions::DIF_DWARF:
9356 EmitDwarf = true;
9357 break;
9358 }
9359 }
9360
9361 // If the arguments don't imply DWARF, don't emit any debug info here.
9362 if (!EmitDwarf)
9363 WantDebug = false;
9364
9365 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9366 llvm::codegenoptions::NoDebugInfo;
9367
9368 // Add the -fdebug-compilation-dir flag if needed.
9369 const char *DebugCompilationDir =
9370 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9371
9372 if (SourceAction->getType() == types::TY_Asm ||
9373 SourceAction->getType() == types::TY_PP_Asm) {
9374 // You might think that it would be ok to set DebugInfoKind outside of
9375 // the guard for source type, however there is a test which asserts
9376 // that some assembler invocation receives no -debug-info-kind,
9377 // and it's not clear whether that test is just overly restrictive.
9378 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9379 : llvm::codegenoptions::NoDebugInfo);
9380
9381 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9382 CmdArgs);
9383
9384 // Set the AT_producer to the clang version when using the integrated
9385 // assembler on assembly source files.
9386 CmdArgs.push_back("-dwarf-debug-producer");
9387 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9388
9389 // And pass along -I options
9390 Args.AddAllArgs(CmdArgs, options::OPT_I);
9391 }
9392 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9393 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9394 llvm::DebuggerKind::Default);
9395 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9396 renderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9397
9398 // Handle -fPIC et al -- the relocation-model affects the assembler
9399 // for some targets.
9400 llvm::Reloc::Model RelocationModel;
9401 unsigned PICLevel;
9402 bool IsPIE;
9403 std::tie(RelocationModel, PICLevel, IsPIE) =
9404 ParsePICArgs(getToolChain(), Args);
9405
9406 const char *RMName = RelocationModelName(RelocationModel);
9407 if (RMName) {
9408 CmdArgs.push_back("-mrelocation-model");
9409 CmdArgs.push_back(RMName);
9410 }
9411
9412 // Optionally embed the -cc1as level arguments into the debug info, for build
9413 // analysis.
9414 if (getToolChain().UseDwarfDebugFlags()) {
9415 ArgStringList OriginalArgs;
9416 for (const auto &Arg : Args)
9417 Arg->render(Args, OriginalArgs);
9418
9419 SmallString<256> Flags;
9420 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9421 escapeSpacesAndBackslashes(Exec, Flags);
9422 for (const char *OriginalArg : OriginalArgs) {
9423 SmallString<128> EscapedArg;
9424 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9425 Flags += " ";
9426 Flags += EscapedArg;
9427 }
9428 CmdArgs.push_back("-dwarf-debug-flags");
9429 CmdArgs.push_back(Args.MakeArgString(Flags));
9430 }
9431
9432 // FIXME: Add -static support, once we have it.
9433
9434 // Add target specific flags.
9435 switch (getToolChain().getArch()) {
9436 default:
9437 break;
9438
9439 case llvm::Triple::mips:
9440 case llvm::Triple::mipsel:
9441 case llvm::Triple::mips64:
9442 case llvm::Triple::mips64el:
9443 AddMIPSTargetArgs(Args, CmdArgs);
9444 break;
9445
9446 case llvm::Triple::x86:
9447 case llvm::Triple::x86_64:
9448 AddX86TargetArgs(Args, CmdArgs);
9449 break;
9450
9451 case llvm::Triple::arm:
9452 case llvm::Triple::armeb:
9453 case llvm::Triple::thumb:
9454 case llvm::Triple::thumbeb:
9455 // This isn't in AddARMTargetArgs because we want to do this for assembly
9456 // only, not C/C++.
9457 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9458 options::OPT_mno_default_build_attributes, true)) {
9459 CmdArgs.push_back("-mllvm");
9460 CmdArgs.push_back("-arm-add-build-attributes");
9461 }
9462 break;
9463
9464 case llvm::Triple::aarch64:
9465 case llvm::Triple::aarch64_32:
9466 case llvm::Triple::aarch64_be:
9467 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9468 CmdArgs.push_back("-mllvm");
9469 CmdArgs.push_back("-aarch64-mark-bti-property");
9470 }
9471 break;
9472
9473 case llvm::Triple::loongarch32:
9474 case llvm::Triple::loongarch64:
9475 AddLoongArchTargetArgs(Args, CmdArgs);
9476 break;
9477
9478 case llvm::Triple::riscv32:
9479 case llvm::Triple::riscv64:
9480 case llvm::Triple::riscv32be:
9481 case llvm::Triple::riscv64be:
9482 AddRISCVTargetArgs(Args, CmdArgs);
9483 break;
9484
9485 case llvm::Triple::hexagon:
9486 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9487 options::OPT_mno_default_build_attributes, true)) {
9488 CmdArgs.push_back("-mllvm");
9489 CmdArgs.push_back("-hexagon-add-build-attributes");
9490 }
9491 break;
9492 }
9493
9494 // Consume all the warning flags. Usually this would be handled more
9495 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9496 // doesn't handle that so rather than warning about unused flags that are
9497 // actually used, we'll lie by omission instead.
9498 // FIXME: Stop lying and consume only the appropriate driver flags
9499 Args.ClaimAllArgs(options::OPT_W_Group);
9500
9501 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9502 getToolChain().getDriver());
9503
9504 // Forward -Xclangas arguments to -cc1as
9505 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9506 Arg->claim();
9507 CmdArgs.push_back(Arg->getValue());
9508 }
9509
9510 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9511
9512 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9513 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9514 Output.getFilename());
9515
9516 // Fixup any previous commands that use -object-file-name because when we
9517 // generated them, the final .obj name wasn't yet known.
9518 for (Command &J : C.getJobs()) {
9519 if (SourceAction != FindSource(&J.getSource()))
9520 continue;
9521 auto &JArgs = J.getArguments();
9522 for (unsigned I = 0; I < JArgs.size(); ++I) {
9523 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9524 Output.isFilename()) {
9525 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9526 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9527 Output.getFilename());
9528 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9529 J.replaceArguments(NewArgs);
9530 break;
9531 }
9532 }
9533 }
9534
9535 assert(Output.isFilename() && "Unexpected lipo output.");
9536 CmdArgs.push_back("-o");
9537 CmdArgs.push_back(Output.getFilename());
9538
9539 const llvm::Triple &T = getToolChain().getTriple();
9540 Arg *A;
9541 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9542 T.isOSBinFormatELF()) {
9543 CmdArgs.push_back("-split-dwarf-output");
9544 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9545 }
9546
9547 if (Triple.isAMDGPU())
9548 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9549
9550 assert(Input.isFilename() && "Invalid input.");
9551 CmdArgs.push_back(Input.getFilename());
9552
9553 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9554 if (D.CC1Main && !D.CCGenDiagnostics) {
9555 // Invoke cc1as directly in this process.
9556 C.addCommand(std::make_unique<CC1Command>(
9557 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9558 Output, D.getPrependArg()));
9559 } else {
9560 C.addCommand(std::make_unique<Command>(
9561 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9562 Output, D.getPrependArg()));
9563 }
9564}
9565
9566// Begin OffloadBundler
9568 const InputInfo &Output,
9569 const InputInfoList &Inputs,
9570 const llvm::opt::ArgList &TCArgs,
9571 const char *LinkingOutput) const {
9572 // The version with only one output is expected to refer to a bundling job.
9573 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9574
9575 // The bundling command looks like this:
9576 // clang-offload-bundler -type=bc
9577 // -targets=host-triple,openmp-triple1,openmp-triple2
9578 // -output=output_file
9579 // -input=unbundle_file_host
9580 // -input=unbundle_file_tgt1
9581 // -input=unbundle_file_tgt2
9582
9583 ArgStringList CmdArgs;
9584
9585 // Get the type.
9586 CmdArgs.push_back(TCArgs.MakeArgString(
9587 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9588
9589 assert(JA.getInputs().size() == Inputs.size() &&
9590 "Not have inputs for all dependence actions??");
9591
9592 // Get the targets.
9593 SmallString<128> Triples;
9594 Triples += "-targets=";
9595 for (unsigned I = 0; I < Inputs.size(); ++I) {
9596 if (I)
9597 Triples += ',';
9598
9599 // Find ToolChain for this input.
9601 const ToolChain *CurTC = &getToolChain();
9602 const Action *CurDep = JA.getInputs()[I];
9603
9604 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9605 CurTC = nullptr;
9606 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9607 assert(CurTC == nullptr && "Expected one dependence!");
9608 CurKind = A->getOffloadingDeviceKind();
9609 CurTC = TC;
9610 });
9611 }
9612 Triples += Action::GetOffloadKindName(CurKind);
9613 Triples += '-';
9614 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9615 TCArgs, CurDep->getOffloadingArch()))
9616 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9617
9618 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9619 Triples += '-';
9620 Triples += CurDep->getOffloadingArch().ArchName;
9621 }
9622 }
9623 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9624
9625 // Get bundled file command.
9626 CmdArgs.push_back(
9627 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9628
9629 // Get unbundled files command.
9630 for (unsigned I = 0; I < Inputs.size(); ++I) {
9632 UB += "-input=";
9633
9634 // Find ToolChain for this input.
9635 const ToolChain *CurTC = &getToolChain();
9636 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9637 CurTC = nullptr;
9638 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9639 assert(CurTC == nullptr && "Expected one dependence!");
9640 CurTC = TC;
9641 });
9642 UB += C.addTempFile(
9643 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9644 } else {
9645 UB += CurTC->getInputFilename(Inputs[I]);
9646 }
9647 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9648 }
9649 addOffloadCompressArgs(TCArgs, CmdArgs);
9650 // All the inputs are encoded as commands.
9651 C.addCommand(std::make_unique<Command>(
9652 JA, *this, ResponseFileSupport::None(),
9653 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9654 CmdArgs, ArrayRef<InputInfo>(), Output));
9655}
9656
9658 const InputInfo &Output,
9659 const InputInfoList &Inputs,
9660 const llvm::opt::ArgList &Args,
9661 const char *LinkingOutput) const {
9662 ArgStringList CmdArgs;
9663
9664 // Add the output file name.
9665 assert(Output.isFilename() && "Invalid output.");
9666 CmdArgs.push_back("-o");
9667 CmdArgs.push_back(Output.getFilename());
9668
9669 // Create the inputs to bundle the needed metadata.
9670 for (const InputInfo &Input : Inputs) {
9671 const Action *OffloadAction = Input.getAction();
9673 const ArgList &TCArgs =
9674 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9676 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9678 if (Arch.empty())
9679 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9680
9681 StringRef Kind =
9683
9684 ArgStringList Features;
9685 SmallVector<StringRef> FeatureArgs;
9686 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9687 false);
9688 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9689 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9690
9691 // TODO: We need to pass in the full target-id and handle it properly in the
9692 // linker wrapper.
9694 "file=" + File.str(),
9695 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9696 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9697 "kind=" + Kind.str(),
9698 };
9699
9701 for (StringRef Feature : FeatureArgs)
9702 Parts.emplace_back("feature=" + Feature.str());
9703
9704 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9705 }
9706
9707 C.addCommand(std::make_unique<Command>(
9709 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9710 CmdArgs, Inputs, Output));
9711}
9712
9713// Options that need the profile compiler-rt library on the target toolchain.
9714// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9715// too.
9716static bool requiresProfileRT(unsigned ID) {
9717 switch (ID) {
9718 case options::OPT_fprofile_generate:
9719 case options::OPT_fprofile_generate_EQ:
9720 case options::OPT_fprofile_instr_generate:
9721 case options::OPT_fprofile_instr_generate_EQ:
9722 case options::OPT_fcoverage_mapping:
9723 case options::OPT_fno_coverage_mapping:
9724 case options::OPT_fcoverage_compilation_dir_EQ:
9725 case options::OPT_ffile_compilation_dir_EQ:
9726 case options::OPT_fcoverage_prefix_map_EQ:
9727 return true;
9728 default:
9729 return false;
9730 }
9731}
9732
9733// Options that need the ubsan compiler-rt library on the target toolchain.
9734static bool requiresUBSanRT(unsigned ID) {
9735 switch (ID) {
9736 case options::OPT_fsanitize_EQ:
9737 case options::OPT_fno_sanitize_EQ:
9738 case options::OPT_fsanitize_minimal_runtime:
9739 case options::OPT_fno_sanitize_minimal_runtime:
9740 return true;
9741 default:
9742 return false;
9743 }
9744}
9745
9747 const InputInfo &Output,
9748 const InputInfoList &Inputs,
9749 const ArgList &Args,
9750 const char *LinkingOutput) const {
9751 using namespace options;
9752
9753 // A list of permitted options that will be forwarded to the embedded device
9754 // compilation job.
9755 const llvm::DenseSet<unsigned> CompilerOptions{
9756 OPT_v,
9757 OPT_hip_path_EQ,
9758 OPT_O_Group,
9759 OPT_g_Group,
9760 OPT_g_flags_Group,
9761 OPT_R_value_Group,
9762 OPT_R_Group,
9763 OPT_Xcuda_ptxas,
9764 OPT_ptxas_path_EQ,
9765 OPT_ftime_report,
9766 OPT_ftime_trace,
9767 OPT_ftime_trace_EQ,
9768 OPT_ftime_trace_granularity_EQ,
9769 OPT_ftime_trace_verbose,
9770 OPT_opt_record_file,
9771 OPT_opt_record_format,
9772 OPT_opt_record_passes,
9773 OPT_fsave_optimization_record,
9774 OPT_fsave_optimization_record_EQ,
9775 OPT_fno_save_optimization_record,
9776 OPT_foptimization_record_file_EQ,
9777 OPT_foptimization_record_passes_EQ,
9778 OPT_save_temps,
9779 OPT_save_temps_EQ,
9780 OPT_mcode_object_version_EQ,
9781 OPT_load,
9782 OPT_no_canonical_prefixes,
9783 OPT_fno_lto,
9784 OPT_flto,
9785 OPT_flto_partitions_EQ,
9786 OPT_flto_EQ,
9787 OPT_hipspv_pass_plugin_EQ,
9788 OPT_use_spirv_backend,
9789 OPT_no_use_spirv_backend,
9790 OPT_fmultilib_flag,
9791 OPT_fprofile_generate,
9792 OPT_fprofile_generate_EQ,
9793 OPT_fprofile_instr_generate,
9794 OPT_fprofile_instr_generate_EQ,
9795 OPT_fcoverage_mapping,
9796 OPT_fno_coverage_mapping,
9797 OPT_fcoverage_compilation_dir_EQ,
9798 OPT_ffile_compilation_dir_EQ,
9799 OPT_fcoverage_prefix_map_EQ,
9800 OPT_fsanitize_EQ,
9801 OPT_fno_sanitize_EQ,
9802 OPT_fsanitize_minimal_runtime,
9803 OPT_fno_sanitize_minimal_runtime,
9804 OPT_fsanitize_trap_EQ,
9805 OPT_fno_sanitize_trap_EQ,
9806 OPT_fslp_vectorize,
9807 OPT_fno_slp_vectorize,
9808 OPT_hipstdpar};
9809 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9810 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9811 // CMake implicit linker argument parsing.
9812 bool SuppressHIPNoRDCVerbose =
9813 JA.getType() == types::TY_HIP_FATBIN &&
9814 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
9815 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9816 return TC.getVFS().exists(
9817 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9818 };
9819 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9820 unsigned ID = A->getOption().getID();
9821 // Don't forward profiling arguments if the toolchain doesn't support it.
9822 // Without this check using it on the host would result in linker errors.
9823 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9824 // together to avoid a device cc1 diagnostic.
9825 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9826 return false;
9827 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9828 // Without this check using it on the host would result in linker errors.
9829 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal") &&
9830 !ToolChainHasRT(TC, "ubsan_standalone"))
9831 return false;
9832 // Don't forward -mllvm to toolchains that don't support LLVM.
9833 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9834 };
9835 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9836 const ToolChain &TC) {
9837 if (A->getOption().matches(OPT_v) && SuppressHIPNoRDCVerbose)
9838 return false;
9839 return (Set.contains(A->getOption().getID()) ||
9840 (A->getOption().getGroup().isValid() &&
9841 Set.contains(A->getOption().getGroup().getID()))) &&
9842 ShouldForwardForToolChain(A, TC);
9843 };
9844
9845 ArgStringList CmdArgs;
9848 auto TCRange = C.getOffloadToolChains(Kind);
9849 for (auto &I : llvm::make_range(TCRange)) {
9850 const ToolChain *TC = I.second;
9851
9852 // We do not use a bound architecture here so options passed only to a
9853 // specific architecture via -Xarch_<cpu> will not be forwarded.
9854 ArgStringList CompilerArgs;
9855 ArgStringList LinkerArgs;
9856 const DerivedArgList &ToolChainArgs =
9857 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9858 for (Arg *A : ToolChainArgs) {
9859 if (A->getOption().matches(OPT_Zlinker_input))
9860 LinkerArgs.emplace_back(A->getValue());
9861 else if (ShouldForward(CompilerOptions, A, *TC)) {
9862 A->claim();
9863 A->render(Args, CompilerArgs);
9864 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9865 A->claim();
9866 A->render(Args, LinkerArgs);
9867 }
9868 }
9869
9870 // If the user explicitly requested it via `--offload-arch` we should
9871 // extract it from any static libraries if present.
9872 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))
9873 CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));
9874
9875 // If this is OpenMP the device linker will need `-lompdevice`.
9876 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9877 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9878 LinkerArgs.emplace_back("-lompdevice");
9879
9880 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9881 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9882 // flags to normal compilation.
9883 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9884 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9885 if (TC->getTriple().isSPIRV() &&
9886 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9887 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9888 // For SPIR-V some functions will be defined by the runtime so allow
9889 // unresolved symbols in `spirv-link`.
9890 LinkerArgs.emplace_back("--allow-partial-linkage");
9891 // Don't optimize out exported symbols.
9892 LinkerArgs.emplace_back("--create-library");
9893 }
9894
9895 // Forward the SYCL device image split option to clang-sycl-linker.
9896 // The driver and clang-sycl-linker share the same value vocabulary, so
9897 // the value is passed through verbatim after validation.
9898 if (Kind == Action::OFK_SYCL) {
9899 if (Arg *A =
9900 ToolChainArgs.getLastArg(OPT_fsycl_device_image_split_EQ)) {
9901 StringRef Mode = A->getValue();
9902 if (Mode != "kernel" && Mode != "translation_unit" &&
9903 Mode != "link_unit")
9904 C.getDriver().Diag(clang::diag::err_drv_invalid_value)
9905 << A->getSpelling() << Mode;
9906 else
9907 LinkerArgs.emplace_back(
9908 Args.MakeArgString("--module-split-mode=" + Mode));
9909 }
9910 }
9911
9912 // Forward all of these to the appropriate toolchain.
9913 for (StringRef Arg : CompilerArgs)
9914 CmdArgs.push_back(Args.MakeArgString(
9915 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9916 for (StringRef Arg : LinkerArgs)
9917 CmdArgs.push_back(Args.MakeArgString(
9918 "--device-linker=" + TC->getTripleString() + "=" + Arg));
9919
9920 // Forward the LTO mode for this toolchain.
9921 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
9922 if (DeviceLTOMode == LTOK_Full)
9923 CmdArgs.push_back(Args.MakeArgString(
9924 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9925 else if (DeviceLTOMode == LTOK_Thin) {
9926 CmdArgs.push_back(Args.MakeArgString(
9927 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9928 if (TC->getTriple().isAMDGPU()) {
9929 CmdArgs.push_back(
9930 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9931 "=-plugin-opt=-force-import-all"));
9932 CmdArgs.push_back(
9933 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9934 "=-plugin-opt=-avail-extern-to-local"));
9935 CmdArgs.push_back(Args.MakeArgString(
9936 "--device-linker=" + TC->getTripleString() +
9937 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9938 if (Kind == Action::OFK_OpenMP) {
9939 CmdArgs.push_back(
9940 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9941 "=-plugin-opt=-amdgpu-internalize-symbols"));
9942 }
9943 }
9944 }
9945 }
9946 }
9947
9948 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9949 CmdArgs.push_back(
9950 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
9951 else
9952 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
9953 getToolChain().getTripleString()));
9954
9955 if (Args.hasArg(options::OPT_v) && !SuppressHIPNoRDCVerbose)
9956 CmdArgs.push_back("--wrapper-verbose");
9957 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
9958 CmdArgs.push_back(
9959 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
9960 CmdArgs.push_back(Args.MakeArgString(
9961 Twine("--device-compiler=--cuda-path=") + A->getValue()));
9962 }
9963 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
9964 CmdArgs.push_back(Args.MakeArgString(
9965 Twine("--device-compiler=--rocm-path=") + A->getValue()));
9966 }
9967
9968 // Construct the link job so we can wrap around it.
9969 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9970 const auto &LinkCommand = C.getJobs().getJobs().back();
9971
9972 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9973 // wrapper.
9974 for (Arg *A :
9975 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
9976 StringRef Val = A->getValue(0);
9977 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9978 auto WrapperOption =
9979 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9980 if (Val.empty())
9981 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
9982 else
9983 CmdArgs.push_back(Args.MakeArgString(
9984 WrapperOption +
9985 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
9986 A->getValue(1)));
9987 }
9988 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
9989 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9990
9991 // Embed bitcode instead of an object in JIT mode.
9992 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
9993 options::OPT_fno_openmp_target_jit, false))
9994 CmdArgs.push_back("--embed-bitcode");
9995
9996 // Save temporary files created by the linker wrapper.
9997 if (Args.hasArg(options::OPT_save_temps_EQ) ||
9998 Args.hasArg(options::OPT_save_temps))
9999 CmdArgs.push_back("--save-temps");
10000
10001 // Pass in the C library for GPUs if present and not disabled.
10002 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
10003 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
10004 options::OPT_nodefaultlibs, options::OPT_nolibc,
10005 options::OPT_nogpulibc)) {
10006 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
10007 // The device C library is only available for NVPTX and AMDGPU targets
10008 // and we only link it by default for OpenMP currently.
10009 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10011 return;
10012 bool HasLibC = TC.getStdlibIncludePath().has_value();
10013 if (HasLibC) {
10014 CmdArgs.push_back(Args.MakeArgString(
10015 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10016 CmdArgs.push_back(Args.MakeArgString(
10017 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10018 }
10019 auto HasCompilerRT = getToolChain().getVFS().exists(
10020 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
10021 /*IsFortran=*/false));
10022 if (HasCompilerRT)
10023 CmdArgs.push_back(
10024 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10025 "-lclang_rt.builtins"));
10026
10027 bool HasFlangRT = getToolChain().getVFS().exists(
10028 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10029 /*IsFortran=*/true));
10030 if (HasFlangRT && C.getDriver().IsFlangMode())
10031 CmdArgs.push_back(
10032 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10033 "-lflang_rt.runtime"));
10034 });
10035 }
10036
10037 // Add the linker arguments to be forwarded by the wrapper.
10038 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10039 LinkCommand->getExecutable()));
10040
10041 // We use action type to differentiate two use cases of the linker wrapper.
10042 // TY_Image for normal linker wrapper work.
10043 // TY_HIP_FATBIN and TY_SYCL_FATBIN for device-only links emitting a fat
10044 // binary directly.
10045 assert(JA.getType() == types::TY_HIP_FATBIN ||
10046 JA.getType() == types::TY_SYCL_FATBIN ||
10047 JA.getType() == types::TY_Image);
10048 if (JA.getType() != types::TY_Image) {
10049 CmdArgs.push_back("--emit-fatbin-only");
10050 CmdArgs.append({"-o", Output.getFilename()});
10051 for (auto Input : Inputs)
10052 CmdArgs.push_back(Input.getFilename());
10053 } else {
10054 for (const char *LinkArg : LinkCommand->getArguments())
10055 CmdArgs.push_back(LinkArg);
10056 }
10057
10058 addOffloadCompressArgs(Args, CmdArgs);
10059
10060 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10061 if (OffloadJobs.A) {
10062 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10063 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10064 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10065 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=" +
10066 Twine(OffloadJobs.NumThreads)));
10067 } else if (!OffloadJobs.A->isClaimed()) {
10068 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10069 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10070 }
10071 }
10072
10073 // Propagate -no-canonical-prefixes.
10074 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10075 CmdArgs.push_back("--no-canonical-prefixes");
10076
10077 const char *Exec =
10078 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10079
10080 // Replace the executable and arguments of the link job with the
10081 // wrapper.
10082 LinkCommand->replaceExecutable(Exec);
10083 LinkCommand->replaceArguments(CmdArgs);
10084}
#define V(N, I)
static StringRef bytes(const std::vector< T, Allocator > &v)
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3918
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition Clang.cpp:117
static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A)
Definition Clang.cpp:2295
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4343
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:710
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5108
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9716
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4524
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:759
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:70
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1354
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1206
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:8837
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2274
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:776
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4016
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4658
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2545
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1244
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:736
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:337
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition Clang.cpp:4635
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:4379
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:322
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition Clang.cpp:2550
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1255
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2326
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2556
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2267
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4082
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:3590
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:307
static bool addExceptionArgs(const ArgList &Args, types::ID InputType, const ToolChain &TC, bool KernelOrKext, bool IsDeviceOffloadAction, const ObjCRuntime &objcRuntime, ArgStringList &CmdArgs)
Adds exception related arguments to the driver command arguments.
Definition Clang.cpp:137
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1271
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition Clang.cpp:252
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition Clang.cpp:1389
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3600
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4024
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3828
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3847
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8816
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:232
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:215
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, bool IsUsingLTO)
Definition Clang.cpp:4675
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9734
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:286
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition Clang.cpp:3521
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2301
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2921
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:371
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3962
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:946
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
A processor an offloading action can target.
Definition OffloadArch.h:32
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:48
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:143
BoundArch getOffloadingArch() const
Definition Action.h:216
ActionClass getKind() const
Definition Action.h:152
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:159
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:107
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
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:93
llvm::SmallVector< BoundArch > 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:3964
std::string SysRoot
sysroot, if present
Definition Driver.h:193
DiagnosticsEngine & getDiags() const
Definition Driver.h:407
const char * getPrependArg() const
Definition Driver.h:418
CC1ToolFunc CC1Main
Definition Driver.h:289
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:896
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:229
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:267
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:4048
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:271
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:281
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:6063
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2501
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:429
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:217
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:214
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:177
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:409
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition Driver.h:168
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:153
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:143
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:250
std::string getTargetTriple() const
Definition Driver.h:426
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:256
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:171
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:223
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:220
bool getProbePrecompiled() const
Definition Driver.h:415
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:92
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:906
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:655
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:664
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:688
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:898
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:646
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:518
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:298
const Driver & getDriver() const
Definition ToolChain.h:282
RTTIMode getRTTIMode() const
Definition ToolChain.h:365
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:677
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 ...
virtual LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:310
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:539
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:510
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:699
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:670
const llvm::Triple & getTriple() const
Definition ToolChain.h:284
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:674
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:307
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:533
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:739
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:652
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:640
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:893
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:522
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:485
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:643
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA={}, Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
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:514
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:481
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:291
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:507
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:13
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< std::string > GetHVXVersion(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:1032
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:656
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9238
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9221
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9246
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:9261
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9210
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9180
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8671
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9195
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9185
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:5208
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:9746
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:9567
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:9657
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:479
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:305
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::optional< StringRef > getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args, SmallVectorImpl< std::string > *TuneFeatures=nullptr)
Return the tune CPU and optionally, the tune features.
Definition RISCV.cpp:433
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.
OffloadJobsOpt parseOffloadJobs(const llvm::opt::ArgList &Args)
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)
void renderDebugInfoCompressionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
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)
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)
void addSplitMachineFunctionsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
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)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine, bool &DXRecordCommandLine)
Check if the command line should be recorded in the object file.
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:329
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:240
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:292
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:253
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:331
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:265
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:49
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'.
Top level wrappers for InstallAPI frontend operations.
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:133
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.
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
const char * CudaVersionToString(CudaVersion V)
Definition Cuda.cpp:60
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:38
Represents a bound architecture for offload / multiple architecture compilation.
llvm::StringRef ArchName
bool empty() const
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:79
static constexpr ResponseFileSupport AtFileUTF8()
Definition Job.h:86