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 default:
361 ClangType = types::getTypeName(Input.getType());
362 break;
363 }
364 CmdArgs.push_back(ClangType);
365 }
366}
367
369 const JobAction &JA, const InputInfo &Output,
370 const ArgList &Args, SanitizerArgs &SanArgs,
371 ArgStringList &CmdArgs) {
372 const Driver &D = TC.getDriver();
373 const llvm::Triple &T = TC.getTriple();
374 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
375 options::OPT_fprofile_generate_EQ,
376 options::OPT_fno_profile_generate);
377 if (PGOGenerateArg &&
378 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
379 PGOGenerateArg = nullptr;
380
381 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
382
383 auto *ProfileGenerateArg = Args.getLastArg(
384 options::OPT_fprofile_instr_generate,
385 options::OPT_fprofile_instr_generate_EQ,
386 options::OPT_fno_profile_instr_generate);
387 if (ProfileGenerateArg &&
388 ProfileGenerateArg->getOption().matches(
389 options::OPT_fno_profile_instr_generate))
390 ProfileGenerateArg = nullptr;
391
392 if (PGOGenerateArg && ProfileGenerateArg)
393 D.Diag(diag::err_drv_argument_not_allowed_with)
394 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
395
396 auto *ProfileUseArg = getLastProfileUseArg(Args);
397
398 if (PGOGenerateArg && ProfileUseArg)
399 D.Diag(diag::err_drv_argument_not_allowed_with)
400 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
401
402 if (ProfileGenerateArg && ProfileUseArg)
403 D.Diag(diag::err_drv_argument_not_allowed_with)
404 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
405
406 if (CSPGOGenerateArg && PGOGenerateArg) {
407 D.Diag(diag::err_drv_argument_not_allowed_with)
408 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
409 PGOGenerateArg = nullptr;
410 }
411
412 if (TC.getTriple().isOSAIX()) {
413 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
414 D.Diag(diag::err_drv_unsupported_opt_for_target)
415 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
416 }
417
418 if (ProfileGenerateArg) {
419 if (ProfileGenerateArg->getOption().matches(
420 options::OPT_fprofile_instr_generate_EQ))
421 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
422 ProfileGenerateArg->getValue()));
423 // The default is to use Clang Instrumentation.
424 CmdArgs.push_back("-fprofile-instrument=clang");
425 if (TC.getTriple().isWindowsMSVCEnvironment() &&
426 Args.hasFlag(options::OPT_frtlib_defaultlib,
427 options::OPT_fno_rtlib_defaultlib, true)) {
428 // Add dependent lib for clang_rt.profile
429 CmdArgs.push_back(Args.MakeArgString(
430 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
431 }
432 }
433
434 if (auto *ColdFuncCoverageArg = Args.getLastArg(
435 options::OPT_fprofile_generate_cold_function_coverage,
436 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
437 SmallString<128> Path(
438 ColdFuncCoverageArg->getOption().matches(
439 options::OPT_fprofile_generate_cold_function_coverage_EQ)
440 ? ColdFuncCoverageArg->getValue()
441 : "");
442 llvm::sys::path::append(Path, "default_%m.profraw");
443 // FIXME: Idealy the file path should be passed through
444 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
445 // shared with other profile use path(see PGOOptions), we need to refactor
446 // PGOOptions to make it work.
447 CmdArgs.push_back("-mllvm");
448 CmdArgs.push_back(Args.MakeArgString(
449 Twine("--instrument-cold-function-only-path=") + Path));
450 CmdArgs.push_back("-mllvm");
451 CmdArgs.push_back("--pgo-instrument-cold-function-only");
452 CmdArgs.push_back("-mllvm");
453 CmdArgs.push_back("--pgo-function-entry-coverage");
454 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
455 }
456
457 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
458 if (!PGOGenerateArg && !CSPGOGenerateArg)
459 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
460 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
461 CmdArgs.push_back("-mllvm");
462 CmdArgs.push_back("--pgo-temporal-instrumentation");
463 }
464
465 Arg *PGOGenArg = nullptr;
466 if (PGOGenerateArg) {
467 assert(!CSPGOGenerateArg);
468 PGOGenArg = PGOGenerateArg;
469 CmdArgs.push_back("-fprofile-instrument=llvm");
470 }
471 if (CSPGOGenerateArg) {
472 assert(!PGOGenerateArg);
473 PGOGenArg = CSPGOGenerateArg;
474 CmdArgs.push_back("-fprofile-instrument=csllvm");
475 }
476 if (PGOGenArg) {
477 if (TC.getTriple().isWindowsMSVCEnvironment() &&
478 Args.hasFlag(options::OPT_frtlib_defaultlib,
479 options::OPT_fno_rtlib_defaultlib, true)) {
480 // Add dependent lib for clang_rt.profile
481 CmdArgs.push_back(Args.MakeArgString(
482 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
483 }
484 if (PGOGenArg->getOption().matches(
485 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
486 : options::OPT_fcs_profile_generate_EQ)) {
487 SmallString<128> Path(PGOGenArg->getValue());
488 llvm::sys::path::append(Path, "default_%m.profraw");
489 CmdArgs.push_back(
490 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
491 }
492 }
493
494 if (ProfileUseArg) {
495 SmallString<128> UsePathBuf;
496 StringRef UsePath;
497 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
498 UsePath = ProfileUseArg->getValue();
499 else if ((ProfileUseArg->getOption().matches(
500 options::OPT_fprofile_use_EQ) ||
501 ProfileUseArg->getOption().matches(
502 options::OPT_fprofile_instr_use))) {
503 UsePathBuf =
504 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
505 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
506 llvm::sys::path::append(UsePathBuf, "default.profdata");
507 UsePath = UsePathBuf;
508 }
509 auto ReaderOrErr =
510 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
511 if (auto E = ReaderOrErr.takeError()) {
512 auto DiagID = D.getDiags().getCustomDiagID(
513 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
514 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
515 D.Diag(DiagID) << UsePath.str() << EI.message();
516 });
517 } else {
518 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
519 std::move(ReaderOrErr.get());
520 StringRef UseKind;
521 // Currently memprof profiles are only added at the IR level. Mark the
522 // profile type as IR in that case as well and the subsequent matching
523 // needs to detect which is available (might be one or both).
524 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
525 if (PGOReader->hasCSIRLevelProfile())
526 UseKind = "csllvm";
527 else
528 UseKind = "llvm";
529 } else
530 UseKind = "clang";
531
532 CmdArgs.push_back(
533 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
534 CmdArgs.push_back(
535 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
536 }
537 }
538
539 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
540 options::OPT_fno_test_coverage, false) ||
541 Args.hasArg(options::OPT_coverage);
542 bool EmitCovData = TC.needsGCovInstrumentation(Args);
543
544 if (Args.hasFlag(options::OPT_fcoverage_mapping,
545 options::OPT_fno_coverage_mapping, false)) {
546 if (!ProfileGenerateArg)
547 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
548 << "-fcoverage-mapping"
549 << "-fprofile-instr-generate";
550
551 CmdArgs.push_back("-fcoverage-mapping");
552 }
553
554 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
555 false)) {
556 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
557 options::OPT_fno_coverage_mapping, false))
558 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
559 << "-fcoverage-mcdc"
560 << "-fcoverage-mapping";
561
562 CmdArgs.push_back("-fcoverage-mcdc");
563 }
564
565 StringRef CoverageCompDir;
566 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
567 options::OPT_fcoverage_compilation_dir_EQ))
568 CoverageCompDir = A->getValue();
569 if (CoverageCompDir.empty()) {
570 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
571 CmdArgs.push_back(
572 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
573 } else
574 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
575 CoverageCompDir));
576
577 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
578 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
579 if (!Args.hasArg(options::OPT_coverage))
580 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
581 << "-fprofile-exclude-files="
582 << "--coverage";
583
584 StringRef v = Arg->getValue();
585 CmdArgs.push_back(
586 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
587 }
588
589 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
590 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
591 if (!Args.hasArg(options::OPT_coverage))
592 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
593 << "-fprofile-filter-files="
594 << "--coverage";
595
596 StringRef v = Arg->getValue();
597 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
598 }
599
600 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
601 StringRef Val = A->getValue();
602 if (Val == "atomic" || Val == "prefer-atomic")
603 CmdArgs.push_back("-fprofile-update=atomic");
604 else if (Val != "single")
605 D.Diag(diag::err_drv_unsupported_option_argument)
606 << A->getSpelling() << Val;
607 }
608 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
609 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
610 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
611 << A->getSpelling()
612 << "-fprofile-generate, -fprofile-instr-generate, or "
613 "-fcs-profile-generate";
614 else {
615 CmdArgs.push_back("-fprofile-continuous");
616 // Platforms that require a bias variable:
617 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
618 CmdArgs.push_back("-mllvm");
619 CmdArgs.push_back("-runtime-counter-relocation");
620 }
621 // -fprofile-instr-generate does not decide the profile file name in the
622 // FE, and so it does not define the filename symbol
623 // (__llvm_profile_filename). Instead, the runtime uses the name
624 // "default.profraw" for the profile file. When continuous mode is ON, we
625 // will create the filename symbol so that we can insert the "%c"
626 // modifier.
627 if (ProfileGenerateArg &&
628 (ProfileGenerateArg->getOption().matches(
629 options::OPT_fprofile_instr_generate) ||
630 (ProfileGenerateArg->getOption().matches(
631 options::OPT_fprofile_instr_generate_EQ) &&
632 strlen(ProfileGenerateArg->getValue()) == 0)))
633 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
634 }
635 }
636
637 int FunctionGroups = 1;
638 int SelectedFunctionGroup = 0;
639 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
640 StringRef Val = A->getValue();
641 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
642 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
643 }
644 if (const auto *A =
645 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
646 StringRef Val = A->getValue();
647 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
648 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
649 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
650 }
651 if (FunctionGroups != 1)
652 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
653 Twine(FunctionGroups)));
654 if (SelectedFunctionGroup != 0)
655 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
656 Twine(SelectedFunctionGroup)));
657
658 // Leave -fprofile-dir= an unused argument unless .gcda emission is
659 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
660 // the flag used. There is no -fno-profile-dir, so the user has no
661 // targeted way to suppress the warning.
662 Arg *FProfileDir = nullptr;
663 if (Args.hasArg(options::OPT_fprofile_arcs) ||
664 Args.hasArg(options::OPT_coverage))
665 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
666
667 // Put the .gcno and .gcda files (if needed) next to the primary output file,
668 // or fall back to a file in the current directory for `clang -c --coverage
669 // d/a.c` in the absence of -o.
670 if (EmitCovNotes || EmitCovData) {
671 SmallString<128> CoverageFilename;
672 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
673 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
674 // path separator.
675 CoverageFilename = DumpDir->getValue();
676 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
677 } else if (Arg *FinalOutput =
678 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
679 CoverageFilename = FinalOutput->getValue();
680 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
681 CoverageFilename = FinalOutput->getValue();
682 } else {
683 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
684 }
685 if (llvm::sys::path::is_relative(CoverageFilename))
686 (void)D.getVFS().makeAbsolute(CoverageFilename);
687 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
688 if (EmitCovNotes) {
689 CmdArgs.push_back(
690 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
691 }
692
693 if (EmitCovData) {
694 if (FProfileDir) {
695 SmallString<128> Gcno = std::move(CoverageFilename);
696 CoverageFilename = FProfileDir->getValue();
697 llvm::sys::path::append(CoverageFilename, Gcno);
698 }
699 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
700 CmdArgs.push_back(
701 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
702 }
703 }
704}
705
706static void
707RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
708 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
709 unsigned DwarfVersion,
710 llvm::DebuggerKind DebuggerTuning) {
711 addDebugInfoKind(CmdArgs, DebugInfoKind);
712 if (DwarfVersion > 0)
713 CmdArgs.push_back(
714 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
715 switch (DebuggerTuning) {
716 case llvm::DebuggerKind::GDB:
717 CmdArgs.push_back("-debugger-tuning=gdb");
718 break;
719 case llvm::DebuggerKind::LLDB:
720 CmdArgs.push_back("-debugger-tuning=lldb");
721 break;
722 case llvm::DebuggerKind::SCE:
723 CmdArgs.push_back("-debugger-tuning=sce");
724 break;
725 case llvm::DebuggerKind::DBX:
726 CmdArgs.push_back("-debugger-tuning=dbx");
727 break;
728 default:
729 break;
730 }
731}
732
734 const ArgList &Args,
735 ArgStringList &CmdArgs,
736 bool IsCC1As = false) {
737 // If no version was requested by the user, use the default value from the
738 // back end. This is consistent with the value returned from
739 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
740 // requiring the corresponding llvm to have the AMDGPU target enabled,
741 // provided the user (e.g. front end tests) can use the default.
743 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
744 CmdArgs.insert(CmdArgs.begin() + 1,
745 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
746 Twine(CodeObjVer)));
747 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
748 // -cc1as does not accept -mcode-object-version option.
749 if (!IsCC1As)
750 CmdArgs.insert(CmdArgs.begin() + 1,
751 Args.MakeArgString(Twine("-mcode-object-version=") +
752 Twine(CodeObjVer)));
753 }
754}
755
756static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
757 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
758 D.getVFS().getBufferForFile(Path);
759 if (!MemBuf)
760 return false;
761 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
762 if (Magic == llvm::file_magic::unknown)
763 return false;
764 // Return true for both raw Clang AST files and object files which may
765 // contain a __clangast section.
766 if (Magic == llvm::file_magic::clang_ast)
767 return true;
769 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
770 return !Obj.takeError();
771}
772
773static bool gchProbe(const Driver &D, StringRef Path) {
774 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
775 if (!Status)
776 return false;
777
778 if (Status->isDirectory()) {
779 std::error_code EC;
780 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
781 !EC && DI != DE; DI = DI.increment(EC)) {
782 if (maybeHasClangPchSignature(D, DI->path()))
783 return true;
784 }
785 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
786 return false;
787 }
788
789 if (maybeHasClangPchSignature(D, Path))
790 return true;
791 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
792 return false;
793}
794
795void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
796 const Driver &D, const ArgList &Args,
797 ArgStringList &CmdArgs,
798 const InputInfo &Output,
799 const InputInfoList &Inputs) const {
800 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
801
803
804 Args.AddLastArg(CmdArgs, options::OPT_C);
805 Args.AddLastArg(CmdArgs, options::OPT_CC);
806
807 // Handle dependency file generation.
808 Arg *ArgM = Args.getLastArg(options::OPT_MM);
809 if (!ArgM)
810 ArgM = Args.getLastArg(options::OPT_M);
811 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
812 if (!ArgMD)
813 ArgMD = Args.getLastArg(options::OPT_MD);
814
815 // -M and -MM imply -w.
816 if (ArgM)
817 CmdArgs.push_back("-w");
818 else
819 ArgM = ArgMD;
820
821 if (ArgM) {
823 // Determine the output location.
824 const char *DepFile;
825 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
826 DepFile = MF->getValue();
827 C.addFailureResultFile(DepFile, &JA);
828 } else if (Output.getType() == types::TY_Dependencies) {
829 DepFile = Output.getFilename();
830 } else if (!ArgMD) {
831 DepFile = "-";
832 } else {
833 DepFile = getDependencyFileName(Args, Inputs);
834 C.addFailureResultFile(DepFile, &JA);
835 }
836 CmdArgs.push_back("-dependency-file");
837 CmdArgs.push_back(DepFile);
838 }
839 // Cmake generates dependency files using all compilation options specified
840 // by users. Claim those not used for dependency files.
842 Args.ClaimAllArgs(options::OPT_offload_compress);
843 Args.ClaimAllArgs(options::OPT_no_offload_compress);
844 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
845 }
846
847 bool HasTarget = false;
848 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
849 HasTarget = true;
850 A->claim();
851 if (A->getOption().matches(options::OPT_MT)) {
852 A->render(Args, CmdArgs);
853 } else {
854 CmdArgs.push_back("-MT");
855 SmallString<128> Quoted;
856 quoteMakeTarget(A->getValue(), Quoted);
857 CmdArgs.push_back(Args.MakeArgString(Quoted));
858 }
859 }
860
861 // Add a default target if one wasn't specified.
862 if (!HasTarget) {
863 const char *DepTarget;
864
865 // If user provided -o, that is the dependency target, except
866 // when we are only generating a dependency file.
867 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
868 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
869 DepTarget = OutputOpt->getValue();
870 } else {
871 // Otherwise derive from the base input.
872 //
873 // FIXME: This should use the computed output file location.
874 SmallString<128> P(Inputs[0].getBaseInput());
875 llvm::sys::path::replace_extension(P, "o");
876 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
877 }
878
879 CmdArgs.push_back("-MT");
880 SmallString<128> Quoted;
881 quoteMakeTarget(DepTarget, Quoted);
882 CmdArgs.push_back(Args.MakeArgString(Quoted));
883 }
884
885 if (ArgM->getOption().matches(options::OPT_M) ||
886 ArgM->getOption().matches(options::OPT_MD))
887 CmdArgs.push_back("-sys-header-deps");
888
889 // Determine module file deps mode.
890 StringRef ModuleFileDepsVal;
891 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
892 options::OPT_fmodule_file_deps,
893 options::OPT_fno_module_file_deps)) {
894 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
895 ModuleFileDepsVal = A->getValue();
896 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
897 ModuleFileDepsVal = "all";
898 else
899 ModuleFileDepsVal = "none";
900 } else if (isa<PrecompileJobAction>(JA)) {
901 ModuleFileDepsVal = "all";
902 }
903 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
904 CmdArgs.push_back(
905 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
906 }
907
908 if (Args.hasArg(options::OPT_MG)) {
909 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
910 ArgM->getOption().matches(options::OPT_MMD))
911 D.Diag(diag::err_drv_mg_requires_m_or_mm);
912 CmdArgs.push_back("-MG");
913 }
914
915 Args.AddLastArg(CmdArgs, options::OPT_MP);
916 Args.AddLastArg(CmdArgs, options::OPT_MV);
917
918 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
919 // before we -I or -include anything else, because we must pick up the
920 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
921 // rather than from e.g. /usr/local/include.
923 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
925 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
927 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
928
929 // If we are offloading to a target via OpenMP we need to include the
930 // openmp_wrappers folder which contains alternative system headers.
932 !Args.hasArg(options::OPT_nostdinc) &&
933 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
934 true) &&
935 getToolChain().getTriple().isGPU()) {
936 if (!Args.hasArg(options::OPT_nobuiltininc)) {
937 // Add openmp_wrappers/* to our system include path. This lets us wrap
938 // standard library headers.
939 SmallString<128> P(D.ResourceDir);
940 llvm::sys::path::append(P, "include");
941 llvm::sys::path::append(P, "openmp_wrappers");
942 CmdArgs.push_back("-internal-isystem");
943 CmdArgs.push_back(Args.MakeArgString(P));
944 }
945
946 CmdArgs.push_back("-include");
947 CmdArgs.push_back("__clang_openmp_device_functions.h");
948 }
949
950 if (Args.hasArg(options::OPT_foffload_via_llvm)) {
951 // Add llvm_wrappers/* to our system include path. This lets us wrap
952 // standard library headers and other headers.
953 SmallString<128> P(D.ResourceDir);
954 llvm::sys::path::append(P, "include", "llvm_offload_wrappers");
955 CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});
957 CmdArgs.push_back("__llvm_offload_device.h");
958 else
959 CmdArgs.push_back("__llvm_offload_host.h");
960 }
961
962 // Add -i* options, and automatically translate to
963 // -include-pch/-include-pth for transparent PCH support. It's
964 // wonky, but we include looking for .gch so we can support seamless
965 // replacement into a build system already set up to be generating
966 // .gch files.
967
968 if (getToolChain().getDriver().IsCLMode()) {
969 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
970 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
971 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
973 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
974 // -fpch-instantiate-templates is the default when creating
975 // precomp using /Yc
976 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
977 options::OPT_fno_pch_instantiate_templates, true))
978 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
979 }
980 if (YcArg || YuArg) {
981 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
982 if (!isa<PrecompileJobAction>(JA)) {
983 CmdArgs.push_back("-include-pch");
984 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
985 C, !ThroughHeader.empty()
986 ? ThroughHeader
987 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
988 }
989
990 if (ThroughHeader.empty()) {
991 CmdArgs.push_back(Args.MakeArgString(
992 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
993 } else {
994 CmdArgs.push_back(
995 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
996 }
997 }
998 }
999
1000 bool RenderedImplicitInclude = false;
1001 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1002 if (A->getOption().matches(options::OPT_include) &&
1003 D.getProbePrecompiled()) {
1004 // Handling of gcc-style gch precompiled headers.
1005 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1006 RenderedImplicitInclude = true;
1007
1008 bool FoundPCH = false;
1009 SmallString<128> P(A->getValue());
1010 // We want the files to have a name like foo.h.pch. Add a dummy extension
1011 // so that replace_extension does the right thing.
1012 P += ".dummy";
1013 llvm::sys::path::replace_extension(P, "pch");
1014 if (D.getVFS().exists(P))
1015 FoundPCH = true;
1016
1017 if (!FoundPCH) {
1018 // For GCC compat, probe for a file or directory ending in .gch instead.
1019 llvm::sys::path::replace_extension(P, "gch");
1020 FoundPCH = gchProbe(D, P.str());
1021 }
1022
1023 if (FoundPCH) {
1024 if (IsFirstImplicitInclude) {
1025 A->claim();
1026 CmdArgs.push_back("-include-pch");
1027 CmdArgs.push_back(Args.MakeArgString(P));
1028 continue;
1029 } else {
1030 // Ignore the PCH if not first on command line and emit warning.
1031 D.Diag(diag::warn_drv_pch_not_first_include) << P
1032 << A->getAsString(Args);
1033 }
1034 }
1035 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1036 // Handling of paths which must come late. These entries are handled by
1037 // the toolchain itself after the resource dir is inserted in the right
1038 // search order.
1039 // Do not claim the argument so that the use of the argument does not
1040 // silently go unnoticed on toolchains which do not honour the option.
1041 continue;
1042 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1043 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1044 continue;
1045 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1046 // This is used only by the driver. No need to pass to cc1.
1047 continue;
1048 }
1049
1050 // Not translated, render as usual.
1051 A->claim();
1052 A->render(Args, CmdArgs);
1053 }
1054
1055 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1057 // Collect all enabled NVPTX architectures.
1058 std::set<unsigned> ArchIDs;
1059 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1060 const ToolChain *TC = I.second;
1061 for (BoundArch Arch :
1062 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1063 if (Arch.Arch.isNVPTX())
1064 ArchIDs.insert(CudaArchToID(Arch.Arch));
1065 }
1066 }
1067
1068 if (!ArchIDs.empty()) {
1069 SmallString<128> List;
1070 llvm::raw_svector_ostream OS(List);
1071 llvm::interleave(ArchIDs, OS, ",");
1072 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1073 }
1074 }
1075
1076 Args.addAllArgs(CmdArgs,
1077 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1078 options::OPT_F, options::OPT_embed_dir_EQ});
1079
1080 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1081
1082 // FIXME: There is a very unfortunate problem here, some troubled
1083 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1084 // really support that we would have to parse and then translate
1085 // those options. :(
1086 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1087 options::OPT_Xpreprocessor);
1088
1089 // -I- is a deprecated GCC feature, reject it.
1090 if (Arg *A = Args.getLastArg(options::OPT_I_))
1091 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1092
1093 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1094 // -isysroot to the CC1 invocation.
1095 StringRef sysroot = C.getSysRoot();
1096 if (sysroot != "") {
1097 if (!Args.hasArg(options::OPT_isysroot)) {
1098 CmdArgs.push_back("-isysroot");
1099 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1100 }
1101 }
1102
1103 // Parse additional include paths from environment variables.
1104 // FIXME: We should probably sink the logic for handling these from the
1105 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1106 // CPATH - included following the user specified includes (but prior to
1107 // builtin and standard includes).
1108 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1109 // C_INCLUDE_PATH - system includes enabled when compiling C.
1110 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1111 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1112 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1113 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1114 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1115 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1116 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1117
1118 // While adding the include arguments, we also attempt to retrieve the
1119 // arguments of related offloading toolchains or arguments that are specific
1120 // of an offloading programming model.
1121
1122 // Add C++ include arguments, if needed.
1123 if (types::isCXX(Inputs[0].getType())) {
1124 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1126 C, JA, getToolChain(),
1127 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1128 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1129 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1130 });
1131 }
1132
1133 // If we are compiling for a GPU target we want to override the system headers
1134 // with ones created by the 'libc' project if present.
1135 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1136 // OffloadKind as an argument.
1137 if (!Args.hasArg(options::OPT_nostdinc) &&
1138 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1139 true) &&
1140 !Args.hasArg(options::OPT_nobuiltininc) &&
1141 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1142 // TODO: CUDA / HIP include their own headers for some common functions
1143 // implemented here. We'll need to clean those up so they do not conflict.
1144 SmallString<128> P(D.ResourceDir);
1145 llvm::sys::path::append(P, "include");
1146 llvm::sys::path::append(P, "llvm_libc_wrappers");
1147 CmdArgs.push_back("-internal-isystem");
1148 CmdArgs.push_back(Args.MakeArgString(P));
1149 }
1150
1151 // Add system include arguments for all targets but IAMCU.
1152 if (!IsIAMCU)
1154 [&Args, &CmdArgs](const ToolChain &TC) {
1155 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1156 });
1157 else {
1158 // For IAMCU add special include arguments.
1159 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1160 }
1161
1162 addMacroPrefixMapArg(D, Args, CmdArgs);
1163 addCoveragePrefixMapArg(D, Args, CmdArgs);
1164
1165 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1166 options::OPT_fno_file_reproducible);
1167
1168 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1169 CmdArgs.push_back("-source-date-epoch");
1170 CmdArgs.push_back(Args.MakeArgString(Epoch));
1171 }
1172
1173 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1174 options::OPT_fno_define_target_os_macros);
1175}
1176
1177// FIXME: Move to target hook.
1178static bool isSignedCharDefault(const llvm::Triple &Triple) {
1179 switch (Triple.getArch()) {
1180 default:
1181 return true;
1182
1183 case llvm::Triple::aarch64:
1184 case llvm::Triple::aarch64_32:
1185 case llvm::Triple::aarch64_be:
1186 case llvm::Triple::arm:
1187 case llvm::Triple::armeb:
1188 case llvm::Triple::thumb:
1189 case llvm::Triple::thumbeb:
1190 if (Triple.isOSDarwin() || Triple.isOSWindows())
1191 return true;
1192 return false;
1193
1194 case llvm::Triple::ppc:
1195 case llvm::Triple::ppc64:
1196 if (Triple.isOSDarwin())
1197 return true;
1198 return false;
1199
1200 case llvm::Triple::csky:
1201 case llvm::Triple::hexagon:
1202 case llvm::Triple::msp430:
1203 case llvm::Triple::ppcle:
1204 case llvm::Triple::ppc64le:
1205 case llvm::Triple::riscv32:
1206 case llvm::Triple::riscv64:
1207 case llvm::Triple::riscv32be:
1208 case llvm::Triple::riscv64be:
1209 case llvm::Triple::systemz:
1210 case llvm::Triple::xcore:
1211 case llvm::Triple::xtensa:
1212 return false;
1213 }
1214}
1215
1216static bool hasMultipleInvocations(const llvm::Triple &Triple,
1217 const ArgList &Args) {
1218 // Supported only on Darwin where we invoke the compiler multiple times
1219 // followed by an invocation to lipo.
1220 if (!Triple.isOSDarwin())
1221 return false;
1222 // If more than one "-arch <arch>" is specified, we're targeting multiple
1223 // architectures resulting in a fat binary.
1224 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1225}
1226
1227static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1228 const llvm::Triple &Triple) {
1229 // When enabling remarks, we need to error if:
1230 // * The remark file is specified but we're targeting multiple architectures,
1231 // which means more than one remark file is being generated.
1233 bool hasExplicitOutputFile =
1234 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1235 if (hasMultipleInvocations && hasExplicitOutputFile) {
1236 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1237 << "-foptimization-record-file";
1238 return false;
1239 }
1240 return true;
1241}
1242
1243static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1244 const llvm::Triple &Triple,
1245 const InputInfo &Input,
1246 const InputInfo &Output, const JobAction &JA) {
1247 StringRef Format = "yaml";
1248 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1249 Format = A->getValue();
1250
1251 CmdArgs.push_back("-opt-record-file");
1252
1253 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1254 if (A) {
1255 CmdArgs.push_back(A->getValue());
1256 } else {
1257 bool hasMultipleArchs =
1258 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1259 Args.getAllArgValues(options::OPT_arch).size() > 1;
1260
1262
1263 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1264 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1265 F = FinalOutput->getValue();
1266 } else {
1267 if (Format != "yaml" && // For YAML, keep the original behavior.
1268 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1269 Output.isFilename())
1270 F = Output.getFilename();
1271 }
1272
1273 if (F.empty()) {
1274 // Use the input filename.
1275 F = llvm::sys::path::stem(Input.getBaseInput());
1276
1277 // If we're compiling for an offload architecture (i.e. a CUDA device),
1278 // we need to make the file name for the device compilation different
1279 // from the host compilation.
1282 llvm::sys::path::replace_extension(F, "");
1284 Triple.str());
1285 F += "-";
1286 F += JA.getOffloadingArch().ArchName;
1287 }
1288 }
1289
1290 // If we're having more than one "-arch", we should name the files
1291 // differently so that every cc1 invocation writes to a different file.
1292 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1293 // name from the triple.
1294 if (hasMultipleArchs) {
1295 // First, remember the extension.
1296 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1297 // then, remove it.
1298 llvm::sys::path::replace_extension(F, "");
1299 // attach -<arch> to it.
1300 F += "-";
1301 F += Triple.getArchName();
1302 // put back the extension.
1303 llvm::sys::path::replace_extension(F, OldExtension);
1304 }
1305
1306 SmallString<32> Extension;
1307 Extension += "opt.";
1308 Extension += Format;
1309
1310 llvm::sys::path::replace_extension(F, Extension);
1311 CmdArgs.push_back(Args.MakeArgString(F));
1312 }
1313
1314 if (const Arg *A =
1315 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1316 CmdArgs.push_back("-opt-record-passes");
1317 CmdArgs.push_back(A->getValue());
1318 }
1319
1320 if (!Format.empty()) {
1321 CmdArgs.push_back("-opt-record-format");
1322 CmdArgs.push_back(Format.data());
1323 }
1324}
1325
1326void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1327 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1328 options::OPT_fno_aapcs_bitfield_width, true))
1329 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1330
1331 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1332 CmdArgs.push_back("-faapcs-bitfield-load");
1333}
1334
1335namespace {
1336void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1337 const ArgList &Args, ArgStringList &CmdArgs) {
1338 // Select the ABI to use.
1339 // FIXME: Support -meabi.
1340 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1341 const char *ABIName = nullptr;
1342 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1343 ABIName = A->getValue();
1344 else
1345 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1346
1347 CmdArgs.push_back("-target-abi");
1348 CmdArgs.push_back(ABIName);
1349}
1350
1351void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1352 auto StrictAlignIter =
1353 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1354 return Arg == "+strict-align" || Arg == "-strict-align";
1355 });
1356 if (StrictAlignIter != CmdArgs.rend() &&
1357 StringRef(*StrictAlignIter) == "+strict-align")
1358 CmdArgs.push_back("-Wunaligned-access");
1359}
1360}
1361
1362static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1363 ArgStringList &CmdArgs, bool isAArch64) {
1364 const llvm::Triple &Triple = TC.getEffectiveTriple();
1365 const Arg *A = isAArch64
1366 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1367 options::OPT_mbranch_protection_EQ)
1368 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1369 if (!A) {
1370 if (Triple.isOSOpenBSD() && isAArch64) {
1371 CmdArgs.push_back("-msign-return-address=non-leaf");
1372 CmdArgs.push_back("-msign-return-address-key=a_key");
1373 CmdArgs.push_back("-mbranch-target-enforce");
1374 }
1375 return;
1376 }
1377
1378 const Driver &D = TC.getDriver();
1379 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1380 D.Diag(diag::warn_incompatible_branch_protection_option)
1381 << Triple.getArchName();
1382
1383 StringRef Scope, Key;
1384 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1385
1386 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1387 Scope = A->getValue();
1388 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1389 D.Diag(diag::err_drv_unsupported_option_argument)
1390 << A->getSpelling() << Scope;
1391 Key = "a_key";
1392 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1393 BranchProtectionPAuthLR = false;
1394 GuardedControlStack = false;
1395 } else {
1396 StringRef DiagMsg;
1397 llvm::ARM::ParsedBranchProtection PBP;
1398 bool EnablePAuthLR = false;
1399
1400 // To know if we need to enable PAuth-LR As part of the standard branch
1401 // protection option, it needs to be determined if the feature has been
1402 // activated in the `march` argument. This information is stored within the
1403 // CmdArgs variable and can be found using a search.
1404 if (isAArch64) {
1405 auto isPAuthLR = [](const char *member) {
1406 llvm::AArch64::ExtensionInfo pauthlr_extension =
1407 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1408 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1409 member;
1410 };
1411
1412 if (llvm::any_of(CmdArgs, isPAuthLR))
1413 EnablePAuthLR = true;
1414 }
1415 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg, Triple,
1416 EnablePAuthLR))
1417 D.Diag(diag::err_drv_unsupported_option_argument)
1418 << A->getSpelling() << DiagMsg;
1419 if (!isAArch64 && PBP.Key == "b_key")
1420 D.Diag(diag::warn_unsupported_branch_protection)
1421 << "b-key" << A->getAsString(Args);
1422 Scope = PBP.Scope;
1423 Key = PBP.Key;
1424 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1425 IndirectBranches = PBP.BranchTargetEnforcement;
1426 GuardedControlStack = PBP.GuardedControlStack;
1427 }
1428
1429 Arg *PtrauthReturnsArg = Args.getLastArg(options::OPT_fptrauth_returns,
1430 options::OPT_fno_ptrauth_returns);
1431 bool HasPtrauthReturns =
1432 PtrauthReturnsArg &&
1433 PtrauthReturnsArg->getOption().matches(options::OPT_fptrauth_returns);
1434 // GCS is currently untested with ptrauth-returns, but enabling this could be
1435 // allowed in future after testing with a suitable system.
1436 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1437 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1438 D.Diag(diag::err_drv_unsupported_opt_for_target)
1439 << A->getAsString(Args) << Triple.getTriple();
1440 else if (HasPtrauthReturns)
1441 D.Diag(diag::err_drv_incompatible_options)
1442 << A->getAsString(Args) << "-fptrauth-returns";
1443 }
1444
1445 CmdArgs.push_back(
1446 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1447 if (Scope != "none")
1448 CmdArgs.push_back(
1449 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1450 if (BranchProtectionPAuthLR)
1451 CmdArgs.push_back(
1452 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1453 if (IndirectBranches)
1454 CmdArgs.push_back("-mbranch-target-enforce");
1455
1456 if (GuardedControlStack)
1457 CmdArgs.push_back("-mguarded-control-stack");
1458}
1459
1460void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1461 ArgStringList &CmdArgs, bool KernelOrKext) const {
1462 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1463
1464 // Determine floating point ABI from the options & target defaults.
1466 if (ABI == arm::FloatABI::Soft) {
1467 // Floating point operations and argument passing are soft.
1468 // FIXME: This changes CPP defines, we need -target-soft-float.
1469 CmdArgs.push_back("-msoft-float");
1470 CmdArgs.push_back("-mfloat-abi");
1471 CmdArgs.push_back("soft");
1472 } else if (ABI == arm::FloatABI::SoftFP) {
1473 // Floating point operations are hard, but argument passing is soft.
1474 CmdArgs.push_back("-mfloat-abi");
1475 CmdArgs.push_back("soft");
1476 } else {
1477 // Floating point operations and argument passing are hard.
1478 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1479 CmdArgs.push_back("-mfloat-abi");
1480 CmdArgs.push_back("hard");
1481 }
1482
1483 // Forward the -mglobal-merge option for explicit control over the pass.
1484 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1485 options::OPT_mno_global_merge)) {
1486 CmdArgs.push_back("-mllvm");
1487 if (A->getOption().matches(options::OPT_mno_global_merge))
1488 CmdArgs.push_back("-arm-global-merge=false");
1489 else
1490 CmdArgs.push_back("-arm-global-merge=true");
1491 }
1492
1493 if (!Args.hasFlag(options::OPT_mimplicit_float,
1494 options::OPT_mno_implicit_float, true))
1495 CmdArgs.push_back("-no-implicit-float");
1496
1497 if (Args.getLastArg(options::OPT_mcmse))
1498 CmdArgs.push_back("-mcmse");
1499
1500 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1501
1502 // Enable/disable return address signing and indirect branch targets.
1503 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1504
1505 AddUnalignedAccessWarning(CmdArgs);
1506}
1507
1508void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1509 ArgStringList &CmdArgs) const {
1510 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1511 if (Arg *A = Args.getLastArg(options::OPT_mxnack, options::OPT_mno_xnack))
1512 A->render(Args, CmdArgs);
1513 if (Arg *A = Args.getLastArg(options::OPT_msramecc, options::OPT_mno_sramecc))
1514 A->render(Args, CmdArgs);
1515}
1516
1517void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1518 const ArgList &Args, bool KernelOrKext,
1519 ArgStringList &CmdArgs) const {
1520 const ToolChain &TC = getToolChain();
1521
1522 // Add the target features
1523 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1524
1525 // Add target specific flags.
1526 switch (TC.getArch()) {
1527 default:
1528 break;
1529
1530 case llvm::Triple::arm:
1531 case llvm::Triple::armeb:
1532 case llvm::Triple::thumb:
1533 case llvm::Triple::thumbeb:
1534 // Use the effective triple, which takes into account the deployment target.
1535 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1536 break;
1537
1538 case llvm::Triple::aarch64:
1539 case llvm::Triple::aarch64_32:
1540 case llvm::Triple::aarch64_be:
1541 AddAArch64TargetArgs(Args, CmdArgs);
1542 break;
1543
1544 case llvm::Triple::amdgpu:
1545 AddAMDGPUTargetArgs(Args, CmdArgs);
1546 break;
1547
1548 case llvm::Triple::loongarch32:
1549 case llvm::Triple::loongarch64:
1550 AddLoongArchTargetArgs(Args, CmdArgs);
1551 break;
1552
1553 case llvm::Triple::mips:
1554 case llvm::Triple::mipsel:
1555 case llvm::Triple::mips64:
1556 case llvm::Triple::mips64el:
1557 AddMIPSTargetArgs(Args, CmdArgs);
1558 break;
1559
1560 case llvm::Triple::ppc:
1561 case llvm::Triple::ppcle:
1562 case llvm::Triple::ppc64:
1563 case llvm::Triple::ppc64le:
1564 AddPPCTargetArgs(Args, CmdArgs);
1565 break;
1566
1567 case llvm::Triple::riscv32:
1568 case llvm::Triple::riscv64:
1569 case llvm::Triple::riscv32be:
1570 case llvm::Triple::riscv64be:
1571 AddRISCVTargetArgs(Args, CmdArgs);
1572 break;
1573
1574 case llvm::Triple::sparc:
1575 case llvm::Triple::sparcel:
1576 case llvm::Triple::sparcv9:
1577 AddSparcTargetArgs(Args, CmdArgs);
1578 break;
1579
1580 case llvm::Triple::systemz:
1581 AddSystemZTargetArgs(Args, CmdArgs);
1582 break;
1583
1584 case llvm::Triple::x86:
1585 case llvm::Triple::x86_64:
1586 AddX86TargetArgs(Args, CmdArgs);
1587 break;
1588
1589 case llvm::Triple::lanai:
1590 AddLanaiTargetArgs(Args, CmdArgs);
1591 break;
1592
1593 case llvm::Triple::hexagon:
1594 AddHexagonTargetArgs(Args, CmdArgs);
1595 break;
1596
1597 case llvm::Triple::wasm32:
1598 case llvm::Triple::wasm64:
1599 AddWebAssemblyTargetArgs(Args, CmdArgs);
1600 break;
1601
1602 case llvm::Triple::ve:
1603 AddVETargetArgs(Args, CmdArgs);
1604 break;
1605 }
1606}
1607
1608namespace {
1609void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1610 ArgStringList &CmdArgs) {
1611 const char *ABIName = nullptr;
1612 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1613 ABIName = A->getValue();
1614 else if (Triple.isOSDarwin())
1615 ABIName = "darwinpcs";
1616 // TODO: we probably want to have some target hook here.
1617 else if (Triple.isOSLinux() &&
1618 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1619 ABIName = "pauthtest";
1620 else
1621 ABIName = "aapcs";
1622
1623 CmdArgs.push_back("-target-abi");
1624 CmdArgs.push_back(ABIName);
1625}
1626}
1627
1628void Clang::AddAArch64TargetArgs(const ArgList &Args,
1629 ArgStringList &CmdArgs) const {
1630 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1631
1632 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1633 Args.hasArg(options::OPT_mkernel) ||
1634 Args.hasArg(options::OPT_fapple_kext))
1635 CmdArgs.push_back("-disable-red-zone");
1636
1637 if (!Args.hasFlag(options::OPT_mimplicit_float,
1638 options::OPT_mno_implicit_float, true))
1639 CmdArgs.push_back("-no-implicit-float");
1640
1641 RenderAArch64ABI(Triple, Args, CmdArgs);
1642
1643 // Forward the -mglobal-merge option for explicit control over the pass.
1644 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1645 options::OPT_mno_global_merge)) {
1646 CmdArgs.push_back("-mllvm");
1647 if (A->getOption().matches(options::OPT_mno_global_merge))
1648 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1649 else
1650 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1651 }
1652
1653 // Handle -msve_vector_bits=<bits>
1654 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1655 StringRef VScaleMax) {
1656 StringRef Val = A->getValue();
1657 const Driver &D = getToolChain().getDriver();
1658 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1659 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1660 Val == "1024+" || Val == "2048+") {
1661 unsigned Bits = 0;
1662 if (!Val.consume_back("+")) {
1663 bool Invalid = Val.getAsInteger(10, Bits);
1664 (void)Invalid;
1665 assert(!Invalid && "Failed to parse value");
1666 CmdArgs.push_back(
1667 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1668 }
1669
1670 bool Invalid = Val.getAsInteger(10, Bits);
1671 (void)Invalid;
1672 assert(!Invalid && "Failed to parse value");
1673
1674 CmdArgs.push_back(
1675 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1676 } else if (Val == "scalable") {
1677 // Silently drop requests for vector-length agnostic code as it's implied.
1678 } else {
1679 // Handle the unsupported values passed to msve-vector-bits.
1680 D.Diag(diag::err_drv_unsupported_option_argument)
1681 << A->getSpelling() << Val;
1682 }
1683 };
1684 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1685 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1686 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1687 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1688
1689 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1690
1691 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1692 CmdArgs.push_back("-tune-cpu");
1693 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1694 }
1695
1696 AddUnalignedAccessWarning(CmdArgs);
1697
1698 if (Triple.isOSDarwin() ||
1699 (Triple.isOSLinux() &&
1700 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1701 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1702 options::OPT_fno_ptrauth_intrinsics);
1703 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1704 options::OPT_fno_ptrauth_calls);
1705 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1706 options::OPT_fno_ptrauth_returns);
1707 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1708 options::OPT_fno_ptrauth_auth_traps);
1709 Args.addOptInFlag(
1710 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1711 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1712 Args.addOptInFlag(
1713 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1714 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1715 Args.addOptInFlag(
1716 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1717 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1718 Args.addOptInFlag(
1719 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1720 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1721 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1722 options::OPT_fno_ptrauth_indirect_gotos);
1723 }
1724 if (Triple.isOSLinux() &&
1725 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1726 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1727 options::OPT_fno_ptrauth_init_fini);
1728 Args.addOptInFlag(
1729 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1730 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1731 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1732 options::OPT_fno_ptrauth_elf_got);
1733 }
1734 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1735 options::OPT_fno_aarch64_jump_table_hardening);
1736
1737 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1738 options::OPT_fno_ptrauth_objc_isa);
1739 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1740 options::OPT_fno_ptrauth_objc_interface_sel);
1741 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1742 options::OPT_fno_ptrauth_objc_class_ro);
1743
1744 // Enable/disable return address signing and indirect branch targets.
1745 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1746}
1747
1748void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1749 ArgStringList &CmdArgs) const {
1750 const llvm::Triple &Triple = getToolChain().getTriple();
1751
1752 CmdArgs.push_back("-target-abi");
1753 CmdArgs.push_back(
1754 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1755 .data());
1756
1757 // Handle -mtune.
1758 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1759 std::string TuneCPU = A->getValue();
1760 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1761 CmdArgs.push_back("-tune-cpu");
1762 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1763 }
1764
1765 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1766 options::OPT_mno_annotate_tablejump)) {
1767 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1768 CmdArgs.push_back("-mllvm");
1769 CmdArgs.push_back("-loongarch-annotate-tablejump");
1770 }
1771 }
1772}
1773
1774void Clang::AddMIPSTargetArgs(const ArgList &Args,
1775 ArgStringList &CmdArgs) const {
1776 const Driver &D = getToolChain().getDriver();
1777 StringRef CPUName;
1778 StringRef ABIName;
1779 const llvm::Triple &Triple = getToolChain().getTriple();
1780 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1781
1782 CmdArgs.push_back("-target-abi");
1783 CmdArgs.push_back(ABIName.data());
1784
1785 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1786 if (ABI == mips::FloatABI::Soft) {
1787 // Floating point operations and argument passing are soft.
1788 CmdArgs.push_back("-msoft-float");
1789 CmdArgs.push_back("-mfloat-abi");
1790 CmdArgs.push_back("soft");
1791 } else {
1792 // Floating point operations and argument passing are hard.
1793 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1794 CmdArgs.push_back("-mfloat-abi");
1795 CmdArgs.push_back("hard");
1796 }
1797
1798 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1799 options::OPT_mno_ldc1_sdc1)) {
1800 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1801 CmdArgs.push_back("-mllvm");
1802 CmdArgs.push_back("-mno-ldc1-sdc1");
1803 }
1804 }
1805
1806 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1807 options::OPT_mno_check_zero_division)) {
1808 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1809 CmdArgs.push_back("-mllvm");
1810 CmdArgs.push_back("-mno-check-zero-division");
1811 }
1812 }
1813
1814 if (Args.getLastArg(options::OPT_mfix4300)) {
1815 CmdArgs.push_back("-mllvm");
1816 CmdArgs.push_back("-mfix4300");
1817 }
1818
1819 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1820 StringRef v = A->getValue();
1821 CmdArgs.push_back("-mllvm");
1822 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1823 A->claim();
1824 }
1825
1826 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1827 Arg *ABICalls =
1828 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1829
1830 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1831 // -mgpopt is the default for static, -fno-pic environments but these two
1832 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1833 // the only case where -mllvm -mgpopt is passed.
1834 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1835 // passed explicitly when compiling something with -mabicalls
1836 // (implictly) in affect. Currently the warning is in the backend.
1837 //
1838 // When the ABI in use is N64, we also need to determine the PIC mode that
1839 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1840 bool NoABICalls =
1841 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1842
1843 llvm::Reloc::Model RelocationModel;
1844 unsigned PICLevel;
1845 bool IsPIE;
1846 std::tie(RelocationModel, PICLevel, IsPIE) =
1847 ParsePICArgs(getToolChain(), Args);
1848
1849 NoABICalls = NoABICalls ||
1850 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1851
1852 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1853 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1854 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1855 CmdArgs.push_back("-mllvm");
1856 CmdArgs.push_back("-mgpopt");
1857
1858 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1859 options::OPT_mno_local_sdata);
1860 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1861 options::OPT_mno_extern_sdata);
1862 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1863 options::OPT_mno_embedded_data);
1864 if (LocalSData) {
1865 CmdArgs.push_back("-mllvm");
1866 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1867 CmdArgs.push_back("-mlocal-sdata=1");
1868 } else {
1869 CmdArgs.push_back("-mlocal-sdata=0");
1870 }
1871 LocalSData->claim();
1872 }
1873
1874 if (ExternSData) {
1875 CmdArgs.push_back("-mllvm");
1876 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1877 CmdArgs.push_back("-mextern-sdata=1");
1878 } else {
1879 CmdArgs.push_back("-mextern-sdata=0");
1880 }
1881 ExternSData->claim();
1882 }
1883
1884 if (EmbeddedData) {
1885 CmdArgs.push_back("-mllvm");
1886 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1887 CmdArgs.push_back("-membedded-data=1");
1888 } else {
1889 CmdArgs.push_back("-membedded-data=0");
1890 }
1891 EmbeddedData->claim();
1892 }
1893
1894 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1895 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1896
1897 if (GPOpt)
1898 GPOpt->claim();
1899
1900 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1901 StringRef Val = StringRef(A->getValue());
1902 if (mips::hasCompactBranches(CPUName)) {
1903 if (Val == "never" || Val == "always" || Val == "optimal") {
1904 CmdArgs.push_back("-mllvm");
1905 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1906 } else
1907 D.Diag(diag::err_drv_unsupported_option_argument)
1908 << A->getSpelling() << Val;
1909 } else
1910 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1911 }
1912
1913 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1914 options::OPT_mno_relax_pic_calls)) {
1915 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1916 CmdArgs.push_back("-mllvm");
1917 CmdArgs.push_back("-mips-jalr-reloc=0");
1918 }
1919 }
1920}
1921
1922void Clang::AddPPCTargetArgs(const ArgList &Args,
1923 ArgStringList &CmdArgs) const {
1924 const Driver &D = getToolChain().getDriver();
1925 const llvm::Triple &T = getToolChain().getTriple();
1926 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1927 CmdArgs.push_back("-tune-cpu");
1928 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
1929 CmdArgs.push_back(Args.MakeArgString(CPU));
1930 }
1931
1932 // Select the ABI to use.
1933 const char *ABIName = nullptr;
1934 if (T.isOSBinFormatELF()) {
1935 switch (getToolChain().getArch()) {
1936 case llvm::Triple::ppc64: {
1937 if (T.isPPC64ELFv2ABI())
1938 ABIName = "elfv2";
1939 else
1940 ABIName = "elfv1";
1941 break;
1942 }
1943 case llvm::Triple::ppc64le:
1944 ABIName = "elfv2";
1945 break;
1946 default:
1947 break;
1948 }
1949 }
1950
1951 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1952 bool VecExtabi = false;
1953 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1954 StringRef V = A->getValue();
1955 if (V == "ieeelongdouble") {
1956 IEEELongDouble = true;
1957 A->claim();
1958 } else if (V == "ibmlongdouble") {
1959 IEEELongDouble = false;
1960 A->claim();
1961 } else if (V == "vec-default") {
1962 VecExtabi = false;
1963 A->claim();
1964 } else if (V == "vec-extabi") {
1965 VecExtabi = true;
1966 A->claim();
1967 } else if (V == "elfv1") {
1968 ABIName = "elfv1";
1969 A->claim();
1970 } else if (V == "elfv2") {
1971 ABIName = "elfv2";
1972 A->claim();
1973 } else if (V != "altivec")
1974 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1975 // the option if given as we don't have backend support for any targets
1976 // that don't use the altivec abi.
1977 ABIName = A->getValue();
1978 }
1979 if (IEEELongDouble)
1980 CmdArgs.push_back("-mabi=ieeelongdouble");
1981 if (VecExtabi) {
1982 if (!T.isOSAIX())
1983 D.Diag(diag::err_drv_unsupported_opt_for_target)
1984 << "-mabi=vec-extabi" << T.str();
1985 CmdArgs.push_back("-mabi=vec-extabi");
1986 }
1987
1988 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
1989 CmdArgs.push_back("-disable-red-zone");
1990
1992 if (FloatABI == ppc::FloatABI::Soft) {
1993 // Floating point operations and argument passing are soft.
1994 CmdArgs.push_back("-msoft-float");
1995 CmdArgs.push_back("-mfloat-abi");
1996 CmdArgs.push_back("soft");
1997 } else {
1998 // Floating point operations and argument passing are hard.
1999 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2000 CmdArgs.push_back("-mfloat-abi");
2001 CmdArgs.push_back("hard");
2002 }
2003
2004 if (ABIName) {
2005 CmdArgs.push_back("-target-abi");
2006 CmdArgs.push_back(ABIName);
2007 }
2008}
2009
2010void Clang::AddRISCVTargetArgs(const ArgList &Args,
2011 ArgStringList &CmdArgs) const {
2012 const llvm::Triple &Triple = getToolChain().getTriple();
2013 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2014
2015 CmdArgs.push_back("-target-abi");
2016 CmdArgs.push_back(ABIName.data());
2017
2018 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2019 CmdArgs.push_back("-msmall-data-limit");
2020 CmdArgs.push_back(A->getValue());
2021 }
2022
2023 if (!Args.hasFlag(options::OPT_mimplicit_float,
2024 options::OPT_mno_implicit_float, true))
2025 CmdArgs.push_back("-no-implicit-float");
2026
2027 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2028 if (!TuneCPU)
2029 return;
2030 if (!TuneCPU->empty()) {
2031 CmdArgs.push_back("-tune-cpu");
2032 if (*TuneCPU == "native")
2033 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2034 else
2035 // TuneCPU might or might not be the original -mtune string, so we
2036 // have to create a new copy here.
2037 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2038 }
2039
2040 // Handle -mrvv-vector-bits=<bits>
2041 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2042 StringRef Val = A->getValue();
2043 const Driver &D = getToolChain().getDriver();
2044
2045 // Get minimum VLen from march.
2046 unsigned MinVLen = 0;
2047 std::string Arch = riscv::getRISCVArch(Args, Triple);
2048 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2049 Arch, /*EnableExperimentalExtensions*/ true);
2050 // Ignore parsing error.
2051 if (!errorToBool(ISAInfo.takeError()))
2052 MinVLen = (*ISAInfo)->getMinVLen();
2053
2054 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2055 // as integer as long as we have a MinVLen.
2056 unsigned Bits = 0;
2057 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2058 Bits = MinVLen;
2059 } else if (!Val.getAsInteger(10, Bits)) {
2060 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2061 // at least MinVLen.
2062 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2063 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2064 Bits = 0;
2065 }
2066
2067 // If we got a valid value try to use it.
2068 if (Bits != 0) {
2069 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2070 CmdArgs.push_back(
2071 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2072 CmdArgs.push_back(
2073 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2074 } else if (Val != "scalable") {
2075 // Handle the unsupported values passed to mrvv-vector-bits.
2076 D.Diag(diag::err_drv_unsupported_option_argument)
2077 << A->getSpelling() << Val;
2078 }
2079 }
2080}
2081
2082void Clang::AddSparcTargetArgs(const ArgList &Args,
2083 ArgStringList &CmdArgs) const {
2085 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2086
2087 if (FloatABI == sparc::FloatABI::Soft) {
2088 // Floating point operations and argument passing are soft.
2089 CmdArgs.push_back("-msoft-float");
2090 CmdArgs.push_back("-mfloat-abi");
2091 CmdArgs.push_back("soft");
2092 } else {
2093 // Floating point operations and argument passing are hard.
2094 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2095 CmdArgs.push_back("-mfloat-abi");
2096 CmdArgs.push_back("hard");
2097 }
2098
2099 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2100 StringRef Name = A->getValue();
2101 std::string TuneCPU;
2102 if (Name == "native")
2103 TuneCPU = std::string(llvm::sys::getHostCPUName());
2104 else
2105 TuneCPU = std::string(Name);
2106
2107 CmdArgs.push_back("-tune-cpu");
2108 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2109 }
2110}
2111
2112void Clang::AddSystemZTargetArgs(const ArgList &Args,
2113 ArgStringList &CmdArgs) const {
2114 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2115 CmdArgs.push_back("-tune-cpu");
2116 if (strcmp(A->getValue(), "native") == 0)
2117 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2118 else
2119 CmdArgs.push_back(A->getValue());
2120 }
2121
2122 bool HasBackchain =
2123 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2124 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2125 options::OPT_mno_packed_stack, false);
2127 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2128 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2129
2130 // Only hard float ABI (-mhard-float) is supported on z/OS.
2131 const Driver &D = getToolChain().getDriver();
2132 const llvm::Triple &Triple = getToolChain().getTriple();
2133 if (HasSoftFloat && Triple.isOSzOS()) {
2134 D.Diag(diag::err_drv_unsupported_opt_for_target)
2135 << "-msoft-float" << Triple.str();
2136 }
2137 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2138 D.Diag(diag::err_drv_unsupported_opt)
2139 << "-mpacked-stack -mbackchain -mhard-float";
2140 }
2141 if (HasBackchain)
2142 CmdArgs.push_back("-mbackchain");
2143 if (HasPackedStack)
2144 CmdArgs.push_back("-mpacked-stack");
2145 if (HasSoftFloat) {
2146 // Floating point operations and argument passing are soft.
2147 CmdArgs.push_back("-msoft-float");
2148 CmdArgs.push_back("-mfloat-abi");
2149 CmdArgs.push_back("soft");
2150 }
2151
2152 if (Triple.isOSzOS())
2153 Args.AddLastArg(CmdArgs, options::OPT_mzos_ppa1_name,
2154 options::OPT_mno_zos_ppa1_name);
2155}
2156
2157void Clang::AddX86TargetArgs(const ArgList &Args,
2158 ArgStringList &CmdArgs) const {
2159 const Driver &D = getToolChain().getDriver();
2160 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2161
2162 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2163 Args.hasArg(options::OPT_mkernel) ||
2164 Args.hasArg(options::OPT_fapple_kext))
2165 CmdArgs.push_back("-disable-red-zone");
2166
2167 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2168 options::OPT_mno_tls_direct_seg_refs, true))
2169 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2170
2171 // Default to avoid implicit floating-point for kernel/kext code, but allow
2172 // that to be overridden with -mno-soft-float.
2173 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2174 Args.hasArg(options::OPT_fapple_kext));
2175 if (Arg *A = Args.getLastArg(
2176 options::OPT_msoft_float, options::OPT_mno_soft_float,
2177 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2178 const Option &O = A->getOption();
2179 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2180 O.matches(options::OPT_msoft_float));
2181 }
2182 if (NoImplicitFloat)
2183 CmdArgs.push_back("-no-implicit-float");
2184
2185 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2186 StringRef Value = A->getValue();
2187 if (Value == "intel" || Value == "att") {
2188 CmdArgs.push_back("-mllvm");
2189 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2190 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2191 } else {
2192 D.Diag(diag::err_drv_unsupported_option_argument)
2193 << A->getSpelling() << Value;
2194 }
2195 } else if (D.IsCLMode()) {
2196 CmdArgs.push_back("-mllvm");
2197 CmdArgs.push_back("-x86-asm-syntax=intel");
2198 }
2199
2200 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2201 options::OPT_mno_skip_rax_setup))
2202 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2203 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2204
2205 // Set flags to support MCU ABI.
2206 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2207 CmdArgs.push_back("-mfloat-abi");
2208 CmdArgs.push_back("soft");
2209 CmdArgs.push_back("-mstack-alignment=4");
2210 }
2211
2212 // Handle -mtune.
2213
2214 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2215 std::string TuneCPU;
2216 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2217 TuneCPU = "generic";
2218
2219 // Override based on -mtune.
2220 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2221 StringRef Name = A->getValue();
2222
2223 if (Name == "native") {
2224 Name = llvm::sys::getHostCPUName();
2225 if (!Name.empty())
2226 TuneCPU = std::string(Name);
2227 } else
2228 TuneCPU = std::string(Name);
2229 }
2230
2231 if (!TuneCPU.empty()) {
2232 CmdArgs.push_back("-tune-cpu");
2233 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2234 }
2235}
2236
2237static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2238 size_t Index = Option.find(Delimiter);
2239 if (Index != StringRef::npos)
2240 Option = Option.substr(0, Index);
2241 return Option;
2242}
2243
2244static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2245 Opt = getOptionName(Opt);
2246 if (CmdArgs.size() < 2)
2247 return;
2248
2249 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2250 StringRef Option = *It;
2251 if (!Option.starts_with(Opt))
2252 continue;
2253 Option = getOptionName(Option);
2254 if (Option != Opt)
2255 continue;
2256 if (StringRef(*(It - 1)) != "-mllvm")
2257 continue;
2258
2259 It = CmdArgs.erase(It);
2260 CmdArgs.erase(It - 1);
2261 return;
2262 }
2263}
2264
2265static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2266 checkAndRemoveLLVMArg(CmdArgs, A);
2267 CmdArgs.push_back("-mllvm");
2268 CmdArgs.push_back(A);
2269}
2270
2271static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2272 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2273 StringRef Option = *It;
2274 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2275 It = CmdArgs.erase(It);
2276 Ie = CmdArgs.end();
2277 } else {
2278 ++It;
2279 }
2280 }
2281
2282 CmdArgs.push_back("-menable-no-infs");
2283 CmdArgs.push_back("-menable-no-nans");
2284 CmdArgs.push_back("-fapprox-func");
2285 CmdArgs.push_back("-funsafe-math-optimizations");
2286 CmdArgs.push_back("-fno-signed-zeros");
2287 CmdArgs.push_back("-mreassociate");
2288 CmdArgs.push_back("-freciprocal-math");
2289 CmdArgs.push_back("-ffp-contract=fast");
2290 CmdArgs.push_back("-ffast-math");
2291 CmdArgs.push_back("-ffinite-math-only");
2292 CmdArgs.push_back("-D__FAST_MATH__");
2293 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2294}
2295
2296static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2297 ArgStringList &CmdArgs) {
2298 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2299 bool HasHVX = HvxVerOpt.has_value();
2300 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2301 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2302 options::OPT_mhexagon_hvx_ieee_fp) ||
2303 !HasHVX)
2304 return;
2305 unsigned HvxVerNum = 0;
2306 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2307 HvxVerNum = 0;
2308
2309 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2310 options::OPT_mhexagon_hvx_qfloat_EQ,
2311 options::OPT_mhexagon_hvx_ieee_fp)) {
2312 if (HvxVerNum >= 79) {
2313 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2314 const char *Mode =
2315 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2316 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2317 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2318 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2319 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2320 .Default(nullptr);
2321 if (!Mode) {
2322 D.Diag(diag::err_drv_invalid_value)
2323 << A->getAsString(Args) << A->getValue();
2324 return;
2325 }
2326 pushBackLLVMArg(CmdArgs, Mode);
2327 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2329 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2330 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2332 } else {
2333 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2334 }
2335 } else {
2336 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2337 options::OPT_mhexagon_hvx_qfloat_EQ,
2338 options::OPT_mno_hexagon_hvx_qfloat);
2339 QFloatArg &&
2340 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2341 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2342 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2343 << (std::string("HVX ") + HvxVer +
2344 "; falling back to legacy qfloat mode");
2345 }
2346 }
2347 }
2348}
2349
2350void Clang::AddHexagonTargetArgs(const ArgList &Args,
2351 ArgStringList &CmdArgs) const {
2352 CmdArgs.push_back("-mqdsp6-compat");
2353 CmdArgs.push_back("-Wreturn-type");
2354
2356 CmdArgs.push_back("-mllvm");
2357 CmdArgs.push_back(
2358 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2359 }
2360
2361 if (!Args.hasArg(options::OPT_fno_short_enums))
2362 CmdArgs.push_back("-fshort-enums");
2363 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2364 CmdArgs.push_back("-mllvm");
2365 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2366 }
2367 CmdArgs.push_back("-mllvm");
2368 CmdArgs.push_back("-machine-sink-split=0");
2369
2370 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2371}
2372
2373void Clang::AddLanaiTargetArgs(const ArgList &Args,
2374 ArgStringList &CmdArgs) const {
2375 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2376 StringRef CPUName = A->getValue();
2377
2378 CmdArgs.push_back("-target-cpu");
2379 CmdArgs.push_back(Args.MakeArgString(CPUName));
2380 }
2381 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2382 StringRef Value = A->getValue();
2383 // Only support mregparm=4 to support old usage. Report error for all other
2384 // cases.
2385 int Mregparm;
2386 if (Value.getAsInteger(10, Mregparm)) {
2387 if (Mregparm != 4) {
2389 diag::err_drv_unsupported_option_argument)
2390 << A->getSpelling() << Value;
2391 }
2392 }
2393 }
2394}
2395
2396void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2397 ArgStringList &CmdArgs) const {
2398 // Default to "hidden" visibility.
2399 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2400 options::OPT_fvisibility_ms_compat))
2401 CmdArgs.push_back("-fvisibility=hidden");
2402}
2403
2404void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2405 // Floating point operations and argument passing are hard.
2406 CmdArgs.push_back("-mfloat-abi");
2407 CmdArgs.push_back("hard");
2408}
2409
2410void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2411 StringRef Target, const InputInfo &Output,
2412 const InputInfo &Input, const ArgList &Args) const {
2413 // If this is a dry run, do not create the compilation database file.
2414 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2415 return;
2416
2417 using llvm::yaml::escape;
2418 const Driver &D = getToolChain().getDriver();
2419
2420 if (!CompilationDatabase) {
2421 std::error_code EC;
2422 auto File = std::make_unique<llvm::raw_fd_ostream>(
2423 Filename, EC,
2424 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2425 if (EC) {
2426 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2427 << EC.message();
2428 return;
2429 }
2430 CompilationDatabase = std::move(File);
2431 }
2432 auto &CDB = *CompilationDatabase;
2433 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2434 if (!CWD)
2435 CWD = ".";
2436 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2437 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2438 if (Output.isFilename())
2439 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2440 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2441 SmallString<128> Buf;
2442 Buf = "-x";
2443 Buf += types::getTypeName(Input.getType());
2444 CDB << ", \"" << escape(Buf) << "\"";
2445 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2446 Buf = "--sysroot=";
2447 Buf += D.SysRoot;
2448 CDB << ", \"" << escape(Buf) << "\"";
2449 }
2450 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2451 if (Output.isFilename())
2452 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2453 for (auto &A: Args) {
2454 auto &O = A->getOption();
2455 // Skip language selection, which is positional.
2456 if (O.getID() == options::OPT_x)
2457 continue;
2458 // Skip writing dependency output and the compilation database itself.
2459 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2460 continue;
2461 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2462 continue;
2463 // Skip inputs.
2464 if (O.getKind() == Option::InputClass)
2465 continue;
2466 // Skip output.
2467 if (O.getID() == options::OPT_o)
2468 continue;
2469 // All other arguments are quoted and appended.
2470 ArgStringList ASL;
2471 A->render(Args, ASL);
2472 for (auto &it: ASL)
2473 CDB << ", \"" << escape(it) << "\"";
2474 }
2475 Buf = "--target=";
2476 Buf += Target;
2477 CDB << ", \"" << escape(Buf) << "\"]},\n";
2478}
2479
2480void Clang::DumpCompilationDatabaseFragmentToDir(
2481 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2482 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2483 // If this is a dry run, do not create the compilation database file.
2484 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2485 return;
2486
2487 if (CompilationDatabase)
2488 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2489
2490 SmallString<256> Path = Dir;
2491 const auto &Driver = C.getDriver();
2492 Driver.getVFS().makeAbsolute(Path);
2493 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2494 if (Err) {
2495 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2496 return;
2497 }
2498
2499 llvm::sys::path::append(
2500 Path,
2501 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2502 int FD;
2503 SmallString<256> TempPath;
2504 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2505 llvm::sys::fs::OF_Text);
2506 if (Err) {
2507 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2508 return;
2509 }
2510 CompilationDatabase =
2511 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2512 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2513}
2514
2515static bool CheckARMImplicitITArg(StringRef Value) {
2516 return Value == "always" || Value == "never" || Value == "arm" ||
2517 Value == "thumb";
2518}
2519
2520static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2521 StringRef Value) {
2522 CmdArgs.push_back("-mllvm");
2523 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2524}
2525
2527 const ArgList &Args,
2528 ArgStringList &CmdArgs,
2529 const Driver &D) {
2530 // Default to -mno-relax-all.
2531 //
2532 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2533 // cannot be done by assembler branch relaxation as it needs a free temporary
2534 // register. Because of this, branch relaxation is handled by a MachineIR pass
2535 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2536 // MachineIR branch relaxation inaccurate and it will miss cases where an
2537 // indirect branch is necessary.
2538 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2539 options::OPT_mno_relax_all);
2540
2541 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2542 options::OPT_mno_incremental_linker_compatible);
2543
2544 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2545
2546 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2547 options::OPT_fno_emit_compact_unwind_non_canonical);
2548
2549 // If you add more args here, also add them to the block below that
2550 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2551
2552 // When passing -I arguments to the assembler we sometimes need to
2553 // unconditionally take the next argument. For example, when parsing
2554 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2555 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2556 // arg after parsing the '-I' arg.
2557 bool TakeNextArg = false;
2558
2559 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2560 bool IsELF = Triple.isOSBinFormatELF();
2561 bool Crel = false, ExperimentalCrel = false;
2562 StringRef RelocSectionSym;
2563 bool SFrame = false, ExperimentalSFrame = false;
2564 bool ImplicitMapSyms = false;
2565 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2566 bool UseNoExecStack = false;
2567 bool Msa = false;
2568 const char *MipsTargetFeature = nullptr;
2569 llvm::SmallVector<const char *> SparcTargetFeatures;
2570 StringRef ImplicitIt;
2571 for (const Arg *A :
2572 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2573 options::OPT_mimplicit_it_EQ)) {
2574 A->claim();
2575
2576 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2577 switch (C.getDefaultToolChain().getArch()) {
2578 case llvm::Triple::arm:
2579 case llvm::Triple::armeb:
2580 case llvm::Triple::thumb:
2581 case llvm::Triple::thumbeb:
2582 // Only store the value; the last value set takes effect.
2583 ImplicitIt = A->getValue();
2584 if (!CheckARMImplicitITArg(ImplicitIt))
2585 D.Diag(diag::err_drv_unsupported_option_argument)
2586 << A->getSpelling() << ImplicitIt;
2587 continue;
2588 default:
2589 break;
2590 }
2591 }
2592
2593 for (StringRef Value : A->getValues()) {
2594 if (TakeNextArg) {
2595 CmdArgs.push_back(Value.data());
2596 TakeNextArg = false;
2597 continue;
2598 }
2599
2600 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2601 Value == "-mbig-obj")
2602 continue; // LLVM handles bigobj automatically
2603
2604 auto Equal = Value.split('=');
2605 auto checkArg = [&](bool ValidTarget,
2606 std::initializer_list<const char *> Set) {
2607 if (!ValidTarget) {
2608 D.Diag(diag::err_drv_unsupported_opt_for_target)
2609 << (Twine("-Wa,") + Equal.first + "=").str()
2610 << Triple.getTriple();
2611 } else if (!llvm::is_contained(Set, Equal.second)) {
2612 D.Diag(diag::err_drv_unsupported_option_argument)
2613 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2614 }
2615 };
2616 switch (C.getDefaultToolChain().getArch()) {
2617 default:
2618 break;
2619 case llvm::Triple::x86:
2620 case llvm::Triple::x86_64:
2621 if (Equal.first == "-mrelax-relocations" ||
2622 Equal.first == "--mrelax-relocations") {
2623 UseRelaxRelocations = Equal.second == "yes";
2624 checkArg(IsELF, {"yes", "no"});
2625 continue;
2626 }
2627 if (Value == "-msse2avx") {
2628 CmdArgs.push_back("-msse2avx");
2629 continue;
2630 }
2631 break;
2632 case llvm::Triple::wasm32:
2633 case llvm::Triple::wasm64:
2634 if (Value == "--no-type-check") {
2635 CmdArgs.push_back("-mno-type-check");
2636 continue;
2637 }
2638 break;
2639 case llvm::Triple::thumb:
2640 case llvm::Triple::thumbeb:
2641 case llvm::Triple::arm:
2642 case llvm::Triple::armeb:
2643 if (Equal.first == "-mimplicit-it") {
2644 // Only store the value; the last value set takes effect.
2645 ImplicitIt = Equal.second;
2646 checkArg(true, {"always", "never", "arm", "thumb"});
2647 continue;
2648 }
2649 if (Value == "-mthumb")
2650 // -mthumb has already been processed in ComputeLLVMTriple()
2651 // recognize but skip over here.
2652 continue;
2653 break;
2654 case llvm::Triple::aarch64:
2655 case llvm::Triple::aarch64_be:
2656 case llvm::Triple::aarch64_32:
2657 if (Equal.first == "-mmapsyms") {
2658 ImplicitMapSyms = Equal.second == "implicit";
2659 checkArg(IsELF, {"default", "implicit"});
2660 continue;
2661 }
2662 break;
2663 case llvm::Triple::mips:
2664 case llvm::Triple::mipsel:
2665 case llvm::Triple::mips64:
2666 case llvm::Triple::mips64el:
2667 if (Value == "--trap") {
2668 CmdArgs.push_back("-target-feature");
2669 CmdArgs.push_back("+use-tcc-in-div");
2670 continue;
2671 }
2672 if (Value == "--break") {
2673 CmdArgs.push_back("-target-feature");
2674 CmdArgs.push_back("-use-tcc-in-div");
2675 continue;
2676 }
2677 if (Value.starts_with("-msoft-float")) {
2678 CmdArgs.push_back("-target-feature");
2679 CmdArgs.push_back("+soft-float");
2680 continue;
2681 }
2682 if (Value.starts_with("-mhard-float")) {
2683 CmdArgs.push_back("-target-feature");
2684 CmdArgs.push_back("-soft-float");
2685 continue;
2686 }
2687 if (Value == "-mmsa") {
2688 Msa = true;
2689 continue;
2690 }
2691 if (Value == "-mno-msa") {
2692 Msa = false;
2693 continue;
2694 }
2695 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2696 .Case("-mips1", "+mips1")
2697 .Case("-mips2", "+mips2")
2698 .Case("-mips3", "+mips3")
2699 .Case("-mips4", "+mips4")
2700 .Case("-mips5", "+mips5")
2701 .Case("-mips32", "+mips32")
2702 .Case("-mips32r2", "+mips32r2")
2703 .Case("-mips32r3", "+mips32r3")
2704 .Case("-mips32r5", "+mips32r5")
2705 .Case("-mips32r6", "+mips32r6")
2706 .Case("-mips64", "+mips64")
2707 .Case("-mips64r2", "+mips64r2")
2708 .Case("-mips64r3", "+mips64r3")
2709 .Case("-mips64r5", "+mips64r5")
2710 .Case("-mips64r6", "+mips64r6")
2711 .Default(nullptr);
2712 if (MipsTargetFeature)
2713 continue;
2714 break;
2715
2716 case llvm::Triple::sparc:
2717 case llvm::Triple::sparcel:
2718 case llvm::Triple::sparcv9:
2719 if (Value == "--undeclared-regs") {
2720 // LLVM already allows undeclared use of G registers, so this option
2721 // becomes a no-op. This solely exists for GNU compatibility.
2722 // TODO implement --no-undeclared-regs
2723 continue;
2724 }
2725 SparcTargetFeatures =
2726 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2727 .Case("-Av8", {"-v8plus"})
2728 .Case("-Av8plus", {"+v8plus", "+v9"})
2729 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2730 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2731 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2732 .Case("-Av9", {"+v9"})
2733 .Case("-Av9a", {"+v9", "+vis"})
2734 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2735 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2736 .Default({});
2737 if (!SparcTargetFeatures.empty())
2738 continue;
2739 break;
2740 }
2741
2742 if (Value == "-force_cpusubtype_ALL") {
2743 // Do nothing, this is the default and we don't support anything else.
2744 } else if (Value == "-L") {
2745 CmdArgs.push_back("-msave-temp-labels");
2746 } else if (Value == "--fatal-warnings") {
2747 CmdArgs.push_back("-massembler-fatal-warnings");
2748 } else if (Value == "--no-warn" || Value == "-W") {
2749 CmdArgs.push_back("-massembler-no-warn");
2750 } else if (Value == "--noexecstack") {
2751 UseNoExecStack = true;
2752 } else if (Value.starts_with("-compress-debug-sections") ||
2753 Value.starts_with("--compress-debug-sections") ||
2754 Value == "-nocompress-debug-sections" ||
2755 Value == "--nocompress-debug-sections") {
2756 CmdArgs.push_back(Value.data());
2757 } else if (Value == "--crel") {
2758 Crel = true;
2759 } else if (Value == "--no-crel") {
2760 Crel = false;
2761 } else if (Value == "--allow-experimental-crel") {
2762 ExperimentalCrel = true;
2763 } else if (Value.starts_with("--reloc-section-sym=")) {
2764 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2765 } else if (Value.starts_with("-I")) {
2766 CmdArgs.push_back(Value.data());
2767 // We need to consume the next argument if the current arg is a plain
2768 // -I. The next arg will be the include directory.
2769 if (Value == "-I")
2770 TakeNextArg = true;
2771 } else if (Value.starts_with("-gdwarf-")) {
2772 // "-gdwarf-N" options are not cc1as options.
2773 unsigned DwarfVersion = DwarfVersionNum(Value);
2774 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2775 CmdArgs.push_back(Value.data());
2776 } else {
2777 RenderDebugEnablingArgs(Args, CmdArgs,
2778 llvm::codegenoptions::DebugInfoConstructor,
2779 DwarfVersion, llvm::DebuggerKind::Default);
2780 }
2781 } else if (Value == "--gsframe") {
2782 SFrame = true;
2783 } else if (Value == "--allow-experimental-sframe") {
2784 ExperimentalSFrame = true;
2785 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2786 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2787 // Do nothing, we'll validate it later.
2788 } else if (Value == "-defsym" || Value == "--defsym") {
2789 if (A->getNumValues() != 2) {
2790 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2791 break;
2792 }
2793 const char *S = A->getValue(1);
2794 auto Pair = StringRef(S).split('=');
2795 auto Sym = Pair.first;
2796 auto SVal = Pair.second;
2797
2798 if (Sym.empty() || SVal.empty()) {
2799 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2800 break;
2801 }
2802 int64_t IVal;
2803 if (SVal.getAsInteger(0, IVal)) {
2804 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2805 break;
2806 }
2807 CmdArgs.push_back("--defsym");
2808 TakeNextArg = true;
2809 } else if (Value == "-fdebug-compilation-dir") {
2810 CmdArgs.push_back("-fdebug-compilation-dir");
2811 TakeNextArg = true;
2812 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2813 // The flag is a -Wa / -Xassembler argument and Options doesn't
2814 // parse the argument, so this isn't automatically aliased to
2815 // -fdebug-compilation-dir (without '=') here.
2816 CmdArgs.push_back("-fdebug-compilation-dir");
2817 CmdArgs.push_back(Value.data());
2818 } else if (Value == "--version") {
2819 D.PrintVersion(C, llvm::outs());
2820 } else {
2821 D.Diag(diag::err_drv_unsupported_option_argument)
2822 << A->getSpelling() << Value;
2823 }
2824 }
2825 }
2826 if (ImplicitIt.size())
2827 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2828 if (Crel) {
2829 if (!ExperimentalCrel)
2830 D.Diag(diag::err_drv_experimental_crel);
2831 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2832 CmdArgs.push_back("--crel");
2833 } else {
2834 D.Diag(diag::err_drv_unsupported_opt_for_target)
2835 << "-Wa,--crel" << D.getTargetTriple();
2836 }
2837 }
2838 if (!RelocSectionSym.empty()) {
2839 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2840 RelocSectionSym != "none")
2841 D.Diag(diag::err_drv_invalid_value)
2842 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2843 << RelocSectionSym;
2844 else if (Triple.isOSBinFormatELF())
2845 CmdArgs.push_back(
2846 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2847 else
2848 D.Diag(diag::err_drv_unsupported_opt_for_target)
2849 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2850 }
2851 if (SFrame) {
2852 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2853 if (!ExperimentalSFrame)
2854 D.Diag(diag::err_drv_experimental_sframe);
2855 else
2856 CmdArgs.push_back("--gsframe");
2857 } else {
2858 D.Diag(diag::err_drv_unsupported_opt_for_target)
2859 << "-Wa,--gsframe" << D.getTargetTriple();
2860 }
2861 }
2862 if (ImplicitMapSyms)
2863 CmdArgs.push_back("-mmapsyms=implicit");
2864 if (Msa)
2865 CmdArgs.push_back("-mmsa");
2866 if (!UseRelaxRelocations)
2867 CmdArgs.push_back("-mrelax-relocations=no");
2868 if (UseNoExecStack)
2869 CmdArgs.push_back("-mnoexecstack");
2870 if (MipsTargetFeature != nullptr) {
2871 CmdArgs.push_back("-target-feature");
2872 CmdArgs.push_back(MipsTargetFeature);
2873 }
2874
2875 for (const char *Feature : SparcTargetFeatures) {
2876 CmdArgs.push_back("-target-feature");
2877 CmdArgs.push_back(Feature);
2878 }
2879
2880 // forward -fembed-bitcode to assmebler
2881 if (C.getDriver().embedBitcodeEnabled() ||
2882 C.getDriver().embedBitcodeMarkerOnly())
2883 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2884
2885 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2886 CmdArgs.push_back("-as-secure-log-file");
2887 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2888 }
2889}
2890
2891static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2892 bool OFastEnabled, const ArgList &Args,
2893 ArgStringList &CmdArgs,
2894 const JobAction &JA) {
2895 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2896 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2897 llvm::StringLiteral("SLEEF")};
2898 bool NoMathErrnoWasImpliedByVecLib = false;
2899 const Arg *VecLibArg = nullptr;
2900 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2901 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2902
2903 // Handle various floating point optimization flags, mapping them to the
2904 // appropriate LLVM code generation flags. This is complicated by several
2905 // "umbrella" flags, so we do this by stepping through the flags incrementally
2906 // adjusting what we think is enabled/disabled, then at the end setting the
2907 // LLVM flags based on the final state.
2908 bool HonorINFs = true;
2909 bool HonorNaNs = true;
2910 bool ApproxFunc = false;
2911 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2912 bool MathErrno = TC.IsMathErrnoDefault();
2913 bool AssociativeMath = false;
2914 bool ReciprocalMath = false;
2915 bool SignedZeros = true;
2916 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2917 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2918 // overriden by ffp-exception-behavior?
2919 bool RoundingFPMath = false;
2920 // -ffp-model values: strict, fast, precise
2921 StringRef FPModel = "";
2922 // -ffp-exception-behavior options: strict, maytrap, ignore
2923 StringRef FPExceptionBehavior = "";
2924 // -ffp-eval-method options: double, extended, source
2925 StringRef FPEvalMethod = "";
2926 llvm::DenormalMode DenormalFPMath =
2927 TC.getDefaultDenormalModeForType(Args, JA);
2928 llvm::DenormalMode DenormalFP32Math =
2929 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2930
2931 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2932 // If one wasn't given by the user, don't pass it here.
2933 StringRef FPContract;
2934 StringRef LastSeenFfpContractOption;
2935 StringRef LastFpContractOverrideOption;
2936 bool SeenUnsafeMathModeOption = false;
2939 FPContract = "on";
2940 bool StrictFPModel = false;
2941 StringRef Float16ExcessPrecision = "";
2942 StringRef BFloat16ExcessPrecision = "";
2944 std::string ComplexRangeStr;
2945 StringRef LastComplexRangeOption;
2946
2947 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2948 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2949 if (Aggressive) {
2950 HonorINFs = false;
2951 HonorNaNs = false;
2953 LastComplexRangeOption, Range);
2954 } else {
2955 HonorINFs = true;
2956 HonorNaNs = true;
2957 setComplexRange(D, CallerOption,
2959 LastComplexRangeOption, Range);
2960 }
2961 MathErrno = false;
2962 AssociativeMath = true;
2963 ReciprocalMath = true;
2964 ApproxFunc = true;
2965 SignedZeros = false;
2966 TrappingMath = false;
2967 RoundingFPMath = false;
2968 FPExceptionBehavior = "";
2969 FPContract = "fast";
2970 SeenUnsafeMathModeOption = true;
2971 };
2972
2973 // Lambda to consolidate common handling for fp-contract
2974 auto restoreFPContractState = [&]() {
2975 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2976 // For other targets, if the state has been changed by one of the
2977 // unsafe-math umbrella options a subsequent -fno-fast-math or
2978 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2979 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2980 // option. If we have not seen an unsafe-math option or -ffp-contract,
2981 // we leave the FPContract state unchanged.
2984 if (LastSeenFfpContractOption != "")
2985 FPContract = LastSeenFfpContractOption;
2986 else if (SeenUnsafeMathModeOption)
2987 FPContract = "on";
2988 }
2989 // In this case, we're reverting to the last explicit fp-contract option
2990 // or the platform default
2991 LastFpContractOverrideOption = "";
2992 };
2993
2994 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2995 CmdArgs.push_back("-mlimit-float-precision");
2996 CmdArgs.push_back(A->getValue());
2997 }
2998
2999 for (const Arg *A : Args) {
3000 llvm::scope_exit CheckMathErrnoForVecLib(
3001 [&, MathErrnoBeforeArg = MathErrno] {
3002 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3003 ArgThatEnabledMathErrnoAfterVecLib = A;
3004 });
3005
3006 switch (A->getOption().getID()) {
3007 // If this isn't an FP option skip the claim below
3008 default: continue;
3009
3010 case options::OPT_fcx_limited_range:
3011 setComplexRange(D, A->getSpelling(),
3013 LastComplexRangeOption, Range);
3014 break;
3015 case options::OPT_fno_cx_limited_range:
3016 setComplexRange(D, A->getSpelling(),
3018 LastComplexRangeOption, Range);
3019 break;
3020 case options::OPT_fcx_fortran_rules:
3021 setComplexRange(D, A->getSpelling(),
3023 LastComplexRangeOption, Range);
3024 break;
3025 case options::OPT_fno_cx_fortran_rules:
3026 setComplexRange(D, A->getSpelling(),
3028 LastComplexRangeOption, Range);
3029 break;
3030 case options::OPT_fcomplex_arithmetic_EQ: {
3032 StringRef Val = A->getValue();
3033 if (Val == "full")
3035 else if (Val == "improved")
3037 else if (Val == "promoted")
3039 else if (Val == "basic")
3041 else {
3042 D.Diag(diag::err_drv_unsupported_option_argument)
3043 << A->getSpelling() << Val;
3044 break;
3045 }
3046 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3047 LastComplexRangeOption, Range);
3048 break;
3049 }
3050 case options::OPT_ffp_model_EQ: {
3051 // If -ffp-model= is seen, reset to fno-fast-math
3052 HonorINFs = true;
3053 HonorNaNs = true;
3054 ApproxFunc = false;
3055 // Turning *off* -ffast-math restores the toolchain default.
3056 MathErrno = TC.IsMathErrnoDefault();
3057 AssociativeMath = false;
3058 ReciprocalMath = false;
3059 SignedZeros = true;
3060
3061 StringRef Val = A->getValue();
3062 if (OFastEnabled && Val != "aggressive") {
3063 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3064 D.Diag(clang::diag::warn_drv_overriding_option)
3065 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3066 break;
3067 }
3068 StrictFPModel = false;
3069 if (!FPModel.empty() && FPModel != Val)
3070 D.Diag(clang::diag::warn_drv_overriding_option)
3071 << Args.MakeArgString("-ffp-model=" + FPModel)
3072 << Args.MakeArgString("-ffp-model=" + Val);
3073 if (Val == "fast") {
3074 FPModel = Val;
3075 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3076 // applyFastMath sets fp-contract="fast"
3077 LastFpContractOverrideOption = "-ffp-model=fast";
3078 } else if (Val == "aggressive") {
3079 FPModel = Val;
3080 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3081 // applyFastMath sets fp-contract="fast"
3082 LastFpContractOverrideOption = "-ffp-model=aggressive";
3083 } else if (Val == "precise") {
3084 FPModel = Val;
3085 FPContract = "on";
3086 LastFpContractOverrideOption = "-ffp-model=precise";
3087 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3089 LastComplexRangeOption, Range);
3090 } else if (Val == "strict") {
3091 StrictFPModel = true;
3092 FPExceptionBehavior = "strict";
3093 FPModel = Val;
3094 FPContract = "off";
3095 LastFpContractOverrideOption = "-ffp-model=strict";
3096 TrappingMath = true;
3097 RoundingFPMath = true;
3098 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3100 LastComplexRangeOption, Range);
3101 } else
3102 D.Diag(diag::err_drv_unsupported_option_argument)
3103 << A->getSpelling() << Val;
3104 break;
3105 }
3106
3107 // Options controlling individual features
3108 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3109 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3110 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3111 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3112 case options::OPT_fapprox_func: ApproxFunc = true; break;
3113 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3114 case options::OPT_fmath_errno: MathErrno = true; break;
3115 case options::OPT_fno_math_errno: MathErrno = false; break;
3116 case options::OPT_fassociative_math: AssociativeMath = true; break;
3117 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3118 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3119 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3120 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3121 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3122 case options::OPT_ftrapping_math:
3123 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3124 FPExceptionBehavior != "strict")
3125 // Warn that previous value of option is overridden.
3126 D.Diag(clang::diag::warn_drv_overriding_option)
3127 << Args.MakeArgString("-ffp-exception-behavior=" +
3128 FPExceptionBehavior)
3129 << "-ftrapping-math";
3130 TrappingMath = true;
3131 TrappingMathPresent = true;
3132 FPExceptionBehavior = "strict";
3133 break;
3134 case options::OPT_fveclib:
3135 VecLibArg = A;
3136 NoMathErrnoWasImpliedByVecLib =
3137 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3138 if (NoMathErrnoWasImpliedByVecLib)
3139 MathErrno = false;
3140 break;
3141 case options::OPT_fno_trapping_math:
3142 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3143 FPExceptionBehavior != "ignore")
3144 // Warn that previous value of option is overridden.
3145 D.Diag(clang::diag::warn_drv_overriding_option)
3146 << Args.MakeArgString("-ffp-exception-behavior=" +
3147 FPExceptionBehavior)
3148 << "-fno-trapping-math";
3149 TrappingMath = false;
3150 TrappingMathPresent = true;
3151 FPExceptionBehavior = "ignore";
3152 break;
3153
3154 case options::OPT_frounding_math:
3155 RoundingFPMath = true;
3156 break;
3157
3158 case options::OPT_fno_rounding_math:
3159 RoundingFPMath = false;
3160 break;
3161
3162 case options::OPT_fdenormal_fp_math_EQ:
3163 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3164 DenormalFP32Math = DenormalFPMath;
3165 if (!DenormalFPMath.isValid()) {
3166 D.Diag(diag::err_drv_invalid_value)
3167 << A->getAsString(Args) << A->getValue();
3168 }
3169 break;
3170
3171 case options::OPT_fdenormal_fp_math_f32_EQ:
3172 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3173 if (!DenormalFP32Math.isValid()) {
3174 D.Diag(diag::err_drv_invalid_value)
3175 << A->getAsString(Args) << A->getValue();
3176 }
3177 break;
3178
3179 // Validate and pass through -ffp-contract option.
3180 case options::OPT_ffp_contract: {
3181 StringRef Val = A->getValue();
3182 if (Val == "fast" || Val == "on" || Val == "off" ||
3183 Val == "fast-honor-pragmas") {
3184 if (Val != FPContract && LastFpContractOverrideOption != "") {
3185 D.Diag(clang::diag::warn_drv_overriding_option)
3186 << LastFpContractOverrideOption
3187 << Args.MakeArgString("-ffp-contract=" + Val);
3188 }
3189
3190 FPContract = Val;
3191 LastSeenFfpContractOption = Val;
3192 LastFpContractOverrideOption = "";
3193 } else
3194 D.Diag(diag::err_drv_unsupported_option_argument)
3195 << A->getSpelling() << Val;
3196 break;
3197 }
3198
3199 // Validate and pass through -ffp-exception-behavior option.
3200 case options::OPT_ffp_exception_behavior_EQ: {
3201 StringRef Val = A->getValue();
3202 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3203 FPExceptionBehavior != Val)
3204 // Warn that previous value of option is overridden.
3205 D.Diag(clang::diag::warn_drv_overriding_option)
3206 << Args.MakeArgString("-ffp-exception-behavior=" +
3207 FPExceptionBehavior)
3208 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3209 TrappingMath = TrappingMathPresent = false;
3210 if (Val == "ignore" || Val == "maytrap")
3211 FPExceptionBehavior = Val;
3212 else if (Val == "strict") {
3213 FPExceptionBehavior = Val;
3214 TrappingMath = TrappingMathPresent = true;
3215 } else
3216 D.Diag(diag::err_drv_unsupported_option_argument)
3217 << A->getSpelling() << Val;
3218 break;
3219 }
3220
3221 // Validate and pass through -ffp-eval-method option.
3222 case options::OPT_ffp_eval_method_EQ: {
3223 StringRef Val = A->getValue();
3224 if (Val == "double" || Val == "extended" || Val == "source")
3225 FPEvalMethod = Val;
3226 else
3227 D.Diag(diag::err_drv_unsupported_option_argument)
3228 << A->getSpelling() << Val;
3229 break;
3230 }
3231
3232 case options::OPT_fexcess_precision_EQ: {
3233 StringRef Val = A->getValue();
3234 const llvm::Triple::ArchType Arch = TC.getArch();
3235 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3236 if (Val == "standard" || Val == "fast")
3237 Float16ExcessPrecision = Val;
3238 // To make it GCC compatible, allow the value of "16" which
3239 // means disable excess precision, the same meaning than clang's
3240 // equivalent value "none".
3241 else if (Val == "16")
3242 Float16ExcessPrecision = "none";
3243 else
3244 D.Diag(diag::err_drv_unsupported_option_argument)
3245 << A->getSpelling() << Val;
3246 } else {
3247 if (!(Val == "standard" || Val == "fast"))
3248 D.Diag(diag::err_drv_unsupported_option_argument)
3249 << A->getSpelling() << Val;
3250 }
3251 BFloat16ExcessPrecision = Float16ExcessPrecision;
3252 break;
3253 }
3254 case options::OPT_ffinite_math_only:
3255 HonorINFs = false;
3256 HonorNaNs = false;
3257 break;
3258 case options::OPT_fno_finite_math_only:
3259 HonorINFs = true;
3260 HonorNaNs = true;
3261 break;
3262
3263 case options::OPT_funsafe_math_optimizations:
3264 AssociativeMath = true;
3265 ReciprocalMath = true;
3266 SignedZeros = false;
3267 ApproxFunc = true;
3268 TrappingMath = false;
3269 FPExceptionBehavior = "";
3270 FPContract = "fast";
3271 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3272 SeenUnsafeMathModeOption = true;
3273 break;
3274 case options::OPT_fno_unsafe_math_optimizations:
3275 AssociativeMath = false;
3276 ReciprocalMath = false;
3277 SignedZeros = true;
3278 ApproxFunc = false;
3279 restoreFPContractState();
3280 break;
3281
3282 case options::OPT_cl_fast_relaxed_math:
3283 applyFastMath(true, A->getSpelling());
3284 break;
3285
3286 case options::OPT_Ofast:
3287 // If -Ofast is the optimization level, then -ffast-math should be enabled
3288 if (!OFastEnabled)
3289 continue;
3290 [[fallthrough]];
3291 case options::OPT_ffast_math:
3292 applyFastMath(true, A->getSpelling());
3293 if (A->getOption().getID() == options::OPT_Ofast)
3294 LastFpContractOverrideOption = "-Ofast";
3295 else
3296 LastFpContractOverrideOption = "-ffast-math";
3297 break;
3298 case options::OPT_fno_fast_math:
3299 HonorINFs = true;
3300 HonorNaNs = true;
3301 // Turning on -ffast-math (with either flag) removes the need for
3302 // MathErrno. However, turning *off* -ffast-math merely restores the
3303 // toolchain default (which may be false).
3304 MathErrno = TC.IsMathErrnoDefault();
3305 AssociativeMath = false;
3306 ReciprocalMath = false;
3307 ApproxFunc = false;
3308 SignedZeros = true;
3309 restoreFPContractState();
3311 setComplexRange(D, A->getSpelling(),
3313 LastComplexRangeOption, Range);
3314 else
3316 LastComplexRangeOption = "";
3317 LastFpContractOverrideOption = "";
3318 break;
3319 } // End switch (A->getOption().getID())
3320
3321 // The StrictFPModel local variable is needed to report warnings
3322 // in the way we intend. If -ffp-model=strict has been used, we
3323 // want to report a warning for the next option encountered that
3324 // takes us out of the settings described by fp-model=strict, but
3325 // we don't want to continue issuing warnings for other conflicting
3326 // options after that.
3327 if (StrictFPModel) {
3328 // If -ffp-model=strict has been specified on command line but
3329 // subsequent options conflict then emit warning diagnostic.
3330 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3331 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3332 FPContract == "off")
3333 // OK: Current Arg doesn't conflict with -ffp-model=strict
3334 ;
3335 else {
3336 StrictFPModel = false;
3337 FPModel = "";
3338 // The warning for -ffp-contract would have been reported by the
3339 // OPT_ffp_contract_EQ handler above. A special check here is needed
3340 // to avoid duplicating the warning.
3341 auto RHS = (A->getNumValues() == 0)
3342 ? A->getSpelling()
3343 : Args.MakeArgString(A->getSpelling() + A->getValue());
3344 if (A->getSpelling() != "-ffp-contract=") {
3345 if (RHS != "-ffp-model=strict")
3346 D.Diag(clang::diag::warn_drv_overriding_option)
3347 << "-ffp-model=strict" << RHS;
3348 }
3349 }
3350 }
3351
3352 // If we handled this option claim it
3353 A->claim();
3354 }
3355
3356 if (!HonorINFs)
3357 CmdArgs.push_back("-menable-no-infs");
3358
3359 if (!HonorNaNs)
3360 CmdArgs.push_back("-menable-no-nans");
3361
3362 if (ApproxFunc)
3363 CmdArgs.push_back("-fapprox-func");
3364
3365 if (MathErrno) {
3366 CmdArgs.push_back("-fmath-errno");
3367 if (NoMathErrnoWasImpliedByVecLib)
3368 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3369 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3370 << VecLibArg->getAsString(Args);
3371 }
3372
3373 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3374 !TrappingMath)
3375 CmdArgs.push_back("-funsafe-math-optimizations");
3376
3377 if (!SignedZeros)
3378 CmdArgs.push_back("-fno-signed-zeros");
3379
3380 if (AssociativeMath && !SignedZeros && !TrappingMath)
3381 CmdArgs.push_back("-mreassociate");
3382
3383 if (ReciprocalMath)
3384 CmdArgs.push_back("-freciprocal-math");
3385
3386 if (TrappingMath) {
3387 // FP Exception Behavior is also set to strict
3388 assert(FPExceptionBehavior == "strict");
3389 }
3390
3391 // The default is IEEE.
3392 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3393 llvm::SmallString<64> DenormFlag;
3394 llvm::raw_svector_ostream ArgStr(DenormFlag);
3395 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3396 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3397 }
3398
3399 // Add f32 specific denormal mode flag if it's different.
3400 if (DenormalFP32Math != DenormalFPMath) {
3401 llvm::SmallString<64> DenormFlag;
3402 llvm::raw_svector_ostream ArgStr(DenormFlag);
3403 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3404 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3405 }
3406
3407 if (!FPContract.empty())
3408 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3409
3410 if (RoundingFPMath)
3411 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3412 else
3413 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3414
3415 if (!FPExceptionBehavior.empty())
3416 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3417 FPExceptionBehavior));
3418
3419 if (!FPEvalMethod.empty())
3420 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3421
3422 if (!Float16ExcessPrecision.empty())
3423 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3424 Float16ExcessPrecision));
3425 if (!BFloat16ExcessPrecision.empty())
3426 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3427 BFloat16ExcessPrecision));
3428
3429 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3430 if (!Recip.empty())
3431 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3432
3433 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3434 // individual features enabled by -ffast-math instead of the option itself as
3435 // that's consistent with gcc's behaviour.
3436 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3437 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3438 CmdArgs.push_back("-ffast-math");
3439
3440 // Handle __FINITE_MATH_ONLY__ similarly.
3441 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3442 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3443 // -menable-no-nans are set by the user.
3444 bool shouldAddFiniteMathOnly = false;
3445 if (!HonorINFs && !HonorNaNs) {
3446 shouldAddFiniteMathOnly = true;
3447 } else {
3448 bool InfValues = true;
3449 bool NanValues = true;
3450 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3451 StringRef ArgValue = Arg->getValue();
3452 if (ArgValue == "-menable-no-nans")
3453 NanValues = false;
3454 else if (ArgValue == "-menable-no-infs")
3455 InfValues = false;
3456 }
3457 if (!NanValues && !InfValues)
3458 shouldAddFiniteMathOnly = true;
3459 }
3460 if (shouldAddFiniteMathOnly) {
3461 CmdArgs.push_back("-ffinite-math-only");
3462 }
3463 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3464 CmdArgs.push_back("-mfpmath");
3465 CmdArgs.push_back(A->getValue());
3466 }
3467
3468 // Disable a codegen optimization for floating-point casts.
3469 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3470 options::OPT_fstrict_float_cast_overflow, false))
3471 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3472
3474 ComplexRangeStr = renderComplexRangeOption(Range);
3475 if (!ComplexRangeStr.empty()) {
3476 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3477 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3478 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3479 complexRangeKindToStr(Range)));
3480 }
3481 if (Args.hasArg(options::OPT_fcx_limited_range))
3482 CmdArgs.push_back("-fcx-limited-range");
3483 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3484 CmdArgs.push_back("-fcx-fortran-rules");
3485 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3486 CmdArgs.push_back("-fno-cx-limited-range");
3487 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3488 CmdArgs.push_back("-fno-cx-fortran-rules");
3489}
3490
3491static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3492 const llvm::Triple &Triple,
3493 const InputInfo &Input) {
3494 // Add default argument set.
3495 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3496 CmdArgs.push_back("-analyzer-checker=core");
3497 CmdArgs.push_back("-analyzer-checker=apiModeling");
3498
3499 if (!Triple.isWindowsMSVCEnvironment()) {
3500 CmdArgs.push_back("-analyzer-checker=unix");
3501 } else {
3502 // Enable "unix" checkers that also work on Windows.
3503 CmdArgs.push_back("-analyzer-checker=unix.API");
3504 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3505 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3506 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3507 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3508 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3509 }
3510
3511 // Disable some unix checkers for PS4/PS5.
3512 if (Triple.isPS()) {
3513 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3514 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3515 }
3516
3517 if (Triple.isOSDarwin()) {
3518 CmdArgs.push_back("-analyzer-checker=osx");
3519 CmdArgs.push_back(
3520 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3521 }
3522 else if (Triple.isOSFuchsia())
3523 CmdArgs.push_back("-analyzer-checker=fuchsia");
3524
3525 CmdArgs.push_back("-analyzer-checker=deadcode");
3526
3527 if (types::isCXX(Input.getType()))
3528 CmdArgs.push_back("-analyzer-checker=cplusplus");
3529
3530 if (!Triple.isPS()) {
3531 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3532 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3533 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3534 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3535 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3536 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3537 }
3538
3539 // Default nullability checks.
3540 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3541 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3542 }
3543
3544 // Set the output format. The default is plist, for (lame) historical reasons.
3545 CmdArgs.push_back("-analyzer-output");
3546 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3547 CmdArgs.push_back(A->getValue());
3548 else
3549 CmdArgs.push_back("plist");
3550
3551 // Disable the presentation of standard compiler warnings when using
3552 // --analyze. We only want to show static analyzer diagnostics or frontend
3553 // errors.
3554 CmdArgs.push_back("-w");
3555
3556 // Add -Xanalyzer arguments when running as analyzer.
3557 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3558}
3559
3560static bool isValidSymbolName(StringRef S) {
3561 if (S.empty())
3562 return false;
3563
3564 if (std::isdigit(S[0]))
3565 return false;
3566
3567 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3568}
3569
3570static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3571 const ArgList &Args, ArgStringList &CmdArgs,
3572 bool KernelOrKext) {
3573 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3574
3575 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3576 // doesn't even have a stack!
3577 if (EffectiveTriple.isNVPTX())
3578 return;
3579
3580 // -stack-protector=0 is default.
3582 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3583 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3584
3585 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3586 options::OPT_fstack_protector_all,
3587 options::OPT_fstack_protector_strong,
3588 options::OPT_fstack_protector)) {
3589 if (A->getOption().matches(options::OPT_fstack_protector))
3590 StackProtectorLevel =
3591 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3592 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3593 StackProtectorLevel = LangOptions::SSPStrong;
3594 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3595 StackProtectorLevel = LangOptions::SSPReq;
3596
3597 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3598 D.Diag(diag::warn_drv_unsupported_option_for_target)
3599 << A->getSpelling() << EffectiveTriple.getTriple();
3600 StackProtectorLevel = DefaultStackProtectorLevel;
3601 }
3602 } else {
3603 StackProtectorLevel = DefaultStackProtectorLevel;
3604 }
3605
3606 if (StackProtectorLevel) {
3607 CmdArgs.push_back("-stack-protector");
3608 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3609 }
3610
3611 // --param ssp-buffer-size=
3612 for (const Arg *A : Args.filtered(options::OPT__param)) {
3613 StringRef Str(A->getValue());
3614 if (Str.consume_front("ssp-buffer-size=")) {
3615 if (StackProtectorLevel) {
3616 CmdArgs.push_back("-stack-protector-buffer-size");
3617 // FIXME: Verify the argument is a valid integer.
3618 CmdArgs.push_back(Args.MakeArgString(Str));
3619 }
3620 A->claim();
3621 }
3622 }
3623
3624 const std::string &TripleStr = EffectiveTriple.getTriple();
3625 StringRef GuardValue;
3626 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3627 GuardValue = A->getValue();
3628 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3629 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3630 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3631 !EffectiveTriple.isSystemZ())
3632 D.Diag(diag::err_drv_unsupported_opt_for_target)
3633 << A->getAsString(Args) << TripleStr;
3634 // z/OS only supports the tls mode.
3635 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3636 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3637 << A->getOption().getName() << GuardValue << "tls";
3638 return;
3639 }
3640 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3641 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3642 GuardValue != "tls" && GuardValue != "global") {
3643 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3644 << A->getOption().getName() << GuardValue << "tls global";
3645 return;
3646 }
3647 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3648 GuardValue == "tls") {
3649 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3650 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3651 << A->getAsString(Args);
3652 return;
3653 }
3654 // Check whether the target subarch supports the hardware TLS register
3655 if (!arm::isHardTPSupported(EffectiveTriple)) {
3656 D.Diag(diag::err_target_unsupported_tp_hard)
3657 << EffectiveTriple.getArchName();
3658 return;
3659 }
3660 // Check whether the user asked for something other than -mtp=cp15
3661 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3662 StringRef Value = A->getValue();
3663 if (Value != "cp15") {
3664 D.Diag(diag::err_drv_argument_not_allowed_with)
3665 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3666 return;
3667 }
3668 }
3669 CmdArgs.push_back("-target-feature");
3670 CmdArgs.push_back("+read-tp-tpidruro");
3671 }
3672 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3673 GuardValue != "global") {
3674 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3675 << A->getOption().getName() << GuardValue << "sysreg global";
3676 return;
3677 }
3678 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3679 if (GuardValue != "tls" && GuardValue != "global") {
3680 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3681 << A->getOption().getName() << GuardValue << "tls global";
3682 return;
3683 }
3684 if (GuardValue == "tls") {
3685 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3686 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3687 << A->getAsString(Args);
3688 return;
3689 }
3690 }
3691 }
3692 A->render(Args, CmdArgs);
3693 }
3694
3695 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3696 StringRef Value = A->getValue();
3697 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3698 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3699 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3700 D.Diag(diag::err_drv_unsupported_opt_for_target)
3701 << A->getAsString(Args) << TripleStr;
3702 int Offset;
3703 if (Value.getAsInteger(10, Offset)) {
3704 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3705 return;
3706 }
3707 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3708 (Offset < 0 || Offset > 0xfffff)) {
3709 D.Diag(diag::err_drv_invalid_int_value)
3710 << A->getOption().getName() << Value;
3711 return;
3712 }
3713 A->render(Args, CmdArgs);
3714 }
3715
3716 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3717 StringRef Value = A->getValue();
3718 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3719 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3720 D.Diag(diag::err_drv_unsupported_opt_for_target)
3721 << A->getAsString(Args) << TripleStr;
3722 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3723 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3724 << A->getOption().getName() << Value << "fs gs";
3725 return;
3726 }
3727 if (EffectiveTriple.isAArch64() &&
3728 llvm::StringSwitch<bool>(Value)
3729 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3730 "tpidr_el2", "far_el1", "far_el2"},
3731 false)
3732 .Default(true)) {
3733 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3734 << A->getOption().getName() << Value
3735 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3736 return;
3737 }
3738 if (EffectiveTriple.isRISCV() && Value != "tp") {
3739 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3740 << A->getOption().getName() << Value << "tp";
3741 return;
3742 }
3743 if (EffectiveTriple.isPPC64() && Value != "r13") {
3744 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3745 << A->getOption().getName() << Value << "r13";
3746 return;
3747 }
3748 if (EffectiveTriple.isPPC32() && Value != "r2") {
3749 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3750 << A->getOption().getName() << Value << "r2";
3751 return;
3752 }
3753 A->render(Args, CmdArgs);
3754 }
3755
3756 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3757 StringRef Value = A->getValue();
3758 if (!isValidSymbolName(Value)) {
3759 D.Diag(diag::err_drv_argument_only_allowed_with)
3760 << A->getOption().getName() << "legal symbol name";
3761 return;
3762 }
3763 A->render(Args, CmdArgs);
3764 }
3765
3766 if (Arg *A =
3767 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3768 if (!EffectiveTriple.isAArch64())
3769 D.Diag(diag::err_drv_unsupported_opt_for_target)
3770 << A->getAsString(Args) << TripleStr;
3771 StringRef Value = A->getValue();
3772 unsigned Width;
3773 if (Value.getAsInteger(10, Width)) {
3774 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3775 return;
3776 }
3777 if (Width != 4 && Width != 8) {
3778 D.Diag(diag::err_drv_invalid_int_value)
3779 << A->getOption().getName() << Value;
3780 }
3781 }
3782 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3783 if (!EffectiveTriple.isSystemZ()) {
3784 D.Diag(diag::err_drv_unsupported_opt_for_target)
3785 << A->getAsString(Args) << TripleStr;
3786 return;
3787 }
3788 if (GuardValue != "global") {
3789 D.Diag(diag::err_drv_argument_only_allowed_with)
3790 << "-mstack-protector-guard-record"
3791 << "-mstack-protector-guard=global";
3792 return;
3793 }
3794 A->render(Args, CmdArgs);
3795 }
3796}
3797
3798static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3799 ArgStringList &CmdArgs) {
3800 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3801
3802 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3803 !EffectiveTriple.isOSFuchsia())
3804 return;
3805
3806 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3807 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3808 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3809 return;
3810
3811 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3812 options::OPT_fno_stack_clash_protection);
3813}
3814
3816 const ToolChain &TC,
3817 const ArgList &Args,
3818 ArgStringList &CmdArgs) {
3819 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3820 StringRef TrivialAutoVarInit = "";
3821
3822 for (const Arg *A : Args) {
3823 switch (A->getOption().getID()) {
3824 default:
3825 continue;
3826 case options::OPT_ftrivial_auto_var_init: {
3827 A->claim();
3828 StringRef Val = A->getValue();
3829 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3830 TrivialAutoVarInit = Val;
3831 else
3832 D.Diag(diag::err_drv_unsupported_option_argument)
3833 << A->getSpelling() << Val;
3834 break;
3835 }
3836 }
3837 }
3838
3839 if (TrivialAutoVarInit.empty())
3840 switch (DefaultTrivialAutoVarInit) {
3842 break;
3844 TrivialAutoVarInit = "pattern";
3845 break;
3847 TrivialAutoVarInit = "zero";
3848 break;
3849 }
3850
3851 if (!TrivialAutoVarInit.empty()) {
3852 CmdArgs.push_back(
3853 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3854 }
3855
3856 if (Arg *A =
3857 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3858 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3859 StringRef(
3860 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3861 "uninitialized")
3862 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3863 A->claim();
3864 StringRef Val = A->getValue();
3865 if (std::stoi(Val.str()) <= 0)
3866 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3867 CmdArgs.push_back(
3868 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3869 }
3870
3871 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3872 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3873 StringRef(
3874 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3875 "uninitialized")
3876 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3877 A->claim();
3878 StringRef Val = A->getValue();
3879 if (std::stoi(Val.str()) <= 0)
3880 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3881 CmdArgs.push_back(
3882 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3883 }
3884}
3885
3886static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3887 types::ID InputType) {
3888 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3889 // for denormal flushing handling based on the target.
3890 const unsigned ForwardedArguments[] = {
3891 options::OPT_cl_opt_disable,
3892 options::OPT_cl_strict_aliasing,
3893 options::OPT_cl_single_precision_constant,
3894 options::OPT_cl_finite_math_only,
3895 options::OPT_cl_kernel_arg_info,
3896 options::OPT_cl_unsafe_math_optimizations,
3897 options::OPT_cl_fast_relaxed_math,
3898 options::OPT_cl_mad_enable,
3899 options::OPT_cl_no_signed_zeros,
3900 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3901 options::OPT_cl_uniform_work_group_size
3902 };
3903
3904 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3905 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3906 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3907 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3908 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3909 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3910 }
3911
3912 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3913 CmdArgs.push_back("-menable-no-infs");
3914 CmdArgs.push_back("-menable-no-nans");
3915 }
3916
3917 for (const auto &Arg : ForwardedArguments)
3918 if (const auto *A = Args.getLastArg(Arg))
3919 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3920
3921 // Only add the default headers if we are compiling OpenCL sources.
3922 if ((types::isOpenCL(InputType) ||
3923 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3924 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3925 CmdArgs.push_back("-finclude-default-header");
3926 CmdArgs.push_back("-fdeclare-opencl-builtins");
3927 }
3928}
3929
3930static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
3931 ArgStringList &CmdArgs, types::ID InputType) {
3932 const unsigned ForwardedArguments[] = {
3933 options::OPT_hlsl_all_resources_bound,
3934 options::OPT_dxil_validator_version,
3935 options::OPT_res_may_alias,
3936 options::OPT_D,
3937 options::OPT_I,
3938 options::OPT_O,
3939 options::OPT_emit_llvm,
3940 options::OPT_emit_obj,
3941 options::OPT_disable_llvm_passes,
3942 options::OPT_fnative_half_type,
3943 options::OPT_fnative_int16_type,
3944 options::OPT_fmatrix_memory_layout_EQ,
3945 options::OPT_hlsl_entrypoint,
3946 options::OPT_fdx_rootsignature_define,
3947 options::OPT_fdx_rootsignature_version,
3948 options::OPT_fhlsl_spv_use_unknown_image_format,
3949 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
3950 options::OPT_fhlsl_spv_preserve_interface};
3951 if (!types::isHLSL(InputType))
3952 return;
3953 for (const auto &Arg : ForwardedArguments)
3954 if (const auto *A = Args.getLastArg(Arg))
3955 A->renderAsInput(Args, CmdArgs);
3956 // Add the default headers if dxc_no_stdinc is not set.
3957 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3958 !Args.hasArg(options::OPT_nostdinc))
3959 CmdArgs.push_back("-finclude-default-header");
3960
3961 if (Args.hasArg(options::OPT_dxc_Zss)) {
3962 if (Args.hasArg(options::OPT_dxc_Zsb))
3963 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
3964 CmdArgs.push_back("-mllvm");
3965 CmdArgs.push_back("-dx-Zss");
3966 }
3967 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
3968 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
3969 if (Args.hasArg(options::OPT_dxc_source_in_debug_module)) {
3970 CmdArgs.push_back("-mllvm");
3971 CmdArgs.push_back("--dx-source-in-debug-module");
3972 }
3973 if (Args.hasArg(options::OPT_dxc_Qstrip_debug)) {
3974 CmdArgs.push_back("-mllvm");
3975 CmdArgs.push_back("--dx-strip-debug");
3976 }
3977 if (Args.hasArg(options::OPT_dxc_Qpdb_in_private)) {
3978 CmdArgs.push_back("-mllvm");
3979 CmdArgs.push_back("--dx-pdb-in-private");
3980 }
3981}
3982
3983static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3984 ArgStringList &CmdArgs, types::ID InputType) {
3985 if (!Args.hasArg(options::OPT_fopenacc))
3986 return;
3987
3988 CmdArgs.push_back("-fopenacc");
3989}
3990
3991static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3992 const ArgList &Args, ArgStringList &CmdArgs) {
3993 // -fbuiltin is default unless -mkernel is used.
3994 bool UseBuiltins =
3995 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3996 !Args.hasArg(options::OPT_mkernel));
3997 if (!UseBuiltins)
3998 CmdArgs.push_back("-fno-builtin");
3999
4000 // -ffreestanding implies -fno-builtin.
4001 if (Args.hasArg(options::OPT_ffreestanding))
4002 UseBuiltins = false;
4003
4004 // Process the -fno-builtin-* options.
4005 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4006 A->claim();
4007
4008 // If -fno-builtin is specified, then there's no need to pass the option to
4009 // the frontend.
4010 if (UseBuiltins)
4011 A->render(Args, CmdArgs);
4012 }
4013}
4014
4016 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4017 Twine Path{Str};
4018 Path.toVector(Result);
4019 return Path.getSingleStringRef() != "";
4020 }
4021 if (llvm::sys::path::cache_directory(Result)) {
4022 llvm::sys::path::append(Result, "clang");
4023 llvm::sys::path::append(Result, "ModuleCache");
4024 return true;
4025 }
4026 return false;
4027}
4028
4031 const char *BaseInput) {
4032 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4033 return StringRef(ModuleOutputEQ->getValue());
4034
4035 SmallString<256> OutputPath;
4036 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4037 FinalOutput && Args.hasArg(options::OPT_c))
4038 OutputPath = FinalOutput->getValue();
4039 else {
4040 llvm::sys::fs::current_path(OutputPath);
4041 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4042 }
4043
4044 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4045 llvm::sys::path::replace_extension(OutputPath, Extension);
4046 return OutputPath;
4047}
4048
4050 const ArgList &Args, const InputInfo &Input,
4051 const InputInfo &Output, bool HaveStd20,
4052 ArgStringList &CmdArgs) {
4053 const bool IsCXX = types::isCXX(Input.getType());
4054 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4055 bool HaveModules = HaveStdCXXModules;
4056
4057 // -fmodules enables the use of precompiled modules (off by default).
4058 // Users can pass -fno-cxx-modules to turn off modules support for
4059 // C++/Objective-C++ programs.
4060 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4061 options::OPT_fno_cxx_modules, true);
4062 bool HaveClangModules = false;
4063 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4064 if (AllowedInCXX || !IsCXX) {
4065 CmdArgs.push_back("-fmodules");
4066 HaveClangModules = true;
4067 }
4068 }
4069
4070 HaveModules |= HaveClangModules;
4071
4072 if (HaveModules && !AllowedInCXX)
4073 CmdArgs.push_back("-fno-cxx-modules");
4074
4075 // -fmodule-maps enables implicit reading of module map files. By default,
4076 // this is enabled if we are using Clang's flavor of precompiled modules.
4077 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4078 options::OPT_fno_implicit_module_maps, HaveClangModules))
4079 CmdArgs.push_back("-fimplicit-module-maps");
4080
4081 // -fmodules-decluse checks that modules used are declared so (off by default)
4082 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4083 options::OPT_fno_modules_decluse);
4084
4085 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4086 // all #included headers are part of modules.
4087 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4088 options::OPT_fno_modules_strict_decluse, false))
4089 CmdArgs.push_back("-fmodules-strict-decluse");
4090
4091 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4092 options::OPT_fno_modulemap_allow_subdirectory_search);
4093
4094 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4095 bool ImplicitModules = false;
4096 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4097 options::OPT_fno_implicit_modules, HaveClangModules)) {
4098 if (HaveModules)
4099 CmdArgs.push_back("-fno-implicit-modules");
4100 } else if (HaveModules) {
4101 ImplicitModules = true;
4102 // -fmodule-cache-path specifies where our implicitly-built module files
4103 // should be written.
4104 SmallString<128> Path;
4105 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4106 Path = A->getValue();
4107
4108 bool HasPath = true;
4109 if (C.isForDiagnostics()) {
4110 // When generating crash reports, we want to emit the modules along with
4111 // the reproduction sources, so we ignore any provided module path.
4112 Path = Output.getFilename();
4113 llvm::sys::path::replace_extension(Path, ".cache");
4114 llvm::sys::path::append(Path, "modules");
4115 } else if (Path.empty()) {
4116 // No module path was provided: use the default.
4117 HasPath = Driver::getDefaultModuleCachePath(Path);
4118 }
4119
4120 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4121 // That being said, that failure is unlikely and not caching is harmless.
4122 if (HasPath) {
4123 const char Arg[] = "-fmodules-cache-path=";
4124 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4125 CmdArgs.push_back(Args.MakeArgString(Path));
4126 }
4127
4128 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4129 }
4130
4131 if (HaveModules) {
4132 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4133 options::OPT_fno_prebuilt_implicit_modules, false))
4134 CmdArgs.push_back("-fprebuilt-implicit-modules");
4135 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4136 options::OPT_fno_modules_validate_input_files_content,
4137 false))
4138 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4139 }
4140
4141 // -fmodule-name specifies the module that is currently being built (or
4142 // used for header checking by -fmodule-maps).
4143 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4144
4145 // -fmodule-map-file can be used to specify files containing module
4146 // definitions.
4147 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4148
4149 // -fbuiltin-module-map can be used to load the clang
4150 // builtin headers modulemap file.
4151 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4152 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4153 llvm::sys::path::append(BuiltinModuleMap, "include");
4154 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4155 if (llvm::sys::fs::exists(BuiltinModuleMap))
4156 CmdArgs.push_back(
4157 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4158 }
4159
4160 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4161 // names to precompiled module files (the module is loaded only if used).
4162 // The -fmodule-file=<file> form can be used to unconditionally load
4163 // precompiled module files (whether used or not).
4164 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4165 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4166
4167 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4168 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4169 CmdArgs.push_back(Args.MakeArgString(
4170 std::string("-fprebuilt-module-path=") + A->getValue()));
4171 A->claim();
4172 }
4173 } else
4174 Args.ClaimAllArgs(options::OPT_fmodule_file);
4175
4176 // When building modules and generating crashdumps, we need to dump a module
4177 // dependency VFS alongside the output.
4178 if (HaveClangModules && C.isForDiagnostics()) {
4179 SmallString<128> VFSDir(Output.getFilename());
4180 llvm::sys::path::replace_extension(VFSDir, ".cache");
4181 // Add the cache directory as a temp so the crash diagnostics pick it up.
4182 C.addTempFile(Args.MakeArgString(VFSDir));
4183
4184 llvm::sys::path::append(VFSDir, "vfs");
4185 CmdArgs.push_back("-module-dependency-dir");
4186 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4187 }
4188
4189 if (HaveClangModules)
4190 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4191
4192 // Pass through all -fmodules-ignore-macro arguments.
4193 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4194 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4195 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4196
4197 if (HaveClangModules) {
4198 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4199
4200 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4201 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4202 D.Diag(diag::err_drv_argument_not_allowed_with)
4203 << A->getAsString(Args) << "-fbuild-session-timestamp";
4204
4205 llvm::sys::fs::file_status Status;
4206 if (llvm::sys::fs::status(A->getValue(), Status))
4207 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4208 CmdArgs.push_back(Args.MakeArgString(
4209 "-fbuild-session-timestamp=" +
4210 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4211 Status.getLastModificationTime().time_since_epoch())
4212 .count())));
4213 }
4214
4215 if (Args.getLastArg(
4216 options::OPT_fmodules_validate_once_per_build_session)) {
4217 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4218 options::OPT_fbuild_session_file))
4219 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4220
4221 Args.AddLastArg(CmdArgs,
4222 options::OPT_fmodules_validate_once_per_build_session);
4223 }
4224
4225 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4226 options::OPT_fno_modules_validate_system_headers,
4227 ImplicitModules))
4228 CmdArgs.push_back("-fmodules-validate-system-headers");
4229
4230 Args.AddLastArg(CmdArgs,
4231 options::OPT_fmodules_disable_diagnostic_validation);
4232 } else {
4233 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4234 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4235 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4236 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4237 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4238 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4239 }
4240
4241 // FIXME: We provisionally don't check ODR violations for decls in the global
4242 // module fragment.
4243 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4244
4245 if (Input.getType() == driver::types::TY_CXXModule ||
4246 Input.getType() == driver::types::TY_PP_CXXModule) {
4247 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4248 CmdArgs.push_back("-fmodules-reduced-bmi");
4249
4250 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4251 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4252 else if (!(Args.hasArg(options::OPT__precompile) ||
4253 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4254 Args.hasArg(options::OPT_fmodule_output))
4255 // If --precompile is specified, we will always generate a module file if
4256 // we're compiling an importable module unit. This is fine even if the
4257 // compilation process won't reach the point of generating the module file
4258 // (e.g., in the preprocessing mode), since the attached flag
4259 // '-fmodule-output' is useless.
4260 //
4261 // But if '--precompile' is specified, it might be annoying to always
4262 // generate the module file as '--precompile' will generate the module
4263 // file anyway.
4264 CmdArgs.push_back(Args.MakeArgString(
4265 "-fmodule-output=" +
4267 }
4268
4269 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4270 Args.hasArg(options::OPT__precompile) &&
4271 (!Args.hasArg(options::OPT_o) ||
4272 Args.getLastArg(options::OPT_o)->getValue() ==
4274 D.Diag(diag::err_drv_reduced_module_output_overrided);
4275 }
4276
4277 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4278 // other translation units than module units. This is more user friendly to
4279 // allow end uers to enable this feature without asking for help from build
4280 // systems.
4281 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4282 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4283
4284 // We need to include the case the input file is a module file here.
4285 // Since the default compilation model for C++ module interface unit will
4286 // create temporary module file and compile the temporary module file
4287 // to get the object file. Then the `-fmodule-output` flag will be
4288 // brought to the second compilation process. So we have to claim it for
4289 // the case too.
4290 if (Input.getType() == driver::types::TY_CXXModule ||
4291 Input.getType() == driver::types::TY_PP_CXXModule ||
4292 Input.getType() == driver::types::TY_ModuleFile) {
4293 Args.ClaimAllArgs(options::OPT_fmodule_output);
4294 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4295 }
4296
4297 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4298 CmdArgs.push_back("-fmodules-embed-all-files");
4299
4300 return HaveModules;
4301}
4302
4303static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4304 ArgStringList &CmdArgs) {
4305 // -fsigned-char is default.
4306 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4307 options::OPT_fno_signed_char,
4308 options::OPT_funsigned_char,
4309 options::OPT_fno_unsigned_char)) {
4310 if (A->getOption().matches(options::OPT_funsigned_char) ||
4311 A->getOption().matches(options::OPT_fno_signed_char)) {
4312 CmdArgs.push_back("-fno-signed-char");
4313 }
4314 } else if (!isSignedCharDefault(T)) {
4315 CmdArgs.push_back("-fno-signed-char");
4316 }
4317
4318 // The default depends on the language standard.
4319 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4320
4321 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4322 options::OPT_fno_short_wchar)) {
4323 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4324 CmdArgs.push_back("-fwchar-type=short");
4325 CmdArgs.push_back("-fno-signed-wchar");
4326 } else {
4327 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4328 CmdArgs.push_back("-fwchar-type=int");
4329 if (T.isOSzOS() ||
4330 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4331 CmdArgs.push_back("-fno-signed-wchar");
4332 else
4333 CmdArgs.push_back("-fsigned-wchar");
4334 }
4335 } else if (T.isOSzOS())
4336 CmdArgs.push_back("-fno-signed-wchar");
4337}
4338
4339static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4340 const llvm::Triple &T, const ArgList &Args,
4341 ObjCRuntime &Runtime, bool InferCovariantReturns,
4342 const InputInfo &Input, ArgStringList &CmdArgs) {
4343 const llvm::Triple::ArchType Arch = TC.getArch();
4344
4345 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4346 // is the default. Except for deployment target of 10.5, next runtime is
4347 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4348 if (Runtime.isNonFragile()) {
4349 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4350 options::OPT_fno_objc_legacy_dispatch,
4352 if (TC.UseObjCMixedDispatch())
4353 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4354 else
4355 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4356 }
4357 }
4358
4359 // Forward -fobjc-direct-precondition-thunk to cc1
4360 // Defaults to false and needs explict turn on for now
4361 // TODO: switch to default true and needs explict turn off in the future.
4362 // TODO: add support for other runtimes
4363 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4364 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4365 if (Runtime.isNeXTFamily()) {
4366 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4367 } else {
4368 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4369 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4370 }
4371 }
4372
4373 if (types::isObjC(Input.getType())) {
4374 // Pass down -fobjc-msgsend-selector-stubs if present.
4375 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4376 options::OPT_fno_objc_msgsend_selector_stubs, false))
4377 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4378
4379 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4380 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4381 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4382 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4383 }
4384
4385 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4386 // to do Array/Dictionary subscripting by default.
4387 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4388 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4389 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4390
4391 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4392 // NOTE: This logic is duplicated in ToolChains.cpp.
4393 if (isObjCAutoRefCount(Args)) {
4394 TC.CheckObjCARC();
4395
4396 CmdArgs.push_back("-fobjc-arc");
4397
4398 // FIXME: It seems like this entire block, and several around it should be
4399 // wrapped in isObjC, but for now we just use it here as this is where it
4400 // was being used previously.
4401 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4403 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4404 else
4405 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4406 }
4407
4408 // Allow the user to enable full exceptions code emission.
4409 // We default off for Objective-C, on for Objective-C++.
4410 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4411 options::OPT_fno_objc_arc_exceptions,
4412 /*Default=*/types::isCXX(Input.getType())))
4413 CmdArgs.push_back("-fobjc-arc-exceptions");
4414 }
4415
4416 // Silence warning for full exception code emission options when explicitly
4417 // set to use no ARC.
4418 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4419 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4420 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4421 }
4422
4423 // Allow the user to control whether messages can be converted to runtime
4424 // functions.
4425 if (types::isObjC(Input.getType())) {
4426 auto *Arg = Args.getLastArg(
4427 options::OPT_fobjc_convert_messages_to_runtime_calls,
4428 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4429 if (Arg &&
4430 Arg->getOption().matches(
4431 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4432 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4433 }
4434
4435 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4436 // rewriter.
4437 if (InferCovariantReturns)
4438 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4439
4440 // Pass down -fobjc-weak or -fno-objc-weak if present.
4441 if (types::isObjC(Input.getType())) {
4442 auto WeakArg =
4443 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4444 if (!WeakArg) {
4445 // nothing to do
4446 } else if (!Runtime.allowsWeak()) {
4447 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4448 D.Diag(diag::err_objc_weak_unsupported);
4449 } else {
4450 WeakArg->render(Args, CmdArgs);
4451 }
4452 }
4453
4454 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4455 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4456
4457 // Forward constant literal flags to cc1.
4458 if (types::isObjC(Input.getType())) {
4459 bool EnableConstantLiterals =
4460 Args.hasFlag(options::OPT_fobjc_constant_literals,
4461 options::OPT_fno_objc_constant_literals,
4462 /*default=*/true) &&
4463 Runtime.hasConstantLiteralClasses();
4464 if (EnableConstantLiterals)
4465 CmdArgs.push_back("-fobjc-constant-literals");
4466 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4467 options::OPT_fno_constant_nsnumber_literals,
4468 /*default=*/true) &&
4469 EnableConstantLiterals)
4470 CmdArgs.push_back("-fconstant-nsnumber-literals");
4471 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4472 options::OPT_fno_constant_nsarray_literals,
4473 /*default=*/true) &&
4474 EnableConstantLiterals)
4475 CmdArgs.push_back("-fconstant-nsarray-literals");
4476 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4477 options::OPT_fno_constant_nsdictionary_literals,
4478 /*default=*/true) &&
4479 EnableConstantLiterals)
4480 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4481 }
4482}
4483
4484static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4485 ArgStringList &CmdArgs) {
4486 bool CaretDefault = true;
4487 bool ColumnDefault = true;
4488
4489 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4490 options::OPT__SLASH_diagnostics_column,
4491 options::OPT__SLASH_diagnostics_caret)) {
4492 switch (A->getOption().getID()) {
4493 case options::OPT__SLASH_diagnostics_caret:
4494 CaretDefault = true;
4495 ColumnDefault = true;
4496 break;
4497 case options::OPT__SLASH_diagnostics_column:
4498 CaretDefault = false;
4499 ColumnDefault = true;
4500 break;
4501 case options::OPT__SLASH_diagnostics_classic:
4502 CaretDefault = false;
4503 ColumnDefault = false;
4504 break;
4505 }
4506 }
4507
4508 // -fcaret-diagnostics is default.
4509 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4510 options::OPT_fno_caret_diagnostics, CaretDefault))
4511 CmdArgs.push_back("-fno-caret-diagnostics");
4512
4513 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4514 options::OPT_fno_diagnostics_fixit_info);
4515 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4516 options::OPT_fno_diagnostics_show_option);
4517
4518 if (const Arg *A =
4519 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4520 CmdArgs.push_back("-fdiagnostics-show-category");
4521 CmdArgs.push_back(A->getValue());
4522 }
4523
4524 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4525 options::OPT_fno_diagnostics_show_hotness);
4526
4527 if (const Arg *A =
4528 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4529 std::string Opt =
4530 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4531 CmdArgs.push_back(Args.MakeArgString(Opt));
4532 }
4533
4534 if (const Arg *A =
4535 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4536 std::string Opt =
4537 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4538 CmdArgs.push_back(Args.MakeArgString(Opt));
4539 }
4540
4541 if (const Arg *A =
4542 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4543 options::OPT_fno_diagnostics_show_inlining_chain)) {
4544 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4545 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4546 else
4547 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4548 }
4549
4550 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4551 CmdArgs.push_back("-fdiagnostics-format");
4552 CmdArgs.push_back(A->getValue());
4553 if (StringRef(A->getValue()) == "sarif" ||
4554 StringRef(A->getValue()) == "SARIF")
4555 D.Diag(diag::warn_drv_sarif_format_unstable);
4556 }
4557
4558 if (const Arg *A = Args.getLastArg(
4559 options::OPT_fdiagnostics_show_note_include_stack,
4560 options::OPT_fno_diagnostics_show_note_include_stack)) {
4561 const Option &O = A->getOption();
4562 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4563 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4564 else
4565 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4566 }
4567
4568 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4569
4570 if (Args.hasArg(options::OPT_fansi_escape_codes))
4571 CmdArgs.push_back("-fansi-escape-codes");
4572
4573 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4574 options::OPT_fno_show_source_location);
4575
4576 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4577 options::OPT_fno_diagnostics_show_line_numbers);
4578
4579 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4580 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4581
4582 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4583 ColumnDefault))
4584 CmdArgs.push_back("-fno-show-column");
4585
4586 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4587 options::OPT_fno_spell_checking);
4588
4589 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4590}
4591
4592static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4593 const ArgList &Args, ArgStringList &CmdArgs,
4594 unsigned DwarfVersion) {
4595 auto *DwarfFormatArg =
4596 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4597 if (!DwarfFormatArg)
4598 return;
4599
4600 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4601 if (DwarfVersion < 3)
4602 D.Diag(diag::err_drv_argument_only_allowed_with)
4603 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4604 else if (!T.isArch64Bit())
4605 D.Diag(diag::err_drv_argument_only_allowed_with)
4606 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4607 else if (!T.isOSBinFormatELF())
4608 D.Diag(diag::err_drv_argument_only_allowed_with)
4609 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4610 }
4611
4612 DwarfFormatArg->render(Args, CmdArgs);
4613}
4614
4615static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4616 const ArgList &Args) {
4617 bool NeedsSimpleTemplateNames =
4618 Args.hasFlag(options::OPT_gsimple_template_names,
4619 options::OPT_gno_simple_template_names,
4621 if (!NeedsSimpleTemplateNames)
4622 return false;
4623
4624 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4625 if (!checkDebugInfoOption(A, Args, D, TC))
4626 return false;
4627
4628 return true;
4629}
4630
4631static void
4632renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4633 const ArgList &Args, types::ID InputType,
4634 ArgStringList &CmdArgs, const InputInfo &Output,
4635 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4636 DwarfFissionKind &DwarfFission) {
4637 bool IRInput = isLLVMIR(InputType);
4638 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4639 !isHIP(InputType) && !isObjC(InputType) &&
4640 !isOpenCL(InputType);
4641
4642 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4643
4644 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4645 options::OPT_fno_debug_record_sysroot, true))
4646 CmdArgs.push_back("-fno-debug-record-sysroot");
4647
4648 // The 'g' groups options involve a somewhat intricate sequence of decisions
4649 // about what to pass from the driver to the frontend, but by the time they
4650 // reach cc1 they've been factored into three well-defined orthogonal choices:
4651 // * what level of debug info to generate
4652 // * what dwarf version to write
4653 // * what debugger tuning to use
4654 // This avoids having to monkey around further in cc1 other than to disable
4655 // codeview if not running in a Windows environment. Perhaps even that
4656 // decision should be made in the driver as well though.
4657 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4658
4659 bool SplitDWARFInlining =
4660 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4661 options::OPT_fno_split_dwarf_inlining, false);
4662
4663 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4664 // object file generation and no IR generation, -gN should not be needed. So
4665 // allow -gsplit-dwarf with either -gN or IR input.
4666 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4667 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4668 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4669 D.Diag(diag::err_drv_unsupported_opt_for_target)
4670 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4671 << TC.getTripleString();
4672 return;
4673 }
4674 Arg *SplitDWARFArg;
4675 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4676 if (DwarfFission != DwarfFissionKind::None &&
4677 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4678 DwarfFission = DwarfFissionKind::None;
4679 SplitDWARFInlining = false;
4680 }
4681 }
4682 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4683 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4684
4685 // If the last option explicitly specified a debug-info level, use it.
4686 if (checkDebugInfoOption(A, Args, D, TC) &&
4687 A->getOption().matches(options::OPT_gN_Group)) {
4688 DebugInfoKind = debugLevelToInfoKind(*A);
4689 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4690 // complicated if you've disabled inline info in the skeleton CUs
4691 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4692 // line-tables-only, so let those compose naturally in that case.
4693 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4694 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4695 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4696 SplitDWARFInlining))
4697 DwarfFission = DwarfFissionKind::None;
4698 }
4699 }
4700
4701 // If a debugger tuning argument appeared, remember it.
4702 bool HasDebuggerTuning = false;
4703 if (const Arg *A =
4704 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4705 HasDebuggerTuning = true;
4706 if (checkDebugInfoOption(A, Args, D, TC)) {
4707 if (A->getOption().matches(options::OPT_glldb))
4708 DebuggerTuning = llvm::DebuggerKind::LLDB;
4709 else if (A->getOption().matches(options::OPT_gsce))
4710 DebuggerTuning = llvm::DebuggerKind::SCE;
4711 else if (A->getOption().matches(options::OPT_gdbx))
4712 DebuggerTuning = llvm::DebuggerKind::DBX;
4713 else
4714 DebuggerTuning = llvm::DebuggerKind::GDB;
4715 }
4716 }
4717
4718 // If a -gdwarf argument appeared, remember it.
4719 bool EmitDwarf = false;
4720 if (const Arg *A = getDwarfNArg(Args))
4721 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4722
4723 bool EmitCodeView = false;
4724 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4725 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4726
4727 // If the user asked for debug info but did not explicitly specify -gcodeview
4728 // or -gdwarf, ask the toolchain for the default format.
4729 if (!EmitCodeView && !EmitDwarf &&
4730 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4731 switch (TC.getDefaultDebugFormat()) {
4732 case llvm::codegenoptions::DIF_CodeView:
4733 EmitCodeView = true;
4734 break;
4735 case llvm::codegenoptions::DIF_DWARF:
4736 EmitDwarf = true;
4737 break;
4738 }
4739 }
4740
4741 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4742 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4743 // be lower than what the user wanted.
4744 if (EmitDwarf) {
4745 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4746 // Clamp effective DWARF version to the max supported by the toolchain.
4747 EffectiveDWARFVersion =
4748 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4749 } else {
4750 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4751 }
4752
4753 // -gline-directives-only supported only for the DWARF debug info.
4754 if (RequestedDWARFVersion == 0 &&
4755 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4756 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4757
4758 // strict DWARF is set to false by default. But for DBX, we need it to be set
4759 // as true by default.
4760 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4761 (void)checkDebugInfoOption(A, Args, D, TC);
4762 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4763 DebuggerTuning == llvm::DebuggerKind::DBX))
4764 CmdArgs.push_back("-gstrict-dwarf");
4765
4766 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4767 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4768
4769 // Column info is included by default for everything except SCE and
4770 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4771 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4772 // practice, however, the Microsoft debuggers don't handle missing end columns
4773 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4774 // it's better not to include any column info.
4775 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4776 (void)checkDebugInfoOption(A, Args, D, TC);
4777 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4778 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4779 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4780 DebuggerTuning != llvm::DebuggerKind::DBX)))
4781 CmdArgs.push_back("-gno-column-info");
4782
4783 if (!Args.hasFlag(options::OPT_gcall_site_info,
4784 options::OPT_gno_call_site_info, true))
4785 CmdArgs.push_back("-gno-call-site-info");
4786
4787 // FIXME: Move backend command line options to the module.
4788 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4789 // If -gline-tables-only or -gline-directives-only is the last option it
4790 // wins.
4791 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4792 TC)) {
4793 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4794 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4795 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4796 CmdArgs.push_back("-dwarf-ext-refs");
4797 CmdArgs.push_back("-fmodule-format=obj");
4798 }
4799 }
4800 }
4801
4802 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4803 CmdArgs.push_back("-fsplit-dwarf-inlining");
4804
4805 // After we've dealt with all combinations of things that could
4806 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4807 // figure out if we need to "upgrade" it to standalone debug info.
4808 // We parse these two '-f' options whether or not they will be used,
4809 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4810 bool NeedFullDebug = Args.hasFlag(
4811 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4812 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4814 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4815 (void)checkDebugInfoOption(A, Args, D, TC);
4816
4817 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4818 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4819 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4820 options::OPT_feliminate_unused_debug_types, false))
4821 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4822 else if (NeedFullDebug)
4823 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4824 }
4825
4826 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4827 false)) {
4828 // Source embedding is a vendor extension to DWARF v5. By now we have
4829 // checked if a DWARF version was stated explicitly, and have otherwise
4830 // fallen back to the target default, so if this is still not at least 5
4831 // we emit an error.
4832 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4833 if (RequestedDWARFVersion < 5)
4834 D.Diag(diag::err_drv_argument_only_allowed_with)
4835 << A->getAsString(Args) << "-gdwarf-5";
4836 else if (EffectiveDWARFVersion < 5)
4837 // The toolchain has reduced allowed dwarf version, so we can't enable
4838 // -gembed-source.
4839 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4840 << A->getAsString(Args) << TC.getTripleString() << 5
4841 << EffectiveDWARFVersion;
4842 else if (checkDebugInfoOption(A, Args, D, TC))
4843 CmdArgs.push_back("-gembed-source");
4844 }
4845
4846 // Enable Key Instructions by default if we're emitting DWARF, the language is
4847 // plain C or C++, and optimisations are enabled.
4848 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4849 bool KeyInstructionsOnByDefault =
4850 EmitDwarf && PlainCOrCXX && OptLevel &&
4851 !OptLevel->getOption().matches(options::OPT_O0);
4852 if (Args.hasFlag(options::OPT_gkey_instructions,
4853 options::OPT_gno_key_instructions,
4854 KeyInstructionsOnByDefault))
4855 CmdArgs.push_back("-gkey-instructions");
4856
4857 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4858 options::OPT_gno_structor_decl_linkage_names, true))
4859 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4860
4861 if (EmitCodeView) {
4862 CmdArgs.push_back("-gcodeview");
4863
4864 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4865 options::OPT_gno_codeview_ghash);
4866
4867 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4868 options::OPT_gno_codeview_command_line);
4869 }
4870
4871 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4872 options::OPT_gno_inline_line_tables);
4873
4874 // When emitting remarks, we need at least debug lines in the output.
4875 if (willEmitRemarks(Args) &&
4876 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4877 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4878
4879 // Adjust the debug info kind for the given toolchain.
4880 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4881
4882 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4883 // set.
4884 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4885 T.isOSAIX() && !HasDebuggerTuning
4886 ? llvm::DebuggerKind::Default
4887 : DebuggerTuning);
4888
4889 // -fdebug-macro turns on macro debug info generation.
4890 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4891 false))
4892 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4893 D, TC))
4894 CmdArgs.push_back("-debug-info-macro");
4895
4896 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4897 const auto *PubnamesArg =
4898 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4899 options::OPT_gpubnames, options::OPT_gno_pubnames);
4900 if (DwarfFission != DwarfFissionKind::None ||
4901 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4902 const bool OptionSet =
4903 (PubnamesArg &&
4904 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4905 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4906 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4907 (!PubnamesArg ||
4908 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4909 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4910 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4911 options::OPT_gpubnames)
4912 ? "-gpubnames"
4913 : "-ggnu-pubnames");
4914 }
4915
4916 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4917 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4918 ForwardTemplateParams = true;
4919 CmdArgs.push_back("-gsimple-template-names=simple");
4920 }
4921
4922 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4923 bool UseDebugTemplateAlias =
4924 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4925 if (const auto *DebugTemplateAlias = Args.getLastArg(
4926 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4927 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4928 // asks for it we should let them have it (if the target supports it).
4929 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4930 const auto &Opt = DebugTemplateAlias->getOption();
4931 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4932 }
4933 }
4934 if (UseDebugTemplateAlias)
4935 CmdArgs.push_back("-gtemplate-alias");
4936
4937 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4938 StringRef v = A->getValue();
4939 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4940 }
4941
4942 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4943 options::OPT_fno_debug_ranges_base_address);
4944
4945 // -gdwarf-aranges turns on the emission of the aranges section in the
4946 // backend.
4947 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4948 A && checkDebugInfoOption(A, Args, D, TC)) {
4949 CmdArgs.push_back("-mllvm");
4950 CmdArgs.push_back("-generate-arange-section");
4951 }
4952
4953 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4954 options::OPT_fno_force_dwarf_frame);
4955
4956 bool EnableTypeUnits = false;
4957 if (Args.hasFlag(options::OPT_fdebug_types_section,
4958 options::OPT_fno_debug_types_section, false)) {
4959 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4960 D.Diag(diag::err_drv_unsupported_opt_for_target)
4961 << Args.getLastArg(options::OPT_fdebug_types_section)
4962 ->getAsString(Args)
4963 << T.getTriple();
4964 } else if (checkDebugInfoOption(
4965 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4966 TC)) {
4967 EnableTypeUnits = true;
4968 CmdArgs.push_back("-mllvm");
4969 CmdArgs.push_back("-generate-type-units");
4970 }
4971 }
4972
4973 if (const Arg *A =
4974 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4975 options::OPT_gno_omit_unreferenced_methods))
4976 (void)checkDebugInfoOption(A, Args, D, TC);
4977 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4978 options::OPT_gno_omit_unreferenced_methods, false) &&
4979 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4980 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4981 !EnableTypeUnits) {
4982 CmdArgs.push_back("-gomit-unreferenced-methods");
4983 }
4984
4985 // To avoid join/split of directory+filename, the integrated assembler prefers
4986 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4987 // form before DWARF v5.
4988 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4989 options::OPT_fno_dwarf_directory_asm,
4990 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4991 CmdArgs.push_back("-fno-dwarf-directory-asm");
4992
4993 // Decide how to render forward declarations of template instantiations.
4994 // SCE wants full descriptions, others just get them in the name.
4995 if (ForwardTemplateParams)
4996 CmdArgs.push_back("-debug-forward-template-params");
4997
4998 // Do we need to explicitly import anonymous namespaces into the parent
4999 // scope?
5000 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5001 CmdArgs.push_back("-dwarf-explicit-import");
5002
5003 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
5004 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5005
5006 // This controls whether or not we perform JustMyCode instrumentation.
5007 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5008 if (TC.getTriple().isOSBinFormatELF() ||
5009 TC.getTriple().isWindowsMSVCEnvironment()) {
5010 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5011 CmdArgs.push_back("-fjmc");
5012 else if (D.IsCLMode())
5013 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5014 << "'/Zi', '/Z7'";
5015 else
5016 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5017 << "-g";
5018 } else {
5019 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5020 }
5021 }
5022
5023 // Add in -fdebug-compilation-dir if necessary.
5024 const char *DebugCompilationDir =
5025 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5026
5027 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5028
5029 // Add the output path to the object file for CodeView debug infos.
5030 if (EmitCodeView && Output.isFilename())
5031 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5032 Output.getFilename());
5033}
5034
5035static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5036 ArgStringList &CmdArgs) {
5037 unsigned RTOptionID = options::OPT__SLASH_MT;
5038
5039 if (Args.hasArg(options::OPT__SLASH_LDd))
5040 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5041 // but defining _DEBUG is sticky.
5042 RTOptionID = options::OPT__SLASH_MTd;
5043
5044 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5045 RTOptionID = A->getOption().getID();
5046
5047 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5048 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5049 .Case("static", options::OPT__SLASH_MT)
5050 .Case("static_dbg", options::OPT__SLASH_MTd)
5051 .Case("dll", options::OPT__SLASH_MD)
5052 .Case("dll_dbg", options::OPT__SLASH_MDd)
5053 .Default(options::OPT__SLASH_MT);
5054 }
5055
5056 StringRef FlagForCRT;
5057 switch (RTOptionID) {
5058 case options::OPT__SLASH_MD:
5059 if (Args.hasArg(options::OPT__SLASH_LDd))
5060 CmdArgs.push_back("-D_DEBUG");
5061 CmdArgs.push_back("-D_MT");
5062 CmdArgs.push_back("-D_DLL");
5063 FlagForCRT = "--dependent-lib=msvcrt";
5064 break;
5065 case options::OPT__SLASH_MDd:
5066 CmdArgs.push_back("-D_DEBUG");
5067 CmdArgs.push_back("-D_MT");
5068 CmdArgs.push_back("-D_DLL");
5069 FlagForCRT = "--dependent-lib=msvcrtd";
5070 break;
5071 case options::OPT__SLASH_MT:
5072 if (Args.hasArg(options::OPT__SLASH_LDd))
5073 CmdArgs.push_back("-D_DEBUG");
5074 CmdArgs.push_back("-D_MT");
5075 CmdArgs.push_back("-flto-visibility-public-std");
5076 FlagForCRT = "--dependent-lib=libcmt";
5077 break;
5078 case options::OPT__SLASH_MTd:
5079 CmdArgs.push_back("-D_DEBUG");
5080 CmdArgs.push_back("-D_MT");
5081 CmdArgs.push_back("-flto-visibility-public-std");
5082 FlagForCRT = "--dependent-lib=libcmtd";
5083 break;
5084 default:
5085 llvm_unreachable("Unexpected option ID.");
5086 }
5087
5088 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5089 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5090 } else {
5091 CmdArgs.push_back(FlagForCRT.data());
5092
5093 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5094 // users want. The /Za flag to cl.exe turns this off, but it's not
5095 // implemented in clang.
5096 CmdArgs.push_back("--dependent-lib=oldnames");
5097 }
5098
5099 // SYCL: Add SYCL runtime library dependency
5100 // SYCL runtime is a required dependency similar to CRT, so we use
5101 // --dependent-lib to embed it in the object file metadata
5102 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5103 !Args.hasArg(options::OPT_nolibsycl) &&
5104 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5105
5106 // Determine debug vs release based on CRT flags
5107 bool IsDebugBuild = false;
5108
5109 // Check -fms-runtime-lib=dll_dbg
5110 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5111 StringRef RuntimeVal = A->getValue();
5112 if (RuntimeVal == "dll_dbg")
5113 IsDebugBuild = true;
5114 }
5115
5116 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5117 // overriding options (e.g., /MDd /MD -> /MD wins)
5118 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5119 if (A->getOption().matches(options::OPT__SLASH_MDd))
5120 IsDebugBuild = true;
5121 }
5122
5123 // Add appropriate SYCL runtime library dependency
5124 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5125 : "--dependent-lib=LLVMSYCL");
5126 }
5127
5128 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5129 // even if the file doesn't actually refer to any of the routines because
5130 // the CRT itself has incomplete dependency markings.
5131 if (TC.getTriple().isWindowsArm64EC())
5132 CmdArgs.push_back("--dependent-lib=softintrin");
5133}
5134
5136 const InputInfo &Output, const InputInfoList &Inputs,
5137 const ArgList &Args, const char *LinkingOutput) const {
5138 const auto &TC = getToolChain();
5139 const llvm::Triple &RawTriple = TC.getTriple();
5140 const llvm::Triple &Triple = TC.getEffectiveTriple();
5141 const std::string &TripleStr = Triple.getTriple();
5142
5143 bool KernelOrKext =
5144 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5145 const Driver &D = TC.getDriver();
5146 ArgStringList CmdArgs;
5147
5148 assert(Inputs.size() >= 1 && "Must have at least one input.");
5149 // CUDA/HIP compilation may have multiple inputs (source file + results of
5150 // device-side compilations). OpenMP device jobs also take the host IR as a
5151 // second input. Module precompilation accepts a list of header files to
5152 // include as part of the module. API extraction accepts a list of header
5153 // files whose API information is emitted in the output. All other jobs are
5154 // expected to have exactly one input. SYCL compilation only expects a
5155 // single input.
5156 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5157 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5158 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5159 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5160 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5161 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5162 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5163 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5164 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5166 bool IsHostOffloadingAction =
5169 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
5170 Args.hasFlag(options::OPT_offload_new_driver,
5171 options::OPT_no_offload_new_driver,
5172 C.getActiveOffloadKinds() != Action::OFK_None));
5173
5174 bool IsRDCMode =
5175 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
5176
5177 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5178 bool IsUsingLTO = LTOMode != LTOK_None;
5179
5180 // Extract API doesn't have a main input file, so invent a fake one as a
5181 // placeholder.
5182 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5183 "extract-api");
5184
5185 const InputInfo &Input =
5186 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5187
5188 InputInfoList ExtractAPIInputs;
5189 InputInfoList HostOffloadingInputs;
5190 const InputInfo *CudaDeviceInput = nullptr;
5191 const InputInfo *OpenMPDeviceInput = nullptr;
5192 for (const InputInfo &I : Inputs) {
5193 if (&I == &Input || I.getType() == types::TY_Nothing) {
5194 // This is the primary input or contains nothing.
5195 } else if (IsExtractAPI) {
5196 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5197 if (I.getType() != ExpectedInputType) {
5198 D.Diag(diag::err_drv_extract_api_wrong_kind)
5199 << I.getFilename() << types::getTypeName(I.getType())
5200 << types::getTypeName(ExpectedInputType);
5201 }
5202 ExtractAPIInputs.push_back(I);
5203 } else if (IsHostOffloadingAction) {
5204 HostOffloadingInputs.push_back(I);
5205 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5206 CudaDeviceInput = &I;
5207 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5208 OpenMPDeviceInput = &I;
5209 } else {
5210 llvm_unreachable("unexpectedly given multiple inputs");
5211 }
5212 }
5213
5214 bool IsUEFI = RawTriple.isUEFI();
5215 bool IsIAMCU = RawTriple.isOSIAMCU();
5216
5217 // C++ is not supported for IAMCU.
5218 if (IsIAMCU && types::isCXX(Input.getType()))
5219 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5220
5221 // Invoke ourselves in -cc1 mode.
5222 //
5223 // FIXME: Implement custom jobs for internal actions.
5224 CmdArgs.push_back("-cc1");
5225
5226 // Add the "effective" target triple.
5227 CmdArgs.push_back("-triple");
5228 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5229
5230 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5231
5232 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5233 if (AuxTriple) {
5234 CmdArgs.push_back("-aux-triple");
5235 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5236
5237 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5238 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5239 // Windows), we need to pass Windows-specific flags to cc1.
5240 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5242 // Figure out the device side triple for the host-side compilation.
5243 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5244 ++I) {
5246 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5247 if (OffloadToolChains.first == OffloadToolChains.second)
5248 continue;
5249
5250 const llvm::Triple &DeviceAuxTriple =
5251 OffloadToolChains.first->second->getTriple();
5252 CmdArgs.push_back("-aux-triple");
5253 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5254 break;
5255 }
5256 }
5257
5258 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5259 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5260 Args.ClaimAllArgs(options::OPT_MJ);
5261 } else if (const Arg *GenCDBFragment =
5262 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5263 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5264 TripleStr, Output, Input, Args);
5265 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5266 }
5267
5268 if ((getToolChain().getTriple().isAMDGPU() ||
5269 (getToolChain().getTriple().isSPIRV() &&
5270 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5271 // Device side compilation printf
5272 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5273 CmdArgs.push_back(Args.MakeArgString(
5274 "-mprintf-kind=" +
5275 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5276 // Force compiler error on invalid conversion specifiers
5277 CmdArgs.push_back(
5278 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5279 }
5280 }
5281
5282 if (IsCuda && !IsCudaDevice) {
5283 // We need to figure out which CUDA version we're compiling for, as that
5284 // determines how we load and launch GPU kernels.
5285 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5286 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5287 assert(CTC && "Expected valid CUDA Toolchain.");
5288 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5289 CmdArgs.push_back(Args.MakeArgString(
5290 Twine("-target-sdk-version=") +
5291 CudaVersionToString(CTC->CudaInstallation.version())));
5292 }
5293
5294 // Optimization level for CodeGen.
5295 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5296 if (A->getOption().matches(options::OPT_O4)) {
5297 CmdArgs.push_back("-O3");
5298 D.Diag(diag::warn_O4_is_O3);
5299 } else {
5300 A->render(Args, CmdArgs);
5301 }
5302 }
5303
5304 // Unconditionally claim the printf option now to avoid unused diagnostic.
5305 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5306 PF->claim();
5307
5308 if (IsSYCL) {
5309 if (IsSYCLDevice) {
5310 // We want to compile sycl kernels.
5311 CmdArgs.push_back("-fsycl-is-device");
5312
5313 // Set O2 optimization level by default
5314 if (!Args.getLastArg(options::OPT_O_Group))
5315 CmdArgs.push_back("-O2");
5316 } else {
5317 // Add any options that are needed specific to SYCL offload while
5318 // performing the host side compilation.
5319
5320 // Let the front-end host compilation flow know about SYCL offload
5321 // compilation.
5322 CmdArgs.push_back("-fsycl-is-host");
5323 }
5324
5325 // Set options for both host and device.
5326 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5327 if (SYCLStdArg) {
5328 SYCLStdArg->render(Args, CmdArgs);
5329 } else {
5330 // Ensure the default version in SYCL mode is 2020.
5331 CmdArgs.push_back("-sycl-std=2020");
5332 }
5333 }
5334
5335 if (Args.hasArg(options::OPT_fclangir))
5336 CmdArgs.push_back("-fclangir");
5337
5338 if (IsOpenMPDevice) {
5339 // We have to pass the triple of the host if compiling for an OpenMP device.
5340 const llvm::Triple &HostTriple =
5341 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5342 CmdArgs.push_back("-aux-triple");
5343 CmdArgs.push_back(HostTriple.str().c_str());
5344 }
5345
5346 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5347 Triple.getArch() == llvm::Triple::thumb)) {
5348 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5349 unsigned Version = 0;
5350 bool Failure =
5351 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5352 if (Failure || Version < 7)
5353 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5354 << TripleStr;
5355 }
5356
5357 // Push all default warning arguments that are specific to
5358 // the given target. These come before user provided warning options
5359 // are provided.
5360 TC.addClangWarningOptions(CmdArgs);
5361
5362 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5363 if (Triple.isSPIR() || Triple.isSPIRV())
5364 CmdArgs.push_back("-Wspir-compat");
5365
5366 // Select the appropriate action.
5367 RewriteKind rewriteKind = RK_None;
5368
5369 bool UnifiedLTO = false;
5370 if (IsUsingLTO) {
5371 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5372 options::OPT_fno_unified_lto, Triple.isPS());
5373 if (UnifiedLTO)
5374 CmdArgs.push_back("-funified-lto");
5375 }
5376
5377 if (Args.hasArg(options::OPT_fdefined_pointer_subtraction))
5378 CmdArgs.push_back("-fdefined-pointer-subtraction");
5379
5380 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5381 // it claims when not running an assembler. Otherwise, clang would emit
5382 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5383 // flags while debugging something. That'd be somewhat inconvenient, and it's
5384 // also inconsistent with most other flags -- we don't warn on
5385 // -ffunction-sections not being used in -E mode either for example, even
5386 // though it's not really used either.
5387 if (!isa<AssembleJobAction>(JA)) {
5388 // The args claimed here should match the args used in
5389 // CollectArgsForIntegratedAssembler().
5390 if (TC.useIntegratedAs()) {
5391 Args.ClaimAllArgs(options::OPT_mrelax_all);
5392 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5393 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5394 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5395 switch (C.getDefaultToolChain().getArch()) {
5396 case llvm::Triple::arm:
5397 case llvm::Triple::armeb:
5398 case llvm::Triple::thumb:
5399 case llvm::Triple::thumbeb:
5400 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5401 break;
5402 default:
5403 break;
5404 }
5405 }
5406 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5407 Args.ClaimAllArgs(options::OPT_Xassembler);
5408 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5409 }
5410
5411 bool IsAMDSPIRVForHIPDevice =
5412 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5413 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5414
5415 if (isa<AnalyzeJobAction>(JA)) {
5416 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5417 CmdArgs.push_back("-analyze");
5418 } else if (isa<PreprocessJobAction>(JA)) {
5419 if (Output.getType() == types::TY_Dependencies)
5420 CmdArgs.push_back("-Eonly");
5421 else {
5422 CmdArgs.push_back("-E");
5423 if (Args.hasArg(options::OPT_rewrite_objc) &&
5424 !Args.hasArg(options::OPT_g_Group))
5425 CmdArgs.push_back("-P");
5426 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5427 CmdArgs.push_back("-fdirectives-only");
5428 }
5429 } else if (isa<AssembleJobAction>(JA)) {
5430 CmdArgs.push_back("-emit-obj");
5431
5432 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5433
5434 // Also ignore explicit -force_cpusubtype_ALL option.
5435 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5436 } else if (isa<PrecompileJobAction>(JA)) {
5437 if (JA.getType() == types::TY_Nothing)
5438 CmdArgs.push_back("-fsyntax-only");
5439 else if (JA.getType() == types::TY_ModuleFile) {
5440 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5441 ((Input.getType() == types::TY_CXXStdModule ||
5442 Input.getType() == types::TY_PP_CXXStdModule) &&
5443 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5444 CmdArgs.push_back("-emit-reduced-module-interface");
5445 else
5446 CmdArgs.push_back("-emit-module-interface");
5447 } else if (JA.getType() == types::TY_HeaderUnit)
5448 CmdArgs.push_back("-emit-header-unit");
5449 else if (!Args.hasArg(options::OPT_ignore_pch))
5450 CmdArgs.push_back("-emit-pch");
5451 } else if (isa<VerifyPCHJobAction>(JA)) {
5452 CmdArgs.push_back("-verify-pch");
5453 } else if (isa<ExtractAPIJobAction>(JA)) {
5454 assert(JA.getType() == types::TY_API_INFO &&
5455 "Extract API actions must generate a API information.");
5456 CmdArgs.push_back("-extract-api");
5457
5458 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5459 PrettySGFArg->render(Args, CmdArgs);
5460
5461 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5462
5463 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5464 ProductNameArg->render(Args, CmdArgs);
5465 if (Arg *ExtractAPIIgnoresFileArg =
5466 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5467 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5468 if (Arg *EmitExtensionSymbolGraphs =
5469 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5470 if (!SymbolGraphDirArg)
5471 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5472
5473 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5474 }
5475 if (SymbolGraphDirArg)
5476 SymbolGraphDirArg->render(Args, CmdArgs);
5477 } else {
5478 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5479 "Invalid action for clang tool.");
5480 if (JA.getType() == types::TY_Nothing) {
5481 CmdArgs.push_back("-fsyntax-only");
5482 } else if (JA.getType() == types::TY_LLVM_IR ||
5483 JA.getType() == types::TY_LTO_IR) {
5484 CmdArgs.push_back("-emit-llvm");
5485 } else if (JA.getType() == types::TY_LLVM_BC ||
5486 JA.getType() == types::TY_LTO_BC) {
5487 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5488 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5489 Args.hasArg(options::OPT_emit_llvm)) {
5490 CmdArgs.push_back("-emit-llvm");
5491 } else {
5492 CmdArgs.push_back("-emit-llvm-bc");
5493 }
5494 } else if (JA.getType() == types::TY_IFS ||
5495 JA.getType() == types::TY_IFS_CPP) {
5496 StringRef ArgStr =
5497 Args.hasArg(options::OPT_interface_stub_version_EQ)
5498 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5499 : "ifs-v1";
5500 CmdArgs.push_back("-emit-interface-stubs");
5501 CmdArgs.push_back(
5502 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5503 } else if (JA.getType() == types::TY_PP_Asm) {
5504 CmdArgs.push_back("-S");
5505 } else if (JA.getType() == types::TY_AST) {
5506 if (!Args.hasArg(options::OPT_ignore_pch))
5507 CmdArgs.push_back("-emit-pch");
5508 } else if (JA.getType() == types::TY_ModuleFile) {
5509 CmdArgs.push_back("-module-file-info");
5510 } else if (JA.getType() == types::TY_RewrittenObjC) {
5511 CmdArgs.push_back("-rewrite-objc");
5512 rewriteKind = RK_NonFragile;
5513 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5514 CmdArgs.push_back("-rewrite-objc");
5515 rewriteKind = RK_Fragile;
5516 } else if (JA.getType() == types::TY_CIR) {
5517 CmdArgs.push_back("-emit-cir");
5518 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5519 CmdArgs.push_back("-emit-obj");
5520 } else {
5521 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5522 }
5523
5524 // Preserve use-list order by default when emitting bitcode, so that
5525 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5526 // same result as running passes here. For LTO, we don't need to preserve
5527 // the use-list order, since serialization to bitcode is part of the flow.
5528 if (JA.getType() == types::TY_LLVM_BC)
5529 CmdArgs.push_back("-emit-llvm-uselists");
5530
5531 if (IsUsingLTO) {
5532 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5533 options::OPT_foffload_lto_EQ);
5534 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5535 !Args.hasFlag(options::OPT_offload_new_driver,
5536 options::OPT_no_offload_new_driver,
5537 C.getActiveOffloadKinds() != Action::OFK_None) &&
5538 !Triple.isAMDGPU() && !Triple.isSPIRV()) {
5539 D.Diag(diag::err_drv_unsupported_opt_for_target)
5540 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5541 << Triple.getTriple();
5542 } else if (Triple.isNVPTX() && !IsRDCMode &&
5544 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5545 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5546 << "-fno-gpu-rdc";
5547 } else {
5548 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5549 CmdArgs.push_back(Args.MakeArgString(
5550 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5551 // PS4 uses the legacy LTO API, which does not support some of the
5552 // features enabled by -flto-unit.
5553 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5554 CmdArgs.push_back("-flto-unit");
5555 }
5556 }
5557 }
5558
5559 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5560
5561 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5562 if (!types::isLLVMIR(Input.getType()))
5563 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5564 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5565 }
5566
5567 if (Triple.isPPC())
5568 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5569 options::OPT_mno_regnames);
5570
5571 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5572 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5573
5574 if (Args.getLastArg(options::OPT_save_temps_EQ))
5575 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5576
5577 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5578 options::OPT_fmemory_profile_EQ,
5579 options::OPT_fno_memory_profile);
5580 if (MemProfArg &&
5581 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5582 MemProfArg->render(Args, CmdArgs);
5583
5584 if (auto *MemProfUseArg =
5585 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5586 if (MemProfArg)
5587 D.Diag(diag::err_drv_argument_not_allowed_with)
5588 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5589 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5590 options::OPT_fprofile_generate_EQ))
5591 D.Diag(diag::err_drv_argument_not_allowed_with)
5592 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5593 MemProfUseArg->render(Args, CmdArgs);
5594 }
5595
5596 // Embed-bitcode option.
5597 // Only white-listed flags below are allowed to be embedded.
5598 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5600 // Add flags implied by -fembed-bitcode.
5601 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5602 // Disable all llvm IR level optimizations.
5603 CmdArgs.push_back("-disable-llvm-passes");
5604
5605 // Render target options.
5606 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5608
5609 // reject options that shouldn't be supported in bitcode
5610 // also reject kernel/kext
5611 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5612 options::OPT_mkernel,
5613 options::OPT_fapple_kext,
5614 options::OPT_ffunction_sections,
5615 options::OPT_fno_function_sections,
5616 options::OPT_fdata_sections,
5617 options::OPT_fno_data_sections,
5618 options::OPT_fbasic_block_sections_EQ,
5619 options::OPT_funique_internal_linkage_names,
5620 options::OPT_fno_unique_internal_linkage_names,
5621 options::OPT_funique_section_names,
5622 options::OPT_fno_unique_section_names,
5623 options::OPT_funique_basic_block_section_names,
5624 options::OPT_fno_unique_basic_block_section_names,
5625 options::OPT_mrestrict_it,
5626 options::OPT_mno_restrict_it,
5627 options::OPT_mstackrealign,
5628 options::OPT_mno_stackrealign,
5629 options::OPT_mstack_alignment,
5630 options::OPT_mcmodel_EQ,
5631 options::OPT_mlong_calls,
5632 options::OPT_mno_long_calls,
5633 options::OPT_ggnu_pubnames,
5634 options::OPT_gdwarf_aranges,
5635 options::OPT_fdebug_types_section,
5636 options::OPT_fno_debug_types_section,
5637 options::OPT_fdwarf_directory_asm,
5638 options::OPT_fno_dwarf_directory_asm,
5639 options::OPT_mrelax_all,
5640 options::OPT_mno_relax_all,
5641 options::OPT_ftrap_function_EQ,
5642 options::OPT_ffixed_r9,
5643 options::OPT_mfix_cortex_a53_835769,
5644 options::OPT_mno_fix_cortex_a53_835769,
5645 options::OPT_ffixed_x18,
5646 options::OPT_mglobal_merge,
5647 options::OPT_mno_global_merge,
5648 options::OPT_mred_zone,
5649 options::OPT_mno_red_zone,
5650 options::OPT_Wa_COMMA,
5651 options::OPT_Xassembler,
5652 options::OPT_mllvm,
5653 options::OPT_mmlir,
5654 };
5655 for (const auto &A : Args)
5656 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5657 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5658
5659 // Render the CodeGen options that need to be passed.
5660 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5661 options::OPT_fno_optimize_sibling_calls);
5662
5664 CmdArgs, JA);
5665
5666 // Render ABI arguments
5667 switch (TC.getArch()) {
5668 default: break;
5669 case llvm::Triple::arm:
5670 case llvm::Triple::armeb:
5671 case llvm::Triple::thumbeb:
5672 RenderARMABI(D, Triple, Args, CmdArgs);
5673 break;
5674 case llvm::Triple::aarch64:
5675 case llvm::Triple::aarch64_32:
5676 case llvm::Triple::aarch64_be:
5677 RenderAArch64ABI(Triple, Args, CmdArgs);
5678 break;
5679 }
5680
5681 // Input/Output file.
5682 if (Output.getType() == types::TY_Dependencies) {
5683 // Handled with other dependency code.
5684 } else if (Output.isFilename()) {
5685 CmdArgs.push_back("-o");
5686 CmdArgs.push_back(Output.getFilename());
5687 } else {
5688 assert(Output.isNothing() && "Input output.");
5689 }
5690
5691 for (const auto &II : Inputs) {
5692 addDashXForInput(Args, II, CmdArgs);
5693 if (II.isFilename())
5694 CmdArgs.push_back(II.getFilename());
5695 else
5696 II.getInputArg().renderAsInput(Args, CmdArgs);
5697 }
5698
5699 C.addCommand(std::make_unique<Command>(
5701 CmdArgs, Inputs, Output, D.getPrependArg()));
5702 return;
5703 }
5704
5705 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5706 CmdArgs.push_back("-fembed-bitcode=marker");
5707
5708 // We normally speed up the clang process a bit by skipping destructors at
5709 // exit, but when we're generating diagnostics we can rely on some of the
5710 // cleanup.
5711 if (!C.isForDiagnostics())
5712 CmdArgs.push_back("-disable-free");
5713 CmdArgs.push_back("-clear-ast-before-backend");
5714
5715#ifdef NDEBUG
5716 const bool IsAssertBuild = false;
5717#else
5718 const bool IsAssertBuild = true;
5719#endif
5720
5721 // Disable the verification pass in no-asserts builds unless otherwise
5722 // specified.
5723 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5724 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5725 CmdArgs.push_back("-disable-llvm-verifier");
5726 }
5727
5728 // Discard value names in no-asserts builds unless otherwise specified.
5729 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5730 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5731 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5732 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5733 return types::isLLVMIR(II.getType());
5734 })) {
5735 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5736 }
5737 CmdArgs.push_back("-discard-value-names");
5738 }
5739
5740 // Set the main file name, so that debug info works even with
5741 // -save-temps.
5742 CmdArgs.push_back("-main-file-name");
5743 CmdArgs.push_back(getBaseInputName(Args, Input));
5744
5745 // Some flags which affect the language (via preprocessor
5746 // defines).
5747 if (Args.hasArg(options::OPT_static))
5748 CmdArgs.push_back("-static-define");
5749
5750 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5751
5752 if (Args.hasArg(options::OPT_municode))
5753 CmdArgs.push_back("-DUNICODE");
5754
5755 if (isa<AnalyzeJobAction>(JA))
5756 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5757
5758 if (isa<AnalyzeJobAction>(JA) ||
5759 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5760 CmdArgs.push_back("-setup-static-analyzer");
5761
5762 // Enable compatilibily mode to avoid analyzer-config related errors.
5763 // Since we can't access frontend flags through hasArg, let's manually iterate
5764 // through them.
5765 bool FoundAnalyzerConfig = false;
5766 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5767 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5768 FoundAnalyzerConfig = true;
5769 break;
5770 }
5771 if (!FoundAnalyzerConfig)
5772 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5773 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5774 FoundAnalyzerConfig = true;
5775 break;
5776 }
5777 if (FoundAnalyzerConfig)
5778 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5779
5781
5782 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5783 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5784 if (FunctionAlignment) {
5785 CmdArgs.push_back("-function-alignment");
5786 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5787 }
5788
5789 if (const Arg *A =
5790 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5791 unsigned Value = 0;
5792 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5793 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5794 << A->getAsString(Args) << A->getValue();
5795 else if (!llvm::isPowerOf2_32(Value))
5796 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5797 << A->getAsString(Args) << A->getValue();
5798
5799 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5800 Twine(std::min(Value, 65536u))));
5801 }
5802
5803 // We support -falign-loops=N where N is a power of 2. GCC supports more
5804 // forms.
5805 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5806 unsigned Value = 0;
5807 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5808 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5809 << A->getAsString(Args) << A->getValue();
5810 else if (Value & (Value - 1))
5811 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5812 << A->getAsString(Args) << A->getValue();
5813 // Treat =0 as unspecified (use the target preference).
5814 if (Value)
5815 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5816 Twine(std::min(Value, 65536u))));
5817 }
5818
5819 if (Triple.isOSzOS()) {
5820 // On z/OS some of the system header feature macros need to
5821 // be defined to enable most cross platform projects to build
5822 // successfully. Ths include the libc++ library. A
5823 // complicating factor is that users can define these
5824 // macros to the same or different values. We need to add
5825 // the definition for these macros to the compilation command
5826 // if the user hasn't already defined them.
5827
5828 auto findMacroDefinition = [&](const std::string &Macro) {
5829 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5830 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5831 return M == Macro || M.find(Macro + '=') != std::string::npos;
5832 });
5833 };
5834
5835 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5836 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5837 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5838 // _OPEN_DEFAULT is required for XL compat
5839 if (!findMacroDefinition("_OPEN_DEFAULT"))
5840 CmdArgs.push_back("-D_OPEN_DEFAULT");
5841 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5842 // _XOPEN_SOURCE=600 is required for libcxx.
5843 if (!findMacroDefinition("_XOPEN_SOURCE"))
5844 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5845 }
5846 }
5847
5848 llvm::Reloc::Model RelocationModel;
5849 unsigned PICLevel;
5850 bool IsPIE;
5851 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5852 Arg *LastPICDataRelArg =
5853 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5854 options::OPT_mpic_data_is_text_relative);
5855 bool NoPICDataIsTextRelative = false;
5856 if (LastPICDataRelArg) {
5857 if (LastPICDataRelArg->getOption().matches(
5858 options::OPT_mno_pic_data_is_text_relative)) {
5859 NoPICDataIsTextRelative = true;
5860 if (!PICLevel)
5861 D.Diag(diag::err_drv_argument_only_allowed_with)
5862 << "-mno-pic-data-is-text-relative"
5863 << "-fpic/-fpie";
5864 }
5865 if (!Triple.isSystemZ())
5866 D.Diag(diag::err_drv_unsupported_opt_for_target)
5867 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5868 : "-mpic-data-is-text-relative")
5869 << RawTriple.str();
5870 }
5871
5872 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5873 RelocationModel == llvm::Reloc::ROPI_RWPI;
5874 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5875 RelocationModel == llvm::Reloc::ROPI_RWPI;
5876
5877 if (Args.hasArg(options::OPT_mcmse) &&
5878 !Args.hasArg(options::OPT_fallow_unsupported)) {
5879 if (IsROPI)
5880 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5881 if (IsRWPI)
5882 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5883 }
5884
5885 if (IsROPI && types::isCXX(Input.getType()) &&
5886 !Args.hasArg(options::OPT_fallow_unsupported))
5887 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5888
5889 const char *RMName = RelocationModelName(RelocationModel);
5890 if (RMName) {
5891 CmdArgs.push_back("-mrelocation-model");
5892 CmdArgs.push_back(RMName);
5893 }
5894 if (PICLevel > 0) {
5895 CmdArgs.push_back("-pic-level");
5896 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5897 if (IsPIE)
5898 CmdArgs.push_back("-pic-is-pie");
5899 if (NoPICDataIsTextRelative)
5900 CmdArgs.push_back("-mcmodel=medium");
5901 }
5902
5903 if (RelocationModel == llvm::Reloc::ROPI ||
5904 RelocationModel == llvm::Reloc::ROPI_RWPI)
5905 CmdArgs.push_back("-fropi");
5906 if (RelocationModel == llvm::Reloc::RWPI ||
5907 RelocationModel == llvm::Reloc::ROPI_RWPI)
5908 CmdArgs.push_back("-frwpi");
5909
5910 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5911 CmdArgs.push_back("-meabi");
5912 CmdArgs.push_back(A->getValue());
5913 }
5914
5915 // -fsemantic-interposition is forwarded to CC1: set the
5916 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5917 // make default visibility external linkage definitions dso_preemptable.
5918 //
5919 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5920 // aliases (make default visibility external linkage definitions dso_local).
5921 // This is the CC1 default for ELF to match COFF/Mach-O.
5922 //
5923 // Otherwise use Clang's traditional behavior: like
5924 // -fno-semantic-interposition but local aliases are not used. So references
5925 // can be interposed if not optimized out.
5926 if (Triple.isOSBinFormatELF()) {
5927 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5928 options::OPT_fno_semantic_interposition);
5929 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5930 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5931 bool SupportsLocalAlias =
5932 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5933 if (!A)
5934 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5935 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5936 A->render(Args, CmdArgs);
5937 else if (!SupportsLocalAlias)
5938 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5939 }
5940 }
5941
5942 {
5943 std::string Model;
5944 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5945 if (!TC.isThreadModelSupported(A->getValue()))
5946 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5947 << A->getValue() << A->getAsString(Args);
5948 Model = A->getValue();
5949 } else
5950 Model = TC.getThreadModel();
5951 if (Model != "posix") {
5952 CmdArgs.push_back("-mthread-model");
5953 CmdArgs.push_back(Args.MakeArgString(Model));
5954 }
5955 }
5956
5957 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5958 StringRef Name = A->getValue();
5959 if (Name == "SVML") {
5960 if (Triple.getArch() != llvm::Triple::x86 &&
5961 Triple.getArch() != llvm::Triple::x86_64)
5962 D.Diag(diag::err_drv_unsupported_opt_for_target)
5963 << Name << Triple.getArchName();
5964 } else if (Name == "AMDLIBM") {
5965 if (Triple.getArch() != llvm::Triple::x86 &&
5966 Triple.getArch() != llvm::Triple::x86_64)
5967 D.Diag(diag::err_drv_unsupported_opt_for_target)
5968 << Name << Triple.getArchName();
5969 } else if (Name == "libmvec") {
5970 if (Triple.getArch() != llvm::Triple::x86 &&
5971 Triple.getArch() != llvm::Triple::x86_64 &&
5972 Triple.getArch() != llvm::Triple::aarch64 &&
5973 Triple.getArch() != llvm::Triple::aarch64_be)
5974 D.Diag(diag::err_drv_unsupported_opt_for_target)
5975 << Name << Triple.getArchName();
5976 } else if (Name == "SLEEF" || Name == "ArmPL") {
5977 if (Triple.getArch() != llvm::Triple::aarch64 &&
5978 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
5979 D.Diag(diag::err_drv_unsupported_opt_for_target)
5980 << Name << Triple.getArchName();
5981 }
5982 A->render(Args, CmdArgs);
5983 }
5984
5985 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5986 options::OPT_fno_merge_all_constants, false))
5987 CmdArgs.push_back("-fmerge-all-constants");
5988
5989 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5990 options::OPT_fno_delete_null_pointer_checks);
5991
5992 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
5993 options::OPT_fno_lifetime_dse);
5994
5995 // LLVM Code Generator Options.
5996
5997 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5998 if (!Triple.isOSAIX() || Triple.isPPC32())
5999 D.Diag(diag::err_drv_unsupported_opt_for_target)
6000 << A->getSpelling() << RawTriple.str();
6001 CmdArgs.push_back("-mabi=quadword-atomics");
6002 }
6003
6004 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
6005 // Emit the unsupported option error until the Clang's library integration
6006 // support for 128-bit long double is available for AIX.
6007 if (Triple.isOSAIX())
6008 D.Diag(diag::err_drv_unsupported_opt_for_target)
6009 << A->getSpelling() << RawTriple.str();
6010 }
6011
6012 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6013 StringRef V = A->getValue(), V1 = V;
6014 unsigned Size;
6015 if (V1.consumeInteger(10, Size) || !V1.empty())
6016 D.Diag(diag::err_drv_invalid_argument_to_option)
6017 << V << A->getOption().getName();
6018 else
6019 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6020 }
6021
6022 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6023 options::OPT_fno_jump_tables);
6024 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6025 options::OPT_fno_profile_sample_accurate);
6026 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6027 options::OPT_fno_preserve_as_comments);
6028
6029 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6030 CmdArgs.push_back("-mregparm");
6031 CmdArgs.push_back(A->getValue());
6032 }
6033
6034 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6035 options::OPT_msvr4_struct_return)) {
6036 if (!TC.getTriple().isPPC32()) {
6037 D.Diag(diag::err_drv_unsupported_opt_for_target)
6038 << A->getSpelling() << RawTriple.str();
6039 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6040 CmdArgs.push_back("-maix-struct-return");
6041 } else {
6042 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6043 CmdArgs.push_back("-msvr4-struct-return");
6044 }
6045 }
6046
6047 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6048 options::OPT_freg_struct_return)) {
6049 if (TC.getArch() != llvm::Triple::x86) {
6050 D.Diag(diag::err_drv_unsupported_opt_for_target)
6051 << A->getSpelling() << RawTriple.str();
6052 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6053 CmdArgs.push_back("-fpcc-struct-return");
6054 } else {
6055 assert(A->getOption().matches(options::OPT_freg_struct_return));
6056 CmdArgs.push_back("-freg-struct-return");
6057 }
6058 }
6059
6060 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6061 if (Triple.getArch() == llvm::Triple::m68k)
6062 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6063 else
6064 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6065 }
6066
6067 if (Args.hasArg(options::OPT_fenable_matrix)) {
6068 // enable-matrix is needed by both the LangOpts and by LLVM.
6069 CmdArgs.push_back("-fenable-matrix");
6070 CmdArgs.push_back("-mllvm");
6071 CmdArgs.push_back("-enable-matrix");
6072 // Only handle default layout if matrix is enabled
6073 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6074 StringRef Val = A->getValue();
6075 if (Val == "row-major" || Val == "column-major") {
6076 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6077 CmdArgs.push_back("-mllvm");
6078 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6079
6080 } else {
6081 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6082 }
6083 }
6084 }
6085
6087 getFramePointerKind(Args, RawTriple);
6088 const char *FPKeepKindStr = nullptr;
6089 switch (FPKeepKind) {
6091 FPKeepKindStr = "-mframe-pointer=none";
6092 break;
6094 FPKeepKindStr = "-mframe-pointer=reserved";
6095 break;
6097 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6098 break;
6100 FPKeepKindStr = "-mframe-pointer=non-leaf";
6101 break;
6103 FPKeepKindStr = "-mframe-pointer=all";
6104 break;
6105 }
6106 assert(FPKeepKindStr && "unknown FramePointerKind");
6107 CmdArgs.push_back(FPKeepKindStr);
6108
6109 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6110 options::OPT_fno_zero_initialized_in_bss);
6111
6112 bool OFastEnabled = isOptimizationLevelFast(Args);
6113 if (Args.hasArg(options::OPT_Ofast))
6114 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6115 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6116 // enabled. This alias option is being used to simplify the hasFlag logic.
6117 OptSpecifier StrictAliasingAliasOption =
6118 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6119 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6120 // doesn't do any TBAA.
6121 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6122 options::OPT_fno_strict_aliasing,
6123 !IsWindowsMSVC && !IsUEFI))
6124 CmdArgs.push_back("-relaxed-aliasing");
6125 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6126 false))
6127 CmdArgs.push_back("-no-pointer-tbaa");
6128 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6129 options::OPT_fno_struct_path_tbaa, true))
6130 CmdArgs.push_back("-no-struct-path-tbaa");
6131
6132 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6133 options::OPT_fno_strict_bool,
6134 options::OPT_fno_strict_bool_EQ)) {
6135 StringRef BFM = "";
6136 if (A->getOption().matches(options::OPT_fstrict_bool))
6137 BFM = "strict";
6138 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6139 BFM = "nonstrict";
6140 else if (A->getValue() == StringRef("truncate"))
6141 BFM = "truncate";
6142 else if (A->getValue() == StringRef("nonzero"))
6143 BFM = "nonzero";
6144 else
6145 D.Diag(diag::err_drv_invalid_value)
6146 << A->getAsString(Args) << A->getValue();
6147 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6148 } else if (KernelOrKext) {
6149 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6150 CmdArgs.push_back("-load-bool-from-mem=truncate");
6151 }
6152
6153 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6154 options::OPT_fno_strict_enums);
6155 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6156 options::OPT_fno_strict_return);
6157 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6158 options::OPT_fno_allow_editor_placeholders);
6159 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6160 options::OPT_fno_strict_vtable_pointers);
6161 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6162 options::OPT_fno_force_emit_vtables);
6163 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6164 options::OPT_fno_optimize_sibling_calls);
6165 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6166 options::OPT_fno_escaping_block_tail_calls);
6167
6168 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6169 options::OPT_fno_fine_grained_bitfield_accesses);
6170
6171 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6172 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6173
6174 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6175 options::OPT_fno_experimental_omit_vtable_rtti);
6176
6177 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6178 options::OPT_fno_disable_block_signature_string);
6179
6180 // Handle segmented stacks.
6181 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6182 options::OPT_fno_split_stack);
6183
6184 // -fprotect-parens=0 is default.
6185 if (Args.hasFlag(options::OPT_fprotect_parens,
6186 options::OPT_fno_protect_parens, false))
6187 CmdArgs.push_back("-fprotect-parens");
6188
6189 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6190
6191 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6192 options::OPT_fno_atomic_remote_memory);
6193 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6194 options::OPT_fno_atomic_fine_grained_memory);
6195 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6196 options::OPT_fno_atomic_ignore_denormal_mode);
6197
6198 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6199 const llvm::Triple::ArchType Arch = TC.getArch();
6200 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6201 StringRef V = A->getValue();
6202 if (V == "64")
6203 CmdArgs.push_back("-fextend-arguments=64");
6204 else if (V != "32")
6205 D.Diag(diag::err_drv_invalid_argument_to_option)
6206 << A->getValue() << A->getOption().getName();
6207 } else
6208 D.Diag(diag::err_drv_unsupported_opt_for_target)
6209 << A->getOption().getName() << TripleStr;
6210 }
6211
6212 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6213 if (TC.getArch() == llvm::Triple::avr)
6214 A->render(Args, CmdArgs);
6215 else
6216 D.Diag(diag::err_drv_unsupported_opt_for_target)
6217 << A->getAsString(Args) << TripleStr;
6218 }
6219
6220 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6221 if (TC.getTriple().isX86())
6222 A->render(Args, CmdArgs);
6223 else if (TC.getTriple().isPPC() &&
6224 (A->getOption().getID() != options::OPT_mlong_double_80))
6225 A->render(Args, CmdArgs);
6226 else
6227 D.Diag(diag::err_drv_unsupported_opt_for_target)
6228 << A->getAsString(Args) << TripleStr;
6229 }
6230
6231 // Decide whether to use verbose asm. Verbose assembly is the default on
6232 // toolchains which have the integrated assembler on by default.
6233 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6234 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6235 IsIntegratedAssemblerDefault))
6236 CmdArgs.push_back("-fno-verbose-asm");
6237
6238 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6239 // use that to indicate the MC default in the backend.
6240 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6241 StringRef V = A->getValue();
6242 unsigned Num;
6243 if (V == "none")
6244 A->render(Args, CmdArgs);
6245 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6246 (V.empty() || (V.consume_front(".") &&
6247 !V.consumeInteger(10, Num) && V.empty())))
6248 A->render(Args, CmdArgs);
6249 else
6250 D.Diag(diag::err_drv_invalid_argument_to_option)
6251 << A->getValue() << A->getOption().getName();
6252 }
6253
6254 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6255 // option to disable integrated-as explicitly.
6257 CmdArgs.push_back("-no-integrated-as");
6258
6259 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6260 CmdArgs.push_back("-mdebug-pass");
6261 CmdArgs.push_back("Structure");
6262 }
6263 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6264 CmdArgs.push_back("-mdebug-pass");
6265 CmdArgs.push_back("Arguments");
6266 }
6267
6268 // Enable -mconstructor-aliases except on darwin, where we have to work around
6269 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6270 // code, where aliases aren't supported.
6271 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6272 CmdArgs.push_back("-mconstructor-aliases");
6273
6274 // Darwin's kernel doesn't support guard variables; just die if we
6275 // try to use them.
6276 if (KernelOrKext && RawTriple.isOSDarwin())
6277 CmdArgs.push_back("-fforbid-guard-variables");
6278
6279 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6280 options::OPT_mno_ms_bitfields)) {
6281 if (A->getOption().matches(options::OPT_mms_bitfields))
6282 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6283 else
6284 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6285 }
6286
6287 if (Triple.isOSCygMing()) {
6288 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6289 options::OPT_fno_auto_import);
6290 }
6291
6292 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6293 Triple.isX86() && IsWindowsMSVC))
6294 CmdArgs.push_back("-fms-volatile");
6295
6296 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6297 // defaults to -fno-direct-access-external-data. Pass the option if different
6298 // from the default.
6299 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6300 options::OPT_fno_direct_access_external_data)) {
6301 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6302 (PICLevel == 0))
6303 A->render(Args, CmdArgs);
6304 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6305 // Some targets default to -fno-direct-access-external-data even for
6306 // -fno-pic.
6307 CmdArgs.push_back("-fno-direct-access-external-data");
6308 }
6309
6310 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6311 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6312
6313 // -fhosted is default.
6314 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6315 // use Freestanding.
6316 bool Freestanding =
6317 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6318 KernelOrKext;
6319 if (Freestanding)
6320 CmdArgs.push_back("-ffreestanding");
6321
6322 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6323
6325 auto SanitizeArgs =
6327 Args.AddLastArg(CmdArgs,
6328 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6329
6330 // This is a coarse approximation of what llvm-gcc actually does, both
6331 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6332 // complicated ways.
6333 bool IsAsyncUnwindTablesDefault =
6335 bool IsSyncUnwindTablesDefault =
6337
6338 bool AsyncUnwindTables = Args.hasFlag(
6339 options::OPT_fasynchronous_unwind_tables,
6340 options::OPT_fno_asynchronous_unwind_tables,
6341 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6342 !Freestanding);
6343 bool UnwindTables =
6344 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6345 IsSyncUnwindTablesDefault && !Freestanding);
6346 if (AsyncUnwindTables)
6347 CmdArgs.push_back("-funwind-tables=2");
6348 else if (UnwindTables)
6349 CmdArgs.push_back("-funwind-tables=1");
6350
6351 // Sframe unwind tables are independent of the other types. Although also
6352 // defined for aarch64, only x86_64 support is implemented at the moment.
6353 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6354 if (Triple.isOSBinFormatELF() && Triple.isX86())
6355 CmdArgs.push_back("--gsframe");
6356 else
6357 D.Diag(diag::err_drv_unsupported_opt_for_target)
6358 << A->getOption().getName() << TripleStr;
6359 }
6360
6361 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6362 // `--gpu-use-aux-triple-only` is specified.
6363 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6364 const ArgList &HostArgs =
6365 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6366 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6367 if (!HostCPU.empty()) {
6368 CmdArgs.push_back("-aux-target-cpu");
6369 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6370 }
6371 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6372 /*ForAS*/ false, /*IsAux*/ true);
6373 }
6374
6375 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6377
6378 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6379
6380 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6381 StringRef Value = A->getValue();
6382 unsigned TLSSize = 0;
6383 Value.getAsInteger(10, TLSSize);
6384 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6385 D.Diag(diag::err_drv_unsupported_opt_for_target)
6386 << A->getOption().getName() << TripleStr;
6387 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6388 D.Diag(diag::err_drv_invalid_int_value)
6389 << A->getOption().getName() << Value;
6390 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6391 }
6392
6393 if (isTLSDESCEnabled(TC, Args))
6394 CmdArgs.push_back("-enable-tlsdesc");
6395
6396 // Add the target cpu
6397 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6398 if (!CPU.empty()) {
6399 CmdArgs.push_back("-target-cpu");
6400 CmdArgs.push_back(Args.MakeArgString(CPU));
6401 }
6402
6403 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6404
6405 // Add clang-cl arguments.
6406 types::ID InputType = Input.getType();
6407 if (D.IsCLMode())
6408 AddClangCLArgs(Args, InputType, CmdArgs);
6409
6410 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6411 llvm::codegenoptions::NoDebugInfo;
6413 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6414 DebugInfoKind, DwarfFission);
6415
6416 // Add the split debug info name to the command lines here so we
6417 // can propagate it to the backend.
6418 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6419 (TC.getTriple().isOSBinFormatELF() ||
6420 TC.getTriple().isOSBinFormatWasm() ||
6421 TC.getTriple().isOSBinFormatCOFF()) &&
6424 if (SplitDWARF) {
6425 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6426 CmdArgs.push_back("-split-dwarf-file");
6427 CmdArgs.push_back(SplitDWARFOut);
6428 if (DwarfFission == DwarfFissionKind::Split) {
6429 CmdArgs.push_back("-split-dwarf-output");
6430 CmdArgs.push_back(SplitDWARFOut);
6431 }
6432 }
6433
6434 // Pass the linker version in use.
6435 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6436 CmdArgs.push_back("-target-linker-version");
6437 CmdArgs.push_back(A->getValue());
6438 }
6439
6440 // Explicitly error on some things we know we don't support and can't just
6441 // ignore.
6442 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6443 Arg *Unsupported;
6444 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6445 TC.getArch() == llvm::Triple::x86) {
6446 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6447 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6448 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6449 << Unsupported->getOption().getName();
6450 }
6451 // The faltivec option has been superseded by the maltivec option.
6452 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6453 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6454 << Unsupported->getOption().getName()
6455 << "please use -maltivec and include altivec.h explicitly";
6456 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6457 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6458 << Unsupported->getOption().getName() << "please use -mno-altivec";
6459 }
6460
6461 Args.AddAllArgs(CmdArgs, options::OPT_v);
6462
6463 if (Args.getLastArg(options::OPT_H)) {
6464 CmdArgs.push_back("-H");
6465 CmdArgs.push_back("-sys-header-deps");
6466 }
6467 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6468
6470 CmdArgs.push_back("-header-include-file");
6471 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6472 ? D.CCPrintHeadersFilename.c_str()
6473 : "-");
6474 CmdArgs.push_back("-sys-header-deps");
6475 CmdArgs.push_back(Args.MakeArgString(
6476 "-header-include-format=" +
6478 CmdArgs.push_back(Args.MakeArgString(
6479 "-header-include-filtering=" +
6481 }
6482 Args.AddLastArg(CmdArgs, options::OPT_P);
6483 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6484
6485 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6486 CmdArgs.push_back("-diagnostic-log-file");
6487 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6488 ? D.CCLogDiagnosticsFilename.c_str()
6489 : "-");
6490 }
6491
6492 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6493 // crashes.
6494 if (D.CCGenDiagnostics)
6495 CmdArgs.push_back("-disable-pragma-debug-crash");
6496
6497 // Allow backend to put its diagnostic files in the same place as frontend
6498 // crash diagnostics files.
6499 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6500 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6501 CmdArgs.push_back("-mllvm");
6502 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6503 }
6504
6505 addSeparateSectionFlags(Triple, Args, CmdArgs);
6506
6507 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6508 options::OPT_fno_basic_block_address_map)) {
6509 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6510 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6511 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6512 A->render(Args, CmdArgs);
6513 } else {
6514 D.Diag(diag::err_drv_unsupported_opt_for_target)
6515 << A->getAsString(Args) << TripleStr;
6516 }
6517 }
6518
6519 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6520 StringRef Val = A->getValue();
6521 if (Val == "labels") {
6522 D.Diag(diag::warn_drv_deprecated_arg)
6523 << A->getAsString(Args) << /*hasReplacement=*/true
6524 << "-fbasic-block-address-map";
6525 CmdArgs.push_back("-fbasic-block-address-map");
6526 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6527 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6528 D.Diag(diag::err_drv_invalid_value)
6529 << A->getAsString(Args) << A->getValue();
6530 else
6531 A->render(Args, CmdArgs);
6532 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6533 // "all" is not supported on AArch64 since branch relaxation creates new
6534 // basic blocks for some cross-section branches.
6535 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6536 D.Diag(diag::err_drv_invalid_value)
6537 << A->getAsString(Args) << A->getValue();
6538 else
6539 A->render(Args, CmdArgs);
6540 } else if (Triple.isNVPTX()) {
6541 // Do not pass the option to the GPU compilation. We still want it enabled
6542 // for the host-side compilation, so seeing it here is not an error.
6543 } else if (Val != "none") {
6544 // =none is allowed everywhere. It's useful for overriding the option
6545 // and is the same as not specifying the option.
6546 D.Diag(diag::err_drv_unsupported_opt_for_target)
6547 << A->getAsString(Args) << TripleStr;
6548 }
6549 }
6550
6551 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6552 options::OPT_fno_unique_section_names);
6553 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6554 options::OPT_fno_separate_named_sections);
6555 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6556 options::OPT_fno_unique_internal_linkage_names);
6557 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6558 options::OPT_fno_unique_basic_block_section_names);
6559
6560 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6561 options::OPT_fno_split_machine_functions)) {
6562 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
6563 // This codegen pass is only available on x86 and AArch64 ELF targets.
6564 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6565 A->render(Args, CmdArgs);
6566 else
6567 D.Diag(diag::err_drv_unsupported_opt_for_target)
6568 << A->getAsString(Args) << TripleStr;
6569 }
6570 }
6571
6572 if (Arg *A =
6573 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6574 options::OPT_fno_partition_static_data_sections)) {
6575 if (!A->getOption().matches(
6576 options::OPT_fno_partition_static_data_sections)) {
6577 // This codegen pass is only available on x86 and AArch64 ELF targets.
6578 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6579 A->render(Args, CmdArgs);
6580 CmdArgs.push_back("-mllvm");
6581 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6582 } else
6583 D.Diag(diag::err_drv_unsupported_opt_for_target)
6584 << A->getAsString(Args) << TripleStr;
6585 }
6586 }
6587
6588 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6589 options::OPT_finstrument_functions_after_inlining,
6590 options::OPT_finstrument_function_entry_bare);
6591 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6592 options::OPT_fno_convergent_functions);
6593
6594 // NVPTX doesn't support PGO or coverage
6595 if (!Triple.isNVPTX())
6596 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6597
6598 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6599
6600 if (getLastProfileSampleUseArg(Args) &&
6601 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6602 options::OPT_fno_sample_profile_use_profi, true)) {
6603 CmdArgs.push_back("-mllvm");
6604 CmdArgs.push_back("-sample-profile-use-profi");
6605 }
6606
6607 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6608 if (RawTriple.isPS() &&
6609 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6610 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6611 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6612 }
6613
6614 // Pass options for controlling the default header search paths.
6615 if (Args.hasArg(options::OPT_nostdinc)) {
6616 CmdArgs.push_back("-nostdsysteminc");
6617 CmdArgs.push_back("-nobuiltininc");
6618 } else {
6619 if (Args.hasArg(options::OPT_nostdlibinc))
6620 CmdArgs.push_back("-nostdsysteminc");
6621 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6622 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6623 }
6624
6625 // Pass the path to compiler resource files.
6626 CmdArgs.push_back("-resource-dir");
6627 CmdArgs.push_back(D.ResourceDir.c_str());
6628
6629 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6630
6631 // Add preprocessing options like -I, -D, etc. if we are using the
6632 // preprocessor.
6633 //
6634 // FIXME: Support -fpreprocessed
6636 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6637
6638 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6639 // that "The compiler can only warn and ignore the option if not recognized".
6640 // When building with ccache, it will pass -D options to clang even on
6641 // preprocessed inputs and configure concludes that -fPIC is not supported.
6642 Args.ClaimAllArgs(options::OPT_D);
6643
6644 // Warn about ignored options to clang.
6645 for (const Arg *A :
6646 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6647 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6648 A->claim();
6649 }
6650
6651 for (const Arg *A :
6652 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6653 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6654 A->claim();
6655 }
6656
6657 claimNoWarnArgs(Args);
6658
6659 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6660
6661 for (const Arg *A :
6662 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6663 A->claim();
6664 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6665 unsigned WarningNumber;
6666 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6667 D.Diag(diag::err_drv_invalid_int_value)
6668 << A->getAsString(Args) << A->getValue();
6669 continue;
6670 }
6671
6672 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6673 CmdArgs.push_back(Args.MakeArgString(
6674 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6675 }
6676 continue;
6677 }
6678 A->render(Args, CmdArgs);
6679 }
6680
6681 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6682
6683 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6684 CmdArgs.push_back("-pedantic");
6685 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6686 Args.AddLastArg(CmdArgs, options::OPT_w);
6687
6688 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6689 options::OPT_fno_fixed_point);
6690
6691 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6692 options::OPT_fno_experimental_overflow_behavior_types);
6693
6694 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6695 A->render(Args, CmdArgs);
6696
6697 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6698 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6699
6700 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6701 options::OPT_fno_experimental_omit_vtable_rtti);
6702
6703 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6704 A->render(Args, CmdArgs);
6705
6706 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6707 // (-ansi is equivalent to -std=c89 or -std=c++98).
6708 //
6709 // If a std is supplied, only add -trigraphs if it follows the
6710 // option.
6711 bool ImplyVCPPCVer = false;
6712 bool ImplyVCPPCXXVer = false;
6713 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6714 if (Std) {
6715 if (Std->getOption().matches(options::OPT_ansi))
6716 if (types::isCXX(InputType))
6717 CmdArgs.push_back("-std=c++98");
6718 else
6719 CmdArgs.push_back("-std=c89");
6720 else {
6721 if (IsSYCL) {
6722 const LangStandard *LangStd =
6723 LangStandard::getLangStandardForName(Std->getValue());
6724 if (LangStd) {
6725 // Use of -std= with 'C' is not supported for SYCL.
6726 if (LangStd->getLanguage() == Language::C)
6727 D.Diag(diag::err_drv_argument_not_allowed_with)
6728 << Std->getAsString(Args) << "-fsycl";
6729 // SYCL requires C++17 or later.
6730 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6731 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6732 }
6733 }
6734 Std->render(Args, CmdArgs);
6735 }
6736
6737 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6738 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6739 options::OPT_ftrigraphs,
6740 options::OPT_fno_trigraphs))
6741 if (A != Std)
6742 A->render(Args, CmdArgs);
6743 } else {
6744 // Honor -std-default.
6745 //
6746 // FIXME: Clang doesn't correctly handle -std= when the input language
6747 // doesn't match. For the time being just ignore this for C++ inputs;
6748 // eventually we want to do all the standard defaulting here instead of
6749 // splitting it between the driver and clang -cc1.
6750 if (!types::isCXX(InputType)) {
6751 if (!Args.hasArg(options::OPT__SLASH_std)) {
6752 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6753 /*Joined=*/true);
6754 } else
6755 ImplyVCPPCVer = true;
6756 }
6757 else if (IsWindowsMSVC)
6758 ImplyVCPPCXXVer = true;
6759
6760 if (IsSYCL && types::isCXX(InputType) &&
6761 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6762 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6763 // on the command line will override. On Windows MSVC, this is handled
6764 // by the ImplyVCPPCXXVer path below.
6765 CmdArgs.push_back("-std=c++17");
6766
6767 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6768 options::OPT_fno_trigraphs);
6769 }
6770
6771 // GCC's behavior for -Wwrite-strings is a bit strange:
6772 // * In C, this "warning flag" changes the types of string literals from
6773 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6774 // for the discarded qualifier.
6775 // * In C++, this is just a normal warning flag.
6776 //
6777 // Implementing this warning correctly in C is hard, so we follow GCC's
6778 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6779 // a non-const char* in C, rather than using this crude hack.
6780 if (!types::isCXX(InputType)) {
6781 // FIXME: This should behave just like a warning flag, and thus should also
6782 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6783 Arg *WriteStrings =
6784 Args.getLastArg(options::OPT_Wwrite_strings,
6785 options::OPT_Wno_write_strings, options::OPT_w);
6786 if (WriteStrings &&
6787 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6788 CmdArgs.push_back("-fconst-strings");
6789 }
6790
6791 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6792 // during C++ compilation, which it is by default. GCC keeps this define even
6793 // in the presence of '-w', match this behavior bug-for-bug.
6794 if (types::isCXX(InputType) &&
6795 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6796 true)) {
6797 CmdArgs.push_back("-fdeprecated-macro");
6798 }
6799
6800 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6801 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6802 if (Asm->getOption().matches(options::OPT_fasm))
6803 CmdArgs.push_back("-fgnu-keywords");
6804 else
6805 CmdArgs.push_back("-fno-gnu-keywords");
6806 }
6807
6808 if (!ShouldEnableAutolink(Args, TC, JA))
6809 CmdArgs.push_back("-fno-autolink");
6810
6811 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6812 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6813 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6814 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6815
6816 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6817
6818 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6819 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6820 Args.AddLastArg(CmdArgs,
6821 options::OPT_fno_experimental_new_constant_interpreter);
6822 } else {
6823 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6824 Args.AddLastArg(CmdArgs,
6825 options::OPT_fexperimental_new_constant_interpreter);
6826 }
6827
6828 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6829 CmdArgs.push_back("-fbracket-depth");
6830 CmdArgs.push_back(A->getValue());
6831 }
6832
6833 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6834 options::OPT_Wlarge_by_value_copy_def)) {
6835 if (A->getNumValues()) {
6836 StringRef bytes = A->getValue();
6837 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6838 } else
6839 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6840 }
6841
6842 if (Args.hasArg(options::OPT_relocatable_pch))
6843 CmdArgs.push_back("-relocatable-pch");
6844
6845 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6846 static const char *kCFABIs[] = {
6847 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6848 };
6849
6850 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6851 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6852 else
6853 A->render(Args, CmdArgs);
6854 }
6855
6856 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6857 CmdArgs.push_back("-fconstant-string-class");
6858 CmdArgs.push_back(A->getValue());
6859 }
6860
6861 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6862 CmdArgs.push_back("-fconstant-array-class");
6863 CmdArgs.push_back(A->getValue());
6864 }
6865 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6866 CmdArgs.push_back("-fconstant-dictionary-class");
6867 CmdArgs.push_back(A->getValue());
6868 }
6869 if (Arg *A =
6870 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6871 CmdArgs.push_back("-fconstant-integer-number-class");
6872 CmdArgs.push_back(A->getValue());
6873 }
6874 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6875 CmdArgs.push_back("-fconstant-float-number-class");
6876 CmdArgs.push_back(A->getValue());
6877 }
6878 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6879 CmdArgs.push_back("-fconstant-double-number-class");
6880 CmdArgs.push_back(A->getValue());
6881 }
6882
6883 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6884 CmdArgs.push_back("-ftabstop");
6885 CmdArgs.push_back(A->getValue());
6886 }
6887
6888 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
6889 options::OPT_fno_experimental_call_graph_section, false))
6890 CmdArgs.push_back("-fexperimental-call-graph-section");
6891
6892 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6893 options::OPT_fno_stack_size_section);
6894
6895 if (Args.hasArg(options::OPT_fstack_usage)) {
6896 CmdArgs.push_back("-stack-usage-file");
6897
6898 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6899 SmallString<128> OutputFilename(OutputOpt->getValue());
6900 llvm::sys::path::replace_extension(OutputFilename, "su");
6901 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6902 } else
6903 CmdArgs.push_back(
6904 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6905 }
6906
6907 CmdArgs.push_back("-ferror-limit");
6908 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6909 CmdArgs.push_back(A->getValue());
6910 else
6911 CmdArgs.push_back("19");
6912
6913 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6914 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6915 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6916 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6917 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6918
6919 // Pass -fmessage-length=.
6920 unsigned MessageLength = 0;
6921 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6922 StringRef V(A->getValue());
6923 if (V.getAsInteger(0, MessageLength))
6924 D.Diag(diag::err_drv_invalid_argument_to_option)
6925 << V << A->getOption().getName();
6926 } else {
6927 // If -fmessage-length=N was not specified, determine whether this is a
6928 // terminal and, if so, implicitly define -fmessage-length appropriately.
6929 MessageLength = llvm::sys::Process::StandardErrColumns();
6930 }
6931 if (MessageLength != 0)
6932 CmdArgs.push_back(
6933 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6934
6935 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6936 CmdArgs.push_back(
6937 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6938
6939 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6940 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6941 Twine(A->getValue(0))));
6942
6943 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6944 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6945 options::OPT_fvisibility_ms_compat)) {
6946 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6947 A->render(Args, CmdArgs);
6948 } else {
6949 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6950 CmdArgs.push_back("-fvisibility=hidden");
6951 CmdArgs.push_back("-ftype-visibility=default");
6952 }
6953 } else if (IsOpenMPDevice) {
6954 // When compiling for the OpenMP device we want protected visibility by
6955 // default. This prevents the device from accidentally preempting code on
6956 // the host, makes the system more robust, and improves performance.
6957 CmdArgs.push_back("-fvisibility=protected");
6958 }
6959
6960 // PS4/PS5 process these options in addClangTargetOptions.
6961 if (!RawTriple.isPS()) {
6962 if (const Arg *A =
6963 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6964 options::OPT_fno_visibility_from_dllstorageclass)) {
6965 if (A->getOption().matches(
6966 options::OPT_fvisibility_from_dllstorageclass)) {
6967 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6968 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6969 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6970 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6971 Args.AddLastArg(CmdArgs,
6972 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6973 }
6974 }
6975 }
6976
6977 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6978 options::OPT_fno_visibility_inlines_hidden, false))
6979 CmdArgs.push_back("-fvisibility-inlines-hidden");
6980
6981 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6982 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6983
6984 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6985 // -fvisibility-global-new-delete=force-hidden.
6986 if (const Arg *A =
6987 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
6988 D.Diag(diag::warn_drv_deprecated_arg)
6989 << A->getAsString(Args) << /*hasReplacement=*/true
6990 << "-fvisibility-global-new-delete=force-hidden";
6991 }
6992
6993 if (const Arg *A =
6994 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
6995 options::OPT_fvisibility_global_new_delete_hidden)) {
6996 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
6997 A->render(Args, CmdArgs);
6998 } else {
6999 assert(A->getOption().matches(
7000 options::OPT_fvisibility_global_new_delete_hidden));
7001 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
7002 }
7003 }
7004
7005 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
7006
7007 if (Args.hasFlag(options::OPT_fnew_infallible,
7008 options::OPT_fno_new_infallible, false))
7009 CmdArgs.push_back("-fnew-infallible");
7010
7011 if (Args.hasFlag(options::OPT_fno_operator_names,
7012 options::OPT_foperator_names, false))
7013 CmdArgs.push_back("-fno-operator-names");
7014
7015 // Forward -f (flag) options which we can pass directly.
7016 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7017 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7018 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7019 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7020 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7021 options::OPT_fno_raw_string_literals);
7022
7023 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7024 Triple.hasDefaultEmulatedTLS()))
7025 CmdArgs.push_back("-femulated-tls");
7026
7027 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7028 options::OPT_fno_check_new);
7029
7030 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7031 // FIXME: There's no reason for this to be restricted to some backend.
7032 // The backend code needs to be changed to include the appropriate function
7033 // calls automatically.
7034 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7035 D.Diag(diag::err_drv_unsupported_opt_for_target)
7036 << A->getAsString(Args) << TripleStr;
7037 }
7038
7039 // AltiVec-like language extensions aren't relevant for assembling.
7040 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7041 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7042
7043 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7044 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7045
7046 // Forward flags for OpenMP. We don't do this if the current action is an
7047 // device offloading action other than OpenMP.
7048 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7049 options::OPT_fno_openmp, false) &&
7050 !Args.hasFlag(options::OPT_foffload_via_llvm,
7051 options::OPT_fno_offload_via_llvm, false) &&
7054
7055 // Determine if target-fast optimizations should be enabled
7056 bool TargetFastUsed =
7057 Args.hasFlag(options::OPT_fopenmp_target_fast,
7058 options::OPT_fno_openmp_target_fast, OFastEnabled);
7059 switch (D.getOpenMPRuntime(Args)) {
7060 case Driver::OMPRT_OMP:
7062 // Clang can generate useful OpenMP code for these two runtime libraries.
7063 CmdArgs.push_back("-fopenmp");
7064
7065 // If no option regarding the use of TLS in OpenMP codegeneration is
7066 // given, decide a default based on the target. Otherwise rely on the
7067 // options and pass the right information to the frontend.
7068 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7069 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7070 CmdArgs.push_back("-fnoopenmp-use-tls");
7071 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7072 options::OPT_fno_openmp_simd);
7073 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7074 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7075 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7076 options::OPT_fno_openmp_extensions, /*Default=*/true))
7077 CmdArgs.push_back("-fno-openmp-extensions");
7078 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7079 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7080 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7081 // effect: the teams reduction buffer is sized at kernel launch by the
7082 // offload plugin to match the actual number of teams. Honoring a
7083 // smaller user-supplied value would silently truncate the buffer for
7084 // larger launches.
7085 if (Arg *A = Args.getLastArg(
7086 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7087 D.Diag(diag::warn_drv_deprecated_custom)
7088 << A->getAsString(Args)
7089 << "the value is ignored; the teams reduction buffer is sized "
7090 "automatically at kernel launch";
7091 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7092 options::OPT_fno_openmp_optimistic_collapse,
7093 /*Default=*/false))
7094 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7095
7096 // When in OpenMP offloading mode with NVPTX target, forward
7097 // cuda-mode flag
7098 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7099 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7100 CmdArgs.push_back("-fopenmp-cuda-mode");
7101
7102 // When in OpenMP offloading mode, enable debugging on the device.
7103 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7104 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7105 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7106 CmdArgs.push_back("-fopenmp-target-debug");
7107
7108 // When in OpenMP offloading mode, forward assumptions information about
7109 // thread and team counts in the device.
7110 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7111 options::OPT_fno_openmp_assume_teams_oversubscription,
7112 /*Default=*/TargetFastUsed))
7113 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7114 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7115 options::OPT_fno_openmp_assume_threads_oversubscription,
7116 /*Default=*/TargetFastUsed))
7117 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7118
7119 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7120 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7121 options::OPT_fno_openmp_assume_no_thread_state,
7122 /*Default=*/TargetFastUsed))
7123 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7124
7125 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7126 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7127 options::OPT_fno_openmp_assume_no_nested_parallelism,
7128 /*Default=*/TargetFastUsed))
7129 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7130
7131 // Handle -fopenmp-target-atomic-reduction.
7132 if (Args.hasFlag(options::OPT_fopenmp_target_atomic_reduction,
7133 options::OPT_fno_openmp_target_atomic_reduction,
7134 /*Default=*/false))
7135 CmdArgs.push_back("-fopenmp-target-atomic-reduction");
7136
7137 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7138 CmdArgs.push_back("-fopenmp-offload-mandatory");
7139 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7140 CmdArgs.push_back("-fopenmp-force-usm");
7141 break;
7142 default:
7143 // By default, if Clang doesn't know how to generate useful OpenMP code
7144 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7145 // down to the actual compilation.
7146 // FIXME: It would be better to have a mode which *only* omits IR
7147 // generation based on the OpenMP support so that we get consistent
7148 // semantic analysis, etc.
7149 break;
7150 }
7151 } else {
7152 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7153 options::OPT_fno_openmp_simd);
7154 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7155 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7156 options::OPT_fno_openmp_extensions);
7157 }
7158 // Forward the offload runtime change to code generation, liboffload implies
7159 // new driver. Otherwise, check if we should forward the new driver to change
7160 // offloading code generation.
7161 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7162 options::OPT_fno_offload_via_llvm, false)) {
7163 CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});
7164 } else if (Args.hasFlag(options::OPT_offload_new_driver,
7165 options::OPT_no_offload_new_driver,
7166 C.getActiveOffloadKinds() != Action::OFK_None)) {
7167 CmdArgs.push_back("--offload-new-driver");
7168 }
7169
7170 const XRayArgs &XRay = TC.getXRayArgs(Args);
7171 XRay.addArgs(TC, Args, CmdArgs, InputType);
7172
7173 for (const auto &Filename :
7174 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7175 if (D.getVFS().exists(Filename))
7176 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7177 else
7178 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7179 }
7180
7181 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7182 StringRef S0 = A->getValue(), S = S0;
7183 unsigned Size, Offset = 0;
7184 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7185 !Triple.isX86() && !Triple.isSystemZ() &&
7186 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7187 Triple.getArch() == llvm::Triple::ppc64 ||
7188 Triple.getArch() == llvm::Triple::ppc64le)))
7189 D.Diag(diag::err_drv_unsupported_opt_for_target)
7190 << A->getAsString(Args) << TripleStr;
7191 else if (S.consumeInteger(10, Size) ||
7192 (!S.empty() &&
7193 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7194 (!S.empty() && (!S.consume_front(",") || S.empty())))
7195 D.Diag(diag::err_drv_invalid_argument_to_option)
7196 << S0 << A->getOption().getName();
7197 else if (Size < Offset)
7198 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7199 else {
7200 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7201 CmdArgs.push_back(Args.MakeArgString(
7202 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7203 if (!S.empty())
7204 CmdArgs.push_back(
7205 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7206 }
7207 }
7208
7209 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7210
7211 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7212 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7213
7214 for (const auto &A :
7215 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7216 CmdArgs.push_back(
7217 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7218
7219 if (TC.SupportsProfiling()) {
7220 Args.AddLastArg(CmdArgs, options::OPT_pg);
7221
7222 llvm::Triple::ArchType Arch = TC.getArch();
7223 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7224 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7225 A->render(Args, CmdArgs);
7226 else
7227 D.Diag(diag::err_drv_unsupported_opt_for_target)
7228 << A->getAsString(Args) << TripleStr;
7229 }
7230 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7231 if (Arch == llvm::Triple::systemz)
7232 A->render(Args, CmdArgs);
7233 else
7234 D.Diag(diag::err_drv_unsupported_opt_for_target)
7235 << A->getAsString(Args) << TripleStr;
7236 }
7237 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7238 if (Arch == llvm::Triple::systemz)
7239 A->render(Args, CmdArgs);
7240 else
7241 D.Diag(diag::err_drv_unsupported_opt_for_target)
7242 << A->getAsString(Args) << TripleStr;
7243 }
7244 }
7245
7246 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7247 if (TC.getTriple().isOSzOS()) {
7248 D.Diag(diag::err_drv_unsupported_opt_for_target)
7249 << A->getAsString(Args) << TripleStr;
7250 }
7251 }
7252 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7253 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7254 D.Diag(diag::err_drv_unsupported_opt_for_target)
7255 << A->getAsString(Args) << TripleStr;
7256 }
7257 }
7258 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7259 if (A->getOption().matches(options::OPT_p)) {
7260 A->claim();
7261 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7262 CmdArgs.push_back("-pg");
7263 }
7264 }
7265
7266 // Reject AIX-specific link options on other targets.
7267 if (!TC.getTriple().isOSAIX()) {
7268 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7269 options::OPT_mxcoff_build_id_EQ)) {
7270 D.Diag(diag::err_drv_unsupported_opt_for_target)
7271 << A->getSpelling() << TripleStr;
7272 }
7273 }
7274
7275 if (Args.getLastArg(options::OPT_fapple_kext) ||
7276 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7277 CmdArgs.push_back("-fapple-kext");
7278
7279 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7280 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7281 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7282 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7283 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7284 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7285 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7286 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7287 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7288 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7289 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7290
7291 if (const char *Name = C.getTimeTraceFile(&JA)) {
7292 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7293 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7294 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7295 }
7296
7297 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7298 CmdArgs.push_back("-ftrapv-handler");
7299 CmdArgs.push_back(A->getValue());
7300 }
7301
7302 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7303
7304 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7305 options::OPT_fno_finite_loops);
7306
7307 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7308 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7309 options::OPT_fno_unroll_loops);
7310 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7311 options::OPT_fno_loop_interchange);
7312 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7313 options::OPT_fno_experimental_loop_fusion);
7314
7315 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7316
7317 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7318
7319 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7320 options::OPT_mno_speculative_load_hardening);
7321
7322 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7323 RenderSCPOptions(TC, Args, CmdArgs);
7324 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7325
7326 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7327
7328 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7329 options::OPT_mno_stackrealign);
7330
7331 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7332 StringRef Value = A->getValue();
7333 int64_t Alignment = 0;
7334 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7335 D.Diag(diag::err_drv_invalid_argument_to_option)
7336 << Value << A->getOption().getName();
7337 else if (Alignment & (Alignment - 1))
7338 D.Diag(diag::err_drv_alignment_not_power_of_two)
7339 << A->getAsString(Args) << Value;
7340 else
7341 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7342 }
7343
7344 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7345 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7346
7347 if (!Size.empty())
7348 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7349 else
7350 CmdArgs.push_back("-mstack-probe-size=0");
7351 }
7352
7353 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7354 options::OPT_mno_stack_arg_probe);
7355
7356 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7357 options::OPT_mno_restrict_it)) {
7358 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7359 CmdArgs.push_back("-mllvm");
7360 CmdArgs.push_back("-arm-restrict-it");
7361 } else {
7362 CmdArgs.push_back("-mllvm");
7363 CmdArgs.push_back("-arm-default-it");
7364 }
7365 }
7366
7367 // Forward -cl options to -cc1
7368 RenderOpenCLOptions(Args, CmdArgs, InputType);
7369
7370 // Forward hlsl options to -cc1
7371 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7372
7373 // Forward OpenACC options to -cc1
7374 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7375
7376 if (IsHIP) {
7377 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7378 options::OPT_fno_hip_new_launch_api, true))
7379 CmdArgs.push_back("-fhip-new-launch-api");
7380 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7381 options::OPT_fno_gpu_allow_device_init);
7382 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7383 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7384 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7385 options::OPT_fno_hip_kernel_arg_name);
7386 }
7387
7388 if (IsCuda || IsHIP) {
7389 if (IsRDCMode)
7390 CmdArgs.push_back("-fgpu-rdc");
7391 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7392 options::OPT_fno_gpu_defer_diag);
7393 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7394 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7395 false)) {
7396 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7397 CmdArgs.push_back("-fgpu-defer-diag");
7398 }
7399 }
7400
7401 // Forward --no-offloadlib to -cc1.
7402 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7403 CmdArgs.push_back("--no-offloadlib");
7404
7405 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7406 CmdArgs.push_back(
7407 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7408
7409 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7410 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7411 SA->getValue()));
7412 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7413 // Emit IBT endbr64 instructions by default
7414 CmdArgs.push_back("-fcf-protection=branch");
7415 // jump-table can generate indirect jumps, which are not permitted
7416 CmdArgs.push_back("-fno-jump-tables");
7417 }
7418
7419 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7420 CmdArgs.push_back(
7421 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7422
7423 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7424
7425 // Forward -f options with positive and negative forms; we translate these by
7426 // hand. Do not propagate PGO options to the GPU-side compilations as the
7427 // profile info is for the host-side compilation only.
7428 if (!(IsCudaDevice || IsHIPDevice)) {
7429 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7430 auto *PGOArg = Args.getLastArg(
7431 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7432 options::OPT_fcs_profile_generate,
7433 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7434 options::OPT_fprofile_use_EQ);
7435 if (PGOArg)
7436 D.Diag(diag::err_drv_argument_not_allowed_with)
7437 << "SampleUse with PGO options";
7438
7439 StringRef fname = A->getValue();
7440 if (!llvm::sys::fs::exists(fname))
7441 D.Diag(diag::err_drv_no_such_file) << fname;
7442 else
7443 A->render(Args, CmdArgs);
7444 }
7445 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7446
7447 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7448 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7449 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7450 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7451 // off.
7452 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7453 options::OPT_fno_unique_internal_linkage_names, true))
7454 CmdArgs.push_back("-funique-internal-linkage-names");
7455 }
7456 }
7457 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7458
7459 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7460 options::OPT_fno_assume_sane_operator_new);
7461
7462 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7463 CmdArgs.push_back("-fapinotes");
7464 if (Args.hasFlag(options::OPT_fapinotes_modules,
7465 options::OPT_fno_apinotes_modules, false))
7466 CmdArgs.push_back("-fapinotes-modules");
7467 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7468
7469 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7470 options::OPT_fno_swift_version_independent_apinotes, false))
7471 CmdArgs.push_back("-fswift-version-independent-apinotes");
7472
7473 // -fblocks=0 is default.
7474 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7475 TC.IsBlocksDefault()) ||
7476 (Args.hasArg(options::OPT_fgnu_runtime) &&
7477 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7478 !Args.hasArg(options::OPT_fno_blocks))) {
7479 CmdArgs.push_back("-fblocks");
7480
7481 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7482 CmdArgs.push_back("-fblocks-runtime-optional");
7483 }
7484
7485 // -fencode-extended-block-signature=1 is default.
7487 CmdArgs.push_back("-fencode-extended-block-signature");
7488
7489 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7490 options::OPT_fno_coro_aligned_allocation, false) &&
7491 types::isCXX(InputType))
7492 CmdArgs.push_back("-fcoro-aligned-allocation");
7493
7494 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7495 /*Default=*/false))
7496 CmdArgs.push_back("-fdefer-ts");
7497
7498 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7499 options::OPT_fno_double_square_bracket_attributes);
7500
7501 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7502 options::OPT_fno_access_control);
7503 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7504 options::OPT_fno_elide_constructors);
7505
7506 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7507
7508 if (KernelOrKext || (types::isCXX(InputType) &&
7509 (RTTIMode == ToolChain::RM_Disabled)))
7510 CmdArgs.push_back("-fno-rtti");
7511
7512 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7513 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7514 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7515 CmdArgs.push_back("-fshort-enums");
7516
7517 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7518
7519 // -fuse-cxa-atexit is default.
7520 if (!Args.hasFlag(
7521 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7522 !RawTriple.isOSAIX() &&
7523 (!RawTriple.isOSWindows() ||
7524 RawTriple.isWindowsCygwinEnvironment()) &&
7525 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7526 RawTriple.hasEnvironment())) ||
7527 KernelOrKext)
7528 CmdArgs.push_back("-fno-use-cxa-atexit");
7529
7530 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7531 options::OPT_fno_register_global_dtors_with_atexit,
7532 RawTriple.isOSDarwin() && !KernelOrKext))
7533 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7534
7535 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7536 options::OPT_fno_use_line_directives);
7537
7538 // -fno-minimize-whitespace is default.
7539 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7540 options::OPT_fno_minimize_whitespace, false)) {
7541 types::ID InputType = Inputs[0].getType();
7542 if (!isDerivedFromC(InputType))
7543 D.Diag(diag::err_drv_opt_unsupported_input_type)
7544 << "-fminimize-whitespace" << types::getTypeName(InputType);
7545 CmdArgs.push_back("-fminimize-whitespace");
7546 }
7547
7548 // -fno-keep-system-includes is default.
7549 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7550 options::OPT_fno_keep_system_includes, false)) {
7551 types::ID InputType = Inputs[0].getType();
7552 if (!isDerivedFromC(InputType))
7553 D.Diag(diag::err_drv_opt_unsupported_input_type)
7554 << "-fkeep-system-includes" << types::getTypeName(InputType);
7555 CmdArgs.push_back("-fkeep-system-includes");
7556 }
7557
7558 // -fms-extensions=0 is default.
7559 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7560 IsWindowsMSVC || IsUEFI))
7561 CmdArgs.push_back("-fms-extensions");
7562
7563 // -fms-compatibility=0 is default.
7564 bool IsMSVCCompat = Args.hasFlag(
7565 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7566 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7567 options::OPT_fno_ms_extensions, true)));
7568 if (IsMSVCCompat) {
7569 CmdArgs.push_back("-fms-compatibility");
7570 if (!types::isCXX(Input.getType()) &&
7571 Args.hasArg(options::OPT_fms_define_stdc))
7572 CmdArgs.push_back("-fms-define-stdc");
7573 }
7574
7575 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7576 // clang and flang.
7577 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7578
7579 // -fms-anonymous-structs is disabled by default.
7580 // Determine whether to enable Microsoft named anonymous struct/union support.
7581 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7582 // where the feature can be:
7583 // - Explicitly enabled via -fms-anonymous-structs.
7584 // - Explicitly disabled via fno-ms-anonymous-structs
7585 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7586 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7587 //
7588 // When multiple relevent options are present, the last option on the command
7589 // line takes precedence. This allows users to selectively override implicit
7590 // enablement. Examples:
7591 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7592 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7593 auto MSAnonymousStructsOptionToUseOrNull =
7594 [](const ArgList &Args) -> const char * {
7595 const char *Option = nullptr;
7596 constexpr const char *Enable = "-fms-anonymous-structs";
7597 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7598
7599 // Iterate through all arguments in order to implement "last flag wins".
7600 for (const Arg *A : Args) {
7601 switch (A->getOption().getID()) {
7602 case options::OPT_fms_anonymous_structs:
7603 A->claim();
7604 Option = Enable;
7605 break;
7606 case options::OPT_fno_ms_anonymous_structs:
7607 A->claim();
7608 Option = Disable;
7609 break;
7610 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7611 // feature.
7612 case options::OPT_fms_extensions:
7613 case options::OPT_fms_compatibility:
7614 Option = Enable;
7615 break;
7616 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7617 // disables the feature.
7618 case options::OPT_fno_ms_extensions:
7619 case options::OPT_fno_ms_compatibility:
7620 Option = Disable;
7621 break;
7622 default:
7623 break;
7624 }
7625 }
7626 return Option;
7627 };
7628
7629 // Only pass a flag to CC1 if a relevant option was seen
7630 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7631 CmdArgs.push_back(MSAnonOpt);
7632
7633 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7634 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7635 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7636
7637 // Handle -fgcc-version, if present.
7638 VersionTuple GNUCVer;
7639 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7640 // Check that the version has 1 to 3 components and the minor and patch
7641 // versions fit in two decimal digits.
7642 StringRef Val = A->getValue();
7643 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7644 bool Invalid = GNUCVer.tryParse(Val);
7645 unsigned Minor = GNUCVer.getMinor().value_or(0);
7646 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7647 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7648 D.Diag(diag::err_drv_invalid_value)
7649 << A->getAsString(Args) << A->getValue();
7650 }
7651 } else if (!IsMSVCCompat) {
7652 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7653 GNUCVer = VersionTuple(4, 2, 1);
7654 }
7655 if (!GNUCVer.empty()) {
7656 CmdArgs.push_back(
7657 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7658 }
7659
7660 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7661 if (!MSVT.empty())
7662 CmdArgs.push_back(
7663 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7664
7665 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7666 if (ImplyVCPPCVer) {
7667 StringRef LanguageStandard;
7668 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7669 Std = StdArg;
7670 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7671 .Case("c11", "-std=c11")
7672 .Case("c17", "-std=c17")
7673 // If you add cases below for spellings that are
7674 // not in LangStandards.def, update
7675 // TransferableCommand::tryParseStdArg() in
7676 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7677 // to match.
7678 // TODO: add c23 when MSVC supports it.
7679 .Case("clatest", "-std=c23")
7680 .Default("");
7681 if (LanguageStandard.empty())
7682 D.Diag(clang::diag::warn_drv_unused_argument)
7683 << StdArg->getAsString(Args);
7684 }
7685 CmdArgs.push_back(LanguageStandard.data());
7686 }
7687 if (ImplyVCPPCXXVer) {
7688 StringRef LanguageStandard;
7689 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7690 Std = StdArg;
7691 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7692 .Case("c++14", "-std=c++14")
7693 .Case("c++17", "-std=c++17")
7694 .Case("c++20", "-std=c++20")
7695 // If you add cases below for spellings that are
7696 // not in LangStandards.def, update
7697 // TransferableCommand::tryParseStdArg() in
7698 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7699 // to match.
7700 // TODO add c++23, c++26, c++29 when MSVC supports
7701 // it.
7702 .Case("c++23preview", "-std=c++23")
7703 .Case("c++26preview", "-std=c++26")
7704 .Case("c++latest", "-std=c++2d")
7705 .Default("");
7706 if (IsSYCL) {
7707 const LangStandard *LangStd =
7708 LangStandard::getLangStandardForName(StdArg->getValue());
7709 if (LangStd) {
7710 // Use of /std: with 'C' is not supported for SYCL.
7711 if (LangStd->getLanguage() == Language::C)
7712 D.Diag(diag::err_drv_argument_not_allowed_with)
7713 << StdArg->getAsString(Args) << "-fsycl";
7714 // SYCL requires C++17 or later.
7715 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7716 D.Diag(diag::err_drv_sycl_requires_cxx17)
7717 << StdArg->getAsString(Args);
7718 }
7719 }
7720 if (LanguageStandard.empty())
7721 D.Diag(clang::diag::warn_drv_unused_argument)
7722 << StdArg->getAsString(Args);
7723 }
7724
7725 if (LanguageStandard.empty()) {
7726 if (IsSYCL)
7727 // For SYCL, C++17 is the default.
7728 LanguageStandard = "-std=c++17";
7729 else if (IsMSVC2015Compatible)
7730 LanguageStandard = "-std=c++14";
7731 else
7732 LanguageStandard = "-std=c++11";
7733 }
7734
7735 CmdArgs.push_back(LanguageStandard.data());
7736 }
7737
7738 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7739 options::OPT_fno_borland_extensions);
7740
7741 // -fno-declspec is default, except for PS4/PS5.
7742 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7743 RawTriple.isPS()))
7744 CmdArgs.push_back("-fdeclspec");
7745 else if (Args.hasArg(options::OPT_fno_declspec))
7746 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7747
7748 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7749 // than 19.
7750 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7751 options::OPT_fno_threadsafe_statics,
7752 !types::isOpenCL(InputType) &&
7753 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7754 CmdArgs.push_back("-fno-threadsafe-statics");
7755
7756 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7757 true))
7758 CmdArgs.push_back("-fno-ms-tls-guards");
7759
7760 // Add -fno-assumptions, if it was specified.
7761 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7762 true))
7763 CmdArgs.push_back("-fno-assumptions");
7764
7765 // -fgnu-keywords default varies depending on language; only pass if
7766 // specified.
7767 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7768 options::OPT_fno_gnu_keywords);
7769
7770 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7771 options::OPT_fno_gnu89_inline);
7772
7773 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7774 options::OPT_finline_hint_functions,
7775 options::OPT_fno_inline_functions);
7776 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7777 if (A->getOption().matches(options::OPT_fno_inline))
7778 A->render(Args, CmdArgs);
7779 } else if (InlineArg) {
7780 InlineArg->render(Args, CmdArgs);
7781 }
7782
7783 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7784
7785 // FIXME: Find a better way to determine whether we are in C++20.
7786 bool HaveCxx20 =
7787 Std &&
7788 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7789 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7790 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7791 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7792 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7793 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7794 Std->containsValue("gnu++26") || Std->containsValue("c++26preview") ||
7795 Std->containsValue("c++2d") || Std->containsValue("gnu++2d") ||
7796 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7797 bool HaveModules =
7798 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7799
7800 // -fdelayed-template-parsing is default when targeting MSVC.
7801 // Many old Windows SDK versions require this to parse.
7802 //
7803 // According to
7804 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7805 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7806 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7807 // not enable -fdelayed-template-parsing by default after C++20.
7808 //
7809 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7810 // able to disable this by default at some point.
7811 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7812 options::OPT_fno_delayed_template_parsing,
7813 IsWindowsMSVC && !HaveCxx20)) {
7814 if (HaveCxx20)
7815 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7816
7817 CmdArgs.push_back("-fdelayed-template-parsing");
7818 }
7819
7820 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7821 options::OPT_fno_pch_validate_input_files_content, false))
7822 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7823 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7824 options::OPT_fno_pch_instantiate_templates, false))
7825 CmdArgs.push_back("-fpch-instantiate-templates");
7826 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7827 false))
7828 CmdArgs.push_back("-fmodules-codegen");
7829 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7830 false))
7831 CmdArgs.push_back("-fmodules-debuginfo");
7832
7833 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7834 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7835 Input, CmdArgs);
7836
7837 if (types::isObjC(Input.getType()) &&
7838 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7839 options::OPT_fno_objc_encode_cxx_class_template_spec,
7840 !Runtime.isNeXTFamily()))
7841 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7842
7843 if (Args.hasFlag(options::OPT_fapplication_extension,
7844 options::OPT_fno_application_extension, false))
7845 CmdArgs.push_back("-fapplication-extension");
7846
7847 // Handle GCC-style exception args.
7848 bool EH = false;
7849 if (!C.getDriver().IsCLMode())
7850 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7851 IsDeviceOffloadAction, Runtime, CmdArgs);
7852
7853 // Handle exception personalities
7854 Arg *A = Args.getLastArg(
7855 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7856 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7857 if (A) {
7858 const Option &Opt = A->getOption();
7859 if (Opt.matches(options::OPT_fsjlj_exceptions))
7860 CmdArgs.push_back("-exception-model=sjlj");
7861 if (Opt.matches(options::OPT_fseh_exceptions))
7862 CmdArgs.push_back("-exception-model=seh");
7863 if (Opt.matches(options::OPT_fdwarf_exceptions))
7864 CmdArgs.push_back("-exception-model=dwarf");
7865 if (Opt.matches(options::OPT_fwasm_exceptions))
7866 CmdArgs.push_back("-exception-model=wasm");
7867 } else {
7868 switch (TC.GetExceptionModel(Args)) {
7869 default:
7870 break;
7871 case llvm::ExceptionHandling::DwarfCFI:
7872 CmdArgs.push_back("-exception-model=dwarf");
7873 break;
7874 case llvm::ExceptionHandling::SjLj:
7875 CmdArgs.push_back("-exception-model=sjlj");
7876 break;
7877 case llvm::ExceptionHandling::WinEH:
7878 CmdArgs.push_back("-exception-model=seh");
7879 break;
7880 }
7881 }
7882
7883 // Unwind information version for x64 Windows.
7884 // Forward the new unified flag if present, otherwise translate legacy flags.
7885 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
7886 A->claim();
7887 CmdArgs.push_back(
7888 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
7889 } else if (const Arg *A =
7890 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
7891 A->claim();
7892 StringRef Val = A->getValue();
7893 if (Val == "best-effort")
7894 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
7895 else if (Val == "required")
7896 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
7897 // "disabled" maps to v1 default, nothing to forward.
7898 else if (Val != "disabled")
7899 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
7900 }
7901
7902 // Control Flow Guard mechanism for Windows.
7903 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
7904
7905 // C++ "sane" operator new.
7906 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7907 options::OPT_fno_assume_sane_operator_new);
7908
7909 // -fassume-unique-vtables is on by default.
7910 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7911 options::OPT_fno_assume_unique_vtables);
7912
7913 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7914 // by default.
7915 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7916 options::OPT_fno_sized_deallocation);
7917
7918 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7919 // by default.
7920 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7921 options::OPT_fno_aligned_allocation,
7922 options::OPT_faligned_new_EQ)) {
7923 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7924 CmdArgs.push_back("-fno-aligned-allocation");
7925 else
7926 CmdArgs.push_back("-faligned-allocation");
7927 }
7928
7929 // The default new alignment can be specified using a dedicated option or via
7930 // a GCC-compatible option that also turns on aligned allocation.
7931 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7932 options::OPT_faligned_new_EQ))
7933 CmdArgs.push_back(
7934 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7935
7936 // -fconstant-cfstrings is default, and may be subject to argument translation
7937 // on Darwin.
7938 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7939 options::OPT_fno_constant_cfstrings, true) ||
7940 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7941 options::OPT_mno_constant_cfstrings, true))
7942 CmdArgs.push_back("-fno-constant-cfstrings");
7943
7944 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7945 options::OPT_fno_pascal_strings);
7946
7947 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7948 // -fno-pack-struct doesn't apply to -fpack-struct=.
7949 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7950 CmdArgs.push_back(
7951 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
7952 } else if (Args.hasFlag(options::OPT_fpack_struct,
7953 options::OPT_fno_pack_struct, false)) {
7954 CmdArgs.push_back("-fpack-struct=1");
7955 }
7956
7957 // Handle -fmax-type-align=N and -fno-type-align
7958 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7959 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7960 if (!SkipMaxTypeAlign) {
7961 std::string MaxTypeAlignStr = "-fmax-type-align=";
7962 MaxTypeAlignStr += A->getValue();
7963 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7964 }
7965 } else if (RawTriple.isOSDarwin()) {
7966 if (!SkipMaxTypeAlign) {
7967 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7968 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7969 }
7970 }
7971
7972 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7973 CmdArgs.push_back("-Qn");
7974
7975 // -fno-common is the default, set -fcommon only when that flag is set.
7976 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7977
7978 // -fsigned-bitfields is default, and clang doesn't yet support
7979 // -funsigned-bitfields.
7980 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7981 options::OPT_funsigned_bitfields, true))
7982 D.Diag(diag::warn_drv_clang_unsupported)
7983 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7984
7985 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7986 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7987 D.Diag(diag::err_drv_clang_unsupported)
7988 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7989
7990 // -finput_charset=UTF-8 is default. Reject others
7991 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7992 StringRef value = inputCharset->getValue();
7993 if (!value.equals_insensitive("utf-8"))
7994 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7995 << value;
7996 }
7997
7998 // -fexec_charset=UTF-8 is default. Reject others
7999 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
8000 StringRef value = execCharset->getValue();
8001 if (!value.equals_insensitive("utf-8"))
8002 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8003 << value;
8004 }
8005
8006 RenderDiagnosticsOptions(D, Args, CmdArgs);
8007
8008 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
8009 options::OPT_fno_asm_blocks);
8010
8011 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
8012 options::OPT_fno_gnu_inline_asm);
8013
8014 handleVectorizeLoopsArgs(Args, CmdArgs);
8015 handleVectorizeSLPArgs(Args, CmdArgs);
8016
8017 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8018 if (!VecWidth.empty())
8019 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8020
8021 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8022 Args.AddLastArg(CmdArgs,
8023 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8024
8025 // -fdollars-in-identifiers default varies depending on platform and
8026 // language; only pass if specified.
8027 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8028 options::OPT_fno_dollars_in_identifiers)) {
8029 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8030 CmdArgs.push_back("-fdollars-in-identifiers");
8031 else
8032 CmdArgs.push_back("-fno-dollars-in-identifiers");
8033 }
8034
8035 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8036 options::OPT_fno_apple_pragma_pack);
8037
8038 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8039 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8040 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8041
8042 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8043 options::OPT_fno_rewrite_imports, false);
8044 if (RewriteImports)
8045 CmdArgs.push_back("-frewrite-imports");
8046
8047 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8048 options::OPT_fno_directives_only);
8049
8050 // Enable rewrite includes if the user's asked for it or if we're generating
8051 // diagnostics.
8052 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8053 // nice to enable this when doing a crashdump for modules as well.
8054 if (Args.hasFlag(options::OPT_frewrite_includes,
8055 options::OPT_fno_rewrite_includes, false) ||
8056 (C.isForDiagnostics() && !HaveModules))
8057 CmdArgs.push_back("-frewrite-includes");
8058
8059 if (Args.hasFlag(options::OPT_fzos_extensions,
8060 options::OPT_fno_zos_extensions, false))
8061 CmdArgs.push_back("-fzos-extensions");
8062 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8063 CmdArgs.push_back("-fno-zos-extensions");
8064
8065 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8066 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8067 options::OPT_traditional_cpp)) {
8069 CmdArgs.push_back("-traditional-cpp");
8070 else
8071 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8072 }
8073
8074 Args.AddLastArg(CmdArgs, options::OPT_dM);
8075 Args.AddLastArg(CmdArgs, options::OPT_dD);
8076 Args.AddLastArg(CmdArgs, options::OPT_dI);
8077
8078 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8079
8080 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8081 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8082 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8083 Args.AddLastArg(CmdArgs, options::OPT__ssaf_include_local_entities);
8084 Args.AddLastArg(CmdArgs, options::OPT__ssaf_no_extract_from_system_headers);
8085 Args.AddLastArg(CmdArgs, options::OPT__ssaf_source_transformation);
8086 Args.AddLastArg(CmdArgs, options::OPT__ssaf_global_scope_analysis_result);
8087 Args.AddLastArg(CmdArgs, options::OPT__ssaf_src_edit_file);
8088 Args.AddLastArg(CmdArgs, options::OPT__ssaf_transformation_report_file);
8089
8090 // Handle serialized diagnostics.
8091 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8092 CmdArgs.push_back("-serialize-diagnostic-file");
8093 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8094 }
8095
8096 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8097 CmdArgs.push_back("-fretain-comments-from-system-headers");
8098
8099 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8100 A->render(Args, CmdArgs);
8101 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8102 A && A->containsValue("g")) {
8103 // Set -fextend-variable-liveness=all by default at -Og.
8104 CmdArgs.push_back("-fextend-variable-liveness=all");
8105 }
8106
8107 // Forward -fcomment-block-commands to -cc1.
8108 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8109 // Forward -fparse-all-comments to -cc1.
8110 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8111
8112 // Turn -fplugin=name.so into -load name.so
8113 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8114 CmdArgs.push_back("-load");
8115 CmdArgs.push_back(A->getValue());
8116 A->claim();
8117 }
8118
8119 // Turn -fplugin-arg-pluginname-key=value into
8120 // -plugin-arg-pluginname key=value
8121 // GCC has an actual plugin_argument struct with key/value pairs that it
8122 // passes to its plugins, but we don't, so just pass it on as-is.
8123 //
8124 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8125 // argument key are allowed to contain dashes. GCC therefore only
8126 // allows dashes in the key. We do the same.
8127 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8128 auto ArgValue = StringRef(A->getValue());
8129 auto FirstDashIndex = ArgValue.find('-');
8130 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8131 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8132
8133 A->claim();
8134 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8135 if (PluginName.empty()) {
8136 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8137 } else {
8138 D.Diag(diag::warn_drv_missing_plugin_arg)
8139 << PluginName << A->getAsString(Args);
8140 }
8141 continue;
8142 }
8143
8144 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8145 CmdArgs.push_back(Args.MakeArgString(Arg));
8146 }
8147
8148 // Forward -fpass-plugin=name.so to -cc1.
8149 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8150 CmdArgs.push_back(
8151 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8152 A->claim();
8153 }
8154
8155 // Forward --vfsoverlay to -cc1.
8156 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8157 CmdArgs.push_back("--vfsoverlay");
8158 CmdArgs.push_back(A->getValue());
8159 A->claim();
8160 }
8161
8162 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8163 options::OPT_fno_safe_buffer_usage_suggestions);
8164
8165 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8166 options::OPT_fno_experimental_late_parse_attributes);
8167
8168 if (Args.hasFlag(options::OPT_funique_source_file_names,
8169 options::OPT_fno_unique_source_file_names, false)) {
8170 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8171 A->render(Args, CmdArgs);
8172 else
8173 CmdArgs.push_back(Args.MakeArgString(
8174 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8175 }
8176
8177 if (Args.hasFlag(
8178 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8179 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8180 false) ||
8181 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8182 options::OPT_fno_experimental_pointer_field_protection_abi,
8183 false))
8184 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8185
8186 if (!IsCudaDevice) {
8187 Args.addOptInFlag(
8188 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8189 options::OPT_fno_experimental_pointer_field_protection_abi);
8190 Args.addOptInFlag(
8191 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8192 options::OPT_fno_experimental_pointer_field_protection_tagged);
8193 }
8194
8195 // Setup statistics file output.
8196 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8197 if (!StatsFile.empty()) {
8198 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8200 CmdArgs.push_back("-stats-file-append");
8201 }
8202
8203 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8204 // parser.
8205 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8206 Arg->claim();
8207 // -finclude-default-header flag is for preprocessor,
8208 // do not pass it to other cc1 commands when save-temps is enabled
8209 if (C.getDriver().isSaveTempsEnabled() &&
8211 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8212 continue;
8213 }
8214 CmdArgs.push_back(Arg->getValue());
8215 }
8216 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8217 A->claim();
8218
8219 // We translate this by hand to the -cc1 argument, since nightly test uses
8220 // it and developers have been trained to spell it with -mllvm. Both
8221 // spellings are now deprecated and should be removed.
8222 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8223 CmdArgs.push_back("-disable-llvm-optzns");
8224 } else {
8225 A->render(Args, CmdArgs);
8226 }
8227 }
8228
8229 // This needs to run after -Xclang argument forwarding to pick up the target
8230 // features enabled through -Xclang -target-feature flags.
8231 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8232
8233 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8234
8235#if CLANG_ENABLE_CIR
8236 // Forward -mmlir arguments to to the MLIR option parser.
8237 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8238 A->claim();
8239 A->render(Args, CmdArgs);
8240 }
8241#endif // CLANG_ENABLE_CIR
8242
8243 // With -save-temps, we want to save the unoptimized bitcode output from the
8244 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8245 // by the frontend.
8246 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8247 // has slightly different breakdown between stages.
8248 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8249 // pristine IR generated by the frontend. Ideally, a new compile action should
8250 // be added so both IR can be captured.
8251 if ((C.getDriver().isSaveTempsEnabled() ||
8253 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8255 CmdArgs.push_back("-disable-llvm-passes");
8256
8257 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8258
8259 const char *Exec = D.getDriverProgramPath();
8260
8261 // Optionally embed the -cc1 level arguments into the debug info or a
8262 // section, for build analysis.
8263 // Also record command line arguments into the debug info if
8264 // -grecord-gcc-switches options is set on.
8265 // By default, -gno-record-gcc-switches is set on and no recording.
8266 auto GRecordSwitches = false;
8267 auto FRecordSwitches = false;
8268 bool DXRecordSwitches = false;
8269 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8270 DXRecordSwitches)) {
8271 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8272 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8273 CmdArgs.push_back("-dwarf-debug-flags");
8274 CmdArgs.push_back(FlagsArgString);
8275 }
8276 if (FRecordSwitches) {
8277 CmdArgs.push_back("-record-command-line");
8278 CmdArgs.push_back(FlagsArgString);
8279 }
8280 if (DXRecordSwitches) {
8281 CmdArgs.push_back("-fdx-record-command-line");
8282 CmdArgs.push_back(FlagsArgString);
8283 }
8284 }
8285
8286 // Host-side offloading compilation receives all device-side outputs. Include
8287 // them in the host compilation depending on the target. If the host inputs
8288 // are not empty we use the new-driver scheme, otherwise use the old scheme.
8289 if ((IsCuda || IsHIP) && CudaDeviceInput) {
8290 CmdArgs.push_back("-fcuda-include-gpubinary");
8291 CmdArgs.push_back(CudaDeviceInput->getFilename());
8292 } else if (!HostOffloadingInputs.empty()) {
8293 if ((IsCuda || IsHIP) &&
8294 (!IsRDCMode || Args.hasArg(options::OPT_cuda_emit_nvcc_abi))) {
8295 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8296 CmdArgs.push_back("-fcuda-include-gpubinary");
8297 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8298 } else {
8299 for (const InputInfo Input : HostOffloadingInputs)
8300 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8301 TC.getInputFilename(Input)));
8302 }
8303 }
8304
8305 if (IsCuda) {
8306 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
8307 options::OPT_fno_cuda_short_ptr, false))
8308 CmdArgs.push_back("-fcuda-short-ptr");
8309 if (Args.hasArg(options::OPT_cuda_emit_nvcc_abi))
8310 CmdArgs.push_back("--cuda-emit-nvcc-abi");
8311 }
8312
8313 if (IsCuda || IsHIP) {
8314 // Determine the original source input.
8315 const Action *SourceAction = &JA;
8316 while (SourceAction->getKind() != Action::InputClass) {
8317 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8318 SourceAction = SourceAction->getInputs()[0];
8319 }
8320 auto CUID = cast<InputAction>(SourceAction)->getId();
8321 if (!CUID.empty())
8322 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8323
8324 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8325 // be overriden by -fno-gpu-approx-transcendentals.
8326 bool UseApproxTranscendentals = Args.hasFlag(
8327 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8328 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8329 options::OPT_fno_gpu_approx_transcendentals,
8330 UseApproxTranscendentals))
8331 CmdArgs.push_back("-fgpu-approx-transcendentals");
8332 } else {
8333 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8334 options::OPT_fno_gpu_approx_transcendentals);
8335 }
8336
8337 if (IsHIP) {
8338 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8339 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8340 }
8341
8342 Args.AddAllArgs(CmdArgs,
8343 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8344
8345 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8346 options::OPT_fno_offload_uniform_block);
8347
8348 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8349 options::OPT_fno_offload_implicit_host_device_templates);
8350
8351 if (IsCudaDevice || IsHIPDevice) {
8352 StringRef InlineThresh =
8353 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8354 if (!InlineThresh.empty()) {
8355 std::string ArgStr =
8356 std::string("-inline-threshold=") + InlineThresh.str();
8357 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8358 }
8359 }
8360
8361 if (IsHIPDevice)
8362 Args.addOptOutFlag(CmdArgs,
8363 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8364 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8365
8366 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8367 // to specify the result of the compile phase on the host, so the meaningful
8368 // device declarations can be identified. Also, -fopenmp-is-target-device is
8369 // passed along to tell the frontend that it is generating code for a device,
8370 // so that only the relevant declarations are emitted.
8371 if (IsOpenMPDevice) {
8372 CmdArgs.push_back("-fopenmp-is-target-device");
8373 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8374 if (Args.hasArg(options::OPT_foffload_via_llvm))
8375 CmdArgs.push_back("-fcuda-is-device");
8376
8377 if (OpenMPDeviceInput) {
8378 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8379 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8380 }
8381 }
8382
8383 if (Triple.isAMDGPU() ||
8384 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8385 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8386
8387 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8388 options::OPT_mno_unsafe_fp_atomics);
8389 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8390 options::OPT_mno_amdgpu_ieee);
8391 }
8392
8393 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8394
8395 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8396 options::OPT_fno_devirtualize_speculatively,
8397 /*Default value*/ false))
8398 CmdArgs.push_back("-fdevirtualize-speculatively");
8399
8400 bool VirtualFunctionElimination =
8401 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8402 options::OPT_fno_virtual_function_elimination, false);
8403 if (VirtualFunctionElimination) {
8404 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8405 // in the future).
8406 if (LTOMode != LTOK_Full)
8407 D.Diag(diag::err_drv_argument_only_allowed_with)
8408 << "-fvirtual-function-elimination"
8409 << "-flto=full";
8410
8411 CmdArgs.push_back("-fvirtual-function-elimination");
8412 }
8413
8414 // VFE requires whole-program-vtables, and enables it by default.
8415 bool WholeProgramVTables = Args.hasFlag(
8416 options::OPT_fwhole_program_vtables,
8417 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8418 if (VirtualFunctionElimination && !WholeProgramVTables) {
8419 D.Diag(diag::err_drv_argument_not_allowed_with)
8420 << "-fno-whole-program-vtables"
8421 << "-fvirtual-function-elimination";
8422 }
8423
8424 if (WholeProgramVTables) {
8425 // PS4 uses the legacy LTO API, which does not support this feature in
8426 // ThinLTO mode.
8427 bool IsPS4 = getToolChain().getTriple().isPS4();
8428
8429 // Check if we passed LTO options but they were suppressed because this is a
8430 // device offloading action, or we passed device offload LTO options which
8431 // were suppressed because this is not the device offload action.
8432 // Check if we are using PS4 in regular LTO mode.
8433 // Otherwise, issue an error.
8434
8435 auto OtherLTOMode = TC.getLTOMode(
8436 Args, IsDeviceOffloadAction ? Action::OFK_None
8437 : static_cast<Action::OffloadKind>(
8438 C.getActiveOffloadKinds()));
8439 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8440
8441 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8442 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8443 D.Diag(diag::err_drv_argument_only_allowed_with)
8444 << "-fwhole-program-vtables"
8445 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8446
8447 // Propagate -fwhole-program-vtables if this is an LTO compile.
8448 if (IsUsingLTO)
8449 CmdArgs.push_back("-fwhole-program-vtables");
8450 }
8451
8452 bool DefaultsSplitLTOUnit =
8453 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8454 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8455 (!Triple.isPS4() && UnifiedLTO);
8456 bool SplitLTOUnit =
8457 Args.hasFlag(options::OPT_fsplit_lto_unit,
8458 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8459 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8460 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8461 << "-fsanitize=cfi";
8462 if (SplitLTOUnit)
8463 CmdArgs.push_back("-fsplit-lto-unit");
8464
8465 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8466 options::OPT_fno_fat_lto_objects)) {
8467 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8468 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8469 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8470 D.Diag(diag::err_drv_unsupported_opt_for_target)
8471 << A->getAsString(Args) << TC.getTripleString();
8472 }
8473 CmdArgs.push_back(Args.MakeArgString(
8474 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8475 CmdArgs.push_back("-flto-unit");
8476 CmdArgs.push_back("-ffat-lto-objects");
8477 A->render(Args, CmdArgs);
8478 }
8479 }
8480
8481 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8482
8483 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8484 options::OPT_fno_force_enable_int128)) {
8485 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8486 CmdArgs.push_back("-fforce-enable-int128");
8487 }
8488
8489 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8490 options::OPT_fno_keep_static_consts);
8491 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8492 options::OPT_fno_keep_persistent_storage_variables);
8493 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8494 options::OPT_fno_complete_member_pointers);
8495 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8496 A->render(Args, CmdArgs);
8497
8498 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8499
8500 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8501
8502 if (Triple.isAArch64() &&
8503 (Args.hasArg(options::OPT_mno_fmv) ||
8504 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8505 // Disable Function Multiversioning on AArch64 target.
8506 CmdArgs.push_back("-target-feature");
8507 CmdArgs.push_back("-fmv");
8508 }
8509
8510 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8511 (TC.getTriple().isOSBinFormatELF() ||
8512 TC.getTriple().isOSBinFormatCOFF()) &&
8513 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8514 !TC.getTriple().isOSNetBSD() &&
8515 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8516 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8517 CmdArgs.push_back("-faddrsig");
8518
8519 const bool HasDefaultDwarf2CFIASM =
8520 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8521 (EH || UnwindTables || AsyncUnwindTables ||
8522 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8523 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8524 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8525 CmdArgs.push_back("-fdwarf2-cfi-asm");
8526
8527 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8528 std::string Str = A->getAsString(Args);
8529 if (!TC.getTriple().isOSBinFormatELF())
8530 D.Diag(diag::err_drv_unsupported_opt_for_target)
8531 << Str << TC.getTripleString();
8532 CmdArgs.push_back(Args.MakeArgString(Str));
8533 }
8534
8535 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8536 // the -cc1 command easier to edit when reproducing compiler crashes.
8537 if (Output.getType() == types::TY_Dependencies) {
8538 // Handled with other dependency code.
8539 } else if (Output.isFilename()) {
8540 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8541 Output.getType() == clang::driver::types::TY_IFS) {
8542 SmallString<128> OutputFilename(Output.getFilename());
8543 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8544 CmdArgs.push_back("-o");
8545 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8546 } else {
8547 CmdArgs.push_back("-o");
8548 CmdArgs.push_back(Output.getFilename());
8549 }
8550 } else {
8551 assert(Output.isNothing() && "Invalid output.");
8552 }
8553
8554 addDashXForInput(Args, Input, CmdArgs);
8555
8556 ArrayRef<InputInfo> FrontendInputs = Input;
8557 if (IsExtractAPI)
8558 FrontendInputs = ExtractAPIInputs;
8559 else if (Input.isNothing())
8560 FrontendInputs = {};
8561
8562 for (const InputInfo &Input : FrontendInputs) {
8563 if (Input.isFilename())
8564 CmdArgs.push_back(Input.getFilename());
8565 else
8566 Input.getInputArg().renderAsInput(Args, CmdArgs);
8567 }
8568
8569 if (D.CC1Main && !D.CCGenDiagnostics) {
8570 // Invoke the CC1 directly in this process
8571 C.addCommand(std::make_unique<CC1Command>(
8572 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8573 Output, D.getPrependArg()));
8574 } else {
8575 C.addCommand(std::make_unique<Command>(
8576 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8577 Output, D.getPrependArg()));
8578 }
8579
8580 // Make the compile command echo its inputs for /showFilenames.
8581 if (Output.getType() == types::TY_Object &&
8582 Args.hasFlag(options::OPT__SLASH_showFilenames,
8583 options::OPT__SLASH_showFilenames_, false)) {
8584 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8585 }
8586
8587 if (Arg *A = Args.getLastArg(options::OPT_pg))
8588 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8589 !Args.hasArg(options::OPT_mfentry))
8590 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8591 << A->getAsString(Args);
8592
8593 // Claim some arguments which clang supports automatically.
8594
8595 // -fpch-preprocess is used with gcc to add a special marker in the output to
8596 // include the PCH file.
8597 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8598
8599 // Claim some arguments which clang doesn't support, but we don't
8600 // care to warn the user about.
8601 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8602 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8603
8604 // Disable warnings for clang -E -emit-llvm foo.c
8605 Args.ClaimAllArgs(options::OPT_emit_llvm);
8606}
8607
8608Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8609 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8610 // as it is for other tools. Some operations on a Tool actually test
8611 // whether that tool is Clang based on the Tool's Name as a string.
8612 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8613
8615
8616/// Add options related to the Objective-C runtime/ABI.
8617///
8618/// Returns true if the runtime is non-fragile.
8619ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8620 const InputInfoList &inputs,
8621 ArgStringList &cmdArgs,
8622 RewriteKind rewriteKind) const {
8623 // Look for the controlling runtime option.
8624 Arg *runtimeArg =
8625 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8626 options::OPT_fobjc_runtime_EQ);
8627
8628 // Just forward -fobjc-runtime= to the frontend. This supercedes
8629 // options about fragility.
8630 if (runtimeArg &&
8631 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8632 ObjCRuntime runtime;
8633 StringRef value = runtimeArg->getValue();
8634 if (runtime.tryParse(value)) {
8635 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8636 << value;
8637 }
8638 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8639 (runtime.getVersion() >= VersionTuple(2, 0)))
8640 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8641 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8643 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8644 << runtime.getVersion().getMajor();
8645 }
8646
8647 runtimeArg->render(args, cmdArgs);
8648 return runtime;
8649 }
8650
8651 // Otherwise, we'll need the ABI "version". Version numbers are
8652 // slightly confusing for historical reasons:
8653 // 1 - Traditional "fragile" ABI
8654 // 2 - Non-fragile ABI, version 1
8655 // 3 - Non-fragile ABI, version 2
8656 unsigned objcABIVersion = 1;
8657 // If -fobjc-abi-version= is present, use that to set the version.
8658 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8659 StringRef value = abiArg->getValue();
8660 if (value == "1")
8661 objcABIVersion = 1;
8662 else if (value == "2")
8663 objcABIVersion = 2;
8664 else if (value == "3")
8665 objcABIVersion = 3;
8666 else
8667 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8668 } else {
8669 // Otherwise, determine if we are using the non-fragile ABI.
8670 bool nonFragileABIIsDefault =
8671 (rewriteKind == RK_NonFragile ||
8672 (rewriteKind == RK_None &&
8674 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8675 options::OPT_fno_objc_nonfragile_abi,
8676 nonFragileABIIsDefault)) {
8677// Determine the non-fragile ABI version to use.
8678#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8679 unsigned nonFragileABIVersion = 1;
8680#else
8681 unsigned nonFragileABIVersion = 2;
8682#endif
8683
8684 if (Arg *abiArg =
8685 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8686 StringRef value = abiArg->getValue();
8687 if (value == "1")
8688 nonFragileABIVersion = 1;
8689 else if (value == "2")
8690 nonFragileABIVersion = 2;
8691 else
8692 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8693 << value;
8694 }
8695
8696 objcABIVersion = 1 + nonFragileABIVersion;
8697 } else {
8698 objcABIVersion = 1;
8699 }
8700 }
8701
8702 // We don't actually care about the ABI version other than whether
8703 // it's non-fragile.
8704 bool isNonFragile = objcABIVersion != 1;
8705
8706 // If we have no runtime argument, ask the toolchain for its default runtime.
8707 // However, the rewriter only really supports the Mac runtime, so assume that.
8708 ObjCRuntime runtime;
8709 if (!runtimeArg) {
8710 switch (rewriteKind) {
8711 case RK_None:
8712 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8713 break;
8714 case RK_Fragile:
8715 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8716 break;
8717 case RK_NonFragile:
8718 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8719 break;
8720 }
8721
8722 // -fnext-runtime
8723 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8724 // On Darwin, make this use the default behavior for the toolchain.
8725 if (getToolChain().getTriple().isOSDarwin()) {
8726 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8727
8728 // Otherwise, build for a generic macosx port.
8729 } else {
8730 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8731 }
8732
8733 // -fgnu-runtime
8734 } else {
8735 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8736 // Legacy behaviour is to target the gnustep runtime if we are in
8737 // non-fragile mode or the GCC runtime in fragile mode.
8738 if (isNonFragile)
8739 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8740 else
8741 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8742 }
8743
8744 if (llvm::any_of(inputs, [](const InputInfo &input) {
8745 return types::isObjC(input.getType());
8746 }))
8747 cmdArgs.push_back(
8748 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8749 return runtime;
8750}
8751
8752static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8753 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8754 I += HaveDash;
8755 return !HaveDash;
8756}
8757
8758namespace {
8759struct EHFlags {
8760 bool Synch = false;
8761 bool Asynch = false;
8762 bool NoUnwindC = false;
8763};
8764} // end anonymous namespace
8765
8766/// /EH controls whether to run destructor cleanups when exceptions are
8767/// thrown. There are three modifiers:
8768/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8769/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8770/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8771/// - c: Assume that extern "C" functions are implicitly nounwind.
8772/// The default is /EHs-c-, meaning cleanups are disabled.
8773static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8774 bool isWindowsMSVC) {
8775 EHFlags EH;
8776
8777 std::vector<std::string> EHArgs =
8778 Args.getAllArgValues(options::OPT__SLASH_EH);
8779 for (const auto &EHVal : EHArgs) {
8780 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8781 switch (EHVal[I]) {
8782 case 'a':
8783 EH.Asynch = maybeConsumeDash(EHVal, I);
8784 if (EH.Asynch) {
8785 // Async exceptions are Windows MSVC only.
8786 if (!isWindowsMSVC) {
8787 EH.Asynch = false;
8788 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8789 continue;
8790 }
8791 EH.Synch = false;
8792 }
8793 continue;
8794 case 'c':
8795 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8796 continue;
8797 case 's':
8798 EH.Synch = maybeConsumeDash(EHVal, I);
8799 if (EH.Synch)
8800 EH.Asynch = false;
8801 continue;
8802 default:
8803 break;
8804 }
8805 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8806 break;
8807 }
8808 }
8809 // The /GX, /GX- flags are only processed if there are not /EH flags.
8810 // The default is that /GX is not specified.
8811 if (EHArgs.empty() &&
8812 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8813 /*Default=*/false)) {
8814 EH.Synch = true;
8815 EH.NoUnwindC = true;
8816 }
8817
8818 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8819 EH.Synch = false;
8820 EH.NoUnwindC = false;
8821 EH.Asynch = false;
8822 }
8823
8824 return EH;
8825}
8826
8827void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8828 ArgStringList &CmdArgs) const {
8829 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8830
8831 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8832
8833 if (Arg *ShowIncludes =
8834 Args.getLastArg(options::OPT__SLASH_showIncludes,
8835 options::OPT__SLASH_showIncludes_user)) {
8836 CmdArgs.push_back("--show-includes");
8837 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8838 CmdArgs.push_back("-sys-header-deps");
8839 }
8840
8841 // This controls whether or not we emit RTTI data for polymorphic types.
8842 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8843 /*Default=*/false))
8844 CmdArgs.push_back("-fno-rtti-data");
8845
8846 // This controls whether or not we emit stack-protector instrumentation.
8847 // In MSVC, Buffer Security Check (/GS) is on by default.
8848 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8849 /*Default=*/true)) {
8850 CmdArgs.push_back("-stack-protector");
8851 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8852 }
8853
8854 const Driver &D = getToolChain().getDriver();
8855
8856 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8857 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8858 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8859 if (types::isCXX(InputType))
8860 CmdArgs.push_back("-fcxx-exceptions");
8861 CmdArgs.push_back("-fexceptions");
8862 if (EH.Asynch)
8863 CmdArgs.push_back("-fasync-exceptions");
8864 }
8865 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8866 CmdArgs.push_back("-fexternc-nounwind");
8867
8868 // /EP should expand to -E -P.
8869 if (Args.hasArg(options::OPT__SLASH_EP)) {
8870 CmdArgs.push_back("-E");
8871 CmdArgs.push_back("-P");
8872 }
8873
8874 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8875 options::OPT__SLASH_Zc_dllexportInlines,
8876 false)) {
8877 CmdArgs.push_back("-fno-dllexport-inlines");
8878 }
8879
8880 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8881 options::OPT__SLASH_Zc_wchar_t, false)) {
8882 CmdArgs.push_back("-fno-wchar");
8883 }
8884
8885 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8886 llvm::Triple::ArchType Arch = getToolChain().getArch();
8887 std::vector<std::string> Values =
8888 Args.getAllArgValues(options::OPT__SLASH_arch);
8889 if (!Values.empty()) {
8890 llvm::SmallSet<std::string, 4> SupportedArches;
8891 if (Arch == llvm::Triple::x86)
8892 SupportedArches.insert("IA32");
8893
8894 for (auto &V : Values)
8895 if (!SupportedArches.contains(V))
8896 D.Diag(diag::err_drv_argument_not_allowed_with)
8897 << std::string("/arch:").append(V) << "/kernel";
8898 }
8899
8900 CmdArgs.push_back("-fno-rtti");
8901 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8902 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8903 << "/kernel";
8904 }
8905
8906 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
8907 options::OPT__SLASH_vlen_EQ_256,
8908 options::OPT__SLASH_vlen_EQ_512)) {
8909 llvm::Triple::ArchType AT = getToolChain().getArch();
8910 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8911 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
8912 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8913 "AVX10.2"};
8914
8915 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
8916 if (Arch512.contains(Arch))
8917 CmdArgs.push_back("-mprefer-vector-width=512");
8918 else
8919 D.Diag(diag::warn_drv_argument_not_allowed_with)
8920 << "/vlen=512" << std::string("/arch:").append(Arch);
8921 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
8922 if (Arch512.contains(Arch))
8923 CmdArgs.push_back("-mprefer-vector-width=256");
8924 else if (Arch != "AVX" && Arch != "AVX2")
8925 D.Diag(diag::warn_drv_argument_not_allowed_with)
8926 << "/vlen=256" << std::string("/arch:").append(Arch);
8927 } else {
8928 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8929 CmdArgs.push_back("-mprefer-vector-width=256");
8930 }
8931 } else {
8932 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
8933 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8934 CmdArgs.push_back("-mprefer-vector-width=256");
8935 CmdArgs.push_back("-target-feature");
8936 CmdArgs.push_back("-amx-tile");
8937 }
8938 if (Arch == "AVX10.2") {
8939 CmdArgs.push_back("-target-feature");
8940 CmdArgs.push_back("+avx10.2");
8941 }
8942 }
8943
8944 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8945 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8946 if (MostGeneralArg && BestCaseArg)
8947 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8948 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8949
8950 if (MostGeneralArg) {
8951 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8952 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8953 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8954
8955 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8956 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8957 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8958 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8959 << FirstConflict->getAsString(Args)
8960 << SecondConflict->getAsString(Args);
8961
8962 if (SingleArg)
8963 CmdArgs.push_back("-fms-memptr-rep=single");
8964 else if (MultipleArg)
8965 CmdArgs.push_back("-fms-memptr-rep=multiple");
8966 else
8967 CmdArgs.push_back("-fms-memptr-rep=virtual");
8968 }
8969
8970 if (Args.hasArg(options::OPT_regcall4))
8971 CmdArgs.push_back("-regcall4");
8972
8973 // Parse the default calling convention options.
8974 if (Arg *CCArg =
8975 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8976 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8977 options::OPT__SLASH_Gregcall)) {
8978 unsigned DCCOptId = CCArg->getOption().getID();
8979 const char *DCCFlag = nullptr;
8980 bool ArchSupported = !isNVPTX;
8981 llvm::Triple::ArchType Arch = getToolChain().getArch();
8982 switch (DCCOptId) {
8983 case options::OPT__SLASH_Gd:
8984 DCCFlag = "-fdefault-calling-conv=cdecl";
8985 break;
8986 case options::OPT__SLASH_Gr:
8987 ArchSupported = Arch == llvm::Triple::x86;
8988 DCCFlag = "-fdefault-calling-conv=fastcall";
8989 break;
8990 case options::OPT__SLASH_Gz:
8991 ArchSupported = Arch == llvm::Triple::x86;
8992 DCCFlag = "-fdefault-calling-conv=stdcall";
8993 break;
8994 case options::OPT__SLASH_Gv:
8995 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8996 DCCFlag = "-fdefault-calling-conv=vectorcall";
8997 break;
8998 case options::OPT__SLASH_Gregcall:
8999 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9000 DCCFlag = "-fdefault-calling-conv=regcall";
9001 break;
9002 }
9003
9004 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9005 if (ArchSupported && DCCFlag)
9006 CmdArgs.push_back(DCCFlag);
9007 }
9008
9009 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
9010 CmdArgs.push_back("-regcall4");
9011
9012 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
9013
9014 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
9015 CmdArgs.push_back("-fdiagnostics-format");
9016 CmdArgs.push_back("msvc");
9017 }
9018
9019 if (Args.hasArg(options::OPT__SLASH_kernel))
9020 CmdArgs.push_back("-fms-kernel");
9021
9022 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9023 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9024 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9025 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9026 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9027 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9028
9029 // Handle the various /guard options. We don't immediately push back clang
9030 // args since there are /d2 args that can modify the behavior of /guard:cf.
9031 bool HasCFGuard = false;
9032 bool HasCFGuardNoChecks = false;
9033 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9034 StringRef GuardArgs = A->getValue();
9035 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9036 // "ehcont-".
9037 if (GuardArgs.equals_insensitive("cf")) {
9038 // Emit CFG instrumentation and the table of address-taken functions.
9039 HasCFGuard = true;
9040 HasCFGuardNoChecks = false;
9041 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9042 // Emit only the table of address-taken functions.
9043 HasCFGuard = false;
9044 HasCFGuardNoChecks = true;
9045 } else if (GuardArgs.equals_insensitive("ehcont")) {
9046 // Emit EH continuation table.
9047 CmdArgs.push_back("-ehcontguard");
9048 } else if (GuardArgs.equals_insensitive("cf-") ||
9049 GuardArgs.equals_insensitive("ehcont-")) {
9050 // Do nothing, but we might want to emit a security warning in future.
9051 } else {
9052 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9053 }
9054 A->claim();
9055 }
9056
9057 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9058 // If CFG is not enabled, it is a no-op.
9059 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9060 if (HasCFGuard) {
9061 HasCFGuard = false;
9062 HasCFGuardNoChecks = true;
9063 }
9064 }
9065
9066 if (HasCFGuard)
9067 CmdArgs.push_back("-cfguard");
9068 else if (HasCFGuardNoChecks)
9069 CmdArgs.push_back("-cfguard-no-checks");
9070
9071 // Control Flow Guard mechanism for Windows.
9072 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9073 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9074 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9075 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9076
9077 for (const auto &FuncOverride :
9078 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9079 CmdArgs.push_back(Args.MakeArgString(
9080 Twine("-loader-replaceable-function=") + FuncOverride));
9081 }
9082
9083 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9084 CmdArgs.push_back("-Wdate-time");
9085
9086 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9087 D.Diag(diag::err_drv_argument_not_allowed_with)
9088 << "/experimental:deterministic"
9089 << "/Brepro-";
9090 }
9091 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9092 // deterministic result, but we force this timestamp to 0, which also
9093 // produces deterministic result.
9094 CmdArgs.push_back("-mno-incremental-linker-compatible");
9095 }
9096
9097 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9098 options::OPT__SLASH_d1nodatetime_, false);
9099
9100 if (HasNoDateTime)
9101 CmdArgs.push_back("-init-datetime-macros=undefined");
9102
9103 // /Brepro is an alias for -mincremental-linker-compatible option.
9104 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9105 options::OPT_mno_incremental_linker_compatible,
9106 getToolChain()
9107 .getTriple()
9108 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9109 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9110 // This option does not allow the user redefinitions for these macros.
9111 if (!HasNoDateTime)
9112 CmdArgs.push_back("-init-datetime-macros=literalone");
9113 }
9114}
9115
9116const char *Clang::getBaseInputName(const ArgList &Args,
9117 const InputInfo &Input) {
9118 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9119}
9120
9121const char *Clang::getBaseInputStem(const ArgList &Args,
9122 const InputInfoList &Inputs) {
9123 const char *Str = getBaseInputName(Args, Inputs[0]);
9124
9125 if (const char *End = strrchr(Str, '.'))
9126 return Args.MakeArgString(std::string(Str, End));
9127
9128 return Str;
9129}
9130
9131const char *Clang::getDependencyFileName(const ArgList &Args,
9132 const InputInfoList &Inputs) {
9133 // FIXME: Think about this more.
9134
9135 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9136 SmallString<128> OutputFilename(OutputOpt->getValue());
9137 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9138 return Args.MakeArgString(OutputFilename);
9139 }
9140
9141 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9142}
9143
9144// Begin ClangAs
9145
9146void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9147 ArgStringList &CmdArgs) const {
9148 StringRef CPUName;
9149 StringRef ABIName;
9150 const llvm::Triple &Triple = getToolChain().getTriple();
9151 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9152
9153 CmdArgs.push_back("-target-abi");
9154 CmdArgs.push_back(ABIName.data());
9155}
9156
9157void ClangAs::AddX86TargetArgs(const ArgList &Args,
9158 ArgStringList &CmdArgs) const {
9159 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9160 /*IsLTO=*/false);
9161
9162 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9163 StringRef Value = A->getValue();
9164 if (Value == "intel" || Value == "att") {
9165 CmdArgs.push_back("-mllvm");
9166 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9167 } else {
9168 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9169 << A->getSpelling() << Value;
9170 }
9171 }
9172}
9173
9174void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9175 ArgStringList &CmdArgs) const {
9176 CmdArgs.push_back("-target-abi");
9177 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9179 .data());
9180}
9181
9182void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9183 ArgStringList &CmdArgs) const {
9184 const llvm::Triple &Triple = getToolChain().getTriple();
9185 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9186
9187 CmdArgs.push_back("-target-abi");
9188 CmdArgs.push_back(ABIName.data());
9189
9190 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9191 options::OPT_mno_default_build_attributes, true)) {
9192 CmdArgs.push_back("-mllvm");
9193 CmdArgs.push_back("-riscv-add-build-attributes");
9194 }
9195}
9196
9198 const InputInfo &Output, const InputInfoList &Inputs,
9199 const ArgList &Args,
9200 const char *LinkingOutput) const {
9201 ArgStringList CmdArgs;
9202
9203 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9204 const InputInfo &Input = Inputs[0];
9205
9206 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9207 const std::string &TripleStr = Triple.getTriple();
9208 const auto &D = getToolChain().getDriver();
9209
9210 // Don't warn about "clang -w -c foo.s"
9211 Args.ClaimAllArgs(options::OPT_w);
9212 // and "clang -emit-llvm -c foo.s"
9213 Args.ClaimAllArgs(options::OPT_emit_llvm);
9214
9215 claimNoWarnArgs(Args);
9216
9217 // Invoke ourselves in -cc1as mode.
9218 //
9219 // FIXME: Implement custom jobs for internal actions.
9220 CmdArgs.push_back("-cc1as");
9221
9222 // Add the "effective" target triple.
9223 CmdArgs.push_back("-triple");
9224 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9225
9227
9228 // Set the output mode, we currently only expect to be used as a real
9229 // assembler.
9230 CmdArgs.push_back("-filetype");
9231 CmdArgs.push_back("obj");
9232
9233 // Set the main file name, so that debug info works even with
9234 // -save-temps or preprocessed assembly.
9235 CmdArgs.push_back("-main-file-name");
9236 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9237
9238 // Add the target cpu
9239 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9240 if (!CPU.empty()) {
9241 CmdArgs.push_back("-target-cpu");
9242 CmdArgs.push_back(Args.MakeArgString(CPU));
9243 }
9244
9245 // Add the target features
9246 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9247
9248 // Ignore explicit -force_cpusubtype_ALL option.
9249 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9250
9251 // Pass along any -I options so we get proper .include search paths.
9252 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9253
9254 // Pass along any --embed-dir or similar options so we get proper embed paths.
9255 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9256
9257 // Determine the original source input.
9258 auto FindSource = [](const Action *S) -> const Action * {
9259 while (S->getKind() != Action::InputClass) {
9260 assert(!S->getInputs().empty() && "unexpected root action!");
9261 S = S->getInputs()[0];
9262 }
9263 return S;
9264 };
9265 const Action *SourceAction = FindSource(&JA);
9266
9267 // Forward -g and handle debug info related flags, assuming we are dealing
9268 // with an actual assembly file.
9269 bool WantDebug = false;
9270 Args.ClaimAllArgs(options::OPT_g_Group);
9271 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9272 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9273 !A->getOption().matches(options::OPT_ggdb0);
9274
9275 // If a -gdwarf argument appeared, remember it.
9276 bool EmitDwarf = false;
9277 if (const Arg *A = getDwarfNArg(Args))
9278 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9279
9280 bool EmitCodeView = false;
9281 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9282 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9283
9284 // If the user asked for debug info but did not explicitly specify -gcodeview
9285 // or -gdwarf, ask the toolchain for the default format.
9286 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9287 switch (getToolChain().getDefaultDebugFormat()) {
9288 case llvm::codegenoptions::DIF_CodeView:
9289 EmitCodeView = true;
9290 break;
9291 case llvm::codegenoptions::DIF_DWARF:
9292 EmitDwarf = true;
9293 break;
9294 }
9295 }
9296
9297 // If the arguments don't imply DWARF, don't emit any debug info here.
9298 if (!EmitDwarf)
9299 WantDebug = false;
9300
9301 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9302 llvm::codegenoptions::NoDebugInfo;
9303
9304 // Add the -fdebug-compilation-dir flag if needed.
9305 const char *DebugCompilationDir =
9306 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9307
9308 if (SourceAction->getType() == types::TY_Asm ||
9309 SourceAction->getType() == types::TY_PP_Asm) {
9310 // You might think that it would be ok to set DebugInfoKind outside of
9311 // the guard for source type, however there is a test which asserts
9312 // that some assembler invocation receives no -debug-info-kind,
9313 // and it's not clear whether that test is just overly restrictive.
9314 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9315 : llvm::codegenoptions::NoDebugInfo);
9316
9317 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9318 CmdArgs);
9319
9320 // Set the AT_producer to the clang version when using the integrated
9321 // assembler on assembly source files.
9322 CmdArgs.push_back("-dwarf-debug-producer");
9323 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9324
9325 // And pass along -I options
9326 Args.AddAllArgs(CmdArgs, options::OPT_I);
9327 }
9328 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9329 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9330 llvm::DebuggerKind::Default);
9331 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9332 renderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9333
9334 // Handle -fPIC et al -- the relocation-model affects the assembler
9335 // for some targets.
9336 llvm::Reloc::Model RelocationModel;
9337 unsigned PICLevel;
9338 bool IsPIE;
9339 std::tie(RelocationModel, PICLevel, IsPIE) =
9340 ParsePICArgs(getToolChain(), Args);
9341
9342 const char *RMName = RelocationModelName(RelocationModel);
9343 if (RMName) {
9344 CmdArgs.push_back("-mrelocation-model");
9345 CmdArgs.push_back(RMName);
9346 }
9347
9348 // Optionally embed the -cc1as level arguments into the debug info, for build
9349 // analysis.
9350 if (getToolChain().UseDwarfDebugFlags()) {
9351 ArgStringList OriginalArgs;
9352 for (const auto &Arg : Args)
9353 Arg->render(Args, OriginalArgs);
9354
9355 SmallString<256> Flags;
9356 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9357 escapeSpacesAndBackslashes(Exec, Flags);
9358 for (const char *OriginalArg : OriginalArgs) {
9359 SmallString<128> EscapedArg;
9360 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9361 Flags += " ";
9362 Flags += EscapedArg;
9363 }
9364 CmdArgs.push_back("-dwarf-debug-flags");
9365 CmdArgs.push_back(Args.MakeArgString(Flags));
9366 }
9367
9368 // FIXME: Add -static support, once we have it.
9369
9370 // Add target specific flags.
9371 switch (getToolChain().getArch()) {
9372 default:
9373 break;
9374
9375 case llvm::Triple::mips:
9376 case llvm::Triple::mipsel:
9377 case llvm::Triple::mips64:
9378 case llvm::Triple::mips64el:
9379 AddMIPSTargetArgs(Args, CmdArgs);
9380 break;
9381
9382 case llvm::Triple::x86:
9383 case llvm::Triple::x86_64:
9384 AddX86TargetArgs(Args, CmdArgs);
9385 break;
9386
9387 case llvm::Triple::arm:
9388 case llvm::Triple::armeb:
9389 case llvm::Triple::thumb:
9390 case llvm::Triple::thumbeb:
9391 // This isn't in AddARMTargetArgs because we want to do this for assembly
9392 // only, not C/C++.
9393 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9394 options::OPT_mno_default_build_attributes, true)) {
9395 CmdArgs.push_back("-mllvm");
9396 CmdArgs.push_back("-arm-add-build-attributes");
9397 }
9398 break;
9399
9400 case llvm::Triple::aarch64:
9401 case llvm::Triple::aarch64_32:
9402 case llvm::Triple::aarch64_be:
9403 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9404 CmdArgs.push_back("-mllvm");
9405 CmdArgs.push_back("-aarch64-mark-bti-property");
9406 }
9407 break;
9408
9409 case llvm::Triple::loongarch32:
9410 case llvm::Triple::loongarch64:
9411 AddLoongArchTargetArgs(Args, CmdArgs);
9412 break;
9413
9414 case llvm::Triple::riscv32:
9415 case llvm::Triple::riscv64:
9416 case llvm::Triple::riscv32be:
9417 case llvm::Triple::riscv64be:
9418 AddRISCVTargetArgs(Args, CmdArgs);
9419 break;
9420
9421 case llvm::Triple::hexagon:
9422 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9423 options::OPT_mno_default_build_attributes, true)) {
9424 CmdArgs.push_back("-mllvm");
9425 CmdArgs.push_back("-hexagon-add-build-attributes");
9426 }
9427 break;
9428 }
9429
9430 // Consume all the warning flags. Usually this would be handled more
9431 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9432 // doesn't handle that so rather than warning about unused flags that are
9433 // actually used, we'll lie by omission instead.
9434 // FIXME: Stop lying and consume only the appropriate driver flags
9435 Args.ClaimAllArgs(options::OPT_W_Group);
9436
9437 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9438 getToolChain().getDriver());
9439
9440 // Forward -Xclangas arguments to -cc1as
9441 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9442 Arg->claim();
9443 CmdArgs.push_back(Arg->getValue());
9444 }
9445
9446 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9447
9448 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9449 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9450 Output.getFilename());
9451
9452 // Fixup any previous commands that use -object-file-name because when we
9453 // generated them, the final .obj name wasn't yet known.
9454 for (Command &J : C.getJobs()) {
9455 if (SourceAction != FindSource(&J.getSource()))
9456 continue;
9457 auto &JArgs = J.getArguments();
9458 for (unsigned I = 0; I < JArgs.size(); ++I) {
9459 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9460 Output.isFilename()) {
9461 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9462 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9463 Output.getFilename());
9464 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9465 J.replaceArguments(NewArgs);
9466 break;
9467 }
9468 }
9469 }
9470
9471 assert(Output.isFilename() && "Unexpected lipo output.");
9472 CmdArgs.push_back("-o");
9473 CmdArgs.push_back(Output.getFilename());
9474
9475 const llvm::Triple &T = getToolChain().getTriple();
9476 Arg *A;
9477 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9478 T.isOSBinFormatELF()) {
9479 CmdArgs.push_back("-split-dwarf-output");
9480 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9481 }
9482
9483 if (Triple.isAMDGPU())
9484 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9485
9486 assert(Input.isFilename() && "Invalid input.");
9487 CmdArgs.push_back(Input.getFilename());
9488
9489 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9490 if (D.CC1Main && !D.CCGenDiagnostics) {
9491 // Invoke cc1as directly in this process.
9492 C.addCommand(std::make_unique<CC1Command>(
9493 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9494 Output, D.getPrependArg()));
9495 } else {
9496 C.addCommand(std::make_unique<Command>(
9497 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9498 Output, D.getPrependArg()));
9499 }
9500}
9501
9502// Begin OffloadBundler
9504 const InputInfo &Output,
9505 const InputInfoList &Inputs,
9506 const llvm::opt::ArgList &TCArgs,
9507 const char *LinkingOutput) const {
9508 // The version with only one output is expected to refer to a bundling job.
9509 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9510
9511 // The bundling command looks like this:
9512 // clang-offload-bundler -type=bc
9513 // -targets=host-triple,openmp-triple1,openmp-triple2
9514 // -output=output_file
9515 // -input=unbundle_file_host
9516 // -input=unbundle_file_tgt1
9517 // -input=unbundle_file_tgt2
9518
9519 ArgStringList CmdArgs;
9520
9521 // Get the type.
9522 CmdArgs.push_back(TCArgs.MakeArgString(
9523 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9524
9525 assert(JA.getInputs().size() == Inputs.size() &&
9526 "Not have inputs for all dependence actions??");
9527
9528 // Get the targets.
9529 SmallString<128> Triples;
9530 Triples += "-targets=";
9531 for (unsigned I = 0; I < Inputs.size(); ++I) {
9532 if (I)
9533 Triples += ',';
9534
9535 // Find ToolChain for this input.
9537 const ToolChain *CurTC = &getToolChain();
9538 const Action *CurDep = JA.getInputs()[I];
9539
9540 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9541 CurTC = nullptr;
9542 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9543 assert(CurTC == nullptr && "Expected one dependence!");
9544 CurKind = A->getOffloadingDeviceKind();
9545 CurTC = TC;
9546 });
9547 }
9548 Triples += Action::GetOffloadKindName(CurKind);
9549 Triples += '-';
9550 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9551 TCArgs, CurDep->getOffloadingArch()))
9552 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9553
9554 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9555 Triples += '-';
9556 Triples += CurDep->getOffloadingArch().ArchName;
9557 }
9558 }
9559 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9560
9561 // Get bundled file command.
9562 CmdArgs.push_back(
9563 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9564
9565 // Get unbundled files command.
9566 for (unsigned I = 0; I < Inputs.size(); ++I) {
9568 UB += "-input=";
9569
9570 // Find ToolChain for this input.
9571 const ToolChain *CurTC = &getToolChain();
9572 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9573 CurTC = nullptr;
9574 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9575 assert(CurTC == nullptr && "Expected one dependence!");
9576 CurTC = TC;
9577 });
9578 UB += C.addTempFile(
9579 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9580 } else {
9581 UB += CurTC->getInputFilename(Inputs[I]);
9582 }
9583 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9584 }
9585 addOffloadCompressArgs(TCArgs, CmdArgs);
9586 // All the inputs are encoded as commands.
9587 C.addCommand(std::make_unique<Command>(
9588 JA, *this, ResponseFileSupport::None(),
9589 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9590 CmdArgs, ArrayRef<InputInfo>(), Output));
9591}
9592
9594 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9595 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9596 const char *LinkingOutput) const {
9597 // The version with multiple outputs is expected to refer to a unbundling job.
9598 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
9599
9600 // The unbundling command looks like this:
9601 // clang-offload-bundler -type=bc
9602 // -targets=host-triple,openmp-triple1,openmp-triple2
9603 // -input=input_file
9604 // -output=unbundle_file_host
9605 // -output=unbundle_file_tgt1
9606 // -output=unbundle_file_tgt2
9607 // -unbundle
9608
9609 ArgStringList CmdArgs;
9610
9611 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9612 InputInfo Input = Inputs.front();
9613
9614 // Get the type.
9615 CmdArgs.push_back(TCArgs.MakeArgString(
9616 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
9617
9618 // Get the targets.
9619 SmallString<128> Triples;
9620 Triples += "-targets=";
9621 auto DepInfo = UA.getDependentActionsInfo();
9622 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9623 if (I)
9624 Triples += ',';
9625
9626 auto &Dep = DepInfo[I];
9627 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
9628 Triples += '-';
9629 Triples += llvm::Triple(Dep.DependentToolChain->ComputeEffectiveClangTriple(
9630 TCArgs, Dep.DependentBoundArch))
9631 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9632
9633 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9634 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9635 !Dep.DependentBoundArch.empty()) {
9636 Triples += '-';
9637 Triples += Dep.DependentBoundArch.ArchName;
9638 }
9639 }
9640
9641 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9642
9643 // Get bundled file command.
9644 CmdArgs.push_back(
9645 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
9646
9647 // Get unbundled files command.
9648 for (unsigned I = 0; I < Outputs.size(); ++I) {
9650 UB += "-output=";
9651 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
9652 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9653 }
9654 CmdArgs.push_back("-unbundle");
9655 CmdArgs.push_back("-allow-missing-bundles");
9656 if (TCArgs.hasArg(options::OPT_v))
9657 CmdArgs.push_back("-verbose");
9658
9659 // All the inputs are encoded as commands.
9660 C.addCommand(std::make_unique<Command>(
9661 JA, *this, ResponseFileSupport::None(),
9662 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9663 CmdArgs, ArrayRef<InputInfo>(), Outputs));
9664}
9665
9667 const InputInfo &Output,
9668 const InputInfoList &Inputs,
9669 const llvm::opt::ArgList &Args,
9670 const char *LinkingOutput) const {
9671 ArgStringList CmdArgs;
9672
9673 // Add the output file name.
9674 assert(Output.isFilename() && "Invalid output.");
9675 CmdArgs.push_back("-o");
9676 CmdArgs.push_back(Output.getFilename());
9677
9678 // Create the inputs to bundle the needed metadata.
9679 for (const InputInfo &Input : Inputs) {
9680 const Action *OffloadAction = Input.getAction();
9682 const ArgList &TCArgs =
9683 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9685 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9687 if (Arch.empty())
9688 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9689
9690 StringRef Kind =
9692
9693 ArgStringList Features;
9694 SmallVector<StringRef> FeatureArgs;
9695 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9696 false);
9697 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9698 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9699
9700 // TODO: We need to pass in the full target-id and handle it properly in the
9701 // linker wrapper.
9703 "file=" + File.str(),
9704 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9705 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9706 "kind=" + Kind.str(),
9707 };
9708
9710 for (StringRef Feature : FeatureArgs)
9711 Parts.emplace_back("feature=" + Feature.str());
9712
9713 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9714 }
9715
9716 C.addCommand(std::make_unique<Command>(
9718 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9719 CmdArgs, Inputs, Output));
9720}
9721
9722// Options that need the profile compiler-rt library on the target toolchain.
9723// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9724// too.
9725static bool requiresProfileRT(unsigned ID) {
9726 switch (ID) {
9727 case options::OPT_fprofile_generate:
9728 case options::OPT_fprofile_generate_EQ:
9729 case options::OPT_fprofile_instr_generate:
9730 case options::OPT_fprofile_instr_generate_EQ:
9731 case options::OPT_fcoverage_mapping:
9732 case options::OPT_fno_coverage_mapping:
9733 case options::OPT_fcoverage_compilation_dir_EQ:
9734 case options::OPT_ffile_compilation_dir_EQ:
9735 case options::OPT_fcoverage_prefix_map_EQ:
9736 return true;
9737 default:
9738 return false;
9739 }
9740}
9741
9742// Options that need the ubsan compiler-rt library on the target toolchain.
9743static bool requiresUBSanRT(unsigned ID) {
9744 switch (ID) {
9745 case options::OPT_fsanitize_EQ:
9746 case options::OPT_fno_sanitize_EQ:
9747 case options::OPT_fsanitize_minimal_runtime:
9748 case options::OPT_fno_sanitize_minimal_runtime:
9749 return true;
9750 default:
9751 return false;
9752 }
9753}
9754
9756 const InputInfo &Output,
9757 const InputInfoList &Inputs,
9758 const ArgList &Args,
9759 const char *LinkingOutput) const {
9760 using namespace options;
9761
9762 // A list of permitted options that will be forwarded to the embedded device
9763 // compilation job.
9764 const llvm::DenseSet<unsigned> CompilerOptions{
9765 OPT_v,
9766 OPT_hip_path_EQ,
9767 OPT_O_Group,
9768 OPT_g_Group,
9769 OPT_g_flags_Group,
9770 OPT_R_value_Group,
9771 OPT_R_Group,
9772 OPT_Xcuda_ptxas,
9773 OPT_ptxas_path_EQ,
9774 OPT_ftime_report,
9775 OPT_ftime_trace,
9776 OPT_ftime_trace_EQ,
9777 OPT_ftime_trace_granularity_EQ,
9778 OPT_ftime_trace_verbose,
9779 OPT_opt_record_file,
9780 OPT_opt_record_format,
9781 OPT_opt_record_passes,
9782 OPT_fsave_optimization_record,
9783 OPT_fsave_optimization_record_EQ,
9784 OPT_fno_save_optimization_record,
9785 OPT_foptimization_record_file_EQ,
9786 OPT_foptimization_record_passes_EQ,
9787 OPT_save_temps,
9788 OPT_save_temps_EQ,
9789 OPT_mcode_object_version_EQ,
9790 OPT_load,
9791 OPT_no_canonical_prefixes,
9792 OPT_fno_lto,
9793 OPT_flto,
9794 OPT_flto_partitions_EQ,
9795 OPT_flto_EQ,
9796 OPT_hipspv_pass_plugin_EQ,
9797 OPT_use_spirv_backend,
9798 OPT_no_use_spirv_backend,
9799 OPT_fmultilib_flag,
9800 OPT_fprofile_generate,
9801 OPT_fprofile_generate_EQ,
9802 OPT_fprofile_instr_generate,
9803 OPT_fprofile_instr_generate_EQ,
9804 OPT_fcoverage_mapping,
9805 OPT_fno_coverage_mapping,
9806 OPT_fcoverage_compilation_dir_EQ,
9807 OPT_ffile_compilation_dir_EQ,
9808 OPT_fcoverage_prefix_map_EQ,
9809 OPT_fsanitize_EQ,
9810 OPT_fno_sanitize_EQ,
9811 OPT_fsanitize_minimal_runtime,
9812 OPT_fno_sanitize_minimal_runtime,
9813 OPT_fsanitize_trap_EQ,
9814 OPT_fno_sanitize_trap_EQ,
9815 OPT_fslp_vectorize,
9816 OPT_fno_slp_vectorize,
9817 OPT_hipstdpar};
9818 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9819 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9820 // CMake implicit linker argument parsing.
9821 bool SuppressHIPNoRDCVerbose =
9822 JA.getType() == types::TY_HIP_FATBIN &&
9823 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
9824 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9825 return TC.getVFS().exists(
9826 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9827 };
9828 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9829 unsigned ID = A->getOption().getID();
9830 // Don't forward profiling arguments if the toolchain doesn't support it.
9831 // Without this check using it on the host would result in linker errors.
9832 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9833 // together to avoid a device cc1 diagnostic.
9834 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9835 return false;
9836 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9837 // Without this check using it on the host would result in linker errors.
9838 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal"))
9839 return false;
9840 // Don't forward -mllvm to toolchains that don't support LLVM.
9841 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9842 };
9843 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9844 const ToolChain &TC) {
9845 if (A->getOption().matches(OPT_v) && SuppressHIPNoRDCVerbose)
9846 return false;
9847 return (Set.contains(A->getOption().getID()) ||
9848 (A->getOption().getGroup().isValid() &&
9849 Set.contains(A->getOption().getGroup().getID()))) &&
9850 ShouldForwardForToolChain(A, TC);
9851 };
9852
9853 ArgStringList CmdArgs;
9856 auto TCRange = C.getOffloadToolChains(Kind);
9857 for (auto &I : llvm::make_range(TCRange)) {
9858 const ToolChain *TC = I.second;
9859
9860 // We do not use a bound architecture here so options passed only to a
9861 // specific architecture via -Xarch_<cpu> will not be forwarded.
9862 ArgStringList CompilerArgs;
9863 ArgStringList LinkerArgs;
9864 const DerivedArgList &ToolChainArgs =
9865 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9866 for (Arg *A : ToolChainArgs) {
9867 if (A->getOption().matches(OPT_Zlinker_input))
9868 LinkerArgs.emplace_back(A->getValue());
9869 else if (ShouldForward(CompilerOptions, A, *TC)) {
9870 A->claim();
9871 A->render(Args, CompilerArgs);
9872 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9873 A->claim();
9874 A->render(Args, LinkerArgs);
9875 }
9876 }
9877
9878 // If the user explicitly requested it via `--offload-arch` we should
9879 // extract it from any static libraries if present.
9880 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))
9881 CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));
9882
9883 // If this is OpenMP the device linker will need `-lompdevice`.
9884 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9885 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9886 LinkerArgs.emplace_back("-lompdevice");
9887
9888 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9889 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9890 // flags to normal compilation.
9891 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9892 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9893 if (TC->getTriple().isSPIRV() &&
9894 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9895 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9896 // For SPIR-V some functions will be defined by the runtime so allow
9897 // unresolved symbols in `spirv-link`.
9898 LinkerArgs.emplace_back("--allow-partial-linkage");
9899 // Don't optimize out exported symbols.
9900 LinkerArgs.emplace_back("--create-library");
9901 }
9902
9903 // Forward the SYCL device image split option to clang-sycl-linker.
9904 // The driver and clang-sycl-linker share the same value vocabulary, so
9905 // the value is passed through verbatim after validation.
9906 if (Kind == Action::OFK_SYCL) {
9907 if (Arg *A =
9908 ToolChainArgs.getLastArg(OPT_fsycl_device_image_split_EQ)) {
9909 StringRef Mode = A->getValue();
9910 if (Mode != "kernel" && Mode != "translation_unit" &&
9911 Mode != "link_unit")
9912 C.getDriver().Diag(clang::diag::err_drv_invalid_value)
9913 << A->getSpelling() << Mode;
9914 else
9915 LinkerArgs.emplace_back(
9916 Args.MakeArgString("--module-split-mode=" + Mode));
9917 }
9918 }
9919
9920 // Forward all of these to the appropriate toolchain.
9921 for (StringRef Arg : CompilerArgs)
9922 CmdArgs.push_back(Args.MakeArgString(
9923 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9924 for (StringRef Arg : LinkerArgs)
9925 CmdArgs.push_back(Args.MakeArgString(
9926 "--device-linker=" + TC->getTripleString() + "=" + Arg));
9927
9928 // Forward the LTO mode for this toolchain.
9929 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
9930 if (DeviceLTOMode == LTOK_Full)
9931 CmdArgs.push_back(Args.MakeArgString(
9932 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9933 else if (DeviceLTOMode == LTOK_Thin) {
9934 CmdArgs.push_back(Args.MakeArgString(
9935 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9936 if (TC->getTriple().isAMDGPU()) {
9937 CmdArgs.push_back(
9938 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9939 "=-plugin-opt=-force-import-all"));
9940 CmdArgs.push_back(
9941 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9942 "=-plugin-opt=-avail-extern-to-local"));
9943 CmdArgs.push_back(Args.MakeArgString(
9944 "--device-linker=" + TC->getTripleString() +
9945 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9946 if (Kind == Action::OFK_OpenMP) {
9947 CmdArgs.push_back(
9948 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9949 "=-plugin-opt=-amdgpu-internalize-symbols"));
9950 }
9951 }
9952 }
9953 }
9954 }
9955
9956 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9957 CmdArgs.push_back(
9958 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
9959 else
9960 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
9961 getToolChain().getTripleString()));
9962
9963 if (Args.hasArg(options::OPT_v) && !SuppressHIPNoRDCVerbose)
9964 CmdArgs.push_back("--wrapper-verbose");
9965 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
9966 CmdArgs.push_back(
9967 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
9968 CmdArgs.push_back(Args.MakeArgString(
9969 Twine("--device-compiler=--cuda-path=") + A->getValue()));
9970 }
9971 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
9972 CmdArgs.push_back(Args.MakeArgString(
9973 Twine("--device-compiler=--rocm-path=") + A->getValue()));
9974 }
9975
9976 // Construct the link job so we can wrap around it.
9977 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9978 const auto &LinkCommand = C.getJobs().getJobs().back();
9979
9980 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9981 // wrapper.
9982 for (Arg *A :
9983 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
9984 StringRef Val = A->getValue(0);
9985 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9986 auto WrapperOption =
9987 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9988 if (Val.empty())
9989 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
9990 else
9991 CmdArgs.push_back(Args.MakeArgString(
9992 WrapperOption +
9993 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
9994 A->getValue(1)));
9995 }
9996 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
9997 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9998
9999 // Embed bitcode instead of an object in JIT mode.
10000 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
10001 options::OPT_fno_openmp_target_jit, false))
10002 CmdArgs.push_back("--embed-bitcode");
10003
10004 // Save temporary files created by the linker wrapper.
10005 if (Args.hasArg(options::OPT_save_temps_EQ) ||
10006 Args.hasArg(options::OPT_save_temps))
10007 CmdArgs.push_back("--save-temps");
10008
10009 // Pass in the C library for GPUs if present and not disabled.
10010 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
10011 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
10012 options::OPT_nodefaultlibs, options::OPT_nolibc,
10013 options::OPT_nogpulibc)) {
10014 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
10015 // The device C library is only available for NVPTX and AMDGPU targets
10016 // and we only link it by default for OpenMP currently.
10017 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10019 return;
10020 bool HasLibC = TC.getStdlibIncludePath().has_value();
10021 if (HasLibC) {
10022 CmdArgs.push_back(Args.MakeArgString(
10023 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10024 CmdArgs.push_back(Args.MakeArgString(
10025 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10026 }
10027 auto HasCompilerRT = getToolChain().getVFS().exists(
10028 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
10029 /*IsFortran=*/false));
10030 if (HasCompilerRT)
10031 CmdArgs.push_back(
10032 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10033 "-lclang_rt.builtins"));
10034
10035 bool HasFlangRT = getToolChain().getVFS().exists(
10036 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10037 /*IsFortran=*/true));
10038 if (HasFlangRT && C.getDriver().IsFlangMode())
10039 CmdArgs.push_back(
10040 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10041 "-lflang_rt.runtime"));
10042 });
10043 }
10044
10045 // Add the linker arguments to be forwarded by the wrapper.
10046 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10047 LinkCommand->getExecutable()));
10048
10049 // We use action type to differentiate two use cases of the linker wrapper.
10050 // TY_Image for normal linker wrapper work.
10051 // TY_HIP_FATBIN for HIP device-only links emitting a fat binary directly.
10052 assert(JA.getType() == types::TY_HIP_FATBIN ||
10053 JA.getType() == types::TY_Image);
10054 if (JA.getType() == types::TY_HIP_FATBIN) {
10055 CmdArgs.push_back("--emit-fatbin-only");
10056 CmdArgs.append({"-o", Output.getFilename()});
10057 for (auto Input : Inputs)
10058 CmdArgs.push_back(Input.getFilename());
10059 } else {
10060 for (const char *LinkArg : LinkCommand->getArguments())
10061 CmdArgs.push_back(LinkArg);
10062 }
10063
10064 addOffloadCompressArgs(Args, CmdArgs);
10065
10066 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10067 if (OffloadJobs.A) {
10068 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10069 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10070 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10071 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=" +
10072 Twine(OffloadJobs.NumThreads)));
10073 } else if (!OffloadJobs.A->isClaimed()) {
10074 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10075 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10076 }
10077 }
10078
10079 // Propagate -no-canonical-prefixes.
10080 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10081 CmdArgs.push_back("--no-canonical-prefixes");
10082
10083 const char *Exec =
10084 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10085
10086 // Replace the executable and arguments of the link job with the
10087 // wrapper.
10088 LinkCommand->replaceExecutable(Exec);
10089 LinkCommand->replaceArguments(CmdArgs);
10090}
#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:3886
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:2265
static void renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, types::ID InputType, ArgStringList &CmdArgs, const InputInfo &Output, llvm::codegenoptions::DebugInfoKind &DebugInfoKind, DwarfFissionKind &DwarfFission)
Definition Clang.cpp:4632
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4303
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:707
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5035
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9725
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4484
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:756
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:70
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1326
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1178
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:8773
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2244
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:773
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3983
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4615
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2515
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1216
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:733
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:4592
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:4339
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:2520
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1227
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2296
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2526
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2237
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4049
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:3560
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:1243
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:1362
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3570
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3991
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3798
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3815
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8752
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 bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9743
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:3491
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2271
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2891
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:368
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3930
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:926
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:154
const ToolChain * getOffloadingToolChain() const
Definition Action.h:218
static std::string GetOffloadingFileNamePrefix(OffloadKind Kind, StringRef NormalizedTriple, bool CreatePrefixForHost=false)
Return a string that can be used as prefix in order to generate unique files for each offloading kind...
Definition Action.cpp:148
BoundArch getOffloadingArch() const
Definition Action.h:217
ActionClass getKind() const
Definition Action.h:153
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:164
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:216
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:224
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:227
ActionList & getInputs()
Definition Action.h:156
unsigned getOffloadingHostActiveKinds() const
Definition Action.h:212
bool isOffloading(OffloadKind OKind) const
Definition Action.h:230
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:95
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:4926
std::string SysRoot
sysroot, if present
Definition Driver.h:195
DiagnosticsEngine & getDiags() const
Definition Driver.h:409
const char * getPrependArg() const
Definition Driver.h:420
CC1ToolFunc CC1Main
Definition Driver.h:291
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:873
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:231
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:269
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:4015
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:273
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:159
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:283
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:7052
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2455
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:431
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:219
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:216
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:179
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:411
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:155
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:145
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:252
std::string getTargetTriple() const
Definition Driver.h:428
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:258
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:173
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:225
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:222
bool getProbePrecompiled() const
Definition Driver.h:417
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:274
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:96
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:909
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:658
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:667
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:691
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:901
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:649
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:521
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:302
const Driver & getDriver() const
Definition ToolChain.h:286
RTTIMode getRTTIMode() const
Definition ToolChain.h:369
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:680
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:314
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:542
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:513
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:702
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:673
const llvm::Triple & getTriple() const
Definition ToolChain.h:288
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:677
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:311
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:536
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:742
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:655
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:643
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:896
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:525
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:488
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:646
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:517
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:484
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:295
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:510
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
const ToolChain & getToolChain() const
Definition Tool.h:52
Tool(const char *Name, const char *ShortName, const ToolChain &TC)
Definition Tool.cpp:14
const char * getShortName() const
Definition Tool.h:50
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
Definition XRayArgs.cpp:181
static std::optional< std::string > GetHVXVersion(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:1012
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:653
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9174
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9157
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9182
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:9197
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9146
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9116
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8608
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9131
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9121
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:5135
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:9755
void ConstructJobMultipleOutputs(Compilation &C, const JobAction &JA, const InputInfoList &Outputs, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
Construct jobs to perform the action JA, writing to the Outputs and with Inputs, and add the jobs to ...
Definition Clang.cpp:9593
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:9503
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:9666
void addSanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addProfileRTArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
std::optional< std::string > getAArch64TargetTuneCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition AArch64.cpp:117
bool isHardTPSupported(const llvm::Triple &Triple)
Definition ARM.cpp:210
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
StringRef getLoongArchABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::string postProcessTargetCPUString(const std::string &CPU, const llvm::Triple &Triple)
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
bool hasCompactBranches(StringRef &CPU)
Definition Mips.cpp:441
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
FloatABI getPPCFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:275
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:401
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)
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:326
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:237
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition Types.cpp:53
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition Types.cpp:289
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition Types.cpp:49
bool isOpenCL(ID Id)
isOpenCL - Is this an "OpenCL" input.
Definition Types.cpp:250
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:328
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition Types.cpp:81
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition Types.cpp:262
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:51
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool willEmitRemarks(const llvm::opt::ArgList &Args)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
The JSON file list parser is used to communicate input to InstallAPI.
std::optional< diag::Group > diagGroupFromCLWarningID(unsigned)
For cl.exe warning IDs that cleany map to clang diagnostic groups, returns the corresponding group.
bool isa(CodeGen::Address addr)
Definition Address.h:330
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
const char * headerIncludeFormatKindToString(HeaderIncludeFormatKind K)
unsigned CudaArchToID(OffloadArch Arch)
Get the numeric ID (e.g. 700) of a CUDA architecture.
Definition Cuda.cpp: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:36
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